mirror of
https://wget.la/https://github.com/Wxw-Gu/WechatExplorer
synced 2026-11-30 16:02:58 +08:00
feat: 新增拓展中心功能, 提供 关键词回复 去水印模板
This commit is contained in:
1 parent
aca103cb96
commit
ebea992b10
85 files changed
+14750
-106
No files matched your search
+50
-12
@@ -6,10 +6,7 @@
|
||||
*/
|
||||
|
||||
import { normalizeGroupExitNotificationTemplate } from './group-exit-monitor'
|
||||
import {
|
||||
isSelectableReportTemplateId,
|
||||
type SelectableReportTemplateId
|
||||
} from './report-templates'
|
||||
import { isSelectableReportTemplateId, type SelectableReportTemplateId } from './report-templates'
|
||||
import type {
|
||||
ScheduledReportMemberNameMode,
|
||||
ScheduledReportMessageType,
|
||||
@@ -321,9 +318,7 @@ export function calculateNextRunAt(scheduleTime: string, from: Date = new Date()
|
||||
}
|
||||
|
||||
/** 收敛定时日报配置:未知值一律回落到安全默认,绝不落一条跑不起来的规则。 */
|
||||
export function normalizeScheduledReportConfig(
|
||||
input: unknown
|
||||
): ScheduledReportAutomationConfig {
|
||||
export function normalizeScheduledReportConfig(input: unknown): ScheduledReportAutomationConfig {
|
||||
const raw = (input ?? {}) as Partial<ScheduledReportAutomationConfig>
|
||||
const scheduleRaw = (raw.schedule ?? {}) as Partial<ScheduledReportAutomationConfig['schedule']>
|
||||
const reportRaw = (raw.report ?? {}) as Partial<ScheduledReportAutomationConfig['report']>
|
||||
@@ -421,13 +416,23 @@ export interface AutomationConditions {
|
||||
}
|
||||
|
||||
/** 执行动作类型。顺序由 `actions` 数组顺序决定。 */
|
||||
export type AutomationActionType = 'replyText' | 'generateReport' | 'sendReportImage'
|
||||
export type AutomationActionType =
|
||||
| 'replyText'
|
||||
| 'generateReport'
|
||||
| 'sendReportImage'
|
||||
| 'extensionAction'
|
||||
|
||||
export interface AutomationAction {
|
||||
type: AutomationActionType
|
||||
enabled: boolean
|
||||
/** `replyText` 的文案。 */
|
||||
text?: string
|
||||
/** `extensionAction`:提供动作的扩展 id。 */
|
||||
extensionId?: string
|
||||
/** `extensionAction`:扩展内注册的动作 id。 */
|
||||
actionId?: string
|
||||
/** `extensionAction`:用户配置的静态输入(JSON 对象)。 */
|
||||
input?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface AutomationRule {
|
||||
@@ -483,6 +488,7 @@ export type AutomationStepStatus = 'pending' | 'running' | 'success' | 'failed'
|
||||
export type AutomationStepKey =
|
||||
| 'received'
|
||||
| 'matched'
|
||||
| 'extension_action'
|
||||
| 'reply'
|
||||
| 'report'
|
||||
| 'send'
|
||||
@@ -771,6 +777,7 @@ export const LEAVE_NOTIFICATION_RULE_NAME = '退群通知'
|
||||
export const AUTOMATION_STEP_LABELS: Record<AutomationStepKey, string> = {
|
||||
received: '收到消息',
|
||||
matched: '规则匹配',
|
||||
extension_action: '执行扩展动作',
|
||||
reply: '回复确认',
|
||||
report: '生成日报',
|
||||
send: '发送日报图片',
|
||||
@@ -998,7 +1005,8 @@ export function describeRuleActions(rule: AutomationRule): string {
|
||||
const labels: Record<AutomationActionType, string> = {
|
||||
replyText: '回复确认',
|
||||
generateReport: '生成日报',
|
||||
sendReportImage: '发送图片'
|
||||
sendReportImage: '发送图片',
|
||||
extensionAction: '执行扩展动作'
|
||||
}
|
||||
const enabled = rule.actions.filter((action) => action.enabled)
|
||||
return enabled.length ? enabled.map((action) => labels[action.type]).join(' → ') : '无动作'
|
||||
@@ -1152,6 +1160,29 @@ export function createDefaultScheduledReportRule(
|
||||
}
|
||||
}
|
||||
|
||||
/** 扩展动作静态输入的体积上限(序列化后字符数)。 */
|
||||
export const EXTENSION_ACTION_INPUT_MAX_CHARS = 4_000
|
||||
|
||||
/**
|
||||
* 收敛扩展动作的静态输入。
|
||||
*
|
||||
* 只接受 JSON 对象:数组 / 字符串会让「输入」变成不可预期的形状,
|
||||
* 扩展作者无法在 `inputSchema` 里表达;超限直接丢弃而不是截断,
|
||||
* 截断后的 JSON 可能语义完全不同。
|
||||
*/
|
||||
export function normalizeExtensionActionInput(value: unknown): Record<string, unknown> | undefined {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined
|
||||
try {
|
||||
const text = JSON.stringify(value)
|
||||
if (!text || text.length > EXTENSION_ACTION_INPUT_MAX_CHARS) return undefined
|
||||
const parsed = JSON.parse(text) as unknown
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
|
||||
return parsed as Record<string, unknown>
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
/** 归一化用户提交的草稿:把未知值收敛成合法值,避免脏数据落盘。 */
|
||||
export function normalizeRuleDraft(
|
||||
input: unknown,
|
||||
@@ -1177,13 +1208,19 @@ export function normalizeRuleDraft(
|
||||
.map((action) => ({
|
||||
type: action.type,
|
||||
enabled: action.enabled !== false,
|
||||
...(typeof action.text === 'string' ? { text: action.text } : {})
|
||||
...(typeof action.text === 'string' ? { text: action.text } : {}),
|
||||
...(typeof action.extensionId === 'string' ? { extensionId: action.extensionId.trim() } : {}),
|
||||
...(typeof action.actionId === 'string' ? { actionId: action.actionId.trim() } : {}),
|
||||
...(normalizeExtensionActionInput(action.input)
|
||||
? { input: normalizeExtensionActionInput(action.input) }
|
||||
: {})
|
||||
}))
|
||||
.filter(
|
||||
(action) =>
|
||||
action.type === 'replyText' ||
|
||||
action.type === 'generateReport' ||
|
||||
action.type === 'sendReportImage'
|
||||
action.type === 'sendReportImage' ||
|
||||
(action.type === 'extensionAction' && Boolean(action.extensionId && action.actionId))
|
||||
)
|
||||
const cooldown = Number(raw.cooldownSeconds)
|
||||
const base = {
|
||||
@@ -1243,7 +1280,8 @@ export function normalizeLeaveNotificationConfig(input: unknown): LeaveNotificat
|
||||
...(effectiveType === 'contact' ? { contactId } : {})
|
||||
},
|
||||
template: normalizeLeaveNotificationTemplate(raw.template),
|
||||
notifyScope: raw.notifyScope === 'selected' ? 'selected' : LEAVE_NOTIFICATION_DEFAULT_NOTIFY_SCOPE,
|
||||
notifyScope:
|
||||
raw.notifyScope === 'selected' ? 'selected' : LEAVE_NOTIFICATION_DEFAULT_NOTIFY_SCOPE,
|
||||
notifyRoomIds: normalizeLeaveNotificationRoomIds(raw.notifyRoomIds),
|
||||
// 用户手动保存一次即视为已确认目标,清除迁移提示。
|
||||
...(raw.targetNeedsReview === true ? { targetNeedsReview: true } : {})
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* 扩展系统的稳定错误码。
|
||||
*
|
||||
* 调用方(UI / 扩展 SDK / 自动化 runner)只依赖这里的 `code`,
|
||||
* 不解析 `message` —— 文案会改,错误码不会。
|
||||
*/
|
||||
|
||||
export const EXTENSION_ERROR_CODES = [
|
||||
'EXTENSION_NOT_FOUND',
|
||||
'EXTENSION_DISABLED',
|
||||
'EXTENSION_INCOMPATIBLE',
|
||||
'EXTENSION_ALREADY_INSTALLED',
|
||||
'EXTENSION_INSTALL_FAILED',
|
||||
'EXTENSION_INVALID_MANIFEST',
|
||||
'EXTENSION_INVALID_PATH',
|
||||
'EXTENSION_HOST_UNAVAILABLE',
|
||||
'PERMISSION_DENIED',
|
||||
'CAPABILITY_UNAVAILABLE',
|
||||
'LICENSE_REQUIRED',
|
||||
'DATABASE_NOT_READY',
|
||||
'SEND_NOT_SUPPORTED',
|
||||
'ACTION_TIMEOUT',
|
||||
'ACTION_FAILED',
|
||||
'RATE_LIMITED',
|
||||
'INVALID_REQUEST',
|
||||
'STORAGE_LIMIT_EXCEEDED'
|
||||
] as const
|
||||
|
||||
export type ExtensionErrorCode = (typeof EXTENSION_ERROR_CODES)[number]
|
||||
|
||||
export const EXTENSION_ERROR_MESSAGES: Record<ExtensionErrorCode, string> = {
|
||||
EXTENSION_NOT_FOUND: '找不到该扩展',
|
||||
EXTENSION_DISABLED: '扩展当前未启用',
|
||||
EXTENSION_INCOMPATIBLE: '扩展与当前 TraceMemo 版本不兼容',
|
||||
EXTENSION_ALREADY_INSTALLED: '已安装同名扩展',
|
||||
EXTENSION_INSTALL_FAILED: '扩展安装失败',
|
||||
EXTENSION_INVALID_MANIFEST: '扩展 manifest 不合法',
|
||||
EXTENSION_INVALID_PATH: '扩展资源路径不合法',
|
||||
EXTENSION_HOST_UNAVAILABLE: '扩展后台进程不可用',
|
||||
PERMISSION_DENIED: '扩展没有该权限',
|
||||
CAPABILITY_UNAVAILABLE: '当前环境不具备该能力',
|
||||
LICENSE_REQUIRED: '需要有效授权',
|
||||
DATABASE_NOT_READY: '微信数据库尚未连接',
|
||||
SEND_NOT_SUPPORTED: '当前发送能力不支持该消息类型',
|
||||
ACTION_TIMEOUT: '扩展处理超时',
|
||||
ACTION_FAILED: '扩展执行失败',
|
||||
RATE_LIMITED: '触发频率限制,请稍后再试',
|
||||
INVALID_REQUEST: '请求格式不合法',
|
||||
STORAGE_LIMIT_EXCEEDED: '扩展存储已超出上限'
|
||||
}
|
||||
|
||||
export interface ExtensionErrorPayload {
|
||||
code: ExtensionErrorCode
|
||||
message: string
|
||||
/** 可选的机器可读细节;**不允许**放聊天正文、文件路径、wxid。 */
|
||||
detail?: string
|
||||
}
|
||||
|
||||
export class ExtensionError extends Error {
|
||||
readonly code: ExtensionErrorCode
|
||||
|
||||
constructor(code: ExtensionErrorCode, message?: string, options?: { cause?: unknown }) {
|
||||
super(message || EXTENSION_ERROR_MESSAGES[code], options)
|
||||
this.name = 'ExtensionError'
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
export function extensionError(code: ExtensionErrorCode, message?: string): ExtensionError {
|
||||
return new ExtensionError(code, message)
|
||||
}
|
||||
|
||||
export function isExtensionErrorCode(value: unknown): value is ExtensionErrorCode {
|
||||
return typeof value === 'string' && (EXTENSION_ERROR_CODES as readonly string[]).includes(value)
|
||||
}
|
||||
|
||||
/** 任意异常 → 可跨进程传输的错误载荷。未知异常一律落到 `ACTION_FAILED`。 */
|
||||
export function toExtensionErrorPayload(error: unknown): ExtensionErrorPayload {
|
||||
if (error instanceof ExtensionError) {
|
||||
return { code: error.code, message: error.message }
|
||||
}
|
||||
if (error && typeof error === 'object') {
|
||||
const candidate = error as { code?: unknown; message?: unknown }
|
||||
if (isExtensionErrorCode(candidate.code)) {
|
||||
return {
|
||||
code: candidate.code,
|
||||
message:
|
||||
typeof candidate.message === 'string'
|
||||
? candidate.message
|
||||
: EXTENSION_ERROR_MESSAGES[candidate.code]
|
||||
}
|
||||
}
|
||||
if (typeof candidate.message === 'string' && candidate.message.trim()) {
|
||||
return { code: 'ACTION_FAILED', message: candidate.message.trim() }
|
||||
}
|
||||
}
|
||||
return { code: 'ACTION_FAILED', message: EXTENSION_ERROR_MESSAGES.ACTION_FAILED }
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { ExtensionMessageType, ExtensionSubscriptions } from './manifest'
|
||||
|
||||
/**
|
||||
* 投递给扩展的规范化消息事件。
|
||||
*
|
||||
* **字段契约**
|
||||
* - `timestamp` 是 **epoch 毫秒**(MessageListener 内部是 epoch 秒,换算只在主进程做一次)。
|
||||
* - `eventId` 对同一条微信消息稳定:`message:<sha1(sessionId:localId)>`,
|
||||
* 扩展重启、后台补投都拿到同一个值,可直接用于幂等。
|
||||
* - `text` 只在可安全还原为纯文本时出现;图片 / 语音 / 视频等不带正文。
|
||||
*/
|
||||
export interface ExtensionMessageEvent {
|
||||
eventId: string
|
||||
accountId: string
|
||||
conversationId: string
|
||||
messageId: string
|
||||
senderId?: string
|
||||
senderName?: string
|
||||
isGroup: boolean
|
||||
isSelf: boolean
|
||||
type: ExtensionMessageType
|
||||
text?: string
|
||||
/** 真正 @ 到当前登录账号(来自 `atuserlist` ∩ 自身 username),不是正文里的 `@昵称`。 */
|
||||
mentionsMe: boolean
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
/** 事件协议版本。未来的持久化队列 / 可靠投递必须保持向后兼容。 */
|
||||
export const EXTENSION_EVENT_PROTOCOL_VERSION = 1
|
||||
|
||||
export interface ExtensionEventEnvelope {
|
||||
version: number
|
||||
kind: 'message.received'
|
||||
event: ExtensionMessageEvent
|
||||
}
|
||||
|
||||
/**
|
||||
* 微信 `local_type` / `messageType` → 扩展侧消息类型。
|
||||
*
|
||||
* 未列出的类型归到 `other`:扩展宁可收到一个明确的 `other`,
|
||||
* 也不要因为宿主新增类型而静默收不到事件。
|
||||
*/
|
||||
export function mapWechatMessageType(messageType: number): ExtensionMessageType {
|
||||
switch (Number(messageType)) {
|
||||
case 1:
|
||||
return 'text'
|
||||
case 3:
|
||||
return 'image'
|
||||
case 34:
|
||||
return 'voice'
|
||||
case 43:
|
||||
return 'video'
|
||||
case 47:
|
||||
return 'sticker'
|
||||
case 49:
|
||||
return 'link'
|
||||
case 10000:
|
||||
case 10002:
|
||||
return 'system'
|
||||
default:
|
||||
return 'other'
|
||||
}
|
||||
}
|
||||
|
||||
export interface BuildExtensionMessageEventInput {
|
||||
eventId: string
|
||||
accountId: string
|
||||
conversationId: string
|
||||
messageId: string
|
||||
senderId?: string
|
||||
senderName?: string
|
||||
isGroup: boolean
|
||||
isSelf: boolean
|
||||
messageType: number
|
||||
content?: string
|
||||
mentionsMe: boolean
|
||||
/** epoch 秒,与 MessageListener 同口径。 */
|
||||
createTimeSeconds: number
|
||||
}
|
||||
|
||||
export function buildExtensionMessageEvent(
|
||||
input: BuildExtensionMessageEventInput
|
||||
): ExtensionMessageEvent {
|
||||
const type = mapWechatMessageType(input.messageType)
|
||||
const text = type === 'text' ? String(input.content ?? '') : ''
|
||||
return {
|
||||
eventId: input.eventId,
|
||||
accountId: input.accountId,
|
||||
conversationId: input.conversationId,
|
||||
messageId: input.messageId,
|
||||
...(input.senderId ? { senderId: input.senderId } : {}),
|
||||
...(input.senderName ? { senderName: input.senderName } : {}),
|
||||
isGroup: input.isGroup,
|
||||
isSelf: input.isSelf,
|
||||
type,
|
||||
...(text ? { text } : {}),
|
||||
mentionsMe: input.mentionsMe,
|
||||
timestamp: Math.round(input.createTimeSeconds * 1000)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* manifest 级订阅过滤。
|
||||
*
|
||||
* 这一层只做「扩展作者声明过的粗筛」;用户级的开关是扩展的启用状态与权限授予,
|
||||
* 不在事件总线里再做第二套真相。
|
||||
*/
|
||||
export function shouldDeliverExtensionEvent(
|
||||
subscriptions: ExtensionSubscriptions | undefined,
|
||||
event: ExtensionMessageEvent
|
||||
): boolean {
|
||||
if (!subscriptions) return false
|
||||
if (!subscriptions.includeSelf && event.isSelf) return false
|
||||
if (subscriptions.requireMentionMe && !event.mentionsMe) return false
|
||||
if (!subscriptions.messageTypes.includes(event.type)) return false
|
||||
if (
|
||||
subscriptions.conversationIds.length > 0 &&
|
||||
!subscriptions.conversationIds.includes(event.conversationId)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import type { ExtensionErrorPayload } from './errors'
|
||||
|
||||
/** 扩展中心 IPC 通道。渲染层只依赖这些常量,不手写通道字符串。 */
|
||||
export const EXTENSION_IPC = {
|
||||
list: 'extension:list',
|
||||
detail: 'extension:get',
|
||||
installDirectory: 'extension:installDirectory',
|
||||
installPackage: 'extension:installPackage',
|
||||
pickDirectory: 'extension:pickDirectory',
|
||||
pickPackage: 'extension:pickPackage',
|
||||
setEnabled: 'extension:setEnabled',
|
||||
uninstall: 'extension:uninstall',
|
||||
logs: 'extension:getLogs',
|
||||
clearLogs: 'extension:clearLogs',
|
||||
pageUrl: 'extension:getPageUrl',
|
||||
pageRequest: 'extension:pageRequest',
|
||||
openDataDir: 'extension:openDataDir',
|
||||
changed: 'extension:changed'
|
||||
} as const
|
||||
|
||||
export type ExtensionChangeReason =
|
||||
| 'installed'
|
||||
| 'enabled'
|
||||
| 'disabled'
|
||||
| 'uninstalled'
|
||||
| 'runtime'
|
||||
| 'actions'
|
||||
|
||||
export interface ExtensionChangedEvent {
|
||||
extensionId: string
|
||||
reason: ExtensionChangeReason
|
||||
}
|
||||
|
||||
export const EXTENSION_PAGE_MESSAGE_SOURCE = 'tracememo-extension-page'
|
||||
export const EXTENSION_PAGE_HOST_SOURCE = 'tracememo-extension-host'
|
||||
|
||||
export interface ExtensionPageBridgeRequest {
|
||||
source: typeof EXTENSION_PAGE_MESSAGE_SOURCE
|
||||
extensionId: string
|
||||
requestId: string
|
||||
method: string
|
||||
params?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface ExtensionPageBridgeResponse {
|
||||
source: typeof EXTENSION_PAGE_HOST_SOURCE
|
||||
requestId: string
|
||||
ok: boolean
|
||||
result?: unknown
|
||||
error?: ExtensionErrorPayload
|
||||
}
|
||||
|
||||
export function isExtensionPageBridgeRequest(value: unknown): value is ExtensionPageBridgeRequest {
|
||||
if (!value || typeof value !== 'object') return false
|
||||
const candidate = value as Partial<ExtensionPageBridgeRequest>
|
||||
return (
|
||||
candidate.source === EXTENSION_PAGE_MESSAGE_SOURCE &&
|
||||
typeof candidate.extensionId === 'string' &&
|
||||
typeof candidate.requestId === 'string' &&
|
||||
typeof candidate.method === 'string'
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
import {
|
||||
EXTENSION_PERMISSIONS,
|
||||
normalizeExtensionPermissions,
|
||||
type ExtensionPermission
|
||||
} from './permissions'
|
||||
|
||||
/**
|
||||
* 扩展 manifest v1。
|
||||
*
|
||||
* 校验策略:**未知值一律拒绝而不是静默丢弃**。一个拼错的权限名如果被悄悄忽略,
|
||||
* 扩展会在运行期以 `PERMISSION_DENIED` 失败,而作者看到的是「manifest 合法」。
|
||||
*/
|
||||
|
||||
export const EXTENSION_MANIFEST_VERSION = 1
|
||||
/** 宿主实现的扩展 API 主版本。扩展的 `apiVersion` 主版本必须与它相同。 */
|
||||
export const EXTENSION_API_VERSION = '1'
|
||||
/** 低于该版本的 TraceMemo 不允许安装本 SDK 产出的扩展。 */
|
||||
export const EXTENSION_MIN_APP_VERSION = '2.6.0'
|
||||
|
||||
export type ExtensionMessageType =
|
||||
| 'text'
|
||||
| 'image'
|
||||
| 'voice'
|
||||
| 'video'
|
||||
| 'sticker'
|
||||
| 'file'
|
||||
| 'link'
|
||||
| 'system'
|
||||
| 'other'
|
||||
|
||||
export const EXTENSION_MESSAGE_TYPES: readonly ExtensionMessageType[] = [
|
||||
'text',
|
||||
'image',
|
||||
'voice',
|
||||
'video',
|
||||
'sticker',
|
||||
'file',
|
||||
'link',
|
||||
'system',
|
||||
'other'
|
||||
]
|
||||
|
||||
export interface ExtensionPageContribution {
|
||||
id: string
|
||||
title: string
|
||||
/** 相对扩展根目录的 HTML 路径;缺省用 `entrypoints.page`。 */
|
||||
entry?: string
|
||||
}
|
||||
|
||||
export interface ExtensionAutomationActionContribution {
|
||||
id: string
|
||||
title: string
|
||||
description?: string
|
||||
}
|
||||
|
||||
export interface ExtensionSubscriptions {
|
||||
messageTypes: ExtensionMessageType[]
|
||||
/** 空数组 = 不按会话过滤。非空时只投递这些会话。 */
|
||||
conversationIds: string[]
|
||||
requireMentionMe: boolean
|
||||
/** 默认 false:扩展默认收不到自己发出的消息。 */
|
||||
includeSelf: boolean
|
||||
}
|
||||
|
||||
export interface ExtensionManifest {
|
||||
manifestVersion: number
|
||||
id: string
|
||||
name: string
|
||||
version: string
|
||||
apiVersion: string
|
||||
minAppVersion?: string
|
||||
description?: string
|
||||
author?: string
|
||||
homepage?: string
|
||||
permissions: ExtensionPermission[]
|
||||
entrypoints: {
|
||||
page?: string
|
||||
background?: string
|
||||
}
|
||||
subscriptions?: ExtensionSubscriptions
|
||||
contributions: {
|
||||
pages: ExtensionPageContribution[]
|
||||
automationActions: ExtensionAutomationActionContribution[]
|
||||
}
|
||||
}
|
||||
|
||||
export interface ExtensionCompatibility {
|
||||
compatible: boolean
|
||||
code?: 'api_version' | 'app_version' | 'manifest'
|
||||
reason?: string
|
||||
}
|
||||
|
||||
export interface ManifestParseResult {
|
||||
ok: boolean
|
||||
manifest?: ExtensionManifest
|
||||
code?: 'EXTENSION_INVALID_MANIFEST' | 'EXTENSION_INCOMPATIBLE'
|
||||
message?: string
|
||||
}
|
||||
|
||||
const EXTENSION_ID_PATTERN =
|
||||
/^[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,38}[a-z0-9])?)+$/
|
||||
const RESERVED_ID_PREFIXES = ['com.tracememo.', 'tracememo.', 'tm.']
|
||||
const SEMVER_PATTERN = /^(\d{1,4})\.(\d{1,4})\.(\d{1,4})(?:-[0-9A-Za-z.-]{1,40})?$/
|
||||
const PAGE_ID_PATTERN = /^[a-z0-9][a-z0-9-]{0,31}$/
|
||||
const ACTION_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{1,63}$/
|
||||
const MAX_PAGES = 20
|
||||
const MAX_AUTOMATION_ACTIONS = 20
|
||||
const MAX_NAME_LENGTH = 64
|
||||
const MAX_DESCRIPTION_LENGTH = 500
|
||||
const MAX_CONVERSATION_SCOPE = 200
|
||||
|
||||
export function isValidExtensionId(value: unknown): value is string {
|
||||
if (typeof value !== 'string') return false
|
||||
const id = value.trim()
|
||||
if (id.length < 3 || id.length > 128) return false
|
||||
if (!EXTENSION_ID_PATTERN.test(id)) return false
|
||||
return !RESERVED_ID_PREFIXES.some((prefix) => id.startsWith(prefix))
|
||||
}
|
||||
|
||||
export function isValidExtensionVersion(value: unknown): value is string {
|
||||
return typeof value === 'string' && SEMVER_PATTERN.test(value.trim())
|
||||
}
|
||||
|
||||
/**
|
||||
* 纯数字比较,忽略 prerelease。
|
||||
*
|
||||
* `minAppVersion` 的语义是「最低可运行版本」,把 `2.6.0-beta.1` 判成低于 `2.6.0`
|
||||
* 会让预发布构建无法安装明示支持的扩展;宁可放行,也不误伤。
|
||||
*/
|
||||
export function compareSemver(left: string, right: string): number | null {
|
||||
const a = SEMVER_PATTERN.exec(String(left || '').trim())
|
||||
const b = SEMVER_PATTERN.exec(String(right || '').trim())
|
||||
if (!a || !b) return null
|
||||
for (let index = 1; index <= 3; index += 1) {
|
||||
const delta = Number(a[index]) - Number(b[index])
|
||||
if (delta !== 0) return delta > 0 ? 1 : -1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
export function isApiVersionCompatible(
|
||||
apiVersion: unknown,
|
||||
hostApiVersion = EXTENSION_API_VERSION
|
||||
): boolean {
|
||||
const declared = String(apiVersion ?? '').trim()
|
||||
if (!/^\d+$/.test(declared)) return false
|
||||
return declared === String(hostApiVersion).trim()
|
||||
}
|
||||
|
||||
export function checkExtensionCompatibility(
|
||||
input: { apiVersion?: unknown; minAppVersion?: unknown },
|
||||
appVersion: string
|
||||
): ExtensionCompatibility {
|
||||
if (!isApiVersionCompatible(input.apiVersion)) {
|
||||
return {
|
||||
compatible: false,
|
||||
code: 'api_version',
|
||||
reason: `扩展 API 版本 ${String(input.apiVersion ?? '')} 与当前 TraceMemo 不兼容`
|
||||
}
|
||||
}
|
||||
const minAppVersion = String(input.minAppVersion ?? '').trim()
|
||||
if (!minAppVersion) return { compatible: true }
|
||||
if (!isValidExtensionVersion(minAppVersion)) {
|
||||
return { compatible: false, code: 'manifest', reason: 'minAppVersion 不是合法版本号' }
|
||||
}
|
||||
const compared = compareSemver(appVersion, minAppVersion)
|
||||
if (compared === null) return { compatible: true }
|
||||
if (compared < 0) {
|
||||
return {
|
||||
compatible: false,
|
||||
code: 'app_version',
|
||||
reason: `需要 TraceMemo ${minAppVersion} 或更高版本(当前 ${appVersion})`
|
||||
}
|
||||
}
|
||||
return { compatible: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* 相对路径安全检查(纯字符串层)。
|
||||
*
|
||||
* 只做语法判断;**真实路径是否仍在扩展目录内必须由主进程用 realpath 再验一次** ——
|
||||
* 符号链接可以绕过任何纯字符串检查。
|
||||
*/
|
||||
export function isSafeRelativeEntryPath(value: unknown): value is string {
|
||||
if (typeof value !== 'string') return false
|
||||
const raw = value.trim().replace(/\\/g, '/')
|
||||
if (!raw || raw.length > 240) return false
|
||||
if (raw.includes('\0')) return false
|
||||
if (raw.startsWith('/') || raw.startsWith('//')) return false
|
||||
if (/^[A-Za-z]:/.test(raw)) return false
|
||||
const segments = raw.split('/')
|
||||
if (segments.length > 10) return false
|
||||
for (const segment of segments) {
|
||||
if (!segment || segment === '.' || segment === '..') return false
|
||||
if (segment.length > 64) return false
|
||||
if (!/^[A-Za-z0-9._@+\- ]+$/.test(segment)) return false
|
||||
if (/[. ]$/.test(segment)) return false
|
||||
// Windows 对 `con.txt` 与 `con` 一视同仁,保留名按「点前的主干」判断。
|
||||
if (/^(con|prn|aux|nul|com\d|lpt\d)(\.|$)/i.test(segment)) return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
function asTrimmedString(value: unknown, maxLength: number): string {
|
||||
if (typeof value !== 'string') return ''
|
||||
return value.trim().slice(0, maxLength)
|
||||
}
|
||||
|
||||
function parseMessageTypes(input: unknown): ExtensionMessageType[] {
|
||||
if (!Array.isArray(input)) return ['text']
|
||||
const result: ExtensionMessageType[] = []
|
||||
for (const value of input) {
|
||||
if (typeof value !== 'string') return []
|
||||
if (!EXTENSION_MESSAGE_TYPES.includes(value as ExtensionMessageType)) return []
|
||||
const typed = value as ExtensionMessageType
|
||||
if (!result.includes(typed)) result.push(typed)
|
||||
}
|
||||
return result.length ? result : ['text']
|
||||
}
|
||||
|
||||
function parseSubscriptions(input: unknown): ExtensionSubscriptions | null {
|
||||
if (input === undefined) return null
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) return null
|
||||
const raw = input as Record<string, unknown>
|
||||
const messageTypes = parseMessageTypes(raw.messageTypes)
|
||||
if (!messageTypes.length) return null
|
||||
const conversationIds: string[] = []
|
||||
if (raw.conversationIds !== undefined) {
|
||||
if (!Array.isArray(raw.conversationIds)) return null
|
||||
if (raw.conversationIds.length > MAX_CONVERSATION_SCOPE) return null
|
||||
for (const value of raw.conversationIds) {
|
||||
if (typeof value !== 'string') return null
|
||||
const id = value.trim()
|
||||
if (!id || id.length > 128) return null
|
||||
if (!conversationIds.includes(id)) conversationIds.push(id)
|
||||
}
|
||||
}
|
||||
return {
|
||||
messageTypes,
|
||||
conversationIds,
|
||||
requireMentionMe: raw.requireMentionMe === true,
|
||||
includeSelf: raw.includeSelf === true
|
||||
}
|
||||
}
|
||||
|
||||
function parsePages(input: unknown): ExtensionPageContribution[] | null {
|
||||
if (input === undefined) return []
|
||||
if (!Array.isArray(input) || input.length > MAX_PAGES) return null
|
||||
const pages: ExtensionPageContribution[] = []
|
||||
for (const value of input) {
|
||||
if (!value || typeof value !== 'object') return null
|
||||
const raw = value as Record<string, unknown>
|
||||
const id = asTrimmedString(raw.id, 32)
|
||||
const title = asTrimmedString(raw.title, 40)
|
||||
if (!PAGE_ID_PATTERN.test(id) || !title) return null
|
||||
if (pages.some((page) => page.id === id)) return null
|
||||
if (raw.entry !== undefined) {
|
||||
if (!isSafeRelativeEntryPath(raw.entry)) return null
|
||||
pages.push({ id, title, entry: raw.entry })
|
||||
} else {
|
||||
pages.push({ id, title })
|
||||
}
|
||||
}
|
||||
return pages
|
||||
}
|
||||
|
||||
function parseAutomationActions(input: unknown): ExtensionAutomationActionContribution[] | null {
|
||||
if (input === undefined) return []
|
||||
if (!Array.isArray(input) || input.length > MAX_AUTOMATION_ACTIONS) return null
|
||||
const actions: ExtensionAutomationActionContribution[] = []
|
||||
for (const value of input) {
|
||||
if (!value || typeof value !== 'object') return null
|
||||
const raw = value as Record<string, unknown>
|
||||
const id = asTrimmedString(raw.id, 64)
|
||||
const title = asTrimmedString(raw.title, 60)
|
||||
if (!ACTION_ID_PATTERN.test(id) || !title) return null
|
||||
if (actions.some((action) => action.id === id)) return null
|
||||
const description = asTrimmedString(raw.description, 200)
|
||||
actions.push({ id, title, ...(description ? { description } : {}) })
|
||||
}
|
||||
return actions
|
||||
}
|
||||
|
||||
function fail(
|
||||
message: string,
|
||||
code: ManifestParseResult['code'] = 'EXTENSION_INVALID_MANIFEST'
|
||||
): ManifestParseResult {
|
||||
return { ok: false, code, message }
|
||||
}
|
||||
|
||||
/** 解析并收敛 manifest。失败时返回**具体**原因,供安装界面直接展示。 */
|
||||
export function parseExtensionManifest(
|
||||
input: unknown,
|
||||
options: { appVersion?: string } = {}
|
||||
): ManifestParseResult {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) {
|
||||
return fail('manifest 必须是 JSON 对象')
|
||||
}
|
||||
const raw = input as Record<string, unknown>
|
||||
|
||||
if (Number(raw.manifestVersion) !== EXTENSION_MANIFEST_VERSION) {
|
||||
return fail(`manifestVersion 必须是 ${EXTENSION_MANIFEST_VERSION}`)
|
||||
}
|
||||
if (!isValidExtensionId(raw.id)) {
|
||||
return fail('id 必须是反向域名形式(如 com.example.hello),且不能使用 TraceMemo 保留前缀')
|
||||
}
|
||||
const name = asTrimmedString(raw.name, MAX_NAME_LENGTH)
|
||||
if (!name) return fail('name 不能为空')
|
||||
if (!isValidExtensionVersion(raw.version)) return fail('version 必须是 x.y.z 形式')
|
||||
if (!isApiVersionCompatible(raw.apiVersion)) {
|
||||
return fail('apiVersion 与当前 TraceMemo 扩展 API 不兼容', 'EXTENSION_INCOMPATIBLE')
|
||||
}
|
||||
if (raw.minAppVersion !== undefined && !isValidExtensionVersion(raw.minAppVersion)) {
|
||||
return fail('minAppVersion 必须是 x.y.z 形式')
|
||||
}
|
||||
|
||||
if (!Array.isArray(raw.permissions)) return fail('permissions 必须是数组')
|
||||
for (const permission of raw.permissions) {
|
||||
if (
|
||||
typeof permission !== 'string' ||
|
||||
!(EXTENSION_PERMISSIONS as readonly string[]).includes(permission)
|
||||
) {
|
||||
return fail(`未知权限:${String(permission)}`)
|
||||
}
|
||||
}
|
||||
const permissions = normalizeExtensionPermissions(raw.permissions)
|
||||
|
||||
const entrypointsRaw = raw.entrypoints
|
||||
if (!entrypointsRaw || typeof entrypointsRaw !== 'object' || Array.isArray(entrypointsRaw)) {
|
||||
return fail('entrypoints 必须是对象')
|
||||
}
|
||||
const entryRaw = entrypointsRaw as Record<string, unknown>
|
||||
const entrypoints: ExtensionManifest['entrypoints'] = {}
|
||||
if (entryRaw.page !== undefined) {
|
||||
if (!isSafeRelativeEntryPath(entryRaw.page)) return fail('entrypoints.page 不是安全的相对路径')
|
||||
entrypoints.page = entryRaw.page
|
||||
}
|
||||
if (entryRaw.background !== undefined) {
|
||||
if (!isSafeRelativeEntryPath(entryRaw.background)) {
|
||||
return fail('entrypoints.background 不是安全的相对路径')
|
||||
}
|
||||
entrypoints.background = entryRaw.background
|
||||
}
|
||||
|
||||
const subscriptions = parseSubscriptions(raw.subscriptions)
|
||||
if (raw.subscriptions !== undefined && subscriptions === null) {
|
||||
return fail('subscriptions 字段不合法(messageTypes 必须是已知消息类型)')
|
||||
}
|
||||
|
||||
const contributionsRaw = raw.contributions
|
||||
if (
|
||||
contributionsRaw !== undefined &&
|
||||
(typeof contributionsRaw !== 'object' || Array.isArray(contributionsRaw))
|
||||
) {
|
||||
return fail('contributions 必须是对象')
|
||||
}
|
||||
const contributionsObject = (contributionsRaw ?? {}) as Record<string, unknown>
|
||||
const pages = parsePages(contributionsObject.pages)
|
||||
if (pages === null) return fail('contributions.pages 不合法')
|
||||
const automationActions = parseAutomationActions(contributionsObject.automationActions)
|
||||
if (automationActions === null) return fail('contributions.automationActions 不合法')
|
||||
|
||||
if (pages.length > 0 && !entrypoints.page) {
|
||||
return fail('注册了页面但缺少 entrypoints.page')
|
||||
}
|
||||
if ((subscriptions !== null || automationActions.length > 0) && !entrypoints.background) {
|
||||
return fail('声明了消息订阅或自动化动作,必须提供 entrypoints.background')
|
||||
}
|
||||
if (!entrypoints.page && !entrypoints.background) {
|
||||
return fail('至少需要 entrypoints.page 或 entrypoints.background')
|
||||
}
|
||||
if (permissions.includes('messages.subscribe') && !subscriptions) {
|
||||
return fail('申请 messages.subscribe 时必须声明 subscriptions')
|
||||
}
|
||||
|
||||
const description = asTrimmedString(raw.description, MAX_DESCRIPTION_LENGTH)
|
||||
const author = asTrimmedString(raw.author, 80)
|
||||
const homepage = asTrimmedString(raw.homepage, 200)
|
||||
const minAppVersion = asTrimmedString(raw.minAppVersion, 20)
|
||||
|
||||
const manifest: ExtensionManifest = {
|
||||
manifestVersion: EXTENSION_MANIFEST_VERSION,
|
||||
id: raw.id.trim(),
|
||||
name,
|
||||
version: String(raw.version).trim(),
|
||||
apiVersion: String(raw.apiVersion).trim(),
|
||||
...(minAppVersion ? { minAppVersion } : {}),
|
||||
...(description ? { description } : {}),
|
||||
...(author ? { author } : {}),
|
||||
...(homepage && /^https?:\/\//.test(homepage) ? { homepage } : {}),
|
||||
permissions,
|
||||
entrypoints,
|
||||
...(subscriptions ? { subscriptions } : {}),
|
||||
contributions: { pages, automationActions }
|
||||
}
|
||||
|
||||
if (options.appVersion) {
|
||||
const compatibility = checkExtensionCompatibility(manifest, options.appVersion)
|
||||
if (!compatibility.compatible) {
|
||||
return fail(compatibility.reason || '扩展与当前版本不兼容', 'EXTENSION_INCOMPATIBLE')
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true, manifest }
|
||||
}
|
||||
|
||||
/** 解析 manifest JSON 文本。JSON 语法错误与 schema 错误分开报,便于作者定位。 */
|
||||
export function parseExtensionManifestJson(
|
||||
text: string,
|
||||
options: { appVersion?: string } = {}
|
||||
): ManifestParseResult {
|
||||
let value: unknown
|
||||
try {
|
||||
value = JSON.parse(text)
|
||||
} catch {
|
||||
return fail('manifest.json 不是合法 JSON')
|
||||
}
|
||||
return parseExtensionManifest(value, options)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
/**
|
||||
* 扩展权限目录。
|
||||
*
|
||||
* 权限是**宿主授予**的,不是扩展自己声称的:manifest 里只声明「需要什么」,
|
||||
* 真正生效的是 registry 里 `grantedPermissions` 与当前启用状态的交集。
|
||||
*/
|
||||
|
||||
export const EXTENSION_PERMISSIONS = [
|
||||
'messages.subscribe',
|
||||
'messages.query',
|
||||
'contacts.list',
|
||||
'wechat.send.text',
|
||||
'wechat.send.image',
|
||||
'wechat.send.video',
|
||||
'ai.chat',
|
||||
'storage',
|
||||
'automation.action'
|
||||
] as const
|
||||
|
||||
export type ExtensionPermission = (typeof EXTENSION_PERMISSIONS)[number]
|
||||
|
||||
export type ExtensionPermissionRisk = 'low' | 'medium' | 'high'
|
||||
|
||||
export interface ExtensionPermissionInfo {
|
||||
label: string
|
||||
description: string
|
||||
risk: ExtensionPermissionRisk
|
||||
}
|
||||
|
||||
export const EXTENSION_PERMISSION_INFO: Record<ExtensionPermission, ExtensionPermissionInfo> = {
|
||||
'messages.subscribe': {
|
||||
label: '接收新消息事件',
|
||||
description:
|
||||
'在 TraceMemo 监听运行期间接收新消息的规范化字段(会话、发送者、消息类型、正文)。',
|
||||
risk: 'high'
|
||||
},
|
||||
'messages.query': {
|
||||
label: '读取指定会话消息',
|
||||
description: '按会话与时间窗口读取有上限的历史消息,不能遍历全部会话。',
|
||||
risk: 'high'
|
||||
},
|
||||
'contacts.list': {
|
||||
label: '读取群列表',
|
||||
description: '读取本机通讯录中的群名称与会话 id,用于配置页选择发送目标;不包含聊天内容。',
|
||||
risk: 'medium'
|
||||
},
|
||||
'wechat.send.text': {
|
||||
label: '发送微信文本',
|
||||
description: '经 TraceMemo 官方 Gateway 发送文本;仍需有效授权、本机发送能力与发送频率限制。',
|
||||
risk: 'high'
|
||||
},
|
||||
'wechat.send.image': {
|
||||
label: '发送微信图片',
|
||||
description:
|
||||
'经 TraceMemo 官方 Gateway 发送图片;只能使用扩展数据目录或临时目录中的文件,仍需有效授权与发送能力。',
|
||||
risk: 'high'
|
||||
},
|
||||
'wechat.send.video': {
|
||||
label: '发送微信视频',
|
||||
description:
|
||||
'经 TraceMemo 官方 Gateway 发送视频文件;原生 Host 以 video 类型提交,单文件不超过 100MB,仍需有效授权与发送能力。',
|
||||
risk: 'high'
|
||||
},
|
||||
'ai.chat': {
|
||||
label: '调用 AI 模型',
|
||||
description: '使用 TraceMemo 已配置的 AI Provider 发起对话;扩展拿不到 API Key 明文。',
|
||||
risk: 'medium'
|
||||
},
|
||||
storage: {
|
||||
label: '扩展私有存储',
|
||||
description: '读写本扩展独立的数据目录,不会接触其他扩展或官方数据。',
|
||||
risk: 'low'
|
||||
},
|
||||
'automation.action': {
|
||||
label: '注册自动化动作',
|
||||
description: '向 TraceMemo 自动化中心注册动作,由用户在规则里选择后才会执行。',
|
||||
risk: 'medium'
|
||||
}
|
||||
}
|
||||
|
||||
export function isExtensionPermission(value: unknown): value is ExtensionPermission {
|
||||
return typeof value === 'string' && (EXTENSION_PERMISSIONS as readonly string[]).includes(value)
|
||||
}
|
||||
|
||||
/** 去重、去空白、丢弃未知值。**未知权限在 manifest 校验阶段就会被拒绝**,这里只做收敛。 */
|
||||
export function normalizeExtensionPermissions(input: unknown): ExtensionPermission[] {
|
||||
if (!Array.isArray(input)) return []
|
||||
const result: ExtensionPermission[] = []
|
||||
for (const value of input) {
|
||||
if (!isExtensionPermission(value)) continue
|
||||
if (result.includes(value)) continue
|
||||
result.push(value)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export function hasExtensionPermission(
|
||||
granted: readonly ExtensionPermission[] | undefined,
|
||||
permission: ExtensionPermission
|
||||
): boolean {
|
||||
return Array.isArray(granted) && granted.includes(permission)
|
||||
}
|
||||
|
||||
/** 界面按风险从高到低展示;同风险保持目录顺序。 */
|
||||
export function sortPermissionsByRisk(
|
||||
permissions: readonly ExtensionPermission[]
|
||||
): ExtensionPermission[] {
|
||||
const weight: Record<ExtensionPermissionRisk, number> = { high: 0, medium: 1, low: 2 }
|
||||
return [...permissions].sort((left, right) => {
|
||||
const delta =
|
||||
weight[EXTENSION_PERMISSION_INFO[left].risk] - weight[EXTENSION_PERMISSION_INFO[right].risk]
|
||||
if (delta !== 0) return delta
|
||||
return EXTENSION_PERMISSIONS.indexOf(left) - EXTENSION_PERMISSIONS.indexOf(right)
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 安装时自动授予的权限子集:只有低风险项。
|
||||
*
|
||||
* 高 / 中风险权限必须由用户在「启用扩展」时确认 —— 安装本身不应等于同意
|
||||
* 读取消息或发送微信。
|
||||
*/
|
||||
export function autoGrantedPermissions(
|
||||
permissions: readonly ExtensionPermission[]
|
||||
): ExtensionPermission[] {
|
||||
return permissions.filter((permission) => EXTENSION_PERMISSION_INFO[permission].risk === 'low')
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
import type { ExtensionEventEnvelope } from './events'
|
||||
import type { ExtensionErrorPayload } from './errors'
|
||||
|
||||
/**
|
||||
* 主进程 ↔ 扩展后台进程的私有协议。
|
||||
*
|
||||
* 只有主进程能构造 `invoke-action` / `event` / `call-result`;
|
||||
* 扩展进程只能发 `call` / `register-action` / `log` / `action-result`。
|
||||
* 任何「宿主可信元数据」(extensionId、origin、purpose、幂等键)都**由主进程填**,
|
||||
* 不接受扩展侧传入。
|
||||
*/
|
||||
export const EXTENSION_HOST_PROTOCOL_VERSION = 1
|
||||
|
||||
export type ExtensionHostCallMethod =
|
||||
| 'storage.get'
|
||||
| 'storage.set'
|
||||
| 'storage.remove'
|
||||
| 'storage.list'
|
||||
| 'messages.query'
|
||||
| 'wechat.send.text'
|
||||
| 'wechat.send.image'
|
||||
| 'wechat.send.video'
|
||||
| 'ai.chat'
|
||||
| 'capabilities.get'
|
||||
|
||||
export interface ExtensionHostReady {
|
||||
type: 'ready'
|
||||
version: number
|
||||
}
|
||||
|
||||
export interface ExtensionHostActivate {
|
||||
type: 'activate'
|
||||
version: number
|
||||
extensionId: string
|
||||
extensionDir: string
|
||||
/** 扩展私有数据目录(`extensions-data/<id>`);媒体文件应落在这里。 */
|
||||
dataDir: string
|
||||
apiVersion: string
|
||||
permissions: string[]
|
||||
}
|
||||
|
||||
export interface ExtensionHostActivated {
|
||||
type: 'activated'
|
||||
version: number
|
||||
ok: boolean
|
||||
error?: ExtensionErrorPayload
|
||||
}
|
||||
|
||||
export interface ExtensionHostShutdown {
|
||||
type: 'shutdown'
|
||||
version: number
|
||||
}
|
||||
|
||||
export interface ExtensionHostCall {
|
||||
type: 'call'
|
||||
version: number
|
||||
callId: string
|
||||
method: ExtensionHostCallMethod
|
||||
params: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface ExtensionHostCallResult {
|
||||
type: 'call-result'
|
||||
version: number
|
||||
callId: string
|
||||
ok: boolean
|
||||
result?: unknown
|
||||
error?: ExtensionErrorPayload
|
||||
}
|
||||
|
||||
export interface ExtensionHostEvent {
|
||||
type: 'event'
|
||||
version: number
|
||||
envelope: ExtensionEventEnvelope
|
||||
}
|
||||
|
||||
export interface ExtensionHostRegisterAction {
|
||||
type: 'register-action'
|
||||
version: number
|
||||
action: {
|
||||
id: string
|
||||
title: string
|
||||
description?: string
|
||||
hasInputSchema: boolean
|
||||
}
|
||||
}
|
||||
|
||||
export interface ExtensionHostInvokeAction {
|
||||
type: 'invoke-action'
|
||||
version: number
|
||||
requestId: string
|
||||
actionId: string
|
||||
input: Record<string, unknown>
|
||||
timeoutMs: number
|
||||
}
|
||||
|
||||
export interface ExtensionHostActionResult {
|
||||
type: 'action-result'
|
||||
version: number
|
||||
requestId: string
|
||||
ok: boolean
|
||||
output?: ExtensionAutomationActionOutput
|
||||
error?: ExtensionErrorPayload
|
||||
}
|
||||
|
||||
export interface ExtensionHostTestSend {
|
||||
type: 'test-send'
|
||||
version: number
|
||||
requestId: string
|
||||
params: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface ExtensionHostTestResult {
|
||||
type: 'test-result'
|
||||
version: number
|
||||
requestId: string
|
||||
ok: boolean
|
||||
result?: unknown
|
||||
error?: ExtensionErrorPayload
|
||||
}
|
||||
|
||||
export interface ExtensionHostLog {
|
||||
type: 'log'
|
||||
version: number
|
||||
level: 'info' | 'warn' | 'error'
|
||||
message: string
|
||||
}
|
||||
|
||||
export type ExtensionHostOutboundMessage =
|
||||
| ExtensionHostReady
|
||||
| ExtensionHostActivated
|
||||
| ExtensionHostCall
|
||||
| ExtensionHostRegisterAction
|
||||
| ExtensionHostLog
|
||||
| ExtensionHostActionResult
|
||||
| ExtensionHostTestResult
|
||||
|
||||
export type ExtensionHostInboundMessage =
|
||||
| ExtensionHostActivate
|
||||
| ExtensionHostShutdown
|
||||
| ExtensionHostCallResult
|
||||
| ExtensionHostEvent
|
||||
| ExtensionHostInvokeAction
|
||||
| ExtensionHostTestSend
|
||||
| ExtensionHostTestResult
|
||||
|
||||
/**
|
||||
* 自动化动作的返回值。
|
||||
*
|
||||
* `reply` 是扩展**声明想发什么**,不是发送指令:真正的发送由宿主在
|
||||
* 权限、授权校验、发送能力全部通过后经 `WechatActionGateway` 完成。
|
||||
*/
|
||||
export interface ExtensionAutomationActionOutput {
|
||||
success: boolean
|
||||
output?: Record<string, unknown>
|
||||
reply?: {
|
||||
type: 'text'
|
||||
text: string
|
||||
/** 群聊里要 @ 的 wxid → 显示名;仅 `wechat.send.text` 被授予时生效。 */
|
||||
at?: Record<string, string>
|
||||
}
|
||||
/** 失败原因(用户可见的短句)。 */
|
||||
error?: string
|
||||
}
|
||||
|
||||
export interface ExtensionMessagesQueryRequest {
|
||||
conversationId: string
|
||||
/** epoch **毫秒**。 */
|
||||
startTime?: number
|
||||
/** epoch **毫秒**。 */
|
||||
endTime?: number
|
||||
limit?: number
|
||||
}
|
||||
|
||||
export interface ExtensionQueriedMessage {
|
||||
messageId: string
|
||||
conversationId: string
|
||||
senderId?: string
|
||||
senderName?: string
|
||||
isSelf: boolean
|
||||
type: string
|
||||
text?: string
|
||||
/** epoch 毫秒。 */
|
||||
timestamp: number
|
||||
}
|
||||
|
||||
export interface ExtensionSendTextRequest {
|
||||
/** 群为 `xxx@chatroom`,私聊为 wxid。 */
|
||||
to: string
|
||||
text: string
|
||||
at?: Record<string, string>
|
||||
/** 扩展自定义去重键;相同键的重复请求会被 Gateway 审计短路。 */
|
||||
dedupeKey?: string
|
||||
}
|
||||
|
||||
/**
|
||||
* 图片发送。
|
||||
*
|
||||
* 图片与视频是两条独立通道:视频必须显式用 `type: 'video'`,
|
||||
* 由原生 Host 的 `/SendMsg` 以 video 类型提交。
|
||||
*/
|
||||
export interface ExtensionSendImageRequest {
|
||||
to: string
|
||||
/** 绝对路径;必须位于扩展数据目录或系统临时目录。 */
|
||||
path: string
|
||||
dedupeKey?: string
|
||||
}
|
||||
|
||||
export interface ExtensionSendVideoRequest {
|
||||
to: string
|
||||
/** 绝对路径;必须位于扩展数据目录或系统临时目录。 */
|
||||
path: string
|
||||
dedupeKey?: string
|
||||
}
|
||||
|
||||
export interface ExtensionSendTextResult {
|
||||
actionId: string
|
||||
status: 'sent'
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { ExtensionCompatibility } from './manifest'
|
||||
import type { ExtensionPermission } from './permissions'
|
||||
import type { ExtensionErrorPayload } from './errors'
|
||||
|
||||
/** 扩展后台进程状态。`crashed` 表示连续崩溃后已停止自动重启,等用户手动处理。 */
|
||||
export type ExtensionRuntimeState = 'inactive' | 'starting' | 'active' | 'error' | 'crashed'
|
||||
|
||||
export interface ExtensionRuntimeSnapshot {
|
||||
state: ExtensionRuntimeState
|
||||
since: number
|
||||
restarts: number
|
||||
/** 面向用户的一句话;**不含**路径、wxid、聊天正文。 */
|
||||
lastError?: string
|
||||
}
|
||||
|
||||
export interface ExtensionAutomationActionSummary {
|
||||
/** 扩展内唯一 id(manifest 声明)。 */
|
||||
id: string
|
||||
title: string
|
||||
description?: string
|
||||
/** 宿主运行期是否真的注册成功(后台进程未启动时为 false)。 */
|
||||
registered: boolean
|
||||
}
|
||||
|
||||
export interface InstalledExtension {
|
||||
id: string
|
||||
name: string
|
||||
version: string
|
||||
apiVersion: string
|
||||
minAppVersion?: string
|
||||
description?: string
|
||||
author?: string
|
||||
enabled: boolean
|
||||
installedAt: number
|
||||
updatedAt: number
|
||||
compatibility: ExtensionCompatibility
|
||||
permissions: ExtensionPermission[]
|
||||
grantedPermissions: ExtensionPermission[]
|
||||
runtime: ExtensionRuntimeSnapshot
|
||||
pages: Array<{ id: string; title: string }>
|
||||
automationActions: ExtensionAutomationActionSummary[]
|
||||
/** 扩展目录是否仍然存在;false 时 UI 必须显示为「文件缺失」而不是可启动。 */
|
||||
filesPresent: boolean
|
||||
}
|
||||
|
||||
export interface ExtensionLogEntry {
|
||||
id: string
|
||||
at: number
|
||||
level: 'info' | 'warn' | 'error'
|
||||
/** 来源:宿主自身事件,或扩展代码主动写入的日志。 */
|
||||
source: 'core' | 'extension'
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface ExtensionInstallResult {
|
||||
success: boolean
|
||||
extension?: InstalledExtension
|
||||
error?: ExtensionErrorPayload
|
||||
}
|
||||
|
||||
export interface ExtensionOperationResult {
|
||||
success: boolean
|
||||
error?: ExtensionErrorPayload
|
||||
}
|
||||
|
||||
export interface ExtensionPageDescriptor {
|
||||
extensionId: string
|
||||
pageId: string
|
||||
title: string
|
||||
url: string
|
||||
}
|
||||
|
||||
/** 渲染层可调用的页面侧能力白名单;扩展页面拿不到发送 / AI / 查询权限。 */
|
||||
export type ExtensionPageMethod =
|
||||
| 'storage.get'
|
||||
| 'storage.set'
|
||||
| 'storage.remove'
|
||||
| 'storage.list'
|
||||
| 'capabilities.get'
|
||||
| 'contacts.listGroups'
|
||||
| 'test.send'
|
||||
| 'douyin.cookie.get'
|
||||
| 'douyin.cookie.set'
|
||||
| 'douyin.cookie.clear'
|
||||
| 'extension.info'
|
||||
|
||||
export interface ExtensionPageRequest {
|
||||
extensionId: string
|
||||
method: ExtensionPageMethod
|
||||
params?: Record<string, unknown>
|
||||
}
|
||||
|
||||
export interface ExtensionPageResponse {
|
||||
ok: boolean
|
||||
result?: unknown
|
||||
error?: ExtensionErrorPayload
|
||||
}
|
||||
|
||||
export interface ExtensionCapabilitySnapshot {
|
||||
extensionId: string
|
||||
enabled: boolean
|
||||
permissions: ExtensionPermission[]
|
||||
platform: NodeJS.Platform
|
||||
databaseReady: boolean
|
||||
send: {
|
||||
supported: boolean
|
||||
ready: boolean
|
||||
canSendText: boolean
|
||||
/** 图片与视频是两条独立通道。 */
|
||||
canSendImage: boolean
|
||||
canSendVideo: boolean
|
||||
/** 仅 `wechat.send.text` 被授予时才有意义。 */
|
||||
licensed: boolean
|
||||
message: string
|
||||
}
|
||||
ai: {
|
||||
configured: boolean
|
||||
modelName: string
|
||||
}
|
||||
}
|
||||
|
||||
export interface ExtensionQuitBehavior {
|
||||
keepData: boolean
|
||||
}
|
||||
@@ -39,6 +39,8 @@ export interface PersonalWechatSenderStatus {
|
||||
canSendText: boolean
|
||||
canSendImage: boolean
|
||||
canSendVoice: boolean
|
||||
/** 视频与图片共用媒体通道;旧 runtime 不报告该字段。 */
|
||||
canSendVideo?: boolean
|
||||
message: string
|
||||
error?: string
|
||||
}
|
||||
@@ -60,6 +62,8 @@ export interface PersonalWechatSendCapability {
|
||||
text: boolean
|
||||
image: boolean
|
||||
voice: boolean
|
||||
/** 图片/视频共用媒体通道;未报告的旧 runtime 视为 false。 */
|
||||
video?: boolean
|
||||
}
|
||||
senderStatus: PersonalWechatSenderStatus
|
||||
message: string
|
||||
@@ -93,10 +97,22 @@ export interface PersonalWechatSendVoiceRequest extends PersonalWechatSendBaseRe
|
||||
durationMs?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* 视频发送。
|
||||
*
|
||||
* 原生 Host 走 `POST /SendMsg`,body 为 `{toWxid, type:'video', msg:<绝对路径>}`;
|
||||
* `filePath` 必须是本机可访问的普通文件。
|
||||
*/
|
||||
export interface PersonalWechatSendVideoRequest extends PersonalWechatSendBaseRequest {
|
||||
type: 'video'
|
||||
filePath: string
|
||||
}
|
||||
|
||||
export type PersonalWechatSendRequest =
|
||||
| PersonalWechatSendTextRequest
|
||||
| PersonalWechatSendImageRequest
|
||||
| PersonalWechatSendVoiceRequest
|
||||
| PersonalWechatSendVideoRequest
|
||||
|
||||
/** Renderer 请求发送刚刚生成的 TTS 语音;Action 元数据由主进程补齐。 */
|
||||
export interface PersonalWechatGeneratedTtsVoiceRequest {
|
||||
|
||||
@@ -74,6 +74,7 @@ export interface WechatActionRecipient {
|
||||
export type WechatActionContent =
|
||||
| { type: 'text'; text: string; at?: Record<string, string> }
|
||||
| { type: 'image'; path: string }
|
||||
| { type: 'video'; path: string }
|
||||
| { type: 'voice'; path: string }
|
||||
|
||||
export interface WechatActionRequest {
|
||||
@@ -127,6 +128,8 @@ export interface PolicyDecision {
|
||||
export interface WechatActionAuditRecord {
|
||||
actionId: string
|
||||
idempotencyKey?: string
|
||||
/** 扩展来源时为扩展 id;其他来源省略。 */
|
||||
extensionId?: string
|
||||
origin: WechatActionOrigin
|
||||
purpose: WechatActionPurpose
|
||||
triggerType: WechatActionTriggerType
|
||||
|
||||
Reference in new issue
Block a user