diff --git a/docs/extensions/api-reference.md b/docs/extensions/api-reference.md index 6333b34..cdc466d 100644 --- a/docs/extensions/api-reference.md +++ b/docs/extensions/api-reference.md @@ -8,7 +8,7 @@ | `id` | 是 | 反向域名,小写;禁止 `com.tracememo.` / `tracememo.` / `tm.` 前缀 | | `name` | 是 | 展示名,≤ 64 字 | | `version` | 是 | `x.y.z`(可带 prerelease) | -| `apiVersion` | 是 | 必须为 `1` | +| `apiVersion` | 是 | 必须为 `1`(向后兼容所有 v1 扩展) | | `minAppVersion` | 否 | 低于该版本拒绝安装 | | `description` / `author` / `homepage` | 否 | 展示用;homepage 仅接受 http(s) | | `permissions` | 是 | 见权限表;未知权限直接判 manifest 非法 | @@ -16,6 +16,7 @@ | `entrypoints.background` | 二选一 | 后台入口相对路径 | | `subscriptions` | 条件 | 申请 `messages.subscribe` 时必填 | | `contributions.pages` | 否 | `[{ id, title, entry? }]`,`id` 形如 `settings` | +| `contributions.navigation` | 否 | `{ label, icon?, pageId?, order? }`,供用户「固定到一级菜单」;`icon` 仅支持内置安全图标集 `spark / bot / digest / bell / media / puzzle / compass / message` | | `contributions.automationActions` | 否 | `[{ id, title, description? }]`,有此项必须提供 background | 路径规则:相对路径、不允许 `..`、反斜杠、盘符、控制字符、Windows 保留名; @@ -26,24 +27,31 @@ | 权限 | 风险 | 能力 | | --- | --- | --- | | `messages.subscribe` | 高 | 接收 `message.received` | -| `messages.query` | 高 | `tm.messages.query` | +| `messages.query` | 高 | `tm.messages.query`(支持游标分页与类型过滤) | +| `media.read` | 高 | `tm.media.readImage` / `readVoice` / `readVideo`(按需解密并写入扩展私有缓存目录) | +| `media.ocr` | 中 | `tm.media.ocrImage`(纯本地系统 OCR,优先复用既有索引缓存) | +| `media.transcribe` | 中 | `tm.media.transcribeVoice`(复用 `VoiceTranscriptionGateway` 与转写缓存) | | `contacts.list` | 中 | 配置页读取群列表(`contacts.listGroups`),不含聊天内容 | | `wechat.send.text` | 高 | `tm.wechat.send`(文本)与自动化 `reply` | | `wechat.send.image` | 高 | `tm.wechat.send({ type: 'image' })` | | `wechat.send.video` | 高 | `tm.wechat.send({ type: 'video' })`,原生 Host 走 `/SendMsg` video | | `wechat.send.voice` | 高 | `tm.wechat.send({ type: 'voice' })`,支持传入 `text` 用宿主 TTS 音色合成发送或传入音频 `path` | | `ai.chat` | 中 | `tm.ai.chat` | +| `ai.vision` | 中 | `tm.media.analyzeImage` / `tm.ai.analyzeImage`(复用已配置的视觉 AI Provider) | +| `render.html` | 低 | `tm.render.htmlToImage`(离线隔离渲染静态 HTML/CSS 为 PNG 长图) | +| `notifications.create` | 中 | `tm.notifications.create`(写入扩展通知中心与未读角标) | | `storage` | 低 | `tm.storage.*` 与页面存储 | | `automation.action` | 中 | `tm.automation.registerAction` | +| `secrets` | 中 | `tm.secrets.*`(经系统安全存储加密保存私有凭据) | -安装时只自动授予**低风险**权限;其余在「启用」确认后授予。停用后回落到低风险集合。 +安装时只自动授予**低风险**权限;其余在「启用」确认后授予。停用后回落到低风险集合。所有权限均由主进程独立校验,不依赖 SDK 侧检查。 ## 后台 API ### tm.extension - `id: string` -- `dataDir: string`(扩展私有数据目录,媒体文件写这里才能通过发送校验) +- `dataDir: string`(扩展私有数据目录,媒体与渲染产物落盘于此) - `permissions: string[]`(当前已授予) ### tm.events @@ -51,109 +59,114 @@ - `on('message.received', handler): () => void` - `off('message.received', handler): void` -事件字段见 `TraceMemoMessageEvent`:`eventId / accountId / conversationId / messageId / -senderId? / senderName? / isGroup / isSelf / type / text? / mentionsMe / timestamp(ms)`。 +事件字段见 `TraceMemoMessageEvent`:`eventId / messageRef / accountId / conversationId / messageId / senderId? / senderName? / isGroup / isSelf / type / text? / mentionsMe / timestamp(ms)`。 +其中 `messageRef` 与 `tm.messages.query` 返回的 `messageRef` 格式完全统一,包含账号、会话与消息身份隔离校验。 ### tm.messages.query ```ts -await tm.messages.query({ conversationId, startTime?, endTime?, limit? }) -// → { messages: [{ messageId, conversationId, senderId?, senderName?, isSelf, type, text?, timestamp }] } +await tm.messages.query({ + conversationId, + startTime?, + endTime?, + limit?, + cursor?, + order?, // 'asc' | 'desc';省略时保持 v1 默认最新一页语义并支持向更早历史续页 + types? // 如 ['text', 'image', 'voice'] +}) +// → { messages: [{ messageId, messageRef, conversationId, senderId?, senderName?, isSelf, type, text?, timestamp }], nextCursor?, hasMore } ``` -- 时间参数是 **epoch 毫秒**;默认最近 24 小时。 -- 单次窗口最多 7 天,`limit` 上限 200。 +- 时间参数是 **epoch 毫秒**;默认最近 24 小时,单次最大 35 天,`limit` 上限 500。 +- 游标以 `(timestamp, messageId)` 为确定性边界,同时间戳多条消息分页不遗漏、不重复。 - 数据库未连接时抛 `DATABASE_NOT_READY`。 +### tm.media(扩展媒体 Gateway) + +```ts +// 按需读取媒体副本(写入扩展私有目录,不暴露原始微信数据库路径与密钥) +await tm.media.readImage({ messageRef, quality?: 'original' | 'thumbnail' }) +await tm.media.readVoice({ messageRef }) +await tm.media.readVideo({ messageRef }) + +// 本地 OCR / 语音转写 / AI 图片理解(自动复用主程序缓存与并发限制) +await tm.media.ocrImage({ messageRef, language?, force? }) +await tm.media.transcribeVoice({ messageRef, force?, waitMs? }) +await tm.media.analyzeImage({ messageRef, prompt?, force? }) + +// 批量按需处理(单次最多 20 项,并发上限 4,单项失败隔离返回) +await tm.media.batch({ + concurrency: 2, + items: [ + { op: 'ocrImage', messageRef: imgRef }, + { op: 'transcribeVoice', messageRef: voiceRef } + ] +}) +``` + +- 跨账号 `messageRef` 触发 `ACCOUNT_MISMATCH`;消息类型不匹配触发 `MEDIA_UNSUPPORTED`;缺失文件触发 `MEDIA_NOT_FOUND`;并发满载触发 `CONCURRENCY_LIMITED`。 +- `tm.ai.analyzeImage` 是 `tm.media.analyzeImage` 的等价别名,均要求 `ai.vision` 权限。 + +### tm.render.htmlToImage + +```ts +await tm.render.htmlToImage({ + html: '

晨报

