@kioku-memory/cli 0.3.0 → 0.4.1

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.
Files changed (66) hide show
  1. package/README.md +63 -23
  2. package/assets/plugins/agy/README.md +34 -0
  3. package/assets/plugins/agy/bin/kioku +36 -0
  4. package/assets/plugins/agy/hooks/forward.mjs +232 -0
  5. package/assets/plugins/agy/hooks.json +25 -0
  6. package/assets/plugins/agy/lib/kioku.mjs +53 -0
  7. package/{lib/kioku.mjs → assets/plugins/agy/lib/run.mjs} +4 -83
  8. package/assets/plugins/agy/package.json +7 -0
  9. package/assets/plugins/agy/plugin.json +6 -0
  10. package/assets/plugins/agy/vitest.config.mjs +5 -0
  11. package/assets/plugins/gemini/README.md +33 -0
  12. package/assets/plugins/gemini/bin/kioku +36 -0
  13. package/assets/plugins/gemini/gemini-extension.json +5 -0
  14. package/assets/plugins/gemini/hooks/forward.mjs +174 -0
  15. package/assets/plugins/gemini/hooks/hooks.json +43 -0
  16. package/assets/plugins/gemini/lib/command.mjs +152 -0
  17. package/assets/plugins/gemini/lib/config.mjs +50 -0
  18. package/assets/plugins/gemini/lib/http.mjs +57 -0
  19. package/assets/plugins/gemini/lib/kioku.mjs +53 -0
  20. package/assets/plugins/gemini/lib/lifecycle.mjs +128 -0
  21. package/assets/plugins/gemini/lib/mcp.mjs +142 -0
  22. package/assets/plugins/gemini/lib/profile.mjs +100 -0
  23. package/assets/plugins/gemini/lib/redact.mjs +91 -0
  24. package/assets/plugins/gemini/lib/run.mjs +372 -0
  25. package/assets/plugins/gemini/lib/text.mjs +14 -0
  26. package/assets/plugins/gemini/lib/usage.mjs +2 -0
  27. package/assets/plugins/gemini/package.json +7 -0
  28. package/assets/plugins/gemini/vitest.config.mjs +5 -0
  29. package/bin/kioku +16 -12
  30. package/dist/index.mjs +8846 -0
  31. package/package.json +14 -5
  32. package/lib/agy.mjs +0 -181
  33. package/lib/api.mjs +0 -38
  34. package/lib/clean.mjs +0 -96
  35. package/lib/codex.mjs +0 -320
  36. package/lib/conflicts.mjs +0 -1303
  37. package/lib/connect.mjs +0 -152
  38. package/lib/doctor.mjs +0 -158
  39. package/lib/dsh.mjs +0 -82
  40. package/lib/files.mjs +0 -92
  41. package/lib/gemini.mjs +0 -199
  42. package/lib/hermes.mjs +0 -276
  43. package/lib/import.mjs +0 -301
  44. package/lib/install.mjs +0 -196
  45. package/lib/local.mjs +0 -294
  46. package/lib/login.mjs +0 -359
  47. package/lib/openclaw.mjs +0 -256
  48. package/lib/opencode.mjs +0 -144
  49. package/lib/panel.mjs +0 -311
  50. package/lib/pi.mjs +0 -90
  51. package/lib/platforms.mjs +0 -297
  52. package/lib/prompts.mjs +0 -38
  53. package/lib/secret.mjs +0 -86
  54. package/lib/setup.mjs +0 -139
  55. package/lib/sources.mjs +0 -333
  56. package/lib/target.mjs +0 -62
  57. package/lib/wizard.mjs +0 -534
  58. /package/{lib → assets/plugins/agy/lib}/command.mjs +0 -0
  59. /package/{lib → assets/plugins/agy/lib}/config.mjs +0 -0
  60. /package/{lib → assets/plugins/agy/lib}/http.mjs +0 -0
  61. /package/{lib → assets/plugins/agy/lib}/lifecycle.mjs +0 -0
  62. /package/{lib → assets/plugins/agy/lib}/mcp.mjs +0 -0
  63. /package/{lib → assets/plugins/agy/lib}/profile.mjs +0 -0
  64. /package/{lib → assets/plugins/agy/lib}/redact.mjs +0 -0
  65. /package/{lib → assets/plugins/agy/lib}/text.mjs +0 -0
  66. /package/{lib → assets/plugins/agy/lib}/usage.mjs +0 -0
