mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-12-01 01:05:30 +08:00
feat: 新增拓展中心功能, 提供 关键词回复 去水印模板
This commit is contained in:
1 parent
aca103cb96
commit
ebea992b10
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' }
|
||||
}
|
||||
@@ -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}`
|
||||
}
|
||||
@@ -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 } : {})
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 })
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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' }
|
||||
})
|
||||
}
|
||||
@@ -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'
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
@@ -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),
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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'
|
||||
|
||||
@@ -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,无法发送语音')
|
||||
|
||||
@@ -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[] {
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
Reference in new issue
Block a user