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
9ffa1efc26
commit
4eaddc2d75
74 files changed
+11738
-379
No files matched your search
@@ -419,44 +419,48 @@ describe('bootstrap cache write gating', () => {
|
||||
expect(snapshotFile(file).ino).not.toBe(beforeMerge.ino)
|
||||
})
|
||||
|
||||
it('keeps the previous cache when replacement fails, then recovers', async () => {
|
||||
const root = '/fixture/gate-rename-failure'
|
||||
const file = cacheFileFor(root)
|
||||
const directory = join(cacheFileFor(root), '..')
|
||||
// Windows 的只读目标会让 MoveFileEx/REPLACE_EXISTING 抛 EPERM;
|
||||
// POSIX 的 rename 不看文件 mode,这个场景在 macOS 上无法复现。
|
||||
it.skipIf(process.platform !== 'win32')(
|
||||
'keeps the previous cache when replacement fails, then recovers',
|
||||
async () => {
|
||||
const root = '/fixture/gate-rename-failure'
|
||||
const file = cacheFileFor(root)
|
||||
const directory = join(cacheFileFor(root), '..')
|
||||
|
||||
saveBootstrapContacts(root, makeContacts(2))
|
||||
await settle()
|
||||
const good = snapshotFile(file)
|
||||
const goodContent = readFileSync(file, 'utf8')
|
||||
expect(good.exists).toBe(true)
|
||||
saveBootstrapContacts(root, makeContacts(2))
|
||||
await settle()
|
||||
const good = snapshotFile(file)
|
||||
const goodContent = readFileSync(file, 'utf8')
|
||||
expect(good.exists).toBe(true)
|
||||
|
||||
// 只读目标在 Windows 上让 MoveFileEx/REPLACE_EXISTING 抛 EPERM;
|
||||
// 这不是 mock,是真实的文件系统行为。
|
||||
chmodSync(file, 0o444)
|
||||
try {
|
||||
saveBootstrapContacts(
|
||||
root,
|
||||
makeContacts(3, (contact) => ({ ...contact, remark: '失败尝试' }))
|
||||
)
|
||||
await settle(1500)
|
||||
// 只读目标让 MoveFileEx/REPLACE_EXISTING 抛 EPERM;这不是 mock,是真实的文件系统行为。
|
||||
chmodSync(file, 0o444)
|
||||
try {
|
||||
saveBootstrapContacts(
|
||||
root,
|
||||
makeContacts(3, (contact) => ({ ...contact, remark: '失败尝试' }))
|
||||
)
|
||||
await settle(1500)
|
||||
|
||||
const failed = snapshotFile(file)
|
||||
expect(failed.ino, '替换失败时目标文件必须原样保留').toBe(good.ino)
|
||||
expect(readFileSync(file, 'utf8')).toBe(goodContent)
|
||||
expect(tempFilesIn(directory), '失败后不能残留 .tmp').toHaveLength(0)
|
||||
} finally {
|
||||
chmodSync(file, 0o666)
|
||||
const failed = snapshotFile(file)
|
||||
expect(failed.ino, '替换失败时目标文件必须原样保留').toBe(good.ino)
|
||||
expect(readFileSync(file, 'utf8')).toBe(goodContent)
|
||||
expect(tempFilesIn(directory), '失败后不能残留 .tmp').toHaveLength(0)
|
||||
} finally {
|
||||
chmodSync(file, 0o666)
|
||||
}
|
||||
|
||||
// 失败过的内容再存一次必须能真正落盘,不能被指纹闸门吞掉
|
||||
const target = makeContacts(3, (contact) => ({ ...contact, remark: '失败尝试' }))
|
||||
saveBootstrapContacts(root, target)
|
||||
await settle()
|
||||
const recovered = snapshotFile(file)
|
||||
expect(recovered.ino).not.toBe(good.ino)
|
||||
expect(JSON.parse(readFileSync(file, 'utf8')).contacts).toHaveLength(3)
|
||||
expect(tempFilesIn(directory)).toHaveLength(0)
|
||||
}
|
||||
|
||||
// 失败过的内容再存一次必须能真正落盘,不能被指纹闸门吞掉
|
||||
const target = makeContacts(3, (contact) => ({ ...contact, remark: '失败尝试' }))
|
||||
saveBootstrapContacts(root, target)
|
||||
await settle()
|
||||
const recovered = snapshotFile(file)
|
||||
expect(recovered.ino).not.toBe(good.ino)
|
||||
expect(JSON.parse(readFileSync(file, 'utf8')).contacts).toHaveLength(3)
|
||||
expect(tempFilesIn(directory)).toHaveLength(0)
|
||||
})
|
||||
)
|
||||
|
||||
it('lands the newest revision under rapid changes', async () => {
|
||||
const root = '/fixture/gate-rapid'
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { spawn } from 'node:child_process'
|
||||
import fs from 'fs-extra'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import {
|
||||
ExtensionHost,
|
||||
forkExtensionHost,
|
||||
killProcessTree,
|
||||
redactSecrets
|
||||
} from '../../src/main/extensions/extension-host'
|
||||
import { ExtensionStorage } from '../../src/main/extensions/extension-storage'
|
||||
import { EXTENSION_HOST_PROTOCOL_VERSION } from '../../src/shared/extensions/rpc'
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
function tempRoot(): string {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-extension-process-'))
|
||||
roots.push(root)
|
||||
return root
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
function isAlive(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0)
|
||||
return true
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
// 先给残留进程一点时间退出,再删目录。
|
||||
await sleep(50)
|
||||
for (const root of roots.splice(0)) fs.removeSync(root)
|
||||
})
|
||||
|
||||
describe('redactSecrets', () => {
|
||||
it('抹掉赋值形态的凭据值,保留键名', () => {
|
||||
expect(redactSecrets('cookie: abcdef123456')).toBe('cookie: ***')
|
||||
expect(redactSecrets('Authorization=BearerToken123')).toBe('Authorization=***')
|
||||
expect(redactSecrets('api_key = sk-1234567890')).toBe('api_key = ***')
|
||||
})
|
||||
|
||||
it('抹掉 Bearer token,普通文本不受影响', () => {
|
||||
expect(redactSecrets('Authorization: Bearer fake-token-for-redaction-test')).toBe(
|
||||
'Authorization: Bearer ***'
|
||||
)
|
||||
expect(redactSecrets('token bucket 已满')).toBe('token bucket 已满')
|
||||
expect(redactSecrets('普通日志:已发送')).toBe('普通日志:已发送')
|
||||
})
|
||||
})
|
||||
|
||||
describe('killProcessTree', () => {
|
||||
const spawned: number[] = []
|
||||
|
||||
afterEach(async () => {
|
||||
for (const pid of spawned.splice(0)) {
|
||||
try {
|
||||
process.kill(pid, 'SIGKILL')
|
||||
} catch {
|
||||
// 已经退出。
|
||||
}
|
||||
}
|
||||
await sleep(30)
|
||||
})
|
||||
|
||||
it.skipIf(process.platform === 'win32')('结束进程组时连带结束孙进程', async () => {
|
||||
const dir = tempRoot()
|
||||
const script = path.join(dir, 'parent.js')
|
||||
fs.writeFileSync(
|
||||
script,
|
||||
`const { spawn } = require('node:child_process')
|
||||
const child = spawn('/bin/sleep', ['300'], { stdio: 'ignore' })
|
||||
process.send({ grandchild: child.pid })
|
||||
setInterval(() => {}, 1000)`
|
||||
)
|
||||
|
||||
const parent = spawn(process.execPath, [script], {
|
||||
detached: true,
|
||||
stdio: ['ignore', 'ignore', 'ignore', 'ipc']
|
||||
})
|
||||
spawned.push(parent.pid as number)
|
||||
|
||||
const grandchildPid = await new Promise<number>((resolve) => {
|
||||
parent.on('message', (message) => resolve((message as { grandchild: number }).grandchild))
|
||||
})
|
||||
spawned.push(grandchildPid)
|
||||
await sleep(100)
|
||||
expect(isAlive(grandchildPid)).toBe(true)
|
||||
|
||||
expect(killProcessTree(parent.pid)).toBe('group')
|
||||
await sleep(300)
|
||||
expect(isAlive(grandchildPid)).toBe(false)
|
||||
expect(isAlive(parent.pid as number)).toBe(false)
|
||||
})
|
||||
|
||||
it('不存在的 pid 返回 fallback 且不抛错', () => {
|
||||
expect(() => killProcessTree(999_999_999)).not.toThrow()
|
||||
expect(killProcessTree(999_999_999)).toBe('fallback')
|
||||
expect(killProcessTree(undefined)).toBe('fallback')
|
||||
})
|
||||
|
||||
it('只结束指定组,不影响另一个进程组', async () => {
|
||||
if (process.platform === 'win32') return
|
||||
const dir = tempRoot()
|
||||
const script = path.join(dir, 'parent.js')
|
||||
fs.writeFileSync(script, 'setInterval(() => {}, 1000)')
|
||||
|
||||
const first = spawn(process.execPath, [script], { detached: true, stdio: 'ignore' })
|
||||
const second = spawn(process.execPath, [script], { detached: true, stdio: 'ignore' })
|
||||
spawned.push(first.pid as number, second.pid as number)
|
||||
await sleep(120)
|
||||
|
||||
killProcessTree(first.pid)
|
||||
await sleep(300)
|
||||
expect(isAlive(first.pid as number)).toBe(false)
|
||||
expect(isAlive(second.pid as number)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('extension host 进程生命周期', () => {
|
||||
/**
|
||||
* 造一个「激活后派生孙进程、收到 shutdown 也不退出」的宿主,用于验证强杀路径。
|
||||
* 孙进程 pid 写到脚本同目录,供测试断言是否残留。
|
||||
*/
|
||||
function createStubbornHostRunner(root: string): string {
|
||||
const script = path.join(root, 'stubborn-host.js')
|
||||
fs.writeFileSync(
|
||||
script,
|
||||
`const { spawn } = require('node:child_process')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
let grandchild = null
|
||||
process.on('message', (raw) => {
|
||||
if (!raw || typeof raw !== 'object') return
|
||||
if (raw.type === 'activate') {
|
||||
grandchild = spawn('/bin/sleep', ['300'], { stdio: 'ignore' })
|
||||
fs.writeFileSync(path.join(__dirname, 'grandchild.pid'), String(grandchild.pid))
|
||||
process.send({ type: 'activated', version: ${EXTENSION_HOST_PROTOCOL_VERSION}, ok: true })
|
||||
}
|
||||
// 刻意忽略 shutdown:模拟扩展卡在清理逻辑里。
|
||||
})
|
||||
process.send({ type: 'ready', version: ${EXTENSION_HOST_PROTOCOL_VERSION} })
|
||||
setInterval(() => {}, 1000)`
|
||||
)
|
||||
return script
|
||||
}
|
||||
|
||||
it.skipIf(process.platform === 'win32')('超时后结束整棵进程树,孙进程不残留', async () => {
|
||||
const root = tempRoot()
|
||||
const script = createStubbornHostRunner(root)
|
||||
const logLines: string[] = []
|
||||
const host = new ExtensionHost({
|
||||
extensionId: 'com.example.stubborn',
|
||||
extensionDir: root,
|
||||
dataDir: path.join(root, 'data'),
|
||||
permissions: [],
|
||||
storage: new ExtensionStorage({ dataRoot: path.join(root, 'storage') }),
|
||||
spawn: forkExtensionHost(script),
|
||||
onLog: (level, message) => logLines.push(`${level}:${message}`),
|
||||
gracefulExitMs: 200,
|
||||
forceExitMs: 2_000
|
||||
})
|
||||
|
||||
await host.start()
|
||||
expect(host.snapshot().state).toBe('active')
|
||||
|
||||
const pidFile = path.join(root, 'grandchild.pid')
|
||||
const grandchildPid = Number(fs.readFileSync(pidFile, 'utf8').trim())
|
||||
expect(isAlive(grandchildPid)).toBe(true)
|
||||
|
||||
const started = Date.now()
|
||||
await host.stop()
|
||||
expect(Date.now() - started).toBeLessThan(5_000)
|
||||
expect(host.snapshot().state).toBe('inactive')
|
||||
expect(logLines.some((line) => line.includes('结束进程树'))).toBe(true)
|
||||
|
||||
await sleep(200)
|
||||
expect(isAlive(grandchildPid)).toBe(false)
|
||||
})
|
||||
|
||||
it('重复 stop 不抛错', async () => {
|
||||
const root = tempRoot()
|
||||
const script = path.join(root, 'quick-host.js')
|
||||
fs.writeFileSync(
|
||||
script,
|
||||
`process.on('message', (raw) => {
|
||||
if (raw && raw.type === 'activate') process.send({ type: 'activated', version: ${EXTENSION_HOST_PROTOCOL_VERSION}, ok: true })
|
||||
if (raw && raw.type === 'shutdown') process.exit(0)
|
||||
})
|
||||
process.send({ type: 'ready', version: ${EXTENSION_HOST_PROTOCOL_VERSION} })`
|
||||
)
|
||||
const host = new ExtensionHost({
|
||||
extensionId: 'com.example.quick',
|
||||
extensionDir: root,
|
||||
dataDir: path.join(root, 'data'),
|
||||
permissions: [],
|
||||
storage: new ExtensionStorage({ dataRoot: path.join(root, 'storage') }),
|
||||
spawn: forkExtensionHost(script),
|
||||
gracefulExitMs: 500,
|
||||
forceExitMs: 1_000
|
||||
})
|
||||
await host.start()
|
||||
await host.stop()
|
||||
await expect(host.stop()).resolves.toBeUndefined()
|
||||
expect(host.snapshot().state).toBe('inactive')
|
||||
})
|
||||
|
||||
it('大量 stderr 不会阻塞宿主,日志有速率上限', async () => {
|
||||
const root = tempRoot()
|
||||
const script = path.join(root, 'noisy-host.js')
|
||||
fs.writeFileSync(
|
||||
script,
|
||||
`const chunk = 'x'.repeat(8 * 1024)
|
||||
process.on('message', (raw) => {
|
||||
if (raw && raw.type === 'activate') {
|
||||
for (let i = 0; i < 160; i += 1) process.stderr.write(chunk)
|
||||
process.send({ type: 'activated', version: ${EXTENSION_HOST_PROTOCOL_VERSION}, ok: true })
|
||||
}
|
||||
if (raw && raw.type === 'shutdown') process.exit(0)
|
||||
})
|
||||
process.send({ type: 'ready', version: ${EXTENSION_HOST_PROTOCOL_VERSION} })`
|
||||
)
|
||||
const logLines: string[] = []
|
||||
const host = new ExtensionHost({
|
||||
extensionId: 'com.example.noisy',
|
||||
extensionDir: root,
|
||||
dataDir: path.join(root, 'data'),
|
||||
permissions: [],
|
||||
storage: new ExtensionStorage({ dataRoot: path.join(root, 'storage') }),
|
||||
spawn: forkExtensionHost(script),
|
||||
onLog: (level, message) => logLines.push(`${level}:${message}`),
|
||||
activateTimeoutMs: 8_000
|
||||
})
|
||||
|
||||
// 1.25MB stderr:管道被持续消费,激活握手必须仍然完成。
|
||||
await host.start()
|
||||
expect(host.snapshot().state).toBe('active')
|
||||
await sleep(200)
|
||||
|
||||
const stderrLines = logLines.filter((line) => line.includes('[stderr]'))
|
||||
expect(stderrLines.length).toBeGreaterThan(0)
|
||||
// 单个 10 秒窗口最多 20 条;允许窗口边界多出一条。
|
||||
expect(stderrLines.length).toBeLessThanOrEqual(21)
|
||||
for (const line of stderrLines) {
|
||||
expect(line.length).toBeLessThanOrEqual(520)
|
||||
}
|
||||
|
||||
await host.stop()
|
||||
})
|
||||
|
||||
it('两个扩展同时运行,停用其中一个不影响另一个', async () => {
|
||||
const root = tempRoot()
|
||||
const script = path.join(root, 'pair-host.js')
|
||||
fs.writeFileSync(
|
||||
script,
|
||||
`process.on('message', (raw) => {
|
||||
if (raw && raw.type === 'activate') process.send({ type: 'activated', version: ${EXTENSION_HOST_PROTOCOL_VERSION}, ok: true })
|
||||
if (raw && raw.type === 'shutdown') process.exit(0)
|
||||
})
|
||||
process.send({ type: 'ready', version: ${EXTENSION_HOST_PROTOCOL_VERSION} })`
|
||||
)
|
||||
const makeHost = (id: string): ExtensionHost =>
|
||||
new ExtensionHost({
|
||||
extensionId: id,
|
||||
extensionDir: root,
|
||||
dataDir: path.join(root, id),
|
||||
permissions: [],
|
||||
storage: new ExtensionStorage({ dataRoot: path.join(root, `storage-${id}`) }),
|
||||
spawn: forkExtensionHost(script),
|
||||
gracefulExitMs: 500,
|
||||
forceExitMs: 1_000
|
||||
})
|
||||
|
||||
const first = makeHost('com.example.first')
|
||||
const second = makeHost('com.example.second')
|
||||
await first.start()
|
||||
await second.start()
|
||||
expect(first.snapshot().state).toBe('active')
|
||||
expect(second.snapshot().state).toBe('active')
|
||||
|
||||
await first.stop()
|
||||
expect(first.snapshot().state).toBe('inactive')
|
||||
expect(second.snapshot().state).toBe('active')
|
||||
|
||||
await second.stop()
|
||||
})
|
||||
})
|
||||
@@ -18,6 +18,7 @@ class FakeChild implements ExtensionHostChild {
|
||||
killed = false
|
||||
autoActivate = true
|
||||
activationOk = true
|
||||
autoRespondAction = true
|
||||
actionOutput: unknown = { success: true, output: { matched: true } }
|
||||
|
||||
send(message: unknown): void {
|
||||
@@ -36,7 +37,7 @@ class FakeChild implements ExtensionHostChild {
|
||||
if (payload.type === 'shutdown') {
|
||||
queueMicrotask(() => this.emit('exit', 0, null))
|
||||
}
|
||||
if (payload.type === 'invoke-action') {
|
||||
if (payload.type === 'invoke-action' && this.autoRespondAction) {
|
||||
queueMicrotask(() => {
|
||||
this.emit('message', {
|
||||
type: 'action-result',
|
||||
@@ -227,4 +228,20 @@ describe('extension host', () => {
|
||||
expect(result?.ok).toBe(false)
|
||||
expect((result?.error as { code: string }).code).toBe('PERMISSION_DENIED')
|
||||
})
|
||||
|
||||
it('停止时未完成的动作以扩展不可用失败,不会永远挂起', async () => {
|
||||
const { host, child } = createHost()
|
||||
child.autoRespondAction = false
|
||||
await host.start()
|
||||
child.emit('message', {
|
||||
type: 'register-action',
|
||||
version: EXTENSION_HOST_PROTOCOL_VERSION,
|
||||
action: { id: 'keyword.reply', title: '关键词回复', hasInputSchema: false }
|
||||
})
|
||||
|
||||
const pending = host.invokeAction('keyword.reply', { text: '长时间任务' })
|
||||
await host.stop()
|
||||
|
||||
await expect(pending).rejects.toMatchObject({ code: 'EXTENSION_HOST_UNAVAILABLE' })
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from 'fs-extra'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
|
||||
import { ExtensionRegistry } from '../../src/main/extensions/extension-registry'
|
||||
import { ExtensionInstaller } from '../../src/main/extensions/extension-installer'
|
||||
@@ -74,7 +74,7 @@ describe('extension installer', () => {
|
||||
const first = createExtensionSource(root)
|
||||
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
|
||||
registry.setEnabled('com.example.fixture', true)
|
||||
registry.setGrantedPermissions('com.example.fixture', ['storage', 'messages.subscribe'])
|
||||
registry.setGrantedPermissions('com.example.fixture', ['storage', 'wechat.send.text'])
|
||||
fs.ensureDirSync(paths.extensionDataDir('com.example.fixture'))
|
||||
fs.writeJsonSync(path.join(paths.extensionDataDir('com.example.fixture'), 'storage.json'), {
|
||||
version: 1,
|
||||
@@ -83,20 +83,60 @@ describe('extension installer', () => {
|
||||
|
||||
const second = path.join(root, 'source-v2')
|
||||
fs.copySync(first, second)
|
||||
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
|
||||
fs.writeJsonSync(
|
||||
path.join(second, 'manifest.json'),
|
||||
// 新版本仍声明这两项权限,升级不应把它们清掉。
|
||||
MANIFEST({ version: '1.2.0', permissions: ['storage', 'wechat.send.text'] })
|
||||
)
|
||||
const outcome = await installer.installFromDirectory(second, { appVersion: '2.6.0' })
|
||||
expect(outcome.upgraded).toBe(true)
|
||||
expect(outcome.previousVersion).toBe('1.0.0')
|
||||
const record = registry.get('com.example.fixture')
|
||||
expect(record?.version).toBe('1.2.0')
|
||||
expect(record?.enabled).toBe(true)
|
||||
expect(record?.grantedPermissions).toEqual(['storage', 'messages.subscribe'])
|
||||
expect(record?.grantedPermissions).toEqual(['storage', 'wechat.send.text'])
|
||||
expect(
|
||||
fs.readJsonSync(path.join(paths.extensionDataDir('com.example.fixture'), 'storage.json'))
|
||||
.values.greeting
|
||||
).toBe('保留我')
|
||||
})
|
||||
|
||||
it('新版本删除的权限在升级后立即失效', async () => {
|
||||
const { paths, registry, installer } = setup()
|
||||
const root = path.dirname(paths.userData)
|
||||
const first = createExtensionSource(root, { permissions: ['storage', 'wechat.send.text'] })
|
||||
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
|
||||
registry.setGrantedPermissions('com.example.fixture', ['storage', 'wechat.send.text'])
|
||||
|
||||
const second = path.join(root, 'source-v2')
|
||||
fs.copySync(first, second)
|
||||
fs.writeJsonSync(
|
||||
path.join(second, 'manifest.json'),
|
||||
MANIFEST({ version: '1.1.0', permissions: ['storage'] })
|
||||
)
|
||||
await installer.installFromDirectory(second, { appVersion: '2.6.0' })
|
||||
|
||||
expect(registry.get('com.example.fixture')?.grantedPermissions).toEqual(['storage'])
|
||||
})
|
||||
|
||||
it('新版本新增的权限不会自动授予', async () => {
|
||||
const { paths, registry, installer } = setup()
|
||||
const root = path.dirname(paths.userData)
|
||||
const first = createExtensionSource(root, { permissions: ['storage'] })
|
||||
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
|
||||
registry.setGrantedPermissions('com.example.fixture', ['storage'])
|
||||
|
||||
const second = path.join(root, 'source-v2')
|
||||
fs.copySync(first, second)
|
||||
fs.writeJsonSync(
|
||||
path.join(second, 'manifest.json'),
|
||||
MANIFEST({ version: '1.1.0', permissions: ['storage', 'wechat.send.text'] })
|
||||
)
|
||||
await installer.installFromDirectory(second, { appVersion: '2.6.0' })
|
||||
|
||||
expect(registry.get('com.example.fixture')?.grantedPermissions).toEqual(['storage'])
|
||||
})
|
||||
|
||||
it('卸载默认保留数据,选择清除时一并删除', async () => {
|
||||
const { paths, registry, installer } = setup()
|
||||
const source = createExtensionSource(path.dirname(paths.userData))
|
||||
@@ -176,6 +216,142 @@ describe('extension installer', () => {
|
||||
fs.existsSync(path.join(paths.installDir('com.example.fixture'), 'ui', 'index.html'))
|
||||
).toBe(true)
|
||||
})
|
||||
|
||||
it('替换代码前仍能读到旧版本,beforeReplace 早于目录改名', async () => {
|
||||
const { paths, registry, installer } = setup()
|
||||
const root = path.dirname(paths.userData)
|
||||
const first = createExtensionSource(root)
|
||||
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
|
||||
registry.setEnabled('com.example.fixture', true)
|
||||
|
||||
const second = path.join(root, 'source-v2')
|
||||
fs.copySync(first, second)
|
||||
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
|
||||
|
||||
let versionDuringCallback = ''
|
||||
await installer.installFromDirectory(second, {
|
||||
appVersion: '2.6.0',
|
||||
beforeReplace: async () => {
|
||||
versionDuringCallback = fs.readJsonSync(
|
||||
path.join(paths.installDir('com.example.fixture'), 'manifest.json')
|
||||
).version as string
|
||||
}
|
||||
})
|
||||
expect(versionDuringCallback).toBe('1.0.0')
|
||||
expect(
|
||||
fs.readJsonSync(path.join(paths.installDir('com.example.fixture'), 'manifest.json')).version
|
||||
).toBe('1.2.0')
|
||||
})
|
||||
|
||||
it('beforeReplace 抛错时磁盘保持原样,只清掉 staging', async () => {
|
||||
const { paths, registry, installer } = setup()
|
||||
const root = path.dirname(paths.userData)
|
||||
const first = createExtensionSource(root)
|
||||
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
|
||||
registry.setEnabled('com.example.fixture', true)
|
||||
|
||||
const second = path.join(root, 'source-v2')
|
||||
fs.copySync(first, second)
|
||||
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
|
||||
|
||||
await expect(
|
||||
installer.installFromDirectory(second, {
|
||||
appVersion: '2.6.0',
|
||||
beforeReplace: async () => {
|
||||
throw new Error('旧进程未能停止')
|
||||
}
|
||||
})
|
||||
).rejects.toThrow(/旧进程/)
|
||||
|
||||
expect(
|
||||
fs.readJsonSync(path.join(paths.installDir('com.example.fixture'), 'manifest.json')).version
|
||||
).toBe('1.0.0')
|
||||
expect(fs.existsSync(paths.stagingDir) ? fs.readdirSync(paths.stagingDir) : []).toEqual([])
|
||||
})
|
||||
|
||||
it('rollback 把代码与 Registry 一起退回旧版本', async () => {
|
||||
const { paths, registry, installer } = setup()
|
||||
const root = path.dirname(paths.userData)
|
||||
const first = createExtensionSource(root)
|
||||
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
|
||||
registry.setEnabled('com.example.fixture', true)
|
||||
|
||||
const second = path.join(root, 'source-v2')
|
||||
fs.copySync(first, second)
|
||||
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
|
||||
|
||||
const outcome = await installer.installFromDirectory(second, { appVersion: '2.6.0' })
|
||||
expect(registry.get('com.example.fixture')?.version).toBe('1.2.0')
|
||||
|
||||
await outcome.rollback()
|
||||
expect(
|
||||
fs.readJsonSync(path.join(paths.installDir('com.example.fixture'), 'manifest.json')).version
|
||||
).toBe('1.0.0')
|
||||
expect(registry.get('com.example.fixture')?.version).toBe('1.0.0')
|
||||
expect(registry.get('com.example.fixture')?.enabled).toBe(true)
|
||||
})
|
||||
|
||||
it('cleanup 删除过渡备份,不留 backup 目录', async () => {
|
||||
const { paths, installer } = setup()
|
||||
const root = path.dirname(paths.userData)
|
||||
const first = createExtensionSource(root)
|
||||
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
|
||||
|
||||
const second = path.join(root, 'source-v2')
|
||||
fs.copySync(first, second)
|
||||
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
|
||||
|
||||
const outcome = await installer.installFromDirectory(second, { appVersion: '2.6.0' })
|
||||
await outcome.cleanup()
|
||||
expect(fs.readdirSync(paths.extensionsDir).filter((name) => name.includes('.backup-'))).toEqual(
|
||||
[]
|
||||
)
|
||||
// cleanup 之后不能再回滚,避免删掉已确认的新版本。
|
||||
await expect(outcome.rollback()).rejects.toMatchObject({ code: 'EXTENSION_INSTALL_FAILED' })
|
||||
})
|
||||
|
||||
it('Registry 写入失败时目录回滚,旧版本仍可用', async () => {
|
||||
const { paths, registry, installer } = setup()
|
||||
const root = path.dirname(paths.userData)
|
||||
const first = createExtensionSource(root)
|
||||
await installer.installFromDirectory(first, { appVersion: '2.6.0' })
|
||||
|
||||
const second = path.join(root, 'source-v2')
|
||||
fs.copySync(first, second)
|
||||
fs.writeJsonSync(path.join(second, 'manifest.json'), MANIFEST({ version: '1.2.0' }))
|
||||
|
||||
const spy = vi.spyOn(registry, 'upsert').mockImplementationOnce(() => {
|
||||
throw new Error('磁盘写入失败')
|
||||
})
|
||||
await expect(
|
||||
installer.installFromDirectory(second, { appVersion: '2.6.0' })
|
||||
).rejects.toMatchObject({ code: 'EXTENSION_INSTALL_FAILED' })
|
||||
spy.mockRestore()
|
||||
|
||||
expect(
|
||||
fs.readJsonSync(path.join(paths.installDir('com.example.fixture'), 'manifest.json')).version
|
||||
).toBe('1.0.0')
|
||||
expect(registry.get('com.example.fixture')?.version).toBe('1.0.0')
|
||||
expect(fs.readdirSync(paths.extensionsDir).filter((name) => name.includes('.backup-'))).toEqual(
|
||||
[]
|
||||
)
|
||||
})
|
||||
|
||||
it('文件夹安装跳过 .git 与 node_modules', async () => {
|
||||
const { paths, installer } = setup()
|
||||
const root = path.dirname(paths.userData)
|
||||
const source = createExtensionSource(root)
|
||||
fs.ensureDirSync(path.join(source, 'node_modules', 'dep'))
|
||||
fs.writeFileSync(path.join(source, 'node_modules', 'dep', 'index.js'), 'x')
|
||||
fs.ensureDirSync(path.join(source, '.git', 'objects'))
|
||||
fs.writeFileSync(path.join(source, '.git', 'HEAD'), 'ref: refs/heads/main')
|
||||
|
||||
await installer.installFromDirectory(source, { appVersion: '2.6.0' })
|
||||
const installed = paths.installDir('com.example.fixture')
|
||||
expect(fs.existsSync(path.join(installed, 'node_modules'))).toBe(false)
|
||||
expect(fs.existsSync(path.join(installed, '.git'))).toBe(false)
|
||||
expect(fs.existsSync(path.join(installed, 'manifest.json'))).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
/* 最小 ZIP 写入器:只支持 stored(无压缩)条目,用于构造非法路径样本。 */
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import fs from 'fs-extra'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import {
|
||||
ACTION_SCHEMA_MAX_BYTES,
|
||||
buildDefaultActionInput,
|
||||
parseActionInputSchema,
|
||||
validateActionInput
|
||||
} from '../../src/shared/extensions/action-schema'
|
||||
import { ExtensionSecretStore } from '../../src/main/extensions/extension-secret-store'
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
function tempRoot(): string {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-m4-'))
|
||||
roots.push(root)
|
||||
return root
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) fs.removeSync(root)
|
||||
})
|
||||
|
||||
describe('动作参数 Schema', () => {
|
||||
it('解析受支持的子集并保留默认值', () => {
|
||||
const parsed = parseActionInputSchema({
|
||||
type: 'object',
|
||||
properties: {
|
||||
keyword: { type: 'string', title: '关键词', minLength: 1, maxLength: 20 },
|
||||
times: { type: 'integer', default: 2, minimum: 1, maximum: 5 },
|
||||
enabled: { type: 'boolean', default: true }
|
||||
},
|
||||
required: ['keyword']
|
||||
})
|
||||
expect(parsed.ok).toBe(true)
|
||||
if (!parsed.ok) return
|
||||
expect(parsed.schema.properties.keyword.type).toBe('string')
|
||||
expect(parsed.schema.required).toEqual(['keyword'])
|
||||
expect(buildDefaultActionInput(parsed.schema)).toEqual({ times: 2, enabled: true })
|
||||
})
|
||||
|
||||
it('拒绝不支持的字段类型与非法结构', () => {
|
||||
expect(parseActionInputSchema({ type: 'array' }).ok).toBe(false)
|
||||
expect(parseActionInputSchema({ type: 'object', properties: { a: { type: 'date' } } }).ok).toBe(
|
||||
false
|
||||
)
|
||||
expect(parseActionInputSchema({ type: 'object', properties: {} }).ok).toBe(false)
|
||||
expect(
|
||||
parseActionInputSchema({
|
||||
type: 'object',
|
||||
properties: { a: { type: 'string' } },
|
||||
required: ['missing']
|
||||
}).ok
|
||||
).toBe(false)
|
||||
})
|
||||
|
||||
it('超过字节上限整体拒绝,不静默截断', () => {
|
||||
const huge = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
text: { type: 'string', description: 'x'.repeat(ACTION_SCHEMA_MAX_BYTES) }
|
||||
}
|
||||
}
|
||||
const parsed = parseActionInputSchema(huge)
|
||||
expect(parsed.ok).toBe(false)
|
||||
if (!parsed.ok) expect(parsed.reason).toContain('上限')
|
||||
})
|
||||
|
||||
it('校验必填、类型、范围与枚举', () => {
|
||||
const parsed = parseActionInputSchema({
|
||||
type: 'object',
|
||||
properties: {
|
||||
keyword: { type: 'string', minLength: 2 },
|
||||
mode: { type: 'string', enum: ['a', 'b'] },
|
||||
count: { type: 'integer', minimum: 1, maximum: 3 }
|
||||
},
|
||||
required: ['keyword']
|
||||
})
|
||||
if (!parsed.ok) throw new Error('schema 应通过')
|
||||
const schema = parsed.schema
|
||||
|
||||
expect(validateActionInput(schema, {}).errors.keyword).toBe('必填')
|
||||
expect(validateActionInput(schema, { keyword: 'x' }).errors.keyword).toContain('至少')
|
||||
expect(validateActionInput(schema, { keyword: 'ok', mode: 'c' }).errors.mode).toContain('范围')
|
||||
expect(validateActionInput(schema, { keyword: 'ok', count: 1.5 }).errors.count).toContain(
|
||||
'整数'
|
||||
)
|
||||
expect(validateActionInput(schema, { keyword: 'ok', count: 9 }).errors.count).toContain(
|
||||
'不能大于'
|
||||
)
|
||||
expect(validateActionInput(schema, { keyword: 'ok', mode: 'a', count: 2 }).ok).toBe(true)
|
||||
})
|
||||
|
||||
it('没有 Schema 时一律通过(向后兼容旧扩展)', () => {
|
||||
expect(validateActionInput(undefined, { anything: 1 }).ok).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('扩展凭据存储', () => {
|
||||
const cipher = {
|
||||
isAvailable: () => true,
|
||||
encrypt: (plain: string) => Buffer.from(`enc:${plain}`, 'utf8'),
|
||||
decrypt: (payload: Buffer) => {
|
||||
const text = payload.toString('utf8')
|
||||
if (!text.startsWith('enc:')) throw new Error('bad payload')
|
||||
return text.slice(4)
|
||||
}
|
||||
}
|
||||
|
||||
it('按扩展命名空间隔离', () => {
|
||||
const root = tempRoot()
|
||||
const store = new ExtensionSecretStore({ root, cipher })
|
||||
store.set('com.example.a', 'cookie', 'value-a')
|
||||
store.set('com.example.b', 'cookie', 'value-b')
|
||||
|
||||
expect(store.get('com.example.a', 'cookie')).toBe('value-a')
|
||||
expect(store.get('com.example.b', 'cookie')).toBe('value-b')
|
||||
expect(new ExtensionSecretStore({ root, cipher }).get('com.example.a', 'cookie')).toBe(
|
||||
'value-a'
|
||||
)
|
||||
})
|
||||
|
||||
it('落盘只有密文,没有明文文件', () => {
|
||||
const root = tempRoot()
|
||||
const store = new ExtensionSecretStore({ root, cipher })
|
||||
store.set('com.example.a', 'cookie', 'super-secret-cookie')
|
||||
|
||||
const files = fs.readdirSync(root)
|
||||
expect(files).toEqual(['com.example.a.bin'])
|
||||
const content = fs.readFileSync(path.join(root, 'com.example.a.bin'), 'utf8')
|
||||
expect(content.startsWith('enc:')).toBe(true)
|
||||
expect(fs.readdirSync(root).some((name) => name.endsWith('.txt'))).toBe(false)
|
||||
})
|
||||
|
||||
it('安全存储不可用时明确失败,不退化成明文', () => {
|
||||
const root = tempRoot()
|
||||
const store = new ExtensionSecretStore({
|
||||
root,
|
||||
cipher: { ...cipher, isAvailable: () => false }
|
||||
})
|
||||
expect(() => store.set('com.example.a', 'cookie', 'x')).toThrowError(/安全存储/)
|
||||
expect(fs.existsSync(root) ? fs.readdirSync(root) : []).toEqual([])
|
||||
})
|
||||
|
||||
it('删除与清空', () => {
|
||||
const root = tempRoot()
|
||||
const store = new ExtensionSecretStore({ root, cipher })
|
||||
store.set('com.example.a', 'cookie', 'v')
|
||||
expect(store.delete('com.example.a', 'cookie')).toBe(true)
|
||||
expect(store.has('com.example.a', 'cookie')).toBe(false)
|
||||
|
||||
store.set('com.example.a', 'cookie', 'v2')
|
||||
store.clear('com.example.a')
|
||||
expect(fs.existsSync(path.join(root, 'com.example.a.bin'))).toBe(false)
|
||||
})
|
||||
|
||||
it('键名不合法时拒绝', () => {
|
||||
const root = tempRoot()
|
||||
const store = new ExtensionSecretStore({ root, cipher })
|
||||
expect(() => store.set('com.example.a', '../escape', 'v')).toThrowError(/键名/)
|
||||
})
|
||||
})
|
||||
@@ -63,8 +63,291 @@ describe('extension registry', () => {
|
||||
const registry = new ExtensionRegistry({ registryFile })
|
||||
expect(registry.list()).toEqual([])
|
||||
})
|
||||
|
||||
it('文件不存在是合法空状态,可以直接写入', () => {
|
||||
const root = tempRoot()
|
||||
const registryFile = path.join(root, 'registry.json')
|
||||
const registry = new ExtensionRegistry({ registryFile })
|
||||
expect(registry.getHealth().state).toBe('ok')
|
||||
registry.upsert({
|
||||
id: 'com.example.a',
|
||||
version: '1.0.0',
|
||||
apiVersion: '1',
|
||||
enabled: false,
|
||||
grantedPermissions: [],
|
||||
installedAt: 1,
|
||||
updatedAt: 1,
|
||||
source: 'directory'
|
||||
})
|
||||
expect(fs.existsSync(registryFile)).toBe(true)
|
||||
})
|
||||
|
||||
it('主文件损坏时从备份恢复,并把损坏现场另存', () => {
|
||||
const root = tempRoot()
|
||||
const registryFile = path.join(root, 'registry.json')
|
||||
const seed = new ExtensionRegistry({ registryFile })
|
||||
seed.upsert(record('com.example.a', { enabled: true, grantedPermissions: ['storage'] }))
|
||||
// 再写一次,让上一版内容进入备份;备份天然落后一版。
|
||||
seed.upsert(record('com.example.b'))
|
||||
expect(
|
||||
JSON.parse(fs.readFileSync(`${registryFile}.bak`, 'utf8')).extensions.map(
|
||||
(item: { id: string }) => item.id
|
||||
)
|
||||
).toEqual(['com.example.a'])
|
||||
|
||||
fs.writeFileSync(registryFile, '{"version":1,"extensions":[{"id":"com.example.a"', 'utf8')
|
||||
|
||||
const recovered = new ExtensionRegistry({ registryFile })
|
||||
const health = recovered.getHealth()
|
||||
expect(health.state).toBe('recovered-from-backup')
|
||||
expect(health.corruptFile).toBeTruthy()
|
||||
// 恢复到备份那一版:最后一次写入丢失;启用状态与授权按安全策略收回。
|
||||
expect(recovered.list().map((item) => item.id)).toEqual(['com.example.a'])
|
||||
expect(recovered.get('com.example.a')?.enabled).toBe(false)
|
||||
expect(recovered.get('com.example.a')?.grantedPermissions).toEqual([])
|
||||
// 主文件应已被备份内容修好。
|
||||
expect(() => JSON.parse(fs.readFileSync(registryFile, 'utf8'))).not.toThrow()
|
||||
const corruptFiles = fs.readdirSync(root).filter((name) => name.includes('.corrupt-'))
|
||||
expect(corruptFiles).toHaveLength(1)
|
||||
expect(fs.readFileSync(path.join(root, corruptFiles[0]), 'utf8')).toContain('com.example.a')
|
||||
})
|
||||
|
||||
it('恢复后继续写入,备份里不会出现损坏内容', () => {
|
||||
const root = tempRoot()
|
||||
const registryFile = path.join(root, 'registry.json')
|
||||
const seed = new ExtensionRegistry({ registryFile })
|
||||
seed.upsert(record('com.example.a', { enabled: true }))
|
||||
seed.upsert(record('com.example.b'))
|
||||
|
||||
fs.writeFileSync(registryFile, 'not-json', 'utf8')
|
||||
const recovered = new ExtensionRegistry({ registryFile })
|
||||
recovered.upsert(record('com.example.c'))
|
||||
|
||||
const backupText = fs.readFileSync(`${registryFile}.bak`, 'utf8')
|
||||
expect(backupText).not.toContain('not-json')
|
||||
expect(() => JSON.parse(backupText)).not.toThrow()
|
||||
expect(JSON.parse(backupText).extensions.map((item: { id: string }) => item.id)).not.toContain(
|
||||
'com.example.c'
|
||||
)
|
||||
})
|
||||
|
||||
it('主文件与备份都损坏时按目录扫描重建,且全部为未启用无授权', () => {
|
||||
const root = tempRoot()
|
||||
const registryFile = path.join(root, 'registry.json')
|
||||
fs.ensureDirSync(root)
|
||||
fs.writeFileSync(registryFile, 'broken', 'utf8')
|
||||
fs.writeFileSync(`${registryFile}.bak`, 'also-broken', 'utf8')
|
||||
|
||||
const recoveryCalls: number[] = []
|
||||
const registry = new ExtensionRegistry({
|
||||
registryFile,
|
||||
recover: () => {
|
||||
recoveryCalls.push(1)
|
||||
return [
|
||||
record('com.example.a', { enabled: true, grantedPermissions: ['wechat.send.text'] }),
|
||||
record('com.example.b', { enabled: true, grantedPermissions: ['storage'] })
|
||||
]
|
||||
}
|
||||
})
|
||||
|
||||
const list = registry.list()
|
||||
expect(recoveryCalls).toHaveLength(1)
|
||||
expect(registry.getHealth().state).toBe('recovered-by-scan')
|
||||
expect(list).toHaveLength(2)
|
||||
for (const item of list) {
|
||||
expect(item.enabled).toBe(false)
|
||||
expect(item.grantedPermissions).toEqual([])
|
||||
}
|
||||
})
|
||||
|
||||
it('主文件与备份都损坏且没有重建来源时拒绝写入,保留现场', () => {
|
||||
const root = tempRoot()
|
||||
const registryFile = path.join(root, 'registry.json')
|
||||
fs.ensureDirSync(root)
|
||||
fs.writeFileSync(registryFile, 'broken', 'utf8')
|
||||
fs.writeFileSync(`${registryFile}.bak`, 'also-broken', 'utf8')
|
||||
|
||||
const registry = new ExtensionRegistry({ registryFile })
|
||||
expect(registry.getHealth().state).toBe('unreadable')
|
||||
expect(registry.list()).toEqual([])
|
||||
expect(() => registry.upsert(record('com.example.a'))).toThrowError(/损坏/)
|
||||
|
||||
// 现场必须还在:损坏原文不能被空状态覆盖。
|
||||
expect(fs.readFileSync(registryFile, 'utf8')).toBe('broken')
|
||||
expect(
|
||||
fs.readdirSync(root).filter((name) => name.includes('.corrupt-')).length
|
||||
).toBeGreaterThanOrEqual(1)
|
||||
})
|
||||
|
||||
it('结构合法但记录不合法的文件按损坏处理', () => {
|
||||
const root = tempRoot()
|
||||
const registryFile = path.join(root, 'registry.json')
|
||||
fs.ensureDirSync(root)
|
||||
fs.writeJsonSync(registryFile, {
|
||||
version: 1,
|
||||
extensions: [{ id: 'not a valid id', version: '1.0.0' }]
|
||||
})
|
||||
const registry = new ExtensionRegistry({ registryFile })
|
||||
expect(registry.list()).toEqual([])
|
||||
expect(registry.getHealth().state).toBe('unreadable')
|
||||
})
|
||||
|
||||
it('写入失败时内存状态回滚,不留下半写的主文件', () => {
|
||||
const root = tempRoot()
|
||||
const registryFile = path.join(root, 'registry.json')
|
||||
const seed = new ExtensionRegistry({ registryFile })
|
||||
seed.upsert(record('com.example.a'))
|
||||
|
||||
const before = fs.readFileSync(registryFile, 'utf8')
|
||||
// 用同名的目录占住临时文件路径,让 writeFileSync 必然失败。
|
||||
fs.mkdirSync(`${registryFile}.tmp`)
|
||||
|
||||
const broken = new ExtensionRegistry({ registryFile })
|
||||
expect(() => broken.upsert(record('com.example.b'))).toThrow()
|
||||
expect(broken.list().map((item) => item.id)).toEqual(['com.example.a'])
|
||||
expect(fs.readFileSync(registryFile, 'utf8')).toBe(before)
|
||||
})
|
||||
|
||||
it('从旧备份恢复时一律降级为未启用、无授权', () => {
|
||||
const root = tempRoot()
|
||||
const registryFile = path.join(root, 'registry.json')
|
||||
const seed = new ExtensionRegistry({ registryFile })
|
||||
seed.upsert(
|
||||
record('com.example.a', { enabled: true, grantedPermissions: ['wechat.send.text'] })
|
||||
)
|
||||
seed.upsert(record('com.example.b', { enabled: true, grantedPermissions: ['storage'] }))
|
||||
|
||||
fs.writeFileSync(registryFile, '{broken', 'utf8')
|
||||
|
||||
const recovered = new ExtensionRegistry({ registryFile })
|
||||
expect(recovered.getHealth().state).toBe('recovered-from-backup')
|
||||
// 备份里是 enabled=true + 发送权限,恢复后必须全部收回。
|
||||
for (const item of recovered.list()) {
|
||||
expect(item.enabled).toBe(false)
|
||||
expect(item.grantedPermissions).toEqual([])
|
||||
// 身份与版本保留,配置目录不受影响。
|
||||
expect(item.version).toBe('1.0.0')
|
||||
}
|
||||
})
|
||||
|
||||
it('恢复标记持久化,重启后仍然提示', () => {
|
||||
const root = tempRoot()
|
||||
const registryFile = path.join(root, 'registry.json')
|
||||
const seed = new ExtensionRegistry({ registryFile })
|
||||
seed.upsert(record('com.example.a', { enabled: true }))
|
||||
seed.upsert(record('com.example.b'))
|
||||
fs.writeFileSync(registryFile, '{broken', 'utf8')
|
||||
|
||||
const first = new ExtensionRegistry({ registryFile })
|
||||
expect(first.getHealth().state).toBe('recovered-from-backup')
|
||||
|
||||
// 重新构造实例等价于重启软件:提示不能消失。
|
||||
const second = new ExtensionRegistry({ registryFile })
|
||||
expect(second.getHealth().state).toBe('recovered-from-backup')
|
||||
expect(second.get('com.example.a')?.enabled).toBe(false)
|
||||
|
||||
expect(second.acknowledgeRecovery()).toBe(true)
|
||||
expect(second.getHealth().state).toBe('ok')
|
||||
const third = new ExtensionRegistry({ registryFile })
|
||||
expect(third.getHealth().state).toBe('ok')
|
||||
})
|
||||
|
||||
it('恢复后用户重新启用的扩展不会被下一次重启自动恢复成启用', () => {
|
||||
const root = tempRoot()
|
||||
const registryFile = path.join(root, 'registry.json')
|
||||
const seed = new ExtensionRegistry({ registryFile })
|
||||
seed.upsert(record('com.example.a', { enabled: true }))
|
||||
seed.upsert(record('com.example.b'))
|
||||
// 再写一次,让备份里同时包含 a 与 b(备份天然落后一版)。
|
||||
seed.upsert(record('com.example.c'))
|
||||
fs.writeFileSync(registryFile, '{broken', 'utf8')
|
||||
|
||||
const recovered = new ExtensionRegistry({ registryFile })
|
||||
recovered.setEnabled('com.example.a', true)
|
||||
// 用户只启用了 a,b 保持停用;恢复提示仍在。
|
||||
expect(recovered.getHealth().state).toBe('recovered-from-backup')
|
||||
|
||||
const restarted = new ExtensionRegistry({ registryFile })
|
||||
expect(restarted.get('com.example.a')?.enabled).toBe(true)
|
||||
expect(restarted.get('com.example.b')?.enabled).toBe(false)
|
||||
})
|
||||
|
||||
it('未发生损坏时旧用户的启用状态与授权原样保留', () => {
|
||||
const root = tempRoot()
|
||||
const registryFile = path.join(root, 'registry.json')
|
||||
const seed = new ExtensionRegistry({ registryFile })
|
||||
seed.upsert(
|
||||
record('com.example.a', { enabled: true, grantedPermissions: ['wechat.send.text'] })
|
||||
)
|
||||
|
||||
const restarted = new ExtensionRegistry({ registryFile })
|
||||
expect(restarted.getHealth().state).toBe('ok')
|
||||
expect(restarted.get('com.example.a')?.enabled).toBe(true)
|
||||
expect(restarted.get('com.example.a')?.grantedPermissions).toEqual(['wechat.send.text'])
|
||||
})
|
||||
|
||||
it('来源字段按白名单解析,未知值归为 directory', () => {
|
||||
const root = tempRoot()
|
||||
const registryFile = path.join(root, 'registry.json')
|
||||
fs.ensureDirSync(root)
|
||||
fs.writeJsonSync(registryFile, {
|
||||
version: 1,
|
||||
extensions: [
|
||||
{
|
||||
id: 'com.example.a',
|
||||
version: '1.0.0',
|
||||
apiVersion: '1',
|
||||
enabled: false,
|
||||
grantedPermissions: [],
|
||||
source: 'template',
|
||||
templateId: 'keyword-bot',
|
||||
templateVersion: '1.0.0'
|
||||
},
|
||||
{
|
||||
id: 'com.example.b',
|
||||
version: '1.0.0',
|
||||
apiVersion: '1',
|
||||
enabled: false,
|
||||
grantedPermissions: [],
|
||||
source: 'evil-source'
|
||||
}
|
||||
]
|
||||
})
|
||||
const registry = new ExtensionRegistry({ registryFile })
|
||||
expect(registry.get('com.example.a')?.source).toBe('template')
|
||||
expect(registry.get('com.example.a')?.templateId).toBe('keyword-bot')
|
||||
expect(registry.get('com.example.b')?.source).toBe('directory')
|
||||
})
|
||||
})
|
||||
|
||||
function record(
|
||||
id: string,
|
||||
overrides: Partial<{
|
||||
enabled: boolean
|
||||
grantedPermissions: Array<'storage' | 'messages.subscribe' | 'wechat.send.text'>
|
||||
}> = {}
|
||||
): {
|
||||
id: string
|
||||
version: string
|
||||
apiVersion: string
|
||||
enabled: boolean
|
||||
grantedPermissions: Array<'storage' | 'messages.subscribe' | 'wechat.send.text'>
|
||||
installedAt: number
|
||||
updatedAt: number
|
||||
source: 'directory'
|
||||
} {
|
||||
return {
|
||||
id,
|
||||
version: '1.0.0',
|
||||
apiVersion: '1',
|
||||
enabled: overrides.enabled ?? false,
|
||||
grantedPermissions: overrides.grantedPermissions ?? [],
|
||||
installedAt: 1,
|
||||
updatedAt: 1,
|
||||
source: 'directory'
|
||||
}
|
||||
}
|
||||
|
||||
describe('extension storage', () => {
|
||||
it('按扩展隔离键空间并支持删除', () => {
|
||||
const root = tempRoot()
|
||||
@@ -87,6 +370,116 @@ describe('extension storage', () => {
|
||||
const storage = new ExtensionStorage({ dataRoot: tempRoot(), maxValueBytes: 32 })
|
||||
expect(() => storage.set('com.example.a', 'big', 'x'.repeat(64))).toThrowError(/上限/)
|
||||
})
|
||||
|
||||
it('20 条规则写入后换实例仍完整读回', () => {
|
||||
const dataRoot = tempRoot()
|
||||
const rules = Array.from({ length: 20 }, (_, index) => ({
|
||||
id: `rule-${index}`,
|
||||
keyword: `关键词${index}`,
|
||||
reply: `回复${index}`
|
||||
}))
|
||||
const first = new ExtensionStorage({ dataRoot })
|
||||
first.set('com.example.keyword-bot', 'rules', rules)
|
||||
|
||||
const second = new ExtensionStorage({ dataRoot })
|
||||
expect(second.get('com.example.keyword-bot', 'rules')).toEqual(rules)
|
||||
expect(second.health('com.example.keyword-bot').state).toBe('ok')
|
||||
})
|
||||
|
||||
it('主文件损坏时从备份恢复,20 条规则不丢', () => {
|
||||
const dataRoot = tempRoot()
|
||||
const rules = Array.from({ length: 20 }, (_, index) => ({ id: `rule-${index}` }))
|
||||
const first = new ExtensionStorage({ dataRoot })
|
||||
first.set('com.example.keyword-bot', 'rules', rules)
|
||||
// 再写一次,让含 20 条规则的内容进入备份。
|
||||
first.set('com.example.keyword-bot', 'enabled', true)
|
||||
|
||||
const filePath = first.filePath('com.example.keyword-bot')
|
||||
fs.writeFileSync(filePath, '{"version":1,"values":{"rules":[', 'utf8')
|
||||
|
||||
const recovered = new ExtensionStorage({ dataRoot })
|
||||
// 恢复后未确认前不给读:否则运行中的机器人会拿着旧配置继续回复。
|
||||
expect(() => recovered.get('com.example.keyword-bot', 'rules')).toThrowError(/确认/)
|
||||
expect(recovered.health('com.example.keyword-bot').state).toBe('recovered-from-backup')
|
||||
|
||||
recovered.acknowledge('com.example.keyword-bot')
|
||||
expect(recovered.get('com.example.keyword-bot', 'rules')).toEqual(rules)
|
||||
|
||||
const corruptFiles = fs
|
||||
.readdirSync(path.dirname(filePath))
|
||||
.filter((name) => name.includes('.corrupt-'))
|
||||
expect(corruptFiles).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('主文件与备份都损坏时停止写入并保留现场', () => {
|
||||
const dataRoot = tempRoot()
|
||||
const storage = new ExtensionStorage({ dataRoot })
|
||||
storage.set('com.example.a', 'rules', [1, 2, 3])
|
||||
storage.set('com.example.a', 'enabled', true)
|
||||
|
||||
const filePath = storage.filePath('com.example.a')
|
||||
fs.writeFileSync(filePath, 'broken', 'utf8')
|
||||
fs.writeFileSync(`${filePath}.bak`, 'also-broken', 'utf8')
|
||||
|
||||
const broken = new ExtensionStorage({ dataRoot })
|
||||
expect(() => broken.get('com.example.a', 'rules')).toThrowError(/损坏/)
|
||||
expect(broken.health('com.example.a').state).toBe('unrecovered')
|
||||
// 未处理损坏状态时不允许写入,否则会把现场覆盖成空配置。
|
||||
expect(() => broken.set('com.example.a', 'enabled', false)).toThrowError(/损坏/)
|
||||
expect(fs.readFileSync(filePath, 'utf8')).toBe('broken')
|
||||
})
|
||||
|
||||
it('重置后恢复可写,且损坏现场仍在', () => {
|
||||
const dataRoot = tempRoot()
|
||||
const storage = new ExtensionStorage({ dataRoot })
|
||||
storage.set('com.example.a', 'rules', [1])
|
||||
storage.set('com.example.a', 'enabled', true)
|
||||
|
||||
const filePath = storage.filePath('com.example.a')
|
||||
fs.writeFileSync(filePath, 'broken', 'utf8')
|
||||
fs.writeFileSync(`${filePath}.bak`, 'also-broken', 'utf8')
|
||||
|
||||
const broken = new ExtensionStorage({ dataRoot })
|
||||
expect(broken.health('com.example.a').state).toBe('unrecovered')
|
||||
broken.reset('com.example.a')
|
||||
expect(broken.health('com.example.a').state).toBe('ok')
|
||||
broken.set('com.example.a', 'enabled', true)
|
||||
expect(broken.get('com.example.a', 'enabled')).toBe(true)
|
||||
|
||||
expect(
|
||||
fs.readdirSync(path.dirname(filePath)).filter((name) => name.includes('.corrupt-'))
|
||||
).not.toHaveLength(0)
|
||||
})
|
||||
|
||||
it('一个扩展的损坏不影响另一个扩展', () => {
|
||||
const dataRoot = tempRoot()
|
||||
const storage = new ExtensionStorage({ dataRoot })
|
||||
storage.set('com.example.a', 'rules', ['a'])
|
||||
storage.set('com.example.b', 'rules', ['b'])
|
||||
|
||||
fs.writeFileSync(storage.filePath('com.example.a'), 'broken', 'utf8')
|
||||
|
||||
const next = new ExtensionStorage({ dataRoot })
|
||||
expect(next.health('com.example.a').state).toBe('unrecovered')
|
||||
expect(next.health('com.example.b').state).toBe('ok')
|
||||
expect(next.get('com.example.b', 'rules')).toEqual(['b'])
|
||||
expect(() => next.set('com.example.b', 'rules', ['b2'])).not.toThrow()
|
||||
})
|
||||
|
||||
it('写入失败时旧配置保持完整', () => {
|
||||
const dataRoot = tempRoot()
|
||||
const storage = new ExtensionStorage({ dataRoot })
|
||||
storage.set('com.example.a', 'rules', ['原始规则'])
|
||||
|
||||
const filePath = storage.filePath('com.example.a')
|
||||
const before = fs.readFileSync(filePath, 'utf8')
|
||||
// 同名目录占住临时文件路径。
|
||||
fs.mkdirSync(`${filePath}.tmp`)
|
||||
|
||||
expect(() => storage.set('com.example.a', 'rules', ['新规则'])).toThrow()
|
||||
expect(fs.readFileSync(filePath, 'utf8')).toBe(before)
|
||||
expect(new ExtensionStorage({ dataRoot }).get('com.example.a', 'rules')).toEqual(['原始规则'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('extension log store', () => {
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
import { createRequire } from 'node:module'
|
||||
import fs from 'fs-extra'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { ExtensionTemplateCatalog } from '../../src/main/extensions/extension-template-catalog'
|
||||
import type { ExtensionRegistryRecord } from '../../src/main/extensions/extension-registry'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const {
|
||||
buildTemplates
|
||||
}: {
|
||||
buildTemplates: (options?: Record<string, unknown>) => unknown
|
||||
} = require('../../scripts/build-extension-templates.cjs')
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
function tempRoot(): string {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-catalog-'))
|
||||
roots.push(root)
|
||||
return root
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) fs.removeSync(root)
|
||||
})
|
||||
|
||||
interface Harness {
|
||||
root: string
|
||||
catalog: ExtensionTemplateCatalog
|
||||
records: Map<string, ExtensionRegistryRecord>
|
||||
}
|
||||
|
||||
function setup(
|
||||
options: { records?: ExtensionRegistryRecord[]; platform?: NodeJS.Platform } = {}
|
||||
): Harness {
|
||||
const work = tempRoot()
|
||||
const sourceRoot = path.join(work, 'examples')
|
||||
fs.copySync(path.join(process.cwd(), 'examples/extensions'), sourceRoot)
|
||||
const templateRoot = path.join(work, 'templates')
|
||||
buildTemplates({
|
||||
sourceRoot,
|
||||
outputDir: templateRoot,
|
||||
lockFile: path.join(work, 'lock.json')
|
||||
})
|
||||
|
||||
const records = new Map<string, ExtensionRegistryRecord>()
|
||||
for (const record of options.records ?? []) records.set(record.id, record)
|
||||
|
||||
const catalog = new ExtensionTemplateCatalog({
|
||||
templateRoot,
|
||||
getRecord: (id) => records.get(id),
|
||||
resolveInstallDir: (id) => path.join(work, 'extensions', id),
|
||||
platform: options.platform ?? 'darwin',
|
||||
probePython: () => '/usr/bin/python3',
|
||||
probeChrome: () => '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'
|
||||
})
|
||||
return { root: work, catalog, records }
|
||||
}
|
||||
|
||||
function record(overrides: Partial<ExtensionRegistryRecord>): ExtensionRegistryRecord {
|
||||
return {
|
||||
id: 'com.example.keyword-bot',
|
||||
version: '1.0.1',
|
||||
apiVersion: '1',
|
||||
enabled: false,
|
||||
grantedPermissions: [],
|
||||
installedAt: 1,
|
||||
updatedAt: 1,
|
||||
source: 'template',
|
||||
templateId: 'keyword-bot',
|
||||
templateVersion: '1.0.1',
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
describe('官方模板目录', () => {
|
||||
it('列出两个模板,未安装时状态为 not-installed', async () => {
|
||||
const { catalog } = setup()
|
||||
const list = await catalog.list()
|
||||
expect(list.map((item) => item.template.templateId).sort()).toEqual([
|
||||
'douyin-sender',
|
||||
'keyword-bot'
|
||||
])
|
||||
expect(list.every((item) => item.state === 'not-installed')).toBe(true)
|
||||
// 版本来自 manifest,不是硬编码。
|
||||
const keyword = list.find((item) => item.template.templateId === 'keyword-bot')
|
||||
expect(keyword?.template.version).toBe('1.0.1')
|
||||
})
|
||||
|
||||
it('已安装同版本显示 installed,本地版本更新时也视为已安装', async () => {
|
||||
const { catalog } = setup({
|
||||
records: [
|
||||
record({ version: '1.0.1' }),
|
||||
record({ id: 'com.example.douyin-sender', version: '9.9.9', templateId: 'douyin-sender' })
|
||||
]
|
||||
})
|
||||
const list = await catalog.list()
|
||||
expect(list.find((item) => item.template.templateId === 'keyword-bot')?.state).toBe('installed')
|
||||
expect(list.find((item) => item.template.templateId === 'douyin-sender')?.state).toBe(
|
||||
'installed'
|
||||
)
|
||||
})
|
||||
|
||||
it('模板版本更高时显示 update-available', async () => {
|
||||
const { catalog } = setup({ records: [record({ version: '0.9.0' })] })
|
||||
const list = await catalog.list()
|
||||
expect(list.find((item) => item.template.templateId === 'keyword-bot')?.state).toBe(
|
||||
'update-available'
|
||||
)
|
||||
})
|
||||
|
||||
it('同 ID 的非模板扩展显示 conflict,不会自动接管', async () => {
|
||||
const { catalog } = setup({ records: [record({ source: 'directory' })] })
|
||||
const list = await catalog.list()
|
||||
const keyword = list.find((item) => item.template.templateId === 'keyword-bot')
|
||||
expect(keyword?.state).toBe('conflict')
|
||||
expect(keyword?.message).toContain('不会自动替换')
|
||||
})
|
||||
|
||||
it('平台不在支持范围时显示 unsupported', async () => {
|
||||
const { catalog } = setup({ platform: 'linux' })
|
||||
const list = await catalog.list()
|
||||
expect(list.every((item) => item.state === 'unsupported')).toBe(true)
|
||||
})
|
||||
|
||||
it('ZIP 被替换后状态变为 damaged,且 resolveZip 拒绝安装', async () => {
|
||||
const { root } = setup()
|
||||
const zipPath = path.join(root, 'templates', 'keyword-bot-1.0.1.zip')
|
||||
const original = fs.readFileSync(zipPath)
|
||||
fs.writeFileSync(zipPath, Buffer.concat([original, Buffer.from('tampered')]))
|
||||
|
||||
// 新实例避免读到缓存的索引状态。
|
||||
const fresh = new ExtensionTemplateCatalog({
|
||||
templateRoot: path.join(root, 'templates'),
|
||||
getRecord: () => undefined,
|
||||
resolveInstallDir: (id) => path.join(root, 'extensions', id),
|
||||
platform: 'darwin',
|
||||
probePython: () => '/usr/bin/python3',
|
||||
probeChrome: () => '/usr/bin/chrome'
|
||||
})
|
||||
const list = await fresh.list()
|
||||
expect(list.find((item) => item.template.templateId === 'keyword-bot')?.state).toBe('damaged')
|
||||
await expect(fresh.resolveZip('keyword-bot')).rejects.toMatchObject({
|
||||
code: 'EXTENSION_INSTALL_FAILED'
|
||||
})
|
||||
})
|
||||
|
||||
it('依赖检测区分「必填缺失」与「安装后再检测」', async () => {
|
||||
const { catalog } = setup()
|
||||
const list = await catalog.list()
|
||||
const douyin = list.find((item) => item.template.templateId === 'douyin-sender')
|
||||
const scriptCheck = douyin?.dependencies.checks.find((check) => check.id === 'externalScript')
|
||||
// 未安装时不判定为缺失,只提示「安装后检测」。
|
||||
expect(scriptCheck?.ok).toBe(false)
|
||||
expect(scriptCheck?.blocking).toBe(false)
|
||||
expect(scriptCheck?.detail).toContain('安装后检测')
|
||||
// Python / Chrome 已由注入的探测返回可用。
|
||||
expect(douyin?.dependencies.checks.find((check) => check.id === 'python')?.ok).toBe(true)
|
||||
expect(douyin?.dependencies.ready).toBe(true)
|
||||
|
||||
const keyword = list.find((item) => item.template.templateId === 'keyword-bot')
|
||||
expect(keyword?.dependencies.checks).toEqual([])
|
||||
expect(keyword?.dependencies.ready).toBe(true)
|
||||
})
|
||||
|
||||
it('已安装但缺少解析脚本时,依赖为未就绪', async () => {
|
||||
const { catalog, records, root } = setup({
|
||||
records: [
|
||||
record({ id: 'com.example.douyin-sender', version: '1.0.5', templateId: 'douyin-sender' })
|
||||
]
|
||||
})
|
||||
records.set(
|
||||
'com.example.douyin-sender',
|
||||
record({
|
||||
id: 'com.example.douyin-sender',
|
||||
version: '1.0.5',
|
||||
templateId: 'douyin-sender'
|
||||
})
|
||||
)
|
||||
fs.ensureDirSync(path.join(root, 'extensions', 'com.example.douyin-sender'))
|
||||
const list = await catalog.list()
|
||||
const douyin = list.find((item) => item.template.templateId === 'douyin-sender')
|
||||
const scriptCheck = douyin?.dependencies.checks.find((check) => check.id === 'externalScript')
|
||||
expect(scriptCheck?.ok).toBe(false)
|
||||
expect(scriptCheck?.blocking).toBe(true)
|
||||
expect(douyin?.dependencies.ready).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,145 @@
|
||||
import { createRequire } from 'node:module'
|
||||
import fs from 'fs-extra'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { Open } from 'unzipper'
|
||||
import { createExtensionPaths } from '../../src/main/extensions/extension-paths'
|
||||
import { ExtensionRegistry } from '../../src/main/extensions/extension-registry'
|
||||
import { ExtensionInstaller } from '../../src/main/extensions/extension-installer'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const {
|
||||
buildTemplates
|
||||
}: {
|
||||
buildTemplates: (options?: Record<string, unknown>) => {
|
||||
templates: Array<{ templateId: string; version: string; sha256: string; file: string }>
|
||||
warnings: string[]
|
||||
}
|
||||
} = require('../../scripts/build-extension-templates.cjs')
|
||||
|
||||
const roots: string[] = []
|
||||
|
||||
function tempRoot(): string {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'tm-templates-'))
|
||||
roots.push(root)
|
||||
return root
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of roots.splice(0)) fs.removeSync(root)
|
||||
})
|
||||
|
||||
/** 复制真实的 examples 到临时目录,避免测试写仓库里的 lock 文件。 */
|
||||
function stageExamples(): { sourceRoot: string; lockFile: string } {
|
||||
const root = tempRoot()
|
||||
const sourceRoot = path.join(root, 'examples')
|
||||
fs.copySync(path.join(process.cwd(), 'examples/extensions'), sourceRoot)
|
||||
return { sourceRoot, lockFile: path.join(root, 'template-lock.json') }
|
||||
}
|
||||
|
||||
describe('官方模板构建', () => {
|
||||
it('产出两个模板与索引,索引指向真实文件', () => {
|
||||
const { sourceRoot, lockFile } = stageExamples()
|
||||
const outputDir = path.join(tempRoot(), 'out')
|
||||
const result = buildTemplates({ sourceRoot, outputDir, lockFile })
|
||||
|
||||
expect(result.templates.map((item) => item.templateId).sort()).toEqual([
|
||||
'douyin-sender',
|
||||
'keyword-bot'
|
||||
])
|
||||
const index = fs.readJsonSync(path.join(outputDir, 'index.json'))
|
||||
expect(index.version).toBe(1)
|
||||
expect(index.templates).toHaveLength(2)
|
||||
for (const template of index.templates) {
|
||||
expect(fs.existsSync(path.join(outputDir, template.file))).toBe(true)
|
||||
expect(template.sha256).toMatch(/^[a-f0-9]{64}$/)
|
||||
}
|
||||
})
|
||||
|
||||
it('两次构建字节一致(确定性 ZIP)', () => {
|
||||
const { sourceRoot, lockFile } = stageExamples()
|
||||
const first = buildTemplates({ sourceRoot, outputDir: path.join(tempRoot(), 'a'), lockFile })
|
||||
const second = buildTemplates({ sourceRoot, outputDir: path.join(tempRoot(), 'b'), lockFile })
|
||||
expect(second.templates.map((item) => item.sha256)).toEqual(
|
||||
first.templates.map((item) => item.sha256)
|
||||
)
|
||||
})
|
||||
|
||||
it('私有脚本与缓存文件不会进入发布包', async () => {
|
||||
const { sourceRoot, lockFile } = stageExamples()
|
||||
// 模拟开发者本机存在被 gitignore 的私有脚本与缓存。
|
||||
const privateScript = path.join(sourceRoot, 'douyin-sender/scripts/douyin.py')
|
||||
fs.ensureDirSync(path.dirname(privateScript))
|
||||
fs.writeFileSync(privateScript, '# private')
|
||||
fs.ensureDirSync(path.join(sourceRoot, 'douyin-sender/scripts/__pycache__'))
|
||||
fs.writeFileSync(path.join(sourceRoot, 'douyin-sender/scripts/__pycache__/x.pyc'), 'x')
|
||||
fs.writeFileSync(path.join(sourceRoot, 'keyword-bot/.DS_Store'), 'x')
|
||||
|
||||
const outputDir = path.join(tempRoot(), 'out')
|
||||
buildTemplates({ sourceRoot, outputDir, lockFile })
|
||||
const zipPath = path.join(outputDir, 'douyin-sender-1.0.5.zip')
|
||||
const archive = await Open.file(zipPath)
|
||||
const names = archive.files.map((file) => file.path)
|
||||
expect(names).not.toContain('scripts/douyin.py')
|
||||
expect(names.some((name) => name.includes('__pycache__'))).toBe(false)
|
||||
|
||||
const keyword = await Open.file(path.join(outputDir, 'keyword-bot-1.0.1.zip'))
|
||||
expect(keyword.files.map((file) => file.path)).not.toContain('.DS_Store')
|
||||
})
|
||||
|
||||
it('入口文件缺失时构建失败', () => {
|
||||
const { sourceRoot, lockFile } = stageExamples()
|
||||
fs.removeSync(path.join(sourceRoot, 'keyword-bot/background/index.js'))
|
||||
expect(() =>
|
||||
buildTemplates({ sourceRoot, outputDir: path.join(tempRoot(), 'out'), lockFile })
|
||||
).toThrowError(/入口|不存在/)
|
||||
})
|
||||
|
||||
it('同版本内容变化被拒绝,升版本后放行', () => {
|
||||
const { sourceRoot, lockFile } = stageExamples()
|
||||
const outputDir = path.join(tempRoot(), 'out')
|
||||
buildTemplates({ sourceRoot, outputDir, lockFile })
|
||||
|
||||
// 改动内容但不升版本。
|
||||
const manifestPath = path.join(sourceRoot, 'keyword-bot/manifest.json')
|
||||
const manifest = fs.readJsonSync(manifestPath)
|
||||
fs.writeJsonSync(manifestPath, { ...manifest, description: '改了一句话' })
|
||||
expect(() => buildTemplates({ sourceRoot, outputDir, lockFile })).toThrowError(/内容已变化/)
|
||||
|
||||
// 升版本后放行。
|
||||
fs.writeJsonSync(manifestPath, { ...manifest, description: '改了一句话', version: '1.0.2' })
|
||||
const result = buildTemplates({ sourceRoot, outputDir, lockFile })
|
||||
expect(result.templates.some((item) => item.version === '1.0.2')).toBe(true)
|
||||
})
|
||||
|
||||
it('产物 ZIP 能被现有安装器直接安装', async () => {
|
||||
const { sourceRoot, lockFile } = stageExamples()
|
||||
const outputDir = path.join(tempRoot(), 'out')
|
||||
buildTemplates({ sourceRoot, outputDir, lockFile })
|
||||
|
||||
const userData = tempRoot()
|
||||
const paths = createExtensionPaths(userData)
|
||||
const registry = new ExtensionRegistry({ registryFile: paths.registryFile })
|
||||
const installer = new ExtensionInstaller({ paths, registry })
|
||||
|
||||
const zipPath = path.join(outputDir, 'keyword-bot-1.0.1.zip')
|
||||
const outcome = await installer.installFromPackage(zipPath, {
|
||||
appVersion: '2.6.0',
|
||||
source: 'template',
|
||||
template: { id: 'keyword-bot', version: '1.0.1' }
|
||||
})
|
||||
|
||||
expect(outcome.manifest.id).toBe('com.example.keyword-bot')
|
||||
expect(outcome.upgraded).toBe(false)
|
||||
const record = registry.get('com.example.keyword-bot')
|
||||
expect(record?.source).toBe('template')
|
||||
expect(record?.templateId).toBe('keyword-bot')
|
||||
expect(record?.templateVersion).toBe('1.0.1')
|
||||
// 安装不等于启用。
|
||||
expect(record?.enabled).toBe(false)
|
||||
expect(
|
||||
fs.existsSync(path.join(paths.installDir('com.example.keyword-bot'), 'ui/index.html'))
|
||||
).toBe(true)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,153 @@
|
||||
import { createRequire } from 'node:module'
|
||||
import path from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
const require = createRequire(import.meta.url)
|
||||
const MATCHER = path.join(process.cwd(), 'examples/extensions/keyword-bot/lib/matcher.js')
|
||||
const BACKGROUND = path.join(process.cwd(), 'examples/extensions/keyword-bot/background/index.js')
|
||||
|
||||
const { normalizeConfig } = require(MATCHER) as {
|
||||
normalizeConfig: (raw: unknown) => {
|
||||
executionMode: 'subscribe' | 'automation'
|
||||
enabled: boolean
|
||||
rules: Array<{ id: string; keyword: string; reply: string }>
|
||||
}
|
||||
}
|
||||
|
||||
interface FakeApi {
|
||||
storage: {
|
||||
get: (key: string) => Promise<unknown>
|
||||
set: (key: string, value: unknown) => Promise<void>
|
||||
}
|
||||
events: { on: (name: string, handler: (event: unknown) => unknown) => void }
|
||||
automation: { registerAction: (definition: Record<string, unknown>) => void }
|
||||
wechat: { send: (payload: Record<string, unknown>) => Promise<void> }
|
||||
log: { info: () => void; warn: () => void; error: () => void }
|
||||
}
|
||||
|
||||
function createApi(config: Record<string, unknown>): {
|
||||
api: FakeApi
|
||||
sends: Array<Record<string, unknown>>
|
||||
handlers: Map<string, (event: unknown) => unknown>
|
||||
getAction: () => Record<string, unknown> | null
|
||||
} {
|
||||
const sends: Array<Record<string, unknown>> = []
|
||||
const handlers = new Map<string, (event: unknown) => unknown>()
|
||||
let action: Record<string, unknown> | null = null
|
||||
const api: FakeApi = {
|
||||
storage: {
|
||||
get: async () => config,
|
||||
set: async () => undefined
|
||||
},
|
||||
events: {
|
||||
on: (name, handler) => handlers.set(name, handler)
|
||||
},
|
||||
automation: {
|
||||
registerAction: (definition) => {
|
||||
action = definition
|
||||
}
|
||||
},
|
||||
wechat: {
|
||||
send: async (payload) => {
|
||||
sends.push(payload)
|
||||
}
|
||||
},
|
||||
log: { info: () => undefined, warn: () => undefined, error: () => undefined }
|
||||
}
|
||||
return { api, sends, handlers, getAction: () => action }
|
||||
}
|
||||
|
||||
function loadBackground(): (api: FakeApi) => void {
|
||||
delete require.cache[require.resolve(BACKGROUND)]
|
||||
return require(BACKGROUND) as (api: FakeApi) => void
|
||||
}
|
||||
|
||||
const baseConfig = {
|
||||
enabled: true,
|
||||
executionMode: 'subscribe',
|
||||
rules: [{ id: 'r1', keyword: '你好', mode: 'contains', reply: '你好呀', enabled: true }],
|
||||
scope: { groups: [], includeDirect: true, requireMentionMe: false }
|
||||
}
|
||||
|
||||
const messageEvent = {
|
||||
eventId: 'evt-1',
|
||||
type: 'text',
|
||||
isSelf: false,
|
||||
conversationId: 'room@chatroom',
|
||||
conversationName: '测试群',
|
||||
senderId: 'wxid_peer',
|
||||
senderName: '张三',
|
||||
text: '你好',
|
||||
isGroup: true,
|
||||
mentionsMe: false,
|
||||
receivedAt: Date.now()
|
||||
}
|
||||
|
||||
describe('关键词机器人执行模式', () => {
|
||||
it('默认是订阅模式,非法值回落', () => {
|
||||
expect(normalizeConfig(undefined).executionMode).toBe('subscribe')
|
||||
expect(normalizeConfig({ executionMode: 'nonsense' }).executionMode).toBe('subscribe')
|
||||
expect(normalizeConfig({ executionMode: 'automation' }).executionMode).toBe('automation')
|
||||
})
|
||||
|
||||
it('订阅模式:事件路径回复一次,动作路径跳过', async () => {
|
||||
const activate = loadBackground()
|
||||
const harness = createApi(baseConfig)
|
||||
activate(harness.api as never)
|
||||
|
||||
const onMessage = harness.handlers.get('message.received')
|
||||
expect(onMessage).toBeTruthy()
|
||||
await onMessage?.(messageEvent)
|
||||
expect(harness.sends).toHaveLength(1)
|
||||
|
||||
const action = harness.getAction()
|
||||
expect(action).toBeTruthy()
|
||||
const result = (await (action!.handler as (input: unknown) => Promise<unknown>)({
|
||||
text: '你好'
|
||||
})) as { success: boolean; output?: { skipped?: string } }
|
||||
expect(result.success).toBe(true)
|
||||
expect(result.output?.skipped).toBe('subscribe-mode')
|
||||
})
|
||||
|
||||
it('自动化模式:事件路径不发送,动作路径给出回复', async () => {
|
||||
const activate = loadBackground()
|
||||
const harness = createApi({ ...baseConfig, executionMode: 'automation' })
|
||||
activate(harness.api as never)
|
||||
|
||||
const onMessage = harness.handlers.get('message.received')
|
||||
await onMessage?.(messageEvent)
|
||||
expect(harness.sends).toHaveLength(0)
|
||||
|
||||
const action = harness.getAction()
|
||||
const result = (await (action!.handler as (input: unknown) => Promise<unknown>)({
|
||||
text: '你好'
|
||||
})) as { success: boolean; reply?: { text: string }; output?: { matched?: boolean } }
|
||||
expect(result.success).toBe(true)
|
||||
expect(result.output?.matched).toBe(true)
|
||||
expect(result.reply?.text).toBe('你好呀')
|
||||
})
|
||||
|
||||
it('文本相同但事件不同,订阅模式各自回复', async () => {
|
||||
const activate = loadBackground()
|
||||
const harness = createApi({
|
||||
...baseConfig,
|
||||
rules: [
|
||||
{
|
||||
id: 'r1',
|
||||
keyword: '你好',
|
||||
mode: 'contains',
|
||||
reply: '你好呀',
|
||||
enabled: true,
|
||||
cooldownSeconds: 0
|
||||
}
|
||||
]
|
||||
})
|
||||
activate(harness.api as never)
|
||||
const onMessage = harness.handlers.get('message.received')
|
||||
|
||||
await onMessage?.({ ...messageEvent, eventId: 'evt-a' })
|
||||
await onMessage?.({ ...messageEvent, eventId: 'evt-b' })
|
||||
// 没有按文本去重:两条独立消息都应回复。
|
||||
expect(harness.sends).toHaveLength(2)
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user