@@ -0,0 +1,57 @@
1
+ // 钩子与 kioku 命令共用的访问密钥检查与报错。报错只给插件自己写的文字或错误类别:
2
+ // fetch 的报错会带上整个 Authorization 请求头,响应解析失败的文字会带上响应的开头
3
+
4
+ // 访问密钥只能是可见的 ASCII 字符:别的字符放不进请求头,fetch 报错时会把整个请求头写进错误文字
5
+ const KEY = /^[\x21-\x7e]+$/
6
+ // 错误码(ECONNREFUSED、UND_ERR_SOCKET 这类)与错误类名(TypeError 这类)的样子
7
+ const CODE = /^[A-Z][A-Z0-9_]*$/
8
+ const NAME = /^[A-Z][A-Za-z]*$/
9
+
10
+ // 文字由插件自己写、不含值和访问密钥的失败,可以原样打印
11
+ export class KiokuFailure extends Error {}
12
+
13
+ // 访问密钥的格式不对时返回原因,否则为 null
14
+ export function keyFormatError(key) {
15
+ return KEY.test(key) ? null : '访问密钥的格式不对:只能是可见的 ASCII 字符,不能有空白'
16
+ }
17
+
18
+ // 错误的类别:只取 code 或 name,不取文字
19
+ export function errorKind(err) {
20
+ if (typeof err?.code === 'string' && CODE.test(err.code)) return err.code
21
+ if (typeof err?.name === 'string' && NAME.test(err.name)) return err.name
22
+ return '未知错误'
23
+ }
24
+
25
+ // fetch 失败的原因:超时,或者连不上(附 cause 的错误码)
26
+ export function fetchFailure(err, timeoutMs) {
27
+ if (err?.name === 'TimeoutError' || err?.name === 'AbortError') {
28
+ return `连接 Kioku 超时(${timeoutMs / 1000} 秒)`
29
+ }
30
+ const code = err?.cause?.code
31
+ return typeof code === 'string' && CODE.test(code)
32
+ ? `无法连接 Kioku(${code})`
33
+ : '无法连接 Kioku'
34
+ }
35
+
36
+ // 收到跳转(3xx)时的报错:说明要把地址改成跳转之后的地址。请求都不跟着跳转走,访问密钥只发给配置的地址;
37
+ // 跳转目标只给协议与主机,路径与查询参数里可能带着令牌;跳到同一个主机、或者没给目标时不举例
38
+ export function redirectError(status, location, url) {
39
+ let origin
40
+ try {
41
+ const target = new URL(location ?? '', `${url}/`)
42
+ const web = target.protocol === 'https:' || target.protocol === 'http:'
43
+ if (web && target.origin !== new URL(url).origin) origin = target.origin
44
+ } catch {
45
+ // 跳转目标解析不了时不举例
46
+ }
47
+ return `Kioku 返回了跳转(${status}),把地址改成跳转之后的地址${origin ? `(例如 ${origin})` : ''}`
48
+ }
49
+
50
+ export function isRedirect(status) {
51
+ return status >= 300 && status < 400
52
+ }
53
+
54
+ // 要打印的失败原因:插件自己写的原样给出,别的只给类别
55
+ export function failureText(err) {
56
+ return err instanceof KiokuFailure ? err.message : errorKind(err)
57
+ }
@@ -0,0 +1,53 @@
1
+ // 插件目录里放着的精简 kioku 入口:只实现 kioku run(插件启用期间放在 PATH 里给 Bash 工具用)。
2
+ // 向导、接入、检查、日常记忆读写等完整命令行在 npm 包 @kioku-memory/cli
3
+
4
+ import { parseRunArgs, run, USAGE, UsageError } from './run.mjs'
5
+
6
+ export { parseRunArgs, run, USAGE, UsageError }
7
+
8
+ const OVERVIEW = `用法:kioku run -e 变量=<标识>#<字段> [-e …] [--purpose <用途>] -- <命令> [参数…]
9
+
10
+ 插件目录内置的命令行入口仅包含 kioku run(向 Kioku 取凭据,放进环境变量并打码输出)。
11
+ 向导、接入管理与记忆读写等完整功能见 @kioku-memory/cli:
12
+
13
+ npx @kioku-memory/cli
14
+ npm install -g @kioku-memory/cli
15
+
16
+ 运行子命令用法:kioku run --help
17
+ `
18
+
19
+ const FULL_CLI_COMMANDS = new Set([
20
+ 'connect',
21
+ 'disconnect',
22
+ 'upgrade',
23
+ 'status',
24
+ 'login',
25
+ 'setup',
26
+ 'install',
27
+ 'doctor',
28
+ 'clean',
29
+ 'import',
30
+ 'local',
31
+ 'open',
32
+ 'search',
33
+ 'get',
34
+ 'ls',
35
+ 'add',
36
+ ])
37
+
38
+ export async function main(argv) {
39
+ const [sub, ...rest] = argv
40
+ if (sub === '-h' || sub === '--help') {
41
+ process.stdout.write(OVERVIEW)
42
+ return 0
43
+ }
44
+ if (sub === 'run') return run(rest)
45
+ if (sub && FULL_CLI_COMMANDS.has(sub)) {
46
+ process.stderr.write(
47
+ `kioku:插件内置入口仅含 run 子命令;运行 npx @kioku-memory/cli ${sub}(或全局安装 @kioku-memory/cli)\n`,
48
+ )
49
+ return 2
50
+ }
51
+ process.stderr.write(sub === undefined ? OVERVIEW : `kioku:不认识的子命令 ${sub}\n\n${OVERVIEW}`)
52
+ return 2
53
+ }
@@ -0,0 +1,128 @@
1
+ // 各平台的钩子共用的生命周期转发:把 session.start、prompt.submit、turn.end 交给 Kioku 的生命周期端点。
2
+ // 这里不放提示词和格式逻辑,都由服务端决定;怎么从平台取输入、怎么把结果交还平台,由各插件自己写。
3
+ // 报错和 kioku 命令一样不带访问密钥:格式不对的访问密钥不发出去,fetch 的报错只取类别,
4
+ // 也不跟着跳转走,访问密钥只发给配置的地址
5
+
6
+ import { execFile, execFileSync } from 'node:child_process'
7
+ import { basename } from 'node:path'
8
+
9
+ import { fetchFailure, isRedirect, keyFormatError, KiokuFailure, redirectError } from './http.mjs'
10
+
11
+ // 各事件等待服务端的上限(毫秒),要比平台给钩子的时限短
12
+ export const TIMEOUTS = { 'session.start': 8000, 'prompt.submit': 5000, 'turn.end': 5000 }
13
+ // 与服务端 contracts 的上限一致
14
+ export const MAX_PROMPT = 20_000
15
+ export const MAX_REPLY = 20_000
16
+ export const MAX_SESSION_ID = 200
17
+ const MAX_NAME = 128
18
+
19
+ // 配置写错了:访问密钥格式不对(kind 为 key),或者服务地址返回跳转(kind 为 url)。
20
+ // 和没有配置一样,平台可以在会话开始时提示一次;文字不带访问密钥
21
+ export class Misconfigured extends KiokuFailure {
22
+ constructor(message, kind) {
23
+ super(message)
24
+ this.kind = kind
25
+ }
26
+ }
27
+
28
+ // 服务地址去掉首尾空白与结尾的斜杠
29
+ export function normalizeBase(url) {
30
+ return (url ?? '').trim().replace(/\/+$/, '')
31
+ }
32
+
33
+ // 访问密钥的格式不对时抛 Misconfigured
34
+ export function assertKeyFormat(key) {
35
+ const problem = keyFormatError(key)
36
+ if (problem) throw new Misconfigured(problem, 'key')
37
+ }
38
+
39
+ // 按长度截断时不切开代理对(表情这类字符):落单的半个到了服务端会变成替换字符
40
+ export function clip(text, max) {
41
+ if (text.length <= max) return text
42
+ const code = text.charCodeAt(max - 1)
43
+ return text.slice(0, code >= 0xd800 && code <= 0xdbff ? max - 1 : max)
44
+ }
45
+
46
+ // 当前项目的目录名与 git 仓库名,服务端用它们召回与项目相关的记忆;取不到的就不带
47
+ export function projectOf(cwd) {
48
+ const project = {}
49
+ const dirName = basename(cwd)
50
+ if (dirName) project.dirName = dirName.slice(0, MAX_NAME)
51
+ try {
52
+ const remote = execFileSync('git', ['-C', cwd, 'remote', 'get-url', 'origin'], {
53
+ encoding: 'utf8',
54
+ timeout: 1500,
55
+ stdio: ['ignore', 'pipe', 'ignore'],
56
+ }).trim()
57
+ const repoName = /([^/:]+?)(?:\.git)?$/.exec(remote)?.[1]
58
+ if (repoName) project.repoName = repoName.slice(0, MAX_NAME)
59
+ } catch {
60
+ // 不是 git 仓库或没有 origin
61
+ }
62
+ return project
63
+ }
64
+
65
+ // 同上,不堵住事件循环:给在宿主进程里跑的扩展用(同步的那个会让宿主的界面停住)
66
+ export function projectOfAsync(cwd) {
67
+ const project = {}
68
+ const dirName = basename(cwd)
69
+ if (dirName) project.dirName = dirName.slice(0, MAX_NAME)
70
+ return new Promise((resolve) => {
71
+ execFile(
72
+ 'git',
73
+ ['-C', cwd, 'remote', 'get-url', 'origin'],
74
+ { encoding: 'utf8', timeout: 1500 },
75
+ (err, stdout) => {
76
+ const repoName = err ? undefined : /([^/:]+?)(?:\.git)?$/.exec(stdout.trim())?.[1]
77
+ if (repoName) project.repoName = repoName.slice(0, MAX_NAME)
78
+ resolve(project)
79
+ },
80
+ )
81
+ })
82
+ }
83
+
84
+ // 服务端要注入的上下文文本;没有时为 undefined。只取文本,输出里的其他字段一律不用:
85
+ // 记忆服务能决定注入什么内容,但不能挡住用户的输入或改变会话
86
+ export function contextOf(hostOutput) {
87
+ if (hostOutput?.mode === 'stdout_json') {
88
+ return (
89
+ hostOutput.value?.hookSpecificOutput?.additionalContext ??
90
+ hostOutput.value?.injectSteps?.[0]?.systemMessage?.systemMessage
91
+ )
92
+ }
93
+ if (hostOutput?.mode === 'stdout_text') return hostOutput.value
94
+ // 没有专门输出格式的运行时:服务端直接给文本
95
+ if (hostOutput?.mode === 'return_value') {
96
+ return (
97
+ hostOutput.value?.systemContext ??
98
+ hostOutput.value?.promptContext ??
99
+ hostOutput.value?.context
100
+ )
101
+ }
102
+ return undefined
103
+ }
104
+
105
+ // 把一个生命周期事件交给服务端;连不上、超时、取消、跳转与非 2xx 都以 KiokuFailure 抛出
106
+ export async function postEvent(base, key, body, timeout, signal) {
107
+ let res
108
+ try {
109
+ res = await fetch(`${base}/v1/lifecycle/event`, {
110
+ method: 'POST',
111
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
112
+ body: JSON.stringify(body),
113
+ redirect: 'manual',
114
+ // 宿主给了中止信号时(用户取消了这次输入)一起听
115
+ signal: signal
116
+ ? AbortSignal.any([AbortSignal.timeout(timeout), signal])
117
+ : AbortSignal.timeout(timeout),
118
+ })
119
+ } catch (err) {
120
+ if (signal?.aborted) throw new KiokuFailure('已取消')
121
+ throw new KiokuFailure(fetchFailure(err, timeout))
122
+ }
123
+ if (isRedirect(res.status)) {
124
+ throw new Misconfigured(redirectError(res.status, res.headers.get('location'), base), 'url')
125
+ }
126
+ if (!res.ok) throw new KiokuFailure(`HTTP ${res.status}`)
127
+ return res
128
+ }
@@ -0,0 +1,142 @@
1
+ // 向 Kioku 的 MCP 端点发一次调用(取工具清单、调用工具)。给没有自己的 MCP 客户端、
2
+ // 要把 Kioku 的工具登记成平台自己的工具的平台用。端点是无状态的,一次请求一个回答,不用先握手
3
+
4
+ import { randomUUID } from 'node:crypto'
5
+ import { readFileSync } from 'node:fs'
6
+ import { chmod, mkdir, rename, rm, writeFile } from 'node:fs/promises'
7
+
8
+ import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
9
+ import { profileDir, profileFile } from './profile.mjs'
10
+ import { plain } from './text.mjs'
11
+
12
+ export const TOOLS_TIMEOUT = 8000
13
+ export const TOOL_CALL_TIMEOUT = 30_000
14
+
15
+ // 回答可能是一段事件流:取最后一条 data
16
+ function payloadOf(text, contentType) {
17
+ if (!contentType.includes('text/event-stream')) return text
18
+ const data = text
19
+ .split(/\r?\n/)
20
+ .filter((line) => line.startsWith('data:'))
21
+ .map((line) => line.slice(5).trim())
22
+ return data.at(-1) ?? ''
23
+ }
24
+
25
+ // 一次 JSON-RPC 调用,返回 result。连不上、超时、取消、跳转、访问密钥无效、响应不对、服务端报错都以 KiokuFailure 抛出
26
+ export async function mcpCall({ url, key }, method, params, timeout, signal) {
27
+ let res
28
+ let text
29
+ try {
30
+ res = await fetch(`${url}/v1/mcp`, {
31
+ method: 'POST',
32
+ headers: {
33
+ 'content-type': 'application/json',
34
+ accept: 'application/json, text/event-stream',
35
+ authorization: `Bearer ${key}`,
36
+ },
37
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
38
+ // 不跟着跳转走:访问密钥只发给配置的地址
39
+ redirect: 'manual',
40
+ signal: signal
41
+ ? AbortSignal.any([AbortSignal.timeout(timeout), signal])
42
+ : AbortSignal.timeout(timeout),
43
+ })
44
+ text = await res.text()
45
+ } catch (err) {
46
+ if (signal?.aborted) throw new KiokuFailure('已取消')
47
+ throw new KiokuFailure(fetchFailure(err, timeout))
48
+ }
49
+ if (isRedirect(res.status)) {
50
+ throw new KiokuFailure(redirectError(res.status, res.headers.get('location'), url))
51
+ }
52
+ if (res.status === 401) throw new KiokuFailure('访问密钥无效或已吊销')
53
+ if (!res.ok) throw new KiokuFailure(`Kioku 返回 HTTP ${res.status}`)
54
+ let data
55
+ try {
56
+ data = JSON.parse(payloadOf(text, res.headers.get('content-type') ?? ''))
57
+ } catch {
58
+ data = null
59
+ }
60
+ if (data === null || typeof data !== 'object') throw new KiokuFailure('Kioku 的响应格式不对')
61
+ if (data.error) {
62
+ // 服务端写的原因压成一行再给
63
+ const reason = plain(data.error.message)
64
+ throw new KiokuFailure(reason ? `Kioku 没有接受这次调用:${reason}` : 'Kioku 没有接受这次调用')
65
+ }
66
+ return data.result
67
+ }
68
+
69
+ // 清单里能用的工具:名字、说明、参数的 schema 都在的
70
+ export function toolsOf(result) {
71
+ const tools = Array.isArray(result?.tools) ? result.tools : []
72
+ return tools
73
+ .filter(
74
+ (tool) =>
75
+ typeof tool?.name === 'string' &&
76
+ tool.name &&
77
+ typeof tool.description === 'string' &&
78
+ tool.inputSchema !== null &&
79
+ typeof tool.inputSchema === 'object' &&
80
+ !Array.isArray(tool.inputSchema),
81
+ )
82
+ .map(({ name, description, inputSchema }) => ({ name, description, inputSchema }))
83
+ }
84
+
85
+ export async function listTools(target, signal) {
86
+ return toolsOf(await mcpCall(target, 'tools/list', {}, TOOLS_TIMEOUT, signal))
87
+ }
88
+
89
+ // 调用一个工具,返回 { text, isError }:结果里的文字块连成一段
90
+ export async function callTool(target, name, args, signal) {
91
+ const result = await mcpCall(
92
+ target,
93
+ 'tools/call',
94
+ { name, arguments: args ?? {} },
95
+ TOOL_CALL_TIMEOUT,
96
+ signal,
97
+ )
98
+ const blocks = Array.isArray(result?.content) ? result.content : []
99
+ const text = blocks
100
+ .filter((block) => block?.type === 'text' && typeof block.text === 'string')
101
+ .map((block) => block.text)
102
+ .join('\n')
103
+ return { text, isError: result?.isError === true }
104
+ }
105
+
106
+ // 工具清单在本机留一份:平台要求登记工具时当场给出清单、等不了一次请求的(OpenClaw 的工具工厂是同步的),
107
+ // 先用这一份,取到新的再换。和地址、访问密钥放在同一个目录,记着是哪个地址的清单
108
+ export function toolCacheFile(platform, env) {
109
+ return profileFile(platform, env).replace(/\.json$/, '-tools.json')
110
+ }
111
+
112
+ // 同步读这一份;没有、读不懂时为 null。at 是取到这份清单的时刻(毫秒),没记时为 0
113
+ export function readToolCacheSync(platform, env) {
114
+ try {
115
+ const data = JSON.parse(readFileSync(toolCacheFile(platform, env), 'utf8'))
116
+ if (typeof data?.url !== 'string') return null
117
+ const at = Number.isFinite(data.at) && data.at > 0 ? data.at : 0
118
+ return { url: data.url, at, tools: toolsOf(data) }
119
+ } catch {
120
+ return null
121
+ }
122
+ }
123
+
124
+ // 写不进去不算失败:下次再取
125
+ export async function writeToolCache(platform, { url, tools, at = Date.now() }, env) {
126
+ const file = toolCacheFile(platform, env)
127
+ const temp = `${file}.${randomUUID()}.tmp`
128
+ try {
129
+ await mkdir(profileDir(env), { recursive: true, mode: 0o700 })
130
+ await writeFile(temp, `${JSON.stringify({ url, at, tools })}\n`, { mode: 0o600, flag: 'wx' })
131
+ await chmod(temp, 0o600)
132
+ await rename(temp, file)
133
+ return true
134
+ } catch {
135
+ await rm(temp, { force: true }).catch(() => {})
136
+ return false
137
+ }
138
+ }
139
+
140
+ export async function removeToolCache(platform, env) {
141
+ await rm(toolCacheFile(platform, env), { force: true }).catch(() => {})
142
+ }
@@ -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
+ }
@@ -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
+ }