feat: 新增拓展中心功能, 提供 关键词回复 去水印模板

This commit is contained in:
Wxw-Gu committed 2026-11-13 17:54:37 +08:00
1 parent aca103cb96
commit b9ad4e1d71
85 files changed
+14750 -106

No files matched your search

@@ -0,0 +1,134 @@
import type { ExtensionAutomationActionContribution } from '../../shared/extensions/manifest'
import type { ExtensionAutomationActionSummary } from '../../shared/extensions/types'
export interface RegisteredExtensionAction {
extensionId: string
extensionName: string
actionId: string
title: string
description?: string
/** 后台进程是否真的注册了这个动作。 */
registered: boolean
/** manifest 是否声明了它(声明了但没注册 = 扩展代码有问题)。 */
declared: boolean
}
/**
* 扩展贡献的自动化动作注册表。
*
* 两个来源刻意分开记:
* - `declared`:manifest 里写了什么 —— 用于在规则编辑器里展示「这个扩展提供了哪些动作」;
* - `registered`:后台进程运行期真正注册了什么 —— 只有它能被执行。
*
* 二者不一致时**不猜**:动作在界面上显示为不可用,规则执行时明确报错。
*/
export class ExtensionActionRegistry {
private readonly registered = new Map<
string,
Map<string, { title: string; description?: string }>
>()
private readonly declared = new Map<
string,
{ name: string; actions: ExtensionAutomationActionContribution[] }
>()
private readonly names = new Map<string, string>()
setDeclared(
extensionId: string,
extensionName: string,
actions: ExtensionAutomationActionContribution[]
): void {
this.names.set(extensionId, extensionName)
this.declared.set(extensionId, { name: extensionName, actions: [...actions] })
}
setRegistered(
extensionId: string,
extensionName: string,
actions: Array<{ id: string; title: string; description?: string }>
): void {
this.names.set(extensionId, extensionName)
this.registered.set(
extensionId,
new Map(
actions.map((action) => [
action.id,
{
title: action.title,
...(action.description ? { description: action.description } : {})
}
])
)
)
}
remove(extensionId: string): void {
this.registered.delete(extensionId)
this.declared.delete(extensionId)
this.names.delete(extensionId)
}
removeRuntime(extensionId: string): void {
this.registered.delete(extensionId)
}
isRegistered(extensionId: string, actionId: string): boolean {
return this.registered.get(extensionId)?.has(actionId) === true
}
get(extensionId: string, actionId: string): RegisteredExtensionAction | undefined {
const declaredAction = this.declared
.get(extensionId)
?.actions.find((action) => action.id === actionId)
const runtime = this.registered.get(extensionId)?.get(actionId)
if (!declaredAction && !runtime) return undefined
return {
extensionId,
extensionName: this.names.get(extensionId) || extensionId,
actionId,
title: runtime?.title || declaredAction?.title || actionId,
...(runtime?.description || declaredAction?.description
? { description: runtime?.description || declaredAction?.description }
: {}),
registered: Boolean(runtime),
declared: Boolean(declaredAction)
}
}
list(): RegisteredExtensionAction[] {
const result: RegisteredExtensionAction[] = []
const extensionIds = new Set([...this.declared.keys(), ...this.registered.keys()])
for (const extensionId of extensionIds) {
const declaredActions = this.declared.get(extensionId)?.actions ?? []
const runtimeActions = this.registered.get(extensionId) ?? new Map()
const ids = new Set([...declaredActions.map((action) => action.id), ...runtimeActions.keys()])
for (const actionId of ids) {
const action = this.get(extensionId, actionId)
if (action) result.push(action)
}
}
return result.sort((left, right) => {
if (left.extensionName !== right.extensionName)
return left.extensionName.localeCompare(right.extensionName)
return left.title.localeCompare(right.title)
})
}
summariesFor(extensionId: string): ExtensionAutomationActionSummary[] {
const declaredActions = this.declared.get(extensionId)?.actions ?? []
const runtimeActions = this.registered.get(extensionId) ?? new Map()
const ids = new Set([...declaredActions.map((action) => action.id), ...runtimeActions.keys()])
return Array.from(ids).map((actionId) => {
const declaredAction = declaredActions.find((action) => action.id === actionId)
const runtime = runtimeActions.get(actionId)
return {
id: actionId,
title: runtime?.title || declaredAction?.title || actionId,
...(runtime?.description || declaredAction?.description
? { description: runtime?.description || declaredAction?.description }
: {}),
registered: Boolean(runtime)
}
})
}
}
@@ -0,0 +1,45 @@
import { ExtensionError } from '../../shared/extensions/errors'
import { hasExtensionPermission } from '../../shared/extensions/permissions'
import type { ExtensionAutomationActionOutput } from '../../shared/extensions/rpc'
import type { ExtensionMessageEvent } from '../../shared/extensions/events'
import { getExtensionManager, hasExtensionManager } from './extension-service'
export interface ExtensionActionContext {
conversationId: string
isGroup: boolean
accountId: string
message?: ExtensionMessageEvent
}
/**
* 自动化 → 扩展动作的桥。
*
* 输入里的 `conversationId` / `accountId` / `message` 是**宿主注入的运行时上下文**,
* 与用户在规则里配置的静态 `input` 合并;同名键以宿主值为准,扩展不能靠配置
* 伪造一个假的会话或账号。
*/
export async function invokeExtensionAction(
extensionId: string,
actionId: string,
input: Record<string, unknown>,
context: ExtensionActionContext
): Promise<ExtensionAutomationActionOutput> {
if (!hasExtensionManager()) {
throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展系统尚未初始化')
}
const runtimeInput: Record<string, unknown> = {
...input,
conversationId: context.conversationId,
isGroup: context.isGroup,
accountId: context.accountId,
...(context.message ? { message: context.message } : {})
}
return getExtensionManager().invokeAutomationAction(extensionId, actionId, runtimeInput)
}
export function canExtensionSendText(extensionId: string): boolean {
if (!hasExtensionManager()) return false
const extension = getExtensionManager().get(extensionId)
if (!extension?.enabled) return false
return hasExtensionPermission(extension.grantedPermissions, 'wechat.send.text')
}
@@ -0,0 +1,74 @@
import { mapLicenseStatus, probeLicenseStatus } from '../services/msg-insert-capability-service'
import { macWechatRuntimeManager } from '../services/mac-wechat-runtime-manager'
export interface ExtensionEntitlementResult {
ok: boolean
message: string
source: 'mac_license' | 'hook_license' | 'unsupported'
}
export interface ExtensionEntitlementDependencies {
platform?: NodeJS.Platform
getMacLicense?: () => Promise<{ authorized: boolean; message?: string }>
probeLicense?: () => Promise<{ ok: boolean; status?: string }>
}
/**
* 扩展发送的 授权校验。
*
* 只在主进程可信边界调用,且**不接受渲染层 / 扩展传入的任何布尔值**:
* - macOS:读 Native Runtime 的 license 状态,要求 `authorized === true`;
* - Windows:探测本机 Hook 的 `/license/status`,只接受 `LICENSE_OK`。
*
* 与「发送能力 ready」是两件事:能力 ready 只说明本机装好了 Runtime,
* 不代表授权有效。
*/
export async function checkExtensionSendEntitlement(
dependencies: ExtensionEntitlementDependencies = {}
): Promise<ExtensionEntitlementResult> {
const platform = dependencies.platform ?? process.platform
if (platform === 'darwin') {
try {
const status = dependencies.getMacLicense
? await dependencies.getMacLicense()
: await macWechatRuntimeManager.getMacLicenseStatus()
if (status.authorized) {
return { ok: true, message: '授权有效', source: 'mac_license' }
}
return {
ok: false,
message: status.message || '需要有效授权才能由扩展发送消息',
source: 'mac_license'
}
} catch (error) {
return {
ok: false,
message: error instanceof Error ? error.message : '无法确认授权状态',
source: 'mac_license'
}
}
}
if (platform === 'win32') {
try {
const probe = dependencies.probeLicense
? await dependencies.probeLicense()
: await probeLicenseStatus()
if (!probe.ok) {
return { ok: false, message: '无法确认授权状态', source: 'hook_license' }
}
const mapped = mapLicenseStatus(probe.status)
return {
ok: mapped.entitlement === 'valid',
message: mapped.message,
source: 'hook_license'
}
} catch (error) {
return {
ok: false,
message: error instanceof Error ? error.message : '无法确认授权状态',
source: 'hook_license'
}
}
}
return { ok: false, message: '当前平台不支持微信发送', source: 'unsupported' }
}
+135
View File
@@ -0,0 +1,135 @@
import { createHash } from 'node:crypto'
import type { ExtensionEventEnvelope } from '../../shared/extensions/events'
import {
buildExtensionMessageEvent,
EXTENSION_EVENT_PROTOCOL_VERSION,
shouldDeliverExtensionEvent,
type ExtensionMessageEvent
} from '../../shared/extensions/events'
import type { ExtensionSubscriptions } from '../../shared/extensions/manifest'
import type { NormalizedIncomingMessage } from '../services/message-listener-service'
const DEDUPE_TTL_MS = 10 * 60 * 1000
const DEDUPE_MAX_ENTRIES = 5_000
export interface ExtensionEventSubscriber {
extensionId: string
subscriptions: ExtensionSubscriptions | undefined
deliver: (envelope: ExtensionEventEnvelope) => boolean
}
export interface ExtensionEventBusDependencies {
listSubscribers: () => ExtensionEventSubscriber[]
getAccountId: () => string
getSelfUsernames: () => string[]
now?: () => number
onDelivered?: (extensionId: string, event: ExtensionMessageEvent) => void
}
export interface ExtensionEventBusStats {
received: number
deduped: number
delivered: number
dropped: number
}
/**
* 把 MessageListener 的规范化消息分发给扩展。
*
* 去重键 `sessionId:localId`,扩展侧独立保留一层,避免进程重启后补投重复;
* 旧 Runtime 只能回读最近活跃会话,能力诊断会如实标记降级。
*/
export class ExtensionEventBus {
private readonly seen = new Map<string, number>()
private readonly now: () => number
private accountId = ''
private counters: ExtensionEventBusStats = { received: 0, deduped: 0, delivered: 0, dropped: 0 }
constructor(private readonly dependencies: ExtensionEventBusDependencies) {
this.now = dependencies.now ?? (() => Date.now())
}
/** 切换账号时清空去重表:旧账号的 localId 不能在新账号下命中。 */
setAccountId(accountId: string): void {
const next = String(accountId || '').trim()
if (next === this.accountId) return
this.accountId = next
this.seen.clear()
}
stats(): ExtensionEventBusStats {
return { ...this.counters }
}
/** 入口**绝不抛**:它挂在 MessageListener 的投递循环上。 */
handleMessage(message: NormalizedIncomingMessage): void {
try {
this.counters.received += 1
const eventId = buildEventId(message.sessionId, message.localId)
if (!this.markSeen(eventId)) {
this.counters.deduped += 1
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 envelope: ExtensionEventEnvelope = {
version: EXTENSION_EVENT_PROTOCOL_VERSION,
kind: 'message.received',
event
}
for (const subscriber of this.dependencies.listSubscribers()) {
if (!shouldDeliverExtensionEvent(subscriber.subscriptions, event)) continue
if (subscriber.deliver(envelope)) {
this.counters.delivered += 1
this.dependencies.onDelivered?.(subscriber.extensionId, event)
} else {
this.counters.dropped += 1
}
}
} catch (error) {
console.warn(
`[ExtensionEventBus] dispatch failed: ${error instanceof Error ? error.message : String(error)}`
)
}
}
private markSeen(eventId: string): boolean {
const now = this.now()
if (this.seen.has(eventId)) return false
this.seen.set(eventId, now)
if (this.seen.size > DEDUPE_MAX_ENTRIES) {
for (const [key, at] of this.seen) {
if (now - at > DEDUPE_TTL_MS) this.seen.delete(key)
}
if (this.seen.size > DEDUPE_MAX_ENTRIES) {
const overflow = this.seen.size - DEDUPE_MAX_ENTRIES
let removed = 0
for (const key of this.seen.keys()) {
this.seen.delete(key)
removed += 1
if (removed >= overflow) break
}
}
}
return true
}
}
export function buildEventId(sessionId: string, localId: string): string {
const digest = createHash('sha1').update(`${sessionId}\u0001${localId}`).digest('hex')
return `message:${digest}`
}
+677
View File
@@ -0,0 +1,677 @@
import { fork, type ChildProcess } from 'node:child_process'
import { randomUUID } from 'node:crypto'
import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors'
import type { ExtensionRuntimeSnapshot } from '../../shared/extensions/types'
import {
sortPermissionsByRisk,
type ExtensionPermission
} from '../../shared/extensions/permissions'
import { EXTENSION_API_VERSION } from '../../shared/extensions/manifest'
import {
EXTENSION_HOST_PROTOCOL_VERSION,
type ExtensionAutomationActionOutput,
type ExtensionHostCall,
type ExtensionHostCallMethod,
type ExtensionHostInboundMessage,
type ExtensionHostOutboundMessage,
type ExtensionMessagesQueryRequest,
type ExtensionQueriedMessage,
type ExtensionSendImageRequest,
type ExtensionSendTextRequest,
type ExtensionSendTextResult,
type ExtensionSendVideoRequest
} from '../../shared/extensions/rpc'
import type { ExtensionEventEnvelope } from '../../shared/extensions/events'
import type { ExtensionCapabilitySnapshot } from '../../shared/extensions/types'
import type { ExtensionStorage } from './extension-storage'
const DEFAULT_ACTIVATE_TIMEOUT_MS = 8_000
const DEFAULT_ACTION_TIMEOUT_MS = 15_000
const MAX_RESTARTS = 3
const RESTART_WINDOW_MS = 5 * 60 * 1000
const RESTART_BASE_DELAY_MS = 1_000
const EVENT_BUCKET_CAPACITY = 100
const EVENT_REFILL_PER_SECOND = 60
export interface ExtensionHostChild {
send(message: unknown): void
kill(): void
on(event: 'message', listener: (message: unknown) => void): void
on(event: 'exit', listener: (code: number | null, signal: string | null) => void): void
on(event: 'error', listener: (error: Error) => void): void
once?(event: 'exit', listener: () => void): void
readonly pid?: number
}
export interface ExtensionHostSpawnOptions {
extensionId: string
extensionDir: string
}
export interface ExtensionHostDependencies {
extensionId: string
extensionDir: string
/** 扩展私有数据目录;媒体文件只允许从这里或临时目录发送。 */
dataDir: string
permissions: ExtensionPermission[]
storage: ExtensionStorage
spawn: (options: ExtensionHostSpawnOptions) => ExtensionHostChild
onLog?: (level: 'info' | 'warn' | 'error', message: string) => void
onStateChange?: (snapshot: ExtensionRuntimeSnapshot) => void
onActionsChanged?: () => void
queryMessages?: (
extensionId: string,
request: ExtensionMessagesQueryRequest
) => Promise<ExtensionQueriedMessage[]>
sendText?: (
extensionId: string,
request: ExtensionSendTextRequest
) => Promise<ExtensionSendTextResult>
sendImage?: (
extensionId: string,
request: ExtensionSendImageRequest
) => Promise<ExtensionSendTextResult>
sendVideo?: (
extensionId: string,
request: ExtensionSendVideoRequest
) => Promise<ExtensionSendTextResult>
aiChat?: (
extensionId: string,
messages: Array<{ role: string; content: string }>
) => Promise<{ text: string }>
capabilities?: (extensionId: string) => Promise<ExtensionCapabilitySnapshot>
now?: () => number
activateTimeoutMs?: number
actionTimeoutMs?: number
}
interface PendingAction {
resolve: (value: ExtensionAutomationActionOutput) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
}
interface RegisteredAction {
id: string
title: string
description?: string
}
interface ActivationWaiter {
resolve: () => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
child: ExtensionHostChild
}
/**
* 单个扩展的后台进程。
*
* **隔离边界**:每个扩展一个独立 Node 子进程,`require` 只发生在那里面;
* 主进程从不 `require` 扩展代码。子进程拿不到 Electron API、数据库句柄、
* 授权凭据或原生发送通道 —— 它只能通过本类转发的白名单 RPC 申请能力。
*
* ⚠️ 独立进程不等于强沙箱:后台仍是任意 Node 代码,安装时按「受信任本地开发者扩展」处理。
*/
export class ExtensionHost {
private readonly dependencies: ExtensionHostDependencies
private readonly storage: ExtensionStorage
private readonly now: () => number
private child: ExtensionHostChild | null = null
private state: ExtensionRuntimeSnapshot
private stopping = false
private activation: Promise<void> | null = null
private activationWaiter: ActivationWaiter | null = null
private restartTimer: ReturnType<typeof setTimeout> | null = null
private readonly pendingActions = new Map<string, PendingAction>()
private readonly testHandlers = new Map<
string,
{
resolve: (value: unknown) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
}
>()
private readonly actions = new Map<string, RegisteredAction>()
private eventTokens = EVENT_BUCKET_CAPACITY
private eventTokensAt: number
private droppedEvents = 0
private mutedDropLog = false
private restartTimestamps: number[] = []
constructor(dependencies: ExtensionHostDependencies) {
this.dependencies = dependencies
this.storage = dependencies.storage
this.now = dependencies.now ?? (() => Date.now())
this.eventTokensAt = this.now()
this.state = { state: 'inactive', since: this.now(), restarts: 0 }
}
snapshot(): ExtensionRuntimeSnapshot {
return { ...this.state }
}
registeredActions(): RegisteredAction[] {
return Array.from(this.actions.values()).map((action) => ({ ...action }))
}
async testSend(params: Record<string, unknown>): Promise<unknown> {
return this.runTestMessage('test-send', params)
}
private async runTestMessage(
type: 'test-send',
params: Record<string, unknown>
): Promise<unknown> {
if (this.state.state !== 'active' || !this.child) {
throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
}
const requestId = randomUUID()
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
this.testHandlers.delete(requestId)
reject(new ExtensionError('ACTION_TIMEOUT'))
}, 450_000)
this.testHandlers.set(requestId, { resolve, reject, timer })
try {
this.child?.send({
type,
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId,
params
})
} catch (error) {
clearTimeout(timer)
this.testHandlers.delete(requestId)
reject(
new ExtensionError(
'EXTENSION_HOST_UNAVAILABLE',
error instanceof Error ? error.message : '扩展进程不可用'
)
)
}
})
}
/** 启动并等待 `activate` 握手完成。重复调用复用同一次启动。 */
async start(): Promise<void> {
if (this.state.state === 'active') return
if (this.activation) return this.activation
this.stopping = false
this.activation = this.doStart().finally(() => {
this.activation = null
})
return this.activation
}
async stop(): Promise<void> {
this.stopping = true
if (this.restartTimer) {
clearTimeout(this.restartTimer)
this.restartTimer = null
}
const child = this.child
this.child = null
this.settleActivation(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.failPendingActions(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展已停止'))
this.actions.clear()
this.setState('inactive')
if (!child) return
try {
child.send({ type: 'shutdown', version: EXTENSION_HOST_PROTOCOL_VERSION })
} catch {
// 进程可能已经断开;kill 兜底。
}
await new Promise<void>((resolve) => {
const timer = setTimeout(() => {
try {
child.kill()
} catch {
// ignore
}
resolve()
}, 1_500)
child.once?.('exit', () => {
clearTimeout(timer)
resolve()
})
})
}
/**
* 投递消息事件。
*
* 令牌桶是**背压边界**:扩展处理慢或消息突发时宁可丢事件并如实记日志,
* 也不能让主进程的监听回调被拖垮。
*/
deliverEvent(envelope: ExtensionEventEnvelope): boolean {
if (this.state.state !== 'active' || !this.child) return false
this.refillTokens()
if (this.eventTokens < 1) {
this.droppedEvents += 1
if (!this.mutedDropLog && this.droppedEvents % 100 === 1) {
this.dependencies.onLog?.('warn', '消息事件超过扩展处理上限,部分事件已丢弃')
this.mutedDropLog = true
setTimeout(() => {
this.mutedDropLog = false
}, 10_000)
}
return false
}
this.eventTokens -= 1
try {
this.child.send({ type: 'event', version: EXTENSION_HOST_PROTOCOL_VERSION, envelope })
return true
} catch {
return false
}
}
/** 调用扩展注册的自动化动作。超时由宿主强制结束,扩展无法自行取消。 */
async invokeAction(
actionId: string,
input: Record<string, unknown>,
timeoutMs = this.dependencies.actionTimeoutMs ?? DEFAULT_ACTION_TIMEOUT_MS
): Promise<ExtensionAutomationActionOutput> {
if (this.state.state !== 'active' || !this.child) {
throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
}
if (!this.actions.has(actionId)) {
throw new ExtensionError('ACTION_FAILED', `扩展没有注册动作 ${actionId}`)
}
const requestId = randomUUID()
return new Promise<ExtensionAutomationActionOutput>((resolve, reject) => {
const timer = setTimeout(
() => {
this.pendingActions.delete(requestId)
reject(new ExtensionError('ACTION_TIMEOUT'))
},
Math.max(1_000, Math.min(timeoutMs, 60_000))
)
this.pendingActions.set(requestId, { resolve, reject, timer })
try {
this.child?.send({
type: 'invoke-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId,
actionId,
input,
timeoutMs
})
} catch (error) {
clearTimeout(timer)
this.pendingActions.delete(requestId)
reject(
new ExtensionError(
'EXTENSION_HOST_UNAVAILABLE',
error instanceof Error ? error.message : '扩展进程不可用'
)
)
}
})
}
private async doStart(): Promise<void> {
this.setState('starting')
this.actions.clear()
let child: ExtensionHostChild
try {
child = this.dependencies.spawn({
extensionId: this.dependencies.extensionId,
extensionDir: this.dependencies.extensionDir
})
} catch (error) {
this.setState('error', error instanceof Error ? error.message : '扩展进程启动失败')
throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程启动失败')
}
this.child = child
this.wire(child)
try {
await this.activateChild(child)
this.setState('active')
this.dependencies.onLog?.('info', '扩展后台已启动')
} catch (error) {
this.dependencies.onLog?.(
'error',
`扩展启动失败:${error instanceof Error ? error.message : String(error)}`
)
// 先摘掉引用再 kill:否则 exit 回调会被当成「运行期崩溃」并触发重启。
if (this.child === child) this.child = null
try {
child.kill()
} catch {
// ignore
}
this.setState('error', error instanceof Error ? error.message : '扩展启动失败')
throw error instanceof Error
? error
: new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展启动失败')
}
}
/** 发 `activate` 并等待 `activated`。握手结果由 `handleMessage` 统一结算。 */
private activateChild(child: ExtensionHostChild): Promise<void> {
const timeoutMs = this.dependencies.activateTimeoutMs ?? DEFAULT_ACTIVATE_TIMEOUT_MS
return new Promise<void>((resolve, reject) => {
const timer = setTimeout(
() => {
this.settleActivation(new ExtensionError('ACTION_TIMEOUT', '扩展启动超时'))
},
Math.max(2_000, timeoutMs)
)
this.activationWaiter = { resolve, reject, timer, child }
try {
child.send({
type: 'activate',
version: EXTENSION_HOST_PROTOCOL_VERSION,
extensionId: this.dependencies.extensionId,
extensionDir: this.dependencies.extensionDir,
dataDir: this.dependencies.dataDir,
apiVersion: EXTENSION_API_VERSION,
permissions: sortPermissionsByRisk(this.dependencies.permissions)
})
} catch (error) {
this.settleActivation(
new ExtensionError(
'EXTENSION_HOST_UNAVAILABLE',
error instanceof Error ? error.message : '无法向扩展进程发送激活指令'
)
)
}
})
}
private settleActivation(error?: Error): void {
const waiter = this.activationWaiter
if (!waiter) return
this.activationWaiter = null
clearTimeout(waiter.timer)
if (error) waiter.reject(error)
else waiter.resolve()
}
private wire(child: ExtensionHostChild): void {
child.on('message', (message) => this.handleMessage(message))
child.on('error', (error) => {
this.dependencies.onLog?.('error', `扩展进程错误:${error.message}`)
})
child.on('exit', (code) => this.handleExit(child, code))
}
private handleExit(child: ExtensionHostChild, code: number | null): void {
if (this.child !== child) return
this.child = null
this.actions.clear()
this.settleActivation(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程已退出'))
this.failPendingActions(
new ExtensionError('EXTENSION_HOST_UNAVAILABLE', `扩展进程已退出(${code ?? 'unknown'})`)
)
this.failPendingTests(new ExtensionError('EXTENSION_HOST_UNAVAILABLE', '扩展进程已退出'))
if (this.stopping) {
this.setState('inactive')
return
}
const timestamp = this.now()
this.restartTimestamps = this.restartTimestamps.filter(
(item) => timestamp - item < RESTART_WINDOW_MS
)
if (this.restartTimestamps.length >= MAX_RESTARTS) {
this.dependencies.onLog?.('error', '扩展连续异常退出,已停止自动重启')
this.setState('crashed', '扩展连续异常退出,已停止自动重启')
return
}
this.restartTimestamps.push(timestamp)
this.setState('starting', '扩展进程异常退出,正在重启')
const delay = RESTART_BASE_DELAY_MS * 2 ** (this.restartTimestamps.length - 1)
this.restartTimer = setTimeout(() => {
this.restartTimer = null
this.state = { ...this.state, restarts: this.state.restarts + 1, since: this.now() }
void this.start().catch(() => undefined)
}, delay)
}
private handleMessage(raw: unknown): void {
if (!raw || typeof raw !== 'object') return
const message = raw as ExtensionHostOutboundMessage & { version?: number }
if (message.version !== EXTENSION_HOST_PROTOCOL_VERSION) return
switch (message.type) {
case 'activated':
this.settleActivation(
message.ok
? undefined
: new ExtensionError('ACTION_FAILED', message.error?.message || '扩展激活失败')
)
return
case 'call':
void this.handleCall(message)
return
case 'register-action': {
const action = message.action
if (!action || typeof action.id !== 'string') return
this.actions.set(action.id, {
id: action.id,
title: String(action.title || action.id).slice(0, 60),
...(action.description ? { description: String(action.description).slice(0, 200) } : {})
})
this.dependencies.onActionsChanged?.()
return
}
case 'log':
this.dependencies.onLog?.(message.level, message.message)
return
case 'action-result': {
const pending = this.pendingActions.get(message.requestId)
if (!pending) return
clearTimeout(pending.timer)
this.pendingActions.delete(message.requestId)
if (message.ok && message.output) {
pending.resolve(message.output)
} else {
pending.reject(
new ExtensionError(
'ACTION_FAILED',
message.error?.message || message.output?.error || '扩展动作执行失败'
)
)
}
return
}
case 'test-result': {
const pending = this.testHandlers.get(message.requestId)
if (!pending) return
clearTimeout(pending.timer)
this.testHandlers.delete(message.requestId)
if (message.ok) pending.resolve(message.result)
else
pending.reject(
new ExtensionError(message.error?.code || 'ACTION_FAILED', message.error?.message)
)
return
}
}
}
private async handleCall(message: ExtensionHostCall): Promise<void> {
try {
const result = await this.executeCall(message.method, message.params)
this.send({
type: 'call-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
callId: message.callId,
ok: true,
result
})
} catch (error) {
this.send({
type: 'call-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
callId: message.callId,
ok: false,
error: toExtensionErrorPayload(error)
})
}
}
private async executeCall(
method: ExtensionHostCallMethod,
params: Record<string, unknown>
): Promise<unknown> {
const extensionId = this.dependencies.extensionId
switch (method) {
case 'storage.get':
this.requirePermission('storage')
return this.storage.get(extensionId, params.key)
case 'storage.set':
this.requirePermission('storage')
this.storage.set(extensionId, params.key, params.value)
return { ok: true }
case 'storage.remove':
this.requirePermission('storage')
return { removed: this.storage.remove(extensionId, params.key) }
case 'storage.list':
this.requirePermission('storage')
return { entries: this.storage.list(extensionId) }
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
)
}
}
case 'wechat.send.text': {
this.requirePermission('wechat.send.text')
if (!this.dependencies.sendText) throw new ExtensionError('SEND_NOT_SUPPORTED')
return this.dependencies.sendText(
extensionId,
params as unknown as ExtensionSendTextRequest
)
}
case 'wechat.send.image': {
this.requirePermission('wechat.send.image')
if (!this.dependencies.sendImage) throw new ExtensionError('SEND_NOT_SUPPORTED')
return this.dependencies.sendImage(
extensionId,
params as unknown as ExtensionSendImageRequest
)
}
case 'wechat.send.video': {
this.requirePermission('wechat.send.video')
if (!this.dependencies.sendVideo) throw new ExtensionError('SEND_NOT_SUPPORTED')
return this.dependencies.sendVideo(
extensionId,
params as unknown as ExtensionSendVideoRequest
)
}
case 'ai.chat': {
this.requirePermission('ai.chat')
if (!this.dependencies.aiChat) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
const messages = Array.isArray(params.messages) ? params.messages : []
const normalized = messages
.filter((item): item is { role: string; content: string } =>
Boolean(item && typeof item === 'object')
)
.slice(0, 40)
.map((item) => ({
role: String((item as { role?: unknown }).role || 'user'),
content: String((item as { content?: unknown }).content || '').slice(0, 20_000)
}))
return this.dependencies.aiChat(extensionId, normalized)
}
case 'capabilities.get':
if (!this.dependencies.capabilities) throw new ExtensionError('CAPABILITY_UNAVAILABLE')
return this.dependencies.capabilities(extensionId)
default:
throw new ExtensionError('INVALID_REQUEST', `未知方法:${String(method)}`)
}
}
private requirePermission(permission: ExtensionPermission): void {
if (!this.dependencies.permissions.includes(permission)) {
throw new ExtensionError('PERMISSION_DENIED', `扩展没有 ${permission} 权限`)
}
}
private send(message: ExtensionHostInboundMessage): void {
try {
this.child?.send(message)
} catch {
// 进程已退出:pending 会由 handleExit 统一失败。
}
}
private failPendingActions(error: Error): void {
for (const [requestId, pending] of this.pendingActions) {
clearTimeout(pending.timer)
this.pendingActions.delete(requestId)
pending.reject(error)
}
}
private failPendingTests(error: Error): void {
for (const [requestId, pending] of this.testHandlers) {
clearTimeout(pending.timer)
this.testHandlers.delete(requestId)
pending.reject(error)
}
}
private refillTokens(): void {
const now = this.now()
const elapsed = Math.max(0, now - this.eventTokensAt)
if (elapsed <= 0) return
this.eventTokens = Math.min(
EVENT_BUCKET_CAPACITY,
this.eventTokens + (elapsed / 1000) * EVENT_REFILL_PER_SECOND
)
this.eventTokensAt = now
}
private setState(next: ExtensionRuntimeSnapshot['state'], lastError?: string): void {
this.state = {
state: next,
since: this.now(),
restarts: this.state.restarts,
...(lastError ? { lastError } : {})
}
this.dependencies.onStateChange?.(this.snapshot())
}
}
/** 真实子进程:`ELECTRON_RUN_AS_NODE` 让 Electron 二进制以 Node 模式运行。 */
export function forkExtensionHost(
scriptPath: string
): (options: ExtensionHostSpawnOptions) => ExtensionHostChild {
return (options) => {
const child: ChildProcess = fork(scriptPath, [], {
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
serialization: 'advanced',
env: {
...process.env,
ELECTRON_RUN_AS_NODE: '1',
TM_EXTENSION_ID: options.extensionId,
TM_EXTENSION_DIR: options.extensionDir
}
})
return {
send: (message) => {
if (!child.connected) throw new Error('扩展进程未连接')
child.send(message as object)
},
kill: () => child.kill(),
on: (event, listener) => {
if (event === 'message') child.on('message', listener as (message: unknown) => void)
else if (event === 'exit') child.on('exit', listener as (code: number | null) => void)
else child.on('error', listener as (error: Error) => void)
},
once: (event, listener) => {
child.once(event, listener)
},
...(child.pid ? { pid: child.pid } : {})
}
}
}
+390
View File
@@ -0,0 +1,390 @@
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { Open } from 'unzipper'
import { ExtensionError } from '../../shared/extensions/errors'
import {
isSafeRelativeEntryPath,
parseExtensionManifest,
type ExtensionManifest
} from '../../shared/extensions/manifest'
import type { ExtensionRegistry, ExtensionRegistryRecord } from './extension-registry'
import { isPathInside, type ExtensionPaths } from './extension-paths'
const MAX_FILES = 2_000
const MAX_TOTAL_BYTES = 50 * 1024 * 1024
const MAX_FILE_BYTES = 20 * 1024 * 1024
const MAX_PACKAGE_BYTES = 100 * 1024 * 1024
export interface InstallOptions {
/** 应用版本,用于 `minAppVersion` 兼容检查。 */
appVersion: string
source?: 'directory' | 'package'
}
export interface InstallOutcome {
manifest: ExtensionManifest
installPath: string
previousVersion?: string
upgraded: boolean
}
export interface ExtensionInstallerDependencies {
paths: ExtensionPaths
registry: ExtensionRegistry
now?: () => number
}
interface TreeEntry {
relativePath: string
type: 'file' | 'directory'
size: number
}
/**
* 扩展安装 / 升级 / 卸载。
*
* 写入顺序固定为「临时目录 → 校验 → 原子改名」:任何一步失败都不会留下
* 半装目录;升级失败时旧版本仍在原位。
*/
export class ExtensionInstaller {
private readonly paths: ExtensionPaths
private readonly registry: ExtensionRegistry
private readonly now: () => number
constructor(dependencies: ExtensionInstallerDependencies) {
this.paths = dependencies.paths
this.registry = dependencies.registry
this.now = dependencies.now ?? (() => Date.now())
}
async installFromDirectory(sourceDir: string, options: InstallOptions): Promise<InstallOutcome> {
const root = path.resolve(sourceDir)
const stat = await fs.stat(root).catch(() => null)
if (!stat || !stat.isDirectory()) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '选择的路径不是目录')
}
const manifest = await this.readManifest(root, options.appVersion)
const entries = await this.collectTree(root)
this.assertEntrypointsPresent(entries, manifest)
const staging = this.paths.stagingPath('dir')
await fs.mkdir(staging, { recursive: true })
try {
await copyTree(root, staging, entries)
return await this.finalize(staging, manifest, options.source ?? 'directory')
} finally {
await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined)
}
}
async installFromPackage(packagePath: string, options: InstallOptions): Promise<InstallOutcome> {
const stat = await fs.stat(packagePath).catch(() => null)
if (!stat || !stat.isFile()) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '选择的扩展包不存在')
}
if (stat.size > MAX_PACKAGE_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包超过大小限制')
}
const archive = await Open.file(packagePath)
if (!archive.files.length || archive.files.length > MAX_FILES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包文件数量不合法')
}
const seen = new Set<string>()
let declaredTotal = 0
const entries: Array<{
relativePath: string
directory: boolean
size: number
entry: (typeof archive.files)[number]
}> = []
for (const entry of archive.files) {
const normalized = normalizeZipPath(entry.path)
const collisionKey = normalized.toLowerCase()
if (seen.has(collisionKey)) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `扩展包内路径重复:${normalized}`)
}
seen.add(collisionKey)
if (entry.type !== 'File' && entry.type !== 'Directory') {
throw new ExtensionError(
'EXTENSION_INSTALL_FAILED',
`扩展包条目类型不受支持:${normalized}`
)
}
const directory = entry.type === 'Directory'
const size = Number(entry.uncompressedSize || 0)
if (!directory && size > MAX_FILE_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `扩展包内文件过大:${normalized}`)
}
declaredTotal += size
if (declaredTotal > MAX_TOTAL_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包解压后体积超过限制')
}
entries.push({ relativePath: normalized, directory, size, entry })
}
const manifestFile = entries.find(
(item) => item.relativePath === 'manifest.json' && !item.directory
)
if (!manifestFile)
throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展包缺少 manifest.json')
const manifest = this.parseManifestText(
(await manifestFile.entry.buffer()).toString('utf8'),
options.appVersion
)
this.assertEntrypointsPresent(
entries.map((item) => ({
relativePath: item.relativePath,
type: item.directory ? 'directory' : 'file',
size: item.size
})),
manifest
)
const staging = this.paths.stagingPath('zip')
await fs.mkdir(staging, { recursive: true })
try {
let actualTotal = 0
for (const item of entries) {
const destination = path.resolve(staging, item.relativePath)
if (!isPathInside(staging, destination)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `扩展包条目越界:${item.relativePath}`)
}
if (item.directory) {
await fs.mkdir(destination, { recursive: true })
continue
}
await fs.mkdir(path.dirname(destination), { recursive: true })
const chunks: Buffer[] = []
for await (const chunk of item.entry.stream()) {
const buffer = Buffer.from(chunk as Uint8Array)
actualTotal += buffer.length
if (actualTotal > MAX_TOTAL_BYTES || buffer.length > MAX_FILE_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展包实际解压体积超过限制')
}
chunks.push(buffer)
}
await fs.writeFile(destination, Buffer.concat(chunks))
const fileStat = await fs.lstat(destination)
if (!fileStat.isFile()) {
throw new ExtensionError(
'EXTENSION_INVALID_PATH',
`扩展包条目不是普通文件:${item.relativePath}`
)
}
}
return await this.finalize(staging, manifest, 'package')
} finally {
await fs.rm(staging, { recursive: true, force: true }).catch(() => undefined)
}
}
/**
* 卸载扩展。
*
* `keepData` 为 true 时**只**删除代码目录,用户配置保留在
* `extensions-data/<id>`,同名扩展重新安装后能读回。
*/
async uninstall(extensionId: string, options: { keepData: boolean }): Promise<void> {
const target = this.paths.installDir(extensionId)
if (!isPathInside(this.paths.extensionsDir, target)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界')
}
const trash = `${target}.removed-${this.now()}`
const exists = await fs
.stat(target)
.then(() => true)
.catch(() => false)
if (exists) {
await fs.rename(target, trash)
await fs.rm(trash, { recursive: true, force: true }).catch(() => undefined)
}
if (!options.keepData) {
await fs
.rm(this.paths.extensionDataDir(extensionId), { recursive: true, force: true })
.catch(() => undefined)
}
this.registry.remove(extensionId)
}
private async readManifest(root: string, appVersion: string): Promise<ExtensionManifest> {
const manifestPath = path.join(root, 'manifest.json')
const text = await fs.readFile(manifestPath, 'utf8').catch(() => '')
if (!text) throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展目录缺少 manifest.json')
return this.parseManifestText(text, appVersion)
}
private parseManifestText(text: string, appVersion: string): ExtensionManifest {
const result = parseExtensionManifestJsonWithDetail(text, appVersion)
if (!result.ok || !result.manifest) {
throw new ExtensionError(
result.code === 'EXTENSION_INCOMPATIBLE'
? 'EXTENSION_INCOMPATIBLE'
: 'EXTENSION_INVALID_MANIFEST',
result.message || '扩展 manifest 不合法'
)
}
return result.manifest
}
private assertEntrypointsPresent(entries: TreeEntry[], manifest: ExtensionManifest): void {
const files = new Set(
entries.filter((entry) => entry.type === 'file').map((entry) => entry.relativePath)
)
for (const [key, value] of Object.entries(manifest.entrypoints)) {
if (!value) continue
if (!files.has(value)) {
throw new ExtensionError(
'EXTENSION_INVALID_MANIFEST',
`entrypoints.${key} 指向的文件不存在:${value}`
)
}
}
for (const page of manifest.contributions.pages) {
const entry = page.entry || manifest.entrypoints.page
if (!entry || !files.has(entry)) {
throw new ExtensionError('EXTENSION_INVALID_MANIFEST', `页面 ${page.id} 的入口文件不存在`)
}
}
}
private async collectTree(root: string): Promise<TreeEntry[]> {
const entries: TreeEntry[] = []
let total = 0
const walk = async (directory: string, prefix: string): Promise<void> => {
const items = await fs.readdir(directory, { withFileTypes: true })
for (const item of items) {
const relativePath = prefix ? `${prefix}/${item.name}` : item.name
if (!isSafeRelativeEntryPath(relativePath)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `文件名不受支持:${relativePath}`)
}
const absolute = path.join(directory, item.name)
const stat = await fs.lstat(absolute)
if (stat.isSymbolicLink()) {
throw new ExtensionError(
'EXTENSION_INVALID_PATH',
`扩展目录不能包含符号链接:${relativePath}`
)
}
if (stat.isDirectory()) {
entries.push({ relativePath, type: 'directory', size: 0 })
await walk(absolute, relativePath)
continue
}
if (!stat.isFile()) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `不支持的文件类型:${relativePath}`)
}
if (stat.size > MAX_FILE_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', `文件过大:${relativePath}`)
}
total += stat.size
if (total > MAX_TOTAL_BYTES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展体积超过限制')
}
entries.push({ relativePath, type: 'file', size: stat.size })
if (entries.length > MAX_FILES) {
throw new ExtensionError('EXTENSION_INSTALL_FAILED', '扩展文件数量超过限制')
}
}
}
await walk(root, '')
return entries
}
/** 临时目录 → 目标目录的原子替换。升级时保留 registry 里的启用状态与授权。 */
private async finalize(
staging: string,
manifest: ExtensionManifest,
source: 'directory' | 'package'
): Promise<InstallOutcome> {
const target = this.paths.installDir(manifest.id)
if (!isPathInside(this.paths.extensionsDir, target)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', '扩展安装路径越界')
}
await fs.mkdir(this.paths.extensionsDir, { recursive: true })
const existingRecord = this.registry.get(manifest.id)
const backup = `${target}.backup-${this.now()}`
const targetExists = await fs
.stat(target)
.then(() => true)
.catch(() => false)
if (targetExists) await fs.rename(target, backup)
try {
await fs.rename(staging, target)
} catch (error) {
if (targetExists) await fs.rename(backup, target).catch(() => undefined)
throw new ExtensionError(
'EXTENSION_INSTALL_FAILED',
error instanceof Error ? error.message : '安装目录替换失败'
)
}
if (targetExists) await fs.rm(backup, { recursive: true, force: true }).catch(() => undefined)
const timestamp = this.now()
const record: ExtensionRegistryRecord = {
id: manifest.id,
version: manifest.version,
apiVersion: manifest.apiVersion,
// 升级不改变启用状态:升级后突然开始跑代码是用户没有同意的行为变化。
enabled: existingRecord?.enabled ?? false,
grantedPermissions: existingRecord?.grantedPermissions ?? [],
installedAt: existingRecord?.installedAt ?? timestamp,
updatedAt: timestamp,
source
}
this.registry.upsert(record)
return {
manifest,
installPath: target,
...(existingRecord ? { previousVersion: existingRecord.version } : {}),
upgraded: Boolean(existingRecord)
}
}
}
function normalizeZipPath(value: string): string {
const normalized = String(value || '')
.replace(/\\/g, '/')
.replace(/\/+$/, '')
if (!isSafeRelativeEntryPath(normalized)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `扩展包内路径不合法:${value}`)
}
return normalized
}
async function copyTree(root: string, destination: string, entries: TreeEntry[]): Promise<void> {
for (const entry of entries) {
const from = path.join(root, entry.relativePath)
const to = path.resolve(destination, entry.relativePath)
if (!isPathInside(destination, to)) {
throw new ExtensionError('EXTENSION_INVALID_PATH', `复制路径越界:${entry.relativePath}`)
}
if (entry.type === 'directory') {
await fs.mkdir(to, { recursive: true })
continue
}
await fs.mkdir(path.dirname(to), { recursive: true })
await fs.copyFile(from, to)
}
}
/**
* 与 shared 的 `parseExtensionManifestJson` 同构,但把「兼容性」与「格式」区分开,
* 好让安装界面给出可操作的提示(升级 TraceMemo vs 修 manifest)。
*/
function parseExtensionManifestJsonWithDetail(
text: string,
appVersion: string
): ReturnType<typeof parseExtensionManifest> {
let value: unknown
try {
value = JSON.parse(text)
} catch {
return { ok: false, code: 'EXTENSION_INVALID_MANIFEST', message: 'manifest.json 不是合法 JSON' }
}
return parseExtensionManifest(value, { appVersion })
}
+195
View File
@@ -0,0 +1,195 @@
import fs from 'fs-extra'
import path from 'node:path'
import { BrowserWindow, dialog, ipcMain, shell } from 'electron'
import { EXTENSION_IPC } from '../../shared/extensions/ipc'
import type {
ExtensionInstallResult,
ExtensionLogEntry,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageRequest,
ExtensionPageResponse,
InstalledExtension
} from '../../shared/extensions/types'
import type { ExtensionManager } from './extension-manager'
import type { ExtensionPaths } from './extension-paths'
export interface ExtensionIpcOptions {
/** 懒取:扩展系统在窗口创建之后才完成初始化。 */
getManager: () => ExtensionManager
paths: ExtensionPaths
/** 扩展页面 IPC 的调用方必须是主窗口;其它 webContents 一律拒绝。 */
isTrustedSender: (senderId: number) => boolean
}
/**
* 注册扩展中心的 IPC。
*
* 所有入参都在这一层收敛类型与长度:渲染层与扩展页面都是「不可信输入」,
* 不能把未校验的对象直接交给 manager。
*/
export function registerExtensionIpc(options: ExtensionIpcOptions): void {
const { paths } = options
const manager = (): ExtensionManager => options.getManager()
const guard = <Args extends unknown[], Result>(
handler: (...args: Args) => Promise<Result> | Result
): ((
event: Electron.IpcMainInvokeEvent,
...args: Args
) => Promise<Result | { success: false; error: { code: string; message: string } }>) => {
return async (event, ...args) => {
if (!options.isTrustedSender(event.sender.id)) {
return { success: false, error: { code: 'PERMISSION_DENIED', message: '不受信任的调用方' } }
}
try {
return await handler(...args)
} catch (error) {
return {
success: false,
error: {
code: 'ACTION_FAILED',
message: error instanceof Error ? error.message : '扩展操作失败'
}
}
}
}
}
ipcMain.handle(
EXTENSION_IPC.list,
guard((): InstalledExtension[] => manager().list())
)
ipcMain.handle(
EXTENSION_IPC.detail,
guard((extensionId: unknown): InstalledExtension | null =>
manager().get(requireId(extensionId))
)
)
ipcMain.handle(
EXTENSION_IPC.pickDirectory,
guard(async (): Promise<string | null> => {
const window = BrowserWindow.getFocusedWindow()
const result = window
? await dialog.showOpenDialog(window, { properties: ['openDirectory'] })
: await dialog.showOpenDialog({ properties: ['openDirectory'] })
return result.canceled || !result.filePaths.length ? null : result.filePaths[0]
})
)
ipcMain.handle(
EXTENSION_IPC.pickPackage,
guard(async (): Promise<string | null> => {
const window = BrowserWindow.getFocusedWindow()
const options: Electron.OpenDialogOptions = {
properties: ['openFile'],
filters: [
{ name: 'TraceMemo 扩展包', extensions: ['zip', 'tmext'] },
{ name: '全部文件', extensions: ['*'] }
]
}
const result = window
? await dialog.showOpenDialog(window, options)
: await dialog.showOpenDialog(options)
return result.canceled || !result.filePaths.length ? null : result.filePaths[0]
})
)
ipcMain.handle(
EXTENSION_IPC.installDirectory,
guard(
(directory: unknown): Promise<ExtensionInstallResult> =>
manager().installFromDirectory(requirePath(directory))
)
)
ipcMain.handle(
EXTENSION_IPC.installPackage,
guard(
(packagePath: unknown): Promise<ExtensionInstallResult> =>
manager().installFromPackage(requirePath(packagePath))
)
)
ipcMain.handle(
EXTENSION_IPC.setEnabled,
guard((payload: unknown): Promise<ExtensionOperationResult> => {
const input = (payload ?? {}) as { id?: unknown; enabled?: unknown }
return manager().setEnabled(requireId(input.id), input.enabled === true)
})
)
ipcMain.handle(
EXTENSION_IPC.uninstall,
guard((payload: unknown): Promise<ExtensionOperationResult> => {
const input = (payload ?? {}) as { id?: unknown; keepData?: unknown }
return manager().uninstall(requireId(input.id), input.keepData !== false)
})
)
ipcMain.handle(
EXTENSION_IPC.logs,
guard((payload: unknown): ExtensionLogEntry[] => {
const input = (payload ?? {}) as { id?: unknown; limit?: unknown }
const limit = Number(input.limit)
return manager().getLogs(requireId(input.id), Number.isFinite(limit) ? limit : 100)
})
)
ipcMain.handle(
EXTENSION_IPC.clearLogs,
guard((extensionId: unknown): { success: true } => {
manager().clearLogs(requireId(extensionId))
return { success: true }
})
)
ipcMain.handle(
EXTENSION_IPC.pageUrl,
guard((payload: unknown): ExtensionPageDescriptor => {
const input = (payload ?? {}) as { id?: unknown; pageId?: unknown }
const pageId =
typeof input.pageId === 'string' && input.pageId.trim() ? input.pageId.trim() : undefined
return manager().pageUrl(requireId(input.id), pageId)
})
)
ipcMain.handle(
EXTENSION_IPC.pageRequest,
guard((payload: unknown): Promise<ExtensionPageResponse> => {
const request = (payload ?? {}) as Partial<ExtensionPageRequest>
const extensionId = requireId(request.extensionId)
const method = String(request.method || '')
const params =
request.params && typeof request.params === 'object' && !Array.isArray(request.params)
? (request.params as Record<string, unknown>)
: {}
return manager().pageRequest(extensionId, method, params)
})
)
ipcMain.handle(
EXTENSION_IPC.openDataDir,
guard(async (extensionId: unknown): Promise<{ success: boolean; error?: string }> => {
const id = requireId(extensionId)
const directory = paths.extensionDataDir(id)
fs.ensureDirSync(directory)
const error = await shell.openPath(directory)
return error ? { success: false, error } : { success: true }
})
)
}
function requireId(value: unknown): string {
const id = String(value || '').trim()
if (!/^[a-z0-9.-]{3,128}$/.test(id)) throw new Error('扩展 id 不合法')
return id
}
function requirePath(value: unknown): string {
const target = String(value || '').trim()
if (!target || target.length > 4_096) throw new Error('路径不合法')
if (!path.isAbsolute(target)) throw new Error('必须使用绝对路径')
return target
}
+125
View File
@@ -0,0 +1,125 @@
import fs from 'fs-extra'
import path from 'node:path'
import { randomUUID } from 'node:crypto'
import type { ExtensionLogEntry } from '../../shared/extensions/types'
const MAX_ENTRIES_PER_EXTENSION = 200
const MAX_MESSAGE_LENGTH = 500
const MAX_FILE_BYTES = 256 * 1024
/**
* 扩展日志:内存环形缓冲 + 磁盘 JSONL(超过上限时轮转一份 `.1`)。
*
* 隐私边界:宿主只记录**生命周期与错误摘要**,不写聊天正文。
* 扩展主动写入的内容会原样落盘并展示给用户,作者必须自己遵守隐私约定。
*/
export class ExtensionLogStore {
private readonly logsDir: string
private readonly memory = new Map<string, ExtensionLogEntry[]>()
private readonly loaded = new Set<string>()
constructor(logsDir: string) {
this.logsDir = logsDir
}
append(
extensionId: string,
level: ExtensionLogEntry['level'],
source: ExtensionLogEntry['source'],
message: string
): ExtensionLogEntry {
this.ensureLoaded(extensionId)
const entry: ExtensionLogEntry = {
id: randomUUID(),
at: Date.now(),
level,
source,
message: sanitizeMessage(message)
}
const list = this.memory.get(extensionId) ?? []
list.push(entry)
if (list.length > MAX_ENTRIES_PER_EXTENSION)
list.splice(0, list.length - MAX_ENTRIES_PER_EXTENSION)
this.memory.set(extensionId, list)
this.appendToDisk(extensionId, entry)
return entry
}
list(extensionId: string, limit = MAX_ENTRIES_PER_EXTENSION): ExtensionLogEntry[] {
this.ensureLoaded(extensionId)
const list = this.memory.get(extensionId) ?? []
return list.slice(-Math.max(1, Math.min(limit, MAX_ENTRIES_PER_EXTENSION))).reverse()
}
clear(extensionId: string): void {
this.memory.set(extensionId, [])
this.loaded.add(extensionId)
fs.removeSync(this.filePath(extensionId))
fs.removeSync(`${this.filePath(extensionId)}.1`)
}
remove(extensionId: string): void {
this.memory.delete(extensionId)
this.loaded.delete(extensionId)
fs.removeSync(this.filePath(extensionId))
fs.removeSync(`${this.filePath(extensionId)}.1`)
}
private filePath(extensionId: string): string {
return path.join(this.logsDir, `${extensionId}.jsonl`)
}
private ensureLoaded(extensionId: string): void {
if (this.loaded.has(extensionId)) return
this.loaded.add(extensionId)
try {
const text = fs.readFileSync(this.filePath(extensionId), 'utf8')
const lines = text.split('\n').filter(Boolean).slice(-MAX_ENTRIES_PER_EXTENSION)
const entries: ExtensionLogEntry[] = []
for (const line of lines) {
try {
const raw = JSON.parse(line) as Partial<ExtensionLogEntry>
if (!raw || typeof raw !== 'object') continue
if (typeof raw.message !== 'string') continue
entries.push({
id: String(raw.id || randomUUID()),
at: Number(raw.at) || 0,
level: raw.level === 'warn' || raw.level === 'error' ? raw.level : 'info',
source: raw.source === 'extension' ? 'extension' : 'core',
message: sanitizeMessage(raw.message)
})
} catch {
// 单行损坏不影响其余日志。
}
}
this.memory.set(extensionId, entries)
} catch {
this.memory.set(extensionId, [])
}
}
private appendToDisk(extensionId: string, entry: ExtensionLogEntry): void {
try {
const filePath = this.filePath(extensionId)
fs.ensureDirSync(path.dirname(filePath))
const size = fs.statSync(filePath, { throwIfNoEntry: false })?.size ?? 0
if (size > MAX_FILE_BYTES) fs.moveSync(filePath, `${filePath}.1`, { overwrite: true })
fs.appendFileSync(filePath, `${JSON.stringify(entry)}\n`, 'utf8')
} catch {
// 日志写不进去不能影响扩展运行。
}
}
}
// eslint-disable-next-line no-control-regex -- 终端 ANSI 序列与控制字符要在落盘前剥掉
const ANSI_PATTERN = /\u001b\[[0-9;]*m/g
// eslint-disable-next-line no-control-regex -- 同上:日志里不允许出现不可见控制字符
const CONTROL_PATTERN = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g
function sanitizeMessage(value: unknown): string {
const text = String(value ?? '')
.replace(ANSI_PATTERN, '')
.replace(CONTROL_PATTERN, '')
.trim()
return text.length > MAX_MESSAGE_LENGTH ? `${text.slice(0, MAX_MESSAGE_LENGTH)}…` : text
}
+761
View File
@@ -0,0 +1,761 @@
import fs from 'fs-extra'
import os from 'node:os'
import path from 'node:path'
import { safeStorage } from 'electron'
import { ExtensionError, toExtensionErrorPayload } from '../../shared/extensions/errors'
import {
autoGrantedPermissions,
hasExtensionPermission,
type ExtensionPermission
} from '../../shared/extensions/permissions'
import {
checkExtensionCompatibility,
parseExtensionManifest,
type ExtensionManifest
} from '../../shared/extensions/manifest'
import type {
ExtensionCapabilitySnapshot,
ExtensionInstallResult,
ExtensionLogEntry,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageMethod,
ExtensionPageResponse,
InstalledExtension
} from '../../shared/extensions/types'
import type {
ExtensionAutomationActionOutput,
ExtensionMessagesQueryRequest,
ExtensionQueriedMessage,
ExtensionSendImageRequest,
ExtensionSendTextRequest,
ExtensionSendTextResult,
ExtensionSendVideoRequest
} from '../../shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
import type { NormalizedIncomingMessage } from '../services/message-listener-service'
import { ExtensionActionRegistry } from './extension-action-registry'
import { ExtensionEventBus } from './extension-event-bus'
import type { ExtensionEntitlementResult } from './extension-entitlement'
import {
ExtensionHost,
forkExtensionHost,
type ExtensionHostChild,
type ExtensionHostSpawnOptions
} from './extension-host'
import { ExtensionInstaller } from './extension-installer'
import { ExtensionLogStore } from './extension-log'
import { ExtensionRegistry, type ExtensionRegistryRecord } from './extension-registry'
import { ExtensionSendGateway } from './extension-send-gateway'
import { ExtensionStorage } from './extension-storage'
import type { ExtensionPaths } from './extension-paths'
export interface ExtensionManagerDependencies {
paths: ExtensionPaths
appVersion: string
platform?: NodeJS.Platform
spawn?: (options: ExtensionHostSpawnOptions) => ExtensionHostChild
getCapability: () => Promise<PersonalWechatSendCapability>
checkEntitlement: () => Promise<ExtensionEntitlementResult>
executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
queryMessages: (request: ExtensionMessagesQueryRequest) => Promise<ExtensionQueriedMessage[]>
/** 群列表(id + 显示名);用于扩展配置页选择发送目标。 */
listGroups: () => Promise<Array<{ id: string; name: string }>>
aiChat: (messages: Array<{ role: string; content: string }>) => Promise<{ text: string }>
getAccountId: () => string
getSelfUsernames: () => string[]
isDatabaseReady: () => boolean
now?: () => number
onChange?: (
extensionId: string,
reason: 'installed' | 'enabled' | 'disabled' | 'uninstalled' | 'runtime' | 'actions'
) => void
}
const PAGE_METHODS: ExtensionPageMethod[] = [
'storage.get',
'storage.set',
'storage.remove',
'storage.list',
'capabilities.get',
'contacts.listGroups',
'test.send',
'douyin.cookie.get',
'douyin.cookie.set',
'douyin.cookie.clear',
'extension.info'
]
/**
* 扩展系统的编排层。
*
* 职责边界:
* - **只做编排**:清单读取、安装、启停、进程托管、事件分发、能力转发;
* - 不实现消息监听(复用 `MessageListenerService`)、不实现发送(复用
* `WechatActionGateway`)、不实现自动化规则存储(复用 `AutomationRuleStore`)。
*
* 所有扩展代码都在 `ExtensionHost` 的子进程里运行;本类不 `require` 任何扩展文件。
*/
export class ExtensionManager {
private readonly dependencies: ExtensionManagerDependencies
private readonly paths: ExtensionPaths
private readonly registry: ExtensionRegistry
private readonly installer: ExtensionInstaller
private readonly storage: ExtensionStorage
private readonly logs: ExtensionLogStore
private readonly actions = new ExtensionActionRegistry()
private readonly sendGateway: ExtensionSendGateway
private readonly hosts = new Map<string, ExtensionHost>()
private readonly manifests = new Map<string, ExtensionManifest | null>()
private readonly eventBus: ExtensionEventBus
private readonly now: () => number
private initialized = false
constructor(dependencies: ExtensionManagerDependencies) {
this.dependencies = dependencies
this.paths = dependencies.paths
this.now = dependencies.now ?? (() => Date.now())
this.registry = new ExtensionRegistry({ registryFile: this.paths.registryFile, now: this.now })
this.installer = new ExtensionInstaller({
paths: this.paths,
registry: this.registry,
now: this.now
})
this.storage = new ExtensionStorage({ dataRoot: this.paths.dataDir })
this.logs = new ExtensionLogStore(this.paths.logsDir)
this.sendGateway = new ExtensionSendGateway({
getCapability: dependencies.getCapability,
checkEntitlement: dependencies.checkEntitlement,
executeAction: dependencies.executeAction,
getExtensionDataRoot: (extensionId) => this.paths.extensionDataDir(extensionId),
now: this.now
})
this.eventBus = new ExtensionEventBus({
listSubscribers: () => this.listEventSubscribers(),
getAccountId: dependencies.getAccountId,
getSelfUsernames: dependencies.getSelfUsernames,
now: this.now
})
}
/** 建立目录、加载状态、拉起已启用的扩展。单个扩展失败不影响其他扩展。 */
async initialize(): Promise<void> {
if (this.initialized) return
this.initialized = true
for (const directory of [
this.paths.extensionsDir,
this.paths.dataDir,
this.paths.stateDir,
this.paths.logsDir,
this.paths.stagingDir
]) {
fs.ensureDirSync(directory)
}
this.eventBus.setAccountId(this.dependencies.getAccountId())
for (const record of this.registry.list()) {
const manifest = this.readManifest(record.id)
if (!manifest) {
this.logs.append(record.id, 'error', 'core', '扩展文件缺失或 manifest 无法读取')
continue
}
this.syncDeclared(record.id, manifest)
if (!record.enabled) continue
const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion)
if (!compatibility.compatible) {
this.logs.append(record.id, 'error', 'core', compatibility.reason || '扩展不兼容')
continue
}
try {
await this.startHost(record.id, manifest)
} catch (error) {
this.logs.append(
record.id,
'error',
'core',
`扩展启动失败:${error instanceof Error ? error.message : String(error)}`
)
}
}
}
list(): InstalledExtension[] {
return this.registry
.list()
.map((record) => this.toInstalled(record))
.sort((left, right) => left.name.localeCompare(right.name))
}
get(extensionId: string): InstalledExtension | null {
const record = this.registry.get(extensionId)
if (!record) return null
return this.toInstalled(record)
}
getLogs(extensionId: string, limit = 100): ExtensionLogEntry[] {
return this.logs.list(extensionId, limit)
}
clearLogs(extensionId: string): void {
this.logs.clear(extensionId)
}
async installFromDirectory(directory: string): Promise<ExtensionInstallResult> {
return this.install(() =>
this.installer.installFromDirectory(directory, { appVersion: this.dependencies.appVersion })
)
}
async installFromPackage(packagePath: string): Promise<ExtensionInstallResult> {
return this.install(() =>
this.installer.installFromPackage(packagePath, {
appVersion: this.dependencies.appVersion,
source: 'package'
})
)
}
async setEnabled(extensionId: string, enabled: boolean): Promise<ExtensionOperationResult> {
const record = this.registry.get(extensionId)
if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
const manifest = this.readManifest(extensionId)
if (!manifest) return failure(new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失'))
if (!enabled) {
await this.stopHost(extensionId)
this.registry.setEnabled(extensionId, false)
this.registry.setGrantedPermissions(extensionId, autoGrantedPermissions(manifest.permissions))
this.dependencies.onChange?.(extensionId, 'disabled')
return { success: true }
}
const compatibility = checkExtensionCompatibility(manifest, this.dependencies.appVersion)
if (!compatibility.compatible) {
return failure(new ExtensionError('EXTENSION_INCOMPATIBLE', compatibility.reason))
}
this.registry.setEnabled(extensionId, true)
this.registry.setGrantedPermissions(extensionId, manifest.permissions)
this.syncDeclared(extensionId, manifest)
if (manifest.entrypoints.background) {
try {
await this.startHost(extensionId, manifest)
} catch {
// 启用状态保留:运行状态会显示为「错误」,用户可以查看日志后重新启用。
}
}
this.dependencies.onChange?.(extensionId, 'enabled')
return { success: true }
}
async uninstall(extensionId: string, keepData: boolean): Promise<ExtensionOperationResult> {
const record = this.registry.get(extensionId)
if (!record) return failure(new ExtensionError('EXTENSION_NOT_FOUND'))
await this.stopHost(extensionId)
this.actions.remove(extensionId)
this.manifests.delete(extensionId)
try {
await this.installer.uninstall(extensionId, { keepData })
} catch (error) {
return failure(toExtensionErrorPayload(error) as unknown as ExtensionError)
}
if (!keepData) this.logs.remove(extensionId)
this.dependencies.onChange?.(extensionId, 'uninstalled')
return { success: true }
}
/** 页面地址。停用的扩展也允许打开自己的配置页(否则用户无法先配置再启用)。 */
pageUrl(extensionId: string, pageId?: string): ExtensionPageDescriptor {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
const manifest = this.readManifest(extensionId)
if (!manifest) throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失')
const page = pageId
? manifest.contributions.pages.find((item) => item.id === pageId)
: manifest.contributions.pages[0]
const entry = page?.entry || manifest.entrypoints.page
if (!entry) throw new ExtensionError('EXTENSION_NOT_FOUND', '扩展没有可打开的页面')
return {
extensionId,
pageId: page?.id || 'main',
title: page?.title || manifest.name,
url: `tm-extension://${extensionId}/${entry}`
}
}
/**
* 扩展页面可调用的能力。
*
* 页面**没有**发送 / 查询 / AI 权限:那些能力只从后台进程按权限申请。
* 页面与后台共享同一个 `storage` 命名空间,所以配置页保存的内容后台能直接读到。
*/
async pageRequest(
extensionId: string,
method: string,
params: Record<string, unknown> = {}
): Promise<ExtensionPageResponse> {
try {
if (!PAGE_METHODS.includes(method as ExtensionPageMethod)) {
throw new ExtensionError('PERMISSION_DENIED', `页面不能调用 ${method}`)
}
if (method.startsWith('douyin.cookie.') && extensionId !== 'com.example.douyin-sender') {
throw new ExtensionError('PERMISSION_DENIED', 'Cookie 能力不适用于此扩展')
}
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
const manifest = this.readManifest(extensionId)
if (!manifest) throw new ExtensionError('EXTENSION_INVALID_MANIFEST', '扩展文件缺失')
if (!manifest.permissions.includes('storage') && method.startsWith('storage.')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 storage 权限')
}
if (method === 'contacts.listGroups' && !manifest.permissions.includes('contacts.list')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 contacts.list 权限')
}
switch (method as ExtensionPageMethod) {
case 'storage.get':
return { ok: true, result: this.storage.get(extensionId, params.key) }
case 'storage.set':
this.storage.set(extensionId, params.key, params.value)
return { ok: true, result: { ok: true } }
case 'storage.remove':
return { ok: true, result: { removed: this.storage.remove(extensionId, params.key) } }
case 'storage.list':
return { ok: true, result: { entries: this.storage.list(extensionId) } }
case 'capabilities.get':
return { ok: true, result: await this.buildCapabilitySnapshot(extensionId) }
case 'contacts.listGroups': {
const groups = await this.dependencies.listGroups()
return {
ok: true,
result: {
groups: groups
.filter((group) => group && group.id)
.map((group) => ({ id: group.id, name: group.name || group.id }))
.slice(0, 2_000)
}
}
}
case 'test.send': {
if (extensionId !== 'com.example.douyin-sender') {
throw new ExtensionError('PERMISSION_DENIED', '测试能力不适用于此扩展')
}
const host = this.hosts.get(extensionId)
if (!host) throw new ExtensionError('EXTENSION_DISABLED')
const cookieHeader = String(params.cookieHeader || '') || this.readDouyinCookie()
try {
return { ok: true, result: await host.testSend({ ...params, cookieHeader }) }
} finally {
params.cookieHeader = ''
}
}
case 'douyin.cookie.get':
return { ok: true, result: { configured: Boolean(this.readDouyinCookie()) } }
case 'douyin.cookie.set': {
const value = String(params.cookieHeader || '').trim()
if (!value) throw new ExtensionError('INVALID_REQUEST', 'Cookie 不能为空')
if (!safeStorage.isEncryptionAvailable())
throw new ExtensionError('CAPABILITY_UNAVAILABLE', '系统安全存储不可用')
fs.writeFileSync(
path.join(this.paths.userData, 'douyin-cookie.bin'),
safeStorage.encryptString(value),
{ mode: 0o600 }
)
fs.chmodSync(path.join(this.paths.userData, 'douyin-cookie.bin'), 0o600)
this.syncDouyinCookieToExtensionData(value)
return { ok: true, result: { configured: true } }
}
case 'douyin.cookie.clear':
this.clearDouyinCookie()
return { ok: true, result: { configured: false } }
case 'extension.info':
return {
ok: true,
result: {
id: manifest.id,
name: manifest.name,
version: manifest.version,
enabled: record.enabled
}
}
default:
throw new ExtensionError('PERMISSION_DENIED', `页面不能调用 ${method}`)
}
} catch (error) {
return { ok: false, error: toExtensionErrorPayload(error) }
}
}
handleMessage(message: NormalizedIncomingMessage): void {
this.eventBus.setAccountId(this.dependencies.getAccountId())
this.eventBus.handleMessage(message)
}
private syncDouyinCookieToExtensionData(value: string): void {
try {
const dataDir = this.paths.extensionDataDir('com.example.douyin-sender')
fs.ensureDirSync(dataDir)
const target = path.join(dataDir, 'douyin-cookie.txt')
fs.writeFileSync(target, value, { mode: 0o600 })
fs.chmodSync(target, 0o600)
} catch {
// 扩展数据目录同步失败不影响加密主存储。
}
}
private readDouyinCookie(): string {
const file = path.join(this.paths.userData, 'douyin-cookie.bin')
if (fs.existsSync(file) && safeStorage.isEncryptionAvailable()) {
try {
const decrypted = safeStorage.decryptString(fs.readFileSync(file)).trim()
if (decrypted) {
this.syncDouyinCookieToExtensionData(decrypted)
return decrypted
}
} catch {
// 加密文件损坏或不可解密时继续尝试桌面 Cookie 文件。
}
}
const desktopCookie = path.join(os.homedir(), 'Desktop', 'douyin-cookie')
if (fs.existsSync(desktopCookie)) {
try {
return fs.readFileSync(desktopCookie, 'utf8').trim()
} catch {
return ''
}
}
return ''
}
private clearDouyinCookie(): void {
try {
fs.removeSync(path.join(this.paths.userData, 'douyin-cookie.bin'))
fs.removeSync(
path.join(this.paths.extensionDataDir('com.example.douyin-sender'), 'douyin-cookie.txt')
)
} catch {
throw new ExtensionError('INVALID_REQUEST', '无法清除抖音 Cookie')
}
}
setAccountId(accountId: string): void {
this.eventBus.setAccountId(accountId)
}
/** 自动化动作执行入口。由 `AutomationActionRunner` 调用。 */
async invokeAutomationAction(
extensionId: string,
actionId: string,
input: Record<string, unknown>,
timeoutMs?: number
): Promise<ExtensionAutomationActionOutput> {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
if (!hasExtensionPermission(record.grantedPermissions, 'automation.action')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 automation.action 权限')
}
const host = this.hosts.get(extensionId)
if (!host) throw new ExtensionError('EXTENSION_HOST_UNAVAILABLE')
if (!this.actions.isRegistered(extensionId, actionId)) {
throw new ExtensionError('ACTION_FAILED', '扩展没有注册该动作')
}
return host.invokeAction(actionId, input, timeoutMs)
}
getActions(): ReturnType<ExtensionActionRegistry['list']> {
return this.actions.list()
}
async dispose(): Promise<void> {
const ids = Array.from(this.hosts.keys())
await Promise.all(ids.map((id) => this.stopHost(id)))
}
private async install(
run: () => Promise<{ manifest: ExtensionManifest; upgraded: boolean; previousVersion?: string }>
): Promise<ExtensionInstallResult> {
let outcome: Awaited<ReturnType<typeof run>>
try {
outcome = await run()
} catch (error) {
return { success: false, error: toExtensionErrorPayload(error) }
}
const { manifest } = outcome
const wasEnabled = this.registry.get(manifest.id)?.enabled === true
if (wasEnabled) await this.stopHost(manifest.id)
this.manifests.delete(manifest.id)
this.manifests.set(manifest.id, manifest)
this.syncDeclared(manifest.id, manifest)
// 新安装只自动授予低风险权限;升级保留用户已经授予的集合。
if (!outcome.upgraded) {
this.registry.setGrantedPermissions(manifest.id, autoGrantedPermissions(manifest.permissions))
}
this.logs.append(
manifest.id,
'info',
'core',
outcome.upgraded
? `扩展已更新:${outcome.previousVersion ?? '?'} → ${manifest.version}`
: `扩展已安装:${manifest.version}`
)
this.dependencies.onChange?.(manifest.id, 'installed')
if (wasEnabled && manifest.entrypoints.background) {
await this.startHost(manifest.id, manifest).catch(() => undefined)
}
const installed = this.get(manifest.id)
return { success: true, ...(installed ? { extension: installed } : {}) }
}
private async startHost(extensionId: string, manifest: ExtensionManifest): Promise<void> {
if (!manifest.entrypoints.background) return
await this.stopHost(extensionId)
const host = new ExtensionHost({
extensionId,
extensionDir: this.paths.installDir(extensionId),
dataDir: this.paths.extensionDataDir(extensionId),
permissions: this.registry.get(extensionId)?.grantedPermissions ?? [],
storage: this.storage,
spawn: this.dependencies.spawn ?? this.defaultSpawn(),
onLog: (level, message) => {
this.logs.append(extensionId, level, 'core', message)
if (level === 'error') this.dependencies.onChange?.(extensionId, 'runtime')
},
onStateChange: () => this.dependencies.onChange?.(extensionId, 'runtime'),
onActionsChanged: () => {
this.syncRegisteredActions(extensionId, manifest.name)
this.dependencies.onChange?.(extensionId, 'actions')
},
queryMessages: (id, request) => this.queryMessages(id, request),
sendText: (id, request) => this.sendText(id, request),
sendImage: (id, request) => this.sendImage(id, request),
sendVideo: (id, request) => this.sendVideo(id, request),
aiChat: (_id, messages) => this.dependencies.aiChat(messages),
capabilities: (id) => this.buildCapabilitySnapshot(id)
})
this.hosts.set(extensionId, host)
await host.start()
}
private async stopHost(extensionId: string): Promise<void> {
const host = this.hosts.get(extensionId)
if (!host) return
this.hosts.delete(extensionId)
await host.stop()
this.actions.removeRuntime(extensionId)
}
private defaultSpawn(): (options: ExtensionHostSpawnOptions) => ExtensionHostChild {
// electron-vite 把主进程入口输出到 out/main,扩展宿主脚本与它同级。
return forkExtensionHost(path.join(__dirname, 'extensionHost.js'))
}
private syncDeclared(extensionId: string, manifest: ExtensionManifest): void {
this.actions.setDeclared(extensionId, manifest.name, manifest.contributions.automationActions)
}
private syncRegisteredActions(extensionId: string, extensionName: string): void {
const host = this.hosts.get(extensionId)
this.actions.setRegistered(extensionId, extensionName, host?.registeredActions() ?? [])
}
private listEventSubscribers(): Array<{
extensionId: string
subscriptions: ExtensionManifest['subscriptions']
deliver: (
envelope: Parameters<ExtensionEventBus['handleMessage']>[0] extends never
? never
: import('../../shared/extensions/events').ExtensionEventEnvelope
) => boolean
}> {
const subscribers: Array<{
extensionId: string
subscriptions: ExtensionManifest['subscriptions']
deliver: (
envelope: import('../../shared/extensions/events').ExtensionEventEnvelope
) => boolean
}> = []
for (const [extensionId, host] of this.hosts) {
const record = this.registry.get(extensionId)
const manifest = this.manifests.get(extensionId)
if (!record?.enabled || !manifest) continue
if (!hasExtensionPermission(record.grantedPermissions, 'messages.subscribe')) continue
if (host.snapshot().state !== 'active') continue
subscribers.push({
extensionId,
subscriptions: manifest.subscriptions,
deliver: (envelope) => host.deliverEvent(envelope)
})
}
return subscribers
}
private async queryMessages(
extensionId: string,
request: ExtensionMessagesQueryRequest
): Promise<ExtensionQueriedMessage[]> {
if (!this.dependencies.isDatabaseReady()) {
throw new ExtensionError('DATABASE_NOT_READY')
}
const conversationId = String(request?.conversationId || '').trim()
if (!conversationId || conversationId.length > 128) {
throw new ExtensionError('INVALID_REQUEST', '会话 id 不合法')
}
const limit = Math.max(1, Math.min(Number(request?.limit) || 50, 200))
const startTime = Number.isFinite(Number(request?.startTime))
? Number(request.startTime)
: Date.now() - 24 * 60 * 60 * 1000
const endTime = Number.isFinite(Number(request?.endTime)) ? Number(request.endTime) : Date.now()
if (endTime <= startTime) throw new ExtensionError('INVALID_REQUEST', '时间范围不合法')
if (endTime - startTime > 7 * 24 * 60 * 60 * 1000) {
throw new ExtensionError('INVALID_REQUEST', '单次查询范围不能超过 7 天')
}
const record = this.registry.get(extensionId)
if (!record?.enabled) throw new ExtensionError('EXTENSION_DISABLED')
return this.dependencies.queryMessages({
conversationId,
startTime,
endTime,
limit
})
}
private async sendText(
extensionId: string,
request: ExtensionSendTextRequest
): Promise<ExtensionSendTextResult> {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
const manifest = this.manifests.get(extensionId)
return this.sendGateway.sendText(
{
extensionId,
permissions: record.grantedPermissions,
conversationScope: manifest?.subscriptions?.conversationIds ?? []
},
request
)
}
private async sendImage(
extensionId: string,
request: ExtensionSendImageRequest
): Promise<ExtensionSendTextResult> {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
const manifest = this.manifests.get(extensionId)
return this.sendGateway.sendImage(
{
extensionId,
permissions: record.grantedPermissions,
conversationScope: manifest?.subscriptions?.conversationIds ?? []
},
request
)
}
private async sendVideo(
extensionId: string,
request: ExtensionSendVideoRequest
): Promise<ExtensionSendTextResult> {
const record = this.registry.get(extensionId)
if (!record) throw new ExtensionError('EXTENSION_NOT_FOUND')
if (!record.enabled) throw new ExtensionError('EXTENSION_DISABLED')
const manifest = this.manifests.get(extensionId)
return this.sendGateway.sendVideo(
{
extensionId,
permissions: record.grantedPermissions,
conversationScope: manifest?.subscriptions?.conversationIds ?? []
},
request
)
}
private async buildCapabilitySnapshot(extensionId: string): Promise<ExtensionCapabilitySnapshot> {
const record = this.registry.get(extensionId)
const granted = record?.grantedPermissions ?? []
const capability = await this.dependencies.getCapability().catch(() => null)
let licensed = false
if (hasExtensionPermission(granted as ExtensionPermission[], 'wechat.send.text')) {
const entitlement = await this.dependencies.checkEntitlement().catch(() => null)
licensed = entitlement?.ok === true
}
return {
extensionId,
enabled: record?.enabled === true,
permissions: [...granted],
platform: this.dependencies.platform ?? process.platform,
databaseReady: this.dependencies.isDatabaseReady(),
send: {
supported: Boolean(capability?.supported),
ready: Boolean(capability?.ready),
canSendText: Boolean(capability?.capabilities?.text),
canSendImage: Boolean(capability?.capabilities?.image),
canSendVideo: Boolean(capability?.capabilities?.video),
licensed,
message: capability?.message || '暂时无法获知微信发送能力'
},
ai: {
configured: false,
modelName: ''
}
}
}
private toInstalled(record: ExtensionRegistryRecord): InstalledExtension {
const manifest = this.readManifest(record.id)
const compatibility = manifest
? checkExtensionCompatibility(manifest, this.dependencies.appVersion)
: { compatible: false, code: 'manifest' as const, reason: '扩展文件缺失或 manifest 无法读取' }
const host = this.hosts.get(record.id)
const runtime = host
? host.snapshot()
: {
state: record.enabled ? ('active' as const) : ('inactive' as const),
since: record.updatedAt,
restarts: 0
}
return {
id: record.id,
name: manifest?.name || record.id,
version: manifest?.version || record.version,
apiVersion: manifest?.apiVersion || record.apiVersion,
...(manifest?.minAppVersion ? { minAppVersion: manifest.minAppVersion } : {}),
...(manifest?.description ? { description: manifest.description } : {}),
...(manifest?.author ? { author: manifest.author } : {}),
enabled: record.enabled,
installedAt: record.installedAt,
updatedAt: record.updatedAt,
compatibility,
permissions: manifest?.permissions ?? [],
grantedPermissions: record.grantedPermissions,
runtime,
pages: (manifest?.contributions.pages ?? []).map((page) => ({
id: page.id,
title: page.title
})),
automationActions: this.actions.summariesFor(record.id),
filesPresent: Boolean(manifest)
}
}
private readManifest(extensionId: string): ExtensionManifest | null {
if (this.manifests.has(extensionId)) return this.manifests.get(extensionId) ?? null
const file = path.join(this.paths.installDir(extensionId), 'manifest.json')
let manifest: ExtensionManifest | null = null
try {
const parsed = parseExtensionManifest(fs.readJsonSync(file) as unknown)
manifest = parsed.ok ? (parsed.manifest ?? null) : null
} catch {
manifest = null
}
this.manifests.set(extensionId, manifest)
return manifest
}
}
function failure(error: unknown): ExtensionOperationResult {
const payload = toExtensionErrorPayload(error)
return { success: false, error: payload }
}
+65
View File
@@ -0,0 +1,65 @@
import path from 'node:path'
import { app } from 'electron'
/**
* 扩展相关目录的唯一解析器。
*
* **所有扩展文件都在 `userData` 下**,与安装目录 / `app.asar` / 源码树完全分离:
* 官方升级只替换应用本体,不会碰这三个目录。Windows 与 macOS 的差异由
* `app.getPath('userData')` 吸收,调用方不假设任何绝对路径。
*
* ```text
* <userData>/extensions/<id>/ 扩展代码(manifest + ui + background)
* <userData>/extensions-data/<id>/ 扩展私有数据(配置、缓存)
* <userData>/extensions-state/ 宿主状态(registry、日志)
* <userData>/extensions-staging/ 安装临时目录(成功后原子改名,不留半装状态)
* ```
*/
export interface ExtensionPaths {
userData: string
extensionsDir: string
dataDir: string
stateDir: string
stagingDir: string
registryFile: string
logsDir: string
installDir: (extensionId: string) => string
extensionDataDir: (extensionId: string) => string
logFile: (extensionId: string) => string
stagingPath: (prefix: string) => string
}
export function createExtensionPaths(userData: string): ExtensionPaths {
const extensionsDir = path.join(userData, 'extensions')
const dataDir = path.join(userData, 'extensions-data')
const stateDir = path.join(userData, 'extensions-state')
const stagingDir = path.join(userData, 'extensions-staging')
const logsDir = path.join(stateDir, 'logs')
return {
userData,
extensionsDir,
dataDir,
stateDir,
stagingDir,
registryFile: path.join(stateDir, 'registry.json'),
logsDir,
installDir: (extensionId) => path.join(extensionsDir, extensionId),
extensionDataDir: (extensionId) => path.join(dataDir, extensionId),
logFile: (extensionId) => path.join(logsDir, `${extensionId}.jsonl`),
stagingPath: (prefix) => path.join(stagingDir, `${prefix}-${Date.now().toString(36)}`)
}
}
let cached: ExtensionPaths | null = null
/** 懒解析:`app.getPath` 必须在 app ready 之后才可靠。 */
export function getExtensionPaths(): ExtensionPaths {
if (!cached) cached = createExtensionPaths(app.getPath('userData'))
return cached
}
/** 判断 `child` 是否在 `parent` 内(含自身)。符号链接需调用方先 realpath。 */
export function isPathInside(parent: string, child: string): boolean {
const relative = path.relative(path.resolve(parent), path.resolve(child))
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
}
+101
View File
@@ -0,0 +1,101 @@
import { promises as fs } from 'node:fs'
import path from 'node:path'
import { protocol } from 'electron'
import { isSafeRelativeEntryPath } from '../../shared/extensions/manifest'
import { isPathInside, type ExtensionPaths } from './extension-paths'
export const EXTENSION_SCHEME = 'tm-extension'
const MIME_TYPES: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.htm': 'text/html; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.css': 'text/css; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.txt': 'text/plain; charset=utf-8',
'.svg': 'image/svg+xml',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.woff': 'font/woff',
'.woff2': 'font/woff2',
'.wasm': 'application/wasm'
}
/**
* 扩展页面协议:只接受 `tm-extension://<extensionId>/<path>`,realpath 必须仍在
* 扩展目录内;响应带严格 CSP(无外链、无内联脚本、无网络)。
*
* `registerSchemesAsPrivileged` 必须在 app ready 前调用。
*/
export function registerExtensionScheme(): void {
protocol.registerSchemesAsPrivileged([
{
scheme: EXTENSION_SCHEME,
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: false,
stream: true
}
}
])
}
export function installExtensionProtocolHandler(paths: ExtensionPaths): 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 = paths.installDir(extensionId)
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'
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:",
"font-src 'self' data:",
"connect-src 'none'",
"object-src 'none'",
"base-uri 'none'",
"form-action 'none'"
].join('; '),
'X-Content-Type-Options': 'nosniff',
'Cache-Control': 'no-store'
}
})
} catch {
return notFound()
}
})
}
function notFound(): Response {
return new Response('Not found', {
status: 404,
headers: { 'Content-Type': 'text/plain; charset=utf-8' }
})
}
+155
View File
@@ -0,0 +1,155 @@
import fs from 'fs-extra'
import path from 'node:path'
import {
normalizeExtensionPermissions,
type ExtensionPermission
} from '../../shared/extensions/permissions'
import { EXTENSION_API_VERSION } from '../../shared/extensions/manifest'
/**
* 宿主侧的扩展安装状态。
*
* **manifest 不是状态的一部分**:它以扩展目录里的 `manifest.json` 为准,
* 升级扩展只替换目录、不动这里的启用状态与权限授予。
*/
export interface ExtensionRegistryRecord {
id: string
version: string
apiVersion: string
enabled: boolean
grantedPermissions: ExtensionPermission[]
installedAt: number
updatedAt: number
source: 'directory' | 'package'
}
interface RegistryFile {
version: number
extensions: ExtensionRegistryRecord[]
}
const REGISTRY_VERSION = 1
function normalizeRecord(value: unknown): ExtensionRegistryRecord | null {
if (!value || typeof value !== 'object') return null
const raw = value as Partial<ExtensionRegistryRecord>
const id = String(raw.id || '').trim()
if (!id) return null
const installedAt = Number(raw.installedAt) || 0
return {
id,
version: String(raw.version || '0.0.0'),
apiVersion: String(raw.apiVersion || EXTENSION_API_VERSION),
// 缺字段一律视为未启用:不能因为文件被手工改坏就自动跑任意代码。
enabled: raw.enabled === true,
grantedPermissions: normalizeExtensionPermissions(raw.grantedPermissions),
installedAt,
updatedAt: Number(raw.updatedAt) || installedAt,
source: raw.source === 'package' ? 'package' : 'directory'
}
}
export interface ExtensionRegistryDependencies {
registryFile: string
now?: () => number
}
export class ExtensionRegistry {
private readonly registryFile: string
private readonly now: () => number
private state: RegistryFile = { version: REGISTRY_VERSION, extensions: [] }
private loaded = false
constructor(dependencies: ExtensionRegistryDependencies) {
this.registryFile = dependencies.registryFile
this.now = dependencies.now ?? (() => Date.now())
}
list(): ExtensionRegistryRecord[] {
this.ensureLoaded()
return this.state.extensions.map((record) => ({
...record,
grantedPermissions: [...record.grantedPermissions]
}))
}
get(id: string): ExtensionRegistryRecord | undefined {
const key = String(id || '').trim()
if (!key) return undefined
return this.list().find((record) => record.id === key)
}
upsert(record: ExtensionRegistryRecord): ExtensionRegistryRecord {
this.ensureLoaded()
const exists = this.state.extensions.some((item) => item.id === record.id)
const next = exists
? this.state.extensions.map((item) => (item.id === record.id ? record : item))
: [...this.state.extensions, record]
this.commit(next)
return { ...record, grantedPermissions: [...record.grantedPermissions] }
}
remove(id: string): boolean {
this.ensureLoaded()
const next = this.state.extensions.filter((item) => item.id !== id)
if (next.length === this.state.extensions.length) return false
this.commit(next)
return true
}
setEnabled(id: string, enabled: boolean): ExtensionRegistryRecord | undefined {
const current = this.get(id)
if (!current) return undefined
return this.upsert({ ...current, enabled, updatedAt: this.now() })
}
setGrantedPermissions(
id: string,
permissions: ExtensionPermission[]
): ExtensionRegistryRecord | undefined {
const current = this.get(id)
if (!current) return undefined
return this.upsert({
...current,
grantedPermissions: normalizeExtensionPermissions(permissions),
updatedAt: this.now()
})
}
private ensureLoaded(): void {
if (this.loaded) return
this.loaded = true
try {
const raw = fs.readJsonSync(this.registryFile) as unknown
if (!raw || typeof raw !== 'object') return
const list = (raw as { extensions?: unknown }).extensions
if (!Array.isArray(list)) return
this.state = {
version: REGISTRY_VERSION,
extensions: list
.map((item) => normalizeRecord(item))
.filter((item): item is ExtensionRegistryRecord => item !== null)
}
} catch {
// 文件不存在 / 损坏都按「没有装过扩展」处理,不阻塞应用启动。
}
}
private commit(extensions: ExtensionRegistryRecord[]): void {
const previous = this.state
this.state = { version: REGISTRY_VERSION, extensions }
try {
this.persist()
} catch (error) {
this.state = previous
throw error
}
}
private persist(): void {
fs.ensureDirSync(path.dirname(this.registryFile))
const temporary = `${this.registryFile}.tmp`
fs.writeJsonSync(temporary, this.state, { spaces: 2 })
fs.moveSync(temporary, this.registryFile, { overwrite: true })
}
}
@@ -0,0 +1,358 @@
import { createHash } from 'node:crypto'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { ExtensionError } from '../../shared/extensions/errors'
import {
hasExtensionPermission,
type ExtensionPermission
} from '../../shared/extensions/permissions'
import type {
ExtensionSendImageRequest,
ExtensionSendTextRequest,
ExtensionSendTextResult,
ExtensionSendVideoRequest
} from '../../shared/extensions/rpc'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
import type { ExtensionEntitlementResult } from './extension-entitlement'
import { isPathInside } from './extension-paths'
const MAX_TEXT_LENGTH = 2_000
const MAX_RECIPIENT_LENGTH = 128
const MAX_MEDIA_BYTES = 100 * 1024 * 1024
const SEND_INTERVAL_MS = 2_000
const SEND_WINDOW_MS = 60_000
const SEND_WINDOW_LIMIT = 10
/** 原生发送端把视频按 `type: 'video'` 提交,这里只放行常见容器。 */
const IMAGE_EXTENSIONS = new Set(['.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp'])
const VIDEO_EXTENSIONS = new Set(['.mp4', '.mov', '.m4v'])
export interface ExtensionSendContext {
extensionId: string
permissions: ExtensionPermission[]
/** manifest 声明的会话范围;空数组表示不限制。 */
conversationScope: string[]
}
export interface ExtensionSendGatewayDependencies {
getCapability: () => Promise<PersonalWechatSendCapability>
checkEntitlement: () => Promise<ExtensionEntitlementResult>
executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
/** 扩展数据目录;媒体文件只允许从这里或系统临时目录发送。 */
getExtensionDataRoot?: (extensionId: string) => string
now?: () => number
}
/**
* 扩展发送出口:权限 / 范围 / 授权 / 频率通过后交给 WechatActionGateway。
*
* origin、purpose、triggerType、幂等键全部由宿主填写,扩展只描述
* 「发给谁、发什么」。
*/
export class ExtensionSendGateway {
private readonly getCapability: () => Promise<PersonalWechatSendCapability>
private readonly checkEntitlement: () => Promise<ExtensionEntitlementResult>
private readonly executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
private readonly getExtensionDataRoot: (extensionId: string) => string
private readonly now: () => number
private readonly sendHistory = new Map<string, number[]>()
constructor(dependencies: ExtensionSendGatewayDependencies) {
this.getCapability = dependencies.getCapability
this.checkEntitlement = dependencies.checkEntitlement
this.executeAction = dependencies.executeAction
this.getExtensionDataRoot = dependencies.getExtensionDataRoot ?? (() => '')
this.now = dependencies.now ?? (() => Date.now())
}
async sendText(
context: ExtensionSendContext,
request: ExtensionSendTextRequest
): Promise<ExtensionSendTextResult> {
if (!hasExtensionPermission(context.permissions, 'wechat.send.text')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.text 权限')
}
const to = String(request?.to || '').trim()
const text = String(request?.text || '').trim()
if (!to || to.length > MAX_RECIPIENT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法')
}
if (!text || text.length > MAX_TEXT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '发送内容不能为空且不能超过 2000 字')
}
if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) {
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围')
}
const at = normalizeAt(request?.at, to)
this.assertRateLimit(context.extensionId)
const capability = await this.getCapability().catch(() => null)
if (!capability || !capability.supported) {
throw new ExtensionError(
'SEND_NOT_SUPPORTED',
capability?.message || '当前环境不支持微信发送'
)
}
if (!capability.ready || !capability.capabilities?.text) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
capability.message || '个人微信发送能力尚未就绪'
)
}
const entitlement = await this.checkEntitlement()
if (!entitlement.ok) {
throw new ExtensionError('LICENSE_REQUIRED', entitlement.message)
}
const result = await this.executeAction({
...(request.dedupeKey
? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) }
: {}),
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to },
content: { type: 'text', text, ...(at ? { at } : {}) },
metadata: { extensionId: context.extensionId }
})
if (result.status === 'sent') {
return { actionId: result.actionId, status: 'sent' }
}
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
}
/**
* 发送图片。
*
* 文件边界是硬性的:只允许扩展数据目录或系统临时目录里的普通文件,
* 否则扩展就能借 TraceMemo 把本机任意文件发出去。
*/
async sendImage(
context: ExtensionSendContext,
request: ExtensionSendImageRequest
): Promise<ExtensionSendTextResult> {
if (!hasExtensionPermission(context.permissions, 'wechat.send.image')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.image 权限')
}
const to = String(request?.to || '').trim()
if (!to || to.length > MAX_RECIPIENT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法')
}
if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) {
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围')
}
const mediaPath = assertSendableMediaPath(
request?.path,
this.getExtensionDataRoot(context.extensionId),
IMAGE_EXTENSIONS
)
this.assertRateLimit(context.extensionId)
const capability = await this.getCapability().catch(() => null)
if (!capability || !capability.supported) {
throw new ExtensionError(
'SEND_NOT_SUPPORTED',
capability?.message || '当前环境不支持微信发送'
)
}
if (!capability.ready || !capability.capabilities?.image) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
capability.message || '个人微信发送能力尚未就绪'
)
}
const entitlement = await this.checkEntitlement()
if (!entitlement.ok) {
throw new ExtensionError('LICENSE_REQUIRED', entitlement.message)
}
const result = await this.executeAction({
...(request.dedupeKey
? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) }
: {}),
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to },
content: { type: 'image', path: mediaPath },
metadata: { extensionId: context.extensionId }
})
if (result.status === 'sent') {
return { actionId: result.actionId, status: 'sent' }
}
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
}
/**
* 发送视频。
*
* 与图片分开是刻意的:原生 Host 用 `type: 'video'` 提交,失败时不能悄悄降级成图片。
* 文件边界与图片相同(扩展数据目录 / 临时目录、普通文件、≤ 100MB)。
*/
async sendVideo(
context: ExtensionSendContext,
request: ExtensionSendVideoRequest
): Promise<ExtensionSendTextResult> {
if (!hasExtensionPermission(context.permissions, 'wechat.send.video')) {
throw new ExtensionError('PERMISSION_DENIED', '扩展没有 wechat.send.video 权限')
}
const to = String(request?.to || '').trim()
if (!to || to.length > MAX_RECIPIENT_LENGTH) {
throw new ExtensionError('INVALID_REQUEST', '接收会话 id 不合法')
}
if (context.conversationScope.length > 0 && !context.conversationScope.includes(to)) {
throw new ExtensionError('PERMISSION_DENIED', '目标会话超出扩展声明的范围')
}
const mediaPath = assertSendableMediaPath(
request?.path,
this.getExtensionDataRoot(context.extensionId),
VIDEO_EXTENSIONS
)
this.assertRateLimit(context.extensionId)
const capability = await this.getCapability().catch(() => null)
if (!capability || !capability.supported) {
throw new ExtensionError(
'SEND_NOT_SUPPORTED',
capability?.message || '当前环境不支持微信发送'
)
}
if (!capability.ready || !capability.capabilities?.video) {
throw new ExtensionError(
'CAPABILITY_UNAVAILABLE',
capability.message || '当前微信发送能力不支持视频'
)
}
const entitlement = await this.checkEntitlement()
if (!entitlement.ok) {
throw new ExtensionError('LICENSE_REQUIRED', entitlement.message)
}
const result = await this.executeAction({
...(request.dedupeKey
? { idempotencyKey: extensionIdempotencyKey(context.extensionId, request.dedupeKey) }
: {}),
origin: 'extension',
purpose: 'extension_send',
triggerType: 'automation',
recipient: { type: to.endsWith('@chatroom') ? 'group' : 'contact', id: to },
content: { type: 'video', path: mediaPath },
metadata: { extensionId: context.extensionId }
})
if (result.status === 'sent') {
return { actionId: result.actionId, status: 'sent' }
}
throw new ExtensionError(mapGatewayError(result.errorCode), result.reason || '微信发送失败')
}
/** 令牌窗口:同一扩展 60 秒内最多 10 条,且两条之间至少 2 秒。 */
private assertRateLimit(extensionId: string): void {
const now = this.now()
const history = (this.sendHistory.get(extensionId) ?? []).filter(
(timestamp) => now - timestamp < SEND_WINDOW_MS
)
const last = history[history.length - 1]
if (last !== undefined && now - last < SEND_INTERVAL_MS) {
throw new ExtensionError('RATE_LIMITED', '发送过于频繁,请稍后再试')
}
if (history.length >= SEND_WINDOW_LIMIT) {
throw new ExtensionError('RATE_LIMITED', '已达到每分钟发送上限')
}
history.push(now)
this.sendHistory.set(extensionId, history)
}
}
/**
* 媒体路径校验:必须是扩展数据目录或系统临时目录内的普通文件。
*
* 用 realpath 复核,符号链接跳到目录外同样会被拒绝;这一层不能省,
* 否则 `wechat.send.image` 就等价于「读取并外发任意本机文件」。
*/
function assertSendableMediaPath(value: unknown, dataRoot: string, allowed: Set<string>): string {
const raw = String(value ?? '').trim()
if (!raw || raw.length > 4_096) {
throw new ExtensionError('INVALID_REQUEST', '媒体路径不合法')
}
if (!path.isAbsolute(raw)) {
throw new ExtensionError('INVALID_REQUEST', '媒体路径必须是绝对路径')
}
let realPath: string
try {
realPath = fs.realpathSync(raw)
} catch {
throw new ExtensionError('INVALID_REQUEST', '媒体文件不存在')
}
const stat = fs.statSync(realPath)
if (!stat.isFile()) {
throw new ExtensionError('INVALID_REQUEST', '媒体路径必须是普通文件')
}
if (stat.size <= 0 || stat.size > MAX_MEDIA_BYTES) {
throw new ExtensionError('INVALID_REQUEST', '媒体文件为空或超过 100MB')
}
const extension = path.extname(realPath).toLowerCase()
if (!allowed.has(extension)) {
throw new ExtensionError('SEND_NOT_SUPPORTED', `不支持发送 ${extension || '无扩展名'} 文件`)
}
const roots = [dataRoot, os.tmpdir()]
.filter(Boolean)
.map((root) => {
try {
return fs.realpathSync(root)
} catch {
return ''
}
})
.filter(Boolean)
if (!roots.some((root) => isPathInside(root, realPath))) {
throw new ExtensionError('PERMISSION_DENIED', '只能发送扩展数据目录或临时目录中的文件')
}
return realPath
}
function normalizeAt(value: unknown, recipientId: string): Record<string, string> | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined
if (!recipientId.endsWith('@chatroom')) return undefined
const entries = Object.entries(value as Record<string, unknown>)
if (!entries.length || entries.length > 50) return undefined
const result: Record<string, string> = {}
for (const [wxid, name] of entries) {
const key = String(wxid).trim()
if (!key || typeof name !== 'string' || !name.trim()) continue
result[key] = name.trim()
}
return Object.keys(result).length ? result : undefined
}
/** 扩展提供的去重键只作为后缀,前缀固定,避免与官方自动化幂等键串台。 */
export function extensionIdempotencyKey(extensionId: string, dedupeKey: string): string {
const digest = createHash('sha1')
.update(`${extensionId}\u0001${String(dedupeKey).trim()}`)
.digest('hex')
return `extension:${extensionId}:${digest}`
}
function mapGatewayError(
code: string | undefined
): 'CAPABILITY_UNAVAILABLE' | 'PERMISSION_DENIED' | 'ACTION_FAILED' | 'INVALID_REQUEST' {
switch (code) {
case 'SEND_CAPABILITY_UNAVAILABLE':
case 'SEND_NOT_READY':
return 'CAPABILITY_UNAVAILABLE'
case 'ACTION_NOT_ALLOWED':
case 'RECIPIENT_SCOPE_VIOLATION':
return 'PERMISSION_DENIED'
case 'INVALID_REQUEST':
case 'INVALID_RECIPIENT':
return 'INVALID_REQUEST'
default:
return 'ACTION_FAILED'
}
}
+128
View File
@@ -0,0 +1,128 @@
import { AIProviderService } from '../services/ai-provider-service'
import {
getChatDb,
getSelfAccountInfo,
isReady,
listContacts,
listMessagesAsync,
resolveMd5
} from '../services/chat-service'
import { personalWechatCapabilityService } from '../services/personal-wechat-capability-service'
import { wechatActionGateway } from '../services/wechat-action-gateway'
import { ExtensionError } from '../../shared/extensions/errors'
import type {
ExtensionMessagesQueryRequest,
ExtensionQueriedMessage
} from '../../shared/extensions/rpc'
import { checkExtensionSendEntitlement } from './extension-entitlement'
import { ExtensionManager } from './extension-manager'
import { getExtensionPaths } from './extension-paths'
let manager: ExtensionManager | null = null
export interface ExtensionSystemOptions {
appVersion: string
onChange: (extensionId: string, reason: string) => void
}
/**
* 扩展系统的主进程接线。
*
* 这里只做依赖注入:所有能力都来自既有服务,扩展系统自己不实现第二套
* 消息监听、发送通道或 AI Provider。
*/
export async function initExtensionSystem(options: ExtensionSystemOptions): Promise<void> {
if (manager) return
manager = new ExtensionManager({
paths: getExtensionPaths(),
appVersion: options.appVersion,
getCapability: () => personalWechatCapabilityService.getPersonalWechatSendCapability(),
checkEntitlement: () => checkExtensionSendEntitlement(),
executeAction: (request) => wechatActionGateway.execute(request),
queryMessages: queryConversationMessages,
listGroups: async () => {
try {
return listContacts()
.filter((contact) => contact.type === 'group')
.map((contact) => ({
id: contact.m_nsUsrName,
name: contact.m_nsNickName || contact.m_nsUsrName
}))
} catch {
return []
}
},
aiChat: chatWithConfiguredProvider,
getAccountId: () => String(getSelfAccountInfo()?.wxid || ''),
getSelfUsernames: () => {
try {
return (getChatDb()?.getWcdb4Client()?.getMyUsernameCandidates?.() ?? []).filter(Boolean)
} catch {
return []
}
},
isDatabaseReady: () => {
try {
return isReady()
} catch {
return false
}
},
onChange: (extensionId, reason) => options.onChange(extensionId, reason)
})
await manager.initialize()
}
export function getExtensionManager(): ExtensionManager {
if (!manager) throw new Error('扩展系统尚未初始化')
return manager
}
export function hasExtensionManager(): boolean {
return manager !== null
}
export async function disposeExtensionSystem(): Promise<void> {
const current = manager
manager = null
if (current) await current.dispose()
}
async function queryConversationMessages(
request: ExtensionMessagesQueryRequest
): Promise<ExtensionQueriedMessage[]> {
const contact = resolveMd5(request.conversationId)
if (!contact?.md5) throw new ExtensionError('DATABASE_NOT_READY', '找不到该会话或数据库未连接')
const messages = await listMessagesAsync(
contact.md5,
Math.floor((request.startTime ?? Date.now() - 86_400_000) / 1000),
Math.floor((request.endTime ?? Date.now()) / 1000),
{ limit: request.limit ?? 50 },
'',
'unknown'
)
return messages.map((message) => ({
messageId: message.serverId || String(message.localId ?? message.id),
conversationId: request.conversationId,
...(message.senderId ? { senderId: message.senderId } : {}),
...(message.name ? { senderName: message.name } : {}),
isSelf: message.isSender === true,
type: message.type,
...(message.type === 'text' ? { text: message.content } : {}),
timestamp: Math.round((message.createTime ?? 0) * 1000)
}))
}
async function chatWithConfiguredProvider(
messages: Array<{ role: string; content: string }>
): Promise<{ text: string }> {
const result = await new AIProviderService().chat(messages)
if (!result.success) {
throw new ExtensionError('CAPABILITY_UNAVAILABLE', result.error || 'AI 调用失败')
}
return { text: result.data || '' }
}
export function extensionManagerForTests(value: ExtensionManager | null): void {
manager = value
}
+142
View File
@@ -0,0 +1,142 @@
import fs from 'fs-extra'
import path from 'node:path'
import { ExtensionError } from '../../shared/extensions/errors'
const STORAGE_FILE = 'storage.json'
const STORAGE_VERSION = 1
const MAX_KEY_LENGTH = 64
const MAX_VALUE_BYTES = 256 * 1024
const MAX_TOTAL_BYTES = 1024 * 1024
const KEY_PATTERN = /^[A-Za-z0-9._-]{1,64}$/
interface StorageFile {
version: number
values: Record<string, unknown>
}
export interface ExtensionStorageDependencies {
/** 通常是 `<userData>/extensions-data`。 */
dataRoot: string
maxTotalBytes?: number
maxValueBytes?: number
}
/**
* 扩展私有的键值存储。
*
* 边界:
* - 每个扩展一个独立目录,键空间互不可见;
* - 单值 / 总量都有上限,写入前先序列化,**不存无法序列化的值**;
* - 卸载时由 `ExtensionInstaller` 决定是否删除,本类不主动清理。
*/
export class ExtensionStorage {
private readonly dataRoot: string
private readonly maxTotalBytes: number
private readonly maxValueBytes: number
constructor(dependencies: ExtensionStorageDependencies) {
this.dataRoot = dependencies.dataRoot
this.maxTotalBytes = dependencies.maxTotalBytes ?? MAX_TOTAL_BYTES
this.maxValueBytes = dependencies.maxValueBytes ?? MAX_VALUE_BYTES
}
filePath(extensionId: string): string {
return path.join(this.dataRoot, extensionId, STORAGE_FILE)
}
directory(extensionId: string): string {
return path.join(this.dataRoot, extensionId)
}
get(extensionId: string, key: unknown): unknown {
const name = assertKey(key)
const values = this.read(extensionId).values
return Object.prototype.hasOwnProperty.call(values, name) ? clone(values[name]) : undefined
}
set(extensionId: string, key: unknown, value: unknown): void {
const name = assertKey(key)
const serialized = serializeValue(value)
if (Buffer.byteLength(serialized, 'utf8') > this.maxValueBytes) {
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '单个存储值超出上限')
}
const file = this.read(extensionId)
file.values[name] = JSON.parse(serialized)
this.assertTotalSize(file)
this.write(extensionId, file)
}
remove(extensionId: string, key: unknown): boolean {
const name = assertKey(key)
const file = this.read(extensionId)
if (!Object.prototype.hasOwnProperty.call(file.values, name)) return false
delete file.values[name]
this.write(extensionId, file)
return true
}
list(extensionId: string): Array<{ key: string; value: unknown }> {
const values = this.read(extensionId).values
return Object.keys(values).map((key) => ({ key, value: clone(values[key]) }))
}
clear(extensionId: string): void {
this.write(extensionId, { version: STORAGE_VERSION, values: {} })
}
private read(extensionId: string): StorageFile {
const filePath = this.filePath(extensionId)
try {
const raw = fs.readJsonSync(filePath) as unknown
if (!raw || typeof raw !== 'object') return { version: STORAGE_VERSION, values: {} }
const values = (raw as { values?: unknown }).values
if (!values || typeof values !== 'object' || Array.isArray(values)) {
return { version: STORAGE_VERSION, values: {} }
}
return { version: STORAGE_VERSION, values: values as Record<string, unknown> }
} catch {
return { version: STORAGE_VERSION, values: {} }
}
}
private write(extensionId: string, file: StorageFile): void {
const filePath = this.filePath(extensionId)
fs.ensureDirSync(path.dirname(filePath))
const temporary = `${filePath}.tmp`
fs.writeJsonSync(temporary, file, { spaces: 2 })
fs.moveSync(temporary, filePath, { overwrite: true })
}
private assertTotalSize(file: StorageFile): void {
const bytes = Buffer.byteLength(JSON.stringify(file.values), 'utf8')
if (bytes > this.maxTotalBytes) {
throw new ExtensionError('STORAGE_LIMIT_EXCEEDED', '扩展存储总量超出上限')
}
}
}
function assertKey(value: unknown): string {
if (typeof value !== 'string') throw new ExtensionError('INVALID_REQUEST', '存储键必须是字符串')
const key = value.trim()
if (!KEY_PATTERN.test(key)) {
throw new ExtensionError('INVALID_REQUEST', '存储键只能包含字母、数字、点、下划线与短横线')
}
if (key.length > MAX_KEY_LENGTH) throw new ExtensionError('INVALID_REQUEST', '存储键过长')
return key
}
function serializeValue(value: unknown): string {
if (value === undefined) throw new ExtensionError('INVALID_REQUEST', '不能存储 undefined')
try {
const serialized = JSON.stringify(value)
if (serialized === undefined) throw new Error('unsupported')
return serialized
} catch {
throw new ExtensionError('INVALID_REQUEST', '存储值必须可序列化为 JSON')
}
}
function clone<T>(value: T): T {
if (value === null || typeof value !== 'object') return value
return JSON.parse(JSON.stringify(value)) as T
}
+545
View File
@@ -0,0 +1,545 @@
/**
* 扩展后台进程入口。
*
* 这个文件**跑在子进程里**,不是主进程:它只负责加载扩展代码、构造受限 SDK、
* 把请求转成白名单 RPC。任何 `require` 都只发生在这里,主进程永远不会加载
* 第三方扩展代码。
*
* 与主进程的协议见 `src/shared/extensions/rpc.ts`。
*/
import fs from 'node:fs'
import path from 'node:path'
import { randomUUID } from 'node:crypto'
import {
EXTENSION_HOST_PROTOCOL_VERSION,
type ExtensionAutomationActionOutput,
type ExtensionHostActivate,
type ExtensionHostCall,
type ExtensionHostCallResult,
type ExtensionHostEvent,
type ExtensionHostInboundMessage,
type ExtensionHostInvokeAction,
type ExtensionHostTestSend,
type ExtensionHostOutboundMessage,
type ExtensionHostRegisterAction
} from '../../shared/extensions/rpc'
import type { ExtensionMessageEvent } from '../../shared/extensions/events'
type MessageHandler = (event: ExtensionMessageEvent) => void | Promise<void>
interface RegisteredActionDefinition {
id: string
title: string
description?: string
inputSchema?: Record<string, unknown>
handler: (input: Record<string, unknown>) => unknown
}
interface PendingCall {
resolve: (value: unknown) => void
reject: (error: Error) => void
timer: ReturnType<typeof setTimeout>
}
const pendingCalls = new Map<string, PendingCall>()
const eventHandlers = new Set<MessageHandler>()
const actions = new Map<string, RegisteredActionDefinition>()
let permissions: string[] = []
let activated = false
let extensionDir = ''
let extensionDataDir = ''
let extensionId = process.env.TM_EXTENSION_ID || ''
function post(message: ExtensionHostOutboundMessage): void {
if (typeof process.send !== 'function') return
try {
process.send(message)
} catch {
// 父进程已断开;子进程会在 shutdown 或退出时结束。
}
}
function sendLog(level: 'info' | 'warn' | 'error', message: string): void {
post({ type: 'log', version: EXTENSION_HOST_PROTOCOL_VERSION, level, message })
}
function requirePermission(permission: string): void {
if (!permissions.includes(permission)) {
const error = new Error(`扩展没有 ${permission} 权限`)
;(error as Error & { code?: string }).code = 'PERMISSION_DENIED'
throw error
}
}
/** 白名单 RPC:扩展只能申请这些能力,且每次都要过权限检查。 */
function callHost(
method: ExtensionHostCall['method'],
params: Record<string, unknown>,
timeoutMs = 8_000
): Promise<unknown> {
if (!activated) return Promise.reject(new Error('扩展尚未激活'))
const callId = randomUUID()
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pendingCalls.delete(callId)
reject(Object.assign(new Error('宿主调用超时'), { code: 'ACTION_TIMEOUT' }))
}, timeoutMs)
pendingCalls.set(callId, { resolve, reject, timer })
post({ type: 'call', version: EXTENSION_HOST_PROTOCOL_VERSION, callId, method, params })
})
}
const tm = {
extension: {
get id(): string {
return extensionId
},
/** 扩展私有数据目录;下载/生成的媒体应放在这里。 */
get dataDir(): string {
return extensionDataDir
},
get permissions(): string[] {
return [...permissions]
}
},
events: {
on(name: 'message.received', handler: MessageHandler): () => void {
if (name !== 'message.received' || typeof handler !== 'function') return () => undefined
eventHandlers.add(handler)
return () => eventHandlers.delete(handler)
},
off(name: 'message.received', handler: MessageHandler): void {
if (name !== 'message.received') return
eventHandlers.delete(handler)
}
},
messages: {
async query(request: {
conversationId: string
startTime?: number
endTime?: number
limit?: number
}): Promise<{ messages: unknown[] }> {
requirePermission('messages.query')
const result = (await callHost('messages.query', { ...request })) as { messages: unknown[] }
return result
}
},
wechat: {
/**
* 发送文本、图片或视频。
*
* 兼容旧调用:不传 `type` 视为 `text`。视频走独立的 video 通道,
* 原生 Host 以 `{toWxid, type:'video', msg:<路径>}` 提交。
*/
async send(request: {
type?: 'text' | 'image' | 'video'
to: string
text?: string
path?: string
at?: Record<string, string>
dedupeKey?: string
}) {
const type =
request && (request.type === 'image' || request.type === 'video') ? request.type : 'text'
if (type === 'image' || type === 'video') {
requirePermission(type === 'video' ? 'wechat.send.video' : 'wechat.send.image')
return (await callHost(
type === 'video' ? 'wechat.send.video' : 'wechat.send.image',
{
to: request.to,
path: request.path,
...(request.dedupeKey ? { dedupeKey: request.dedupeKey } : {})
},
180_000
)) as {
actionId: string
status: 'sent'
}
}
requirePermission('wechat.send.text')
return (await callHost(
'wechat.send.text',
{
to: request.to,
text: request.text,
...(request.at ? { at: request.at } : {}),
...(request.dedupeKey ? { dedupeKey: request.dedupeKey } : {})
},
20_000
)) as {
actionId: string
status: 'sent'
}
}
},
ai: {
async chat(messages: Array<{ role: string; content: string }>) {
requirePermission('ai.chat')
return (await callHost('ai.chat', { messages }, 60_000)) as { text: string }
}
},
storage: {
async get(key: string): Promise<unknown> {
requirePermission('storage')
return callHost('storage.get', { key })
},
async set(key: string, value: unknown): Promise<void> {
requirePermission('storage')
await callHost('storage.set', { key, value })
},
async remove(key: string): Promise<boolean> {
requirePermission('storage')
const result = (await callHost('storage.remove', { key })) as { removed?: boolean }
return result.removed === true
},
async list(): Promise<Array<{ key: string; value: unknown }>> {
requirePermission('storage')
const result = (await callHost('storage.list', {})) as {
entries?: Array<{ key: string; value: unknown }>
}
return result.entries ?? []
}
},
automation: {
registerAction(definition: {
id: string
title: string
description?: string
inputSchema?: Record<string, unknown>
handler: (input: Record<string, unknown>) => unknown
}): void {
requirePermission('automation.action')
const id = String(definition?.id || '').trim()
if (!/^[a-z0-9][a-z0-9._-]{1,63}$/.test(id)) throw new Error('动作 id 不合法')
if (typeof definition.handler !== 'function') throw new Error('动作必须提供 handler')
const title = String(definition.title || id)
.trim()
.slice(0, 60)
if (!title) throw new Error('动作 title 不能为空')
actions.set(id, {
id,
title,
...(definition.description
? { description: String(definition.description).slice(0, 200) }
: {}),
...(definition.inputSchema ? { inputSchema: definition.inputSchema } : {}),
handler: definition.handler
})
const message: ExtensionHostRegisterAction = {
type: 'register-action',
version: EXTENSION_HOST_PROTOCOL_VERSION,
action: {
id,
title,
...(definition.description
? { description: String(definition.description).slice(0, 200) }
: {}),
hasInputSchema: Boolean(definition.inputSchema)
}
}
post(message)
}
},
capabilities: {
async get(): Promise<unknown> {
return callHost('capabilities.get', {})
}
},
log: {
info(message: unknown): void {
sendLog('info', String(message ?? ''))
},
warn(message: unknown): void {
sendLog('warn', String(message ?? ''))
},
error(message: unknown): void {
sendLog('error', String(message ?? ''))
}
}
}
/** 入口文件必须真实位于扩展目录内;符号链接与越界路径都会被拒绝。 */
function resolveBackgroundEntry(dir: string): string | null {
const manifestPath = path.join(dir, 'manifest.json')
let manifest: { entrypoints?: { background?: unknown } }
try {
manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8')) as typeof manifest
} catch {
return null
}
const relative = String(manifest.entrypoints?.background || '')
if (!relative) return null
const resolved = path.resolve(dir, relative)
try {
const realDir = fs.realpathSync(dir)
const realEntry = fs.realpathSync(resolved)
const inside = path.relative(realDir, realEntry)
if (!inside || inside.startsWith('..') || path.isAbsolute(inside)) return null
return realEntry
} catch {
return null
}
}
function pickExportedActivator(loaded: unknown): ((api: typeof tm) => unknown) | null {
if (typeof loaded === 'function') return loaded as (api: typeof tm) => unknown
if (loaded && typeof loaded === 'object') {
const candidate = (loaded as { activate?: unknown }).activate
if (typeof candidate === 'function') return candidate as (api: typeof tm) => unknown
}
return null
}
async function activate(message: ExtensionHostActivate): Promise<void> {
extensionId = message.extensionId
extensionDir = message.extensionDir
extensionDataDir = message.dataDir
permissions = Array.isArray(message.permissions) ? message.permissions : []
const entry = resolveBackgroundEntry(extensionDir)
if (!entry) {
post({
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: false,
error: { code: 'EXTENSION_INVALID_PATH', message: '后台入口文件不合法或不存在' }
})
return
}
try {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const loaded = require(entry) as unknown
const activator = pickExportedActivator(loaded)
if (activator) await activator(tm)
activated = true
post({ type: 'activated', version: EXTENSION_HOST_PROTOCOL_VERSION, ok: true })
} catch (error) {
activated = false
post({
type: 'activated',
version: EXTENSION_HOST_PROTOCOL_VERSION,
ok: false,
error: {
code: 'ACTION_FAILED',
message: error instanceof Error ? error.message.slice(0, 300) : '扩展激活失败'
}
})
}
}
async function dispatchEvent(message: ExtensionHostEvent): Promise<void> {
if (!activated) return
for (const handler of eventHandlers) {
try {
await withTimeout(Promise.resolve(handler(message.envelope.event)), 10_000)
} catch (error) {
sendLog('error', `消息处理失败:${error instanceof Error ? error.message : String(error)}`)
}
}
}
function validateActionInput(
schema: Record<string, unknown> | undefined,
input: Record<string, unknown>
): void {
if (!schema) return
const required = Array.isArray(schema.required) ? schema.required : []
for (const key of required) {
if (typeof key === 'string' && !(key in input)) {
throw new Error(`缺少必填参数:${key}`)
}
}
const properties = schema.properties
if (!properties || typeof properties !== 'object') return
for (const [key, definition] of Object.entries(properties as Record<string, unknown>)) {
if (!(key in input)) continue
const type = (definition as { type?: unknown })?.type
const value = input[key]
if (type === 'string' && typeof value !== 'string') throw new Error(`参数 ${key} 必须是字符串`)
if (type === 'number' && typeof value !== 'number') throw new Error(`参数 ${key} 必须是数字`)
if (type === 'boolean' && typeof value !== 'boolean')
throw new Error(`参数 ${key} 必须是布尔值`)
}
}
async function invokeAction(message: ExtensionHostInvokeAction): Promise<void> {
const definition = actions.get(message.actionId)
if (!definition) {
post({
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: { code: 'ACTION_FAILED', message: `动作不存在:${message.actionId}` }
})
return
}
try {
validateActionInput(definition.inputSchema, message.input)
const raw = await withTimeout(
Promise.resolve(definition.handler(message.input)),
Math.max(1_000, Math.min(message.timeoutMs - 500, 60_000))
)
const output = normalizeActionOutput(raw)
post({
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: output.success,
output,
...(output.success
? {}
: {
error: { code: 'ACTION_FAILED' as const, message: output.error || '扩展动作返回失败' }
})
})
} catch (error) {
post({
type: 'action-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: {
code:
error instanceof Error && /超时/.test(error.message) ? 'ACTION_TIMEOUT' : 'ACTION_FAILED',
message: error instanceof Error ? error.message.slice(0, 300) : '扩展动作执行失败'
}
})
}
}
function normalizeActionOutput(raw: unknown): ExtensionAutomationActionOutput {
if (!raw || typeof raw !== 'object') {
return { success: false, error: '动作必须返回对象' }
}
const value = raw as Partial<ExtensionAutomationActionOutput>
const reply = value.reply
const hasReply =
reply && reply.type === 'text' && typeof reply.text === 'string' && reply.text.trim().length > 0
return {
success: value.success !== false,
...(value.output && typeof value.output === 'object' ? { output: value.output } : {}),
...(hasReply
? {
reply: {
type: 'text' as const,
text: reply!.text.trim().slice(0, 2_000),
...(reply!.at && typeof reply!.at === 'object' ? { at: reply!.at } : {})
}
}
: {}),
...(typeof value.error === 'string' && value.error.trim()
? { error: value.error.trim().slice(0, 300) }
: {})
}
}
function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T> {
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('扩展处理超时')), timeoutMs)
promise.then(
(value) => {
clearTimeout(timer)
resolve(value)
},
(error) => {
clearTimeout(timer)
reject(error)
}
)
})
}
process.on('message', (raw: unknown) => {
if (!raw || typeof raw !== 'object') return
const message = raw as ExtensionHostInboundMessage
if (message.version !== EXTENSION_HOST_PROTOCOL_VERSION) return
switch (message.type) {
case 'activate':
void activate(message)
return
case 'event':
void dispatchEvent(message)
return
case 'invoke-action':
void invokeAction(message)
return
case 'test-send':
if (extensionId !== 'com.example.douyin-sender') return
void dispatchTestSend(message)
return
case 'call-result': {
const result = message as ExtensionHostCallResult
const pending = pendingCalls.get(result.callId)
if (!pending) return
clearTimeout(pending.timer)
pendingCalls.delete(result.callId)
if (result.ok) {
pending.resolve(result.result)
} else {
pending.reject(
Object.assign(new Error(result.error?.message || '宿主调用失败'), {
code: result.error?.code || 'ACTION_FAILED'
})
)
}
return
}
case 'shutdown':
process.exit(0)
}
})
async function dispatchTestSend(message: ExtensionHostTestSend): Promise<void> {
const handler = (
globalThis as typeof globalThis & {
__tmTestSend?: (params: Record<string, unknown>) => Promise<unknown>
}
).__tmTestSend
if (!handler) {
post({
type: 'test-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: { code: 'ACTION_FAILED', message: '测试处理器不可用' }
})
return
}
try {
const result = await handler(message.params)
post({
type: 'test-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: true,
result
})
} catch (error) {
post({
type: 'test-result',
version: EXTENSION_HOST_PROTOCOL_VERSION,
requestId: message.requestId,
ok: false,
error: {
code: 'ACTION_FAILED',
message: error instanceof Error ? error.message : '测试任务失败'
}
})
}
}
process.on('uncaughtException', (error) => {
sendLog('error', `未捕获异常:${error.message}`)
process.exit(1)
})
process.on('unhandledRejection', (reason) => {
sendLog(
'warn',
`未处理的 Promise 拒绝:${reason instanceof Error ? reason.message : String(reason)}`
)
})
// 让宿主知道进程已就绪,可以发 activate。必须在监听器之后发送。
post({ type: 'ready', version: EXTENSION_HOST_PROTOCOL_VERSION })
+57 -5
View File
@@ -141,6 +141,16 @@ import {
leaveNotificationContactDisplayName
} from './services/leave-notification-target'
import { MessageListenerService } from './services/message-listener-service'
import { EXTENSION_IPC } from '../shared/extensions/ipc'
import { installExtensionProtocolHandler, registerExtensionScheme } from './extensions/extension-protocol'
import { registerExtensionIpc } from './extensions/extension-ipc'
import { getExtensionPaths } from './extensions/extension-paths'
import {
disposeExtensionSystem,
getExtensionManager,
hasExtensionManager,
initExtensionSystem
} from './extensions/extension-service'
import { automationRuleStore } from './services/automation-rule-store'
import { automationExecutionLogService } from './services/automation-execution-log-service'
import { initAutomationService, getAutomationService } from './services/automation-service'
@@ -1079,8 +1089,10 @@ function createWindow(): void {
// Electron 初始化完成并准备创建浏览器窗口后,将调用此方法
// 某些 API 只能在此事件发生后使用
app.whenReady().then(async () => {
if (isLegacyMigrationHelper) {
/* 扩展页面走自定义协议;scheme 必须在 app ready 之前登记为特权协议。 */
registerExtensionScheme()
app.whenReady().then(async () => { if (isLegacyMigrationHelper) {
try {
runLegacySafeStorageHelper()
app.exit(0)
@@ -1442,7 +1454,24 @@ app.whenReady().then(async () => {
// Create the renderer before native WCDB bootstrap so startup progress is visible immediately.
await reportTemplateService.recover()
registerReportTemplateIpc()
installExtensionProtocolHandler(getExtensionPaths())
registerExtensionIpc({
getManager: getExtensionManager,
paths: getExtensionPaths(),
isTrustedSender: (senderId) =>
BrowserWindow.getAllWindows().some((window) => window.webContents.id === senderId)
})
createWindow()
void initExtensionSystem({
appVersion: app.getVersion(),
onChange: (extensionId, reason) => {
for (const window of BrowserWindow.getAllWindows()) {
if (!window.isDestroyed()) {
window.webContents.send(EXTENSION_IPC.changed, { extensionId, reason })
}
}
}
})
wcdbBootstrapPromise = bootstrapWcdbNativeAsync().then(() => {
console.log('[WCDB4] async bootstrap complete')
})
@@ -1706,6 +1735,21 @@ app.whenReady().then(async () => {
}`
)
}
/*
* 扩展事件分发:与 Automation 并行、互不影响。
* 扩展侧的异常不能污染 MessageListener 的投递循环,也不能阻断 Automation。
*/
if (hasExtensionManager()) {
try {
getExtensionManager().handleMessage(message)
} catch (error) {
console.warn(
`[Extension] handleMessage failed: ${
error instanceof Error ? error.message : String(error)
}`
)
}
}
})
const sessions = await wcdb4Client.getSessionsAsync({ hydrateDisplayNames: false })
configureRecallProtection(wcdb4Client, resolvedRoot, settings.recallProtectionEnabled)
@@ -1884,7 +1928,7 @@ app.whenReady().then(async () => {
// 排查「消息到底发没发出去」时恰好缺的就是那份证据。
// 普通手动发送保持 triggerType=user;带 postfixText 的日报图片由 Gateway 编排成
// 两个 automation action,以复用同一条 3s 队列,并严格在图片 sent 后才发后置词。
if (request.type === 'text' || request.type === 'image') {
if (request.type === 'text' || request.type === 'image' || request.type === 'video') {
const to = String(request.to || '').trim()
const recipient = {
type:
@@ -1912,7 +1956,12 @@ app.whenReady().then(async () => {
}
const action = await wechatActionGateway.execute({
origin: 'user_manual',
purpose: request.type === 'text' ? 'manual_text' : 'manual_image',
purpose:
request.type === 'text'
? 'manual_text'
: request.type === 'video'
? 'manual_video'
: 'manual_image',
triggerType: 'user',
recipient,
content:
@@ -1922,7 +1971,9 @@ app.whenReady().then(async () => {
text: String(request.text || ''),
...(request.at ? { at: request.at } : {})
}
: { type: 'image', path: String(request.filePath || '') }
: request.type === 'video'
? { type: 'video', path: String(request.filePath || '') }
: { type: 'image', path: String(request.filePath || '') }
})
// 返回契约保持 `PersonalWechatSendResult`,界面判读不用改。
return toPersonalWechatSendResult(action, await currentPersonalWechatSenderStatus())
@@ -3674,6 +3725,7 @@ app.on('before-quit', (event) => {
agentHubService.stop()
scheduledReportService.stop()
groupExitMonitorService.stop()
await disposeExtensionSystem().catch(() => undefined)
flushBootstrapCacheWritesSync()
const [, nativeCallsDrained] = await Promise.all([
apiServer.stop().catch(() => undefined),
+182 -26
View File
@@ -19,8 +19,21 @@ import {
renderLeaveNotificationText,
type GroupMemberExitedEvent
} from '../../shared/group-exit-event'
import type { WechatActionContent, WechatActionRequest, WechatActionResult } from '../../shared/wechat-action'
import type { SaveGeneratedReportRequest, SaveGeneratedReportResult } from '../../shared/report-history'
import type {
WechatActionContent,
WechatActionRequest,
WechatActionResult
} from '../../shared/wechat-action'
import type { ExtensionMessageEvent } from '../../shared/extensions/events'
import type { ExtensionAutomationActionOutput } from '../../shared/extensions/rpc'
import {
canExtensionSendText,
invokeExtensionAction
} from '../extensions/extension-automation-bridge'
import type {
SaveGeneratedReportRequest,
SaveGeneratedReportResult
} from '../../shared/report-history'
import {
generateAgentGroupReport,
type AgentGroupReportRequest,
@@ -45,6 +58,21 @@ import type { AutomationTargetResolution } from './automation-wechat-target'
/** 一步执行完毕后,后续步骤的处置方式。 */
const STEP_ORDER: AutomationStepKey[] = ['received', 'matched', 'reply', 'report', 'send']
/**
* 配了扩展动作时的步骤顺序。
*
* 只有规则真的配了扩展动作才把这一步加进来:给每条日报都渲染一条
* 「执行扩展动作 已跳过」是纯噪声,用户会以为规则配错了。
*/
const EXTENSION_STEP_ORDER: AutomationStepKey[] = [
'received',
'matched',
'extension_action',
'reply',
'report',
'send'
]
/** 退群通知的步骤顺序(与消息型规则**不共用**)。 */
const LEAVE_NOTIFICATION_STEP_ORDER: AutomationStepKey[] = [
'exit_received',
@@ -74,6 +102,7 @@ const SCHEDULED_REPORT_STEP_ORDER: AutomationStepKey[] = [
*/
const SKIPPED_AFTER_REPLY_FAILURE = '前置步骤失败(回复确认未成功),本次不再继续。'
const SKIPPED_AFTER_REPORT_FAILURE = '前置步骤失败(日报未生成),没有图片可发送。'
const SKIPPED_AFTER_EXTENSION_FAILURE = '前置步骤失败(扩展动作未成功),本次不再继续。'
/**
* 定时日报「生成 / 落库」失败时,后续步骤的 `skipReason`。
@@ -102,6 +131,8 @@ export interface AutomationRunInput {
sourceDisplayName: string
/** 群消息触发者;仅内置日报确认回复会使用它构造 @。 */
triggerSender?: { wxid: string; displayName: string }
/** 触发本次执行的消息(扩展动作的运行时上下文)。 */
message?: ExtensionMessageEvent
}
export interface AutomationRunResult {
@@ -185,6 +216,22 @@ export interface ScheduledReportRunResult {
export interface AutomationActionRunnerDependencies {
generateReport?: (request: AgentGroupReportRequest) => Promise<AgentGroupReportResult>
executeAction?: (request: WechatActionRequest) => Promise<WechatActionResult>
/**
* 扩展动作调用。默认走 `ExtensionManager`;单测注入假实现即可绕开子进程。
*/
invokeExtensionAction?: (
extensionId: string,
actionId: string,
input: Record<string, unknown>,
context: {
conversationId: string
isGroup: boolean
accountId: string
message?: ExtensionMessageEvent
}
) => Promise<ExtensionAutomationActionOutput>
/** 扩展是否具备发送文本的权限。默认读扩展中心授予集合。 */
canExtensionSendText?: (extensionId: string) => boolean
now?: () => number
/** 延迟实现。默认真 sleep;单测注入即时 resolve 的假实现,避免真的等 2 秒。 */
delay?: (ms: number) => Promise<void>
@@ -246,7 +293,9 @@ function actionErrorMessage(code: string | undefined, fallback: string | undefin
}
export class AutomationActionRunner {
private readonly generateReport: (request: AgentGroupReportRequest) => Promise<AgentGroupReportResult>
private readonly generateReport: (
request: AgentGroupReportRequest
) => Promise<AgentGroupReportResult>
private readonly executeAction: (request: WechatActionRequest) => Promise<WechatActionResult>
private readonly now: () => number
private readonly delay: (ms: number) => Promise<void>
@@ -257,21 +306,31 @@ export class AutomationActionRunner {
AutomationActionRunnerDependencies['resolveReportContact']
>
private readonly getContactAvatars: (usernames: string[]) => Promise<Record<string, string>>
private readonly invokeExtensionAction: NonNullable<
AutomationActionRunnerDependencies['invokeExtensionAction']
>
private readonly canExtensionSendText: (extensionId: string) => boolean
constructor(dependencies: AutomationActionRunnerDependencies = {}) {
this.generateReport = dependencies.generateReport ?? generateAgentGroupReport
this.executeAction = dependencies.executeAction ?? ((request) => wechatActionGateway.execute(request))
this.executeAction =
dependencies.executeAction ?? ((request) => wechatActionGateway.execute(request))
this.now = dependencies.now ?? (() => Date.now())
this.delay =
dependencies.delay ??
((ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
dependencies.delay ?? ((ms) => new Promise<void>((resolve) => setTimeout(resolve, ms)))
this.saveGeneratedReport = dependencies.saveGeneratedReport ?? saveGeneratedReport
this.resolveReportContact = dependencies.resolveReportContact ?? ((raw) => resolveMd5(raw))
this.getContactAvatars = dependencies.getContactAvatars ?? ((ids) => getContactAvatars(ids))
this.invokeExtensionAction =
dependencies.invokeExtensionAction ??
((id, actionId, input, context) => invokeExtensionAction(id, actionId, input, context))
this.canExtensionSendText = dependencies.canExtensionSendText ?? canExtensionSendText
}
async run(input: AutomationRunInput): Promise<AutomationRunResult> {
const steps = STEP_ORDER.map((key) => createStep(key))
const extensionAction = findAction(input.rule, 'extensionAction')
const order = extensionAction ? EXTENSION_STEP_ORDER : STEP_ORDER
const steps = order.map((key) => createStep(key))
const stepAt = (key: AutomationStepKey): AutomationStep =>
steps.find((step) => step.key === key) as AutomationStep
@@ -282,25 +341,77 @@ export class AutomationActionRunner {
const reportAction = findAction(input.rule, 'generateReport')
const sendAction = findAction(input.rule, 'sendReportImage')
// ---- 步骤 3:回复确认 ----
// ---- 步骤 3:扩展动作 ----
//
// 回复等待:规则一命中就秒回,看起来就是个机器人(消息刚到、回复就到)。
// 等待时长是**规则自己的一项执行参数**(`rule.replyDelaySeconds`,在
// 「编辑自动化 → 3 · 触发后执行」里配),所以不同规则可以不一样。
//
// 等待刻意放在 `reply` 步骤计时**之外** —— `reply.durationMs` 只应该反映发送本身,
// 否则用户看到「回复确认 2000ms」会误以为是发送慢。
// 已经命中就不再回头重判规则:等待窗口里规则被停用/删掉也不中断本次执行,
// 与 cooldown、同消息幂等的口径一致(都是「命中那一刻」的快照)。
if (replyAction) {
// 扩展动作先跑,它产出的 `reply` 会成为下一步「回复确认」的内容。
// 扩展本身**不发送**:内容交回宿主,由宿主在权限与授权都通过后经 Gateway 发出。
let extensionOutput: ExtensionAutomationActionOutput | undefined
if (extensionAction) {
const extensionStep = stepAt('extension_action')
extensionStep.status = 'running'
extensionStep.startedAt = this.now()
try {
extensionOutput = await this.invokeExtensionAction(
String(extensionAction.extensionId || ''),
String(extensionAction.actionId || ''),
extensionAction.input ?? {},
{
conversationId: input.conversationId,
isGroup: input.isGroup,
accountId: input.message?.accountId ?? '',
...(input.message ? { message: input.message } : {})
}
)
} catch (error) {
markFailed(
extensionStep,
this.now(),
error instanceof Error ? error.message : '扩展动作执行失败'
)
markRemainingSkipped(steps, order, 'extension_action', SKIPPED_AFTER_EXTENSION_FAILURE)
return { steps, status: 'failed', errorSummary: extensionStep.error }
}
if (!extensionOutput || extensionOutput.success === false) {
markFailed(extensionStep, this.now(), extensionOutput?.error || '扩展动作返回失败')
markRemainingSkipped(steps, order, 'extension_action', SKIPPED_AFTER_EXTENSION_FAILURE)
return { steps, status: 'failed', errorSummary: extensionStep.error }
}
if (extensionOutput.reply) extensionStep.detail = '已生成回复内容'
markSuccess(extensionStep, this.now())
}
const extensionReply = extensionOutput?.reply
// 步骤 4:回复确认。
// 命中即视为快照:等待窗口内规则被停用/删除也不中断本次执行。
// 等待时长来自 rule.replyDelaySeconds,且不计入 reply.durationMs。
const willReply = Boolean(extensionReply) || Boolean(replyAction)
if (willReply) {
// 用共享的归一化函数,而不是 `Number(...) || 0`:旧版 rules.json 里没有这个字段,
// 那应该按**默认 2 秒**处理(否则「默认 2 秒」要等用户手动进编辑页才会生效)。
const replyDelayMs = normalizeReplyDelaySeconds(input.rule.replyDelaySeconds) * 1_000
if (replyDelayMs > 0) await this.delay(replyDelayMs)
}
if (!replyAction) {
if (!willReply) {
markSkipped(stepAt('reply'))
} else if (extensionReply) {
const replyStep = stepAt('reply')
const extensionId = String(extensionAction?.extensionId || '')
if (!this.canExtensionSendText(extensionId)) {
markFailed(replyStep, this.now(), '扩展没有 wechat.send.text 权限,回复未发送')
markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
return { steps, status: 'failed', errorSummary: replyStep.error }
}
replyStep.status = 'running'
replyStep.startedAt = this.now()
const sent = await this.sendExtensionReply(input, extensionId, extensionReply)
if (!sent.ok) {
markFailed(replyStep, this.now(), sent.error || '回复确认失败')
markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
return { steps, status: 'failed', errorSummary: replyStep.error }
}
markSuccess(replyStep, this.now())
} else {
const replyStep = stepAt('reply')
replyStep.status = 'running'
@@ -316,12 +427,12 @@ export class AutomationActionRunner {
: undefined
const sent = await this.sendThroughGateway(input, 'reply', {
type: 'text',
text: replyAction.text?.trim() || DEFAULT_REPLY_TEXT,
text: replyAction?.text?.trim() || DEFAULT_REPLY_TEXT,
...(confirmationAt ? { at: confirmationAt } : {})
})
if (!sent.ok) {
markFailed(replyStep, this.now(), sent.error || '回复确认失败')
markRemainingSkipped(steps, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
markRemainingSkipped(steps, order, 'reply', SKIPPED_AFTER_REPLY_FAILURE)
return { steps, status: 'failed', errorSummary: replyStep.error }
}
markSuccess(replyStep, this.now())
@@ -346,7 +457,7 @@ export class AutomationActionRunner {
}
if (!result.success || !result.pngPath) {
markFailed(reportStep, this.now(), result.error || '日报生成失败')
markRemainingSkipped(steps, 'report', SKIPPED_AFTER_REPORT_FAILURE)
markRemainingSkipped(steps, order, 'report', SKIPPED_AFTER_REPORT_FAILURE)
return { steps, status: 'failed', errorSummary: reportStep.error }
}
pngPath = result.pngPath
@@ -395,6 +506,43 @@ export class AutomationActionRunner {
return { steps, status: 'success', pngPath }
}
/**
* 发送扩展产出的回复。
*
* 内容来自扩展,**发送动作来自宿主**:`origin` / `purpose` / 幂等键都在这里填,
* 扩展返回的只是「想说什么」。所以扩展无法借这条链路绕过发送策略。
*/
private async sendExtensionReply(
input: AutomationRunInput,
extensionId: string,
reply: NonNullable<ExtensionAutomationActionOutput['reply']>
): Promise<{ ok: boolean; error?: string }> {
try {
const result = await this.executeAction({
idempotencyKey: `extension_action:${input.executionId}`,
origin: 'extension',
purpose: 'extension_action',
triggerType: 'automation',
executionId: input.executionId,
recipient: {
type: input.isGroup ? 'group' : 'contact',
id: input.conversationId,
name: input.sourceDisplayName
},
content: {
type: 'text',
text: reply.text,
...(reply.at ? { at: reply.at } : {})
},
metadata: { extensionId }
})
if (result.status === 'sent') return { ok: true }
return { ok: false, error: actionErrorMessage(result.errorCode, result.reason) }
} catch (error) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
}
}
/**
* 把「@我生成日报」产出的日报写进**日报历史**。
*
@@ -522,7 +670,9 @@ export class AutomationActionRunner {
generated.groupName || reportContact?.m_nsNickName || input.sourceDisplayName || '群聊',
contactAvatar,
source: 'scheduled',
dateRange: generated.reportMetadata?.dateRange || scheduledReportRangeLabel(input.config.report.range),
dateRange:
generated.reportMetadata?.dateRange ||
scheduledReportRangeLabel(input.config.report.range),
reportDate: generated.reportMetadata?.reportDate,
messageCount: generated.messageCount ?? generated.reportMetadata?.messageCount ?? 0,
generatedAt: new Date(this.now()).toISOString(),
@@ -674,7 +824,9 @@ export class AutomationActionRunner {
* 与 `run()` 的差别:没有动作链、没有回复等待、没有 cooldown
* (退群是低频事件,且**不能被时间窗合并** —— 两个成员先后退出就是两条通知)。
*/
async runLeaveNotification(input: LeaveNotificationRunInput): Promise<LeaveNotificationRunResult> {
async runLeaveNotification(
input: LeaveNotificationRunInput
): Promise<LeaveNotificationRunResult> {
const steps = LEAVE_NOTIFICATION_STEP_ORDER.map((key) => createStep(key))
const stepAt = (key: AutomationStepKey): AutomationStep =>
steps.find((step) => step.key === key) as AutomationStep
@@ -792,18 +944,22 @@ export class AutomationActionRunner {
}
}
function findAction(rule: AutomationRule, type: AutomationAction['type']): AutomationAction | undefined {
function findAction(
rule: AutomationRule,
type: AutomationAction['type']
): AutomationAction | undefined {
return rule.actions.find((action) => action.type === type && action.enabled)
}
/** 把 `after` 之后的步骤全部标成 `skipped`(前一步挂了,后面的不许再动)。 */
function markRemainingSkipped(
steps: AutomationStep[],
order: AutomationStepKey[],
after: AutomationStepKey,
skipReason?: string
): void {
const from = STEP_ORDER.indexOf(after) + 1
for (const key of STEP_ORDER.slice(from)) {
const from = order.indexOf(after) + 1
for (const key of order.slice(from)) {
const step = steps.find((item) => item.key === key)
if (step) markSkipped(step, skipReason)
}
+31 -18
View File
@@ -1,8 +1,5 @@
import { createHash, randomUUID } from 'node:crypto'
import {
matchAutomationRule,
type AutomationMatchInput
} from '../../shared/automation-matcher'
import { matchAutomationRule, type AutomationMatchInput } from '../../shared/automation-matcher'
import {
AUTOMATION_SEND_PURPOSE,
BUILTIN_LEAVE_NOTIFICATION_RULE_ID,
@@ -14,6 +11,8 @@ import {
type ScheduledRuleRunOutcome
} from '../../shared/automation'
import type { GroupMemberExitedEvent } from '../../shared/group-exit-event'
import { buildExtensionMessageEvent } from '../../shared/extensions/events'
import { buildEventId } from '../extensions/extension-event-bus'
import type { PersonalWechatSendCapability } from '../../shared/personal-wechat'
import type { Wcdb4Client } from '../wcdb4-client'
import type { NormalizedIncomingMessage } from './message-listener-service'
@@ -28,18 +27,12 @@ import {
scheduledReportSourceDisplayName
} from './scheduled-report-target'
import type { AutomationTargetContact } from './automation-wechat-target'
import {
automationRuleStore,
type AutomationRuleStore
} from './automation-rule-store'
import { automationRuleStore, type AutomationRuleStore } from './automation-rule-store'
import {
automationExecutionLogService,
type AutomationExecutionLogService
} from './automation-execution-log-service'
import {
automationActionRunner,
type AutomationActionRunner
} from './automation-action-runner'
import { automationActionRunner, type AutomationActionRunner } from './automation-action-runner'
/**
* AutomationService —— Automation v1 的编排层。
*
@@ -137,9 +130,7 @@ export function leaveNotificationIdempotencyKey(eventId: string): string {
* 「立即执行」会因为幂等而被静默吞掉。
*/
export function scheduledReportExecutionId(ruleId: string, slot: string): string {
return createHash('sha1')
.update(`scheduled_report\u0001${ruleId}\u0001${slot}`)
.digest('hex')
return createHash('sha1').update(`scheduled_report\u0001${ruleId}\u0001${slot}`).digest('hex')
}
/** 定时日报一次执行的结果(定义在 shared 层,便于 IPC / 渲染层共用)。 */
@@ -291,7 +282,7 @@ export class AutomationService {
const sourceDisplayName = this.resolveDisplayName(message)
try {
await this.execute(rule, message, sourceDisplayName)
await this.execute(rule, message, sourceDisplayName, selfUsernames)
} finally {
// 无论 success / failed / 抛异常都要解除 in-flight。
// 漏掉这一步会让这条规则在这个会话里**永久锁死**。
@@ -660,7 +651,10 @@ export class AutomationService {
return true
}
/** 「在哪些聊天生效」的可选项。`id` 必须是 `xxx@chatroom`,与 message.sessionId 对齐。 */ listGroups(): Array<{ id: string; name: string }> {
/** 「在哪些聊天生效」的可选项。`id` 必须是 `xxx@chatroom`,与 message.sessionId 对齐。 */ listGroups(): Array<{
id: string
name: string
}> {
try {
return listContacts()
.filter((contact) => contact.type === 'group' || contact.m_nsUsrName?.endsWith('@chatroom'))
@@ -683,7 +677,8 @@ export class AutomationService {
private async execute(
rule: AutomationRule,
message: NormalizedIncomingMessage,
sourceDisplayName: string
sourceDisplayName: string,
selfUsernames: string[]
): Promise<void> {
const executionId = randomUUID()
const startedAt = this.now()
@@ -727,6 +722,24 @@ export class AutomationService {
displayName: message.senderNickname
}
}
: {}),
...(rule.actions.some((action) => action.type === 'extensionAction' && action.enabled)
? {
message: buildExtensionMessageEvent({
eventId: buildEventId(message.sessionId, message.localId),
accountId: String(getSelfAccountInfo()?.wxid || ''),
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 } : {}),
mentionsMe: message.mentionTargets.some((target) => selfUsernames.includes(target)),
createTimeSeconds: message.createTime
})
}
: {})
})
} catch (error) {
+16 -19
View File
@@ -112,9 +112,7 @@ export function formatMacWechatHostStartupFailure(code: number | null, diagnosti
const lines = diagnostic.trim().split('\n').filter(Boolean)
const detail = lines[lines.length - 1]
if (detail) return `发送运行时启动失败(进程退出码 ${code ?? '未知'}):${detail}`
return code === null
? '发送运行时在启动过程中退出'
: `发送运行时启动失败(进程退出码 ${code})`
return code === null ? '发送运行时在启动过程中退出' : `发送运行时启动失败(进程退出码 ${code})`
}
export function resolveMacWechatSendMechanism(
@@ -201,6 +199,12 @@ export function deriveMacWechatSenderStatus({
const canSendText = bindingReady && supportsCapability('text') && binding?.canSendText === true
const canSendImage = bindingReady && supportsCapability('image') && binding?.canSendImage === true
const canSendVoice = bindingReady && supportsCapability('voice') && binding?.canSendVoice === true
/*
* 视频复用图片的媒体通道(Host 的 `/SendMsg` type=video)。
* Runtime manifest 不单独声明 video 能力,因此以图片通道是否可用作为判据;
* 真正的发送结果仍以 Host 返回为准,不在 UI 层假装支持。
*/
const canSendVideo = bindingReady && binding?.canSendImage === true
const sessionAttached = identityMatches && (binding?.sessionAttached ?? false)
const scriptLoaded = identityMatches && (binding?.scriptLoaded ?? false)
@@ -224,10 +228,11 @@ export function deriveMacWechatSenderStatus({
imageHookInstalled: identityMatches && (binding?.canSendImage ?? false),
imageHookReady: identityMatches && (binding?.canSendImage ?? false),
messageListenerReady: scriptLoaded,
canSend: canSendText || canSendImage || canSendVoice,
canSend: canSendText || canSendImage || canSendVoice || canSendVideo,
canSendText,
canSendImage,
canSendVoice,
canSendVideo,
message,
error: state === 'error' ? message : undefined
}
@@ -349,9 +354,7 @@ export class MacWechatRuntimeManager {
* comes up WITHOUT touching WeChat (lazy init inside the host), so "runtime
* online" and "WeChat bound" stay two independent states.
*/
ensureStarted(
options: { allowManualRestart?: boolean } = {}
): Promise<MacWechatRuntimeSnapshot> {
ensureStarted(options: { allowManualRestart?: boolean } = {}): Promise<MacWechatRuntimeSnapshot> {
if (this.startInFlight) return this.startInFlight
const startPromise = this.ensureStartedOnce(options)
@@ -367,9 +370,9 @@ export class MacWechatRuntimeManager {
return startPromise
}
protected async ensureStartedOnce(
options: { allowManualRestart?: boolean }
): Promise<MacWechatRuntimeSnapshot> {
protected async ensureStartedOnce(options: {
allowManualRestart?: boolean
}): Promise<MacWechatRuntimeSnapshot> {
if (this.manuallyStopped && !options.allowManualRestart) return this.getSnapshot()
if (options.allowManualRestart) this.manuallyStopped = false
if (isMacNativeRuntimeUnavailable()) {
@@ -481,19 +484,13 @@ export class MacWechatRuntimeManager {
}
try {
if (!app.isPackaged) {
execFileSync('/usr/bin/codesign', [
'--force',
'--sign',
'-',
'--timestamp=none',
hostPath
])
execFileSync('/usr/bin/codesign', ['--force', '--sign', '-', '--timestamp=none', hostPath])
}
execFileSync('/usr/bin/codesign', ['--verify', '--strict', hostPath])
} catch (error) {
this.lifecycle = 'stopped'
this.lastError = '无法验证发送 Host 签名:' +
(error instanceof Error ? error.message : String(error))
this.lastError =
'无法验证发送 Host 签名:' + (error instanceof Error ? error.message : String(error))
appLogger.write({
level: 'error',
scope: 'mac-wechat-runtime',
+43 -3
View File
@@ -137,14 +137,39 @@ export function extractMentionTargets(source: string | undefined): string[] {
if (!match) return []
const inner = match[1].trim()
const unwrapped = inner.replace(/^<!\[CDATA\[/, '').replace(/\]\]>$/, '').trim()
return unwrapped ? [unwrapped] : []
if (!unwrapped) return []
return unwrapped
.split(',')
.map((item) => item.trim())
.filter(Boolean)
}
/** 把 WCDB 的 `source` 列(zstd 压缩的 Buffer)还原成 XML 文本。 */
/** 把 WCDB 的 `source` 列(明文 XML 字符串或 zstd 压缩的 Buffer)还原成 XML 文本。 */
export function decodeSourcePayload(value: unknown): string | undefined {
if (typeof value === 'string') {
const trimmed = value.trim()
if (!trimmed) return undefined
if (
trimmed.length >= 8 &&
trimmed.length % 2 === 0 &&
/^28b52ffd[0-9a-f]+$/i.test(trimmed)
) {
try {
return Buffer.from(zstdDecompress(Buffer.from(trimmed, 'hex'))).toString('utf8')
} catch {
return undefined
}
}
return trimmed
}
let buffer: Buffer | null = null
if (Buffer.isBuffer(value)) {
buffer = value
} else if (value instanceof Uint8Array) {
buffer = Buffer.from(value)
} else if (Array.isArray(value)) {
buffer = Buffer.from(value)
} else {
const candidate = value as { type?: string; data?: unknown } | null
if (candidate?.type === 'Buffer' && Array.isArray(candidate.data)) {
@@ -193,6 +218,7 @@ export class MessageListenerService {
private readonly pendingSessions = new Set<string>()
private coalesceTimer: ReturnType<typeof setTimeout> | null = null
private readbackInFlight = false
private pendingReadback = false
private disposed = false
private readonly coalesceMs: number
@@ -282,8 +308,13 @@ export class MessageListenerService {
* - **legacy(protocol v1,旧 runtime)**:只能退回「最近活跃会话」`getSessions()[0]`。
*/
private async readback(): Promise<void> {
if (this.disposed || this.readbackInFlight) return
if (this.disposed) return
if (this.readbackInFlight) {
this.pendingReadback = true
return
}
this.readbackInFlight = true
this.pendingReadback = false
const startedAt = Date.now()
const preciseSessions = Array.from(this.pendingSessions)
@@ -321,6 +352,15 @@ export class MessageListenerService {
)
} finally {
this.readbackInFlight = false
if (!this.disposed && (this.pendingReadback || this.pendingSessions.size > 0)) {
this.pendingReadback = false
if (!this.coalesceTimer) {
this.coalesceTimer = setTimeout(() => {
this.coalesceTimer = null
void this.readback()
}, this.coalesceMs)
}
}
}
}
@@ -37,7 +37,8 @@ export class PersonalWechatCapabilityService {
const capabilities = {
text: Boolean(senderStatus.canSendText),
image: Boolean(senderStatus.canSendImage),
voice: Boolean(senderStatus.canSendVoice)
voice: Boolean(senderStatus.canSendVoice),
video: Boolean(senderStatus.canSendVideo)
}
const status = this.mapState(senderStatus)
const ready = status === 'ready'
+166 -13
View File
@@ -23,7 +23,10 @@ import type {
import { loadSettings } from './settings-store'
import { SilkAudioDecoder, SilkAudioEncoder } from '../voice-pipeline/audio-decoder'
import { appLogger } from '../app-logger'
import { accountDirectoryBelongsToIdentity, readLocalAccountIdentity } from './local-account-identity'
import {
accountDirectoryBelongsToIdentity,
readLocalAccountIdentity
} from './local-account-identity'
import { macWechatRuntimeManager } from './mac-wechat-runtime-manager'
const execFileAsync = promisify(execFile)
@@ -31,6 +34,8 @@ const WINDOWS_LOOPBACK_HOST = '127.0.0.1'
const REQUEST_TIMEOUT_MS = 20_000
const MAX_IMAGE_BYTES = 20 * 1024 * 1024
const MAX_VOICE_BYTES = 20 * 1024 * 1024
/** 视频与扩展发送通道的上限保持一致。 */
const MAX_VIDEO_BYTES = 100 * 1024 * 1024
// 语音编码由 native runtime 内的 SILK 实现完成,不再是外部编码器进程。
const VOICE_ENCODER_NAME = 'silk'
const VOICE_ENCODER_VERSION = 'tm-wechat-native'
@@ -327,6 +332,73 @@ function stageMacWechatImageForMessageSourceSend(
return stagedPath
}
const MAC_VIDEO_STAGE_PREFIX = 'tm-video-'
const MAC_VIDEO_STAGE_RETENTION_MS = 10 * 60 * 1000
/**
* macOS WeChat 运行在 App Sandbox 容器中,注入在微信进程内的 `libtmwechat.dylib`
* 只能读取 `~/Library/Containers/com.tencent.xinWeChat/Data/...` 容器内路径,
* 直接传 `~/Library/Application Support/TraceMemo/...` 会触发 `VIDEO_PREPARATION_FAILED:0`。
* 因此发送前需将容器外视频暂存到微信容器的 `Documents` 目录。
*/
export function stageMacWechatVideoForSend(
filePath: string,
wechatFilesRoot = WECHAT_FILES_ROOT
): { stagedPath: string; cleanup: () => void } {
const normalized = String(filePath || '').trim()
const containerDataRoot = dirname(dirname(wechatFilesRoot))
if (
containerDataRoot.includes('com.tencent.xinWeChat') &&
normalized.startsWith(`${containerDataRoot}${sep}`)
) {
return { stagedPath: normalized, cleanup: () => {} }
}
const documentsDir = dirname(wechatFilesRoot)
const stageDir = existsSync(documentsDir) ? documentsDir : wechatFilesRoot
mkdirSync(stageDir, { recursive: true })
// 顺手清理超过 10 分钟的历史暂存视频,防止异常退出残留。
const now = Date.now()
try {
for (const entry of readdirSync(stageDir)) {
if (!entry.startsWith(MAC_VIDEO_STAGE_PREFIX)) continue
const candidate = join(stageDir, entry)
try {
if (now - statSync(candidate).mtimeMs > MAC_VIDEO_STAGE_RETENTION_MS) {
unlinkSync(candidate)
}
} catch {
// Best-effort stale file cleanup.
}
}
} catch {
// Ignore directory listing errors.
}
const extension = extname(normalized).toLowerCase()
const safeExtension = /^\.[a-z0-9]{1,8}$/.test(extension) ? extension : '.mp4'
const stagedPath = join(
stageDir,
`${MAC_VIDEO_STAGE_PREFIX}${randomBytes(6).toString('hex')}-${now}${safeExtension}`
)
copyFileSync(normalized, stagedPath)
return {
stagedPath,
cleanup: () => {
const timer = setTimeout(() => {
try {
unlinkSync(stagedPath)
} catch {
// Best-effort delayed cleanup after WeChat finishes asynchronous video upload.
}
}, 120_000)
timer.unref?.()
}
}
}
/** Locate the current account's temporary image directory consumed by the image send path. */
export function findWechatImagePath(
root = WECHAT_FILES_ROOT,
@@ -443,6 +515,12 @@ export function buildWindowsWechatRequest(
body: { toWxid: target, type: 'image', msg: String(request.filePath || '').trim() }
}
}
if (request.type === 'video') {
return {
endpoint: '/SendMsg',
body: { toWxid: target, type: 'video', msg: String(request.filePath || '').trim() }
}
}
const fromId = String(request.fromId || '').trim()
const filePath = String(options.filePath || request.filePath || '').trim()
@@ -609,6 +687,7 @@ export class PersonalWechatSendService {
if (request.type === 'text') return this.sendMacText(request)
if (request.type === 'image') return this.sendMacImage(request)
if (request.type === 'voice') return this.sendMacVoice(request)
if (request.type === 'video') return this.sendMacVideo(request)
}
return {
success: false,
@@ -772,11 +851,78 @@ export class PersonalWechatSendService {
signal: AbortSignal.timeout(timeoutMs)
}).catch(() => null)
if (response === null || !response.ok) return null
return (await response.json().catch(() => null)) as {
code: number
ok: boolean
message: string
} | null
const payload = (await response.json().catch(() => null)) as Record<string, unknown> | null
if (!payload) return null
/*
* 不同 Host 路由的响应形状不一致:`/sendText` 等返回 `{ok}`,
* `/SendMsg` 兼容层可能返回 `{status:true}` 或 Windows 风格的 `{ret:0}`。
* 这里统一收敛,避免「实际已发送、界面报失败」。
*/
const explicitFailure = payload.ok === false || payload.status === false
const ok =
!explicitFailure &&
(payload.ok === true || payload.status === true || payload.ret === 0 || payload.code === 0)
return {
code: Number(payload.code ?? payload.ret ?? (ok ? 0 : 1)),
ok,
message: String(payload.message ?? payload.msg ?? '')
}
}
/**
* macOS 视频发送:`POST /SendMsg`,body 为 `{toWxid, type:'video', msg:<绝对路径>}`。
*
* 微信运行在 App Sandbox 容器中,注入的 `libtmwechat.dylib` 在微信进程内执行,
* 只能访问微信沙盒容器目录(`~/Library/Containers/com.tencent.xinWeChat/Data/...`)。
* 因此先将容器外视频暂存到微信容器 `Documents` 目录,再调用 `/SendMsg`。
*/
private async sendMacVideo(
request: Extract<PersonalWechatSendRequest, { type: 'video' }>
): Promise<PersonalWechatSendResult> {
await macWechatRuntimeManager.ensureStarted()
const status = await macWechatRuntimeManager.buildSenderStatus()
if (!status.canSendVideo) {
return {
success: false,
status,
error: status.message || '当前微信发送组件不支持视频,请升级后重试'
}
}
const filePath = String(request.filePath || '').trim()
if (!filePath || !existsSync(filePath)) {
return { success: false, status, error: '请选择有效的视频文件' }
}
const size = statSync(filePath).size
if (size <= 0 || size > MAX_VIDEO_BYTES) {
return { success: false, status, error: '视频必须小于 100 MB' }
}
let staged: { stagedPath: string; cleanup: () => void } | null = null
try {
staged = stageMacWechatVideoForSend(filePath, this.wechatFilesRoot)
} catch (error) {
const latest = await macWechatRuntimeManager.buildSenderStatus()
return {
success: false,
status: latest,
error: error instanceof Error ? error.message : '无法将视频暂存到微信沙盒目录'
}
}
try {
const result = await this.postMacHost(
'/SendMsg',
{ toWxid: request.to, type: 'video', msg: staged.stagedPath },
180_000
)
const latest = await macWechatRuntimeManager.buildSenderStatus()
if (!result?.ok) {
return { success: false, status: latest, error: result?.message || '视频发送失败' }
}
return { success: true, status: latest }
} finally {
staged.cleanup()
}
}
private async sendMacImage(
@@ -974,21 +1120,24 @@ export class PersonalWechatSendService {
request = { ...request, to, text }
} else {
const filePath = String(request.filePath || '').trim()
const label = request.type === 'voice' ? '语音' : request.type === 'video' ? '视频' : '图片'
const limit =
request.type === 'voice'
? MAX_VOICE_BYTES
: request.type === 'video'
? MAX_VIDEO_BYTES
: MAX_IMAGE_BYTES
if (!filePath || !existsSync(filePath)) {
const status = await this.getWindowsStatus()
return {
success: false,
status,
error: `请选择有效的${request.type === 'voice' ? '语音' : '图片'}文件`
}
return { success: false, status, error: `请选择有效的${label}文件` }
}
const size = statSync(filePath).size
if (size <= 0 || size > (request.type === 'voice' ? MAX_VOICE_BYTES : MAX_IMAGE_BYTES)) {
if (size <= 0 || size > limit) {
const status = await this.getWindowsStatus()
return {
success: false,
status,
error: `${request.type === 'voice' ? '语音' : '图片'}必须小于 20 MB`
error: `${label}必须小于 ${Math.round(limit / (1024 * 1024))} MB`
}
}
request = { ...request, to, filePath }
@@ -1019,6 +1168,10 @@ export class PersonalWechatSendService {
filePath: preparedImage.filePath
})
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 60_000)
} else if (request.type === 'video') {
// 视频不复制到临时目录:原生 Host 直接按绝对路径读取。
const windowsRequest = buildWindowsWechatRequest(request)
await requestWindowsHook(windowsRequest.endpoint, windowsRequest.body, 180_000)
} else if (request.type === 'voice') {
const fromId = String(request.fromId || '').trim()
if (!fromId) throw new Error('无法识别当前微信账号 wxid,无法发送语音')
+76 -6
View File
@@ -39,7 +39,15 @@ const AUTOMATION_PURPOSE_ALLOWLIST = new Set([
// purpose,各自有幂等位 —— 少这一条会被 evaluateWechatActionPolicy 拦下。
'automation_scheduled_report_postfix',
'manual_report_image',
'manual_report_postfix'
'manual_report_postfix',
/*
* 扩展来源的两个用途。
*
* 扩展不能自己决定 purpose:`ExtensionSendGateway` 与自动化 runner 分别填这两个值,
* 且 `evaluateWechatActionPolicy` 要求 `origin === 'extension'`,两边同时成立才放行。
*/
'extension_send',
'extension_action'
])
export interface ReportImageSequenceRequest {
@@ -137,6 +145,46 @@ export class WechatActionGateway {
return this.loadAuditState().records.map((record) => ({ ...record }))
}
/**
* 扩展来源的发送入口。
*
* 与 `execute()` 的区别只有一个:`origin` / `purpose` / `metadata.extensionId`
* 由这里按宿主规则填,扩展侧传不进来。其余检查(能力、审计、幂等、
* 自动化发送节流)与普通发送完全一致。
*/
async executeFromExtension(input: {
extensionId: string
purpose: 'extension_send' | 'extension_action'
recipient: WechatActionRequest['recipient']
content: WechatActionContent
idempotencyKey?: string
executionId?: string
}): Promise<WechatActionResult> {
const extensionId = String(input.extensionId || '').trim()
const startedAt = this.deps.now().toISOString()
if (!extensionId) {
return {
actionId: randomUUID(),
status: 'blocked',
decision: 'block',
errorCode: 'INVALID_REQUEST',
reason: '扩展发送缺少扩展标识',
startedAt,
finishedAt: startedAt
}
}
return this.execute({
...(input.idempotencyKey ? { idempotencyKey: String(input.idempotencyKey) } : {}),
...(input.executionId ? { executionId: String(input.executionId) } : {}),
origin: 'extension',
purpose: input.purpose,
triggerType: 'automation',
recipient: input.recipient,
content: input.content,
metadata: { extensionId }
})
}
async execute(request: WechatActionRequest): Promise<WechatActionResult> {
const normalized = normalizeActionRequest(request)
const idempotencyKey = normalized ? this.idempotencyKey(normalized) : undefined
@@ -256,9 +304,10 @@ export class WechatActionGateway {
const queued = this.automationSendTail.then(async () => {
const now = this.deps.now().getTime()
const remaining = this.lastAutomationSendStartedAt !== undefined
? Math.max(0, AUTOMATION_SEND_INTERVAL_MS - (now - this.lastAutomationSendStartedAt))
: 0
const remaining =
this.lastAutomationSendStartedAt !== undefined
? Math.max(0, AUTOMATION_SEND_INTERVAL_MS - (now - this.lastAutomationSendStartedAt))
: 0
if (remaining > 0) await this.deps.wait(remaining)
this.lastAutomationSendStartedAt = this.deps.now().getTime()
return this.deps.send(sendRequest)
@@ -393,14 +442,20 @@ export class WechatActionGateway {
!request.content ||
(request.content.type !== 'text' &&
request.content.type !== 'image' &&
request.content.type !== 'video' &&
request.content.type !== 'voice')
) {
return
}
const state = this.loadAuditState()
const extensionId =
request.metadata && typeof request.metadata.extensionId === 'string'
? request.metadata.extensionId.trim().slice(0, 128)
: ''
const record: WechatActionAuditRecord = {
actionId: result.actionId,
...(idempotencyKey ? { idempotencyKey } : {}),
...(extensionId ? { extensionId } : {}),
origin: request.origin,
purpose: request.purpose,
triggerType: request.triggerType,
@@ -465,6 +520,18 @@ export function evaluateWechatActionPolicy(request: WechatActionRequest): Policy
reason: `自动化动作不允许执行 purpose=${request.purpose}`
}
}
/*
* 扩展用途必须来自扩展来源。少了这一条,任何能构造 `WechatActionRequest` 的
* 内部调用都可以用 `extension_send` 绕过自动化用途白名单。
*/
if (String(request.purpose).startsWith('extension_') && request.origin !== 'extension') {
return {
decision: 'block',
source: 'deterministic',
reasonCode: 'ACTION_NOT_ALLOWED',
reason: '扩展发送用途只能用于扩展来源的请求'
}
}
return { decision: 'allow', source: 'deterministic' }
}
@@ -526,7 +593,7 @@ export function normalizeActionRequest(value: unknown): WechatActionRequest | nu
content: { type: 'text', text, ...(at ? { at } : {}) }
} as WechatActionRequest
}
if (contentType !== 'image' && contentType !== 'voice') return null
if (contentType !== 'image' && contentType !== 'video' && contentType !== 'voice') return null
const filePath = String((content as { path?: unknown }).path || '').trim()
if (!filePath) return null
return {
@@ -585,6 +652,9 @@ function toPersonalWechatSendRequest(request: WechatActionRequest): PersonalWech
if (request.content.type === 'image') {
return { ...base, type: 'image', filePath: request.content.path }
}
if (request.content.type === 'video') {
return { ...base, type: 'video', filePath: request.content.path }
}
const metadata = request.metadata && typeof request.metadata === 'object' ? request.metadata : {}
const fromId = typeof metadata.fromId === 'string' ? metadata.fromId.trim() : ''
const durationMs =
@@ -638,7 +708,7 @@ function contentAudit(
}
function contentTypeLabel(type: WechatActionContent['type']): string {
return type === 'text' ? '文字' : type === 'image' ? '图片' : '语音'
return type === 'text' ? '文字' : type === 'image' ? '图片' : type === 'video' ? '视频' : '语音'
}
function normalizeAuditRecords(values: unknown[]): WechatActionAuditRecord[] {
+22 -2
View File
@@ -1442,8 +1442,16 @@ export class Wcdb4Client {
// cannot silently stop at a shard boundary.
let tableMessages: Wcdb4Message[] = []
const cursorSatisfiesLimit = maxRows !== undefined && cursorMessages.length >= maxRows
const cursorMissingSource =
cursorMessages.length > 0 &&
cursorMessages.some(
(msg) => !msg.raw || !Object.prototype.hasOwnProperty.call(msg.raw, 'source')
)
let tableScanExecuted = false
if (!cursorSatisfiesLimit && (endTime || cursorMessages.length === 0)) {
if (
(!cursorSatisfiesLimit && (endTime || cursorMessages.length === 0)) ||
(Boolean(endTime) && cursorMissingSource)
) {
tableScanExecuted = true
tableMessages = await this.getMessagesByTableScanAsync(
username,
@@ -2411,7 +2419,19 @@ export class Wcdb4Client {
? `local:${message.mesLocalID}:${message.msgCreateTime || 0}`
: `${message.msgCreateTime}:${message.msgContent}`
const key = recoveredRow ? `recovered:${identity}` : identity
merged.set(key, message)
const existing = merged.get(key)
if (existing?.raw && message.raw) {
merged.set(key, {
...existing,
...message,
raw: {
...existing.raw,
...message.raw
}
})
} else {
merged.set(key, message)
}
}
const messages = Array.from(merged.values()).sort(
(left, right) =>
+36
View File
@@ -1,5 +1,17 @@
import { ElectronAPI } from '@electron-toolkit/preload'
import { Contact, Message, MessagesAroundResult } from '../shared/types'
import type {
ExtensionChangedEvent,
ExtensionPageRequest
} from '../shared/extensions/ipc'
import type {
ExtensionInstallResult,
ExtensionLogEntry,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageResponse,
InstalledExtension
} from '../shared/extensions/types'
import {
GroupReportExportRequest,
GroupReportExportResult,
@@ -817,6 +829,30 @@ declare global {
onAgentHubConversationsCleared: (callback: () => void) => () => void
onAgentHubStatus: (callback: (status: AgentHubStatus) => void) => () => void
onAgentHubLog: (callback: (entry: AgentHubLogEntry) => void) => () => void
/* 扩展中心 */
listExtensions: () => Promise<InstalledExtension[]>
getExtension: (extensionId: string) => Promise<InstalledExtension | null>
pickExtensionDirectory: () => Promise<string | null>
pickExtensionPackage: () => Promise<string | null>
installExtensionFromDirectory: (directory: string) => Promise<ExtensionInstallResult>
installExtensionFromPackage: (packagePath: string) => Promise<ExtensionInstallResult>
setExtensionEnabled: (
extensionId: string,
enabled: boolean
) => Promise<ExtensionOperationResult>
uninstallExtension: (
extensionId: string,
keepData?: boolean
) => Promise<ExtensionOperationResult>
getExtensionLogs: (extensionId: string, limit?: number) => Promise<ExtensionLogEntry[]>
clearExtensionLogs: (extensionId: string) => Promise<{ success: true }>
getExtensionPageUrl: (
extensionId: string,
pageId?: string
) => Promise<ExtensionPageDescriptor>
extensionPageRequest: (request: ExtensionPageRequest) => Promise<ExtensionPageResponse>
openExtensionDataDir: (extensionId: string) => Promise<{ success: boolean; error?: string }>
onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => () => void
}
}
}
+40
View File
@@ -131,6 +131,16 @@ import type {
SaveTextToSpeechSettingsRequest,
SynthesizeTextToSpeechRequest
} from '../shared/text-to-speech'
import type { ExtensionChangedEvent } from '../shared/extensions/ipc'
import type {
ExtensionInstallResult,
ExtensionLogEntry,
ExtensionOperationResult,
ExtensionPageDescriptor,
ExtensionPageRequest,
ExtensionPageResponse,
InstalledExtension
} from '../shared/extensions/types'
// 渲染器的自定义 API
const api = {
@@ -265,6 +275,36 @@ const api = {
enabled: boolean
): Promise<MsgInsertApplyResult> =>
ipcRenderer.invoke('automation:setMsgInsertSwitch', { name, enabled }),
listExtensions: (): Promise<InstalledExtension[]> => ipcRenderer.invoke('extension:list'),
getExtension: (extensionId: string): Promise<InstalledExtension | null> =>
ipcRenderer.invoke('extension:get', extensionId),
pickExtensionDirectory: (): Promise<string | null> =>
ipcRenderer.invoke('extension:pickDirectory'),
pickExtensionPackage: (): Promise<string | null> => ipcRenderer.invoke('extension:pickPackage'),
installExtensionFromDirectory: (directory: string): Promise<ExtensionInstallResult> =>
ipcRenderer.invoke('extension:installDirectory', directory),
installExtensionFromPackage: (packagePath: string): Promise<ExtensionInstallResult> =>
ipcRenderer.invoke('extension:installPackage', packagePath),
setExtensionEnabled: (extensionId: string, enabled: boolean): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:setEnabled', { id: extensionId, enabled }),
uninstallExtension: (extensionId: string, keepData = true): Promise<ExtensionOperationResult> =>
ipcRenderer.invoke('extension:uninstall', { id: extensionId, keepData }),
getExtensionLogs: (extensionId: string, limit?: number): Promise<ExtensionLogEntry[]> =>
ipcRenderer.invoke('extension:getLogs', { id: extensionId, limit }),
clearExtensionLogs: (extensionId: string): Promise<{ success: true }> =>
ipcRenderer.invoke('extension:clearLogs', extensionId),
getExtensionPageUrl: (extensionId: string, pageId?: string): Promise<ExtensionPageDescriptor> =>
ipcRenderer.invoke('extension:getPageUrl', { id: extensionId, pageId }),
extensionPageRequest: (request: ExtensionPageRequest): Promise<ExtensionPageResponse> =>
ipcRenderer.invoke('extension:pageRequest', request),
openExtensionDataDir: (extensionId: string): Promise<{ success: boolean; error?: string }> =>
ipcRenderer.invoke('extension:openDataDir', extensionId),
onExtensionChanged: (callback: (event: ExtensionChangedEvent) => void) => {
const listener = (_event: Electron.IpcRendererEvent, payload: ExtensionChangedEvent): void =>
callback(payload)
ipcRenderer.on('extension:changed', listener)
return () => ipcRenderer.removeListener('extension:changed', listener)
},
onGroupExitMonitorState: (callback: (state: GroupExitMonitorState) => void) => {
const listener = (_event: Electron.IpcRendererEvent, state: GroupExitMonitorState): void =>
callback(state)
+1 -1
View File
@@ -7,7 +7,7 @@
<!-- https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP -->
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: wxe-media:; media-src 'self' https: blob: data: wxe-media:;"
content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https: wxe-media:; media-src 'self' https: blob: data: wxe-media:; frame-src tm-extension:;"
/>
</head>
+3
View File
@@ -46,6 +46,7 @@ import { Button, useToast } from './components/ui'
import { AppUpdatePrompt } from './features/app-update/AppUpdatePrompt'
import { GroupExitMonitorWorkspace, type GroupExitMonitorOpenViewRequest } from './features/group-exit-monitor/GroupExitMonitorWorkspace'
import { AutomationWorkspace, type AutomationOpenRuleRequest } from './features/automation/AutomationWorkspace'
import { ExtensionWorkspace } from './features/extensions/ExtensionWorkspace'
import { selectContactAvatarRefreshUsernames } from './utils/contact-avatar'
import {
buildContactSearchIndex,
@@ -2139,6 +2140,8 @@ function App(): React.ReactElement {
)
case 'agent-hub':
return <AgentHubWorkspace selfInfo={selfInfo} />
case 'extensions':
return <ExtensionWorkspace />
case 'api':
return (
<ApiWorkspace
@@ -46,6 +46,15 @@ function NavIcon({ page }: NavIconProps): React.ReactElement {
<path d="m16.5 9 3 3-3 3" />
</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" />
<path d="M8.5 12h7" />
<path d="M8.5 16h4.5" />
</svg>
)
case 'export':
return (
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false">
@@ -5,6 +5,7 @@ export type AppPage =
| 'exit-monitor'
| 'automation'
| 'agent-hub'
| 'extensions'
| 'export'
| 'api'
| 'settings'
@@ -20,6 +21,7 @@ export const PRIMARY_NAV_ITEMS: NavigationItem[] = [
{ id: 'report', label: '日报' },
{ id: 'exit-monitor', label: '退群监控' },
{ id: 'automation', label: '自动化' },
{ id: 'extensions', label: '扩展' },
{ id: 'agent-hub', label: 'Agent' },
{ id: 'export', label: '导出' },
{ id: 'api', label: 'API' },
@@ -0,0 +1,122 @@
import * as React from 'react'
import {
EXTENSION_PAGE_HOST_SOURCE,
isExtensionPageBridgeRequest
} from '../../../../shared/extensions/ipc'
import type {
ExtensionPageDescriptor,
ExtensionPageMethod
} from '../../../../shared/extensions/types'
import { Button } from '../../components/ui'
interface ExtensionPageHostProps {
descriptor: ExtensionPageDescriptor
onBack: () => void
}
/**
* 扩展页面容器。
*
* 页面在 `sandbox="allow-scripts"` 的 iframe 里运行:没有 Node、没有 preload、
* 没有 `window.api`,与官方渲染层不同源。它与宿主的唯一通道是 postMessage,
* 由本组件转成受白名单约束的 `extensionPageRequest`。
*/
export function ExtensionPageHost({
descriptor,
onBack
}: ExtensionPageHostProps): React.ReactElement {
const frameRef = React.useRef<HTMLIFrameElement | null>(null)
const [loaded, setLoaded] = React.useState(false)
const [slow, setSlow] = React.useState(false)
const [reloadKey, setReloadKey] = React.useState(0)
React.useEffect(() => {
const timer = window.setTimeout(() => setSlow(true), 8_000)
return () => window.clearTimeout(timer)
}, [reloadKey])
React.useEffect(() => {
const onMessage = (event: MessageEvent): void => {
const frame = frameRef.current
if (!frame || event.source !== frame.contentWindow) return
if (!isExtensionPageBridgeRequest(event.data)) return
const request = event.data
if (request.extensionId !== descriptor.extensionId) return
void window.api
.extensionPageRequest({
extensionId: descriptor.extensionId,
method: request.method as ExtensionPageMethod,
params: request.params ?? {}
})
.then((response) => {
frame.contentWindow?.postMessage(
{
source: EXTENSION_PAGE_HOST_SOURCE,
requestId: request.requestId,
ok: response.ok,
...(response.ok ? { result: response.result } : { error: response.error })
},
'*'
)
})
.catch((error) => {
frame.contentWindow?.postMessage(
{
source: EXTENSION_PAGE_HOST_SOURCE,
requestId: request.requestId,
ok: false,
error: {
code: 'ACTION_FAILED',
message: error instanceof Error ? error.message : '调用失败'
}
},
'*'
)
})
}
window.addEventListener('message', onMessage)
return () => window.removeEventListener('message', onMessage)
}, [descriptor.extensionId])
React.useEffect(() => {
const onKeyDown = (event: KeyboardEvent): void => {
if (event.key === 'Escape') onBack()
}
window.addEventListener('keydown', onKeyDown)
return () => window.removeEventListener('keydown', onKeyDown)
}, [onBack])
return (
<div className="extension-page-host">
<header className="extension-page-host-header">
<Button size="sm" variant="ghost" onClick={onBack}>
← 返回扩展中心
</Button>
<div className="extension-page-host-title">
<strong>{descriptor.title}</strong>
<span>{descriptor.extensionId}</span>
</div>
<Button size="sm" variant="ghost" onClick={() => setReloadKey((value) => value + 1)}>
重新加载
</Button>
</header>
<div className="extension-page-host-body">
{!loaded && (
<div className="extension-page-host-loading">
<p>{slow ? '页面尚未响应。扩展页面必须通过 tm.* 与宿主通信。' : '正在加载扩展页面…'}</p>
</div>
)}
<iframe
key={reloadKey}
ref={frameRef}
className="extension-page-frame"
title={descriptor.title}
src={descriptor.url}
sandbox="allow-scripts"
referrerPolicy="no-referrer"
onLoad={() => setLoaded(true)}
/>
</div>
</div>
)
}
@@ -0,0 +1,494 @@
import * as React from 'react'
import {
EXTENSION_PERMISSION_INFO,
sortPermissionsByRisk,
type ExtensionPermission
} from '../../../../shared/extensions/permissions'
import type {
ExtensionLogEntry,
ExtensionPageDescriptor,
InstalledExtension
} from '../../../../shared/extensions/types'
import { Button, Spinner, useToast } from '../../components/ui'
import { ExtensionPageHost } from './ExtensionPageHost'
const STATUS_LABELS: Record<InstalledExtension['runtime']['state'], string> = {
inactive: '未运行',
starting: '启动中',
active: '运行中',
error: '运行错误',
crashed: '已停止'
}
function formatTimestamp(value: number): string {
if (!value) return '—'
return new Date(value).toLocaleString('zh-CN', { hour12: false })
}
function statusTone(extension: InstalledExtension): 'success' | 'warning' | 'danger' | 'muted' {
if (!extension.enabled) return 'muted'
if (extension.runtime.state === 'active') return 'success'
if (extension.runtime.state === 'crashed' || extension.runtime.state === 'error') return 'danger'
return 'warning'
}
export function ExtensionWorkspace(): React.ReactElement {
const { toast } = useToast()
const [extensions, setExtensions] = React.useState<InstalledExtension[]>([])
const [selectedId, setSelectedId] = React.useState<string | null>(null)
const [logs, setLogs] = React.useState<ExtensionLogEntry[]>([])
const [busy, setBusy] = React.useState(false)
const [page, setPage] = React.useState<ExtensionPageDescriptor | null>(null)
const [pendingEnable, setPendingEnable] = React.useState<InstalledExtension | null>(null)
const [pendingUninstall, setPendingUninstall] = React.useState<string | null>(null)
const refresh = React.useCallback(async (): Promise<void> => {
const list = await window.api.listExtensions()
setExtensions(list)
setSelectedId((current) => {
if (current && list.some((item) => item.id === current)) return current
return list[0]?.id ?? null
})
}, [])
React.useEffect(() => {
void refresh().catch(() => undefined)
const unsubscribe = window.api.onExtensionChanged(() => {
void refresh().catch(() => undefined)
})
return unsubscribe
}, [refresh])
const selected = React.useMemo(
() => extensions.find((item) => item.id === selectedId) ?? null,
[extensions, selectedId]
)
const selectedIdForLogs = selected?.id
const selectedRuntimeState = selected?.runtime.state
const selectedUpdatedAt = selected?.updatedAt
React.useEffect(() => {
if (!selectedIdForLogs) {
setLogs([])
return
}
let disposed = false
void window.api
.getExtensionLogs(selectedIdForLogs, 60)
.then((entries) => {
if (!disposed) setLogs(entries)
})
.catch(() => undefined)
return () => {
disposed = true
}
}, [selectedIdForLogs, selectedRuntimeState, selectedUpdatedAt])
const run = async <T,>(action: () => Promise<T>, successMessage?: string): Promise<T | null> => {
setBusy(true)
try {
return await action()
} catch (error) {
toast({
title: '操作失败',
description: error instanceof Error ? error.message : String(error),
variant: 'destructive'
})
return null
} finally {
setBusy(false)
if (successMessage) toast({ title: successMessage, variant: 'success' })
}
}
const installFrom = async (kind: 'directory' | 'package'): Promise<void> => {
const target =
kind === 'directory'
? await window.api.pickExtensionDirectory()
: await window.api.pickExtensionPackage()
if (!target) return
setBusy(true)
try {
const result =
kind === 'directory'
? await window.api.installExtensionFromDirectory(target)
: await window.api.installExtensionFromPackage(target)
if (!result.success) {
toast({
title: '安装失败',
description: result.error?.message || '扩展安装失败',
variant: 'destructive'
})
return
}
await refresh()
if (result.extension) setSelectedId(result.extension.id)
toast({
title: '扩展已安装',
description: `${result.extension?.name || ''} ${result.extension?.version || ''}`.trim(),
variant: 'success'
})
} finally {
setBusy(false)
}
}
const requestEnable = (extension: InstalledExtension): void => {
const risky = extension.permissions.filter(
(permission) => EXTENSION_PERMISSION_INFO[permission].risk !== 'low'
)
if (risky.length > 0) {
setPendingEnable(extension)
return
}
void toggleEnabled(extension, true)
}
const toggleEnabled = async (extension: InstalledExtension, enabled: boolean): Promise<void> => {
setPendingEnable(null)
const result = await run(() => window.api.setExtensionEnabled(extension.id, enabled))
if (result?.success) {
toast({
title: enabled ? '扩展已启用' : '扩展已停用',
description: extension.name,
variant: 'success'
})
await refresh()
} else if (result && !result.success) {
toast({
title: enabled ? '启用失败' : '停用失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
}
}
const confirmUninstall = async (extension: InstalledExtension): Promise<void> => {
setPendingUninstall(null)
const result = await run(() => window.api.uninstallExtension(extension.id, true))
if (result?.success) {
toast({ title: '扩展已卸载', description: '扩展数据已保留', variant: 'success' })
await refresh()
} else if (result && !result.success) {
toast({
title: '卸载失败',
description: result.error?.message || '操作失败',
variant: 'destructive'
})
}
}
if (page) {
return (
<ExtensionPageHost
descriptor={page}
onBack={() => {
setPage(null)
void refresh().catch(() => undefined)
}}
/>
)
}
return (
<div className="extension-workspace">
<aside className="extension-sidebar">
<header className="extension-sidebar-header">
<div>
<h2>扩展</h2>
<p>把二次开发从官方源码里剥离出来</p>
</div>
<span className="extension-count">{extensions.length}</span>
</header>
<div className="extension-install-row">
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() => void installFrom('directory')}
>
安装目录
</Button>
<Button
size="sm"
variant="outline"
disabled={busy}
onClick={() => void installFrom('package')}
>
安装 ZIP
</Button>
</div>
<div className="extension-list" role="listbox" aria-label="已安装扩展">
{extensions.length === 0 ? (
<p className="extension-empty">
还没有安装扩展。可以在 <code>examples/extensions</code> 下找到两个可直接安装的示例。
</p>
) : (
extensions.map((extension) => (
<button
key={extension.id}
type="button"
role="option"
aria-selected={extension.id === selectedId}
className={`extension-list-item ${extension.id === selectedId ? 'is-active' : ''}`}
onClick={() => setSelectedId(extension.id)}
>
<span
className={`extension-status-dot tone-${statusTone(extension)}`}
aria-hidden
/>
<span className="extension-list-main">
<span className="extension-list-name">{extension.name}</span>
<span className="extension-list-meta">
v{extension.version} ·{' '}
{extension.enabled ? STATUS_LABELS[extension.runtime.state] : '已停用'}
</span>
</span>
</button>
))
)}
</div>
</aside>
<section className="extension-detail" aria-label="扩展详情">
{!selected ? (
<div className="extension-detail-empty">
<h3>选择左侧的扩展</h3>
<p>安装后在这里查看权限、页面、自动化动作与执行日志。</p>
</div>
) : (
<>
<header className="extension-detail-header">
<div>
<div className="extension-detail-title">
<h3>{selected.name}</h3>
<span className="extension-version">v{selected.version}</span>
<span className={`extension-badge tone-${statusTone(selected)}`}>
{selected.enabled ? STATUS_LABELS[selected.runtime.state] : '已停用'}
</span>
</div>
<p className="extension-detail-description">
{selected.description || '该扩展没有提供描述。'}
</p>
<p className="extension-detail-id">{selected.id}</p>
{!selected.compatibility.compatible && (
<p className="extension-incompatible">
{selected.compatibility.reason || '扩展与当前版本不兼容'}
</p>
)}
{selected.runtime.lastError && (
<p className="extension-runtime-error">{selected.runtime.lastError}</p>
)}
</div>
<div className="extension-detail-actions">
<Button
size="sm"
variant={selected.enabled ? 'outline' : 'default'}
disabled={busy || !selected.compatibility.compatible}
onClick={() =>
selected.enabled ? void toggleEnabled(selected, false) : requestEnable(selected)
}
>
{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="ghost"
onClick={() => void window.api.openExtensionDataDir(selected.id)}
>
数据目录
</Button>
</div>
</header>
<div className="extension-detail-grid">
<section className="extension-card">
<h4>页面</h4>
{selected.pages.length === 0 ? (
<p className="extension-muted">该扩展没有注册页面。</p>
) : (
<ul className="extension-page-list">
{selected.pages.map((item) => (
<li key={item.id}>
<span>{item.title}</span>
<Button
size="sm"
variant="link"
onClick={() => {
void window.api
.getExtensionPageUrl(selected.id, item.id)
.then(setPage)
.catch(() => undefined)
}}
>
打开
</Button>
</li>
))}
</ul>
)}
</section>
<section className="extension-card">
<h4>权限</h4>
{selected.permissions.length === 0 ? (
<p className="extension-muted">未申请任何权限。</p>
) : (
<ul className="extension-permission-list">
{sortPermissionsByRisk(selected.permissions).map((permission) => (
<li key={permission}>
<div>
<span className="extension-permission-label">
{EXTENSION_PERMISSION_INFO[permission].label}
</span>
<span
className={`extension-permission-risk risk-${EXTENSION_PERMISSION_INFO[permission].risk}`}
>
{EXTENSION_PERMISSION_INFO[permission].risk === 'high'
? '高'
: EXTENSION_PERMISSION_INFO[permission].risk === 'medium'
? '中'
: '低'}
</span>
</div>
<p>{EXTENSION_PERMISSION_INFO[permission].description}</p>
<span
className={`extension-grant ${selected.grantedPermissions.includes(permission) ? 'is-granted' : ''}`}
>
{selected.grantedPermissions.includes(permission) ? '已授予' : '未授予'}
</span>
</li>
))}
</ul>
)}
</section>
<section className="extension-card extension-card-wide">
<h4>自动化动作</h4>
{selected.automationActions.length === 0 ? (
<p className="extension-muted">该扩展没有注册自动化动作。</p>
) : (
<ul className="extension-action-list">
{selected.automationActions.map((action) => (
<li key={action.id}>
<span>{action.title}</span>
<span
className={`extension-grant ${action.registered ? 'is-granted' : ''}`}
>
{action.registered ? '已注册' : '未注册'}
</span>
</li>
))}
</ul>
)}
</section>
<section className="extension-card extension-card-wide">
<div className="extension-card-header">
<h4>运行日志</h4>
<Button
size="sm"
variant="ghost"
onClick={() => {
void window.api.clearExtensionLogs(selected.id).then(() => setLogs([]))
}}
>
清空
</Button>
</div>
{logs.length === 0 ? (
<p className="extension-muted">暂无日志。</p>
) : (
<ul className="extension-log-list">
{logs.map((entry) => (
<li key={entry.id} className={`log-${entry.level}`}>
<span className="extension-log-time">{formatTimestamp(entry.at)}</span>
<span className="extension-log-source">
{entry.source === 'extension' ? '扩展' : '宿主'}
</span>
<span className="extension-log-message">{entry.message}</span>
</li>
))}
</ul>
)}
</section>
</div>
<footer className="extension-detail-footer">
<span>安装于 {formatTimestamp(selected.installedAt)}</span>
{pendingUninstall === selected.id ? (
<span className="extension-uninstall-confirm">
卸载后扩展代码会被移除,配置与数据默认保留。
<Button
size="sm"
variant="destructive"
onClick={() => void confirmUninstall(selected)}
>
确认卸载
</Button>
<Button size="sm" variant="ghost" onClick={() => setPendingUninstall(null)}>
取消
</Button>
</span>
) : (
<Button size="sm" variant="ghost" onClick={() => setPendingUninstall(selected.id)}>
卸载
</Button>
)}
</footer>
</>
)}
</section>
{pendingEnable && (
<div className="extension-modal-backdrop" role="dialog" aria-modal="true">
<div className="extension-modal">
<h3>启用「{pendingEnable.name}」</h3>
<p>该扩展会获得以下权限。扩展代码在独立进程中运行,但仍属于受信任的本地代码。</p>
<ul className="extension-permission-list">
{sortPermissionsByRisk(pendingEnable.permissions).map(
(permission: ExtensionPermission) => (
<li key={permission}>
<div>
<span className="extension-permission-label">
{EXTENSION_PERMISSION_INFO[permission].label}
</span>
</div>
<p>{EXTENSION_PERMISSION_INFO[permission].description}</p>
</li>
)
)}
</ul>
<div className="extension-modal-actions">
<Button variant="ghost" onClick={() => setPendingEnable(null)}>
取消
</Button>
<Button onClick={() => void toggleEnabled(pendingEnable, true)}>确认启用</Button>
</div>
</div>
</div>
)}
{busy && (
<div className="extension-busy" aria-live="polite">
<Spinner />
</div>
)}
</div>
)
}
+597
View File
@@ -0,0 +1,597 @@
/* 扩展中心:左侧扩展列表 + 右侧详情 / 扩展页面容器。 */
.extension-workspace {
box-sizing: border-box;
display: grid;
grid-template-columns: 288px minmax(0, 1fr);
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
background: var(--wxex-bg-main);
color: var(--wxex-text-primary);
font-family: var(--wxex-font);
}
.extension-sidebar {
display: flex;
flex-direction: column;
min-height: 0;
gap: 12px;
padding: 24px 16px 16px;
border-right: 1px solid var(--wxex-border);
background: var(--wxex-bg-sidebar);
}
.extension-sidebar-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
padding: 0 4px;
h2 {
margin: 0;
font-size: 18px;
line-height: 24px;
font-weight: 700;
}
p {
margin: 4px 0 0;
color: var(--wxex-text-muted);
font-size: 12px;
line-height: 18px;
}
}
.extension-count {
min-width: 24px;
height: 22px;
padding: 0 7px;
border-radius: 999px;
background: var(--wxex-brand-soft);
color: var(--wxex-brand);
font-size: 12px;
font-weight: 600;
line-height: 22px;
text-align: center;
}
.extension-install-row {
display: flex;
gap: 8px;
padding: 0 4px;
}
.extension-list {
display: flex;
flex-direction: column;
gap: 4px;
min-height: 0;
overflow: auto;
padding: 2px 0 8px;
}
.extension-list-item {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
padding: 10px 10px;
border: 1px solid transparent;
border-radius: var(--wxex-radius-md);
background: transparent;
color: inherit;
text-align: left;
cursor: pointer;
&:hover {
background: var(--wxex-brand-soft);
}
&.is-active {
border-color: var(--wxex-border);
background: var(--wxex-bg-elevated);
box-shadow: var(--wxex-shadow-popover);
}
}
.extension-status-dot {
flex: 0 0 auto;
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--wxex-text-muted);
&.tone-success {
background: var(--wxex-success);
}
&.tone-warning {
background: var(--wxex-warning);
}
&.tone-danger {
background: var(--wxex-danger);
}
}
.extension-list-main {
display: flex;
flex-direction: column;
min-width: 0;
}
.extension-list-name {
font-size: 13px;
font-weight: 600;
line-height: 18px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.extension-list-meta {
color: var(--wxex-text-muted);
font-size: 11px;
line-height: 16px;
}
.extension-empty {
margin: 8px 4px;
color: var(--wxex-text-muted);
font-size: 12px;
line-height: 19px;
}
.extension-detail {
display: flex;
flex-direction: column;
min-width: 0;
min-height: 0;
overflow: auto;
padding: 28px clamp(20px, 3vw, 40px) 32px;
gap: 18px;
}
.extension-detail-empty {
margin: auto;
max-width: 42ch;
text-align: center;
color: var(--wxex-text-muted);
h3 {
margin: 0 0 8px;
color: var(--wxex-text-primary);
font-size: 16px;
}
p {
margin: 0;
font-size: 13px;
line-height: 20px;
}
}
.extension-detail-header {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 20px;
flex-wrap: wrap;
}
.extension-detail-title {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
h3 {
margin: 0;
font-size: 22px;
line-height: 30px;
font-weight: 700;
}
}
.extension-version {
color: var(--wxex-text-muted);
font-size: 12px;
}
.extension-badge {
padding: 2px 8px;
border-radius: 999px;
background: var(--wxex-bg-sidebar);
color: var(--wxex-text-secondary);
font-size: 11px;
font-weight: 600;
line-height: 18px;
&.tone-success {
background: color-mix(in srgb, var(--wxex-success) 14%, transparent);
color: var(--wxex-success);
}
&.tone-warning {
background: color-mix(in srgb, var(--wxex-warning) 16%, transparent);
color: var(--wxex-warning);
}
&.tone-danger {
background: color-mix(in srgb, var(--wxex-danger) 14%, transparent);
color: var(--wxex-danger);
}
}
.extension-detail-description {
margin: 8px 0 0;
max-width: 72ch;
color: var(--wxex-text-secondary);
font-size: 13px;
line-height: 20px;
}
.extension-detail-id {
margin: 6px 0 0;
color: var(--wxex-text-muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
}
.extension-incompatible,
.extension-runtime-error {
margin: 8px 0 0;
padding: 6px 10px;
border-radius: var(--wxex-radius-sm);
background: color-mix(in srgb, var(--wxex-danger) 10%, transparent);
color: var(--wxex-danger);
font-size: 12px;
line-height: 18px;
}
.extension-detail-actions {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
padding-top: 4px;
}
.extension-detail-grid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 14px;
}
.extension-card {
display: flex;
flex-direction: column;
gap: 10px;
min-width: 0;
padding: 16px 18px;
border: 1px solid var(--wxex-border);
border-radius: var(--wxex-radius-lg);
background: var(--wxex-bg-elevated);
h4 {
margin: 0;
font-size: 13px;
font-weight: 700;
}
}
.extension-card-wide {
grid-column: 1 / -1;
}
.extension-card-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.extension-muted {
margin: 0;
color: var(--wxex-text-muted);
font-size: 12px;
line-height: 19px;
}
.extension-hint {
margin: 0;
color: var(--wxex-text-muted);
font-size: 11px;
line-height: 17px;
}
.extension-page-list,
.extension-action-list {
display: flex;
flex-direction: column;
gap: 8px;
margin: 0;
padding: 0;
list-style: none;
li {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
font-size: 13px;
}
}
.extension-permission-list {
display: flex;
flex-direction: column;
gap: 12px;
margin: 0;
padding: 0;
list-style: none;
li {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 4px 10px;
padding-bottom: 10px;
border-bottom: 1px solid var(--wxex-border);
&:last-child {
border-bottom: none;
padding-bottom: 0;
}
> div {
flex: 1 1 auto;
min-width: 0;
}
> .extension-grant {
margin-left: auto;
}
}
p {
flex: 0 0 100%;
order: 3;
margin: 0;
color: var(--wxex-text-muted);
font-size: 11px;
line-height: 17px;
}
}
.extension-permission-label {
font-size: 13px;
font-weight: 600;
}
.extension-permission-risk {
margin-left: 6px;
padding: 0 5px;
border-radius: 4px;
font-size: 10px;
font-weight: 600;
line-height: 16px;
&.risk-high {
background: color-mix(in srgb, var(--wxex-danger) 14%, transparent);
color: var(--wxex-danger);
}
&.risk-medium {
background: color-mix(in srgb, var(--wxex-warning) 16%, transparent);
color: var(--wxex-warning);
}
&.risk-low {
background: var(--wxex-bg-sidebar);
color: var(--wxex-text-muted);
}
}
.extension-grant {
align-self: flex-start;
padding: 1px 7px;
border-radius: 999px;
background: var(--wxex-bg-sidebar);
color: var(--wxex-text-muted);
font-size: 10px;
line-height: 16px;
white-space: nowrap;
&.is-granted {
background: color-mix(in srgb, var(--wxex-success) 12%, transparent);
color: var(--wxex-success);
}
}
.extension-log-list {
display: flex;
flex-direction: column;
gap: 4px;
margin: 0;
padding: 0;
max-height: 320px;
overflow: auto;
list-style: none;
li {
display: grid;
grid-template-columns: 132px 40px minmax(0, 1fr);
gap: 10px;
align-items: baseline;
padding: 4px 6px;
border-radius: var(--wxex-radius-sm);
font-size: 12px;
line-height: 18px;
&.log-warn {
background: color-mix(in srgb, var(--wxex-warning) 8%, transparent);
}
&.log-error {
background: color-mix(in srgb, var(--wxex-danger) 8%, transparent);
color: var(--wxex-danger);
}
}
}
.extension-log-time {
color: var(--wxex-text-muted);
font-variant-numeric: tabular-nums;
font-size: 11px;
}
.extension-log-source {
color: var(--wxex-text-muted);
font-size: 11px;
}
.extension-log-message {
min-width: 0;
overflow-wrap: anywhere;
}
.extension-detail-footer {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
padding-top: 6px;
color: var(--wxex-text-muted);
font-size: 11px;
}
.extension-uninstall-confirm {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
color: var(--wxex-danger);
}
.extension-modal-backdrop {
position: fixed;
inset: 0;
z-index: 60;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
background: rgba(15, 20, 18, 0.42);
}
.extension-modal {
width: min(520px, 100%);
max-height: 80vh;
overflow: auto;
padding: 22px 24px;
border-radius: var(--wxex-radius-lg);
background: var(--wxex-bg-elevated);
box-shadow: 0 18px 48px rgba(0, 0, 0, 0.24);
h3 {
margin: 0 0 6px;
font-size: 16px;
}
> p {
margin: 0 0 14px;
color: var(--wxex-text-secondary);
font-size: 12px;
line-height: 19px;
}
}
.extension-modal-actions {
display: flex;
justify-content: flex-end;
gap: 8px;
margin-top: 18px;
}
.extension-busy {
position: fixed;
inset: 0;
z-index: 70;
display: flex;
align-items: center;
justify-content: center;
background: color-mix(in srgb, var(--wxex-bg-main) 55%, transparent);
}
/* 扩展页面容器:iframe 铺满,头部保留返回入口。 */
.extension-page-host {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-width: 0;
min-height: 0;
background: var(--wxex-bg-main);
}
.extension-page-host-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 16px;
padding: 10px 16px;
border-bottom: 1px solid var(--wxex-border);
}
.extension-page-host-title {
display: flex;
flex-direction: column;
align-items: center;
line-height: 16px;
span {
color: var(--wxex-text-muted);
font-size: 10px;
}
}
.extension-page-host-body {
position: relative;
flex: 1;
min-height: 0;
background: var(--wxex-bg-elevated);
}
.extension-page-frame {
width: 100%;
height: 100%;
border: 0;
background: var(--wxex-bg-elevated);
}
.extension-page-host-loading {
position: absolute;
inset: 0;
z-index: 1;
display: flex;
align-items: center;
justify-content: center;
padding: 24px;
color: var(--wxex-text-muted);
font-size: 12px;
text-align: center;
}
@media (max-width: 1080px) {
.extension-workspace {
grid-template-columns: 232px minmax(0, 1fr);
}
.extension-detail-grid {
grid-template-columns: minmax(0, 1fr);
}
}
+1
View File
@@ -21,4 +21,5 @@
@use './group-member-stats';
@use './local-index';
@use './automation';
@use './extensions';
@use './theme';
+50 -12
View File
@@ -6,10 +6,7 @@
*/
import { normalizeGroupExitNotificationTemplate } from './group-exit-monitor'
import {
isSelectableReportTemplateId,
type SelectableReportTemplateId
} from './report-templates'
import { isSelectableReportTemplateId, type SelectableReportTemplateId } from './report-templates'
import type {
ScheduledReportMemberNameMode,
ScheduledReportMessageType,
@@ -321,9 +318,7 @@ export function calculateNextRunAt(scheduleTime: string, from: Date = new Date()
}
/** 收敛定时日报配置:未知值一律回落到安全默认,绝不落一条跑不起来的规则。 */
export function normalizeScheduledReportConfig(
input: unknown
): ScheduledReportAutomationConfig {
export function normalizeScheduledReportConfig(input: unknown): ScheduledReportAutomationConfig {
const raw = (input ?? {}) as Partial<ScheduledReportAutomationConfig>
const scheduleRaw = (raw.schedule ?? {}) as Partial<ScheduledReportAutomationConfig['schedule']>
const reportRaw = (raw.report ?? {}) as Partial<ScheduledReportAutomationConfig['report']>
@@ -421,13 +416,23 @@ export interface AutomationConditions {
}
/** 执行动作类型。顺序由 `actions` 数组顺序决定。 */
export type AutomationActionType = 'replyText' | 'generateReport' | 'sendReportImage'
export type AutomationActionType =
| 'replyText'
| 'generateReport'
| 'sendReportImage'
| 'extensionAction'
export interface AutomationAction {
type: AutomationActionType
enabled: boolean
/** `replyText` 的文案。 */
text?: string
/** `extensionAction`:提供动作的扩展 id。 */
extensionId?: string
/** `extensionAction`:扩展内注册的动作 id。 */
actionId?: string
/** `extensionAction`:用户配置的静态输入(JSON 对象)。 */
input?: Record<string, unknown>
}
export interface AutomationRule {
@@ -483,6 +488,7 @@ export type AutomationStepStatus = 'pending' | 'running' | 'success' | 'failed'
export type AutomationStepKey =
| 'received'
| 'matched'
| 'extension_action'
| 'reply'
| 'report'
| 'send'
@@ -771,6 +777,7 @@ export const LEAVE_NOTIFICATION_RULE_NAME = '退群通知'
export const AUTOMATION_STEP_LABELS: Record<AutomationStepKey, string> = {
received: '收到消息',
matched: '规则匹配',
extension_action: '执行扩展动作',
reply: '回复确认',
report: '生成日报',
send: '发送日报图片',
@@ -998,7 +1005,8 @@ export function describeRuleActions(rule: AutomationRule): string {
const labels: Record<AutomationActionType, string> = {
replyText: '回复确认',
generateReport: '生成日报',
sendReportImage: '发送图片'
sendReportImage: '发送图片',
extensionAction: '执行扩展动作'
}
const enabled = rule.actions.filter((action) => action.enabled)
return enabled.length ? enabled.map((action) => labels[action.type]).join(' → ') : '无动作'
@@ -1152,6 +1160,29 @@ export function createDefaultScheduledReportRule(
}
}
/** 扩展动作静态输入的体积上限(序列化后字符数)。 */
export const EXTENSION_ACTION_INPUT_MAX_CHARS = 4_000
/**
* 收敛扩展动作的静态输入。
*
* 只接受 JSON 对象:数组 / 字符串会让「输入」变成不可预期的形状,
* 扩展作者无法在 `inputSchema` 里表达;超限直接丢弃而不是截断,
* 截断后的 JSON 可能语义完全不同。
*/
export function normalizeExtensionActionInput(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined
try {
const text = JSON.stringify(value)
if (!text || text.length > EXTENSION_ACTION_INPUT_MAX_CHARS) return undefined
const parsed = JSON.parse(text) as unknown
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
return parsed as Record<string, unknown>
} catch {
return undefined
}
}
/** 归一化用户提交的草稿:把未知值收敛成合法值,避免脏数据落盘。 */
export function normalizeRuleDraft(
input: unknown,
@@ -1177,13 +1208,19 @@ export function normalizeRuleDraft(
.map((action) => ({
type: action.type,
enabled: action.enabled !== false,
...(typeof action.text === 'string' ? { text: action.text } : {})
...(typeof action.text === 'string' ? { text: action.text } : {}),
...(typeof action.extensionId === 'string' ? { extensionId: action.extensionId.trim() } : {}),
...(typeof action.actionId === 'string' ? { actionId: action.actionId.trim() } : {}),
...(normalizeExtensionActionInput(action.input)
? { input: normalizeExtensionActionInput(action.input) }
: {})
}))
.filter(
(action) =>
action.type === 'replyText' ||
action.type === 'generateReport' ||
action.type === 'sendReportImage'
action.type === 'sendReportImage' ||
(action.type === 'extensionAction' && Boolean(action.extensionId && action.actionId))
)
const cooldown = Number(raw.cooldownSeconds)
const base = {
@@ -1243,7 +1280,8 @@ export function normalizeLeaveNotificationConfig(input: unknown): LeaveNotificat
...(effectiveType === 'contact' ? { contactId } : {})
},
template: normalizeLeaveNotificationTemplate(raw.template),
notifyScope: raw.notifyScope === 'selected' ? 'selected' : LEAVE_NOTIFICATION_DEFAULT_NOTIFY_SCOPE,
notifyScope:
raw.notifyScope === 'selected' ? 'selected' : LEAVE_NOTIFICATION_DEFAULT_NOTIFY_SCOPE,
notifyRoomIds: normalizeLeaveNotificationRoomIds(raw.notifyRoomIds),
// 用户手动保存一次即视为已确认目标,清除迁移提示。
...(raw.targetNeedsReview === true ? { targetNeedsReview: true } : {})
+98
View File
@@ -0,0 +1,98 @@
/**
* 扩展系统的稳定错误码。
*
* 调用方(UI / 扩展 SDK / 自动化 runner)只依赖这里的 `code`,
* 不解析 `message` —— 文案会改,错误码不会。
*/
export const EXTENSION_ERROR_CODES = [
'EXTENSION_NOT_FOUND',
'EXTENSION_DISABLED',
'EXTENSION_INCOMPATIBLE',
'EXTENSION_ALREADY_INSTALLED',
'EXTENSION_INSTALL_FAILED',
'EXTENSION_INVALID_MANIFEST',
'EXTENSION_INVALID_PATH',
'EXTENSION_HOST_UNAVAILABLE',
'PERMISSION_DENIED',
'CAPABILITY_UNAVAILABLE',
'LICENSE_REQUIRED',
'DATABASE_NOT_READY',
'SEND_NOT_SUPPORTED',
'ACTION_TIMEOUT',
'ACTION_FAILED',
'RATE_LIMITED',
'INVALID_REQUEST',
'STORAGE_LIMIT_EXCEEDED'
] as const
export type ExtensionErrorCode = (typeof EXTENSION_ERROR_CODES)[number]
export const EXTENSION_ERROR_MESSAGES: Record<ExtensionErrorCode, string> = {
EXTENSION_NOT_FOUND: '找不到该扩展',
EXTENSION_DISABLED: '扩展当前未启用',
EXTENSION_INCOMPATIBLE: '扩展与当前 TraceMemo 版本不兼容',
EXTENSION_ALREADY_INSTALLED: '已安装同名扩展',
EXTENSION_INSTALL_FAILED: '扩展安装失败',
EXTENSION_INVALID_MANIFEST: '扩展 manifest 不合法',
EXTENSION_INVALID_PATH: '扩展资源路径不合法',
EXTENSION_HOST_UNAVAILABLE: '扩展后台进程不可用',
PERMISSION_DENIED: '扩展没有该权限',
CAPABILITY_UNAVAILABLE: '当前环境不具备该能力',
LICENSE_REQUIRED: '需要有效授权',
DATABASE_NOT_READY: '微信数据库尚未连接',
SEND_NOT_SUPPORTED: '当前发送能力不支持该消息类型',
ACTION_TIMEOUT: '扩展处理超时',
ACTION_FAILED: '扩展执行失败',
RATE_LIMITED: '触发频率限制,请稍后再试',
INVALID_REQUEST: '请求格式不合法',
STORAGE_LIMIT_EXCEEDED: '扩展存储已超出上限'
}
export interface ExtensionErrorPayload {
code: ExtensionErrorCode
message: string
/** 可选的机器可读细节;**不允许**放聊天正文、文件路径、wxid。 */
detail?: string
}
export class ExtensionError extends Error {
readonly code: ExtensionErrorCode
constructor(code: ExtensionErrorCode, message?: string, options?: { cause?: unknown }) {
super(message || EXTENSION_ERROR_MESSAGES[code], options)
this.name = 'ExtensionError'
this.code = code
}
}
export function extensionError(code: ExtensionErrorCode, message?: string): ExtensionError {
return new ExtensionError(code, message)
}
export function isExtensionErrorCode(value: unknown): value is ExtensionErrorCode {
return typeof value === 'string' && (EXTENSION_ERROR_CODES as readonly string[]).includes(value)
}
/** 任意异常 → 可跨进程传输的错误载荷。未知异常一律落到 `ACTION_FAILED`。 */
export function toExtensionErrorPayload(error: unknown): ExtensionErrorPayload {
if (error instanceof ExtensionError) {
return { code: error.code, message: error.message }
}
if (error && typeof error === 'object') {
const candidate = error as { code?: unknown; message?: unknown }
if (isExtensionErrorCode(candidate.code)) {
return {
code: candidate.code,
message:
typeof candidate.message === 'string'
? candidate.message
: EXTENSION_ERROR_MESSAGES[candidate.code]
}
}
if (typeof candidate.message === 'string' && candidate.message.trim()) {
return { code: 'ACTION_FAILED', message: candidate.message.trim() }
}
}
return { code: 'ACTION_FAILED', message: EXTENSION_ERROR_MESSAGES.ACTION_FAILED }
}
+123
View File
@@ -0,0 +1,123 @@
import type { ExtensionMessageType, ExtensionSubscriptions } from './manifest'
/**
* 投递给扩展的规范化消息事件。
*
* **字段契约**
* - `timestamp` 是 **epoch 毫秒**(MessageListener 内部是 epoch 秒,换算只在主进程做一次)。
* - `eventId` 对同一条微信消息稳定:`message:<sha1(sessionId:localId)>`,
* 扩展重启、后台补投都拿到同一个值,可直接用于幂等。
* - `text` 只在可安全还原为纯文本时出现;图片 / 语音 / 视频等不带正文。
*/
export interface ExtensionMessageEvent {
eventId: string
accountId: string
conversationId: string
messageId: string
senderId?: string
senderName?: string
isGroup: boolean
isSelf: boolean
type: ExtensionMessageType
text?: string
/** 真正 @ 到当前登录账号(来自 `atuserlist` ∩ 自身 username),不是正文里的 `@昵称`。 */
mentionsMe: boolean
timestamp: number
}
/** 事件协议版本。未来的持久化队列 / 可靠投递必须保持向后兼容。 */
export const EXTENSION_EVENT_PROTOCOL_VERSION = 1
export interface ExtensionEventEnvelope {
version: number
kind: 'message.received'
event: ExtensionMessageEvent
}
/**
* 微信 `local_type` / `messageType` → 扩展侧消息类型。
*
* 未列出的类型归到 `other`:扩展宁可收到一个明确的 `other`,
* 也不要因为宿主新增类型而静默收不到事件。
*/
export function mapWechatMessageType(messageType: number): ExtensionMessageType {
switch (Number(messageType)) {
case 1:
return 'text'
case 3:
return 'image'
case 34:
return 'voice'
case 43:
return 'video'
case 47:
return 'sticker'
case 49:
return 'link'
case 10000:
case 10002:
return 'system'
default:
return 'other'
}
}
export interface BuildExtensionMessageEventInput {
eventId: string
accountId: string
conversationId: string
messageId: string
senderId?: string
senderName?: string
isGroup: boolean
isSelf: boolean
messageType: number
content?: string
mentionsMe: boolean
/** epoch 秒,与 MessageListener 同口径。 */
createTimeSeconds: number
}
export function buildExtensionMessageEvent(
input: BuildExtensionMessageEventInput
): ExtensionMessageEvent {
const type = mapWechatMessageType(input.messageType)
const text = type === 'text' ? String(input.content ?? '') : ''
return {
eventId: input.eventId,
accountId: input.accountId,
conversationId: input.conversationId,
messageId: input.messageId,
...(input.senderId ? { senderId: input.senderId } : {}),
...(input.senderName ? { senderName: input.senderName } : {}),
isGroup: input.isGroup,
isSelf: input.isSelf,
type,
...(text ? { text } : {}),
mentionsMe: input.mentionsMe,
timestamp: Math.round(input.createTimeSeconds * 1000)
}
}
/**
* manifest 级订阅过滤。
*
* 这一层只做「扩展作者声明过的粗筛」;用户级的开关是扩展的启用状态与权限授予,
* 不在事件总线里再做第二套真相。
*/
export function shouldDeliverExtensionEvent(
subscriptions: ExtensionSubscriptions | undefined,
event: ExtensionMessageEvent
): boolean {
if (!subscriptions) return false
if (!subscriptions.includeSelf && event.isSelf) return false
if (subscriptions.requireMentionMe && !event.mentionsMe) return false
if (!subscriptions.messageTypes.includes(event.type)) return false
if (
subscriptions.conversationIds.length > 0 &&
!subscriptions.conversationIds.includes(event.conversationId)
) {
return false
}
return true
}
+62
View File
@@ -0,0 +1,62 @@
import type { ExtensionErrorPayload } from './errors'
/** 扩展中心 IPC 通道。渲染层只依赖这些常量,不手写通道字符串。 */
export const EXTENSION_IPC = {
list: 'extension:list',
detail: 'extension:get',
installDirectory: 'extension:installDirectory',
installPackage: 'extension:installPackage',
pickDirectory: 'extension:pickDirectory',
pickPackage: 'extension:pickPackage',
setEnabled: 'extension:setEnabled',
uninstall: 'extension:uninstall',
logs: 'extension:getLogs',
clearLogs: 'extension:clearLogs',
pageUrl: 'extension:getPageUrl',
pageRequest: 'extension:pageRequest',
openDataDir: 'extension:openDataDir',
changed: 'extension:changed'
} as const
export type ExtensionChangeReason =
| 'installed'
| 'enabled'
| 'disabled'
| 'uninstalled'
| 'runtime'
| 'actions'
export interface ExtensionChangedEvent {
extensionId: string
reason: ExtensionChangeReason
}
export const EXTENSION_PAGE_MESSAGE_SOURCE = 'tracememo-extension-page'
export const EXTENSION_PAGE_HOST_SOURCE = 'tracememo-extension-host'
export interface ExtensionPageBridgeRequest {
source: typeof EXTENSION_PAGE_MESSAGE_SOURCE
extensionId: string
requestId: string
method: string
params?: Record<string, unknown>
}
export interface ExtensionPageBridgeResponse {
source: typeof EXTENSION_PAGE_HOST_SOURCE
requestId: string
ok: boolean
result?: unknown
error?: ExtensionErrorPayload
}
export function isExtensionPageBridgeRequest(value: unknown): value is ExtensionPageBridgeRequest {
if (!value || typeof value !== 'object') return false
const candidate = value as Partial<ExtensionPageBridgeRequest>
return (
candidate.source === EXTENSION_PAGE_MESSAGE_SOURCE &&
typeof candidate.extensionId === 'string' &&
typeof candidate.requestId === 'string' &&
typeof candidate.method === 'string'
)
}
+419
View File
@@ -0,0 +1,419 @@
import {
EXTENSION_PERMISSIONS,
normalizeExtensionPermissions,
type ExtensionPermission
} from './permissions'
/**
* 扩展 manifest v1。
*
* 校验策略:**未知值一律拒绝而不是静默丢弃**。一个拼错的权限名如果被悄悄忽略,
* 扩展会在运行期以 `PERMISSION_DENIED` 失败,而作者看到的是「manifest 合法」。
*/
export const EXTENSION_MANIFEST_VERSION = 1
/** 宿主实现的扩展 API 主版本。扩展的 `apiVersion` 主版本必须与它相同。 */
export const EXTENSION_API_VERSION = '1'
/** 低于该版本的 TraceMemo 不允许安装本 SDK 产出的扩展。 */
export const EXTENSION_MIN_APP_VERSION = '2.6.0'
export type ExtensionMessageType =
| 'text'
| 'image'
| 'voice'
| 'video'
| 'sticker'
| 'file'
| 'link'
| 'system'
| 'other'
export const EXTENSION_MESSAGE_TYPES: readonly ExtensionMessageType[] = [
'text',
'image',
'voice',
'video',
'sticker',
'file',
'link',
'system',
'other'
]
export interface ExtensionPageContribution {
id: string
title: string
/** 相对扩展根目录的 HTML 路径;缺省用 `entrypoints.page`。 */
entry?: string
}
export interface ExtensionAutomationActionContribution {
id: string
title: string
description?: string
}
export interface ExtensionSubscriptions {
messageTypes: ExtensionMessageType[]
/** 空数组 = 不按会话过滤。非空时只投递这些会话。 */
conversationIds: string[]
requireMentionMe: boolean
/** 默认 false:扩展默认收不到自己发出的消息。 */
includeSelf: boolean
}
export interface ExtensionManifest {
manifestVersion: number
id: string
name: string
version: string
apiVersion: string
minAppVersion?: string
description?: string
author?: string
homepage?: string
permissions: ExtensionPermission[]
entrypoints: {
page?: string
background?: string
}
subscriptions?: ExtensionSubscriptions
contributions: {
pages: ExtensionPageContribution[]
automationActions: ExtensionAutomationActionContribution[]
}
}
export interface ExtensionCompatibility {
compatible: boolean
code?: 'api_version' | 'app_version' | 'manifest'
reason?: string
}
export interface ManifestParseResult {
ok: boolean
manifest?: ExtensionManifest
code?: 'EXTENSION_INVALID_MANIFEST' | 'EXTENSION_INCOMPATIBLE'
message?: string
}
const EXTENSION_ID_PATTERN =
/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?)+$/
const RESERVED_ID_PREFIXES = ['com.tracememo.', 'tracememo.', 'tm.']
const SEMVER_PATTERN = /^(\d{1,4})\.(\d{1,4})\.(\d{1,4})(?:-[0-9A-Za-z.-]{1,40})?$/
const PAGE_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/
const ACTION_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{1,63}$/
const MAX_PAGES = 20
const MAX_AUTOMATION_ACTIONS = 20
const MAX_NAME_LENGTH = 64
const MAX_DESCRIPTION_LENGTH = 500
const MAX_CONVERSATION_SCOPE = 200
export function isValidExtensionId(value: unknown): value is string {
if (typeof value !== 'string') return false
const id = value.trim()
if (id.length < 3 || id.length > 128) return false
if (!EXTENSION_ID_PATTERN.test(id)) return false
return !RESERVED_ID_PREFIXES.some((prefix) => id.startsWith(prefix))
}
export function isValidExtensionVersion(value: unknown): value is string {
return typeof value === 'string' && SEMVER_PATTERN.test(value.trim())
}
/**
* 纯数字比较,忽略 prerelease。
*
* `minAppVersion` 的语义是「最低可运行版本」,把 `2.6.0-beta.1` 判成低于 `2.6.0`
* 会让预发布构建无法安装明示支持的扩展;宁可放行,也不误伤。
*/
export function compareSemver(left: string, right: string): number | null {
const a = SEMVER_PATTERN.exec(String(left || '').trim())
const b = SEMVER_PATTERN.exec(String(right || '').trim())
if (!a || !b) return null
for (let index = 1; index <= 3; index += 1) {
const delta = Number(a[index]) - Number(b[index])
if (delta !== 0) return delta > 0 ? 1 : -1
}
return 0
}
export function isApiVersionCompatible(
apiVersion: unknown,
hostApiVersion = EXTENSION_API_VERSION
): boolean {
const declared = String(apiVersion ?? '').trim()
if (!/^\d+$/.test(declared)) return false
return declared === String(hostApiVersion).trim()
}
export function checkExtensionCompatibility(
input: { apiVersion?: unknown; minAppVersion?: unknown },
appVersion: string
): ExtensionCompatibility {
if (!isApiVersionCompatible(input.apiVersion)) {
return {
compatible: false,
code: 'api_version',
reason: `扩展 API 版本 ${String(input.apiVersion ?? '')} 与当前 TraceMemo 不兼容`
}
}
const minAppVersion = String(input.minAppVersion ?? '').trim()
if (!minAppVersion) return { compatible: true }
if (!isValidExtensionVersion(minAppVersion)) {
return { compatible: false, code: 'manifest', reason: 'minAppVersion 不是合法版本号' }
}
const compared = compareSemver(appVersion, minAppVersion)
if (compared === null) return { compatible: true }
if (compared < 0) {
return {
compatible: false,
code: 'app_version',
reason: `需要 TraceMemo ${minAppVersion} 或更高版本(当前 ${appVersion})`
}
}
return { compatible: true }
}
/**
* 相对路径安全检查(纯字符串层)。
*
* 只做语法判断;**真实路径是否仍在扩展目录内必须由主进程用 realpath 再验一次** ——
* 符号链接可以绕过任何纯字符串检查。
*/
export function isSafeRelativeEntryPath(value: unknown): value is string {
if (typeof value !== 'string') return false
const raw = value.trim().replace(/\\/g, '/')
if (!raw || raw.length > 240) return false
if (raw.includes('\0')) return false
if (raw.startsWith('/') || raw.startsWith('//')) return false
if (/^[A-Za-z]:/.test(raw)) return false
const segments = raw.split('/')
if (segments.length > 10) return false
for (const segment of segments) {
if (!segment || segment === '.' || segment === '..') return false
if (segment.length > 64) return false
if (!/^[A-Za-z0-9._@+\- ]+$/.test(segment)) return false
if (/[. ]$/.test(segment)) return false
// Windows 对 `con.txt` 与 `con` 一视同仁,保留名按「点前的主干」判断。
if (/^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(segment)) return false
}
return true
}
function asTrimmedString(value: unknown, maxLength: number): string {
if (typeof value !== 'string') return ''
return value.trim().slice(0, maxLength)
}
function parseMessageTypes(input: unknown): ExtensionMessageType[] {
if (!Array.isArray(input)) return ['text']
const result: ExtensionMessageType[] = []
for (const value of input) {
if (typeof value !== 'string') return []
if (!EXTENSION_MESSAGE_TYPES.includes(value as ExtensionMessageType)) return []
const typed = value as ExtensionMessageType
if (!result.includes(typed)) result.push(typed)
}
return result.length ? result : ['text']
}
function parseSubscriptions(input: unknown): ExtensionSubscriptions | null {
if (input === undefined) return null
if (!input || typeof input !== 'object' || Array.isArray(input)) return null
const raw = input as Record<string, unknown>
const messageTypes = parseMessageTypes(raw.messageTypes)
if (!messageTypes.length) return null
const conversationIds: string[] = []
if (raw.conversationIds !== undefined) {
if (!Array.isArray(raw.conversationIds)) return null
if (raw.conversationIds.length > MAX_CONVERSATION_SCOPE) return null
for (const value of raw.conversationIds) {
if (typeof value !== 'string') return null
const id = value.trim()
if (!id || id.length > 128) return null
if (!conversationIds.includes(id)) conversationIds.push(id)
}
}
return {
messageTypes,
conversationIds,
requireMentionMe: raw.requireMentionMe === true,
includeSelf: raw.includeSelf === true
}
}
function parsePages(input: unknown): ExtensionPageContribution[] | null {
if (input === undefined) return []
if (!Array.isArray(input) || input.length > MAX_PAGES) return null
const pages: ExtensionPageContribution[] = []
for (const value of input) {
if (!value || typeof value !== 'object') return null
const raw = value as Record<string, unknown>
const id = asTrimmedString(raw.id, 32)
const title = asTrimmedString(raw.title, 40)
if (!PAGE_ID_PATTERN.test(id) || !title) return null
if (pages.some((page) => page.id === id)) return null
if (raw.entry !== undefined) {
if (!isSafeRelativeEntryPath(raw.entry)) return null
pages.push({ id, title, entry: raw.entry })
} else {
pages.push({ id, title })
}
}
return pages
}
function parseAutomationActions(input: unknown): ExtensionAutomationActionContribution[] | null {
if (input === undefined) return []
if (!Array.isArray(input) || input.length > MAX_AUTOMATION_ACTIONS) return null
const actions: ExtensionAutomationActionContribution[] = []
for (const value of input) {
if (!value || typeof value !== 'object') return null
const raw = value as Record<string, unknown>
const id = asTrimmedString(raw.id, 64)
const title = asTrimmedString(raw.title, 60)
if (!ACTION_ID_PATTERN.test(id) || !title) return null
if (actions.some((action) => action.id === id)) return null
const description = asTrimmedString(raw.description, 200)
actions.push({ id, title, ...(description ? { description } : {}) })
}
return actions
}
function fail(
message: string,
code: ManifestParseResult['code'] = 'EXTENSION_INVALID_MANIFEST'
): ManifestParseResult {
return { ok: false, code, message }
}
/** 解析并收敛 manifest。失败时返回**具体**原因,供安装界面直接展示。 */
export function parseExtensionManifest(
input: unknown,
options: { appVersion?: string } = {}
): ManifestParseResult {
if (!input || typeof input !== 'object' || Array.isArray(input)) {
return fail('manifest 必须是 JSON 对象')
}
const raw = input as Record<string, unknown>
if (Number(raw.manifestVersion) !== EXTENSION_MANIFEST_VERSION) {
return fail(`manifestVersion 必须是 ${EXTENSION_MANIFEST_VERSION}`)
}
if (!isValidExtensionId(raw.id)) {
return fail('id 必须是反向域名形式(如 com.example.hello),且不能使用 TraceMemo 保留前缀')
}
const name = asTrimmedString(raw.name, MAX_NAME_LENGTH)
if (!name) return fail('name 不能为空')
if (!isValidExtensionVersion(raw.version)) return fail('version 必须是 x.y.z 形式')
if (!isApiVersionCompatible(raw.apiVersion)) {
return fail('apiVersion 与当前 TraceMemo 扩展 API 不兼容', 'EXTENSION_INCOMPATIBLE')
}
if (raw.minAppVersion !== undefined && !isValidExtensionVersion(raw.minAppVersion)) {
return fail('minAppVersion 必须是 x.y.z 形式')
}
if (!Array.isArray(raw.permissions)) return fail('permissions 必须是数组')
for (const permission of raw.permissions) {
if (
typeof permission !== 'string' ||
!(EXTENSION_PERMISSIONS as readonly string[]).includes(permission)
) {
return fail(`未知权限:${String(permission)}`)
}
}
const permissions = normalizeExtensionPermissions(raw.permissions)
const entrypointsRaw = raw.entrypoints
if (!entrypointsRaw || typeof entrypointsRaw !== 'object' || Array.isArray(entrypointsRaw)) {
return fail('entrypoints 必须是对象')
}
const entryRaw = entrypointsRaw as Record<string, unknown>
const entrypoints: ExtensionManifest['entrypoints'] = {}
if (entryRaw.page !== undefined) {
if (!isSafeRelativeEntryPath(entryRaw.page)) return fail('entrypoints.page 不是安全的相对路径')
entrypoints.page = entryRaw.page
}
if (entryRaw.background !== undefined) {
if (!isSafeRelativeEntryPath(entryRaw.background)) {
return fail('entrypoints.background 不是安全的相对路径')
}
entrypoints.background = entryRaw.background
}
const subscriptions = parseSubscriptions(raw.subscriptions)
if (raw.subscriptions !== undefined && subscriptions === null) {
return fail('subscriptions 字段不合法(messageTypes 必须是已知消息类型)')
}
const contributionsRaw = raw.contributions
if (
contributionsRaw !== undefined &&
(typeof contributionsRaw !== 'object' || Array.isArray(contributionsRaw))
) {
return fail('contributions 必须是对象')
}
const contributionsObject = (contributionsRaw ?? {}) as Record<string, unknown>
const pages = parsePages(contributionsObject.pages)
if (pages === null) return fail('contributions.pages 不合法')
const automationActions = parseAutomationActions(contributionsObject.automationActions)
if (automationActions === null) return fail('contributions.automationActions 不合法')
if (pages.length > 0 && !entrypoints.page) {
return fail('注册了页面但缺少 entrypoints.page')
}
if ((subscriptions !== null || automationActions.length > 0) && !entrypoints.background) {
return fail('声明了消息订阅或自动化动作,必须提供 entrypoints.background')
}
if (!entrypoints.page && !entrypoints.background) {
return fail('至少需要 entrypoints.page 或 entrypoints.background')
}
if (permissions.includes('messages.subscribe') && !subscriptions) {
return fail('申请 messages.subscribe 时必须声明 subscriptions')
}
const description = asTrimmedString(raw.description, MAX_DESCRIPTION_LENGTH)
const author = asTrimmedString(raw.author, 80)
const homepage = asTrimmedString(raw.homepage, 200)
const minAppVersion = asTrimmedString(raw.minAppVersion, 20)
const manifest: ExtensionManifest = {
manifestVersion: EXTENSION_MANIFEST_VERSION,
id: raw.id.trim(),
name,
version: String(raw.version).trim(),
apiVersion: String(raw.apiVersion).trim(),
...(minAppVersion ? { minAppVersion } : {}),
...(description ? { description } : {}),
...(author ? { author } : {}),
...(homepage && /^https?:\/\//.test(homepage) ? { homepage } : {}),
permissions,
entrypoints,
...(subscriptions ? { subscriptions } : {}),
contributions: { pages, automationActions }
}
if (options.appVersion) {
const compatibility = checkExtensionCompatibility(manifest, options.appVersion)
if (!compatibility.compatible) {
return fail(compatibility.reason || '扩展与当前版本不兼容', 'EXTENSION_INCOMPATIBLE')
}
}
return { ok: true, manifest }
}
/** 解析 manifest JSON 文本。JSON 语法错误与 schema 错误分开报,便于作者定位。 */
export function parseExtensionManifestJson(
text: string,
options: { appVersion?: string } = {}
): ManifestParseResult {
let value: unknown
try {
value = JSON.parse(text)
} catch {
return fail('manifest.json 不是合法 JSON')
}
return parseExtensionManifest(value, options)
}
+127
View File
@@ -0,0 +1,127 @@
/**
* 扩展权限目录。
*
* 权限是**宿主授予**的,不是扩展自己声称的:manifest 里只声明「需要什么」,
* 真正生效的是 registry 里 `grantedPermissions` 与当前启用状态的交集。
*/
export const EXTENSION_PERMISSIONS = [
'messages.subscribe',
'messages.query',
'contacts.list',
'wechat.send.text',
'wechat.send.image',
'wechat.send.video',
'ai.chat',
'storage',
'automation.action'
] as const
export type ExtensionPermission = (typeof EXTENSION_PERMISSIONS)[number]
export type ExtensionPermissionRisk = 'low' | 'medium' | 'high'
export interface ExtensionPermissionInfo {
label: string
description: string
risk: ExtensionPermissionRisk
}
export const EXTENSION_PERMISSION_INFO: Record<ExtensionPermission, ExtensionPermissionInfo> = {
'messages.subscribe': {
label: '接收新消息事件',
description:
'在 TraceMemo 监听运行期间接收新消息的规范化字段(会话、发送者、消息类型、正文)。',
risk: 'high'
},
'messages.query': {
label: '读取指定会话消息',
description: '按会话与时间窗口读取有上限的历史消息,不能遍历全部会话。',
risk: 'high'
},
'contacts.list': {
label: '读取群列表',
description: '读取本机通讯录中的群名称与会话 id,用于配置页选择发送目标;不包含聊天内容。',
risk: 'medium'
},
'wechat.send.text': {
label: '发送微信文本',
description: '经 TraceMemo 官方 Gateway 发送文本;仍需有效授权、本机发送能力与发送频率限制。',
risk: 'high'
},
'wechat.send.image': {
label: '发送微信图片',
description:
'经 TraceMemo 官方 Gateway 发送图片;只能使用扩展数据目录或临时目录中的文件,仍需有效授权与发送能力。',
risk: 'high'
},
'wechat.send.video': {
label: '发送微信视频',
description:
'经 TraceMemo 官方 Gateway 发送视频文件;原生 Host 以 video 类型提交,单文件不超过 100MB,仍需有效授权与发送能力。',
risk: 'high'
},
'ai.chat': {
label: '调用 AI 模型',
description: '使用 TraceMemo 已配置的 AI Provider 发起对话;扩展拿不到 API Key 明文。',
risk: 'medium'
},
storage: {
label: '扩展私有存储',
description: '读写本扩展独立的数据目录,不会接触其他扩展或官方数据。',
risk: 'low'
},
'automation.action': {
label: '注册自动化动作',
description: '向 TraceMemo 自动化中心注册动作,由用户在规则里选择后才会执行。',
risk: 'medium'
}
}
export function isExtensionPermission(value: unknown): value is ExtensionPermission {
return typeof value === 'string' && (EXTENSION_PERMISSIONS as readonly string[]).includes(value)
}
/** 去重、去空白、丢弃未知值。**未知权限在 manifest 校验阶段就会被拒绝**,这里只做收敛。 */
export function normalizeExtensionPermissions(input: unknown): ExtensionPermission[] {
if (!Array.isArray(input)) return []
const result: ExtensionPermission[] = []
for (const value of input) {
if (!isExtensionPermission(value)) continue
if (result.includes(value)) continue
result.push(value)
}
return result
}
export function hasExtensionPermission(
granted: readonly ExtensionPermission[] | undefined,
permission: ExtensionPermission
): boolean {
return Array.isArray(granted) && granted.includes(permission)
}
/** 界面按风险从高到低展示;同风险保持目录顺序。 */
export function sortPermissionsByRisk(
permissions: readonly ExtensionPermission[]
): ExtensionPermission[] {
const weight: Record<ExtensionPermissionRisk, number> = { high: 0, medium: 1, low: 2 }
return [...permissions].sort((left, right) => {
const delta =
weight[EXTENSION_PERMISSION_INFO[left].risk] - weight[EXTENSION_PERMISSION_INFO[right].risk]
if (delta !== 0) return delta
return EXTENSION_PERMISSIONS.indexOf(left) - EXTENSION_PERMISSIONS.indexOf(right)
})
}
/**
* 安装时自动授予的权限子集:只有低风险项。
*
* 高 / 中风险权限必须由用户在「启用扩展」时确认 —— 安装本身不应等于同意
* 读取消息或发送微信。
*/
export function autoGrantedPermissions(
permissions: readonly ExtensionPermission[]
): ExtensionPermission[] {
return permissions.filter((permission) => EXTENSION_PERMISSION_INFO[permission].risk === 'low')
}
+219
View File
@@ -0,0 +1,219 @@
import type { ExtensionEventEnvelope } from './events'
import type { ExtensionErrorPayload } from './errors'
/**
* 主进程 ↔ 扩展后台进程的私有协议。
*
* 只有主进程能构造 `invoke-action` / `event` / `call-result`;
* 扩展进程只能发 `call` / `register-action` / `log` / `action-result`。
* 任何「宿主可信元数据」(extensionId、origin、purpose、幂等键)都**由主进程填**,
* 不接受扩展侧传入。
*/
export const EXTENSION_HOST_PROTOCOL_VERSION = 1
export type ExtensionHostCallMethod =
| 'storage.get'
| 'storage.set'
| 'storage.remove'
| 'storage.list'
| 'messages.query'
| 'wechat.send.text'
| 'wechat.send.image'
| 'wechat.send.video'
| 'ai.chat'
| 'capabilities.get'
export interface ExtensionHostReady {
type: 'ready'
version: number
}
export interface ExtensionHostActivate {
type: 'activate'
version: number
extensionId: string
extensionDir: string
/** 扩展私有数据目录(`extensions-data/<id>`);媒体文件应落在这里。 */
dataDir: string
apiVersion: string
permissions: string[]
}
export interface ExtensionHostActivated {
type: 'activated'
version: number
ok: boolean
error?: ExtensionErrorPayload
}
export interface ExtensionHostShutdown {
type: 'shutdown'
version: number
}
export interface ExtensionHostCall {
type: 'call'
version: number
callId: string
method: ExtensionHostCallMethod
params: Record<string, unknown>
}
export interface ExtensionHostCallResult {
type: 'call-result'
version: number
callId: string
ok: boolean
result?: unknown
error?: ExtensionErrorPayload
}
export interface ExtensionHostEvent {
type: 'event'
version: number
envelope: ExtensionEventEnvelope
}
export interface ExtensionHostRegisterAction {
type: 'register-action'
version: number
action: {
id: string
title: string
description?: string
hasInputSchema: boolean
}
}
export interface ExtensionHostInvokeAction {
type: 'invoke-action'
version: number
requestId: string
actionId: string
input: Record<string, unknown>
timeoutMs: number
}
export interface ExtensionHostActionResult {
type: 'action-result'
version: number
requestId: string
ok: boolean
output?: ExtensionAutomationActionOutput
error?: ExtensionErrorPayload
}
export interface ExtensionHostTestSend {
type: 'test-send'
version: number
requestId: string
params: Record<string, unknown>
}
export interface ExtensionHostTestResult {
type: 'test-result'
version: number
requestId: string
ok: boolean
result?: unknown
error?: ExtensionErrorPayload
}
export interface ExtensionHostLog {
type: 'log'
version: number
level: 'info' | 'warn' | 'error'
message: string
}
export type ExtensionHostOutboundMessage =
| ExtensionHostReady
| ExtensionHostActivated
| ExtensionHostCall
| ExtensionHostRegisterAction
| ExtensionHostLog
| ExtensionHostActionResult
| ExtensionHostTestResult
export type ExtensionHostInboundMessage =
| ExtensionHostActivate
| ExtensionHostShutdown
| ExtensionHostCallResult
| ExtensionHostEvent
| ExtensionHostInvokeAction
| ExtensionHostTestSend
| ExtensionHostTestResult
/**
* 自动化动作的返回值。
*
* `reply` 是扩展**声明想发什么**,不是发送指令:真正的发送由宿主在
* 权限、授权校验、发送能力全部通过后经 `WechatActionGateway` 完成。
*/
export interface ExtensionAutomationActionOutput {
success: boolean
output?: Record<string, unknown>
reply?: {
type: 'text'
text: string
/** 群聊里要 @ 的 wxid → 显示名;仅 `wechat.send.text` 被授予时生效。 */
at?: Record<string, string>
}
/** 失败原因(用户可见的短句)。 */
error?: string
}
export interface ExtensionMessagesQueryRequest {
conversationId: string
/** epoch **毫秒**。 */
startTime?: number
/** epoch **毫秒**。 */
endTime?: number
limit?: number
}
export interface ExtensionQueriedMessage {
messageId: string
conversationId: string
senderId?: string
senderName?: string
isSelf: boolean
type: string
text?: string
/** epoch 毫秒。 */
timestamp: number
}
export interface ExtensionSendTextRequest {
/** 群为 `xxx@chatroom`,私聊为 wxid。 */
to: string
text: string
at?: Record<string, string>
/** 扩展自定义去重键;相同键的重复请求会被 Gateway 审计短路。 */
dedupeKey?: string
}
/**
* 图片发送。
*
* 图片与视频是两条独立通道:视频必须显式用 `type: 'video'`,
* 由原生 Host 的 `/SendMsg` 以 video 类型提交。
*/
export interface ExtensionSendImageRequest {
to: string
/** 绝对路径;必须位于扩展数据目录或系统临时目录。 */
path: string
dedupeKey?: string
}
export interface ExtensionSendVideoRequest {
to: string
/** 绝对路径;必须位于扩展数据目录或系统临时目录。 */
path: string
dedupeKey?: string
}
export interface ExtensionSendTextResult {
actionId: string
status: 'sent'
}
+124
View File
@@ -0,0 +1,124 @@
import type { ExtensionCompatibility } from './manifest'
import type { ExtensionPermission } from './permissions'
import type { ExtensionErrorPayload } from './errors'
/** 扩展后台进程状态。`crashed` 表示连续崩溃后已停止自动重启,等用户手动处理。 */
export type ExtensionRuntimeState = 'inactive' | 'starting' | 'active' | 'error' | 'crashed'
export interface ExtensionRuntimeSnapshot {
state: ExtensionRuntimeState
since: number
restarts: number
/** 面向用户的一句话;**不含**路径、wxid、聊天正文。 */
lastError?: string
}
export interface ExtensionAutomationActionSummary {
/** 扩展内唯一 id(manifest 声明)。 */
id: string
title: string
description?: string
/** 宿主运行期是否真的注册成功(后台进程未启动时为 false)。 */
registered: boolean
}
export interface InstalledExtension {
id: string
name: string
version: string
apiVersion: string
minAppVersion?: string
description?: string
author?: string
enabled: boolean
installedAt: number
updatedAt: number
compatibility: ExtensionCompatibility
permissions: ExtensionPermission[]
grantedPermissions: ExtensionPermission[]
runtime: ExtensionRuntimeSnapshot
pages: Array<{ id: string; title: string }>
automationActions: ExtensionAutomationActionSummary[]
/** 扩展目录是否仍然存在;false 时 UI 必须显示为「文件缺失」而不是可启动。 */
filesPresent: boolean
}
export interface ExtensionLogEntry {
id: string
at: number
level: 'info' | 'warn' | 'error'
/** 来源:宿主自身事件,或扩展代码主动写入的日志。 */
source: 'core' | 'extension'
message: string
}
export interface ExtensionInstallResult {
success: boolean
extension?: InstalledExtension
error?: ExtensionErrorPayload
}
export interface ExtensionOperationResult {
success: boolean
error?: ExtensionErrorPayload
}
export interface ExtensionPageDescriptor {
extensionId: string
pageId: string
title: string
url: string
}
/** 渲染层可调用的页面侧能力白名单;扩展页面拿不到发送 / AI / 查询权限。 */
export type ExtensionPageMethod =
| 'storage.get'
| 'storage.set'
| 'storage.remove'
| 'storage.list'
| 'capabilities.get'
| 'contacts.listGroups'
| 'test.send'
| 'douyin.cookie.get'
| 'douyin.cookie.set'
| 'douyin.cookie.clear'
| 'extension.info'
export interface ExtensionPageRequest {
extensionId: string
method: ExtensionPageMethod
params?: Record<string, unknown>
}
export interface ExtensionPageResponse {
ok: boolean
result?: unknown
error?: ExtensionErrorPayload
}
export interface ExtensionCapabilitySnapshot {
extensionId: string
enabled: boolean
permissions: ExtensionPermission[]
platform: NodeJS.Platform
databaseReady: boolean
send: {
supported: boolean
ready: boolean
canSendText: boolean
/** 图片与视频是两条独立通道。 */
canSendImage: boolean
canSendVideo: boolean
/** 仅 `wechat.send.text` 被授予时才有意义。 */
licensed: boolean
message: string
}
ai: {
configured: boolean
modelName: string
}
}
export interface ExtensionQuitBehavior {
keepData: boolean
}
+16
View File
@@ -39,6 +39,8 @@ export interface PersonalWechatSenderStatus {
canSendText: boolean
canSendImage: boolean
canSendVoice: boolean
/** 视频与图片共用媒体通道;旧 runtime 不报告该字段。 */
canSendVideo?: boolean
message: string
error?: string
}
@@ -60,6 +62,8 @@ export interface PersonalWechatSendCapability {
text: boolean
image: boolean
voice: boolean
/** 图片/视频共用媒体通道;未报告的旧 runtime 视为 false。 */
video?: boolean
}
senderStatus: PersonalWechatSenderStatus
message: string
@@ -93,10 +97,22 @@ export interface PersonalWechatSendVoiceRequest extends PersonalWechatSendBaseRe
durationMs?: number
}
/**
* 视频发送。
*
* 原生 Host 走 `POST /SendMsg`,body 为 `{toWxid, type:'video', msg:<绝对路径>}`;
* `filePath` 必须是本机可访问的普通文件。
*/
export interface PersonalWechatSendVideoRequest extends PersonalWechatSendBaseRequest {
type: 'video'
filePath: string
}
export type PersonalWechatSendRequest =
| PersonalWechatSendTextRequest
| PersonalWechatSendImageRequest
| PersonalWechatSendVoiceRequest
| PersonalWechatSendVideoRequest
/** Renderer 请求发送刚刚生成的 TTS 语音;Action 元数据由主进程补齐。 */
export interface PersonalWechatGeneratedTtsVoiceRequest {
+3
View File
@@ -74,6 +74,7 @@ export interface WechatActionRecipient {
export type WechatActionContent =
| { type: 'text'; text: string; at?: Record<string, string> }
| { type: 'image'; path: string }
| { type: 'video'; path: string }
| { type: 'voice'; path: string }
export interface WechatActionRequest {
@@ -127,6 +128,8 @@ export interface PolicyDecision {
export interface WechatActionAuditRecord {
actionId: string
idempotencyKey?: string
/** 扩展来源时为扩展 id;其他来源省略。 */
extensionId?: string
origin: WechatActionOrigin
purpose: WechatActionPurpose
triggerType: WechatActionTriggerType