@kioku-memory/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,248 @@
1
+ // OpenClaw 这个平台的 kioku setup 与 kioku doctor。
2
+ // 插件读本机文件里的服务地址与访问密钥(不放进 OpenClaw 的配置:那份配置会被 openclaw config get 打印出来);
3
+ // OpenClaw 自己的两项(记忆槽位、允许插件读对话)交给它的 openclaw config set 去改,不自己动它的配置文件
4
+
5
+ import { capture } from './command.mjs'
6
+ import { KiokuFailure } from './http.mjs'
7
+ import { listTools, removeToolCache, writeToolCache } from './mcp.mjs'
8
+ import { profileFile, readProfile, removeProfile, writeProfile } from './profile.mjs'
9
+ import { resolveTarget } from './target.mjs'
10
+
11
+ const PLUGIN = 'kioku'
12
+ const SOURCE = 'npm:@kioku-memory/openclaw'
13
+ // 允许插件读对话:第三方插件默认拿不到每轮的输入与回复,召回与会话摘要都要它
14
+ const ACCESS = `plugins.entries.${PLUGIN}.hooks.allowConversationAccess`
15
+ const SLOT = 'plugins.slots.memory'
16
+ // OpenClaw 自带的记忆插件,还原时选回它
17
+ const BUILTIN = 'memory-core'
18
+
19
+ // 命令以失败退出:output 是它打印的内容,只用来认是哪种失败,不打印(里面可能有别的配置)
20
+ class CommandFailed extends KiokuFailure {
21
+ constructor(args, output) {
22
+ super(`openclaw ${args.slice(0, 3).join(' ')} 没有成功`)
23
+ this.output = output
24
+ }
25
+ }
26
+
27
+ // 调 openclaw 命令。找不到这个命令时返回 null;失败(含超时)时抛 CommandFailed
28
+ async function openclaw(env, args) {
29
+ const result = await capture(env.KIOKU_OPENCLAW_BIN || 'openclaw', args, env, {
30
+ timeout: 60_000,
31
+ })
32
+ if (!result.found) return null
33
+ if (!result.ok) throw new CommandFailed(args, result.output)
34
+ return result.stdout
35
+ }
36
+
37
+ // 读 OpenClaw 的一项配置:null 是没有 openclaw 命令,undefined 是没读出来,否则是值(没设时是空字符串)
38
+ async function configValue(env, key) {
39
+ let out
40
+ try {
41
+ out = await openclaw(env, ['config', 'get', key, '--json'])
42
+ } catch (err) {
43
+ // 没设过的项它以失败退出,并说没有这个路径;别的失败(超时这类)不当成没设
44
+ return /not found/i.test(err?.output ?? '') ? '' : undefined
45
+ }
46
+ if (out === null) return null
47
+ const last = out.trim().split(/\r?\n/).at(-1)?.trim() ?? ''
48
+ try {
49
+ const value = JSON.parse(last)
50
+ return typeof value === 'string' || typeof value === 'boolean' ? String(value) : undefined
51
+ } catch {
52
+ return undefined
53
+ }
54
+ }
55
+
56
+ // 输出里的那个 JSON 对象:前面可能有几行提示,其中也可能带花括号,所以从每一个行首的花括号试
57
+ function jsonIn(out) {
58
+ for (const match of out.matchAll(/^\{/gm)) {
59
+ try {
60
+ return JSON.parse(out.slice(match.index))
61
+ } catch {
62
+ // 不是从这里开始的
63
+ }
64
+ }
65
+ return undefined
66
+ }
67
+
68
+ // 插件在 OpenClaw 里的状态:null 是没有 openclaw 命令,false 是没装,undefined 是没查出来
69
+ // (命令失败、输出读不懂),否则是 { enabled, loaded, slot }。没查出来不当成没装:照着没装去做会留下半截的配置
70
+ async function pluginState(env) {
71
+ let out
72
+ try {
73
+ out = await openclaw(env, ['plugins', 'inspect', PLUGIN, '--json'])
74
+ } catch (err) {
75
+ return /plugin not found/i.test(err?.output ?? '') ? false : undefined
76
+ }
77
+ if (out === null) return null
78
+ const plugin = jsonIn(out)?.plugin
79
+ if (plugin?.id !== PLUGIN) return undefined
80
+ return {
81
+ enabled: plugin.enabled === true,
82
+ loaded: plugin.status === 'loaded',
83
+ slot: plugin.memorySlotSelected === true,
84
+ }
85
+ }
86
+
87
+ // 让 OpenClaw 去掉一项配置;去不掉不算失败
88
+ async function removeSetting(env, key) {
89
+ try {
90
+ return (await openclaw(env, ['config', 'unset', key])) !== null
91
+ } catch {
92
+ return false
93
+ }
94
+ }
95
+
96
+ // 让 OpenClaw 改一项配置,改完读回来核对。返回 'done'、'no-openclaw' 或 'failed'。不抛错:
97
+ // 调用方这时多半已经把访问密钥写下了,不能让这里的失败看起来像什么都没写
98
+ async function applySetting(env, key, value) {
99
+ try {
100
+ if ((await openclaw(env, ['config', 'set', key, value])) === null) return 'no-openclaw'
101
+ return (await configValue(env, key)) === value ? 'done' : 'failed'
102
+ } catch {
103
+ return 'failed'
104
+ }
105
+ }
106
+
107
+ function manual(out, settings, state) {
108
+ out.write(
109
+ state === 'no-openclaw'
110
+ ? '没有找到 openclaw 命令,这几项要自己运行:\n'
111
+ : 'OpenClaw 的配置没有改成,这几项要自己运行:\n',
112
+ )
113
+ for (const [key, value] of settings) out.write(` openclaw config set ${key} ${value}\n`)
114
+ }
115
+
116
+ async function undo({ dryRun }, { env, out }) {
117
+ const profile = profileFile('openclaw', env)
118
+ const state = await pluginState(env)
119
+ // 只在记忆槽位现在选的是 kioku 时改回去:之后换成了别的插件的话,不去动它
120
+ const ours = Boolean(state && state.slot)
121
+ out.write(`${profile}:删掉\n`)
122
+ if (state === null) out.write('没有找到 openclaw 命令,OpenClaw 的配置没有动\n')
123
+ else {
124
+ out.write(`OpenClaw 的配置\n ${ACCESS}:去掉\n`)
125
+ if (ours) out.write(` ${SLOT} → ${BUILTIN}\n`)
126
+ else if (state === undefined) out.write(` ${SLOT}:没有查出来现在选的是什么\n`)
127
+ else out.write(` ${SLOT}:现在选的不是 kioku,不动\n`)
128
+ }
129
+ if (dryRun) {
130
+ out.write('没有写入(--dry-run)\n')
131
+ return 0
132
+ }
133
+ if (await removeProfile('openclaw', env)) out.write(`已删掉 ${profile}\n`)
134
+ else out.write(`${profile} 本来就没有\n`)
135
+ await removeToolCache('openclaw', env)
136
+ if (state !== null) {
137
+ // 不再允许插件读对话:插件还装着的话,留着这一项它照样拿得到每轮的输入与回复
138
+ const access = await configValue(env, ACCESS)
139
+ if (access !== '' && !(await removeSetting(env, ACCESS))) {
140
+ out.write(
141
+ `OpenClaw 里允许插件读对话的那一项没有去掉,要自己运行:\n openclaw config unset ${ACCESS}\n`,
142
+ )
143
+ }
144
+ }
145
+ if (ours) {
146
+ const result = await applySetting(env, SLOT, BUILTIN)
147
+ if (result === 'done') out.write('OpenClaw 改回用自带的记忆,重启网关生效。\n')
148
+ else manual(out, [[SLOT, BUILTIN]], result)
149
+ } else if (state === undefined) {
150
+ out.write(
151
+ `OpenClaw 的记忆槽位没有查出来(openclaw plugins inspect 失败了):用 openclaw config get ${SLOT} 看,还是 kioku 的话运行\n openclaw config set ${SLOT} ${BUILTIN}\n`,
152
+ )
153
+ }
154
+ out.write(`插件要另外卸载:openclaw plugins uninstall ${PLUGIN}\n`)
155
+ return 0
156
+ }
157
+
158
+ export async function setupOpenclaw(options, io) {
159
+ const { env, out } = io
160
+ if (options.undo) return undo(options, io)
161
+ const { url, key, saved } = await resolveTarget({ id: 'openclaw', name: 'OpenClaw' }, options, io)
162
+ const profile = profileFile('openclaw', env)
163
+ const same = Boolean(saved && saved.url === url && saved.key === key)
164
+ if (same) out.write(`${profile} 不用改\n`)
165
+ else out.write(`${profile}:写入服务地址与访问密钥(只给本人读写)\n`)
166
+ out.write(`OpenClaw 的配置\n ${ACCESS} → true\n ${SLOT} → ${PLUGIN}(装上插件之后)\n`)
167
+ if (options.dryRun) {
168
+ out.write('没有写入(--dry-run)\n')
169
+ return 0
170
+ }
171
+ if (!same) await writeProfile('openclaw', { url, key }, env)
172
+ // 工具清单先取一份留在本机:插件第一次登记工具时就有得用。取不到不算失败,插件自己会再取
173
+ if (options.check) {
174
+ try {
175
+ const tools = await listTools({ url, key })
176
+ // 一个工具都没有的回答不留:留下的话插件会当成新取到的清单用上一小时
177
+ if (tools.length) await writeToolCache('openclaw', { url, tools }, env)
178
+ } catch {
179
+ // 留给插件
180
+ }
181
+ }
182
+ // 访问密钥这时已经写下了:后面改 OpenClaw 的配置不成也不算失败,把要做的列出来
183
+ const todo = []
184
+ let result = await applySetting(env, ACCESS, 'true')
185
+ if (result !== 'done') todo.push([ACCESS, 'true'])
186
+ const state = result === 'no-openclaw' ? null : await pluginState(env)
187
+ // 槽位只在插件装上之后才选得了;装的时候 OpenClaw 自己会选上,这里只管装好之后被换走的
188
+ if (state && !state.slot) {
189
+ result = await applySetting(env, SLOT, PLUGIN)
190
+ if (result !== 'done') todo.push([SLOT, PLUGIN])
191
+ }
192
+ if (todo.length) {
193
+ out.write('地址与访问密钥已经写下。\n')
194
+ manual(out, todo, result)
195
+ } else if (state) {
196
+ out.write('OpenClaw 已配好,重启网关(openclaw gateway restart)后生效。\n')
197
+ } else {
198
+ out.write('地址与访问密钥已经写下。\n')
199
+ }
200
+ if (state === undefined) {
201
+ out.write(
202
+ '插件装了没有、记忆槽位选的是什么没有查出来(openclaw plugins inspect 失败了):用 kioku doctor openclaw 再看一次\n',
203
+ )
204
+ } else if (!state) {
205
+ out.write(`接下来装上插件:openclaw plugins install ${SOURCE}\n`)
206
+ if (todo.length) out.write('装好之后再运行一次 kioku setup openclaw。\n')
207
+ }
208
+ out.write(
209
+ '只在本机入口的对话里生效;外部渠道来的消息里没有长期记忆(自带的记忆工具也随槽位停用)。\n',
210
+ )
211
+ return 0
212
+ }
213
+
214
+ export async function inspectOpenclaw({ env }, { ok, warn, note }) {
215
+ const profile = await readProfile('openclaw', env).catch(() => null)
216
+ if (!profile) {
217
+ warn('没有 kioku setup openclaw 写下的地址与访问密钥,插件不会生效:运行 kioku setup openclaw')
218
+ }
219
+ const state = await pluginState(env)
220
+ if (state === null) {
221
+ note('没有找到 openclaw 命令,查不了它的配置:用 openclaw plugins inspect kioku 看')
222
+ return
223
+ }
224
+ if (state === undefined) {
225
+ warn(
226
+ 'OpenClaw 里的插件状态没有查出来(openclaw plugins inspect 失败了):用 openclaw plugins inspect kioku 看',
227
+ )
228
+ return
229
+ }
230
+ if (!state) {
231
+ warn(`OpenClaw 里没有装 kioku 的插件:openclaw plugins install ${SOURCE}`)
232
+ return
233
+ }
234
+ if (state.enabled && state.loaded) ok('OpenClaw 里装了 kioku 的插件')
235
+ else
236
+ warn('OpenClaw 里的 kioku 插件没有启用或没有加载成功:用 openclaw plugins inspect kioku 看原因')
237
+ if (state.slot) ok('OpenClaw 的记忆槽位选的是 kioku,自带的记忆工具已停用')
238
+ else warn('OpenClaw 的记忆槽位选的不是 kioku:运行 kioku setup openclaw')
239
+ const access = await configValue(env, ACCESS)
240
+ if (access === 'true') ok('OpenClaw 允许 kioku 读对话(召回与会话摘要要用)')
241
+ else if (access === undefined)
242
+ warn('OpenClaw 允不允许 kioku 读对话没有查出来(openclaw config get 失败了)')
243
+ else warn('OpenClaw 没有允许 kioku 读对话,召回与会话摘要不会生效:运行 kioku setup openclaw')
244
+ note('只在本机入口的对话里生效;外部渠道来的消息里不注入、不上报、不给工具')
245
+ note(
246
+ '工作区里的 MEMORY.md 有内容时 OpenClaw 仍会放进提示:用 kioku import --from openclaw 迁走后清空它',
247
+ )
248
+ }
package/lib/pi.mjs ADDED
@@ -0,0 +1,81 @@
1
+ // pi 这个平台的 kioku setup 与 kioku doctor。
2
+ // pi 没有自带的长期记忆要停用,扩展自己注册 MCP 服务,所以 setup 只做一件事:把服务地址与访问密钥写进本机的文件,
3
+ // 扩展读它
4
+
5
+ import { homedir } from 'node:os'
6
+ import { join } from 'node:path'
7
+
8
+ import { readSettings, readText } from './files.mjs'
9
+ import { profileFile, readProfile, removeProfile, writeProfile } from './profile.mjs'
10
+ import { resolveTarget } from './target.mjs'
11
+
12
+ const SOURCE = 'git:github.com/lonelyman0108/kioku-plugins'
13
+
14
+ export function piHome(env) {
15
+ return env.PI_CODING_AGENT_DIR || join(homedir(), '.pi', 'agent')
16
+ }
17
+
18
+ // 包的来源写法有几种(git:、https://、本地路径),都带着仓库名
19
+ function installed(settings) {
20
+ const packages = Array.isArray(settings?.packages) ? settings.packages : []
21
+ return packages.some((entry) => {
22
+ const source = typeof entry === 'string' ? entry : entry?.source
23
+ return typeof source === 'string' && source.includes('kioku-plugins')
24
+ })
25
+ }
26
+
27
+ export async function setupPi(options, io) {
28
+ const { env, out } = io
29
+ const profile = profileFile('pi', env)
30
+ if (options.undo) {
31
+ if (options.dryRun) out.write(`${profile}:删掉\n没有写入(--dry-run)\n`)
32
+ else if (await removeProfile('pi', env)) out.write(`已删掉 ${profile}\n`)
33
+ else out.write(`${profile} 本来就没有\n`)
34
+ out.write(`扩展要另外卸载:pi remove ${SOURCE}\n`)
35
+ return 0
36
+ }
37
+ const { url, key, saved } = await resolveTarget({ id: 'pi', name: 'pi' }, options, io)
38
+ const same = Boolean(saved && saved.url === url && saved.key === key)
39
+ if (same) out.write(`${profile} 不用改\n`)
40
+ else out.write(`${profile}:写入服务地址与访问密钥(只给本人读写)\n`)
41
+ if (options.dryRun) {
42
+ out.write('没有写入(--dry-run)\n')
43
+ return 0
44
+ }
45
+ if (!same) await writeProfile('pi', { url, key }, env)
46
+ const { settings } = await readSettings(join(piHome(env), 'settings.json')).catch(() => ({}))
47
+ out.write('pi 已配好,新开会话(或 /reload)生效。\n')
48
+ if (!installed(settings)) out.write(`接下来装上扩展:pi install ${SOURCE}\n`)
49
+ return 0
50
+ }
51
+
52
+ // 一份 mcp.json 里有没有叫 kioku 的服务;没有这个文件、读不懂时为假(读不懂的由 pi 自己报)
53
+ async function namesKioku(file) {
54
+ try {
55
+ return Object.hasOwn(JSON.parse((await readText(file)) ?? '{}')?.mcpServers ?? {}, 'kioku')
56
+ } catch {
57
+ return false
58
+ }
59
+ }
60
+
61
+ export async function inspectPi({ env, cwd }, { ok, warn }) {
62
+ const profile = await readProfile('pi', env).catch(() => null)
63
+ if (!profile) warn('没有 kioku setup pi 写下的地址与访问密钥,扩展不会生效:运行 kioku setup pi')
64
+
65
+ // 用户级的与当前项目的设置都看:扩展可以只装在项目里,项目的 mcp.json 也盖过扩展注册的服务
66
+ const home = piHome(env)
67
+ const project = join(cwd, '.pi')
68
+ const user = await readSettings(join(home, 'settings.json'))
69
+ const local = await readSettings(join(project, 'settings.json')).catch(() => ({}))
70
+ if (installed(user.settings) || installed(local.settings)) ok('pi 里装了 kioku 的扩展')
71
+ else warn(`pi 里没有装 kioku 的扩展:pi install ${SOURCE}`)
72
+
73
+ const shadowing = []
74
+ for (const file of [join(home, 'mcp.json'), join(project, 'mcp.json')]) {
75
+ if (await namesKioku(file)) shadowing.push(file)
76
+ }
77
+ if (shadowing.length) {
78
+ warn(`${shadowing.join('、')} 里有一个叫 kioku 的 MCP 服务,它会盖过扩展注册的那个:去掉它`)
79
+ } else ok('MCP 服务由扩展在会话开始时注册')
80
+ ok('pi 没有自带的长期记忆要停用')
81
+ }
@@ -0,0 +1,137 @@
1
+ // kioku setup 与 kioku doctor 认得的平台:自带的长期记忆在哪个配置文件里、怎么停用、怎么看现在的状态。
2
+ // 这里只描述配置,读写文件由 setup.mjs 做
3
+
4
+ import { readFile } from 'node:fs/promises'
5
+ import { homedir } from 'node:os'
6
+ import { join } from 'node:path'
7
+
8
+ import { inspectCodex, preflightCodex, setupCodex } from './codex.mjs'
9
+ import { inspectDsh, setupDsh } from './dsh.mjs'
10
+ import { inspectHermes, preflightHermes, readHermesConfig, setupHermes } from './hermes.mjs'
11
+ import { inspectOpenclaw, setupOpenclaw } from './openclaw.mjs'
12
+ import { inspectPi, setupPi } from './pi.mjs'
13
+ import { readProfile } from './profile.mjs'
14
+
15
+ // 真值的环境变量写法
16
+ const TRUTHY = /^(1|true|yes|on)$/i
17
+
18
+ // 项目里优先于用户设置的两份设置文件
19
+ const PROJECT_SETTINGS = ['.claude/settings.local.json', '.claude/settings.json']
20
+
21
+ // 读一份 JSON 设置里的某一项;文件没有或读不懂时为 undefined
22
+ async function settingOf(file, key) {
23
+ try {
24
+ return JSON.parse((await readFile(file, 'utf8')).replace(/^\uFEFF/, ''))?.[key]
25
+ } catch {
26
+ return undefined
27
+ }
28
+ }
29
+
30
+ const claudeCode = {
31
+ name: 'Claude Code',
32
+ // 应用的运行时要是这个,服务端才按这个平台给注入
33
+ runtimeFamily: 'claudecode',
34
+ // 这个平台的会话里有的环境变量,不写平台时靠它认出来
35
+ detect: (env) => env.CLAUDECODE === '1',
36
+ // 用户级的设置文件
37
+ settingsFile: (env) => join(env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude'), 'settings.json'),
38
+ memory: {
39
+ name: '自动记忆(auto memory)',
40
+ // 停用:用户设置里把 autoMemoryEnabled 设为 false
41
+ disable: (settings) => ({ ...settings, autoMemoryEnabled: false }),
42
+ // 还原:去掉这一项,回到默认(开着)
43
+ restore: (settings) => {
44
+ const rest = { ...settings }
45
+ delete rest.autoMemoryEnabled
46
+ return rest
47
+ },
48
+ changed: ['autoMemoryEnabled'],
49
+ // 现在是不是停用的,以及是哪里停用的
50
+ disabledBy: (settings, env) => {
51
+ if (TRUTHY.test((env.CLAUDE_CODE_DISABLE_AUTO_MEMORY ?? '').trim())) {
52
+ return '环境变量 CLAUDE_CODE_DISABLE_AUTO_MEMORY'
53
+ }
54
+ return settings?.autoMemoryEnabled === false ? '用户设置' : null
55
+ },
56
+ // 又在哪里启用了:当前项目的设置优先于用户设置。别处(托管的设置)查不到
57
+ enabledBy: async (env, cwd) => {
58
+ // 环境变量停用着时,设置里写什么都不生效
59
+ if (TRUTHY.test((env.CLAUDE_CODE_DISABLE_AUTO_MEMORY ?? '').trim())) return null
60
+ for (const name of PROJECT_SETTINGS) {
61
+ if ((await settingOf(join(cwd, name), 'autoMemoryEnabled')) === true)
62
+ return `项目的 ${name} `
63
+ }
64
+ return null
65
+ },
66
+ },
67
+ // 插件是否在用:这个会话里钩子已经配好了访问密钥文件,或者用户设置的 enabledPlugins 里有以「kioku@」开头、
68
+ // 值为 true 的一项。项目级的设置里启用的认不出来,所以认不出时只提醒、不算有问题
69
+ pluginActive: (settings, env) =>
70
+ Boolean(env.KIOKU_API_KEY_FILE) ||
71
+ Object.entries(settings?.enabledPlugins ?? {}).some(
72
+ ([id, on]) => id.startsWith('kioku@') && on === true,
73
+ ),
74
+ pluginHint: '在 Claude Code 里用 /plugin 安装并启用 kioku',
75
+ }
76
+
77
+ const codex = {
78
+ name: 'Codex',
79
+ runtimeFamily: 'codex',
80
+ // Codex 的会话里没有可靠的标记,要写明平台
81
+ detect: () => false,
82
+ // 地址与访问密钥放在本机的文件里(profile.mjs);readConfig 读出来给 doctor、login、import 用
83
+ readConfig: (env) => readProfile('codex', env),
84
+ setup: setupCodex,
85
+ // kioku login 申请之前先做的检查
86
+ preflight: preflightCodex,
87
+ inspect: inspectCodex,
88
+ }
89
+
90
+ const pi = {
91
+ name: 'pi',
92
+ runtimeFamily: 'pi',
93
+ detect: () => false,
94
+ readConfig: (env) => readProfile('pi', env),
95
+ setup: setupPi,
96
+ inspect: inspectPi,
97
+ }
98
+
99
+ const hermes = {
100
+ name: 'Hermes',
101
+ runtimeFamily: 'hermes',
102
+ detect: () => false,
103
+ // 地址与访问密钥在 Hermes 自己的 .env 里
104
+ readConfig: readHermesConfig,
105
+ setup: setupHermes,
106
+ preflight: preflightHermes,
107
+ inspect: inspectHermes,
108
+ }
109
+
110
+ const openclaw = {
111
+ name: 'OpenClaw',
112
+ runtimeFamily: 'openclaw',
113
+ detect: () => false,
114
+ readConfig: (env) => readProfile('openclaw', env),
115
+ setup: setupOpenclaw,
116
+ inspect: inspectOpenclaw,
117
+ }
118
+
119
+ const dsh = {
120
+ name: 'DeepSeek Harness',
121
+ runtimeFamily: 'dsh',
122
+ detect: () => false,
123
+ readConfig: (env) => readProfile('dsh', env),
124
+ setup: setupDsh,
125
+ inspect: inspectDsh,
126
+ }
127
+
128
+ export const PLATFORMS = { 'claude-code': claudeCode, codex, pi, hermes, openclaw, dsh }
129
+
130
+ export function platformNames() {
131
+ return Object.keys(PLATFORMS).join('、')
132
+ }
133
+
134
+ // 不写平台时按环境变量认;认不出为 null
135
+ export function detectPlatform(env) {
136
+ return Object.keys(PLATFORMS).find((id) => PLATFORMS[id].detect(env)) ?? null
137
+ }
@@ -0,0 +1,100 @@
1
+ // 没有自己的密钥存储的平台(Codex、pi 这类),地址与访问密钥放在本机的一个文件里:
2
+ // <配置目录>/kioku/<平台>.json,只给本人读写。kioku setup 写它,各平台的钩子与 kioku doctor 读它。
3
+ // 一个平台一个文件:每个平台在 Kioku 里是各自的应用,访问密钥不共用
4
+
5
+ import { randomUUID } from 'node:crypto'
6
+ import { chmod, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
7
+ import { homedir } from 'node:os'
8
+ import { join } from 'node:path'
9
+
10
+ import { errorKind, keyFormatError, KiokuFailure } from './http.mjs'
11
+
12
+ // 平台名要拼进文件名,只收这些字符
13
+ const PLATFORM = /^[a-z][a-z0-9-]{0,31}$/
14
+
15
+ // 放这些文件的目录:KIOKU_CONFIG_DIR,否则 XDG 的配置目录下的 kioku
16
+ export function profileDir(env) {
17
+ if (env.KIOKU_CONFIG_DIR) return env.KIOKU_CONFIG_DIR
18
+ return join(env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'kioku')
19
+ }
20
+
21
+ export function profileFile(platform, env) {
22
+ if (!PLATFORM.test(platform)) throw new KiokuFailure('平台名不对')
23
+ return join(profileDir(env), `${platform}.json`)
24
+ }
25
+
26
+ // 服务地址:去掉首尾空白与结尾的斜杠;不是 http(s) 地址、或者带着账号密码、查询参数时返回原因
27
+ export function serverUrlProblem(url) {
28
+ // URL 解析会悄悄去掉中间的换行与制表符:原样写进配置文件的是带着它们的那一份
29
+ if (/[\s\p{Cc}]/u.test(url)) return '服务地址里不能有空白或控制字符'
30
+ let parsed
31
+ try {
32
+ parsed = new URL(url)
33
+ } catch {
34
+ return '服务地址不是有效的地址'
35
+ }
36
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
37
+ return '服务地址要以 http:// 或 https:// 开头'
38
+ }
39
+ if (parsed.username || parsed.password || parsed.search || parsed.hash) {
40
+ return '服务地址里不要带账号密码、查询参数'
41
+ }
42
+ return null
43
+ }
44
+
45
+ // 读这个平台的地址与访问密钥。没有这个文件时为 null;文件读不懂、内容不对时抛 KiokuFailure,
46
+ // 文字只写文件的位置与问题,不带内容
47
+ export async function readProfile(platform, env) {
48
+ const file = profileFile(platform, env)
49
+ let text
50
+ try {
51
+ text = await readFile(file, 'utf8')
52
+ } catch (err) {
53
+ if (err?.code === 'ENOENT') return null
54
+ throw new KiokuFailure(`无法读取 ${file}(${errorKind(err)})`)
55
+ }
56
+ let data
57
+ try {
58
+ data = JSON.parse(text)
59
+ } catch {
60
+ data = null
61
+ }
62
+ const url = typeof data?.serverUrl === 'string' ? data.serverUrl.trim().replace(/\/+$/, '') : ''
63
+ const key = typeof data?.apiKey === 'string' ? data.apiKey.trim() : ''
64
+ if (!url || !key) throw new KiokuFailure(`${file} 里没有服务地址或访问密钥`)
65
+ const problem = serverUrlProblem(url) ?? keyFormatError(key)
66
+ if (problem) throw new KiokuFailure(`${file}:${problem}`)
67
+ return { url, key, file }
68
+ }
69
+
70
+ // 写这个平台的地址与访问密钥:目录与文件都只给本人,先写临时文件再改名
71
+ export async function writeProfile(platform, { url, key }, env) {
72
+ const file = profileFile(platform, env)
73
+ const clean = url.trim().replace(/\/+$/, '')
74
+ const problem = serverUrlProblem(clean) ?? keyFormatError(key)
75
+ if (problem) throw new KiokuFailure(problem)
76
+ const temp = `${file}.${randomUUID()}.tmp`
77
+ try {
78
+ await mkdir(profileDir(env), { recursive: true, mode: 0o700 })
79
+ const body = `${JSON.stringify({ serverUrl: clean, apiKey: key }, null, 2)}\n`
80
+ await writeFile(temp, body, { mode: 0o600, flag: 'wx' })
81
+ // 已有的文件权限可能更宽,改名之后以新文件的为准;再收一次,不受 umask 影响
82
+ await chmod(temp, 0o600)
83
+ await rename(temp, file)
84
+ } catch (err) {
85
+ await rm(temp, { force: true }).catch(() => {})
86
+ throw new KiokuFailure(`无法写入 ${file}(${errorKind(err)})`)
87
+ }
88
+ return file
89
+ }
90
+
91
+ export async function removeProfile(platform, env) {
92
+ const file = profileFile(platform, env)
93
+ try {
94
+ await rm(file)
95
+ return file
96
+ } catch (err) {
97
+ if (err?.code === 'ENOENT') return null
98
+ throw new KiokuFailure(`无法删除 ${file}(${errorKind(err)})`)
99
+ }
100
+ }
package/lib/redact.mjs ADDED
@@ -0,0 +1,91 @@
1
+ // 打码:输出里原样出现的值换成 ***。按字节比对、不解码,所以不会把一个字符拆开,
2
+ // 不是 UTF-8 的输出(例如二进制)也原样通过。只防值顺手出现在输出里,不是安全边界:
3
+ // 值被编码、拆开或改了大小写后再打印,就认不出来
4
+
5
+ import { PassThrough, Transform } from 'node:stream'
6
+
7
+ const MASK = Buffer.from('***')
8
+
9
+ // 少于这么多个字符的值不打码:这么短的串在输出里到处都是,换掉会误伤
10
+ export const MIN_REDACT_CHARS = 4
11
+
12
+ export function redactable(value) {
13
+ return [...value].length >= MIN_REDACT_CHARS
14
+ }
15
+
16
+ // buf 的结尾是某个值的开头(一次还没写完的出现)时,返回这一段的长度,否则为 0
17
+ function partialTail(buf, needles) {
18
+ let longest = 0
19
+ for (const needle of needles) {
20
+ // 从最长的可能找起,第一个对上的就是这个值能留下的最长一段
21
+ for (let at = Math.max(0, buf.length - needle.length + 1); at < buf.length; at++) {
22
+ const length = buf.length - at
23
+ if (length <= longest) break
24
+ if (buf[at] === needle[0] && buf.subarray(at).equals(needle.subarray(0, length))) {
25
+ longest = length
26
+ break
27
+ }
28
+ }
29
+ }
30
+ return longest
31
+ }
32
+
33
+ // 返回一个 Transform:写进去原始输出,读出来打过码的输出。
34
+ // 值可能被拆在相邻的两块里:块的结尾像某个值的开头时,这一段先留着,拼上下一块再判断,结束时冲刷出去。
35
+ // 几个值互相包含或重叠时,盖住的范围取并集,连成一片的只写一个 ***
36
+ export function createRedactor(values) {
37
+ const needles = [...new Set(values.filter(redactable))].map((v) => Buffer.from(v, 'utf8'))
38
+ if (needles.length === 0) return new PassThrough()
39
+ let pending = Buffer.alloc(0)
40
+ // pending 开头已经确定盖住的字节数:上一次写出的最后一段延续到了这里
41
+ let carry = 0
42
+ // 上一次写出的最后一个字节盖住了没有:盖住的话,从 pending 开头接着盖的部分不再另写 ***
43
+ let covered = false
44
+
45
+ function drain(final) {
46
+ const limit = final ? pending.length : pending.length - partialTail(pending, needles)
47
+ if (limit <= 0) return null
48
+ // [0, limit) 里每个字节盖不盖住都已经定了:盖住它的出现都从 limit 之前开始,而且都完整地在 pending 里
49
+ const ranges = carry > 0 ? [[0, carry]] : []
50
+ for (const needle of needles) {
51
+ for (
52
+ let at = pending.indexOf(needle);
53
+ at !== -1 && at < limit;
54
+ at = pending.indexOf(needle, at + 1)
55
+ ) {
56
+ ranges.push([at, at + needle.length])
57
+ }
58
+ }
59
+ ranges.sort((a, b) => a[0] - b[0])
60
+ const runs = []
61
+ for (const [from, to] of ranges) {
62
+ const last = runs.at(-1)
63
+ if (last && from <= last[1]) last[1] = Math.max(last[1], to)
64
+ else runs.push([from, to])
65
+ }
66
+ const parts = []
67
+ let pos = 0
68
+ for (const [from, to] of runs) {
69
+ if (from > pos) parts.push(pending.subarray(pos, from))
70
+ if (from > 0 || !covered) parts.push(MASK)
71
+ pos = Math.min(to, limit)
72
+ }
73
+ if (pos < limit) parts.push(pending.subarray(pos, limit))
74
+ const reach = runs.length > 0 ? runs.at(-1)[1] : 0
75
+ covered = reach >= limit
76
+ carry = Math.max(0, reach - limit)
77
+ pending = pending.subarray(limit)
78
+ return Buffer.concat(parts)
79
+ }
80
+
81
+ const emit = (callback, out) => callback(null, out?.length ? out : undefined)
82
+ return new Transform({
83
+ transform(chunk, _encoding, callback) {
84
+ pending = pending.length > 0 ? Buffer.concat([pending, chunk]) : chunk
85
+ emit(callback, drain(false))
86
+ },
87
+ flush(callback) {
88
+ emit(callback, drain(true))
89
+ },
90
+ })
91
+ }