mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 17:25:15 +08:00
feat: 扩展中心支持多模态消息、HTML 渲染、一级导航与应用内通知
This commit is contained in:
1 parent
b20e514c90
commit
4ea73c3414
63 files changed
+8360
-644
No files matched your search
@@ -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',
|
||||
|
||||
@@ -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<ExtensionQueriedMessage[]>
|
||||
) => Promise<ExtensionQueriedMessage[] | ExtensionMessagesQueryResult>
|
||||
mediaReadImage?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadImageRequest
|
||||
) => Promise<ExtensionMediaReadImageResult>
|
||||
mediaReadVoice?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadVoiceRequest
|
||||
) => Promise<ExtensionMediaReadVoiceResult>
|
||||
mediaReadVideo?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadVideoRequest
|
||||
) => Promise<ExtensionMediaReadVideoResult>
|
||||
mediaOcrImage?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaOcrImageRequest
|
||||
) => Promise<ExtensionMediaOcrImageResult>
|
||||
mediaTranscribeVoice?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaTranscribeVoiceRequest
|
||||
) => Promise<ExtensionMediaTranscribeVoiceResult>
|
||||
mediaAnalyzeImage?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaAnalyzeImageRequest
|
||||
) => Promise<ExtensionMediaAnalyzeImageResult>
|
||||
mediaBatch?: (
|
||||
extensionId: string,
|
||||
request: ExtensionMediaBatchRequest
|
||||
) => Promise<ExtensionMediaBatchResult>
|
||||
renderHtmlToImage?: (
|
||||
extensionId: string,
|
||||
request: ExtensionRenderHtmlToImageRequest
|
||||
) => Promise<ExtensionRenderHtmlToImageResult>
|
||||
createNotification?: (
|
||||
extensionId: string,
|
||||
request: ExtensionNotificationCreateRequest
|
||||
) => Promise<ExtensionNotificationCreateResult> | ExtensionNotificationCreateResult
|
||||
listNotifications?: (extensionId: string) => Promise<ExtensionNotificationItem[]> | ExtensionNotificationItem[]
|
||||
markNotificationsRead?: (
|
||||
extensionId: string,
|
||||
request: ExtensionNotificationMarkReadRequest
|
||||
) => Promise<ExtensionNotificationMarkReadResult> | 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)
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<PersonalWechatSendCapability>
|
||||
checkEntitlement: () => Promise<ExtensionEntitlementResult>
|
||||
executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
|
||||
queryMessages: (request: ExtensionMessagesQueryRequest) => Promise<ExtensionQueriedMessage[]>
|
||||
queryMessages: (
|
||||
request: ExtensionMessagesQueryRequest
|
||||
) => Promise<ExtensionQueriedMessage[] | ExtensionMessagesQueryResult>
|
||||
/** 可选媒体网关工厂:在主进程独立校验权限与会话范围后按需读取/解析媒体。 */
|
||||
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<ExtensionRenderHtmlToImageResult>
|
||||
/** 群列表(id + 显示名);用于扩展配置页选择发送目标。 */
|
||||
listGroups: () => Promise<Array<{ id: string; name: string }>>
|
||||
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<string, ExtensionHost>()
|
||||
private readonly manifests = new Map<string, ExtensionManifest | null>()
|
||||
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<ExtensionMediaReadImageResult> {
|
||||
return this.requireMediaGateway(extensionId).readImage(extensionId, request)
|
||||
}
|
||||
|
||||
private async mediaReadVoice(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadVoiceRequest
|
||||
): Promise<ExtensionMediaReadVoiceResult> {
|
||||
return this.requireMediaGateway(extensionId).readVoice(extensionId, request)
|
||||
}
|
||||
|
||||
private async mediaReadVideo(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaReadVideoRequest
|
||||
): Promise<ExtensionMediaReadVideoResult> {
|
||||
return this.requireMediaGateway(extensionId).readVideo(extensionId, request)
|
||||
}
|
||||
|
||||
private async mediaOcrImage(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaOcrImageRequest
|
||||
): Promise<ExtensionMediaOcrImageResult> {
|
||||
return this.requireMediaGateway(extensionId).ocrImage(extensionId, request)
|
||||
}
|
||||
|
||||
private async mediaTranscribeVoice(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaTranscribeVoiceRequest
|
||||
): Promise<ExtensionMediaTranscribeVoiceResult> {
|
||||
return this.requireMediaGateway(extensionId).transcribeVoice(extensionId, request)
|
||||
}
|
||||
|
||||
private async mediaAnalyzeImage(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaAnalyzeImageRequest
|
||||
): Promise<ExtensionMediaAnalyzeImageResult> {
|
||||
return this.requireMediaGateway(extensionId).analyzeImage(extensionId, request)
|
||||
}
|
||||
|
||||
private async mediaBatch(
|
||||
extensionId: string,
|
||||
request: ExtensionMediaBatchRequest
|
||||
): Promise<ExtensionMediaBatchResult> {
|
||||
return this.requireMediaGateway(extensionId).batch(extensionId, request)
|
||||
}
|
||||
|
||||
private async renderHtmlToImage(
|
||||
extensionId: string,
|
||||
request: ExtensionRenderHtmlToImageRequest
|
||||
): Promise<ExtensionRenderHtmlToImageResult> {
|
||||
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<ExtensionQueriedMessage[]> {
|
||||
): Promise<ExtensionQueriedMessage[] | ExtensionMessagesQueryResult> {
|
||||
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: {
|
||||
|
||||
@@ -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<ExtensionMediaBatchOperation, number> = {
|
||||
readImage: 15_000,
|
||||
readVoice: 20_000,
|
||||
readVideo: 30_000,
|
||||
ocrImage: 25_000,
|
||||
transcribeVoice: 30_000,
|
||||
analyzeImage: 60_000
|
||||
}
|
||||
|
||||
const OP_REQUIRED_PERMISSION: Record<ExtensionMediaBatchOperation, ExtensionPermission> = {
|
||||
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<ResolvedExtensionMediaMessage | null>
|
||||
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<VoiceTranscriptionOutcome | null>
|
||||
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<Record<ExtensionMediaBatchOperation, number>>
|
||||
now?: () => number
|
||||
}
|
||||
|
||||
interface CacheEntry<T> {
|
||||
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, '<path>')
|
||||
.replace(/\/(?:Users|home|var|tmp|private|Library|Volumes)\/[^\s'"]+/g, '<path>')
|
||||
.replace(/\b(aesKey|xorKey|apiKey|token|secret)\s*[:=]\s*\S+/gi, '$1=***')
|
||||
.slice(0, 200)
|
||||
}
|
||||
|
||||
function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
|
||||
return new Promise<T>((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<ExtensionMediaBatchOperation, number>
|
||||
private readonly now: () => number
|
||||
|
||||
private activeGlobal = 0
|
||||
private readonly activeByExtension = new Map<string, number>()
|
||||
private readonly inFlight = new Map<string, Promise<unknown>>()
|
||||
private readonly ocrCache = new Map<string, CacheEntry<Omit<ExtensionMediaOcrImageResult, 'messageRef' | 'cached'>>>()
|
||||
private readonly visionCache = new Map<
|
||||
string,
|
||||
CacheEntry<Omit<ExtensionMediaAnalyzeImageResult, 'messageRef' | 'cached'>>
|
||||
>()
|
||||
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<ExtensionMediaReadImageResult> {
|
||||
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<ExtensionMediaReadVoiceResult> {
|
||||
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<ExtensionMediaReadVideoResult> {
|
||||
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<ExtensionMediaOcrImageResult> {
|
||||
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<ExtensionMediaTranscribeVoiceResult> {
|
||||
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<ExtensionMediaAnalyzeImageResult> {
|
||||
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<ExtensionMediaBatchResult> {
|
||||
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<void> => {
|
||||
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<ExtensionMediaBatchItemResult> {
|
||||
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<ResolvedExtensionMediaMessage> {
|
||||
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<T>(
|
||||
extensionId: string,
|
||||
op: ExtensionMediaBatchOperation,
|
||||
dedupeKey: string,
|
||||
task: () => Promise<T>
|
||||
): Promise<T> {
|
||||
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<T>(map: Map<string, CacheEntry<T>>, 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<T>(map: Map<string, CacheEntry<T>>, 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
|
||||
}
|
||||
}
|
||||
@@ -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')
|
||||
}
|
||||
}
|
||||
@@ -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<PinnedNavigationFile>
|
||||
if (!parsed || Number(parsed.version) !== STORE_VERSION || !Array.isArray(parsed.items)) {
|
||||
return []
|
||||
}
|
||||
const result: PinnedNavigationRecord[] = []
|
||||
const seen = new Set<string>()
|
||||
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 })
|
||||
}
|
||||
}
|
||||
@@ -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<string, number[]>()
|
||||
private readonly updateHistory = new Map<string, number[]>()
|
||||
|
||||
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<string>): ExtensionNotificationSummary {
|
||||
let totalUnread = 0
|
||||
let unpinnedUnread = 0
|
||||
const unreadByExtension: Record<string, number> = {}
|
||||
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<string, number[]>,
|
||||
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<NotificationFile>
|
||||
if (!parsed || Number(parsed.version) !== STORE_VERSION || !Array.isArray(parsed.items)) {
|
||||
return []
|
||||
}
|
||||
const result: ExtensionNotificationItem[] = []
|
||||
const seen = new Set<string>()
|
||||
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 })
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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<string, string> = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
@@ -25,6 +28,135 @@ const MIME_TYPES: Record<string, string> = {
|
||||
'.wasm': 'application/wasm'
|
||||
}
|
||||
|
||||
/** 扩展私有预览只放行静态媒体文件,禁止读取脚本、HTML 或 storage.json。 */
|
||||
const PRIVATE_MEDIA_MIME_TYPES: Record<string, string> = {
|
||||
'.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<ResolvedExtensionProtocolFile | null> {
|
||||
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://<extensionId>/<path>`,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'
|
||||
}
|
||||
|
||||
@@ -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<VoiceTranscriptionGateway, 'transcribe' | 'snapshot'>
|
||||
}
|
||||
|
||||
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<void> {
|
||||
if (manager) return
|
||||
const ttsService = new TextToSpeechSettingsService()
|
||||
|
||||
let fallbackImageService: ImageDecryptService | null = null
|
||||
let fallbackImageKey = ''
|
||||
let fallbackImageClient: ReturnType<
|
||||
NonNullable<ReturnType<typeof getChatDb>>['getWcdb4Client']
|
||||
> | null = null
|
||||
let cachedVoiceService: {
|
||||
client: ReturnType<NonNullable<ReturnType<typeof getChatDb>>['getWcdb4Client']>
|
||||
service: VoiceService
|
||||
} | null = null
|
||||
let cachedVideoService: {
|
||||
client: ReturnType<NonNullable<ReturnType<typeof getChatDb>>['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<ResolvedExtensionMediaMessage | null> {
|
||||
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<ExtensionQueriedMessage[]> {
|
||||
request: ExtensionMessagesQueryRequest,
|
||||
accountId: string,
|
||||
encodeRef: (ref: ExtensionMessageRef) => string
|
||||
): Promise<ExtensionMessagesQueryResult> {
|
||||
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(
|
||||
|
||||
@@ -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<string, unknown> }>
|
||||
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: {
|
||||
|
||||
@@ -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<string, string> = {
|
||||
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<void>((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<void>((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 (
|
||||
|
||||
@@ -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()) {
|
||||
|
||||
@@ -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<void>
|
||||
onceReadyToShow: (callback: () => void) => void
|
||||
onceResize: (callback: () => void) => void
|
||||
getContentSize: () => [number, number]
|
||||
setContentSize: (width: number, height: number) => void
|
||||
executeJavaScript: (code: string) => Promise<unknown>
|
||||
capturePage: (rect: { x: number; y: number; width: number; height: number }) => Promise<Buffer>
|
||||
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-<timestamp>.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 = `<meta http-equiv="Content-Security-Policy" content="${STATIC_RENDER_CSP}">`
|
||||
const styleTag = css.trim() ? `<style>${css}</style>` : ''
|
||||
const trimmed = html.trim()
|
||||
if (/<html\b/i.test(trimmed)) {
|
||||
if (/<head\b[^>]*>/i.test(trimmed)) {
|
||||
return trimmed.replace(/<head\b[^>]*>/i, (match) => `${match}\n${cspTag}\n${styleTag}`)
|
||||
}
|
||||
return trimmed.replace(/<html\b[^>]*>/i, (match) => `${match}\n<head>${cspTag}${styleTag}</head>`)
|
||||
}
|
||||
return `<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
${cspTag}
|
||||
<style>html,body{margin:0;padding:0;box-sizing:border-box;}</style>
|
||||
${styleTag}
|
||||
</head>
|
||||
<body>${trimmed}</body>
|
||||
</html>`
|
||||
}
|
||||
|
||||
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<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
|
||||
return new Promise<T>((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<HtmlRenderServiceDependencies['createWindow']>
|
||||
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<RenderFileToPngResult> {
|
||||
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<RenderFileToPngResult> => {
|
||||
const readyToShow = new Promise<void>((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<void>((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<RenderExtensionHtmlResult> {
|
||||
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()
|
||||
Vendored
+16
-1
@@ -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<ExtensionPageDescriptor>
|
||||
extensionPageRequest: (request: ExtensionPageRequest) => Promise<ExtensionPageResponse>
|
||||
openExtensionDataDir: (extensionId: string) => Promise<{ success: boolean; error?: string }>
|
||||
listPinnedExtensionNav: () => Promise<PinnedExtensionNavItem[]>
|
||||
pinExtensionNav: (extensionId: string, pageId?: string) => Promise<ExtensionOperationResult>
|
||||
unpinExtensionNav: (extensionId: string) => Promise<ExtensionOperationResult>
|
||||
reorderPinnedExtensionNav: (extensionIds: string[]) => Promise<ExtensionOperationResult>
|
||||
listExtensionNotifications: (extensionId?: string) => Promise<ExtensionNotificationItem[]>
|
||||
getExtensionNotificationSummary: () => Promise<ExtensionNotificationSummary>
|
||||
markExtensionNotificationsRead: (payload: {
|
||||
id?: string
|
||||
extensionId?: string
|
||||
all?: boolean
|
||||
}) => Promise<{ changed: number }>
|
||||
clearExtensionNotifications: (extensionId?: string) => Promise<{ removed: number }>
|
||||
onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => () => void
|
||||
}
|
||||
}
|
||||
|
||||
+23
-1
@@ -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<PinnedExtensionNavItem[]> =>
|
||||
ipcRenderer.invoke('extension:pinnedNavigation'),
|
||||
pinExtensionNav: (extensionId: string, pageId?: string): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:pinNavigation', { id: extensionId, pageId }),
|
||||
unpinExtensionNav: (extensionId: string): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:unpinNavigation', extensionId),
|
||||
reorderPinnedExtensionNav: (extensionIds: string[]): Promise<ExtensionOperationResult> =>
|
||||
ipcRenderer.invoke('extension:reorderNavigation', extensionIds),
|
||||
listExtensionNotifications: (extensionId?: string): Promise<ExtensionNotificationItem[]> =>
|
||||
ipcRenderer.invoke('extension:notificationsList', extensionId),
|
||||
getExtensionNotificationSummary: (): Promise<ExtensionNotificationSummary> =>
|
||||
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)
|
||||
|
||||
@@ -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<AppPage>('archive')
|
||||
/** 从其它页面跳到扩展中心时的定位目标;扩展中心消费后清空。 */
|
||||
const [extensionDeepLink, setExtensionDeepLink] = useState<ExtensionDeepLink | null>(null)
|
||||
/** 通过一级导航固定入口直接打开的扩展页面,复用同一个 ExtensionPageHost 容器。 */
|
||||
const [pinnedExtensionPage, setPinnedExtensionPage] = useState<ExtensionPageDescriptor | null>(
|
||||
null
|
||||
)
|
||||
/** 「退群监控 ⇄ 自动化」之间的跨页深链。 */
|
||||
const [automationOpenRuleRequest, setAutomationOpenRuleRequest] =
|
||||
React.useState<AutomationOpenRuleRequest | null>(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 (
|
||||
<div className="extension-page-wrapper">
|
||||
<ExtensionPageHost
|
||||
descriptor={pinnedExtensionPage}
|
||||
onBack={() => {
|
||||
setPinnedExtensionPage(null)
|
||||
setActivePage('extensions')
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
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}
|
||||
|
||||
@@ -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({
|
||||
<div className={`app-shell theme-${appearanceTheme} ${compactMode ? 'is-compact' : ''}`}>
|
||||
<aside className="app-primary-rail">
|
||||
<BrandLogo />
|
||||
<PrimaryNavigation activePage={activePage} onPageChange={onPageChange} />
|
||||
<PrimaryNavigation
|
||||
activePage={activePage}
|
||||
onPageChange={onPageChange}
|
||||
activePinnedExtensionId={activePinnedExtensionId}
|
||||
onOpenPinnedExtension={onOpenPinnedExtension}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="app-guide-launcher"
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import React from 'react'
|
||||
import { AppPage, PRIMARY_NAV_ITEMS } from './navigation'
|
||||
import type { GroupExitMonitorState } from '../../../../shared/group-exit-monitor'
|
||||
import type { ExtensionNavigationIcon } from '../../../../shared/extensions/manifest'
|
||||
import type {
|
||||
ExtensionNotificationSummary,
|
||||
PinnedExtensionNavItem
|
||||
} from '../../../../shared/extensions/types'
|
||||
|
||||
interface NavIconProps {
|
||||
page: AppPage
|
||||
@@ -9,6 +14,76 @@ interface NavIconProps {
|
||||
interface PrimaryNavigationProps {
|
||||
activePage: AppPage
|
||||
onPageChange: (page: AppPage) => void
|
||||
/** 可选外部注入(便于测试);省略时自动从宿主加载并订阅变更。 */
|
||||
pinnedExtensions?: PinnedExtensionNavItem[]
|
||||
/** 可选外部注入(便于测试);省略时自动从宿主加载扩展通知汇总。 */
|
||||
notificationSummary?: ExtensionNotificationSummary
|
||||
activePinnedExtensionId?: string | null
|
||||
onOpenPinnedExtension?: (item: PinnedExtensionNavItem) => void
|
||||
}
|
||||
|
||||
function ExtensionNavIcon({ icon }: { icon: ExtensionNavigationIcon }): React.ReactElement {
|
||||
switch (icon) {
|
||||
case 'spark':
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M12 3.5 14.3 9.7 20.5 12l-6.2 2.3L12 20.5l-2.3-6.2L3.5 12l6.2-2.3L12 3.5Z" />
|
||||
</svg>
|
||||
)
|
||||
case 'bot':
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<rect x="5" y="7.5" width="14" height="10.5" rx="3" />
|
||||
<path d="M12 4.5v3" />
|
||||
<circle cx="9.5" cy="12.5" r="1" />
|
||||
<circle cx="14.5" cy="12.5" r="1" />
|
||||
</svg>
|
||||
)
|
||||
case 'digest':
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M6 4.5h9l3 3v12H6z" />
|
||||
<path d="M9 10h6" />
|
||||
<path d="M9 13.5h6" />
|
||||
<path d="M9 17h4" />
|
||||
</svg>
|
||||
)
|
||||
case 'bell':
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M7 16.5h10l-1.2-2.2V10a3.8 3.8 0 0 0-7.6 0v4.3L7 16.5Z" />
|
||||
<path d="M10.5 19a1.5 1.5 0 0 0 3 0" />
|
||||
</svg>
|
||||
)
|
||||
case 'media':
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<rect x="4.5" y="6" width="15" height="12" rx="2" />
|
||||
<circle cx="9.5" cy="10.5" r="1.4" />
|
||||
<path d="m6.5 16 4-3.5 2.8 2.2 2.2-1.8 2 3.1" />
|
||||
</svg>
|
||||
)
|
||||
case 'compass':
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<circle cx="12" cy="12" r="7.5" />
|
||||
<path d="m14.8 9.2-1.8 4.6-4.6 1.8 1.8-4.6 4.6-1.8Z" />
|
||||
</svg>
|
||||
)
|
||||
case 'message':
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M5 6.5h14v9H9.5L6 18.5v-3H5v-9Z" />
|
||||
</svg>
|
||||
)
|
||||
case 'puzzle':
|
||||
default:
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M9.5 4.5h5v2a1.5 1.5 0 1 0 3 0v-2h1.5v15h-15v-15H5.5v2a1.5 1.5 0 1 1-3 0v-2H5" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
function NavIcon({ page }: NavIconProps): React.ReactElement {
|
||||
@@ -47,7 +122,6 @@ function NavIcon({ page }: NavIconProps): React.ReactElement {
|
||||
</svg>
|
||||
)
|
||||
case 'extensions':
|
||||
// 拼图:扩展是「往现有能力上加一块」,与自动化的闪电区分开。
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M9.5 4.5h5v2a1.5 1.5 0 1 0 3 0v-2h1.5v15h-15v-15H5.5v2a1.5 1.5 0 1 1-3 0v-2H5" />
|
||||
@@ -64,7 +138,6 @@ function NavIcon({ page }: NavIconProps): React.ReactElement {
|
||||
</svg>
|
||||
)
|
||||
case 'automation':
|
||||
// 闪电:强调「命中即自动执行」,与退群监控的箭头区分开。
|
||||
return (
|
||||
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
|
||||
<path d="M13 4.5 7.5 13h4l-.5 6.5L16.5 11h-4z" />
|
||||
@@ -110,10 +183,57 @@ const SEND_CAPABILITY_POLL_MS = 30 * 60 * 1000
|
||||
|
||||
export function PrimaryNavigation({
|
||||
activePage,
|
||||
onPageChange
|
||||
onPageChange,
|
||||
pinnedExtensions: pinnedOverride,
|
||||
notificationSummary: notificationOverride,
|
||||
activePinnedExtensionId,
|
||||
onOpenPinnedExtension
|
||||
}: PrimaryNavigationProps): React.ReactElement {
|
||||
const [unreadExitCount, setUnreadExitCount] = React.useState(0)
|
||||
const [sendUnavailable, setSendUnavailable] = React.useState(false)
|
||||
const [loadedPinned, setLoadedPinned] = React.useState<PinnedExtensionNavItem[]>([])
|
||||
const [loadedSummary, setLoadedSummary] = React.useState<ExtensionNotificationSummary>({
|
||||
totalUnread: 0,
|
||||
unpinnedUnread: 0,
|
||||
unreadByExtension: {}
|
||||
})
|
||||
|
||||
const pinnedExtensions = pinnedOverride ?? loadedPinned
|
||||
const notificationSummary = notificationOverride ?? loadedSummary
|
||||
|
||||
React.useEffect(() => {
|
||||
if (pinnedOverride && notificationOverride) return
|
||||
const api = typeof window !== 'undefined' ? window.api : undefined
|
||||
if (!api) return
|
||||
let disposed = false
|
||||
const refreshExtensionNavState = (): void => {
|
||||
if (!pinnedOverride && typeof api.listPinnedExtensionNav === 'function') {
|
||||
void api
|
||||
.listPinnedExtensionNav()
|
||||
.then((items) => {
|
||||
if (!disposed && Array.isArray(items)) setLoadedPinned(items)
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}
|
||||
if (!notificationOverride && typeof api.getExtensionNotificationSummary === 'function') {
|
||||
void api
|
||||
.getExtensionNotificationSummary()
|
||||
.then((summary) => {
|
||||
if (!disposed && summary) setLoadedSummary(summary)
|
||||
})
|
||||
.catch(() => undefined)
|
||||
}
|
||||
}
|
||||
refreshExtensionNavState()
|
||||
const unsubscribe =
|
||||
typeof api.onExtensionChanged === 'function'
|
||||
? api.onExtensionChanged(() => refreshExtensionNavState())
|
||||
: null
|
||||
return () => {
|
||||
disposed = true
|
||||
unsubscribe?.()
|
||||
}
|
||||
}, [pinnedOverride, notificationOverride])
|
||||
|
||||
React.useEffect(() => {
|
||||
const api = typeof window !== 'undefined' ? window.api : undefined
|
||||
@@ -129,7 +249,6 @@ export function PrimaryNavigation({
|
||||
}
|
||||
checkSendCapability()
|
||||
const timer = window.setInterval(checkSendCapability, SEND_CAPABILITY_POLL_MS)
|
||||
// 半小时才轮一次,红点会过期;窗口重新可见时补查一次,成本可忽略。
|
||||
const onVisibilityChange = (): void => {
|
||||
if (!document.hidden) checkSendCapability()
|
||||
}
|
||||
@@ -169,34 +288,91 @@ export function PrimaryNavigation({
|
||||
void api.markGroupExitMonitorRead().catch(() => undefined)
|
||||
}, [activePage])
|
||||
|
||||
const beforeSettings = PRIMARY_NAV_ITEMS.filter((item) => item.id !== 'settings')
|
||||
const settingsItem = PRIMARY_NAV_ITEMS.find((item) => item.id === 'settings')
|
||||
|
||||
const renderBuiltInItem = (item: (typeof PRIMARY_NAV_ITEMS)[number]): React.ReactElement => {
|
||||
const unpinnedUnread = item.id === 'extensions' ? notificationSummary.unpinnedUnread : 0
|
||||
const titleParts = [item.label]
|
||||
if (item.id === 'extensions' && sendUnavailable) titleParts.push('当前暂无发送能力')
|
||||
if (unpinnedUnread > 0) titleParts.push(`${unpinnedUnread} 条未读扩展通知`)
|
||||
return (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
className={`primary-nav-item ${!activePinnedExtensionId && activePage === item.id ? 'active' : ''}`}
|
||||
onClick={() => onPageChange(item.id)}
|
||||
title={titleParts.join(' · ')}
|
||||
>
|
||||
<span className="primary-nav-mark" aria-hidden>
|
||||
<NavIcon page={item.id} />
|
||||
{item.id === 'exit-monitor' && unreadExitCount > 0 && (
|
||||
<span className="primary-nav-badge">{Math.min(unreadExitCount, 99)}</span>
|
||||
)}
|
||||
{item.id === 'extensions' && sendUnavailable && (
|
||||
<span
|
||||
className="primary-nav-badge primary-nav-badge-warn"
|
||||
data-badge-kind="send-warning"
|
||||
title="当前暂无发送能力"
|
||||
>
|
||||
!
|
||||
</span>
|
||||
)}
|
||||
{unpinnedUnread > 0 && (
|
||||
<span
|
||||
className={`primary-nav-badge primary-nav-badge-notification ${sendUnavailable ? 'primary-nav-badge-bottom' : ''}`}
|
||||
data-badge-kind="extension-unread"
|
||||
title={`未固定扩展有 ${unpinnedUnread} 条未读通知`}
|
||||
>
|
||||
{Math.min(unpinnedUnread, 99)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="primary-nav-label">{item.label}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<nav className="primary-navigation" aria-label="一级导航">
|
||||
{PRIMARY_NAV_ITEMS.map((item) => (
|
||||
<button
|
||||
key={item.id}
|
||||
type="button"
|
||||
className={`primary-nav-item ${activePage === item.id ? 'active' : ''}`}
|
||||
onClick={() => onPageChange(item.id)}
|
||||
title={
|
||||
item.id === 'extensions' && sendUnavailable
|
||||
? `${item.label}(当前暂无发送能力)`
|
||||
: item.label
|
||||
}
|
||||
>
|
||||
<span className="primary-nav-mark" aria-hidden>
|
||||
<NavIcon page={item.id} />
|
||||
{item.id === 'exit-monitor' && unreadExitCount > 0 && (
|
||||
<span className="primary-nav-badge">{Math.min(unreadExitCount, 99)}</span>
|
||||
)}
|
||||
{item.id === 'extensions' && sendUnavailable && (
|
||||
<span className="primary-nav-badge" title="当前暂无发送能力">
|
||||
!
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="primary-nav-label">{item.label}</span>
|
||||
</button>
|
||||
))}
|
||||
{beforeSettings.map(renderBuiltInItem)}
|
||||
{pinnedExtensions.length > 0 && (
|
||||
<>
|
||||
<div className="primary-nav-divider" role="separator" aria-hidden />
|
||||
{pinnedExtensions.map((item) => {
|
||||
const isActive = activePinnedExtensionId === item.extensionId
|
||||
const unread = notificationSummary.unreadByExtension[item.extensionId] ?? 0
|
||||
return (
|
||||
<button
|
||||
key={`ext:${item.extensionId}`}
|
||||
type="button"
|
||||
data-pinned-extension-id={item.extensionId}
|
||||
className={`primary-nav-item primary-nav-item-pinned ${isActive ? 'active' : ''}`}
|
||||
onClick={() => onOpenPinnedExtension?.(item)}
|
||||
title={
|
||||
unread > 0
|
||||
? `${item.label}(${unread} 条未读通知)`
|
||||
: `${item.label}(已固定扩展)`
|
||||
}
|
||||
>
|
||||
<span className="primary-nav-mark" aria-hidden>
|
||||
<ExtensionNavIcon icon={item.icon} />
|
||||
{unread > 0 && (
|
||||
<span
|
||||
className="primary-nav-badge primary-nav-badge-notification"
|
||||
data-badge-kind="pinned-unread"
|
||||
>
|
||||
{Math.min(unread, 99)}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="primary-nav-label">{item.label}</span>
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
</>
|
||||
)}
|
||||
{settingsItem && renderBuiltInItem(settingsItem)}
|
||||
</nav>
|
||||
)
|
||||
}
|
||||
@@ -6,9 +6,12 @@ import {
|
||||
} from '../../../../shared/extensions/permissions'
|
||||
import type {
|
||||
ExtensionLogEntry,
|
||||
ExtensionNotificationItem,
|
||||
ExtensionNotificationSummary,
|
||||
ExtensionPageDescriptor,
|
||||
ExtensionSystemHealth,
|
||||
InstalledExtension
|
||||
InstalledExtension,
|
||||
PinnedExtensionNavItem
|
||||
} from '../../../../shared/extensions/types'
|
||||
import type {
|
||||
ExtensionTemplateEntry,
|
||||
@@ -78,8 +81,10 @@ export function ExtensionWorkspace({
|
||||
const [templates, setTemplates] = React.useState<ExtensionTemplateStatus[]>([])
|
||||
const [templatesLoading, setTemplatesLoading] = React.useState(true)
|
||||
const [installingTemplate, setInstallingTemplate] = React.useState<string | null>(null)
|
||||
/** 右侧主区域:扩展列表 or 官方模板画廊。 */
|
||||
const [view, setView] = React.useState<'extensions' | 'templates' | 'guide'>('extensions')
|
||||
/** 右侧主区域:扩展列表、官方模板画廊、二次开发引导或通知中心。 */
|
||||
const [view, setView] = React.useState<'extensions' | 'templates' | 'guide' | 'notifications'>(
|
||||
'extensions'
|
||||
)
|
||||
/** 深链定位的模板:进入画廊时自动展开它。 */
|
||||
const [focusedTemplateId, setFocusedTemplateId] = React.useState<string | null>(null)
|
||||
/** 正在创建项目的模板;非空时显示创建对话框。 */
|
||||
@@ -98,20 +103,51 @@ export function ExtensionWorkspace({
|
||||
message?: string
|
||||
} | null>(null)
|
||||
const [sendMaskDismissed, setSendMaskDismissed] = React.useState(false)
|
||||
const [pinnedNavItems, setPinnedNavItems] = React.useState<PinnedExtensionNavItem[]>([])
|
||||
const [notifications, setNotifications] = React.useState<ExtensionNotificationItem[]>([])
|
||||
const [notificationSummary, setNotificationSummary] =
|
||||
React.useState<ExtensionNotificationSummary>({
|
||||
totalUnread: 0,
|
||||
unpinnedUnread: 0,
|
||||
unreadByExtension: {}
|
||||
})
|
||||
|
||||
const refresh = React.useCallback(async (): Promise<void> => {
|
||||
const loadSendCap =
|
||||
typeof window.api?.getPersonalWechatSendCapability === 'function'
|
||||
? window.api.getPersonalWechatSendCapability().catch(() => null)
|
||||
: Promise.resolve(null)
|
||||
const [list, systemHealth, templateList, nextSendCap] = await Promise.all([
|
||||
window.api.listExtensions(),
|
||||
window.api.getExtensionHealth().catch(() => null),
|
||||
window.api.listExtensionTemplates().catch(() => []),
|
||||
loadSendCap
|
||||
])
|
||||
const loadPinnedNav =
|
||||
typeof window.api?.listPinnedExtensionNav === 'function'
|
||||
? window.api.listPinnedExtensionNav().catch(() => [])
|
||||
: Promise.resolve([])
|
||||
const loadNotifications =
|
||||
typeof window.api?.listExtensionNotifications === 'function'
|
||||
? window.api.listExtensionNotifications().catch(() => [])
|
||||
: Promise.resolve([])
|
||||
const loadNotificationSummary =
|
||||
typeof window.api?.getExtensionNotificationSummary === 'function'
|
||||
? window.api.getExtensionNotificationSummary().catch(() => ({
|
||||
totalUnread: 0,
|
||||
unpinnedUnread: 0,
|
||||
unreadByExtension: {}
|
||||
}))
|
||||
: Promise.resolve({ totalUnread: 0, unpinnedUnread: 0, unreadByExtension: {} })
|
||||
const [list, systemHealth, templateList, nextSendCap, nextPinnedNav, nextNotifications, nextSummary] =
|
||||
await Promise.all([
|
||||
window.api.listExtensions(),
|
||||
window.api.getExtensionHealth().catch(() => null),
|
||||
window.api.listExtensionTemplates().catch(() => []),
|
||||
loadSendCap,
|
||||
loadPinnedNav,
|
||||
loadNotifications,
|
||||
loadNotificationSummary
|
||||
])
|
||||
setExtensions(list)
|
||||
setHealth(systemHealth)
|
||||
setPinnedNavItems(nextPinnedNav)
|
||||
setNotifications(nextNotifications)
|
||||
setNotificationSummary(nextSummary)
|
||||
setTemplates(templateList)
|
||||
setSendCapability(nextSendCap)
|
||||
setTemplatesLoading(false)
|
||||
@@ -556,6 +592,86 @@ export function ExtensionWorkspace({
|
||||
}
|
||||
}
|
||||
|
||||
const togglePinNavigation = async (extension: InstalledExtension): Promise<void> => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const result = extension.pinnedToNav
|
||||
? await window.api.unpinExtensionNav(extension.id)
|
||||
: await window.api.pinExtensionNav(
|
||||
extension.id,
|
||||
extension.navigation?.pageId || extension.pages[0]?.id
|
||||
)
|
||||
if (!result.success) {
|
||||
toast({
|
||||
title: extension.pinnedToNav ? '取消固定失败' : '固定到一级菜单失败',
|
||||
description: result.error?.message || '操作失败',
|
||||
variant: 'destructive'
|
||||
})
|
||||
} else {
|
||||
toast({
|
||||
title: extension.pinnedToNav ? '已从一级菜单移除' : '已固定到一级菜单',
|
||||
description: extension.pinnedToNav
|
||||
? `${extension.name} 已取消固定`
|
||||
: `${extension.name} 已显示在设置上方`
|
||||
})
|
||||
}
|
||||
await refresh()
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const movePinnedNavigation = async (extensionId: string, delta: -1 | 1): Promise<void> => {
|
||||
const ids = pinnedNavItems.map((item) => item.extensionId)
|
||||
const index = ids.indexOf(extensionId)
|
||||
const target = index + delta
|
||||
if (index < 0 || target < 0 || target >= ids.length) return
|
||||
const next = [...ids]
|
||||
;[next[index], next[target]] = [next[target], next[index]]
|
||||
setBusy(true)
|
||||
try {
|
||||
await window.api.reorderPinnedExtensionNav(next)
|
||||
await refresh()
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const openNotificationTarget = async (item: ExtensionNotificationItem): Promise<void> => {
|
||||
await window.api.markExtensionNotificationsRead?.({ id: item.id }).catch(() => undefined)
|
||||
const targetExtension = extensions.find((ext) => ext.id === item.extensionId)
|
||||
if (targetExtension && targetExtension.pages.length > 0) {
|
||||
try {
|
||||
const descriptor = await window.api.getExtensionPageUrl(
|
||||
item.extensionId,
|
||||
item.pageId || targetExtension.pages[0]?.id
|
||||
)
|
||||
setPage(descriptor)
|
||||
void refresh().catch(() => undefined)
|
||||
return
|
||||
} catch {
|
||||
// 页面不可用时退回该扩展详情。
|
||||
}
|
||||
}
|
||||
setSelectedId(item.extensionId)
|
||||
setView('extensions')
|
||||
void refresh().catch(() => undefined)
|
||||
}
|
||||
|
||||
const markAllNotificationsRead = async (): Promise<void> => {
|
||||
await window.api.markExtensionNotificationsRead?.({ all: true }).catch(() => undefined)
|
||||
await refresh()
|
||||
}
|
||||
|
||||
const clearAllNotifications = async (): Promise<void> => {
|
||||
await window.api.clearExtensionNotifications?.().catch(() => undefined)
|
||||
await refresh()
|
||||
}
|
||||
|
||||
const selectedPinnedIndex = selected
|
||||
? pinnedNavItems.findIndex((item) => item.extensionId === selected.id)
|
||||
: -1
|
||||
|
||||
if (page) {
|
||||
return (
|
||||
<div className="extension-page-wrapper">
|
||||
@@ -657,6 +773,15 @@ export function ExtensionWorkspace({
|
||||
>
|
||||
二次开发
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant={view === 'notifications' ? 'default' : 'outline'}
|
||||
className="extension-template-entry"
|
||||
onClick={() => setView(view === 'notifications' ? 'extensions' : 'notifications')}
|
||||
>
|
||||
扩展通知
|
||||
{notificationSummary.totalUnread > 0 ? ` (${notificationSummary.totalUnread})` : ''}
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
@@ -784,7 +909,94 @@ export function ExtensionWorkspace({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{view === 'guide' ? (
|
||||
{view === 'notifications' ? (
|
||||
<section className="extension-notifications-panel" aria-label="扩展通知中心">
|
||||
<header className="extension-detail-header">
|
||||
<div>
|
||||
<h3>扩展通知中心</h3>
|
||||
<p className="extension-detail-description">
|
||||
汇总扩展主动发出的提醒;未固定到一级菜单的扩展未读数会自动聚合到左侧「扩展」角标。
|
||||
</p>
|
||||
</div>
|
||||
<div className="extension-detail-actions">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={notificationSummary.totalUnread === 0}
|
||||
onClick={() => void markAllNotificationsRead()}
|
||||
>
|
||||
全部标为已读
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={notifications.length === 0}
|
||||
onClick={() => void clearAllNotifications()}
|
||||
>
|
||||
清空通知
|
||||
</Button>
|
||||
</div>
|
||||
</header>
|
||||
{notifications.length === 0 ? (
|
||||
<div className="extension-detail-empty">
|
||||
<h3>暂无扩展通知</h3>
|
||||
<p>扩展调用通知能力后,提醒会显示在这里并支持一键跳转到对应扩展页面。</p>
|
||||
</div>
|
||||
) : (
|
||||
<ul className="extension-notification-list">
|
||||
{notifications.map((item) => {
|
||||
const levelLabel =
|
||||
item.level === 'success'
|
||||
? '成功'
|
||||
: item.level === 'warning'
|
||||
? '提醒'
|
||||
: item.level === 'error'
|
||||
? '异常'
|
||||
: '信息'
|
||||
return (
|
||||
<li
|
||||
key={item.id}
|
||||
className={`extension-notification-item level-${item.level} ${item.read ? 'is-read' : 'is-unread'}`}
|
||||
>
|
||||
<div className="extension-notification-meta">
|
||||
<span className={`extension-badge tone-${item.level === 'error' ? 'danger' : item.level === 'warning' ? 'warn' : item.level === 'success' ? 'ok' : 'neutral'}`}>
|
||||
{levelLabel}
|
||||
</span>
|
||||
<strong>{item.title}</strong>
|
||||
<span className="extension-muted">{item.extensionName}</span>
|
||||
{!item.read && <span className="extension-notification-dot">未读</span>}
|
||||
</div>
|
||||
{item.body && <p className="extension-notification-body">{item.body}</p>}
|
||||
<div className="extension-notification-actions">
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => void openNotificationTarget(item)}
|
||||
>
|
||||
查看页面
|
||||
</Button>
|
||||
{!item.read && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
onClick={() => {
|
||||
void window.api
|
||||
.markExtensionNotificationsRead?.({ id: item.id })
|
||||
.then(() => refresh())
|
||||
.catch(() => undefined)
|
||||
}}
|
||||
>
|
||||
标记已读
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
)}
|
||||
</section>
|
||||
) : view === 'guide' ? (
|
||||
<DevelopmentGuide
|
||||
onBack={() => setView('extensions')}
|
||||
onCreateProject={() => setView('templates')}
|
||||
@@ -896,18 +1108,52 @@ export function ExtensionWorkspace({
|
||||
{selected.enabled ? '停用' : '启用'}
|
||||
</Button>
|
||||
{selected.pages.length > 0 && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
void window.api
|
||||
.getExtensionPageUrl(selected.id, selected.pages[0]?.id)
|
||||
.then(setPage)
|
||||
.catch(() => undefined)
|
||||
}}
|
||||
>
|
||||
打开页面
|
||||
</Button>
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
void window.api
|
||||
.getExtensionPageUrl(selected.id, selected.pages[0]?.id)
|
||||
.then(setPage)
|
||||
.catch(() => undefined)
|
||||
}}
|
||||
>
|
||||
打开页面
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant={selected.pinnedToNav ? 'outline' : 'ghost'}
|
||||
disabled={busy}
|
||||
onClick={() => void togglePinNavigation(selected)}
|
||||
>
|
||||
{selected.pinnedToNav ? '取消固定' : '固定到一级菜单'}
|
||||
</Button>
|
||||
{selected.pinnedToNav && pinnedNavItems.length > 1 && (
|
||||
<>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={busy || selectedPinnedIndex <= 0}
|
||||
onClick={() => void movePinnedNavigation(selected.id, -1)}
|
||||
>
|
||||
上移
|
||||
</Button>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
disabled={
|
||||
busy ||
|
||||
selectedPinnedIndex < 0 ||
|
||||
selectedPinnedIndex >= pinnedNavItems.length - 1
|
||||
}
|
||||
onClick={() => void movePinnedNavigation(selected.id, 1)}
|
||||
>
|
||||
下移
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
<Button
|
||||
size="sm"
|
||||
|
||||
@@ -1164,3 +1164,61 @@
|
||||
border-color: color-mix(in srgb, currentColor 26%, transparent);
|
||||
background: color-mix(in srgb, currentColor 6%, transparent);
|
||||
}
|
||||
|
||||
.extension-notifications-panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.extension-notification-list {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.extension-notification-item {
|
||||
padding: 12px 14px;
|
||||
border-radius: var(--wxex-radius-md, 10px);
|
||||
border: 1px solid var(--wxex-border);
|
||||
background: var(--wxex-bg-elevated, var(--wxex-bg-card));
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.extension-notification-item.is-unread {
|
||||
border-color: color-mix(in srgb, var(--wxex-accent, #2563eb) 45%, var(--wxex-border));
|
||||
}
|
||||
|
||||
.extension-notification-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.extension-notification-dot {
|
||||
font-size: 11px;
|
||||
padding: 1px 6px;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--wxex-accent, #2563eb) 14%, transparent);
|
||||
color: var(--wxex-accent, #2563eb);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.extension-notification-body {
|
||||
margin: 0;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
color: var(--wxex-text-secondary);
|
||||
}
|
||||
|
||||
.extension-notification-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
+8
@@ -124,6 +124,14 @@ body {
|
||||
}
|
||||
}
|
||||
|
||||
.primary-nav-divider {
|
||||
width: 28px;
|
||||
height: 1px;
|
||||
flex: 0 0 1px;
|
||||
margin: 4px auto;
|
||||
background: var(--border-subtle, rgba(0, 0, 0, 0.12));
|
||||
}
|
||||
|
||||
.primary-nav-item {
|
||||
width: 100%;
|
||||
height: 58px;
|
||||
|
||||
@@ -20,6 +20,15 @@
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.primary-nav-badge-notification {
|
||||
background: var(--wxex-accent, #2563eb);
|
||||
}
|
||||
|
||||
.primary-nav-badge-bottom {
|
||||
top: auto;
|
||||
bottom: -6px;
|
||||
}
|
||||
|
||||
.exit-monitor-page,
|
||||
.exit-monitor-manage-page {
|
||||
box-sizing: border-box;
|
||||
|
||||
@@ -33,7 +33,12 @@ export const EXTENSION_ERROR_CODES = [
|
||||
/** 目标目录已有文件 / 目标不可写;创建项目被拒绝。 */
|
||||
'EXTENSION_PROJECT_EXISTS',
|
||||
/** 检测到安装副本被用户修改,拒绝自动覆盖。 */
|
||||
'EXTENSION_MODIFIED_LOCALLY'
|
||||
'EXTENSION_MODIFIED_LOCALLY',
|
||||
'MEDIA_NOT_FOUND',
|
||||
'MEDIA_UNSUPPORTED',
|
||||
'ACCOUNT_MISMATCH',
|
||||
'CONCURRENCY_LIMITED',
|
||||
'RENDER_FAILED'
|
||||
] as const
|
||||
|
||||
export type ExtensionErrorCode = (typeof EXTENSION_ERROR_CODES)[number]
|
||||
@@ -61,7 +66,12 @@ export const EXTENSION_ERROR_MESSAGES: Record<ExtensionErrorCode, string> = {
|
||||
EXTENSION_STORAGE_CORRUPTED: '扩展配置已损坏',
|
||||
EXTENSION_SOURCE_MISSING: '开发源码目录不可用',
|
||||
EXTENSION_PROJECT_EXISTS: '目标项目目录不可用',
|
||||
EXTENSION_MODIFIED_LOCALLY: '扩展代码已被本地修改'
|
||||
EXTENSION_MODIFIED_LOCALLY: '扩展代码已被本地修改',
|
||||
MEDIA_NOT_FOUND: '找不到该消息对应的媒体资源',
|
||||
MEDIA_UNSUPPORTED: '该消息类型不支持当前媒体操作',
|
||||
ACCOUNT_MISMATCH: '消息引用不属于当前已连接账号',
|
||||
CONCURRENCY_LIMITED: '并发任务已达上限,请稍后再试',
|
||||
RENDER_FAILED: '页面渲染失败'
|
||||
}
|
||||
|
||||
export interface ExtensionErrorPayload {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { ExtensionMessageType, ExtensionSubscriptions } from './manifest'
|
||||
import { encodeExtensionMessageRef, type ExtensionMessageRef } from './media'
|
||||
|
||||
/**
|
||||
* 投递给扩展的规范化消息事件。
|
||||
@@ -11,6 +12,8 @@ import type { ExtensionMessageType, ExtensionSubscriptions } from './manifest'
|
||||
*/
|
||||
export interface ExtensionMessageEvent {
|
||||
eventId: string
|
||||
/** 跨实时事件与历史查询统一的消息引用,用于按需读取媒体与解析接口。 */
|
||||
messageRef?: string
|
||||
accountId: string
|
||||
conversationId: string
|
||||
messageId: string
|
||||
@@ -67,6 +70,7 @@ export interface BuildExtensionMessageEventInput {
|
||||
accountId: string
|
||||
conversationId: string
|
||||
messageId: string
|
||||
localId?: string
|
||||
senderId?: string
|
||||
senderName?: string
|
||||
isGroup: boolean
|
||||
@@ -79,12 +83,22 @@ export interface BuildExtensionMessageEventInput {
|
||||
}
|
||||
|
||||
export function buildExtensionMessageEvent(
|
||||
input: BuildExtensionMessageEventInput
|
||||
input: BuildExtensionMessageEventInput,
|
||||
encodeRef: (ref: ExtensionMessageRef) => string = encodeExtensionMessageRef
|
||||
): ExtensionMessageEvent {
|
||||
const type = mapWechatMessageType(input.messageType)
|
||||
const text = type === 'text' ? String(input.content ?? '') : ''
|
||||
const timestamp = Math.round(input.createTimeSeconds * 1000)
|
||||
const messageRef = encodeRef({
|
||||
accountId: input.accountId,
|
||||
conversationId: input.conversationId,
|
||||
messageId: input.messageId,
|
||||
...(input.localId ? { localId: input.localId } : {}),
|
||||
timestamp
|
||||
})
|
||||
return {
|
||||
eventId: input.eventId,
|
||||
messageRef,
|
||||
accountId: input.accountId,
|
||||
conversationId: input.conversationId,
|
||||
messageId: input.messageId,
|
||||
@@ -95,7 +109,7 @@ export function buildExtensionMessageEvent(
|
||||
type,
|
||||
...(text ? { text } : {}),
|
||||
mentionsMe: input.mentionsMe,
|
||||
timestamp: Math.round(input.createTimeSeconds * 1000)
|
||||
timestamp
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -34,6 +34,14 @@ export const EXTENSION_IPC = {
|
||||
pageUrl: 'extension:getPageUrl',
|
||||
pageRequest: 'extension:pageRequest',
|
||||
openDataDir: 'extension:openDataDir',
|
||||
pinnedNavigation: 'extension:pinnedNavigation',
|
||||
pinNavigation: 'extension:pinNavigation',
|
||||
unpinNavigation: 'extension:unpinNavigation',
|
||||
reorderNavigation: 'extension:reorderNavigation',
|
||||
notificationsList: 'extension:notificationsList',
|
||||
notificationsSummary: 'extension:notificationsSummary',
|
||||
notificationsMarkRead: 'extension:notificationsMarkRead',
|
||||
notificationsClear: 'extension:notificationsClear',
|
||||
changed: 'extension:changed'
|
||||
} as const
|
||||
|
||||
@@ -44,6 +52,8 @@ export type ExtensionChangeReason =
|
||||
| 'uninstalled'
|
||||
| 'runtime'
|
||||
| 'actions'
|
||||
| 'navigation'
|
||||
| 'notifications'
|
||||
|
||||
export interface ExtensionChangedEvent {
|
||||
extensionId: string
|
||||
|
||||
@@ -53,6 +53,27 @@ export interface ExtensionAutomationActionContribution {
|
||||
description?: string
|
||||
}
|
||||
|
||||
export const EXTENSION_NAVIGATION_ICONS = [
|
||||
'spark',
|
||||
'bot',
|
||||
'digest',
|
||||
'bell',
|
||||
'media',
|
||||
'puzzle',
|
||||
'compass',
|
||||
'message'
|
||||
] as const
|
||||
|
||||
export type ExtensionNavigationIcon = (typeof EXTENSION_NAVIGATION_ICONS)[number]
|
||||
|
||||
export interface ExtensionNavigationContribution {
|
||||
label: string
|
||||
icon?: ExtensionNavigationIcon
|
||||
/** 点击固定入口后打开的页面 id;省略时默认打开第一个页面。 */
|
||||
pageId?: string
|
||||
order?: number
|
||||
}
|
||||
|
||||
export interface ExtensionSubscriptions {
|
||||
messageTypes: ExtensionMessageType[]
|
||||
/** 空数组 = 不按会话过滤。非空时只投递这些会话。 */
|
||||
@@ -81,6 +102,7 @@ export interface ExtensionManifest {
|
||||
contributions: {
|
||||
pages: ExtensionPageContribution[]
|
||||
automationActions: ExtensionAutomationActionContribution[]
|
||||
navigation?: ExtensionNavigationContribution
|
||||
}
|
||||
}
|
||||
|
||||
@@ -281,6 +303,42 @@ function parseAutomationActions(input: unknown): ExtensionAutomationActionContri
|
||||
return actions
|
||||
}
|
||||
|
||||
function parseNavigation(
|
||||
input: unknown,
|
||||
pages: readonly ExtensionPageContribution[]
|
||||
): ExtensionNavigationContribution | undefined | null {
|
||||
if (input === undefined) return undefined
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) return null
|
||||
const raw = input as Record<string, unknown>
|
||||
const label = asTrimmedString(raw.label, 24)
|
||||
if (!label) return null
|
||||
let icon: ExtensionNavigationIcon | undefined
|
||||
if (raw.icon !== undefined) {
|
||||
const candidate = String(raw.icon).trim()
|
||||
if (!(EXTENSION_NAVIGATION_ICONS as readonly string[]).includes(candidate)) return null
|
||||
icon = candidate as ExtensionNavigationIcon
|
||||
}
|
||||
let pageId: string | undefined
|
||||
if (raw.pageId !== undefined) {
|
||||
const candidate = asTrimmedString(raw.pageId, 32)
|
||||
if (!PAGE_ID_PATTERN.test(candidate)) return null
|
||||
if (pages.length > 0 && !pages.some((page) => page.id === candidate)) return null
|
||||
pageId = candidate
|
||||
}
|
||||
let order: number | undefined
|
||||
if (raw.order !== undefined) {
|
||||
const num = Number(raw.order)
|
||||
if (!Number.isFinite(num) || num < -1000 || num > 1000) return null
|
||||
order = Math.round(num)
|
||||
}
|
||||
return {
|
||||
label,
|
||||
...(icon ? { icon } : {}),
|
||||
...(pageId ? { pageId } : {}),
|
||||
...(order !== undefined ? { order } : {})
|
||||
}
|
||||
}
|
||||
|
||||
function fail(
|
||||
message: string,
|
||||
code: ManifestParseResult['code'] = 'EXTENSION_INVALID_MANIFEST'
|
||||
@@ -359,9 +417,11 @@ export function parseExtensionManifest(
|
||||
if (pages === null) return fail('contributions.pages 不合法')
|
||||
const automationActions = parseAutomationActions(contributionsObject.automationActions)
|
||||
if (automationActions === null) return fail('contributions.automationActions 不合法')
|
||||
const navigation = parseNavigation(contributionsObject.navigation, pages)
|
||||
if (navigation === null) return fail('contributions.navigation 不合法')
|
||||
|
||||
if (pages.length > 0 && !entrypoints.page) {
|
||||
return fail('注册了页面但缺少 entrypoints.page')
|
||||
if ((pages.length > 0 || navigation !== undefined) && !entrypoints.page) {
|
||||
return fail('注册了页面或导航入口但缺少 entrypoints.page')
|
||||
}
|
||||
if ((subscriptions !== null || automationActions.length > 0) && !entrypoints.background) {
|
||||
return fail('声明了消息订阅或自动化动作,必须提供 entrypoints.background')
|
||||
@@ -391,7 +451,11 @@ export function parseExtensionManifest(
|
||||
permissions,
|
||||
entrypoints,
|
||||
...(subscriptions ? { subscriptions } : {}),
|
||||
contributions: { pages, automationActions }
|
||||
contributions: {
|
||||
pages,
|
||||
automationActions,
|
||||
...(navigation ? { navigation } : {})
|
||||
}
|
||||
}
|
||||
|
||||
if (options.appVersion) {
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
import type { ExtensionErrorPayload } from './errors'
|
||||
|
||||
const MESSAGE_REF_PREFIX = 'tmref1_'
|
||||
const MESSAGE_REF_MAX_LENGTH = 1024
|
||||
const CURSOR_PREFIX = 'tmcur1_'
|
||||
const CURSOR_MAX_LENGTH = 512
|
||||
|
||||
export interface ExtensionMessageRef {
|
||||
accountId: string
|
||||
conversationId: string
|
||||
messageId: string
|
||||
localId?: string
|
||||
/** epoch 毫秒;用于缩小媒体回查窗口与按月目录定位。 */
|
||||
timestamp?: number
|
||||
}
|
||||
|
||||
export interface ExtensionMessagesQueryCursor {
|
||||
order: 'asc' | 'desc'
|
||||
/** epoch 毫秒。 */
|
||||
timestamp: number
|
||||
messageId: string
|
||||
}
|
||||
|
||||
function bytesToBase64Url(bytes: Uint8Array): string {
|
||||
let binary = ''
|
||||
for (let index = 0; index < bytes.length; index += 1) {
|
||||
binary += String.fromCharCode(bytes[index])
|
||||
}
|
||||
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '')
|
||||
}
|
||||
|
||||
function base64UrlToBytes(value: string): Uint8Array | null {
|
||||
if (!/^[A-Za-z0-9_-]+$/.test(value)) return null
|
||||
const normalized = value.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4)
|
||||
try {
|
||||
const binary = atob(padded)
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let index = 0; index < binary.length; index += 1) {
|
||||
bytes[index] = binary.charCodeAt(index)
|
||||
}
|
||||
return bytes
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function isSafeToken(value: unknown, maxLength: number): value is string {
|
||||
if (typeof value !== 'string') return false
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed || trimmed.length > maxLength) return false
|
||||
for (let index = 0; index < trimmed.length; index += 1) {
|
||||
if (trimmed.charCodeAt(index) < 32) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/** 生成跨实时事件与历史查询统一的 opaque messageRef。 */
|
||||
export function encodeExtensionMessageRef(input: ExtensionMessageRef): string {
|
||||
const accountId = String(input.accountId || '').trim()
|
||||
const conversationId = String(input.conversationId || '').trim()
|
||||
const messageId = String(input.messageId || '').trim()
|
||||
if (!conversationId || !messageId) {
|
||||
throw new Error('消息引用缺少会话或消息标识')
|
||||
}
|
||||
const payload: Record<string, unknown> = {
|
||||
v: 1,
|
||||
a: accountId,
|
||||
c: conversationId,
|
||||
m: messageId
|
||||
}
|
||||
const localId = input.localId !== undefined ? String(input.localId).trim() : ''
|
||||
if (localId) payload.l = localId
|
||||
if (typeof input.timestamp === 'number' && Number.isFinite(input.timestamp) && input.timestamp > 0) {
|
||||
payload.t = Math.round(input.timestamp)
|
||||
}
|
||||
const encoded = bytesToBase64Url(new TextEncoder().encode(JSON.stringify(payload)))
|
||||
return `${MESSAGE_REF_PREFIX}${encoded}`
|
||||
}
|
||||
|
||||
/** 还原 opaque messageRef;支持带宿主签名后缀的格式,篡改、超长或字段缺失一律返回 null。 */
|
||||
export function decodeExtensionMessageRef(value: unknown): ExtensionMessageRef | null {
|
||||
if (typeof value !== 'string') return null
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed.startsWith(MESSAGE_REF_PREFIX) || trimmed.length > MESSAGE_REF_MAX_LENGTH) {
|
||||
return null
|
||||
}
|
||||
const dotIndex = trimmed.indexOf('.')
|
||||
const body = dotIndex > 0 ? trimmed.slice(MESSAGE_REF_PREFIX.length, dotIndex) : trimmed.slice(MESSAGE_REF_PREFIX.length)
|
||||
if (dotIndex > 0) {
|
||||
const suffix = trimmed.slice(dotIndex + 1)
|
||||
if (!/^[A-Za-z0-9_-]{16,64}$/.test(suffix)) return null
|
||||
}
|
||||
const bytes = base64UrlToBytes(body)
|
||||
if (!bytes) return null
|
||||
try {
|
||||
const parsed = JSON.parse(new TextDecoder().decode(bytes)) as Record<string, unknown>
|
||||
if (!parsed || typeof parsed !== 'object' || parsed.v !== 1) return null
|
||||
if (!isSafeToken(parsed.c, 160) || !isSafeToken(parsed.m, 160)) return null
|
||||
const accountId = typeof parsed.a === 'string' ? parsed.a.trim() : ''
|
||||
if (accountId.length > 160) return null
|
||||
for (let index = 0; index < accountId.length; index += 1) {
|
||||
if (accountId.charCodeAt(index) < 32) return null
|
||||
}
|
||||
const localId = isSafeToken(parsed.l, 120) ? parsed.l.trim() : undefined
|
||||
const timestamp =
|
||||
typeof parsed.t === 'number' && Number.isFinite(parsed.t) && parsed.t > 0
|
||||
? Math.round(parsed.t)
|
||||
: undefined
|
||||
return {
|
||||
accountId,
|
||||
conversationId: parsed.c.trim(),
|
||||
messageId: parsed.m.trim(),
|
||||
...(localId ? { localId } : {}),
|
||||
...(timestamp !== undefined ? { timestamp } : {})
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** 编码分页游标:以 (timestamp, messageId) 元组保证同秒多消息不漏不重。 */
|
||||
export function encodeMessagesQueryCursor(cursor: ExtensionMessagesQueryCursor): string {
|
||||
const payload = {
|
||||
v: 1,
|
||||
o: cursor.order === 'desc' ? 'desc' : 'asc',
|
||||
t: Math.round(cursor.timestamp),
|
||||
m: cursor.messageId
|
||||
}
|
||||
return `${CURSOR_PREFIX}${bytesToBase64Url(new TextEncoder().encode(JSON.stringify(payload)))}`
|
||||
}
|
||||
|
||||
export function decodeMessagesQueryCursor(value: unknown): ExtensionMessagesQueryCursor | null {
|
||||
if (typeof value !== 'string') return null
|
||||
const trimmed = value.trim()
|
||||
if (!trimmed.startsWith(CURSOR_PREFIX) || trimmed.length > CURSOR_MAX_LENGTH) return null
|
||||
const bytes = base64UrlToBytes(trimmed.slice(CURSOR_PREFIX.length))
|
||||
if (!bytes) return null
|
||||
try {
|
||||
const parsed = JSON.parse(new TextDecoder().decode(bytes)) as Record<string, unknown>
|
||||
if (!parsed || typeof parsed !== 'object' || parsed.v !== 1) return null
|
||||
if (parsed.o !== 'asc' && parsed.o !== 'desc') return null
|
||||
if (typeof parsed.t !== 'number' || !Number.isFinite(parsed.t)) return null
|
||||
if (!isSafeToken(parsed.m, 160)) return null
|
||||
return {
|
||||
order: parsed.o,
|
||||
timestamp: Math.round(parsed.t),
|
||||
messageId: parsed.m.trim()
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export interface ExtensionMediaReadImageRequest {
|
||||
messageRef: string
|
||||
quality?: 'original' | 'thumbnail'
|
||||
}
|
||||
|
||||
export interface ExtensionMediaReadImageResult {
|
||||
messageRef: string
|
||||
mimeType: string
|
||||
bytes: number
|
||||
sha256: string
|
||||
/** 位于扩展私有数据目录内的可读副本路径,不暴露原始微信目录。 */
|
||||
path: string
|
||||
/** 扩展沙箱页面可直接加载的受控只读预览地址(tm-extension://)。 */
|
||||
previewUrl?: string
|
||||
quality: 'original' | 'thumbnail'
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export interface ExtensionMediaReadVoiceRequest {
|
||||
messageRef: string
|
||||
}
|
||||
|
||||
export interface ExtensionMediaReadVoiceResult {
|
||||
messageRef: string
|
||||
mimeType: 'audio/wav'
|
||||
bytes: number
|
||||
sha256: string
|
||||
durationMs?: number
|
||||
/** 位于扩展私有数据目录内的 WAV 副本路径。 */
|
||||
path: string
|
||||
/** 扩展沙箱页面可直接加载的受控只读预览地址(tm-extension://)。 */
|
||||
previewUrl?: string
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export interface ExtensionMediaReadVideoRequest {
|
||||
messageRef: string
|
||||
}
|
||||
|
||||
export interface ExtensionMediaReadVideoResult {
|
||||
messageRef: string
|
||||
mimeType: 'video/mp4'
|
||||
bytes: number
|
||||
sha256: string
|
||||
/** 位于扩展私有数据目录内的视频副本路径。 */
|
||||
path: string
|
||||
/** 扩展沙箱页面可直接加载的受控只读预览地址(tm-extension://)。 */
|
||||
previewUrl?: string
|
||||
posterPath?: string
|
||||
posterPreviewUrl?: string
|
||||
durationMs?: number
|
||||
width?: number
|
||||
height?: number
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export interface ExtensionMediaOcrImageRequest {
|
||||
messageRef: string
|
||||
language?: string
|
||||
force?: boolean
|
||||
}
|
||||
|
||||
export interface ExtensionMediaOcrImageResult {
|
||||
messageRef: string
|
||||
text: string
|
||||
language: string | null
|
||||
engine: string
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export interface ExtensionMediaTranscribeVoiceRequest {
|
||||
messageRef: string
|
||||
force?: boolean
|
||||
/** 最多同步等待毫秒数,超时仍未完成时返回 `state: 'pending'`。 */
|
||||
waitMs?: number
|
||||
}
|
||||
|
||||
export interface ExtensionMediaTranscribeVoiceResult {
|
||||
messageRef: string
|
||||
state: 'transcribed' | 'pending' | 'failed'
|
||||
transcript?: string
|
||||
durationMs?: number
|
||||
cached: boolean
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface ExtensionMediaAnalyzeImageRequest {
|
||||
messageRef: string
|
||||
prompt?: string
|
||||
force?: boolean
|
||||
}
|
||||
|
||||
export interface ExtensionMediaAnalyzeImageResult {
|
||||
messageRef: string
|
||||
description: string
|
||||
ocrText?: string
|
||||
tags?: string[]
|
||||
category?: string
|
||||
model?: string
|
||||
cached: boolean
|
||||
}
|
||||
|
||||
export type ExtensionMediaBatchOperation =
|
||||
| 'readImage'
|
||||
| 'readVoice'
|
||||
| 'readVideo'
|
||||
| 'ocrImage'
|
||||
| 'transcribeVoice'
|
||||
| 'analyzeImage'
|
||||
|
||||
export interface ExtensionMediaBatchItem {
|
||||
op: ExtensionMediaBatchOperation
|
||||
messageRef: string
|
||||
options?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface ExtensionMediaBatchRequest {
|
||||
items: ExtensionMediaBatchItem[]
|
||||
concurrency?: number
|
||||
}
|
||||
|
||||
export interface ExtensionMediaBatchItemResult {
|
||||
index: number
|
||||
op: ExtensionMediaBatchOperation
|
||||
messageRef: string
|
||||
ok: boolean
|
||||
result?:
|
||||
| ExtensionMediaReadImageResult
|
||||
| ExtensionMediaReadVoiceResult
|
||||
| ExtensionMediaReadVideoResult
|
||||
| ExtensionMediaOcrImageResult
|
||||
| ExtensionMediaTranscribeVoiceResult
|
||||
| ExtensionMediaAnalyzeImageResult
|
||||
error?: ExtensionErrorPayload
|
||||
}
|
||||
|
||||
export interface ExtensionMediaBatchResult {
|
||||
results: ExtensionMediaBatchItemResult[]
|
||||
}
|
||||
@@ -3,12 +3,18 @@
|
||||
export const EXTENSION_PERMISSIONS = [
|
||||
'messages.subscribe',
|
||||
'messages.query',
|
||||
'media.read',
|
||||
'media.ocr',
|
||||
'media.transcribe',
|
||||
'contacts.list',
|
||||
'wechat.send.text',
|
||||
'wechat.send.image',
|
||||
'wechat.send.video',
|
||||
'wechat.send.voice',
|
||||
'ai.chat',
|
||||
'ai.vision',
|
||||
'render.html',
|
||||
'notifications.create',
|
||||
'storage',
|
||||
'automation.action',
|
||||
'secrets'
|
||||
@@ -42,6 +48,22 @@ export const EXTENSION_PERMISSION_INFO: Record<ExtensionPermission, ExtensionPer
|
||||
description: '按会话与时间窗口读取有上限的历史消息,不能遍历全部会话。',
|
||||
risk: 'high'
|
||||
},
|
||||
'media.read': {
|
||||
label: '按需读取消息媒体',
|
||||
description:
|
||||
'通过 messageRef 按需读取指定消息关联的图片、语音或视频副本;原始数据库路径与密钥不会暴露给扩展。',
|
||||
risk: 'high'
|
||||
},
|
||||
'media.ocr': {
|
||||
label: '本地图片文字识别',
|
||||
description: '对指定图片消息执行本机系统 OCR 识别,仅在本地运行,不上传原图。',
|
||||
risk: 'medium'
|
||||
},
|
||||
'media.transcribe': {
|
||||
label: '本地语音转文字',
|
||||
description: '对指定语音消息执行本机语音识别并复用已有转写缓存。',
|
||||
risk: 'medium'
|
||||
},
|
||||
'contacts.list': {
|
||||
label: '读取群列表',
|
||||
description: '读取本机通讯录中的群名称与会话 id,用于配置页选择发送目标;不包含聊天内容。',
|
||||
@@ -75,6 +97,21 @@ export const EXTENSION_PERMISSION_INFO: Record<ExtensionPermission, ExtensionPer
|
||||
description: '使用 TraceMemo 已配置的 AI Provider 发起对话;扩展拿不到 API Key 明文。',
|
||||
risk: 'medium'
|
||||
},
|
||||
'ai.vision': {
|
||||
label: '调用 AI 图片理解',
|
||||
description: '使用 TraceMemo 已配置的视觉模型理解指定图片消息;扩展拿不到 API Key 明文。',
|
||||
risk: 'medium'
|
||||
},
|
||||
'render.html': {
|
||||
label: '渲染静态 HTML 长图',
|
||||
description: '在隔离离线窗口中将静态 HTML/CSS 渲染为 PNG 长图,仅输出到该扩展自己的私有目录。',
|
||||
risk: 'low'
|
||||
},
|
||||
'notifications.create': {
|
||||
label: '发送应用内通知',
|
||||
description: '向 TraceMemo 扩展通知中心写入带级别的通知,支持未读角标与跳转到本扩展页面。',
|
||||
risk: 'medium'
|
||||
},
|
||||
storage: {
|
||||
label: '扩展私有存储',
|
||||
description: '读写本扩展独立的数据目录,不会接触其他扩展或官方数据。',
|
||||
|
||||
@@ -10,6 +10,17 @@ export type ExtensionHostCallMethod =
|
||||
| 'storage.remove'
|
||||
| 'storage.list'
|
||||
| 'messages.query'
|
||||
| 'media.readImage'
|
||||
| 'media.readVoice'
|
||||
| 'media.readVideo'
|
||||
| 'media.ocrImage'
|
||||
| 'media.transcribeVoice'
|
||||
| 'media.analyzeImage'
|
||||
| 'media.batch'
|
||||
| 'render.htmlToImage'
|
||||
| 'notifications.create'
|
||||
| 'notifications.list'
|
||||
| 'notifications.markRead'
|
||||
| 'wechat.send.text'
|
||||
| 'wechat.send.image'
|
||||
| 'wechat.send.video'
|
||||
@@ -187,10 +198,16 @@ export interface ExtensionMessagesQueryRequest {
|
||||
/** epoch **毫秒**。 */
|
||||
endTime?: number
|
||||
limit?: number
|
||||
/** 上一页返回的 opaque 游标;与 order 配合保证同时间戳消息不漏不重。 */
|
||||
cursor?: string
|
||||
order?: 'asc' | 'desc'
|
||||
types?: string[]
|
||||
}
|
||||
|
||||
export interface ExtensionQueriedMessage {
|
||||
messageId: string
|
||||
/** 跨实时事件与历史查询统一的消息引用,可直接传给 tm.media.* 接口。 */
|
||||
messageRef?: string
|
||||
conversationId: string
|
||||
senderId?: string
|
||||
senderName?: string
|
||||
@@ -201,6 +218,12 @@ export interface ExtensionQueriedMessage {
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
export interface ExtensionMessagesQueryResult {
|
||||
messages: ExtensionQueriedMessage[]
|
||||
nextCursor?: string
|
||||
hasMore: boolean
|
||||
}
|
||||
|
||||
export interface ExtensionSendTextRequest {
|
||||
/** 群为 `xxx@chatroom`,私聊为 wxid。 */
|
||||
to: string
|
||||
@@ -239,3 +262,53 @@ export interface ExtensionSendTextResult {
|
||||
actionId: string
|
||||
status: 'sent'
|
||||
}
|
||||
|
||||
export interface ExtensionRenderHtmlToImageRequest {
|
||||
html: string
|
||||
css?: string
|
||||
/** 可选相对文件名(自动落盘至扩展私有目录的 rendered/ 下)。 */
|
||||
fileName?: string
|
||||
width?: number
|
||||
maxHeight?: number
|
||||
backgroundColor?: string
|
||||
timeoutMs?: number
|
||||
}
|
||||
|
||||
export interface ExtensionRenderHtmlToImageResult {
|
||||
path: string
|
||||
/** 扩展沙箱页面可直接加载的受控只读预览地址(tm-extension://)。 */
|
||||
previewUrl?: string
|
||||
width: number
|
||||
height: number
|
||||
pixelWidth?: number
|
||||
pixelHeight?: number
|
||||
deviceScaleFactor?: number
|
||||
bytes: number
|
||||
mimeType: 'image/png'
|
||||
sha256: string
|
||||
}
|
||||
|
||||
export type ExtensionNotificationLevel = 'info' | 'success' | 'warning' | 'error'
|
||||
|
||||
export interface ExtensionNotificationCreateRequest {
|
||||
title: string
|
||||
body?: string
|
||||
level?: ExtensionNotificationLevel
|
||||
dedupeKey?: string
|
||||
pageId?: string
|
||||
}
|
||||
|
||||
export interface ExtensionNotificationCreateResult {
|
||||
id: string
|
||||
deduped: boolean
|
||||
createdAt: number
|
||||
}
|
||||
|
||||
export interface ExtensionNotificationMarkReadRequest {
|
||||
id?: string
|
||||
all?: boolean
|
||||
}
|
||||
|
||||
export interface ExtensionNotificationMarkReadResult {
|
||||
changed: number
|
||||
}
|
||||
@@ -1,4 +1,9 @@
|
||||
import type { ExtensionCompatibility } from './manifest'
|
||||
import type {
|
||||
ExtensionCompatibility,
|
||||
ExtensionNavigationContribution,
|
||||
ExtensionNavigationIcon
|
||||
} from './manifest'
|
||||
import type { ExtensionNotificationLevel } from './rpc'
|
||||
import type { ExtensionPermission } from './permissions'
|
||||
import type { ExtensionErrorPayload } from './errors'
|
||||
import type { ExtensionSource } from './source'
|
||||
@@ -58,12 +63,45 @@ export interface InstalledExtension {
|
||||
pendingPermissions: ExtensionPermission[]
|
||||
runtime: ExtensionRuntimeSnapshot
|
||||
pages: Array<{ id: string; title: string }>
|
||||
navigation?: ExtensionNavigationContribution
|
||||
pinnedToNav?: boolean
|
||||
automationActions: ExtensionAutomationActionSummary[]
|
||||
/** 扩展目录是否仍然存在;false 时 UI 必须显示为「文件缺失」而不是可启动。 */
|
||||
filesPresent: boolean
|
||||
storage: ExtensionStorageHealthSummary
|
||||
}
|
||||
|
||||
export interface PinnedExtensionNavItem {
|
||||
extensionId: string
|
||||
extensionName: string
|
||||
label: string
|
||||
icon: ExtensionNavigationIcon
|
||||
pageId?: string
|
||||
order: number
|
||||
enabled: boolean
|
||||
}
|
||||
|
||||
export interface ExtensionNotificationItem {
|
||||
id: string
|
||||
extensionId: string
|
||||
extensionName: string
|
||||
title: string
|
||||
body?: string
|
||||
level: ExtensionNotificationLevel
|
||||
dedupeKey?: string
|
||||
pageId?: string
|
||||
read: boolean
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
|
||||
export interface ExtensionNotificationSummary {
|
||||
totalUnread: number
|
||||
/** 未固定到一级导航的扩展未读总数,聚合展示在扩展中心入口。 */
|
||||
unpinnedUnread: number
|
||||
unreadByExtension: Record<string, number>
|
||||
}
|
||||
|
||||
/** 从其它页面跳到扩展中心时的定位目标。 */
|
||||
export interface ExtensionDeepLink {
|
||||
/** 定位官方模板(打开模板画廊并展开该卡片)。 */
|
||||
|
||||
Reference in new issue
Block a user