', + css: 'main { padding: 20px; }', + fileName: 'morning-2026-12-01.png', // 可选,仅接受安全相对路径 + width: 460, + maxHeight: 16000, + backgroundColor: '#ffffff', + timeoutMs: 20000 +}) +// → { path, previewUrl, width, height, pixelWidth, pixelHeight, deviceScaleFactor, bytes, mimeType: 'image/png', sha256 } +``` + +- 与官方群聊日报共用同一 `HtmlRenderService` 离线渲染引擎。 +- 仅接受静态 HTML/CSS:自动拦截 `焦点', + highlights: ['项目评审通过'], + actionItems: ['张三跟进上线'], + groupBriefs: [{ groupName: '产品测试群', summary: '讨论了发布排期' }] + }) + ) + const html = buildDigestHtml({ + dateLabel: '2026-12-01', + ...summary, + totalMessages: 42, + totalMediaResolved: 3, + groupCount: 1 + }) + assert.equal(/ + + diff --git a/examples/extensions/morning-digest/ui/style.css b/examples/extensions/morning-digest/ui/style.css new file mode 100644 index 0000000..ff032ff --- /dev/null +++ b/examples/extensions/morning-digest/ui/style.css @@ -0,0 +1,225 @@ +* { + box-sizing: border-box; +} + +body { + margin: 0; + padding: 24px; + font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif; + background: #f5f7fa; + color: #18212f; +} + +.page { + max-width: 960px; + margin: 0 auto; + display: flex; + flex-direction: column; + gap: 16px; +} + +.hero { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 16px; + background: #ffffff; + border: 1px solid #e5e9f0; + border-radius: 14px; + padding: 20px; +} + +.kicker { + font-size: 12px; + color: #2563eb; + font-weight: 600; + margin-bottom: 4px; +} + +.hero h1 { + margin: 0 0 6px; + font-size: 22px; +} + +.subtitle { + margin: 0; + font-size: 13px; + color: #64748b; +} + +.hero-actions { + display: flex; + gap: 8px; + flex-shrink: 0; +} + +.btn { + padding: 8px 14px; + border-radius: 8px; + border: 1px solid #cbd5e1; + background: #ffffff; + color: #1e293b; + font-size: 13px; + cursor: pointer; +} + +.btn.primary { + background: #2563eb; + border-color: #2563eb; + color: #ffffff; +} + +.btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.banner { + padding: 10px 14px; + border-radius: 10px; + font-size: 13px; + background: #eff6ff; + color: #1d4ed8; + border: 1px solid #bfdbfe; +} + +.banner[data-tone="error"] { + background: #fef2f2; + color: #b91c1c; + border-color: #fecaca; +} + +.banner[data-tone="ok"] { + background: #f0fdf4; + color: #15803d; + border-color: #bbf7d0; +} + +.grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 16px; +} + +.card { + background: #ffffff; + border: 1px solid #e5e9f0; + border-radius: 14px; + padding: 18px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.card h2 { + margin: 0; + font-size: 15px; +} + +.card h3 { + margin: 8px 0 0; + font-size: 14px; +} + +.field { + display: flex; + flex-direction: column; + gap: 6px; + font-size: 13px; +} + +.field input, +.field select { + padding: 8px 10px; + border-radius: 8px; + border: 1px solid #cbd5e1; + font-size: 13px; +} + +.field-row { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 10px; +} + +.check-row { + display: flex; + align-items: center; + gap: 8px; + font-size: 13px; + cursor: pointer; +} + +.group-list { + max-height: 220px; + overflow: auto; + border: 1px solid #e2e8f0; + border-radius: 8px; + padding: 6px; + display: flex; + flex-direction: column; + gap: 4px; +} + +.group-item { + display: flex; + align-items: center; + gap: 8px; + padding: 6px 8px; + border-radius: 6px; + font-size: 13px; + cursor: pointer; +} + +.group-item:hover { + background: #f8fafc; +} + +.result-head { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; +} + +.result-body { + font-size: 13px; + line-height: 1.65; + white-space: pre-wrap; + background: #f8fafc; + border-radius: 10px; + padding: 14px; +} + +.result-body.empty { + color: #64748b; +} + +.preview-wrap { + margin-top: 14px; + padding: 12px; + border-radius: 12px; + background: #f8fafc; + border: 1px solid #e2e8f0; + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; +} + +.preview-caption { + font-size: 12px; + color: #64748b; + word-break: break-all; + align-self: flex-start; +} + +.preview-img { + max-width: 100%; + width: 460px; + height: auto; + border-radius: 10px; + border: 1px solid #cbd5e1; + box-shadow: 0 6px 20px rgba(15, 23, 42, 0.08); + background: #ffffff; +} diff --git a/examples/extensions/template-lock.json b/examples/extensions/template-lock.json index 2410c53..dddfe57 100644 --- a/examples/extensions/template-lock.json +++ b/examples/extensions/template-lock.json @@ -17,6 +17,10 @@ "sha256": "eb672f076710619dc363756d854319a8ded9b8f6a4833c258c1493c57bb89629", "bytes": 25231 }, + "group-chat-bot@1.1.0": { + "sha256": "be1fb28a2b8a20c95fccd19f6e2229f7166abfffefcf120309febcf3c882f437", + "bytes": 25947 + }, "keyword-bot@1.0.0": { "sha256": "3d8e5453e7ae6de7e29c16eb3c9e718a98bae27e9ed2edfd10399fb158e1c87d", "bytes": 19121 @@ -24,6 +28,10 @@ "keyword-bot@1.0.1": { "sha256": "ae379a10dac553b60cc8c823186734d917b604b6dff27e2e7d2d62f5cf5e4d41", "bytes": 19517 + }, + "morning-digest@1.0.0": { + "sha256": "3336d3c7739aad0d40919546ca7884581aaaf7e3487db5428041d6bc0f6bd992", + "bytes": 14556 } } } diff --git a/packages/extension-sdk/index.d.ts b/packages/extension-sdk/index.d.ts index efe1c99..94541ef 100644 --- a/packages/extension-sdk/index.d.ts +++ b/packages/extension-sdk/index.d.ts @@ -1,4 +1,4 @@ -/** TraceMemo 扩展 SDK v1:仅类型定义,运行期由宿主注入全局 tm。 */ +/** TraceMemo 扩展 SDK v1(兼容扩展):仅类型定义,运行期由宿主注入全局 tm。 */ export type ExtensionMessageType = | 'text' @@ -11,9 +11,23 @@ export type ExtensionMessageType = | 'system' | 'other' +export type ExtensionNavigationIcon = + | 'spark' + | 'bot' + | 'digest' + | 'bell' + | 'media' + | 'puzzle' + | 'compass' + | 'message' + +export type ExtensionNotificationLevel = 'info' | 'success' | 'warning' | 'error' + export interface TraceMemoMessageEvent { /** 同一条微信消息稳定不变:`message:`。 */ eventId: string + /** 跨实时事件与历史查询统一的不透明消息引用,可直接传给 tm.media.* 接口。 */ + messageRef: string accountId: string conversationId: string messageId: string @@ -31,6 +45,8 @@ export interface TraceMemoMessageEvent { export interface TraceMemoQueriedMessage { messageId: string + /** 跨实时事件与历史查询统一的不透明消息引用,可直接传给 tm.media.* 接口。 */ + messageRef: string conversationId: string senderId?: string senderName?: string @@ -41,6 +57,175 @@ export interface TraceMemoQueriedMessage { timestamp: number } +export interface TraceMemoMessagesQueryRequest { + conversationId: string + /** epoch 毫秒;默认最近 24 小时。 */ + startTime?: number + /** epoch 毫秒;默认现在。 */ + endTime?: number + limit?: number + /** 上一页返回的 opaque 游标;同时间戳多条消息不漏不重。 */ + cursor?: string + order?: 'asc' | 'desc' + types?: ExtensionMessageType[] +} + +export interface TraceMemoMessagesQueryResult { + messages: TraceMemoQueriedMessage[] + nextCursor?: string + hasMore: boolean +} + +export interface TraceMemoMediaReadImageResult { + messageRef: string + mimeType: string + bytes: number + sha256: string + /** 扩展私有数据目录内的可读副本路径。 */ + path: string + /** 扩展沙箱页面可直接加载的受控只读预览 URL。 */ + previewUrl?: string + quality: 'original' | 'thumbnail' + cached: boolean +} + +export interface TraceMemoMediaReadVoiceResult { + messageRef: string + mimeType: 'audio/wav' + bytes: number + sha256: string + durationMs?: number + path: string + previewUrl?: string + cached: boolean +} + +export interface TraceMemoMediaReadVideoResult { + messageRef: string + mimeType: 'video/mp4' + bytes: number + sha256: string + path: string + previewUrl?: string + posterPath?: string + posterPreviewUrl?: string + durationMs?: number + width?: number + height?: number + cached: boolean +} + +export interface TraceMemoMediaOcrImageResult { + messageRef: string + text: string + language: string | null + engine: string + cached: boolean +} + +export interface TraceMemoMediaTranscribeVoiceResult { + messageRef: string + state: 'transcribed' | 'pending' | 'failed' + transcript?: string + durationMs?: number + cached: boolean + error?: string +} + +export interface TraceMemoMediaAnalyzeImageResult { + messageRef: string + description: string + ocrText?: string + tags?: string[] + category?: string + model?: string + cached: boolean +} + +export type TraceMemoMediaBatchOperation = + | 'readImage' + | 'readVoice' + | 'readVideo' + | 'ocrImage' + | 'transcribeVoice' + | 'analyzeImage' + +export interface TraceMemoMediaBatchItem { + op: TraceMemoMediaBatchOperation + messageRef: string + options?: Record +} + +export interface TraceMemoMediaBatchItemResult { + index: number + op: TraceMemoMediaBatchOperation + messageRef: string + ok: boolean + result?: + | TraceMemoMediaReadImageResult + | TraceMemoMediaReadVoiceResult + | TraceMemoMediaReadVideoResult + | TraceMemoMediaOcrImageResult + | TraceMemoMediaTranscribeVoiceResult + | TraceMemoMediaAnalyzeImageResult + error?: { code: string; message: string } +} + +export interface TraceMemoRenderHtmlRequest { + html: string + css?: string + /** 可选相对文件名(输出到扩展私有目录的 rendered/ 下)。 */ + fileName?: string + width?: number + maxHeight?: number + backgroundColor?: string + timeoutMs?: number +} + +export interface TraceMemoRenderHtmlResult { + path: string + /** 扩展沙箱页面可直接加载的受控只读预览 URL。 */ + previewUrl?: string + width: number + height: number + pixelWidth?: number + pixelHeight?: number + deviceScaleFactor?: number + bytes: number + mimeType: 'image/png' + sha256: string +} + +export interface TraceMemoNotificationCreateRequest { + title: string + body?: string + level?: ExtensionNotificationLevel + /** 扩展内去重键;相同键更新既有通知而不重复叠加未读数。 */ + dedupeKey?: string + /** 点击通知后跳转的本扩展页面 id。 */ + pageId?: string +} + +export interface TraceMemoNotificationCreateResult { + id: string + deduped: boolean + createdAt: number +} + +export interface TraceMemoNotificationItem { + id: string + extensionId: string + extensionName: string + title: string + body?: string + level: ExtensionNotificationLevel + dedupeKey?: string + pageId?: string + read: boolean + createdAt: number + updatedAt: number +} + export interface TraceMemoSendTextRequest { /** 缺省为 text。 */ type?: 'text' @@ -147,6 +332,18 @@ export interface TraceMemoApi { readonly dataDir: string readonly permissions: string[] } + page: { + onRequest( + method: string, + handler: (params: Record) => unknown | Promise + ): void + } + secrets: { + get(key: string): Promise + set(key: string, value: string): Promise + delete(key: string): Promise + has(key: string): Promise + } events: { on( name: 'message.received', @@ -158,20 +355,53 @@ export interface TraceMemoApi { ): void } messages: { - query(request: { - conversationId: string - /** epoch 毫秒;默认最近 24 小时。 */ - startTime?: number - /** epoch 毫秒;默认现在。 */ - endTime?: number - limit?: number - }): Promise<{ messages: TraceMemoQueriedMessage[] }> + query(request: TraceMemoMessagesQueryRequest): Promise + } + media: { + readImage(request: { + messageRef: string + quality?: 'original' | 'thumbnail' + }): Promise + readVoice(request: { messageRef: string }): Promise + readVideo(request: { messageRef: string }): Promise + ocrImage(request: { + messageRef: string + language?: string + force?: boolean + }): Promise + transcribeVoice(request: { + messageRef: string + force?: boolean + waitMs?: number + }): Promise + analyzeImage(request: { + messageRef: string + prompt?: string + force?: boolean + }): Promise + batch(request: { + items: TraceMemoMediaBatchItem[] + concurrency?: number + }): Promise<{ results: TraceMemoMediaBatchItemResult[] }> + } + render: { + htmlToImage(request: TraceMemoRenderHtmlRequest): Promise + } + notifications: { + create(request: TraceMemoNotificationCreateRequest): Promise + list(): Promise + markRead(request?: { id?: string; all?: boolean }): Promise<{ changed: number }> } wechat: { send(request: TraceMemoSendRequest): Promise<{ actionId: string; status: 'sent' }> } ai: { chat(messages: Array<{ role: string; content: string }>): Promise<{ text: string }> + analyzeImage(request: { + messageRef: string + prompt?: string + force?: boolean + }): Promise } storage: { get(key: string): Promise diff --git a/scripts/build-extension-templates.cjs b/scripts/build-extension-templates.cjs index 651f294..bb112c5 100644 --- a/scripts/build-extension-templates.cjs +++ b/scripts/build-extension-templates.cjs @@ -33,6 +33,16 @@ const TEMPLATE_SPECS = [ }, platforms: ['darwin', 'win32'] }, + { + id: 'morning-digest', + dir: 'morning-digest', + requires: { + python: false, + chrome: false, + externalScript: false + }, + platforms: ['darwin', 'win32'] + }, { id: 'douyin-sender', dir: 'douyin-sender', diff --git a/src/main/extensions/extension-event-bus.ts b/src/main/extensions/extension-event-bus.ts index 25810ed..caf7947 100644 --- a/src/main/extensions/extension-event-bus.ts +++ b/src/main/extensions/extension-event-bus.ts @@ -6,6 +6,7 @@ import { shouldDeliverExtensionEvent, type ExtensionMessageEvent } from '../../shared/extensions/events' +import type { ExtensionMessageRef } from '../../shared/extensions/media' import type { ExtensionSubscriptions } from '../../shared/extensions/manifest' import type { NormalizedIncomingMessage } from '../services/message-listener-service' @@ -22,6 +23,7 @@ export interface ExtensionEventBusDependencies { listSubscribers: () => ExtensionEventSubscriber[] getAccountId: () => string getSelfUsernames: () => string[] + encodeMessageRef?: (ref: ExtensionMessageRef) => string now?: () => number onDelivered?: (extensionId: string, event: ExtensionMessageEvent) => void } @@ -71,21 +73,25 @@ export class ExtensionEventBus { return } const selfUsernames = new Set(this.dependencies.getSelfUsernames()) - const event = buildExtensionMessageEvent({ - eventId, - accountId: this.accountId, - conversationId: message.sessionId, - messageId: message.serverId || message.localId, - ...(message.senderId ? { senderId: message.senderId } : {}), - ...(message.senderNickname ? { senderName: message.senderNickname } : {}), - isGroup: message.isGroup, - isSelf: message.isSelf, - messageType: message.messageType, - ...(message.content !== undefined ? { content: message.content } : {}), - // 只有 source 里真实出现当前账号 username 才算 @我;拿不到自身身份时一律 false。 - mentionsMe: message.mentionTargets.some((target) => selfUsernames.has(target)), - createTimeSeconds: message.createTime - }) + const event = buildExtensionMessageEvent( + { + eventId, + accountId: this.accountId, + conversationId: message.sessionId, + messageId: message.serverId || message.localId, + localId: message.localId, + ...(message.senderId ? { senderId: message.senderId } : {}), + ...(message.senderNickname ? { senderName: message.senderNickname } : {}), + isGroup: message.isGroup, + isSelf: message.isSelf, + messageType: message.messageType, + ...(message.content !== undefined ? { content: message.content } : {}), + // 只有 source 里真实出现当前账号 username 才算 @我;拿不到自身身份时一律 false。 + mentionsMe: message.mentionTargets.some((target) => selfUsernames.has(target)), + createTimeSeconds: message.createTime + }, + this.dependencies.encodeMessageRef + ) const envelope: ExtensionEventEnvelope = { version: EXTENSION_EVENT_PROTOCOL_VERSION, kind: 'message.received', diff --git a/src/main/extensions/extension-host.ts b/src/main/extensions/extension-host.ts index b5bb108..7937a4b 100644 --- a/src/main/extensions/extension-host.ts +++ b/src/main/extensions/extension-host.ts @@ -4,7 +4,6 @@ import { existsSync } from 'node:fs' import { tmpdir } from 'node:os' import { killProcessTree, type ProcessTreeKillResult } from '../process-tree' import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors' -import type { ExtensionRuntimeSnapshot } from '../../shared/extensions/types' import { sortPermissionsByRisk, type ExtensionPermission @@ -18,15 +17,42 @@ import { type ExtensionHostInboundMessage, type ExtensionHostOutboundMessage, type ExtensionMessagesQueryRequest, + type ExtensionMessagesQueryResult, + type ExtensionNotificationCreateRequest, + type ExtensionNotificationCreateResult, + type ExtensionNotificationMarkReadRequest, + type ExtensionNotificationMarkReadResult, type ExtensionQueriedMessage, + type ExtensionRenderHtmlToImageRequest, + type ExtensionRenderHtmlToImageResult, type ExtensionSendImageRequest, type ExtensionSendTextRequest, type ExtensionSendTextResult, type ExtensionSendVideoRequest, type ExtensionSendVoiceRequest } from '../../shared/extensions/rpc' +import type { + ExtensionMediaAnalyzeImageRequest, + ExtensionMediaAnalyzeImageResult, + ExtensionMediaBatchRequest, + ExtensionMediaBatchResult, + ExtensionMediaOcrImageRequest, + ExtensionMediaOcrImageResult, + ExtensionMediaReadImageRequest, + ExtensionMediaReadImageResult, + ExtensionMediaReadVideoRequest, + ExtensionMediaReadVideoResult, + ExtensionMediaReadVoiceRequest, + ExtensionMediaReadVoiceResult, + ExtensionMediaTranscribeVoiceRequest, + ExtensionMediaTranscribeVoiceResult +} from '../../shared/extensions/media' import type { ExtensionEventEnvelope } from '../../shared/extensions/events' -import type { ExtensionCapabilitySnapshot } from '../../shared/extensions/types' +import type { + ExtensionCapabilitySnapshot, + ExtensionNotificationItem, + ExtensionRuntimeSnapshot +} from '../../shared/extensions/types' import { parseActionInputSchema, type ExtensionActionInputSchema @@ -95,6 +121,8 @@ export interface ExtensionHostDependencies { /** 扩展私有数据目录;媒体文件只允许从这里或临时目录发送。 */ dataDir: string permissions: ExtensionPermission[] + /** 实时权限检查(回查主进程最新状态),未提供时回退到启动快照 permissions。 */ + hasPermission?: (permission: ExtensionPermission) => boolean storage: ExtensionStorage secrets?: ExtensionSecretStore spawn: (options: ExtensionHostSpawnOptions) => ExtensionHostChild @@ -104,7 +132,48 @@ export interface ExtensionHostDependencies { queryMessages?: ( extensionId: string, request: ExtensionMessagesQueryRequest - ) => Promise + ) => Promise + mediaReadImage?: ( + extensionId: string, + request: ExtensionMediaReadImageRequest + ) => Promise + mediaReadVoice?: ( + extensionId: string, + request: ExtensionMediaReadVoiceRequest + ) => Promise + mediaReadVideo?: ( + extensionId: string, + request: ExtensionMediaReadVideoRequest + ) => Promise + mediaOcrImage?: ( + extensionId: string, + request: ExtensionMediaOcrImageRequest + ) => Promise + mediaTranscribeVoice?: ( + extensionId: string, + request: ExtensionMediaTranscribeVoiceRequest + ) => Promise + mediaAnalyzeImage?: ( + extensionId: string, + request: ExtensionMediaAnalyzeImageRequest + ) => Promise + mediaBatch?: ( + extensionId: string, + request: ExtensionMediaBatchRequest + ) => Promise + renderHtmlToImage?: ( + extensionId: string, + request: ExtensionRenderHtmlToImageRequest + ) => Promise + createNotification?: ( + extensionId: string, + request: ExtensionNotificationCreateRequest + ) => Promise | ExtensionNotificationCreateResult + listNotifications?: (extensionId: string) => Promise | ExtensionNotificationItem[] + markNotificationsRead?: ( + extensionId: string, + request: ExtensionNotificationMarkReadRequest + ) => Promise | ExtensionNotificationMarkReadResult sendText?: ( extensionId: string, request: ExtensionSendTextRequest @@ -311,6 +380,7 @@ export class ExtensionHost { this.settleActivation(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止')) this.failPendingActions(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止')) this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止')) + this.failPendingPageRequests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止')) this.actions.clear() if (!child) { this.setState('inactive') @@ -592,6 +662,9 @@ export class ExtensionHost { new ExtensionError('EXTENSION_HOST_UNAVAILABLE', `扩展进程已退出(${code ?? 'unknown'})`) ) this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程已退出')) + this.failPendingPageRequests( + new ExtensionError('EXTENSION_HOST_UNAVAILABLE', `扩展进程已退出(${code ?? 'unknown'})`) + ) if (this.stopping) { this.setState('inactive') return @@ -775,12 +848,108 @@ export class ExtensionHost { case 'messages.query': { this.requirePermission('messages.query') if (!this.dependencies.queryMessages) throw new ExtensionError('CAPABILITY_UNAVAILABLE') - return { - messages: await this.dependencies.queryMessages( - extensionId, - params as unknown as ExtensionMessagesQueryRequest - ) + const queried = await this.dependencies.queryMessages( + extensionId, + params as unknown as ExtensionMessagesQueryRequest + ) + if (Array.isArray(queried)) { + return { messages: queried, hasMore: false } } + return queried + } + case 'media.readImage': { + this.requirePermission('media.read') + if (!this.dependencies.mediaReadImage) throw new ExtensionError('CAPABILITY_UNAVAILABLE') + return this.dependencies.mediaReadImage( + extensionId, + params as unknown as ExtensionMediaReadImageRequest + ) + } + case 'media.readVoice': { + this.requirePermission('media.read') + if (!this.dependencies.mediaReadVoice) throw new ExtensionError('CAPABILITY_UNAVAILABLE') + return this.dependencies.mediaReadVoice( + extensionId, + params as unknown as ExtensionMediaReadVoiceRequest + ) + } + case 'media.readVideo': { + this.requirePermission('media.read') + if (!this.dependencies.mediaReadVideo) throw new ExtensionError('CAPABILITY_UNAVAILABLE') + return this.dependencies.mediaReadVideo( + extensionId, + params as unknown as ExtensionMediaReadVideoRequest + ) + } + case 'media.ocrImage': { + this.requirePermission('media.ocr') + if (!this.dependencies.mediaOcrImage) throw new ExtensionError('CAPABILITY_UNAVAILABLE') + return this.dependencies.mediaOcrImage( + extensionId, + params as unknown as ExtensionMediaOcrImageRequest + ) + } + case 'media.transcribeVoice': { + this.requirePermission('media.transcribe') + if (!this.dependencies.mediaTranscribeVoice) { + throw new ExtensionError('CAPABILITY_UNAVAILABLE') + } + return this.dependencies.mediaTranscribeVoice( + extensionId, + params as unknown as ExtensionMediaTranscribeVoiceRequest + ) + } + case 'media.analyzeImage': { + this.requirePermission('ai.vision') + if (!this.dependencies.mediaAnalyzeImage) throw new ExtensionError('CAPABILITY_UNAVAILABLE') + return this.dependencies.mediaAnalyzeImage( + extensionId, + params as unknown as ExtensionMediaAnalyzeImageRequest + ) + } + case 'media.batch': { + if (!this.dependencies.mediaBatch) throw new ExtensionError('CAPABILITY_UNAVAILABLE') + return this.dependencies.mediaBatch( + extensionId, + params as unknown as ExtensionMediaBatchRequest + ) + } + case 'render.htmlToImage': { + this.requirePermission('render.html') + if (!this.dependencies.renderHtmlToImage) { + throw new ExtensionError('CAPABILITY_UNAVAILABLE') + } + return this.dependencies.renderHtmlToImage( + extensionId, + params as unknown as ExtensionRenderHtmlToImageRequest + ) + } + case 'notifications.create': { + this.requirePermission('notifications.create') + if (!this.dependencies.createNotification) { + throw new ExtensionError('CAPABILITY_UNAVAILABLE') + } + return this.dependencies.createNotification( + extensionId, + params as unknown as ExtensionNotificationCreateRequest + ) + } + case 'notifications.list': { + this.requirePermission('notifications.create') + if (!this.dependencies.listNotifications) { + throw new ExtensionError('CAPABILITY_UNAVAILABLE') + } + return { items: await this.dependencies.listNotifications(extensionId) } + } + case 'notifications.markRead': { + this.requirePermission('notifications.create') + if (!this.dependencies.markNotificationsRead) { + throw new ExtensionError('CAPABILITY_UNAVAILABLE') + } + return this.dependencies.markNotificationsRead( + extensionId, + params as unknown as ExtensionNotificationMarkReadRequest + ) } case 'wechat.send.text': { this.requirePermission('wechat.send.text') @@ -838,7 +1007,10 @@ export class ExtensionHost { } private requirePermission(permission: ExtensionPermission): void { - if (!this.dependencies.permissions.includes(permission)) { + const allowed = this.dependencies.hasPermission + ? this.dependencies.hasPermission(permission) + : this.dependencies.permissions.includes(permission) + if (!allowed) { throw new ExtensionError('PERMISSION_DENIED', `扩展没有 ${permission} 权限`) } } @@ -867,6 +1039,14 @@ export class ExtensionHost { } } + private failPendingPageRequests(error: Error): void { + for (const [requestId, pending] of this.pendingPageRequests) { + clearTimeout(pending.timer) + this.pendingPageRequests.delete(requestId) + pending.reject(error) + } + } + private refillTokens(): void { const now = this.now() const elapsed = Math.max(0, now - this.eventTokensAt) diff --git a/src/main/extensions/extension-ipc.ts b/src/main/extensions/extension-ipc.ts index 4010879..b72de6c 100644 --- a/src/main/extensions/extension-ipc.ts +++ b/src/main/extensions/extension-ipc.ts @@ -7,11 +7,14 @@ import type { ExtensionInstallResult, ExtensionProjectResult, ExtensionLogEntry, + ExtensionNotificationItem, + ExtensionNotificationSummary, ExtensionOperationResult, ExtensionPageDescriptor, ExtensionPageRequest, ExtensionPageResponse, - InstalledExtension + InstalledExtension, + PinnedExtensionNavItem } from '../../shared/extensions/types' import type { ExtensionManager } from './extension-manager' import type { ExtensionPaths } from './extension-paths' @@ -368,6 +371,80 @@ export function registerExtensionIpc(options: ExtensionIpcOptions): void { return error ? { success: false, error } : { success: true } }) ) + + ipcMain.handle( + EXTENSION_IPC.pinnedNavigation, + guard((): PinnedExtensionNavItem[] => manager().listPinnedNavigation()) + ) + + ipcMain.handle( + EXTENSION_IPC.pinNavigation, + guard((payload: unknown): ExtensionOperationResult => { + const input = (payload ?? {}) as { id?: unknown; pageId?: unknown } + const pageId = + typeof input.pageId === 'string' && input.pageId.trim() ? input.pageId.trim() : undefined + return manager().pinNavigation(requireId(input.id), pageId) + }) + ) + + ipcMain.handle( + EXTENSION_IPC.unpinNavigation, + guard((extensionId: unknown): ExtensionOperationResult => + manager().unpinNavigation(requireId(extensionId)) + ) + ) + + ipcMain.handle( + EXTENSION_IPC.reorderNavigation, + guard((extensionIds: unknown): ExtensionOperationResult => { + const ids = Array.isArray(extensionIds) + ? extensionIds.filter((item): item is string => typeof item === 'string') + : [] + return manager().reorderPinnedNavigation(ids) + }) + ) + + ipcMain.handle( + EXTENSION_IPC.notificationsList, + guard((extensionId?: unknown): ExtensionNotificationItem[] => { + const id = + typeof extensionId === 'string' && extensionId.trim() ? requireId(extensionId) : undefined + return manager().listNotifications(id) + }) + ) + + ipcMain.handle( + EXTENSION_IPC.notificationsSummary, + guard((): ExtensionNotificationSummary => manager().getNotificationSummary()) + ) + + ipcMain.handle( + EXTENSION_IPC.notificationsMarkRead, + guard((payload: unknown): { changed: number } => { + const input = (payload ?? {}) as { id?: unknown; extensionId?: unknown; all?: unknown } + const id = typeof input.id === 'string' && input.id.trim() ? input.id.trim() : undefined + const extensionId = + typeof input.extensionId === 'string' && input.extensionId.trim() + ? requireId(input.extensionId) + : undefined + return { + changed: manager().markNotificationsRead({ + ...(id ? { id } : {}), + ...(extensionId ? { extensionId } : {}), + all: input.all === true + }) + } + }) + ) + + ipcMain.handle( + EXTENSION_IPC.notificationsClear, + guard((extensionId?: unknown): { removed: number } => { + const id = + typeof extensionId === 'string' && extensionId.trim() ? requireId(extensionId) : undefined + return { removed: manager().clearNotifications(id) } + }) + ) } function requireId(value: unknown): string { diff --git a/src/main/extensions/extension-manager.ts b/src/main/extensions/extension-manager.ts index fcf0357..4f0731c 100644 --- a/src/main/extensions/extension-manager.ts +++ b/src/main/extensions/extension-manager.ts @@ -24,6 +24,8 @@ import type { ExtensionCapabilitySnapshot, ExtensionInstallResult, ExtensionLogEntry, + ExtensionNotificationItem, + ExtensionNotificationSummary, ExtensionOperationResult, ExtensionPageDescriptor, ExtensionPageMethod, @@ -32,18 +34,45 @@ import type { ExtensionProjectResult, ExtensionSystemHealth, ExtensionTtsCapabilitySnapshot, - InstalledExtension + InstalledExtension, + PinnedExtensionNavItem } from '../../shared/extensions/types' import type { ExtensionAutomationActionOutput, ExtensionMessagesQueryRequest, + ExtensionMessagesQueryResult, + ExtensionNotificationCreateRequest, + ExtensionNotificationCreateResult, + ExtensionNotificationMarkReadRequest, + ExtensionNotificationMarkReadResult, ExtensionQueriedMessage, + ExtensionRenderHtmlToImageRequest, + ExtensionRenderHtmlToImageResult, ExtensionSendImageRequest, ExtensionSendTextRequest, ExtensionSendTextResult, ExtensionSendVideoRequest, ExtensionSendVoiceRequest } from '../../shared/extensions/rpc' +import type { + ExtensionMediaAnalyzeImageRequest, + ExtensionMediaAnalyzeImageResult, + ExtensionMediaBatchRequest, + ExtensionMediaBatchResult, + ExtensionMediaOcrImageRequest, + ExtensionMediaOcrImageResult, + ExtensionMediaReadImageRequest, + ExtensionMediaReadImageResult, + ExtensionMediaReadVideoRequest, + ExtensionMediaReadVideoResult, + ExtensionMediaReadVoiceRequest, + ExtensionMediaReadVoiceResult, + ExtensionMediaTranscribeVoiceRequest, + ExtensionMediaTranscribeVoiceResult, + ExtensionMessageRef +} from '../../shared/extensions/media' +import type { ExtensionMediaGateway } from './extension-media-gateway' +import { buildExtensionPrivateMediaPreviewUrl } from './extension-protocol' import type { PersonalWechatSendCapability } from '../../shared/personal-wechat' import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action' import type { NormalizedIncomingMessage } from '../services/message-listener-service' @@ -67,6 +96,8 @@ import { type ExtensionTemplateStatus } from './extension-template-catalog' import { ExtensionLogStore } from './extension-log' +import { ExtensionNavigationStore } from './extension-navigation-store' +import { ExtensionNotificationStore } from './extension-notification-store' import { ExtensionRegistry, type ExtensionRegistryRecord } from './extension-registry' import { ExtensionSendGateway } from './extension-send-gateway' import { ExtensionStorage } from './extension-storage' @@ -80,7 +111,26 @@ export interface ExtensionManagerDependencies { getCapability: () => Promise checkEntitlement: () => Promise executeAction: (request: WechatActionRequest) => Promise - queryMessages: (request: ExtensionMessagesQueryRequest) => Promise + queryMessages: ( + request: ExtensionMessagesQueryRequest + ) => Promise + /** 可选媒体网关工厂:在主进程独立校验权限与会话范围后按需读取/解析媒体。 */ + createMediaGateway?: (context: { + hasPermission: (extensionId: string, permission: ExtensionPermission) => boolean + isConversationAllowed: (extensionId: string, conversationId: string) => boolean + getExtensionDataRoot: (extensionId: string) => string + }) => ExtensionMediaGateway + mediaGateway?: ExtensionMediaGateway + /** 可选 messageRef 主进程签名函数;配置后事件总线与历史查询共用签名机制。 */ + encodeMessageRef?: (ref: ExtensionMessageRef) => string + /** 账号切换回调,用于刷新 messageRef 签名世代。 */ + onAccountChanged?: (accountId: string) => void + /** 离线静态 HTML 渲染实现(复用通用 HtmlRenderService)。 */ + renderHtmlToImage?: ( + extensionId: string, + extensionDataRoot: string, + request: ExtensionRenderHtmlToImageRequest + ) => Promise /** 群列表(id + 显示名);用于扩展配置页选择发送目标。 */ listGroups: () => Promise> aiChat: (messages: Array<{ role: string; content: string }>) => Promise<{ text: string }> @@ -103,7 +153,15 @@ export interface ExtensionManagerDependencies { now?: () => number onChange?: ( extensionId: string, - reason: 'installed' | 'enabled' | 'disabled' | 'uninstalled' | 'runtime' | 'actions' + reason: + | 'installed' + | 'enabled' + | 'disabled' + | 'uninstalled' + | 'runtime' + | 'actions' + | 'navigation' + | 'notifications' ) => void } @@ -129,8 +187,11 @@ export class ExtensionManager { private readonly installer: ExtensionInstaller private readonly storage: ExtensionStorage private readonly logs: ExtensionLogStore + private readonly navigationStore: ExtensionNavigationStore + private readonly notificationStore: ExtensionNotificationStore private readonly actions = new ExtensionActionRegistry() private readonly sendGateway: ExtensionSendGateway + private readonly mediaGateway: ExtensionMediaGateway | null private readonly hosts = new Map() private readonly manifests = new Map() private readonly eventBus: ExtensionEventBus @@ -183,6 +244,8 @@ export class ExtensionManager { onHealthChange: (extensionId, health) => this.handleStorageHealthChange(extensionId, health) }) this.logs = new ExtensionLogStore(this.paths.logsDir) + this.navigationStore = new ExtensionNavigationStore(this.paths.pinnedNavigationFile, this.now) + this.notificationStore = new ExtensionNotificationStore(this.paths.notificationsFile, this.now) this.sendGateway = new ExtensionSendGateway({ getCapability: dependencies.getCapability, checkEntitlement: dependencies.checkEntitlement, @@ -197,8 +260,19 @@ export class ExtensionManager { listSubscribers: () => this.listEventSubscribers(), getAccountId: dependencies.getAccountId, getSelfUsernames: dependencies.getSelfUsernames, + ...(dependencies.encodeMessageRef ? { encodeMessageRef: dependencies.encodeMessageRef } : {}), now: this.now }) + this.mediaGateway = + dependencies.mediaGateway ?? + dependencies.createMediaGateway?.({ + hasPermission: (extensionId, permission) => + this.hasActivePermission(extensionId, permission), + isConversationAllowed: (extensionId, conversationId) => + this.isConversationAllowed(extensionId, conversationId), + getExtensionDataRoot: (extensionId) => this.paths.extensionDataDir(extensionId) + }) ?? + null } /** 建立目录、加载状态、拉起已启用的扩展。单个扩展失败不影响其他扩展。 */ @@ -633,6 +707,8 @@ export class ExtensionManager { } } else { this.registry.remove(extensionId) + this.navigationStore.remove(extensionId) + this.notificationStore.removeByExtension(extensionId) } } catch (error) { return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) @@ -1058,10 +1134,176 @@ export class ExtensionManager { return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) } if (!keepData) this.logs.remove(extensionId) + this.navigationStore.remove(extensionId) + this.notificationStore.removeByExtension(extensionId) this.dependencies.onChange?.(extensionId, 'uninstalled') return { success: true } } + /** 返回用户固定到一级导航的扩展条目(自动过滤已卸载或无页面扩展)。 */ + listPinnedNavigation(): PinnedExtensionNavItem[] { + const records = this.navigationStore.list() + const result: PinnedExtensionNavItem[] = [] + for (const pinned of records) { + const record = this.registry.get(pinned.extensionId) + if (!record) continue + const manifest = this.readManifest(pinned.extensionId) + if (!manifest || !manifest.entrypoints.page) continue + const nav = manifest.contributions.navigation + const defaultPageId = nav?.pageId || manifest.contributions.pages[0]?.id + const pageId = pinned.pageId || defaultPageId + result.push({ + extensionId: record.id, + extensionName: manifest.name, + label: nav?.label || manifest.name, + icon: nav?.icon || 'puzzle', + ...(pageId ? { pageId } : {}), + order: pinned.order, + enabled: record.enabled + }) + } + return result + } + + pinNavigation(extensionId: string, pageId?: string): ExtensionOperationResult { + const record = this.registry.get(extensionId) + if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND')) + const manifest = this.readManifest(extensionId) + if (!manifest || !manifest.entrypoints.page) { + return failure(new ExtensionError('INVALID_REQUEST', '该扩展没有可固定的页面入口')) + } + const targetPageId = pageId || manifest.contributions.navigation?.pageId || manifest.contributions.pages[0]?.id + if ( + targetPageId && + manifest.contributions.pages.length > 0 && + !manifest.contributions.pages.some((page) => page.id === targetPageId) + ) { + return failure(new ExtensionError('INVALID_REQUEST', `扩展页面不存在:${targetPageId}`)) + } + try { + this.navigationStore.pin(extensionId, targetPageId) + this.dependencies.onChange?.(extensionId, 'navigation') + return { success: true } + } catch (error) { + return failure(toExtensionErrorPayload(error) as unknown as ExtensionError) + } + } + + unpinNavigation(extensionId: string): ExtensionOperationResult { + this.navigationStore.unpin(extensionId) + this.dependencies.onChange?.(extensionId, 'navigation') + return { success: true } + } + + reorderPinnedNavigation(extensionIds: string[]): ExtensionOperationResult { + const sanitized = Array.isArray(extensionIds) + ? extensionIds.map((id) => String(id || '').trim()).filter((id) => isValidExtensionId(id)) + : [] + this.navigationStore.reorder(sanitized) + this.dependencies.onChange?.(sanitized[0] || '', 'navigation') + return { success: true } + } + + createNotification( + extensionId: string, + request: ExtensionNotificationCreateRequest + ): ExtensionNotificationCreateResult { + 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, 'notifications.create')) { + throw new ExtensionError('PERMISSION_DENIED', '扩展没有 notifications.create 权限') + } + const manifest = this.readManifest(extensionId) + const extensionName = manifest?.name || record.id + const targetPageId = request?.pageId + ? String(request.pageId).trim() + : manifest?.contributions.navigation?.pageId || manifest?.contributions.pages[0]?.id + if ( + request?.pageId && + manifest && + manifest.contributions.pages.length > 0 && + !manifest.contributions.pages.some((page) => page.id === targetPageId) + ) { + throw new ExtensionError('INVALID_REQUEST', `通知跳转页面不存在:${targetPageId}`) + } + const created = this.notificationStore.create(extensionId, extensionName, { + ...request, + ...(targetPageId ? { pageId: targetPageId } : {}) + }) + this.dependencies.onChange?.(extensionId, 'notifications') + return created + } + + listNotifications(extensionId?: string): ExtensionNotificationItem[] { + return this.notificationStore.list(extensionId) + } + + /** 扩展后台查询自身通知(强绑定调用方 extensionId,绝不跨扩展读取)。 */ + private listOwnNotifications(extensionId: string): ExtensionNotificationItem[] { + 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, 'notifications.create')) { + throw new ExtensionError('PERMISSION_DENIED', '扩展没有 notifications.create 权限') + } + return this.notificationStore.list(extensionId) + } + + /** 扩展后台标记自身通知已读(强绑定调用方 extensionId,禁止修改其他扩展通知)。 */ + private markOwnNotificationsRead( + extensionId: string, + request: ExtensionNotificationMarkReadRequest + ): ExtensionNotificationMarkReadResult { + 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, 'notifications.create')) { + throw new ExtensionError('PERMISSION_DENIED', '扩展没有 notifications.create 权限') + } + const id = typeof request?.id === 'string' && request.id.trim() ? request.id.trim() : undefined + const all = request?.all === true || !id + const changed = this.notificationStore.markRead({ + extensionId, + ...(id ? { id } : {}), + ...(all ? { all: true } : {}) + }) + if (changed > 0) { + this.dependencies.onChange?.(extensionId, 'notifications') + } + return { changed } + } + + getNotificationSummary(): ExtensionNotificationSummary { + const pinnedIds = new Set(this.listPinnedNavigation().map((item) => item.extensionId)) + return this.notificationStore.summary(pinnedIds) + } + + markNotificationsRead(options: { id?: string; extensionId?: string; all?: boolean }): number { + const changed = this.notificationStore.markRead(options) + if (changed > 0) { + this.dependencies.onChange?.(options.extensionId || '', 'notifications') + } + return changed + } + + clearNotifications(extensionId?: string): number { + const removed = this.notificationStore.clear(extensionId) + if (removed > 0) { + this.dependencies.onChange?.(extensionId || '', 'notifications') + } + return removed + } + /** 页面地址。停用的扩展也允许打开自己的配置页(否则用户无法先配置再启用)。 */ pageUrl(extensionId: string, pageId?: string): ExtensionPageDescriptor { const record = this.registry.get(extensionId) @@ -1176,12 +1418,15 @@ export class ExtensionManager { } handleMessage(message: NormalizedIncomingMessage): void { - this.eventBus.setAccountId(this.dependencies.getAccountId()) + const accountId = this.dependencies.getAccountId() + this.eventBus.setAccountId(accountId) + this.dependencies.onAccountChanged?.(accountId) this.eventBus.handleMessage(message) } setAccountId(accountId: string): void { this.eventBus.setAccountId(accountId) + this.dependencies.onAccountChanged?.(accountId) } /** 自动化动作执行入口。由 `AutomationActionRunner` 调用。 */ @@ -1380,6 +1625,7 @@ export class ExtensionManager { extensionDir: resolvedRoot.root, dataDir: this.paths.extensionDataDir(extensionId), permissions: this.registry.get(extensionId)?.grantedPermissions ?? [], + hasPermission: (permission) => this.hasActivePermission(extensionId, permission), storage: this.storage, secrets: this.secrets, spawn: this.dependencies.spawn ?? this.defaultSpawn(), @@ -1393,6 +1639,17 @@ export class ExtensionManager { this.dependencies.onChange?.(extensionId, 'actions') }, queryMessages: (id, request) => this.queryMessages(id, request), + mediaReadImage: (id, request) => this.mediaReadImage(id, request), + mediaReadVoice: (id, request) => this.mediaReadVoice(id, request), + mediaReadVideo: (id, request) => this.mediaReadVideo(id, request), + mediaOcrImage: (id, request) => this.mediaOcrImage(id, request), + mediaTranscribeVoice: (id, request) => this.mediaTranscribeVoice(id, request), + mediaAnalyzeImage: (id, request) => this.mediaAnalyzeImage(id, request), + mediaBatch: (id, request) => this.mediaBatch(id, request), + renderHtmlToImage: (id, request) => this.renderHtmlToImage(id, request), + createNotification: (id, request) => this.createNotification(id, request), + listNotifications: (id) => this.listOwnNotifications(id), + markNotificationsRead: (id, request) => this.markOwnNotificationsRead(id, request), sendText: (id, request) => this.sendText(id, request), sendImage: (id, request) => this.sendImage(id, request), sendVideo: (id, request) => this.sendVideo(id, request), @@ -1459,10 +1716,112 @@ export class ExtensionManager { return subscribers } + private hasActivePermission(extensionId: string, permission: ExtensionPermission): boolean { + const record = this.registry.get(extensionId) + if (!record?.enabled || this.isSuspended(extensionId)) return false + return hasExtensionPermission(record.grantedPermissions, permission) + } + + /** 若 manifest.subscriptions.conversationIds 非空,则限制扩展只能访问声明范围内的会话。 */ + private isConversationAllowed(extensionId: string, conversationId: string): boolean { + const manifest = this.readManifest(extensionId) + const scope = manifest?.subscriptions?.conversationIds ?? [] + if (scope.length === 0) return true + return scope.includes(conversationId) + } + + private requireMediaGateway(extensionId: string): ExtensionMediaGateway { + 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 (!this.mediaGateway) { + throw new ExtensionError('CAPABILITY_UNAVAILABLE', '当前环境未启用扩展媒体能力') + } + return this.mediaGateway + } + + private async mediaReadImage( + extensionId: string, + request: ExtensionMediaReadImageRequest + ): Promise { + return this.requireMediaGateway(extensionId).readImage(extensionId, request) + } + + private async mediaReadVoice( + extensionId: string, + request: ExtensionMediaReadVoiceRequest + ): Promise { + return this.requireMediaGateway(extensionId).readVoice(extensionId, request) + } + + private async mediaReadVideo( + extensionId: string, + request: ExtensionMediaReadVideoRequest + ): Promise { + return this.requireMediaGateway(extensionId).readVideo(extensionId, request) + } + + private async mediaOcrImage( + extensionId: string, + request: ExtensionMediaOcrImageRequest + ): Promise { + return this.requireMediaGateway(extensionId).ocrImage(extensionId, request) + } + + private async mediaTranscribeVoice( + extensionId: string, + request: ExtensionMediaTranscribeVoiceRequest + ): Promise { + return this.requireMediaGateway(extensionId).transcribeVoice(extensionId, request) + } + + private async mediaAnalyzeImage( + extensionId: string, + request: ExtensionMediaAnalyzeImageRequest + ): Promise { + return this.requireMediaGateway(extensionId).analyzeImage(extensionId, request) + } + + private async mediaBatch( + extensionId: string, + request: ExtensionMediaBatchRequest + ): Promise { + return this.requireMediaGateway(extensionId).batch(extensionId, request) + } + + private async renderHtmlToImage( + extensionId: string, + request: ExtensionRenderHtmlToImageRequest + ): Promise { + 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, 'render.html')) { + throw new ExtensionError('PERMISSION_DENIED', '扩展没有 render.html 权限') + } + if (!this.dependencies.renderHtmlToImage) { + throw new ExtensionError('CAPABILITY_UNAVAILABLE', '当前环境未启用 HTML 渲染能力') + } + const dataRoot = this.paths.extensionDataDir(extensionId) + const rendered = await this.dependencies.renderHtmlToImage(extensionId, dataRoot, request) + const previewUrl = + rendered.previewUrl ?? buildExtensionPrivateMediaPreviewUrl(extensionId, dataRoot, rendered.path) + return { + ...rendered, + ...(previewUrl ? { previewUrl } : {}) + } + } + private async queryMessages( extensionId: string, request: ExtensionMessagesQueryRequest - ): Promise { + ): Promise { if (!this.dependencies.isDatabaseReady()) { throw new ExtensionError('DATABASE_NOT_READY') } @@ -1481,11 +1840,30 @@ export class ExtensionManager { } const record = this.registry.get(extensionId) if (!record?.enabled) throw new ExtensionError('EXTENSION_DISABLED') + if (this.isSuspended(extensionId)) { + throw new ExtensionError('EXTENSION_STORAGE_CORRUPTED', '扩展已暂停,查询被拒绝') + } + if (!hasExtensionPermission(record.grantedPermissions, 'messages.query')) { + throw new ExtensionError('PERMISSION_DENIED', '扩展没有 messages.query 权限') + } + if (!this.isConversationAllowed(extensionId, conversationId)) { + throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的访问范围') + } + const order = request?.order === 'asc' || request?.order === 'desc' ? request.order : undefined + const cursor = typeof request?.cursor === 'string' && request.cursor.trim() + ? request.cursor.trim() + : undefined + const types = Array.isArray(request?.types) + ? request.types.map((item) => String(item || '').trim()).filter(Boolean).slice(0, 16) + : undefined return this.dependencies.queryMessages({ conversationId, startTime, endTime, - limit + limit, + ...(cursor ? { cursor } : {}), + ...(order ? { order } : {}), + ...(types?.length ? { types } : {}) }) } @@ -1678,6 +2056,10 @@ export class ExtensionManager { id: page.id, title: page.title })), + ...(manifest?.contributions.navigation + ? { navigation: manifest.contributions.navigation } + : {}), + pinnedToNav: this.navigationStore.isPinned(record.id), automationActions: this.actions.summariesFor(record.id), filesPresent: Boolean(manifest), storage: { diff --git a/src/main/extensions/extension-media-gateway.ts b/src/main/extensions/extension-media-gateway.ts new file mode 100644 index 0000000..a26d3b6 --- /dev/null +++ b/src/main/extensions/extension-media-gateway.ts @@ -0,0 +1,935 @@ +import fs from 'fs-extra' +import path from 'node:path' +import { createHash } from 'node:crypto' +import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors' +import type { ExtensionPermission } from '../../shared/extensions/permissions' +import { + decodeExtensionMessageRef, + decodeMessagesQueryCursor, + encodeMessagesQueryCursor, + type ExtensionMediaAnalyzeImageRequest, + type ExtensionMediaAnalyzeImageResult, + type ExtensionMediaBatchItem, + type ExtensionMediaBatchItemResult, + type ExtensionMediaBatchOperation, + type ExtensionMediaBatchRequest, + type ExtensionMediaBatchResult, + type ExtensionMediaOcrImageRequest, + type ExtensionMediaOcrImageResult, + type ExtensionMediaReadImageRequest, + type ExtensionMediaReadImageResult, + type ExtensionMediaReadVideoRequest, + type ExtensionMediaReadVideoResult, + type ExtensionMediaReadVoiceRequest, + type ExtensionMediaReadVoiceResult, + type ExtensionMediaTranscribeVoiceRequest, + type ExtensionMediaTranscribeVoiceResult, + type ExtensionMessageRef +} from '../../shared/extensions/media' +import type { + ExtensionMessagesQueryRequest, + ExtensionMessagesQueryResult, + ExtensionQueriedMessage +} from '../../shared/extensions/rpc' +import type { VoiceMessageReference } from '../../shared/voice-recognition' +import type { VoiceTranscriptionOutcome } from '../voice-pipeline/voice-transcription-gateway' +import { isPathInside } from './extension-paths' +import { buildExtensionPrivateMediaPreviewUrl } from './extension-protocol' + +const DEFAULT_GLOBAL_CONCURRENCY = 4 +const DEFAULT_PER_EXTENSION_CONCURRENCY = 2 +const DEFAULT_MAX_BATCH_ITEMS = 20 +const DEFAULT_MAX_VIDEO_BYTES = 100 * 1024 * 1024 +const DEFAULT_CACHE_ENTRIES = 128 +const DEFAULT_CACHE_TTL_MS = 10 * 60 * 1000 +const DEFAULT_TRANSCRIBE_WAIT_MS = 12_000 +const MAX_TRANSCRIBE_WAIT_MS = 25_000 + +const DEFAULT_TIMEOUTS_MS: Record = { + readImage: 15_000, + readVoice: 20_000, + readVideo: 30_000, + ocrImage: 25_000, + transcribeVoice: 30_000, + analyzeImage: 60_000 +} + +const OP_REQUIRED_PERMISSION: Record = { + readImage: 'media.read', + readVoice: 'media.read', + readVideo: 'media.read', + ocrImage: 'media.ocr', + transcribeVoice: 'media.transcribe', + analyzeImage: 'ai.vision' +} + +export interface ResolvedExtensionMediaMessage { + messageId: string + localId?: number + serverId?: string + conversationId: string + senderName?: string + type: 'image' | 'voice' | 'video' | 'other' + /** epoch 秒。 */ + createTimeSeconds: number + image?: { md5?: string; datName?: string } + voice?: { durationSeconds?: number } + video?: { + hashes: string[] + byteLength?: number + duration?: number + width?: number + height?: number + } +} + +export interface ExtensionMediaGatewayDependencies { + isDatabaseReady: () => boolean + getAccountId: () => string + getExtensionDataRoot: (extensionId: string) => string + hasPermission: (extensionId: string, permission: ExtensionPermission) => boolean + /** 校验扩展是否允许访问目标会话(manifest.subscriptions.conversationIds 约束)。 */ + isConversationAllowed?: (extensionId: string, conversationId: string) => boolean + /** messageRef 验签;不配置就退化为只解码不校验,伪造与切号前旧引用都会放行。 */ + verifySignedRef?: (rawRef: unknown, expectedAccountId: string) => ExtensionMessageRef | null + resolveMessage: (ref: ExtensionMessageRef) => Promise + readImageData: ( + message: ResolvedExtensionMediaMessage, + quality: 'original' | 'thumbnail' + ) => Promise<{ + buffer: Buffer + mimeType: string + imageHash?: string + quality: 'original' | 'thumbnail' + } | null> + readVoiceData: ( + message: ResolvedExtensionMediaMessage + ) => Promise<{ wavBuffer: Buffer; durationMs?: number } | null> + readVideoAsset: (message: ResolvedExtensionMediaMessage) => Promise<{ + filePath: string + posterPath?: string + durationMs?: number + width?: number + height?: number + } | null> + getCachedOcr?: ( + conversationId: string, + messageId: string + ) => { text: string; language?: string | null; engine?: string } | null + recognizeOcr: ( + imageDataUrl: string, + language?: string + ) => Promise<{ + success: boolean + text: string + language: string | null + engine: string + error?: string + }> + transcribeVoice: ( + reference: VoiceMessageReference, + options: { force?: boolean; waitMs: number } + ) => Promise + analyzeImage: (input: { + messageId: string + conversationId: string + senderName: string + sentAt: number + imageHash: string + imageDataUrl: string + prompt?: string + force?: boolean + }) => Promise<{ + description: string + ocrText?: string + tags?: string[] + category?: string + model?: string + cached?: boolean + }> + maxGlobalConcurrent?: number + maxPerExtensionConcurrent?: number + maxBatchItems?: number + maxVideoBytes?: number + cacheTtlMs?: number + timeoutsMs?: Partial> + now?: () => number +} + +interface CacheEntry { + value: T + at: number +} + +function sha256Hex(buffer: Buffer): string { + return createHash('sha256').update(buffer).digest('hex') +} + +function extensionForImageMime(mimeType: string): string { + const normalized = mimeType.toLowerCase() + if (normalized.includes('png')) return '.png' + if (normalized.includes('webp')) return '.webp' + if (normalized.includes('gif')) return '.gif' + if (normalized.includes('bmp')) return '.bmp' + return '.jpg' +} + +/** 避免底层异常把本机目录或密钥原样回传给扩展。 */ +function sanitizeMediaErrorMessage(message: string): string { + return String(message || '媒体处理失败') + .replace(/[A-Za-z]:\\[^\s'"]+/g, '') + .replace(/\/(?:Users|home|var|tmp|private|Library|Volumes)\/[^\s'"]+/g, '') + .replace(/\b(aesKey|xorKey|apiKey|token|secret)\s*[:=]\s*\S+/gi, '$1=***') + .slice(0, 200) +} + +function withTimeout(promise: Promise, timeoutMs: number): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(new ExtensionError('ACTION_TIMEOUT', '媒体处理超时')) + }, timeoutMs) + promise.then( + (value) => { + clearTimeout(timer) + resolve(value) + }, + (error) => { + clearTimeout(timer) + reject(error) + } + ) + }) +} + +/** + * 扩展媒体与按需解析入口:账号隔离、权限、缓存边界与并发上限一律在主进程校验, + * 底层复用主程序已有的图片解密、语音转写、系统 OCR 与视觉模型。 + */ +export class ExtensionMediaGateway { + private readonly maxGlobal: number + private readonly maxPerExtension: number + private readonly maxBatchItems: number + private readonly maxVideoBytes: number + private readonly cacheTtlMs: number + private readonly timeouts: Record + private readonly now: () => number + + private activeGlobal = 0 + private readonly activeByExtension = new Map() + private readonly inFlight = new Map>() + private readonly ocrCache = new Map>>() + private readonly visionCache = new Map< + string, + CacheEntry> + >() + private lastAccountId = '' + + constructor(private readonly deps: ExtensionMediaGatewayDependencies) { + this.maxGlobal = Math.max(1, deps.maxGlobalConcurrent ?? DEFAULT_GLOBAL_CONCURRENCY) + this.maxPerExtension = Math.max( + 1, + deps.maxPerExtensionConcurrent ?? DEFAULT_PER_EXTENSION_CONCURRENCY + ) + this.maxBatchItems = Math.max(1, deps.maxBatchItems ?? DEFAULT_MAX_BATCH_ITEMS) + this.maxVideoBytes = Math.max(1024, deps.maxVideoBytes ?? DEFAULT_MAX_VIDEO_BYTES) + this.cacheTtlMs = Math.max(1_000, deps.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS) + this.timeouts = { ...DEFAULT_TIMEOUTS_MS, ...(deps.timeoutsMs ?? {}) } + this.now = deps.now ?? (() => Date.now()) + } + + async readImage( + extensionId: string, + request: ExtensionMediaReadImageRequest + ): Promise { + this.assertPermission(extensionId, 'media.read') + const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef) + const quality: 'original' | 'thumbnail' = + request?.quality === 'thumbnail' ? 'thumbnail' : 'original' + + const dedupeKey = `${accountId}:${extensionId}:readImage:${ref.conversationId}:${ref.messageId}:${quality}` + return this.runGuarded(extensionId, 'readImage', dedupeKey, async () => { + const message = await this.requireTypedMessage(ref, 'image') + const data = await this.deps.readImageData(message, quality) + if (!data || data.buffer.length === 0) { + throw new ExtensionError('MEDIA_NOT_FOUND', '找不到该图片消息的本地文件') + } + const sha256 = sha256Hex(data.buffer) + const shortHash = sha256.slice(0, 32) + const ext = extensionForImageMime(data.mimeType) + const written = await this.writeCachedMediaFile( + extensionId, + accountId, + 'images', + `${shortHash}_${data.quality}${ext}`, + data.buffer + ) + const previewUrl = buildExtensionPrivateMediaPreviewUrl( + extensionId, + this.deps.getExtensionDataRoot(extensionId), + written.filePath + ) + return { + messageRef: request.messageRef, + mimeType: data.mimeType, + bytes: data.buffer.length, + sha256, + path: written.filePath, + ...(previewUrl ? { previewUrl } : {}), + quality: data.quality, + cached: written.cached + } + }) + } + + async readVoice( + extensionId: string, + request: ExtensionMediaReadVoiceRequest + ): Promise { + this.assertPermission(extensionId, 'media.read') + const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef) + const dedupeKey = `${accountId}:${extensionId}:readVoice:${ref.conversationId}:${ref.messageId}` + return this.runGuarded(extensionId, 'readVoice', dedupeKey, async () => { + const message = await this.requireTypedMessage(ref, 'voice') + const voice = await this.deps.readVoiceData(message) + if (!voice || voice.wavBuffer.length === 0) { + throw new ExtensionError('MEDIA_NOT_FOUND', '找不到该语音消息的音频数据') + } + const sha256 = sha256Hex(voice.wavBuffer) + const shortHash = sha256.slice(0, 32) + const written = await this.writeCachedMediaFile( + extensionId, + accountId, + 'voices', + `${shortHash}.wav`, + voice.wavBuffer + ) + const previewUrl = buildExtensionPrivateMediaPreviewUrl( + extensionId, + this.deps.getExtensionDataRoot(extensionId), + written.filePath + ) + const durationMs = + voice.durationMs ?? + (message.voice?.durationSeconds ? Math.round(message.voice.durationSeconds * 1000) : undefined) + return { + messageRef: request.messageRef, + mimeType: 'audio/wav', + bytes: voice.wavBuffer.length, + sha256, + ...(durationMs !== undefined ? { durationMs } : {}), + path: written.filePath, + ...(previewUrl ? { previewUrl } : {}), + cached: written.cached + } + }) + } + + async readVideo( + extensionId: string, + request: ExtensionMediaReadVideoRequest + ): Promise { + this.assertPermission(extensionId, 'media.read') + const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef) + const dedupeKey = `${accountId}:${extensionId}:readVideo:${ref.conversationId}:${ref.messageId}` + return this.runGuarded(extensionId, 'readVideo', dedupeKey, async () => { + const message = await this.requireTypedMessage(ref, 'video') + const asset = await this.deps.readVideoAsset(message) + if (!asset?.filePath || !(await fs.pathExists(asset.filePath))) { + throw new ExtensionError('MEDIA_NOT_FOUND', '本地未找到该视频文件') + } + const stat = await fs.stat(asset.filePath) + if (!stat.isFile() || stat.size <= 0) { + throw new ExtensionError('MEDIA_NOT_FOUND', '本地视频文件无效') + } + if (stat.size > this.maxVideoBytes) { + throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '视频体积超出单文件上限') + } + const videoBuffer = await fs.readFile(asset.filePath) + const sha256 = sha256Hex(videoBuffer) + const shortHash = sha256.slice(0, 32) + const written = await this.writeCachedMediaFile( + extensionId, + accountId, + 'videos', + `${shortHash}.mp4`, + videoBuffer + ) + const dataRoot = this.deps.getExtensionDataRoot(extensionId) + const previewUrl = buildExtensionPrivateMediaPreviewUrl(extensionId, dataRoot, written.filePath) + let posterPath: string | undefined + let posterPreviewUrl: string | undefined + if (asset.posterPath && (await fs.pathExists(asset.posterPath))) { + try { + const posterBuffer = await fs.readFile(asset.posterPath) + if (posterBuffer.length > 0 && posterBuffer.length <= 10 * 1024 * 1024) { + const posterWritten = await this.writeCachedMediaFile( + extensionId, + accountId, + 'videos', + `${shortHash}_poster.jpg`, + posterBuffer + ) + posterPath = posterWritten.filePath + posterPreviewUrl = buildExtensionPrivateMediaPreviewUrl( + extensionId, + dataRoot, + posterWritten.filePath + ) + } + } catch { + posterPath = undefined + posterPreviewUrl = undefined + } + } + const durationMs = + asset.durationMs ?? + (message.video?.duration ? Math.round(message.video.duration * 1000) : undefined) + return { + messageRef: request.messageRef, + mimeType: 'video/mp4', + bytes: videoBuffer.length, + sha256, + path: written.filePath, + ...(previewUrl ? { previewUrl } : {}), + ...(posterPath ? { posterPath } : {}), + ...(posterPreviewUrl ? { posterPreviewUrl } : {}), + ...(durationMs !== undefined ? { durationMs } : {}), + ...(asset.width ?? message.video?.width ? { width: asset.width ?? message.video?.width } : {}), + ...(asset.height ?? message.video?.height + ? { height: asset.height ?? message.video?.height } + : {}), + cached: written.cached + } + }) + } + + async ocrImage( + extensionId: string, + request: ExtensionMediaOcrImageRequest + ): Promise { + this.assertPermission(extensionId, 'media.ocr') + const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef) + const language = typeof request?.language === 'string' ? request.language.trim().slice(0, 32) : '' + const force = request?.force === true + const cacheKey = `${accountId}:${ref.conversationId}:${ref.messageId}:${language || 'auto'}` + + if (!force) { + const memHit = this.readCache(this.ocrCache, cacheKey) + if (memHit) { + return { messageRef: request.messageRef, ...memHit, cached: true } + } + } + + const dedupeKey = `${accountId}:ocrImage:${ref.conversationId}:${ref.messageId}:${language || 'auto'}:${force ? '1' : '0'}` + return this.runGuarded(extensionId, 'ocrImage', dedupeKey, async () => { + const message = await this.requireTypedMessage(ref, 'image') + if (!force && !language && this.deps.getCachedOcr) { + const indexed = this.deps.getCachedOcr(message.conversationId, message.messageId) + if (indexed && typeof indexed.text === 'string') { + const payload = { + text: indexed.text, + language: indexed.language ?? null, + engine: indexed.engine || 'system-ocr' + } + this.writeCache(this.ocrCache, cacheKey, payload) + return { + messageRef: request.messageRef, + ...payload, + cached: true + } + } + } + const data = await this.deps.readImageData(message, 'original') + if (!data || data.buffer.length === 0) { + throw new ExtensionError('MEDIA_NOT_FOUND', '找不到该图片消息的本地文件') + } + const dataUrl = `data:${data.mimeType};base64,${data.buffer.toString('base64')}` + const ocr = await this.deps.recognizeOcr(dataUrl, language || undefined) + if (!ocr.success) { + throw new ExtensionError( + 'CAPABILITY_UNAVAILABLE', + sanitizeMediaErrorMessage(ocr.error || '本地图片文字识别失败') + ) + } + const payload = { + text: ocr.text, + language: ocr.language, + engine: ocr.engine + } + this.writeCache(this.ocrCache, cacheKey, payload) + return { + messageRef: request.messageRef, + ...payload, + cached: false + } + }) + } + + async transcribeVoice( + extensionId: string, + request: ExtensionMediaTranscribeVoiceRequest + ): Promise { + this.assertPermission(extensionId, 'media.transcribe') + const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef) + const force = request?.force === true + const waitMs = Math.max( + 0, + Math.min( + Number.isFinite(Number(request?.waitMs)) + ? Math.trunc(Number(request.waitMs)) + : DEFAULT_TRANSCRIBE_WAIT_MS, + MAX_TRANSCRIBE_WAIT_MS + ) + ) + const dedupeKey = `${accountId}:transcribeVoice:${ref.conversationId}:${ref.messageId}:${force ? '1' : '0'}` + return this.runGuarded(extensionId, 'transcribeVoice', dedupeKey, async () => { + const message = await this.requireTypedMessage(ref, 'voice') + const localId = + message.localId ?? (ref.localId && /^\d+$/.test(ref.localId) ? Number(ref.localId) : 0) + const voiceRef: VoiceMessageReference = { + sessionId: message.conversationId, + localId, + createTime: message.createTimeSeconds, + ...(message.serverId ? { svrId: message.serverId } : {}), + ...(message.voice?.durationSeconds + ? { durationSeconds: message.voice.durationSeconds } + : {}) + } + const outcome = await this.deps.transcribeVoice(voiceRef, { force, waitMs }) + if (!outcome) { + throw new ExtensionError('CONCURRENCY_LIMITED', '语音转写队列已满,请稍后再试') + } + if (outcome.state === 'transcribed') { + return { + messageRef: request.messageRef, + state: 'transcribed', + transcript: outcome.transcript, + ...(outcome.durationMs !== undefined ? { durationMs: outcome.durationMs } : {}), + cached: outcome.cached + } + } + if (outcome.state === 'pending') { + return { + messageRef: request.messageRef, + state: 'pending', + cached: false + } + } + return { + messageRef: request.messageRef, + state: 'failed', + cached: false, + error: sanitizeMediaErrorMessage(outcome.error) + } + }) + } + + async analyzeImage( + extensionId: string, + request: ExtensionMediaAnalyzeImageRequest + ): Promise { + this.assertPermission(extensionId, 'ai.vision') + const { ref, accountId } = this.verifyRef(extensionId, request?.messageRef) + const prompt = typeof request?.prompt === 'string' ? request.prompt.trim().slice(0, 1000) : '' + const force = request?.force === true + const promptHash = prompt ? createHash('sha256').update(prompt).digest('hex').slice(0, 16) : 'default' + const cacheKey = `${accountId}:${ref.conversationId}:${ref.messageId}:${promptHash}` + + if (!force) { + const memHit = this.readCache(this.visionCache, cacheKey) + if (memHit) { + return { messageRef: request.messageRef, ...memHit, cached: true } + } + } + + const dedupeKey = `${accountId}:analyzeImage:${ref.conversationId}:${ref.messageId}:${promptHash}:${force ? '1' : '0'}` + return this.runGuarded(extensionId, 'analyzeImage', dedupeKey, async () => { + const message = await this.requireTypedMessage(ref, 'image') + const data = await this.deps.readImageData(message, 'original') + if (!data || data.buffer.length === 0) { + throw new ExtensionError('MEDIA_NOT_FOUND', '找不到该图片消息的本地文件') + } + const imageHash = data.imageHash || `sha256:${sha256Hex(data.buffer).slice(0, 32)}` + const imageDataUrl = `data:${data.mimeType};base64,${data.buffer.toString('base64')}` + const analyzed = await this.deps.analyzeImage({ + messageId: message.messageId, + conversationId: message.conversationId, + senderName: message.senderName || '联系人', + sentAt: Math.round(message.createTimeSeconds * 1000), + imageHash, + imageDataUrl, + ...(prompt ? { prompt } : {}), + force + }) + const payload = { + description: analyzed.description, + ...(analyzed.ocrText ? { ocrText: analyzed.ocrText } : {}), + ...(analyzed.tags?.length ? { tags: analyzed.tags } : {}), + ...(analyzed.category ? { category: analyzed.category } : {}), + ...(analyzed.model ? { model: analyzed.model } : {}) + } + this.writeCache(this.visionCache, cacheKey, payload) + return { + messageRef: request.messageRef, + ...payload, + cached: analyzed.cached === true + } + }) + } + + async batch( + extensionId: string, + request: ExtensionMediaBatchRequest + ): Promise { + const items = Array.isArray(request?.items) ? request.items : null + if (!items || items.length === 0) { + throw new ExtensionError('INVALID_REQUEST', 'batch.items 不能为空') + } + if (items.length > this.maxBatchItems) { + throw new ExtensionError( + 'INVALID_REQUEST', + `单次批量处理最多支持 ${this.maxBatchItems} 项` + ) + } + const requestedConcurrency = Number(request?.concurrency) + const workerLimit = Math.max( + 1, + Math.min( + Number.isFinite(requestedConcurrency) ? Math.trunc(requestedConcurrency) : 2, + this.maxPerExtension, + 4 + ) + ) + + const results: ExtensionMediaBatchItemResult[] = new Array(items.length) + let cursor = 0 + + const worker = async (): Promise => { + while (cursor < items.length) { + const index = cursor + cursor += 1 + const item = items[index] + results[index] = await this.executeBatchItem(extensionId, index, item) + } + } + + await Promise.all( + Array.from({ length: Math.min(workerLimit, items.length) }, () => worker()) + ) + return { results } + } + + private async executeBatchItem( + extensionId: string, + index: number, + item: ExtensionMediaBatchItem + ): Promise { + const op = item?.op + const messageRef = typeof item?.messageRef === 'string' ? item.messageRef : '' + const options = + item?.options && typeof item.options === 'object' && !Array.isArray(item.options) + ? item.options + : {} + + if (!op || !(op in OP_REQUIRED_PERMISSION)) { + return { + index, + op: (op || 'readImage') as ExtensionMediaBatchOperation, + messageRef, + ok: false, + error: { code: 'INVALID_REQUEST', message: '不支持的批量媒体操作类型' } + } + } + + try { + let result: ExtensionMediaBatchItemResult['result'] + switch (op) { + case 'readImage': + result = await this.readImage(extensionId, { + messageRef, + quality: options.quality === 'thumbnail' ? 'thumbnail' : 'original' + }) + break + case 'readVoice': + result = await this.readVoice(extensionId, { messageRef }) + break + case 'readVideo': + result = await this.readVideo(extensionId, { messageRef }) + break + case 'ocrImage': + result = await this.ocrImage(extensionId, { + messageRef, + ...(typeof options.language === 'string' ? { language: options.language } : {}), + force: options.force === true + }) + break + case 'transcribeVoice': + result = await this.transcribeVoice(extensionId, { + messageRef, + force: options.force === true, + ...(typeof options.waitMs === 'number' ? { waitMs: options.waitMs } : {}) + }) + break + case 'analyzeImage': + result = await this.analyzeImage(extensionId, { + messageRef, + ...(typeof options.prompt === 'string' ? { prompt: options.prompt } : {}), + force: options.force === true + }) + break + } + return { index, op, messageRef, ok: true, result } + } catch (error) { + return { + index, + op, + messageRef, + ok: false, + error: toExtensionErrorPayload(error) + } + } + } + + private assertPermission(extensionId: string, permission: ExtensionPermission): void { + if (!this.deps.hasPermission(extensionId, permission)) { + throw new ExtensionError('PERMISSION_DENIED', `扩展没有 ${permission} 权限`) + } + } + + private verifyRef( + extensionId: string, + rawRef: unknown + ): { ref: ExtensionMessageRef; accountId: string } { + if (!this.deps.isDatabaseReady()) { + throw new ExtensionError('DATABASE_NOT_READY', '微信数据库尚未连接') + } + const accountId = String(this.deps.getAccountId() || '').trim() + if (!accountId) { + throw new ExtensionError('DATABASE_NOT_READY', '当前未连接到有效微信账号') + } + if (this.lastAccountId && this.lastAccountId !== accountId) { + this.ocrCache.clear() + this.visionCache.clear() + } + this.lastAccountId = accountId + + const ref = this.deps.verifySignedRef + ? this.deps.verifySignedRef(rawRef, accountId) + : decodeExtensionMessageRef(rawRef) + if (!ref) { + // 保留跨账号明确错误码:若结构有效但账号不匹配,返回 ACCOUNT_MISMATCH。 + const parsed = decodeExtensionMessageRef(rawRef) + if (parsed && parsed.accountId && parsed.accountId !== accountId) { + throw new ExtensionError('ACCOUNT_MISMATCH', '消息引用不属于当前已连接账号') + } + throw new ExtensionError('INVALID_REQUEST', 'messageRef 无效、未签名或已失效') + } + if (!ref.accountId || ref.accountId !== accountId) { + throw new ExtensionError('ACCOUNT_MISMATCH', '消息引用不属于当前已连接账号') + } + if (this.deps.isConversationAllowed && !this.deps.isConversationAllowed(extensionId, ref.conversationId)) { + throw new ExtensionError('PERMISSION_DENIED', '消息所属会话超出扩展声明的访问范围') + } + return { ref, accountId } + } + + private async requireTypedMessage( + ref: ExtensionMessageRef, + expectedType: 'image' | 'voice' | 'video' + ): Promise { + const resolved = await this.deps.resolveMessage(ref) + if (!resolved) { + throw new ExtensionError('MEDIA_NOT_FOUND', '找不到对应的消息记录') + } + if (resolved.conversationId !== ref.conversationId) { + throw new ExtensionError('ACCOUNT_MISMATCH', '消息所属会话与引用不一致') + } + if (resolved.type !== expectedType) { + throw new ExtensionError('MEDIA_UNSUPPORTED', `该消息类型为 ${resolved.type},不支持此操作`) + } + return resolved + } + + private async runGuarded( + extensionId: string, + op: ExtensionMediaBatchOperation, + dedupeKey: string, + task: () => Promise + ): Promise { + const existing = this.inFlight.get(dedupeKey) + if (existing) return (await existing) as T + + const extCount = this.activeByExtension.get(extensionId) ?? 0 + if (this.activeGlobal >= this.maxGlobal || extCount >= this.maxPerExtension) { + throw new ExtensionError('CONCURRENCY_LIMITED', '媒体处理并发已达上限,请稍后再试') + } + + this.activeGlobal += 1 + this.activeByExtension.set(extensionId, extCount + 1) + + const timeoutMs = this.timeouts[op] + const promise = withTimeout(task(), timeoutMs) + .catch((error) => { + if (error instanceof ExtensionError) throw error + throw new ExtensionError( + 'ACTION_FAILED', + sanitizeMediaErrorMessage(error instanceof Error ? error.message : String(error)) + ) + }) + .finally(() => { + this.inFlight.delete(dedupeKey) + this.activeGlobal = Math.max(0, this.activeGlobal - 1) + const current = this.activeByExtension.get(extensionId) ?? 1 + if (current <= 1) this.activeByExtension.delete(extensionId) + else this.activeByExtension.set(extensionId, current - 1) + }) + + this.inFlight.set(dedupeKey, promise) + return promise + } + + /** 始终落盘到扩展私有数据目录且按账号哈希分桶,禁止跨扩展与跨账号共享缓存路径。 */ + private async writeCachedMediaFile( + extensionId: string, + accountId: string, + bucket: 'images' | 'voices' | 'videos', + fileName: string, + data: Buffer + ): Promise<{ filePath: string; cached: boolean }> { + const dataRoot = path.resolve(this.deps.getExtensionDataRoot(extensionId)) + const accountScope = createHash('sha256').update(accountId).digest('hex').slice(0, 16) + const cacheDir = path.join(dataRoot, 'media-cache', accountScope, bucket) + const filePath = path.join(cacheDir, fileName) + if (!isPathInside(dataRoot, filePath)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', '媒体缓存路径越界') + } + await fs.ensureDir(cacheDir) + const realRoot = await fs.realpath(dataRoot) + const realDir = await fs.realpath(cacheDir) + if (!isPathInside(realRoot, realDir)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', '媒体缓存目录存在非法符号链接') + } + if (await fs.pathExists(filePath)) { + const stat = await fs.lstat(filePath) + if (!stat.isSymbolicLink() && stat.isFile() && stat.size === data.length) { + return { filePath, cached: true } + } + } + const tempPath = `${filePath}.${Date.now().toString(36)}.tmp` + await fs.writeFile(tempPath, data) + await fs.move(tempPath, filePath, { overwrite: true }) + return { filePath, cached: false } + } + + private readCache(map: Map>, key: string): T | null { + const entry = map.get(key) + if (!entry) return null + if (this.now() - entry.at > this.cacheTtlMs) { + map.delete(key) + return null + } + return entry.value + } + + private writeCache(map: Map>, key: string, value: T): void { + map.set(key, { value, at: this.now() }) + if (map.size > DEFAULT_CACHE_ENTRIES) { + const oldest = map.keys().next().value + if (oldest) map.delete(oldest) + } + } +} + +function compareCodePoint(left: string, right: string): number { + if (left === right) return 0 + return left < right ? -1 : 1 +} + +/** 确定性游标分页:按 (timestamp, messageId) 排序,同时间戳多条消息不漏不重。 */ +export function paginateQueriedMessages( + allMessages: ExtensionQueriedMessage[], + request: ExtensionMessagesQueryRequest +): ExtensionMessagesQueryResult { + const limit = Math.max(1, Math.min(Number(request.limit) || 50, 500)) + const cursor = request.cursor ? decodeMessagesQueryCursor(request.cursor) : null + if (request.cursor && !cursor) { + throw new ExtensionError('INVALID_REQUEST', '分页游标无效') + } + if (cursor && request.order && cursor.order !== request.order) { + throw new ExtensionError('INVALID_REQUEST', '分页游标与排序方向不一致') + } + if (cursor && request.order === undefined && cursor.order !== 'desc') { + throw new ExtensionError('INVALID_REQUEST', '默认分页模式仅接受向更早历史续页的游标') + } + + const allowedTypes = + Array.isArray(request.types) && request.types.length > 0 + ? new Set(request.types.map((item) => String(item).trim()).filter(Boolean)) + : null + + const filtered = allMessages.filter((item) => { + if (allowedTypes && !allowedTypes.has(item.type)) return false + if (request.startTime !== undefined && item.timestamp < request.startTime) return false + if (request.endTime !== undefined && item.timestamp > request.endTime) return false + return true + }) + + const ascSorted = [...filtered].sort((left, right) => { + const timeDelta = left.timestamp - right.timestamp + return timeDelta !== 0 ? timeDelta : compareCodePoint(left.messageId, right.messageId) + }) + + // 未显式指定 order 时保持 v1 默认语义(返回最新一页并按时间升序排列),同时支持向更早历史续页。 + if (request.order === undefined) { + const olderPool = cursor + ? ascSorted.filter((item) => { + const timeDelta = item.timestamp - cursor.timestamp + const cmp = timeDelta !== 0 ? timeDelta : compareCodePoint(item.messageId, cursor.messageId) + return cmp < 0 + }) + : ascSorted + const hasMore = olderPool.length > limit + const page = olderPool.slice(-limit) + const oldest = page[0] + return { + messages: page, + ...(hasMore && oldest + ? { + nextCursor: encodeMessagesQueryCursor({ + order: 'desc', + timestamp: oldest.timestamp, + messageId: oldest.messageId + }) + } + : {}), + hasMore + } + } + + const order: 'asc' | 'desc' = request.order === 'desc' ? 'desc' : 'asc' + const sorted = order === 'desc' ? [...ascSorted].reverse() : ascSorted + const afterCursor = cursor + ? sorted.filter((item) => { + const timeDelta = item.timestamp - cursor.timestamp + const cmp = timeDelta !== 0 ? timeDelta : compareCodePoint(item.messageId, cursor.messageId) + return order === 'desc' ? cmp < 0 : cmp > 0 + }) + : sorted + + const hasMore = afterCursor.length > limit + const page = afterCursor.slice(0, limit) + const last = page[page.length - 1] + return { + messages: page, + ...(hasMore && last + ? { + nextCursor: encodeMessagesQueryCursor({ + order, + timestamp: last.timestamp, + messageId: last.messageId + }) + } + : {}), + hasMore + } +} diff --git a/src/main/extensions/extension-message-ref-signer.ts b/src/main/extensions/extension-message-ref-signer.ts new file mode 100644 index 0000000..dee6cfb --- /dev/null +++ b/src/main/extensions/extension-message-ref-signer.ts @@ -0,0 +1,73 @@ +import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto' +import { + decodeExtensionMessageRef, + encodeExtensionMessageRef, + type ExtensionMessageRef +} from '../../shared/extensions/media' + +const SIGNATURE_BYTES = 16 + +/** + * messageRef 用运行期密钥 + 账号世代签名,防止扩展伪造引用; + * 世代随账号切换递增,切号前签发的旧引用必须全部失效。 + */ +export class ExtensionMessageRefSigner { + private readonly secret: Buffer + private generation = 1 + private currentAccountId = '' + + constructor(secret?: Buffer) { + this.secret = secret && secret.length >= 16 ? secret : randomBytes(32) + } + + /** 账号变化时递增世代,让切号前签发的所有 messageRef 失效。 */ + syncAccount(accountId: string): void { + const normalized = String(accountId || '').trim() + if (!normalized) return + if (this.currentAccountId && this.currentAccountId !== normalized) { + this.generation += 1 + } + this.currentAccountId = normalized + } + + sign(ref: ExtensionMessageRef): string { + this.syncAccount(ref.accountId) + const unsigned = encodeExtensionMessageRef(ref) + const mac = this.computeMac(unsigned, this.generation) + return `${unsigned}.${mac}` + } + + verify(rawRef: unknown, expectedAccountId: string): ExtensionMessageRef | null { + if (typeof rawRef !== 'string') return null + const trimmed = rawRef.trim() + const dotIndex = trimmed.lastIndexOf('.') + if (dotIndex <= 0 || dotIndex === trimmed.length - 1) return null + + const unsigned = trimmed.slice(0, dotIndex) + const providedSig = trimmed.slice(dotIndex + 1) + if (!/^[A-Za-z0-9_-]{16,64}$/.test(providedSig)) return null + + const normalizedAccount = String(expectedAccountId || '').trim() + if (!normalizedAccount) return null + this.syncAccount(normalizedAccount) + + const expectedSig = this.computeMac(unsigned, this.generation) + const providedBuf = Buffer.from(providedSig, 'utf8') + const expectedBuf = Buffer.from(expectedSig, 'utf8') + if (providedBuf.length !== expectedBuf.length || !timingSafeEqual(providedBuf, expectedBuf)) { + return null + } + + const decoded = decodeExtensionMessageRef(unsigned) + if (!decoded || decoded.accountId !== normalizedAccount) return null + return decoded + } + + private computeMac(unsigned: string, generation: number): string { + return createHmac('sha256', this.secret) + .update(`${generation}:${unsigned}`) + .digest() + .subarray(0, SIGNATURE_BYTES) + .toString('base64url') + } +} diff --git a/src/main/extensions/extension-navigation-store.ts b/src/main/extensions/extension-navigation-store.ts new file mode 100644 index 0000000..ae8d04c --- /dev/null +++ b/src/main/extensions/extension-navigation-store.ts @@ -0,0 +1,144 @@ +import fs from 'fs-extra' +import path from 'node:path' +import { isValidExtensionId } from '../../shared/extensions/manifest' + +export interface PinnedNavigationRecord { + extensionId: string + pageId?: string + order: number + pinnedAt: number +} + +interface PinnedNavigationFile { + version: number + items: PinnedNavigationRecord[] +} + +const STORE_VERSION = 1 +const MAX_PINNED_ITEMS = 12 + +/** 宿主管理的一级导航固定项存储;独立于扩展自身配置,重启可恢复、卸载自动清理。 */ +export class ExtensionNavigationStore { + private items: PinnedNavigationRecord[] = [] + + constructor( + private readonly filePath: string, + private readonly now: () => number = () => Date.now() + ) { + this.items = this.load() + } + + list(): PinnedNavigationRecord[] { + return [...this.items].sort((left, right) => { + if (left.order !== right.order) return left.order - right.order + return left.pinnedAt - right.pinnedAt + }) + } + + isPinned(extensionId: string): boolean { + return this.items.some((item) => item.extensionId === extensionId) + } + + pin(extensionId: string, pageId?: string): PinnedNavigationRecord[] { + const existing = this.items.find((item) => item.extensionId === extensionId) + if (existing) { + if (pageId !== undefined) existing.pageId = pageId || undefined + this.save() + return this.list() + } + if (this.items.length >= MAX_PINNED_ITEMS) { + throw new Error(`最多固定 ${MAX_PINNED_ITEMS} 个扩展到一级导航`) + } + const maxOrder = this.items.reduce((acc, item) => Math.max(acc, item.order), -1) + this.items.push({ + extensionId, + ...(pageId ? { pageId } : {}), + order: maxOrder + 1, + pinnedAt: this.now() + }) + this.save() + return this.list() + } + + unpin(extensionId: string): PinnedNavigationRecord[] { + const before = this.items.length + this.items = this.items.filter((item) => item.extensionId !== extensionId) + if (this.items.length !== before) { + this.reindex() + this.save() + } + return this.list() + } + + remove(extensionId: string): boolean { + const before = this.items.length + this.items = this.items.filter((item) => item.extensionId !== extensionId) + if (this.items.length === before) return false + this.reindex() + this.save() + return true + } + + reorder(extensionIds: string[]): PinnedNavigationRecord[] { + const byId = new Map(this.items.map((item) => [item.extensionId, item])) + const ordered: PinnedNavigationRecord[] = [] + for (const id of extensionIds) { + const found = byId.get(id) + if (!found) continue + ordered.push(found) + byId.delete(id) + } + for (const remaining of byId.values()) { + ordered.push(remaining) + } + this.items = ordered.map((item, index) => ({ ...item, order: index })) + this.save() + return this.list() + } + + private reindex(): void { + this.items = this.list().map((item, index) => ({ ...item, order: index })) + } + + private load(): PinnedNavigationRecord[] { + if (!fs.existsSync(this.filePath)) return [] + try { + const parsed = fs.readJsonSync(this.filePath) as Partial + if (!parsed || Number(parsed.version) !== STORE_VERSION || !Array.isArray(parsed.items)) { + return [] + } + const result: PinnedNavigationRecord[] = [] + const seen = new Set() + for (const item of parsed.items) { + if (!item || typeof item !== 'object') continue + const extensionId = String(item.extensionId || '').trim() + if (!isValidExtensionId(extensionId) || seen.has(extensionId)) continue + seen.add(extensionId) + const pageId = + typeof item.pageId === 'string' && item.pageId.trim() + ? item.pageId.trim().slice(0, 32) + : undefined + const order = Number.isFinite(Number(item.order)) ? Math.round(Number(item.order)) : result.length + const pinnedAt = + Number.isFinite(Number(item.pinnedAt)) && Number(item.pinnedAt) > 0 + ? Math.round(Number(item.pinnedAt)) + : this.now() + result.push({ extensionId, ...(pageId ? { pageId } : {}), order, pinnedAt }) + } + return result.sort((left, right) => left.order - right.order).slice(0, MAX_PINNED_ITEMS) + } catch { + return [] + } + } + + private save(): void { + fs.ensureDirSync(path.dirname(this.filePath)) + const temp = `${this.filePath}.${process.pid}.${Date.now().toString(36)}.tmp` + const payload: PinnedNavigationFile = { + version: STORE_VERSION, + items: this.list() + } + fs.writeJsonSync(temp, payload, { spaces: 2 }) + fs.moveSync(temp, this.filePath, { overwrite: true }) + } +} diff --git a/src/main/extensions/extension-notification-store.ts b/src/main/extensions/extension-notification-store.ts new file mode 100644 index 0000000..e15139f --- /dev/null +++ b/src/main/extensions/extension-notification-store.ts @@ -0,0 +1,268 @@ +import fs from 'fs-extra' +import path from 'node:path' +import { randomUUID } from 'node:crypto' +import { ExtensionError } from '../../shared/extensions/errors' +import { isValidExtensionId } from '../../shared/extensions/manifest' +import type { + ExtensionNotificationCreateRequest, + ExtensionNotificationCreateResult, + ExtensionNotificationLevel +} from '../../shared/extensions/rpc' +import type { + ExtensionNotificationItem, + ExtensionNotificationSummary +} from '../../shared/extensions/types' + +interface NotificationFile { + version: number + items: ExtensionNotificationItem[] +} + +const STORE_VERSION = 1 +const MAX_TOTAL_NOTIFICATIONS = 200 +const MAX_PER_EXTENSION_NOTIFICATIONS = 50 +const RATE_WINDOW_MS = 60_000 +const DEFAULT_MAX_NEW_PER_WINDOW = 20 +const DEFAULT_MAX_UPDATES_PER_WINDOW = 60 +const VALID_LEVELS: readonly ExtensionNotificationLevel[] = ['info', 'success', 'warning', 'error'] + +export interface ExtensionNotificationStoreOptions { + maxNewPerWindow?: number + maxUpdatesPerWindow?: number + rateWindowMs?: number +} + +function normalizeLevel(value: unknown): ExtensionNotificationLevel { + return typeof value === 'string' && (VALID_LEVELS as readonly string[]).includes(value) + ? (value as ExtensionNotificationLevel) + : 'info' +} + +/** 宿主管理的扩展通知中心持久化存储;支持扩展内去重、限频防刷屏、分级、未读统计与卸载清理。 */ +export class ExtensionNotificationStore { + private items: ExtensionNotificationItem[] = [] + private readonly maxNewPerWindow: number + private readonly maxUpdatesPerWindow: number + private readonly rateWindowMs: number + private readonly newHistory = new Map() + private readonly updateHistory = new Map() + + constructor( + private readonly filePath: string, + private readonly now: () => number = () => Date.now(), + options: ExtensionNotificationStoreOptions = {} + ) { + this.maxNewPerWindow = Math.max(1, options.maxNewPerWindow ?? DEFAULT_MAX_NEW_PER_WINDOW) + this.maxUpdatesPerWindow = Math.max(1, options.maxUpdatesPerWindow ?? DEFAULT_MAX_UPDATES_PER_WINDOW) + this.rateWindowMs = Math.max(1_000, options.rateWindowMs ?? RATE_WINDOW_MS) + this.items = this.load() + } + + create( + extensionId: string, + extensionName: string, + request: ExtensionNotificationCreateRequest + ): ExtensionNotificationCreateResult { + const title = String(request?.title || '') + .trim() + .slice(0, 80) + if (!title) { + throw new ExtensionError('INVALID_REQUEST', '通知标题不能为空') + } + const body = + typeof request?.body === 'string' && request.body.trim() + ? request.body.trim().slice(0, 300) + : undefined + const level = normalizeLevel(request?.level) + const dedupeKey = + typeof request?.dedupeKey === 'string' && request.dedupeKey.trim() + ? request.dedupeKey.trim().slice(0, 128) + : undefined + const pageId = + typeof request?.pageId === 'string' && request.pageId.trim() + ? request.pageId.trim().slice(0, 32) + : undefined + const at = this.now() + + if (dedupeKey) { + const existing = this.items.find( + (item) => item.extensionId === extensionId && item.dedupeKey === dedupeKey + ) + if (existing) { + this.assertRateLimit(this.updateHistory, extensionId, this.maxUpdatesPerWindow, at) + existing.extensionName = extensionName + existing.title = title + existing.body = body + existing.level = level + existing.pageId = pageId + existing.updatedAt = at + this.save() + return { id: existing.id, deduped: true, createdAt: existing.createdAt } + } + } + + this.assertRateLimit(this.newHistory, extensionId, this.maxNewPerWindow, at) + const record: ExtensionNotificationItem = { + id: `ext-ntf-${randomUUID()}`, + extensionId, + extensionName, + title, + ...(body ? { body } : {}), + level, + ...(dedupeKey ? { dedupeKey } : {}), + ...(pageId ? { pageId } : {}), + read: false, + createdAt: at, + updatedAt: at + } + this.items.unshift(record) + this.prune(extensionId) + this.save() + return { id: record.id, deduped: false, createdAt: record.createdAt } + } + + list(extensionId?: string): ExtensionNotificationItem[] { + const filtered = extensionId + ? this.items.filter((item) => item.extensionId === extensionId) + : this.items + return [...filtered] + .sort((left, right) => right.updatedAt - left.updatedAt) + .map((item) => ({ ...item })) + } + + summary(pinnedExtensionIds: ReadonlySet): ExtensionNotificationSummary { + let totalUnread = 0 + let unpinnedUnread = 0 + const unreadByExtension: Record = {} + for (const item of this.items) { + if (item.read) continue + totalUnread += 1 + unreadByExtension[item.extensionId] = (unreadByExtension[item.extensionId] ?? 0) + 1 + if (!pinnedExtensionIds.has(item.extensionId)) { + unpinnedUnread += 1 + } + } + return { totalUnread, unpinnedUnread, unreadByExtension } + } + + markRead(options: { id?: string; extensionId?: string; all?: boolean }): number { + let changed = 0 + for (const item of this.items) { + if (item.read) continue + if (options.extensionId && item.extensionId !== options.extensionId) { + continue + } + if (options.all) { + item.read = true + changed += 1 + } else if (options.id && item.id === options.id) { + item.read = true + changed += 1 + } else if (!options.id && options.extensionId && item.extensionId === options.extensionId) { + item.read = true + changed += 1 + } + } + if (changed > 0) this.save() + return changed + } + + private assertRateLimit( + bucket: Map, + extensionId: string, + limit: number, + at: number + ): void { + const recent = (bucket.get(extensionId) ?? []).filter((ts) => at - ts < this.rateWindowMs) + if (recent.length >= limit) { + bucket.set(extensionId, recent) + throw new ExtensionError('CONCURRENCY_LIMITED', '通知写入过于频繁,请稍后再试') + } + recent.push(at) + bucket.set(extensionId, recent) + } + + clear(extensionId?: string): number { + const before = this.items.length + this.items = extensionId + ? this.items.filter((item) => item.extensionId !== extensionId) + : [] + const removed = before - this.items.length + if (removed > 0) this.save() + return removed + } + + removeByExtension(extensionId: string): number { + return this.clear(extensionId) + } + + private prune(extensionId: string): void { + const perExt = this.items.filter((item) => item.extensionId === extensionId) + if (perExt.length > MAX_PER_EXTENSION_NOTIFICATIONS) { + const keepIds = new Set( + perExt + .sort((a, b) => b.updatedAt - a.updatedAt) + .slice(0, MAX_PER_EXTENSION_NOTIFICATIONS) + .map((item) => item.id) + ) + this.items = this.items.filter( + (item) => item.extensionId !== extensionId || keepIds.has(item.id) + ) + } + if (this.items.length > MAX_TOTAL_NOTIFICATIONS) { + this.items.sort((a, b) => b.updatedAt - a.updatedAt) + this.items = this.items.slice(0, MAX_TOTAL_NOTIFICATIONS) + } + } + + private load(): ExtensionNotificationItem[] { + if (!fs.existsSync(this.filePath)) return [] + try { + const parsed = fs.readJsonSync(this.filePath) as Partial + if (!parsed || Number(parsed.version) !== STORE_VERSION || !Array.isArray(parsed.items)) { + return [] + } + const result: ExtensionNotificationItem[] = [] + const seen = new Set() + for (const raw of parsed.items) { + if (!raw || typeof raw !== 'object') continue + const id = String(raw.id || '').trim() + const extensionId = String(raw.extensionId || '').trim() + const title = String(raw.title || '').trim().slice(0, 80) + if (!id || seen.has(id) || !isValidExtensionId(extensionId) || !title) continue + seen.add(id) + const createdAt = Number.isFinite(Number(raw.createdAt)) ? Number(raw.createdAt) : this.now() + const updatedAt = Number.isFinite(Number(raw.updatedAt)) ? Number(raw.updatedAt) : createdAt + result.push({ + id, + extensionId, + extensionName: String(raw.extensionName || extensionId).slice(0, 64), + title, + ...(typeof raw.body === 'string' && raw.body.trim() + ? { body: raw.body.trim().slice(0, 300) } + : {}), + level: normalizeLevel(raw.level), + ...(typeof raw.dedupeKey === 'string' && raw.dedupeKey.trim() + ? { dedupeKey: raw.dedupeKey.trim().slice(0, 128) } + : {}), + ...(typeof raw.pageId === 'string' && raw.pageId.trim() + ? { pageId: raw.pageId.trim().slice(0, 32) } + : {}), + read: raw.read === true, + createdAt, + updatedAt + }) + } + return result.sort((a, b) => b.updatedAt - a.updatedAt).slice(0, MAX_TOTAL_NOTIFICATIONS) + } catch { + return [] + } + } + + private save(): void { + fs.ensureDirSync(path.dirname(this.filePath)) + const temp = `${this.filePath}.${process.pid}.${Date.now().toString(36)}.tmp` + fs.writeJsonSync(temp, { version: STORE_VERSION, items: this.items }, { spaces: 2 }) + fs.moveSync(temp, this.filePath, { overwrite: true }) + } +} diff --git a/src/main/extensions/extension-paths.ts b/src/main/extensions/extension-paths.ts index a84e147..f4fe579 100644 --- a/src/main/extensions/extension-paths.ts +++ b/src/main/extensions/extension-paths.ts @@ -22,6 +22,8 @@ export interface ExtensionPaths { stateDir: string stagingDir: string registryFile: string + pinnedNavigationFile: string + notificationsFile: string logsDir: string installDir: (extensionId: string) => string extensionDataDir: (extensionId: string) => string @@ -42,6 +44,8 @@ export function createExtensionPaths(userData: string): ExtensionPaths { stateDir, stagingDir, registryFile: path.join(stateDir, 'registry.json'), + pinnedNavigationFile: path.join(stateDir, 'pinned-navigation.json'), + notificationsFile: path.join(stateDir, 'notifications.json'), logsDir, installDir: (extensionId) => path.join(extensionsDir, extensionId), extensionDataDir: (extensionId) => path.join(dataDir, extensionId), diff --git a/src/main/extensions/extension-protocol.ts b/src/main/extensions/extension-protocol.ts index 21b743e..e0eaa6f 100644 --- a/src/main/extensions/extension-protocol.ts +++ b/src/main/extensions/extension-protocol.ts @@ -5,6 +5,9 @@ import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest' import { isPathInside, type ExtensionPaths } from './extension-paths' export const EXTENSION_SCHEME = 'tm-extension' +export const EXTENSION_PRIVATE_DATA_PREFIX = '_data/' + +const ALLOWED_PRIVATE_DATA_DIRS = ['rendered/', 'media-cache/'] as const const MIME_TYPES: Record = { '.html': 'text/html; charset=utf-8', @@ -25,6 +28,135 @@ const MIME_TYPES: Record = { '.wasm': 'application/wasm' } +/** 扩展私有预览只放行静态媒体文件,禁止读取脚本、HTML 或 storage.json。 */ +const PRIVATE_MEDIA_MIME_TYPES: Record = { + '.png': 'image/png', + '.jpg': 'image/jpeg', + '.jpeg': 'image/jpeg', + '.gif': 'image/gif', + '.webp': 'image/webp', + '.bmp': 'image/bmp', + '.wav': 'audio/wav', + '.mp3': 'audio/mpeg', + '.m4a': 'audio/mp4', + '.mp4': 'video/mp4' +} + +const MAX_CODE_FILE_BYTES = 20 * 1024 * 1024 +const MAX_PRIVATE_IMAGE_AUDIO_BYTES = 25 * 1024 * 1024 +const MAX_PRIVATE_VIDEO_BYTES = 100 * 1024 * 1024 + +const PAGE_CSP = [ + "default-src 'self'", + "script-src 'self'", + "style-src 'self' 'unsafe-inline'", + "img-src 'self' data: https:", + "media-src 'self' data: https:", + "font-src 'self' data:", + "connect-src 'none'", + "object-src 'none'", + "base-uri 'none'", + "form-action 'none'" +].join('; ') + +const PRIVATE_MEDIA_CSP = "default-src 'none'; sandbox" + +/** 为位于扩展私有目录 rendered/ 或 media-cache/ 下的媒体文件构造受控预览 URL。 */ +export function buildExtensionPrivateMediaPreviewUrl( + extensionId: string, + extensionDataRoot: string, + filePath: string +): string | undefined { + const id = String(extensionId || '').trim().toLowerCase() + if (!/^[a-z0-9.-]{3,128}$/.test(id)) return undefined + const root = path.resolve(extensionDataRoot) + const target = path.resolve(filePath) + if (!isPathInside(root, target)) return undefined + const relative = path.relative(root, target).replace(/\\/g, '/') + if (!isSafeRelativeEntryPath(relative)) return undefined + if (!ALLOWED_PRIVATE_DATA_DIRS.some((prefix) => relative.startsWith(prefix))) return undefined + const ext = path.extname(relative).toLowerCase() + if (!(ext in PRIVATE_MEDIA_MIME_TYPES)) return undefined + const encodedPath = relative + .split('/') + .map((segment) => encodeURIComponent(segment)) + .join('/') + return `${EXTENSION_SCHEME}://${id}/${EXTENSION_PRIVATE_DATA_PREFIX}${encodedPath}` +} + +export interface ResolvedExtensionProtocolFile { + realFile: string + contentType: string + csp: string + size: number + isPrivateMedia: boolean +} + +/** 扩展协议统一解析器:支持扩展代码文件与受控的 `_data/{rendered,media-cache}/` 媒体只读预览。 */ +export async function resolveExtensionProtocolFile( + requestUrl: string, + dependencies: ExtensionProtocolDependencies +): Promise { + const url = new URL(requestUrl) + if (url.protocol !== `${EXTENSION_SCHEME}:`) return null + const extensionId = url.hostname.toLowerCase() + if (!/^[a-z0-9.-]{3,128}$/.test(extensionId)) return null + const relative = decodeURIComponent(url.pathname).replace(/^\/+/, '') + if (!isSafeRelativeEntryPath(relative)) return null + + const isPrivateMedia = relative.startsWith(EXTENSION_PRIVATE_DATA_PREFIX) + if (isPrivateMedia) { + // 只有已安装的扩展允许解析私有预览文件。 + if (!dependencies.resolveRoot(extensionId)) return null + const subPath = relative.slice(EXTENSION_PRIVATE_DATA_PREFIX.length) + if (!isSafeRelativeEntryPath(subPath)) return null + if (!ALLOWED_PRIVATE_DATA_DIRS.some((prefix) => subPath.startsWith(prefix))) return null + + const ext = path.extname(subPath).toLowerCase() + const contentType = PRIVATE_MEDIA_MIME_TYPES[ext] + if (!contentType) return null + + const dataRoot = dependencies.paths.extensionDataDir(extensionId) + const resolved = path.resolve(dataRoot, subPath) + if (!isPathInside(dataRoot, resolved)) return null + const lstat = await fs.lstat(resolved).catch(() => null) + if (!lstat || lstat.isSymbolicLink() || !lstat.isFile()) return null + const realRoot = await fs.realpath(dataRoot).catch(() => null) + const realFile = await fs.realpath(resolved).catch(() => null) + if (!realRoot || !realFile || !isPathInside(realRoot, realFile)) return null + + const maxBytes = ext === '.mp4' ? MAX_PRIVATE_VIDEO_BYTES : MAX_PRIVATE_IMAGE_AUDIO_BYTES + if (lstat.size <= 0 || lstat.size > maxBytes) return null + return { + realFile, + contentType, + csp: PRIVATE_MEDIA_CSP, + size: lstat.size, + isPrivateMedia: true + } + } + + const root = dependencies.resolveRoot(extensionId) + if (!root) return null + const resolved = path.resolve(root, relative) + if (!isPathInside(root, resolved)) return null + const realRoot = await fs.realpath(root).catch(() => null) + const realFile = await fs.realpath(resolved).catch(() => null) + if (!realRoot || !realFile || !isPathInside(realRoot, realFile)) return null + + const stat = await fs.stat(realFile).catch(() => null) + if (!stat || !stat.isFile() || stat.size > MAX_CODE_FILE_BYTES) return null + const contentType = + MIME_TYPES[path.extname(realFile).toLowerCase()] || 'application/octet-stream' + return { + realFile, + contentType, + csp: PAGE_CSP, + size: stat.size, + isPrivateMedia: false + } +} + /** 扩展页面协议:只接受 `tm-extension:///`,realpath 必须仍在。 */ export function registerExtensionScheme(): void { protocol.registerSchemesAsPrivileged([ @@ -50,42 +182,14 @@ export interface ExtensionProtocolDependencies { export function installExtensionProtocolHandler(dependencies: ExtensionProtocolDependencies): void { protocol.handle(EXTENSION_SCHEME, async (request) => { try { - const url = new URL(request.url) - const extensionId = url.hostname.toLowerCase() - if (!/^[a-z0-9.-]{3,128}$/.test(extensionId)) return notFound() - const relative = decodeURIComponent(url.pathname).replace(/^\/+/, '') - if (!isSafeRelativeEntryPath(relative)) return notFound() - - 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) - const realFile = await fs.realpath(resolved).catch(() => null) - if (!realRoot || !realFile) return notFound() - if (!isPathInside(realRoot, realFile)) return notFound() - - const stat = await fs.stat(realFile) - if (!stat.isFile() || stat.size > 20 * 1024 * 1024) return notFound() - const body = await fs.readFile(realFile) - const contentType = - MIME_TYPES[path.extname(realFile).toLowerCase()] || 'application/octet-stream' + const resolved = await resolveExtensionProtocolFile(request.url, dependencies) + if (!resolved) return notFound() + const body = await fs.readFile(resolved.realFile) return new Response(body, { status: 200, headers: { - 'Content-Type': contentType, - 'Content-Security-Policy': [ - "default-src 'self'", - "script-src 'self'", - "style-src 'self' 'unsafe-inline'", - "img-src 'self' data: https:", - "media-src 'self' data: https:", - "font-src 'self' data:", - "connect-src 'none'", - "object-src 'none'", - "base-uri 'none'", - "form-action 'none'" - ].join('; '), + 'Content-Type': resolved.contentType, + 'Content-Security-Policy': resolved.csp, 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'no-store' } diff --git a/src/main/extensions/extension-service.ts b/src/main/extensions/extension-service.ts index 6c99051..dad2461 100644 --- a/src/main/extensions/extension-service.ts +++ b/src/main/extensions/extension-service.ts @@ -1,4 +1,5 @@ import { app, safeStorage } from 'electron' +import { createHash } from 'node:crypto' import path from 'node:path' import { AIProviderService } from '../services/ai-provider-service' import { @@ -7,18 +8,37 @@ import { isReady, listContacts, listMessagesAsync, - resolveMd5 + resolveMd5, + type FormattedMessage } from '../services/chat-service' +import { imageInsightService } from '../services/image-insight-service' +import { ImageKeyConfigService } from '../services/image-key-config-service' +import { imageTextIndexService } from '../services/image-text-index-service' import { personalWechatCapabilityService } from '../services/personal-wechat-capability-service' +import { htmlRenderService } from '../services/html-render-service' +import { loadSettings } from '../services/settings-store' +import { systemOcrService } from '../services/system-ocr-service' import { TextToSpeechSettingsService } from '../services/text-to-speech-settings-service' import { wechatActionGateway } from '../services/wechat-action-gateway' +import { ImageDecryptService } from '../image-decrypt-service' +import { VideoAssetService } from '../video-asset-service' +import { VoiceService } from '../voice-service' +import type { VoiceTranscriptionGateway } from '../voice-pipeline/voice-transcription-gateway' import { ExtensionError } from '../../shared/extensions/errors' +import type { ExtensionMessageRef } from '../../shared/extensions/media' import type { ExtensionMessagesQueryRequest, + ExtensionMessagesQueryResult, ExtensionQueriedMessage } from '../../shared/extensions/rpc' import { checkExtensionSendEntitlement } from './extension-entitlement' import { ExtensionManager } from './extension-manager' +import { + ExtensionMediaGateway, + paginateQueriedMessages, + type ResolvedExtensionMediaMessage +} from './extension-media-gateway' +import { ExtensionMessageRefSigner } from './extension-message-ref-signer' import { getExtensionPaths } from './extension-paths' let manager: ExtensionManager | null = null @@ -34,19 +54,281 @@ function resolveTemplateRoot(): string { export interface ExtensionSystemOptions { appVersion: string onChange: (extensionId: string, reason: string) => void + getImageDecryptService?: () => ImageDecryptService | null + voiceTranscriptionGateway?: Pick +} + +function decodeBase64DataUrl(value: string): { buffer: Buffer; mimeType: string } | null { + const match = /^data:(image\/[a-z0-9.+-]+);base64,([a-z0-9+/=]+)$/i.exec(value) + if (!match) return null + return { mimeType: match[1].toLowerCase(), buffer: Buffer.from(match[2], 'base64') } } /** 扩展系统的主进程接线。 */ export async function initExtensionSystem(options: ExtensionSystemOptions): Promise { if (manager) return const ttsService = new TextToSpeechSettingsService() + + let fallbackImageService: ImageDecryptService | null = null + let fallbackImageKey = '' + let fallbackImageClient: ReturnType< + NonNullable>['getWcdb4Client'] + > | null = null + let cachedVoiceService: { + client: ReturnType>['getWcdb4Client']> + service: VoiceService + } | null = null + let cachedVideoService: { + client: ReturnType>['getWcdb4Client']> + service: VideoAssetService + } | null = null + + const resolveImageDecryptService = (): ImageDecryptService | null => { + const injected = options.getImageDecryptService?.() + if (injected) return injected + const imageConfig = new ImageKeyConfigService().getConfig() + const aesKey = imageConfig.aesKey || '' + const xorKey = imageConfig.xorKey || '0x40' + if (!aesKey) return null + const client = getChatDb()?.getWcdb4Client() || null + const key = `${xorKey}:${aesKey}` + if ( + !fallbackImageService || + fallbackImageKey !== key || + fallbackImageClient !== client + ) { + fallbackImageService = new ImageDecryptService(xorKey, aesKey, client, loadSettings().dbRoot) + fallbackImageKey = key + fallbackImageClient = client + } + return fallbackImageService + } + + const resolveVoiceService = (): VoiceService | null => { + const client = getChatDb()?.getWcdb4Client() + if (!client) return null + if (!cachedVoiceService || cachedVoiceService.client !== client) { + cachedVoiceService = { client, service: new VoiceService(client) } + } + return cachedVoiceService.service + } + + const resolveVideoService = (): VideoAssetService | null => { + const client = getChatDb()?.getWcdb4Client() + if (!client) return null + if (!cachedVideoService || cachedVideoService.client !== client) { + cachedVideoService = { client, service: new VideoAssetService(client) } + } + return cachedVideoService.service + } + + const getAccountId = (): string => String(getSelfAccountInfo()?.wxid || '') + const messageRefSigner = new ExtensionMessageRefSigner() + manager = new ExtensionManager({ paths: getExtensionPaths(), appVersion: options.appVersion, getCapability: () => personalWechatCapabilityService.getPersonalWechatSendCapability(), checkEntitlement: () => checkExtensionSendEntitlement(), executeAction: (request) => wechatActionGateway.execute(request), - queryMessages: queryConversationMessages, + encodeMessageRef: (ref) => messageRefSigner.sign(ref), + onAccountChanged: (accountId) => messageRefSigner.syncAccount(accountId), + queryMessages: (request) => + queryConversationMessages(request, getAccountId(), (ref) => messageRefSigner.sign(ref)), + createMediaGateway: ({ hasPermission, isConversationAllowed, getExtensionDataRoot }) => + new ExtensionMediaGateway({ + isDatabaseReady: () => { + try { + return isReady() + } catch { + return false + } + }, + getAccountId, + getExtensionDataRoot, + hasPermission, + isConversationAllowed, + verifySignedRef: (rawRef, expectedAccountId) => + messageRefSigner.verify(rawRef, expectedAccountId), + resolveMessage: resolveMediaMessageByRef, + readImageData: async (message, quality) => { + const service = resolveImageDecryptService() + if (!service) { + throw new ExtensionError('CAPABILITY_UNAVAILABLE', '尚未配置图片解密密钥') + } + const primaryPath = await service.findImageFileAsync( + message.image?.md5, + message.image?.datName, + { + allowThumbnail: quality === 'thumbnail', + sessionId: message.conversationId, + createTime: message.createTimeSeconds + } + ) + const resolvedQuality: 'original' | 'thumbnail' = primaryPath + ? quality + : 'thumbnail' + const filePath = + primaryPath || + (quality === 'original' + ? await service.findImageFileAsync(message.image?.md5, message.image?.datName, { + allowThumbnail: true, + sessionId: message.conversationId, + createTime: message.createTimeSeconds + }) + : null) + if (!filePath) return null + const decoded = await service.decryptImageToBase64WithFallbackAsync(filePath, true) + if (!decoded?.data) return null + const parsed = decodeBase64DataUrl(decoded.data) + if (!parsed) return null + return { + buffer: parsed.buffer, + mimeType: parsed.mimeType, + ...(message.image?.md5 ? { imageHash: message.image.md5.toLowerCase() } : {}), + quality: resolvedQuality + } + }, + readVoiceData: async (message) => { + const service = resolveVoiceService() + if (!service) { + throw new ExtensionError('DATABASE_NOT_READY', '微信数据库尚未连接') + } + const resolved = await service.resolveVoice( + message.conversationId, + message.localId ?? 0, + message.createTimeSeconds, + message.serverId + ) + if (!resolved.success || !resolved.data) return null + return { + wavBuffer: Buffer.from(resolved.data, 'base64'), + ...(message.voice?.durationSeconds + ? { durationMs: Math.round(message.voice.durationSeconds * 1000) } + : {}) + } + }, + readVideoAsset: async (message) => { + const service = resolveVideoService() + if (!service) { + throw new ExtensionError('DATABASE_NOT_READY', '微信数据库尚未连接') + } + const resolved = await service.resolve(message.video?.hashes ?? [], { + createTime: message.createTimeSeconds, + byteLength: message.video?.byteLength, + duration: message.video?.duration, + width: message.video?.width, + height: message.video?.height + }) + if (!resolved.success || !resolved.url) return null + const filePath = service.pathForUrl(resolved.url) + if (!filePath) return null + const posterPath = resolved.poster ? service.pathForUrl(resolved.poster) : undefined + return { + filePath, + ...(posterPath ? { posterPath } : {}), + ...(message.video?.duration + ? { durationMs: Math.round(message.video.duration * 1000) } + : {}), + ...(message.video?.width ? { width: message.video.width } : {}), + ...(message.video?.height ? { height: message.video.height } : {}) + } + }, + getCachedOcr: (conversationId, messageId) => { + const entry = imageTextIndexService.getConversationOcr(conversationId).get(messageId) + if (!entry) return null + return { text: entry.text, language: null, engine: 'system-ocr' } + }, + recognizeOcr: async (imageDataUrl, language) => { + const result = await systemOcrService.recognize({ + imageDataUrl, + ...(language ? { language } : {}) + }) + return { + success: result.success, + text: result.text, + language: result.language, + engine: result.engine, + ...(result.error ? { error: result.error } : {}) + } + }, + transcribeVoice: async (reference, opts) => { + if (!options.voiceTranscriptionGateway) { + throw new ExtensionError('CAPABILITY_UNAVAILABLE', '语音转写服务尚未初始化') + } + const outcomes = await options.voiceTranscriptionGateway.transcribe([reference], opts) + if (!outcomes) return null + return outcomes[0] ?? null + }, + analyzeImage: async (input) => { + const accountScope = createHash('sha256') + .update(getAccountId() || 'unknown') + .digest('hex') + .slice(0, 12) + if (!input.prompt) { + const response = await imageInsightService.analyze({ + messageId: input.messageId, + imageHash: `${accountScope}:${input.imageHash}`, + imageDataUrl: input.imageDataUrl, + sender: input.senderName, + sentAt: input.sentAt, + sessionId: input.conversationId, + force: input.force + }) + if (!response.success || !response.insight) { + throw new ExtensionError( + 'CAPABILITY_UNAVAILABLE', + response.error || 'AI 图片理解调用失败' + ) + } + return { + description: response.insight.description, + ...(response.insight.ocrText ? { ocrText: response.insight.ocrText } : {}), + ...(response.insight.tags?.length ? { tags: response.insight.tags } : {}), + ...(response.insight.category ? { category: response.insight.category } : {}), + ...(response.insight.model ? { model: response.insight.model } : {}), + cached: response.fromCache === true + } + } + const provider = new AIProviderService() + const runtime = provider.getVisionRuntimeConfig() + if (!runtime.configured || !runtime.providerId || !runtime.model) { + throw new ExtensionError('CAPABILITY_UNAVAILABLE', '尚未配置支持图片理解的 AI 模型') + } + const result = await provider.analyzeImage( + [ + { + role: 'user', + content: [ + { type: 'text', text: input.prompt }, + { type: 'image', dataUrl: input.imageDataUrl } + ] + } + ], + { providerId: runtime.providerId, modelId: runtime.model } + ) + if (!result.success || !result.data) { + throw new ExtensionError('CAPABILITY_UNAVAILABLE', result.error || 'AI 图片理解调用失败') + } + return { + description: result.data.trim(), + model: runtime.modelName || runtime.model, + cached: false + } + } + }), + renderHtmlToImage: (extensionId, extensionDataRoot, request) => + htmlRenderService.renderExtensionHtmlToPng({ + extensionId, + html: request.html, + css: request.css, + extensionDataRoot, + fileName: request.fileName, + width: request.width, + maxHeight: request.maxHeight, + backgroundColor: request.backgroundColor, + timeoutMs: request.timeoutMs + }), listGroups: async () => { try { return listContacts() @@ -109,7 +391,7 @@ export async function initExtensionSystem(options: ExtensionSystemOptions): Prom cleanupVoice: (filePath) => { ttsService.removeGeneratedAudio(filePath) }, - getAccountId: () => String(getSelfAccountInfo()?.wxid || ''), + getAccountId, getSelfUsernames: () => { try { return (getChatDb()?.getWcdb4Client()?.getMyUsernameCandidates?.() ?? []).filter(Boolean) @@ -169,24 +451,114 @@ function normalizeQueriedMessageType(rawType: string | undefined): { return { type: value || 'other', isTextLike: false } } +function toResolvedMediaMessage( + conversationId: string, + message: FormattedMessage +): ResolvedExtensionMediaMessage { + const normalized = normalizeQueriedMessageType(message.type) + const contentData = message.contentData + const mediaType: ResolvedExtensionMediaMessage['type'] = + normalized.type === 'image' || contentData?.type === 'image' + ? 'image' + : normalized.type === 'voice' || contentData?.type === 'voice' + ? 'voice' + : normalized.type === 'video' || contentData?.type === 'video' + ? 'video' + : 'other' + + const videoHashes = + contentData?.type === 'video' + ? [contentData.md5, contentData.newMd5, contentData.rawMd5] + .map((item) => String(item || '').trim()) + .filter(Boolean) + : [] + + return { + messageId: message.serverId || String(message.localId ?? message.id), + ...(message.localId !== undefined ? { localId: message.localId } : {}), + ...(message.serverId ? { serverId: message.serverId } : {}), + conversationId, + ...(message.name ? { senderName: message.name } : {}), + type: mediaType, + createTimeSeconds: message.createTime ?? 0, + ...(contentData?.type === 'image' + ? { image: { md5: contentData.md5, datName: contentData.datName } } + : {}), + ...(mediaType === 'voice' + ? { + voice: { + durationSeconds: + message.voiceDuration ?? + (contentData?.type === 'voice' ? contentData.duration : undefined) + } + } + : {}), + ...(contentData?.type === 'video' + ? { + video: { + hashes: videoHashes, + byteLength: contentData.byteLength, + duration: contentData.duration, + width: contentData.width, + height: contentData.height + } + } + : {}) + } +} + +function matchesRef(message: FormattedMessage, ref: ExtensionMessageRef): boolean { + const canonicalId = message.serverId || String(message.localId ?? message.id) + if (canonicalId === ref.messageId) return true + if (message.serverId && message.serverId === ref.messageId) return true + if (ref.localId && message.localId !== undefined && String(message.localId) === ref.localId) { + return true + } + if (message.localId !== undefined && String(message.localId) === ref.messageId) return true + return message.id === ref.messageId +} + +/** 结合 messageRef 的时间戳先查窄窗口,未命中再回退宽窗口,避免扫描整个会话。 */ +async function resolveMediaMessageByRef( + ref: ExtensionMessageRef +): Promise { + const contact = resolveMd5(ref.conversationId) + if (!contact?.md5) return null + const nowSec = Math.floor(Date.now() / 1000) + const centerSec = ref.timestamp ? Math.floor(ref.timestamp / 1000) : nowSec + const windows: Array<[number, number]> = ref.timestamp + ? [ + [Math.max(0, centerSec - 15), centerSec + 15], + [Math.max(0, centerSec - 300), centerSec + 300] + ] + : [[Math.max(0, nowSec - 86_400), nowSec + 60]] + + for (const [startSec, endSec] of windows) { + const rows = await listMessagesAsync(contact.md5, startSec, endSec, undefined, '', 'unknown') + const matched = rows.find((item) => matchesRef(item, ref)) + if (matched) return toResolvedMediaMessage(ref.conversationId, matched) + } + return null +} + async function queryConversationMessages( - request: ExtensionMessagesQueryRequest -): Promise { + request: ExtensionMessagesQueryRequest, + accountId: string, + encodeRef: (ref: ExtensionMessageRef) => string +): Promise { const contact = resolveMd5(request.conversationId) if (!contact?.md5) throw new ExtensionError('DATABASE_NOT_READY', '找不到该会话或数据库未连接') - const limit = Math.max(1, Math.min(Number(request.limit) || 50, 500)) + const startMs = request.startTime ?? Date.now() - 86_400_000 + const endMs = request.endTime ?? Date.now() const rawMessages = await listMessagesAsync( contact.md5, - Math.floor((request.startTime ?? Date.now() - 86_400_000) / 1000), - Math.floor((request.endTime ?? Date.now()) / 1000), + Math.floor(startMs / 1000), + Math.ceil(endMs / 1000), undefined, '', 'unknown' ) - const sorted = [...rawMessages] - .sort((left, right) => (left.createTime ?? 0) - (right.createTime ?? 0)) - .slice(-limit) - return sorted.map((message) => { + const mapped: ExtensionQueriedMessage[] = rawMessages.map((message) => { const normalizedType = normalizeQueriedMessageType(message.type) const quoteText = message.contentData && @@ -196,17 +568,28 @@ async function queryConversationMessages( ? message.contentData.content : '' const resolvedText = String(message.content || quoteText || '').trim() + const messageId = message.serverId || String(message.localId ?? message.id) + const timestamp = Math.round((message.createTime ?? 0) * 1000) + const messageRef = encodeRef({ + accountId, + conversationId: request.conversationId, + messageId, + ...(message.localId !== undefined ? { localId: String(message.localId) } : {}), + timestamp + }) return { - messageId: message.serverId || String(message.localId ?? message.id), + messageId, + messageRef, conversationId: request.conversationId, ...(message.senderId ? { senderId: message.senderId } : {}), ...(message.name ? { senderName: message.name } : {}), isSelf: message.isSender === true, type: normalizedType.type, ...(normalizedType.isTextLike && resolvedText ? { text: resolvedText } : {}), - timestamp: Math.round((message.createTime ?? 0) * 1000) + timestamp } }) + return paginateQueriedMessages(mapped, request) } async function chatWithConfiguredProvider( diff --git a/src/main/extensions/host-runtime.ts b/src/main/extensions/host-runtime.ts index 0406942..120cb5f 100644 --- a/src/main/extensions/host-runtime.ts +++ b/src/main/extensions/host-runtime.ts @@ -146,14 +146,86 @@ const tm = { startTime?: number endTime?: number limit?: number - }): Promise<{ messages: unknown[] }> { + cursor?: string + order?: 'asc' | 'desc' + types?: string[] + }): Promise<{ messages: unknown[]; nextCursor?: string; hasMore?: boolean }> { requirePermission('messages.query') const result = (await callHost('messages.query', { ...request }, 25_000)) as { messages: unknown[] + nextCursor?: string + hasMore?: boolean } return result } }, + media: { + async readImage(request: { messageRef: string; quality?: 'original' | 'thumbnail' }) { + requirePermission('media.read') + return callHost('media.readImage', { ...request }, 20_000) + }, + async readVoice(request: { messageRef: string }) { + requirePermission('media.read') + return callHost('media.readVoice', { ...request }, 25_000) + }, + async readVideo(request: { messageRef: string }) { + requirePermission('media.read') + return callHost('media.readVideo', { ...request }, 35_000) + }, + async ocrImage(request: { messageRef: string; language?: string; force?: boolean }) { + requirePermission('media.ocr') + return callHost('media.ocrImage', { ...request }, 30_000) + }, + async transcribeVoice(request: { messageRef: string; force?: boolean; waitMs?: number }) { + requirePermission('media.transcribe') + return callHost('media.transcribeVoice', { ...request }, 35_000) + }, + async analyzeImage(request: { messageRef: string; prompt?: string; force?: boolean }) { + requirePermission('ai.vision') + return callHost('media.analyzeImage', { ...request }, 65_000) + }, + async batch(request: { + items: Array<{ op: string; messageRef: string; options?: Record }> + concurrency?: number + }) { + return callHost('media.batch', { ...request }, 120_000) + } + }, + render: { + async htmlToImage(request: { + html: string + css?: string + fileName?: string + width?: number + maxHeight?: number + backgroundColor?: string + timeoutMs?: number + }) { + requirePermission('render.html') + return callHost('render.htmlToImage', { ...request }, 50_000) + } + }, + notifications: { + async create(request: { + title: string + body?: string + level?: 'info' | 'success' | 'warning' | 'error' + dedupeKey?: string + pageId?: string + }) { + requirePermission('notifications.create') + return callHost('notifications.create', { ...request }, 8_000) + }, + async list() { + requirePermission('notifications.create') + const result = (await callHost('notifications.list', {}, 8_000)) as { items?: unknown[] } + return Array.isArray(result?.items) ? result.items : [] + }, + async markRead(request: { id?: string; all?: boolean } = {}) { + requirePermission('notifications.create') + return callHost('notifications.markRead', { ...request }, 8_000) + } + }, wechat: { /** 发送文本、图片、视频或语音。 */ async send(request: { @@ -222,6 +294,10 @@ const tm = { async chat(messages: Array<{ role: string; content: string }>) { requirePermission('ai.chat') return (await callHost('ai.chat', { messages }, 60_000)) as { text: string } + }, + async analyzeImage(request: { messageRef: string; prompt?: string; force?: boolean }) { + requirePermission('ai.vision') + return callHost('media.analyzeImage', { ...request }, 65_000) } }, storage: { diff --git a/src/main/group-report-service.ts b/src/main/group-report-service.ts index 08be1a6..697713a 100644 --- a/src/main/group-report-service.ts +++ b/src/main/group-report-service.ts @@ -1,10 +1,8 @@ import { app, BrowserWindow } from 'electron' -import crypto from 'node:crypto' import { appendFileSync } from 'node:fs' import fs from 'fs-extra' import os from 'os' import path from 'path' -import { fileURLToPath } from 'node:url' import { GroupReportExportRequest, GroupReportExportResult, @@ -23,6 +21,7 @@ import { getReportTemplate } from '../shared/report-templates' import type { ReportTemplateRef } from '../shared/report-template-package' import { injectReportTemplateFragmentContract } from '../shared/report-template-fragment-contract' import { reportTemplateService, validateReportTemplateHtml } from './report-template-service' +import { htmlRenderService } from './services/html-render-service' const LEGACY_TEMPLATE_FILES: Record = { v1: 'mobile_daily_report_v1.html', @@ -1017,95 +1016,21 @@ const captureFullPage = async ( const maxCaptureWidth = LEGACY_TEMPLATE_FILES[templateId || ''] ? 1200 : template.maxCaptureWidth const maxCaptureHeight = templateOverride?.maxCaptureHeight || 20000 console.log(`[GroupReport] capture begin html=${htmlPath}`) - const reportSessionPartition = `report-template-${crypto.randomUUID()}` - const reportWindow = new BrowserWindow({ - show: false, - opacity: 0, - skipTaskbar: true, + const result = await htmlRenderService.renderFileToPng({ + htmlPath, + pngPath, width: captureWidth, - height: 800, - frame: false, + maxWidth: maxCaptureWidth, + minHeight: 800, + maxHeight: maxCaptureHeight, backgroundColor: '#f3f5f7', - webPreferences: { - sandbox: true, - contextIsolation: true, - nodeIntegration: false, - partition: reportSessionPartition + minPngBytes: 1000, + onBlockedRequest: (details, reason) => { + recordBlockedTemplateRequest(details as Electron.OnBeforeRequestListenerDetails, reason) } }) - const allowedDocumentPath = path.resolve(htmlPath) - const requestHandler = ( - details: Electron.OnBeforeRequestListenerDetails, - callback: (response: { cancel: boolean }) => void - ): void => { - if (details.url.startsWith('file:')) { - try { - const requestedPath = path.resolve(fileURLToPath(details.url)) - if (requestedPath === allowedDocumentPath) { - callback({ cancel: false }) - } else { - recordBlockedTemplateRequest(details, 'file-path-not-allowed') - callback({ cancel: true }) - } - } catch { - recordBlockedTemplateRequest(details, 'invalid-file-url') - callback({ cancel: true }) - } - return - } - recordBlockedTemplateRequest(details, 'scheme-not-allowed') - callback({ cancel: true }) - } - reportWindow.webContents.session.webRequest.onBeforeRequest( - { urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*', 'file://*/*'] }, - requestHandler - ) - reportWindow.webContents.setWindowOpenHandler(() => ({ action: 'deny' })) - reportWindow.webContents.on('will-navigate', (event) => event.preventDefault()) - - try { - const readyToShow = new Promise((resolve) => reportWindow.once('ready-to-show', resolve)) - await reportWindow.loadFile(htmlPath) - await readyToShow - console.log('[GroupReport] capture loaded html') - await reportWindow.webContents.executeJavaScript(`Promise.all([ - document.fonts.ready, - ...Array.from(document.images).map((img) => img.complete ? Promise.resolve() : new Promise((resolve) => { - img.addEventListener('load', resolve, { once: true }); - img.addEventListener('error', resolve, { once: true }); - })) - ])`) - console.log('[GroupReport] capture assets ready') - const metrics = (await reportWindow.webContents.executeJavaScript(`({ - width: Math.ceil(Math.max(document.documentElement.scrollWidth, document.body.scrollWidth, ${captureWidth})), - height: Math.ceil(Math.max(document.documentElement.scrollHeight, document.body.scrollHeight, 800)) - })`)) as { width: number; height: number } - const width = Math.max(captureWidth, Math.min(maxCaptureWidth, Math.ceil(metrics.width))) - const height = Math.max(800, Math.min(maxCaptureHeight, Math.ceil(metrics.height))) - const [currentWidth, currentHeight] = reportWindow.getContentSize() - if (currentWidth !== width || currentHeight !== height) { - const resized = new Promise((resolve) => reportWindow.once('resize', resolve)) - reportWindow.setContentSize(width, height) - await resized - } - await reportWindow.webContents.executeJavaScript( - 'new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))' - ) - await new Promise((resolve) => setTimeout(resolve, 100)) - console.log(`[GroupReport] capture native page width=${width} height=${height}`) - const image = await reportWindow.webContents.capturePage( - { x: 0, y: 0, width, height }, - { stayHidden: true } - ) - const png = image.toPNG() - if (png.length < 1000) throw new Error('生成的日报图片为空') - await fs.writeFile(pngPath, png) - console.log(`[GroupReport] capture ok bytes=${png.length} png=${pngPath}`) - return `data:image/png;base64,${png.toString('base64')}` - } finally { - reportWindow.webContents.session.webRequest.onBeforeRequest(null) - reportWindow.destroy() - } + console.log(`[GroupReport] capture ok bytes=${result.bytes} png=${pngPath}`) + return result.imageDataUrl } export const exportGroupReport = async ( diff --git a/src/main/index.ts b/src/main/index.ts index cd41c19..4ad0830 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1737,6 +1737,8 @@ app.whenReady().then(async () => { if (isLegacyMigrationHelper) { createWindow() void initExtensionSystem({ appVersion: app.getVersion(), + getImageDecryptService: () => ensureImageDecryptService(), + voiceTranscriptionGateway, onChange: (extensionId, reason) => { for (const window of BrowserWindow.getAllWindows()) { if (!window.isDestroyed()) { diff --git a/src/main/services/html-render-service.ts b/src/main/services/html-render-service.ts new file mode 100644 index 0000000..f7ae162 --- /dev/null +++ b/src/main/services/html-render-service.ts @@ -0,0 +1,594 @@ +import { BrowserWindow } from 'electron' +import crypto from 'node:crypto' +import fs from 'fs-extra' +import os from 'node:os' +import path from 'node:path' +import { fileURLToPath } from 'node:url' +import { ExtensionError } from '../../shared/extensions/errors' +import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest' +import { isPathInside } from '../extensions/extension-paths' +import { buildExtensionPrivateMediaPreviewUrl } from '../extensions/extension-protocol' + +const DEFAULT_WIDTH = 430 +const MIN_WIDTH = 240 +const DEFAULT_MAX_WIDTH = 1600 +const DEFAULT_MIN_HEIGHT = 120 +const DEFAULT_MAX_HEIGHT = 16_000 +const DEFAULT_MAX_HTML_BYTES = 1024 * 1024 +const DEFAULT_MAX_PNG_BYTES = 20 * 1024 * 1024 +const DEFAULT_TIMEOUT_MS = 20_000 +const DEFAULT_MAX_CONCURRENT = 2 +const MIN_VALID_PNG_BYTES = 100 + +/** 禁止脚本、外链、表单与框架:只允许内联样式与 data: 图片/字体。 */ +export const STATIC_RENDER_CSP = + "default-src 'none'; img-src data:; style-src 'unsafe-inline'; font-src data:; media-src 'none'; script-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none';" + +const FORBIDDEN_HTML_PATTERNS: Array<{ pattern: RegExp; reason: string }> = [ + { pattern: /<\s*script\b/i, reason: '不允许包含 script 标签' }, + { pattern: /<\s*(?:iframe|frame|frameset|object|embed|applet|base)\b/i, reason: '不允许包含外部嵌入或重定向标签' }, + { pattern: /<\s*meta\b[^>]*http-equiv\s*=\s*['"]?\s*refresh/i, reason: '不允许包含 meta refresh 跳转' }, + { pattern: /\bon[a-z]{2,32}\s*=/i, reason: '不允许包含内联事件处理属性' }, + { pattern: /\b(?:javascript|vbscript)\s*:/i, reason: '不允许包含脚本协议 URL' }, + { pattern: /\b(?:src|href|xlink:href|srcset|action|poster)\s*=\s*['"]?\s*(?:https?:|wss?:|ftp:|file:|\/\/)/i, reason: '不允许引用外部网络或本地文件资源' }, + { pattern: /@import\b/i, reason: '不允许在样式中使用 @import 加载外部资源' }, + { pattern: /url\(\s*['"]?\s*(?:https?:|wss?:|ftp:|file:|\/\/)/i, reason: '不允许在样式中引用外部网络或本地文件 URL' } +] + +export interface RenderBlockedRequestDetails { + url: string + method: string + resourceType: string +} + +export interface RenderWindowAdapter { + loadFile: (filePath: string) => Promise + onceReadyToShow: (callback: () => void) => void + onceResize: (callback: () => void) => void + getContentSize: () => [number, number] + setContentSize: (width: number, height: number) => void + executeJavaScript: (code: string) => Promise + capturePage: (rect: { x: number; y: number; width: number; height: number }) => Promise + installRequestFilter: ( + handler: ( + details: RenderBlockedRequestDetails, + callback: (response: { cancel: boolean }) => void + ) => void + ) => void + clearRequestFilter: () => void + isDestroyed: () => boolean + destroy: () => void +} + +export interface RenderFileToPngOptions { + htmlPath: string + pngPath: string + width?: number + maxWidth?: number + minHeight?: number + maxHeight?: number + backgroundColor?: string + timeoutMs?: number + maxPngBytes?: number + minPngBytes?: number + /** 为 true 时在 HTTP 响应头追加严格 CSP,适合不可信静态 HTML。 */ + enforceStaticCsp?: boolean + /** 捕获前的帧稳定等待(毫秒);真实 Electron 默认 100ms,单元测试注入窗口时为 0。 */ + settleMs?: number + onBlockedRequest?: (details: RenderBlockedRequestDetails, reason: string) => void +} + +export interface RenderFileToPngResult { + pngPath: string + width: number + height: number + pixelWidth?: number + pixelHeight?: number + deviceScaleFactor?: number + bytes: number + sha256: string + imageDataUrl: string +} + +export interface RenderExtensionHtmlOptions { + extensionId?: string + html: string + css?: string + /** 扩展私有数据根目录;生成的 PNG 必须落在此目录内。 */ + extensionDataRoot: string + /** 可选相对文件名(默认 `rendered/render-.png`)。 */ + fileName?: string + width?: number + maxHeight?: number + backgroundColor?: string + timeoutMs?: number +} + +export interface RenderExtensionHtmlResult { + path: string + previewUrl?: string + width: number + height: number + pixelWidth?: number + pixelHeight?: number + deviceScaleFactor?: number + bytes: number + mimeType: 'image/png' + sha256: string +} + +export interface HtmlRenderServiceDependencies { + createWindow?: (options: { + width: number + height: number + backgroundColor: string + partition: string + enforceStaticCsp: boolean + }) => RenderWindowAdapter + maxConcurrent?: number + maxHtmlBytes?: number + maxPngBytes?: number + tempDir?: string +} + +function clampInt(value: unknown, fallback: number, min: number, max: number): number { + const parsed = Number(value) + if (!Number.isFinite(parsed)) return fallback + return Math.max(min, Math.min(max, Math.round(parsed))) +} + +function normalizeBackgroundColor(value: unknown): string { + const raw = String(value || '').trim() + if (/^#[0-9a-fA-F]{3,8}$/.test(raw)) return raw + return '#ffffff' +} + +/** 静态 HTML 安全校验:在进入 BrowserWindow 之前阻断脚本、事件处理器和外链。 */ +export function assertSafeStaticHtml(html: string, css = '', maxBytes = DEFAULT_MAX_HTML_BYTES): void { + const htmlText = String(html ?? '') + const cssText = String(css ?? '') + if (!htmlText.trim()) { + throw new ExtensionError('INVALID_REQUEST', 'html 内容不能为空') + } + const totalBytes = Buffer.byteLength(htmlText, 'utf8') + Buffer.byteLength(cssText, 'utf8') + if (totalBytes > maxBytes) { + throw new ExtensionError( + 'INVALID_REQUEST', + `HTML 与 CSS 总大小不能超过 ${Math.floor(maxBytes / 1024)}KB` + ) + } + if (cssText && /<\s*\/?\s*style\b/i.test(cssText)) { + throw new ExtensionError('INVALID_REQUEST', '静态 HTML 校验未通过:css 中不允许包含 style 标签') + } + for (const rule of FORBIDDEN_HTML_PATTERNS) { + if (rule.pattern.test(htmlText) || (cssText && rule.pattern.test(cssText))) { + throw new ExtensionError('INVALID_REQUEST', `静态 HTML 校验未通过:${rule.reason}`) + } + } +} + +const PNG_MAGIC = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) + +function readPngPixelDimensions(png: Buffer): { pixelWidth: number; pixelHeight: number } | null { + if (png.length < 24) return null + if (!png.subarray(0, 8).equals(PNG_MAGIC)) return null + const pixelWidth = png.readUInt32BE(16) + const pixelHeight = png.readUInt32BE(20) + if (!pixelWidth || !pixelHeight) return null + return { pixelWidth, pixelHeight } +} + +/** 构造带严格 CSP 与隔离样式的完整静态 HTML 文档。 */ +export function buildIsolatedHtmlDocument(html: string, css = ''): string { + const cspTag = `` + const styleTag = css.trim() ? `` : '' + const trimmed = html.trim() + if (/]*>/i.test(trimmed)) { + return trimmed.replace(/]*>/i, (match) => `${match}\n${cspTag}\n${styleTag}`) + } + return trimmed.replace(/]*>/i, (match) => `${match}\n${cspTag}${styleTag}`) + } + return ` + + + + +${cspTag} + +${styleTag} + +${trimmed} +` +} + +function createElectronRenderWindow(options: { + width: number + height: number + backgroundColor: string + partition: string + enforceStaticCsp: boolean +}): RenderWindowAdapter { + const win = new BrowserWindow({ + show: false, + opacity: 0, + skipTaskbar: true, + width: options.width, + height: options.height, + frame: false, + backgroundColor: options.backgroundColor, + webPreferences: { + sandbox: true, + contextIsolation: true, + nodeIntegration: false, + webSecurity: true, + allowRunningInsecureContent: false, + partition: options.partition + } + }) + + win.webContents.setWindowOpenHandler(() => ({ action: 'deny' })) + win.webContents.on('will-navigate', (event) => event.preventDefault()) + + if (options.enforceStaticCsp) { + win.webContents.session.webRequest.onHeadersReceived((details, callback) => { + callback({ + responseHeaders: { + ...(details.responseHeaders ?? {}), + 'Content-Security-Policy': [STATIC_RENDER_CSP] + } + }) + }) + } + + return { + loadFile: (filePath) => win.loadFile(filePath), + onceReadyToShow: (cb) => { + win.once('ready-to-show', cb) + }, + onceResize: (cb) => { + win.once('resize', cb) + }, + getContentSize: () => { + const [w, h] = win.getContentSize() + return [w, h] + }, + setContentSize: (w, h) => win.setContentSize(w, h), + executeJavaScript: (code) => win.webContents.executeJavaScript(code), + capturePage: async (rect) => { + const image = await win.webContents.capturePage(rect, { stayHidden: true }) + return image.toPNG() + }, + installRequestFilter: (handler) => { + win.webContents.session.webRequest.onBeforeRequest( + { urls: ['http://*/*', 'https://*/*', 'ws://*/*', 'wss://*/*', 'ftp://*/*', 'file://*/*'] }, + (details, callback) => { + handler( + { + url: details.url, + method: details.method, + resourceType: details.resourceType + }, + callback + ) + } + ) + }, + clearRequestFilter: () => { + win.webContents.session.webRequest.onBeforeRequest(null) + if (options.enforceStaticCsp) { + win.webContents.session.webRequest.onHeadersReceived(null) + } + }, + isDestroyed: () => win.isDestroyed(), + destroy: () => { + if (!win.isDestroyed()) win.destroy() + } + } +} + +/** 构造文件级网络隔离拦截器:仅放行当前单个本地 HTML 文件,拒绝所有外链与其他 file:// 路径。 */ +export function createDocumentIsolationHandler( + allowedDocumentPath: string, + onBlocked?: (details: RenderBlockedRequestDetails, reason: string) => void +): ( + details: RenderBlockedRequestDetails, + callback: (response: { cancel: boolean }) => void +) => void { + const normalizedAllowed = path.resolve(allowedDocumentPath) + return (details, callback) => { + if (details.url.startsWith('file:')) { + try { + const requestedPath = path.resolve(fileURLToPath(details.url)) + const same = + process.platform === 'win32' + ? requestedPath.toLowerCase() === normalizedAllowed.toLowerCase() + : requestedPath === normalizedAllowed + if (same) { + callback({ cancel: false }) + } else { + onBlocked?.(details, 'file-path-not-allowed') + callback({ cancel: true }) + } + } catch { + onBlocked?.(details, 'invalid-file-url') + callback({ cancel: true }) + } + return + } + onBlocked?.(details, 'scheme-not-allowed') + callback({ cancel: true }) + } +} + +function withTimeout(promise: Promise, timeoutMs: number): Promise { + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject(new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时')) + }, timeoutMs) + promise.then( + (value) => { + clearTimeout(timer) + resolve(value) + }, + (error) => { + clearTimeout(timer) + reject(error) + } + ) + }) +} + +/** + * 官方群聊日报与扩展 `tm.render.htmlToImage` 共用本服务: + * 隔离窗口/Session、网络拦截、尺寸与并发上限必须两侧一致。 + */ +export class HtmlRenderService { + private readonly createWindow: NonNullable + private readonly maxConcurrent: number + private readonly maxHtmlBytes: number + private readonly maxPngBytes: number + private readonly tempDir: string + private readonly defaultSettleMs: number + private activeCount = 0 + + constructor(deps: HtmlRenderServiceDependencies = {}) { + this.createWindow = deps.createWindow ?? createElectronRenderWindow + this.defaultSettleMs = deps.createWindow ? 0 : 100 + this.maxConcurrent = Math.max(1, deps.maxConcurrent ?? DEFAULT_MAX_CONCURRENT) + this.maxHtmlBytes = Math.max(1024, deps.maxHtmlBytes ?? DEFAULT_MAX_HTML_BYTES) + this.maxPngBytes = Math.max(1024, deps.maxPngBytes ?? DEFAULT_MAX_PNG_BYTES) + this.tempDir = deps.tempDir ?? path.join(os.tmpdir(), 'tracememo-html-render') + } + + get activeRenders(): number { + return this.activeCount + } + + async renderFileToPng(options: RenderFileToPngOptions): Promise { + if (this.activeCount >= this.maxConcurrent) { + throw new ExtensionError('CONCURRENCY_LIMITED', '页面渲染并发已达上限,请稍后再试') + } + const captureWidth = clampInt(options.width, DEFAULT_WIDTH, MIN_WIDTH, 2400) + const maxCaptureWidth = Math.max( + captureWidth, + clampInt(options.maxWidth, Math.max(captureWidth, DEFAULT_MAX_WIDTH), captureWidth, 2400) + ) + const minCaptureHeight = clampInt(options.minHeight, DEFAULT_MIN_HEIGHT, 64, 4000) + const maxCaptureHeight = Math.max( + minCaptureHeight, + clampInt(options.maxHeight, DEFAULT_MAX_HEIGHT, minCaptureHeight, 25_000) + ) + const timeoutMs = clampInt(options.timeoutMs, DEFAULT_TIMEOUT_MS, 200, 60_000) + const maxPngBytes = Math.max(1024, options.maxPngBytes ?? this.maxPngBytes) + const minPngBytes = Math.max(1, options.minPngBytes ?? MIN_VALID_PNG_BYTES) + const backgroundColor = normalizeBackgroundColor(options.backgroundColor ?? '#f3f5f7') + + this.activeCount += 1 + let win: RenderWindowAdapter | null = null + let wroteOutput = false + let aborted = false + + try { + const partition = `html-render-${crypto.randomUUID()}` + win = this.createWindow({ + width: captureWidth, + height: Math.min(800, maxCaptureHeight), + backgroundColor, + partition, + enforceStaticCsp: options.enforceStaticCsp === true + }) + const currentWin = win + const isolationHandler = createDocumentIsolationHandler( + options.htmlPath, + options.onBlockedRequest + ) + currentWin.installRequestFilter(isolationHandler) + + const run = async (): Promise => { + const readyToShow = new Promise((resolve) => currentWin.onceReadyToShow(resolve)) + await currentWin.loadFile(options.htmlPath) + await readyToShow + await currentWin.executeJavaScript(`Promise.all([ + document.fonts ? document.fonts.ready : Promise.resolve(), + ...Array.from(document.images || []).map((img) => img.complete ? Promise.resolve() : new Promise((resolve) => { + img.addEventListener('load', resolve, { once: true }); + img.addEventListener('error', resolve, { once: true }); + })) + ])`) + const metrics = (await currentWin.executeJavaScript(`({ + width: Math.ceil(Math.max(document.documentElement.scrollWidth, document.body ? document.body.scrollWidth : 0, ${captureWidth})), + height: Math.ceil(Math.max(document.documentElement.scrollHeight, document.body ? document.body.scrollHeight : 0, ${minCaptureHeight})) + })`)) as { width?: number; height?: number } | null + + const width = Math.max( + captureWidth, + Math.min(maxCaptureWidth, Math.ceil(Number(metrics?.width) || captureWidth)) + ) + const height = Math.max( + minCaptureHeight, + Math.min(maxCaptureHeight, Math.ceil(Number(metrics?.height) || minCaptureHeight)) + ) + + const [currentWidth, currentHeight] = currentWin.getContentSize() + if (currentWidth !== width || currentHeight !== height) { + const resized = new Promise((resolve) => { + const fallback = setTimeout(resolve, 300) + currentWin.onceResize(() => { + clearTimeout(fallback) + resolve() + }) + }) + currentWin.setContentSize(width, height) + await resized + } + + await currentWin.executeJavaScript( + 'new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)))' + ) + const settleMs = options.settleMs ?? this.defaultSettleMs + if (settleMs > 0) { + await new Promise((resolve) => setTimeout(resolve, settleMs)) + } + if (aborted) { + throw new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时') + } + const png = await currentWin.capturePage({ x: 0, y: 0, width, height }) + if (aborted) { + throw new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时') + } + if (!png || png.length < minPngBytes) { + throw new ExtensionError('RENDER_FAILED', '渲染生成的 PNG 图片为空或过小') + } + if (png.length > maxPngBytes) { + throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '渲染生成的 PNG 图片超过体积上限') + } + await fs.ensureDir(path.dirname(options.pngPath)) + if (aborted) { + throw new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时') + } + await fs.writeFile(options.pngPath, png) + if (aborted) { + await fs.remove(options.pngPath).catch(() => undefined) + throw new ExtensionError('ACTION_TIMEOUT', 'HTML 渲染超时') + } + wroteOutput = true + const sha256 = crypto.createHash('sha256').update(png).digest('hex') + const pixelDims = readPngPixelDimensions(png) + const deviceScaleFactor = + pixelDims && width > 0 ? Number((pixelDims.pixelWidth / width).toFixed(2)) : undefined + return { + pngPath: options.pngPath, + width, + height, + ...(pixelDims ? { pixelWidth: pixelDims.pixelWidth, pixelHeight: pixelDims.pixelHeight } : {}), + ...(deviceScaleFactor ? { deviceScaleFactor } : {}), + bytes: png.length, + sha256, + imageDataUrl: `data:image/png;base64,${png.toString('base64')}` + } + } + + return await withTimeout(run(), timeoutMs) + } catch (error) { + aborted = true + if (!wroteOutput) { + await fs.remove(options.pngPath).catch(() => undefined) + } + if (error instanceof ExtensionError) throw error + throw new ExtensionError( + 'RENDER_FAILED', + error instanceof Error ? error.message.slice(0, 200) : '页面渲染失败' + ) + } finally { + if (win) { + try { + win.clearRequestFilter() + } catch { + // 窗口已销毁时忽略清理钩子异常。 + } + try { + win.destroy() + } catch { + // 忽略重复销毁异常。 + } + } + this.activeCount = Math.max(0, this.activeCount - 1) + } + } + + /** 为扩展渲染静态 HTML 长图,输出严格隔离在扩展私有数据目录中。 */ + async renderExtensionHtmlToPng( + options: RenderExtensionHtmlOptions + ): Promise { + assertSafeStaticHtml(options.html, options.css, this.maxHtmlBytes) + const dataRoot = path.resolve(options.extensionDataRoot) + const relativeTarget = this.resolveExtensionOutputPath(options.fileName) + const targetPath = path.resolve(dataRoot, relativeTarget) + if (!isPathInside(dataRoot, targetPath)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', '渲染输出路径越界') + } + + await fs.ensureDir(dataRoot) + await fs.ensureDir(path.dirname(targetPath)) + const realRoot = await fs.realpath(dataRoot) + const realParent = await fs.realpath(path.dirname(targetPath)) + if (!isPathInside(realRoot, realParent)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', '渲染输出目录包含非法符号链接') + } + + await fs.ensureDir(this.tempDir) + const tempHtmlPath = path.join(this.tempDir, `ext-render-${crypto.randomUUID()}.html`) + const documentHtml = buildIsolatedHtmlDocument(options.html, options.css) + + try { + await fs.writeFile(tempHtmlPath, documentHtml, 'utf8') + const rendered = await this.renderFileToPng({ + htmlPath: tempHtmlPath, + pngPath: targetPath, + width: clampInt(options.width, DEFAULT_WIDTH, MIN_WIDTH, DEFAULT_MAX_WIDTH), + maxWidth: DEFAULT_MAX_WIDTH, + minHeight: DEFAULT_MIN_HEIGHT, + maxHeight: clampInt(options.maxHeight, DEFAULT_MAX_HEIGHT, DEFAULT_MIN_HEIGHT, DEFAULT_MAX_HEIGHT), + backgroundColor: options.backgroundColor ?? '#ffffff', + timeoutMs: clampInt(options.timeoutMs, DEFAULT_TIMEOUT_MS, 500, 45_000), + maxPngBytes: this.maxPngBytes, + enforceStaticCsp: true + }) + const previewUrl = options.extensionId + ? buildExtensionPrivateMediaPreviewUrl(options.extensionId, dataRoot, rendered.pngPath) + : undefined + return { + path: rendered.pngPath, + ...(previewUrl ? { previewUrl } : {}), + width: rendered.width, + height: rendered.height, + ...(rendered.pixelWidth !== undefined ? { pixelWidth: rendered.pixelWidth } : {}), + ...(rendered.pixelHeight !== undefined ? { pixelHeight: rendered.pixelHeight } : {}), + ...(rendered.deviceScaleFactor !== undefined + ? { deviceScaleFactor: rendered.deviceScaleFactor } + : {}), + bytes: rendered.bytes, + mimeType: 'image/png', + sha256: rendered.sha256 + } + } finally { + await fs.remove(tempHtmlPath).catch(() => undefined) + } + } + + private resolveExtensionOutputPath(fileName: string | undefined): string { + const raw = String(fileName || '').trim() + if (!raw) { + return path.join('rendered', `render-${Date.now().toString(36)}-${crypto.randomBytes(4).toString('hex')}.png`) + } + const normalized = raw.replace(/\\/g, '/') + if (!isSafeRelativeEntryPath(normalized)) { + throw new ExtensionError('EXTENSION_INVALID_PATH', '输出文件名包含非法路径片段') + } + const withExt = normalized.toLowerCase().endsWith('.png') ? normalized : `${normalized}.png` + return withExt.startsWith('rendered/') ? withExt : `rendered/${withExt}` + } +} + +export const htmlRenderService = new HtmlRenderService() diff --git a/src/preload/index.d.ts b/src/preload/index.d.ts index 0bb0468..2e9269e 100644 --- a/src/preload/index.d.ts +++ b/src/preload/index.d.ts @@ -7,13 +7,16 @@ import type { import type { ExtensionInstallResult, ExtensionLogEntry, + ExtensionNotificationItem, + ExtensionNotificationSummary, ExtensionOperationResult, ExtensionPageDescriptor, ExtensionPageResponse, ExtensionActionInfo, ExtensionProjectResult, ExtensionSystemHealth, - InstalledExtension + InstalledExtension, + PinnedExtensionNavItem } from '../shared/extensions/types' import type { ExtensionTemplateStatus } from '../shared/extensions/templates' import { @@ -924,6 +927,18 @@ declare global { ) => Promise extensionPageRequest: (request: ExtensionPageRequest) => Promise openExtensionDataDir: (extensionId: string) => Promise<{ success: boolean; error?: string }> + listPinnedExtensionNav: () => Promise + pinExtensionNav: (extensionId: string, pageId?: string) => Promise + unpinExtensionNav: (extensionId: string) => Promise + reorderPinnedExtensionNav: (extensionIds: string[]) => Promise + listExtensionNotifications: (extensionId?: string) => Promise + getExtensionNotificationSummary: () => Promise + markExtensionNotificationsRead: (payload: { + id?: string + extensionId?: string + all?: boolean + }) => Promise<{ changed: number }> + clearExtensionNotifications: (extensionId?: string) => Promise<{ removed: number }> onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => () => void } } diff --git a/src/preload/index.ts b/src/preload/index.ts index 81bee8d..5baeb7b 100644 --- a/src/preload/index.ts +++ b/src/preload/index.ts @@ -147,6 +147,8 @@ import type { ExtensionChangedEvent } from '../shared/extensions/ipc' import type { ExtensionInstallResult, ExtensionLogEntry, + ExtensionNotificationItem, + ExtensionNotificationSummary, ExtensionOperationResult, ExtensionPageDescriptor, ExtensionPageRequest, @@ -154,7 +156,8 @@ import type { ExtensionActionInfo, ExtensionProjectResult, ExtensionSystemHealth, - InstalledExtension + InstalledExtension, + PinnedExtensionNavItem } from '../shared/extensions/types' import type { ExtensionTemplateStatus } from '../shared/extensions/templates' @@ -375,6 +378,25 @@ const api = { ipcRenderer.invoke('extension:pageRequest', request), openExtensionDataDir: (extensionId: string): Promise<{ success: boolean; error?: string }> => ipcRenderer.invoke('extension:openDataDir', extensionId), + listPinnedExtensionNav: (): Promise => + ipcRenderer.invoke('extension:pinnedNavigation'), + pinExtensionNav: (extensionId: string, pageId?: string): Promise => + ipcRenderer.invoke('extension:pinNavigation', { id: extensionId, pageId }), + unpinExtensionNav: (extensionId: string): Promise => + ipcRenderer.invoke('extension:unpinNavigation', extensionId), + reorderPinnedExtensionNav: (extensionIds: string[]): Promise => + ipcRenderer.invoke('extension:reorderNavigation', extensionIds), + listExtensionNotifications: (extensionId?: string): Promise => + ipcRenderer.invoke('extension:notificationsList', extensionId), + getExtensionNotificationSummary: (): Promise => + ipcRenderer.invoke('extension:notificationsSummary'), + markExtensionNotificationsRead: (payload: { + id?: string + extensionId?: string + all?: boolean + }): Promise<{ changed: number }> => ipcRenderer.invoke('extension:notificationsMarkRead', payload), + clearExtensionNotifications: (extensionId?: string): Promise<{ removed: number }> => + ipcRenderer.invoke('extension:notificationsClear', extensionId), onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => { const listener = (_event: Electron.IpcRendererEvent, payload: ExtensionChangedEvent): void => callback(payload) diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 0403bf5..08cdaf3 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -53,7 +53,12 @@ import { type AutomationOpenRuleRequest } from './features/automation/AutomationWorkspace' import { ExtensionWorkspace } from './features/extensions/ExtensionWorkspace' -import type { ExtensionDeepLink } from '../../shared/extensions/types' +import { ExtensionPageHost } from './features/extensions/ExtensionPageHost' +import type { + ExtensionDeepLink, + ExtensionPageDescriptor, + PinnedExtensionNavItem +} from '../../shared/extensions/types' import { selectContactAvatarRefreshUsernames } from './utils/contact-avatar' import { buildContactSearchIndex, @@ -267,6 +272,10 @@ function App(): React.ReactElement { const [activePage, setActivePage] = useState('archive') /** 从其它页面跳到扩展中心时的定位目标;扩展中心消费后清空。 */ const [extensionDeepLink, setExtensionDeepLink] = useState(null) + /** 通过一级导航固定入口直接打开的扩展页面,复用同一个 ExtensionPageHost 容器。 */ + const [pinnedExtensionPage, setPinnedExtensionPage] = useState( + null + ) /** 「退群监控 ⇄ 自动化」之间的跨页深链。 */ const [automationOpenRuleRequest, setAutomationOpenRuleRequest] = React.useState(null) @@ -1604,11 +1613,36 @@ function App(): React.ReactElement { /** 跳到扩展中心并带上定位目标(模板 / 扩展)。 */ const openExtensionDeepLink = (target: ExtensionDeepLink): void => { + setPinnedExtensionPage(null) setExtensionDeepLink(target) handlePageChange('extensions') } + const openPinnedExtensionNav = (item: PinnedExtensionNavItem): void => { + void window.api.markExtensionNotificationsRead?.({ extensionId: item.extensionId }).catch(() => undefined) + void window.api + .getExtensionPageUrl(item.extensionId, item.pageId) + .then((descriptor) => { + setPinnedExtensionPage(descriptor) + }) + .catch(() => { + setPinnedExtensionPage(null) + openExtensionDeepLink({ extensionId: item.extensionId }) + }) + } + + React.useEffect(() => { + if (typeof window === 'undefined' || typeof window.api?.onExtensionChanged !== 'function') return + return window.api.onExtensionChanged((event) => { + if (event.reason !== 'uninstalled') return + setPinnedExtensionPage((current) => + current && current.extensionId === event.extensionId ? null : current + ) + }) + }, []) + const handlePageChange = (page: AppPage): void => { + setPinnedExtensionPage(null) setActivePage(page) if (page === 'archive' && selectedContact) void handleSelectContact(selectedContact) if (page === 'settings') setSettingsCategory('account-database') @@ -2085,6 +2119,19 @@ function App(): React.ReactElement { ) const renderCurrentWorkspace = (): React.ReactElement => { + if (pinnedExtensionPage) { + return ( +
+ { + setPinnedExtensionPage(null) + setActivePage('extensions') + }} + /> +
+ ) + } switch (activePage) { case 'archive': return renderArchiveWorkspace() @@ -2382,6 +2429,8 @@ function App(): React.ReactElement { dbReady={isDatabaseConnected} dbConnecting={isDatabaseConnecting} onPageChange={handlePageChange} + activePinnedExtensionId={pinnedExtensionPage?.extensionId ?? null} + onOpenPinnedExtension={openPinnedExtensionNav} onOpenSettings={openSettings} onOpenGuide={openFirstUseGuide} appearanceTheme={appearanceSettings.theme} diff --git a/src/renderer/src/components/layout/AppShell.tsx b/src/renderer/src/components/layout/AppShell.tsx index 6ef6062..3d2e5b1 100644 --- a/src/renderer/src/components/layout/AppShell.tsx +++ b/src/renderer/src/components/layout/AppShell.tsx @@ -2,6 +2,7 @@ import React from 'react' import { AccountSummary } from '../account/AccountSummary' import { PrimaryNavigation } from './PrimaryNavigation' import { AppPage, PRIMARY_NAV_ITEMS } from './navigation' +import type { PinnedExtensionNavItem } from '../../../../shared/extensions/types' import brandIcon from '../../assets/brand-icon.svg' interface SelfInfo { @@ -17,6 +18,8 @@ interface AppShellProps { dbReady: boolean dbConnecting?: boolean onPageChange: (page: AppPage) => void + activePinnedExtensionId?: string | null + onOpenPinnedExtension?: (item: PinnedExtensionNavItem) => void onOpenSettings: () => void onOpenGuide: () => void appearanceTheme?: 'system' | 'light' | 'dark' @@ -38,6 +41,8 @@ export function AppShell({ dbReady, dbConnecting = false, onPageChange, + activePinnedExtensionId, + onOpenPinnedExtension, onOpenSettings, onOpenGuide, appearanceTheme = 'system', @@ -57,7 +62,12 @@ export function AppShell({