@kioku-memory/cli 0.6.1 → 0.6.2-edge.20261127111942.gcfb34f8
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.
- package/NOTICE +4 -0
- package/README.md +14 -6
- package/assets/plugins/zcode/.mcp.json +11 -0
- package/assets/plugins/zcode/.zcode-plugin/plugin.json +12 -0
- package/assets/plugins/zcode/README.md +48 -0
- package/assets/plugins/zcode/bin/kioku +36 -0
- package/assets/plugins/zcode/hooks/forward.mjs +350 -0
- package/assets/plugins/zcode/hooks/hooks.json +44 -0
- package/assets/plugins/zcode/hooks/mcp-stdio.mjs +261 -0
- package/assets/plugins/zcode/lib/command.mjs +158 -0
- package/assets/plugins/zcode/lib/config.mjs +44 -0
- package/assets/plugins/zcode/lib/http.mjs +102 -0
- package/assets/plugins/zcode/lib/kioku.mjs +58 -0
- package/assets/plugins/zcode/lib/lifecycle.mjs +163 -0
- package/assets/plugins/zcode/lib/mcp.mjs +171 -0
- package/assets/plugins/zcode/lib/profile.mjs +100 -0
- package/assets/plugins/zcode/lib/redact.mjs +91 -0
- package/assets/plugins/zcode/lib/run.mjs +406 -0
- package/assets/plugins/zcode/lib/text.mjs +14 -0
- package/assets/plugins/zcode/lib/usage.mjs +2 -0
- package/assets/plugins/zcode/marketplace.json +19 -0
- package/assets/plugins/zcode/package.json +7 -0
- package/assets/plugins/zcode/vitest.config.mjs +5 -0
- package/dist/index.mjs +379 -4
- package/package.json +1 -1
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// 各平台的钩子共用的生命周期转发:把 session.start、prompt.submit、turn.end 交给 Kioku 的生命周期端点。
|
|
2
|
+
// 这里不放提示词和格式逻辑,都由服务端决定;怎么从平台取输入、怎么把结果交还平台,由各插件自己写。
|
|
3
|
+
// 报错和 kioku 命令一样不带访问密钥:格式不对的访问密钥不发出去,fetch 的报错只取类别,
|
|
4
|
+
// 也不跟着跳转走,访问密钥只发给配置的地址
|
|
5
|
+
|
|
6
|
+
import { execFile, execFileSync } from 'node:child_process'
|
|
7
|
+
import { hostname } from 'node:os'
|
|
8
|
+
import { basename } from 'node:path'
|
|
9
|
+
|
|
10
|
+
import {
|
|
11
|
+
fetchFailure,
|
|
12
|
+
isRedirect,
|
|
13
|
+
keyFormatError,
|
|
14
|
+
KiokuFailure,
|
|
15
|
+
redirectError,
|
|
16
|
+
rejectionOf,
|
|
17
|
+
} from './http.mjs'
|
|
18
|
+
|
|
19
|
+
// 各事件等待服务端的上限(毫秒),要比平台给钩子的时限短
|
|
20
|
+
export const TIMEOUTS = { 'session.start': 8000, 'prompt.submit': 5000, 'turn.end': 5000 }
|
|
21
|
+
// 与服务端 contracts 的上限一致
|
|
22
|
+
export const MAX_PROMPT = 20_000
|
|
23
|
+
export const MAX_REPLY = 20_000
|
|
24
|
+
export const MAX_SESSION_ID = 200
|
|
25
|
+
const MAX_NAME = 128
|
|
26
|
+
|
|
27
|
+
function stripControl(text) {
|
|
28
|
+
let out = ''
|
|
29
|
+
for (const ch of text) {
|
|
30
|
+
const code = ch.charCodeAt(0)
|
|
31
|
+
if (code >= 0x20 && code !== 0x7f && (code < 0x80 || code > 0x9f)) out += ch
|
|
32
|
+
}
|
|
33
|
+
return out
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function deviceKeyOf(env = process.env) {
|
|
37
|
+
const override = typeof env?.KIOKU_DEVICE_KEY === 'string' ? env.KIOKU_DEVICE_KEY : ''
|
|
38
|
+
let raw = override
|
|
39
|
+
if (!stripControl(raw).trim()) {
|
|
40
|
+
try {
|
|
41
|
+
raw = hostname()
|
|
42
|
+
} catch {
|
|
43
|
+
raw = ''
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const clean = clip(stripControl(raw).trim(), MAX_NAME).trim()
|
|
47
|
+
return clean || undefined
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// 配置写错了:访问密钥格式不对(kind 为 key),或者服务地址返回跳转(kind 为 url)。
|
|
51
|
+
// 和没有配置一样,平台可以在会话开始时提示一次;文字不带访问密钥
|
|
52
|
+
export class Misconfigured extends KiokuFailure {
|
|
53
|
+
constructor(message, kind) {
|
|
54
|
+
super(message)
|
|
55
|
+
this.kind = kind
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// 服务地址去掉首尾空白与结尾的斜杠
|
|
60
|
+
export function normalizeBase(url) {
|
|
61
|
+
return (url ?? '').trim().replace(/\/+$/, '')
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// 访问密钥的格式不对时抛 Misconfigured
|
|
65
|
+
export function assertKeyFormat(key) {
|
|
66
|
+
const problem = keyFormatError(key)
|
|
67
|
+
if (problem) throw new Misconfigured(problem, 'key')
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// 按长度截断时不切开代理对(表情这类字符):落单的半个到了服务端会变成替换字符
|
|
71
|
+
export function clip(text, max) {
|
|
72
|
+
if (text.length <= max) return text
|
|
73
|
+
const code = text.charCodeAt(max - 1)
|
|
74
|
+
return text.slice(0, code >= 0xd800 && code <= 0xdbff ? max - 1 : max)
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// 当前项目的目录名与 git 仓库名,服务端用它们召回与项目相关的记忆;取不到的就不带
|
|
78
|
+
export function projectOf(cwd) {
|
|
79
|
+
const project = {}
|
|
80
|
+
const dirName = basename(cwd)
|
|
81
|
+
if (dirName) project.dirName = clip(dirName, MAX_NAME)
|
|
82
|
+
try {
|
|
83
|
+
const remote = execFileSync('git', ['-C', cwd, 'remote', 'get-url', 'origin'], {
|
|
84
|
+
encoding: 'utf8',
|
|
85
|
+
timeout: 1500,
|
|
86
|
+
stdio: ['ignore', 'pipe', 'ignore'],
|
|
87
|
+
}).trim()
|
|
88
|
+
const repoName = /([^/:]+?)(?:\.git)?$/.exec(remote)?.[1]
|
|
89
|
+
if (repoName) project.repoName = clip(repoName, MAX_NAME)
|
|
90
|
+
} catch {
|
|
91
|
+
// 不是 git 仓库或没有 origin
|
|
92
|
+
}
|
|
93
|
+
return project
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// 同上,不堵住事件循环:给在宿主进程里跑的扩展用(同步的那个会让宿主的界面停住)
|
|
97
|
+
export function projectOfAsync(cwd) {
|
|
98
|
+
const project = {}
|
|
99
|
+
const dirName = basename(cwd)
|
|
100
|
+
if (dirName) project.dirName = clip(dirName, MAX_NAME)
|
|
101
|
+
return new Promise((resolve) => {
|
|
102
|
+
execFile(
|
|
103
|
+
'git',
|
|
104
|
+
['-C', cwd, 'remote', 'get-url', 'origin'],
|
|
105
|
+
{ encoding: 'utf8', timeout: 1500 },
|
|
106
|
+
(err, stdout) => {
|
|
107
|
+
const repoName = err ? undefined : /([^/:]+?)(?:\.git)?$/.exec(stdout.trim())?.[1]
|
|
108
|
+
if (repoName) project.repoName = clip(repoName, MAX_NAME)
|
|
109
|
+
resolve(project)
|
|
110
|
+
},
|
|
111
|
+
)
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// 服务端要注入的上下文文本;没有时为 undefined。只取文本,输出里的其他字段一律不用:
|
|
116
|
+
// 记忆服务能决定注入什么内容,但不能挡住用户的输入或改变会话
|
|
117
|
+
export function contextOf(hostOutput) {
|
|
118
|
+
if (hostOutput?.mode === 'stdout_json') {
|
|
119
|
+
return (
|
|
120
|
+
hostOutput.value?.hookSpecificOutput?.additionalContext ??
|
|
121
|
+
hostOutput.value?.injectSteps?.[0]?.systemMessage?.systemMessage
|
|
122
|
+
)
|
|
123
|
+
}
|
|
124
|
+
if (hostOutput?.mode === 'stdout_text') return hostOutput.value
|
|
125
|
+
// 没有专门输出格式的运行时:服务端直接给文本
|
|
126
|
+
if (hostOutput?.mode === 'return_value') {
|
|
127
|
+
return (
|
|
128
|
+
hostOutput.value?.systemContext ??
|
|
129
|
+
hostOutput.value?.promptContext ??
|
|
130
|
+
hostOutput.value?.context
|
|
131
|
+
)
|
|
132
|
+
}
|
|
133
|
+
return undefined
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// 把一个生命周期事件交给服务端;连不上、超时、取消、跳转与非 2xx 都以 KiokuFailure 抛出
|
|
137
|
+
export async function postEvent(base, key, body, timeout, signal) {
|
|
138
|
+
let res
|
|
139
|
+
try {
|
|
140
|
+
res = await fetch(`${base}/v1/lifecycle/event`, {
|
|
141
|
+
method: 'POST',
|
|
142
|
+
headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
|
|
143
|
+
body: JSON.stringify(body),
|
|
144
|
+
redirect: 'manual',
|
|
145
|
+
// 宿主给了中止信号时(用户取消了这次输入)一起听
|
|
146
|
+
signal: signal
|
|
147
|
+
? AbortSignal.any([AbortSignal.timeout(timeout), signal])
|
|
148
|
+
: AbortSignal.timeout(timeout),
|
|
149
|
+
})
|
|
150
|
+
} catch (err) {
|
|
151
|
+
if (signal?.aborted) throw new KiokuFailure('已取消')
|
|
152
|
+
throw new KiokuFailure(fetchFailure(err, timeout))
|
|
153
|
+
}
|
|
154
|
+
if (isRedirect(res.status)) {
|
|
155
|
+
throw new Misconfigured(redirectError(res.status, res.headers.get('location'), base), 'url')
|
|
156
|
+
}
|
|
157
|
+
if (res.status === 401 || res.status === 503) {
|
|
158
|
+
const rejected = rejectionOf(res.status, await res.json().catch(() => null))
|
|
159
|
+
if (rejected) throw rejected
|
|
160
|
+
}
|
|
161
|
+
if (!res.ok) throw new KiokuFailure(`HTTP ${res.status}`)
|
|
162
|
+
return res
|
|
163
|
+
}
|
|
@@ -0,0 +1,171 @@
|
|
|
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 {
|
|
9
|
+
fetchFailure,
|
|
10
|
+
isRedirect,
|
|
11
|
+
jsonOrNull,
|
|
12
|
+
KiokuFailure,
|
|
13
|
+
redirectError,
|
|
14
|
+
rejectionOf,
|
|
15
|
+
} from './http.mjs'
|
|
16
|
+
import { profileDir, profileFile } from './profile.mjs'
|
|
17
|
+
import { plain } from './text.mjs'
|
|
18
|
+
|
|
19
|
+
export const TOOLS_TIMEOUT = 8000
|
|
20
|
+
export const TOOL_CALL_TIMEOUT = 30_000
|
|
21
|
+
|
|
22
|
+
// 回答可能是一段事件流:合并同一事件里的多行 data,取最后一条非空载荷
|
|
23
|
+
function payloadOf(text, contentType) {
|
|
24
|
+
if (!contentType.includes('text/event-stream')) return text
|
|
25
|
+
const events = []
|
|
26
|
+
let current = []
|
|
27
|
+
for (const rawLine of text.split(/\r?\n/)) {
|
|
28
|
+
if (rawLine === '') {
|
|
29
|
+
if (current.length) {
|
|
30
|
+
events.push(current.join('\n'))
|
|
31
|
+
current = []
|
|
32
|
+
}
|
|
33
|
+
continue
|
|
34
|
+
}
|
|
35
|
+
if (rawLine.startsWith('data:')) current.push(rawLine.slice(5).trimStart())
|
|
36
|
+
}
|
|
37
|
+
if (current.length) events.push(current.join('\n'))
|
|
38
|
+
return (
|
|
39
|
+
events
|
|
40
|
+
.map((chunk) => chunk.trim())
|
|
41
|
+
.filter((chunk) => chunk && chunk !== '[DONE]')
|
|
42
|
+
.at(-1) ?? ''
|
|
43
|
+
)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// 一次 JSON-RPC 调用,返回 result。连不上、超时、取消、跳转、访问密钥无效、响应不对、服务端报错都以 KiokuFailure 抛出
|
|
47
|
+
export async function mcpCall({ url, key }, method, params, timeout, signal) {
|
|
48
|
+
let res
|
|
49
|
+
let text
|
|
50
|
+
try {
|
|
51
|
+
res = await fetch(`${url}/v1/mcp`, {
|
|
52
|
+
method: 'POST',
|
|
53
|
+
headers: {
|
|
54
|
+
'content-type': 'application/json',
|
|
55
|
+
accept: 'application/json, text/event-stream',
|
|
56
|
+
authorization: `Bearer ${key}`,
|
|
57
|
+
},
|
|
58
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
|
|
59
|
+
// 不跟着跳转走:访问密钥只发给配置的地址
|
|
60
|
+
redirect: 'manual',
|
|
61
|
+
signal: signal
|
|
62
|
+
? AbortSignal.any([AbortSignal.timeout(timeout), signal])
|
|
63
|
+
: AbortSignal.timeout(timeout),
|
|
64
|
+
})
|
|
65
|
+
text = await res.text()
|
|
66
|
+
} catch (err) {
|
|
67
|
+
if (signal?.aborted) throw new KiokuFailure('已取消')
|
|
68
|
+
throw new KiokuFailure(fetchFailure(err, timeout))
|
|
69
|
+
}
|
|
70
|
+
if (isRedirect(res.status)) {
|
|
71
|
+
throw new KiokuFailure(redirectError(res.status, res.headers.get('location'), url))
|
|
72
|
+
}
|
|
73
|
+
// 401 与数据库不可用的 503 带着错误码,优先用这边的清晰提示
|
|
74
|
+
const rejected = res.ok ? null : rejectionOf(res.status, jsonOrNull(text))
|
|
75
|
+
if (rejected) throw rejected
|
|
76
|
+
if (!res.ok) throw new KiokuFailure(`Kioku 返回 HTTP ${res.status}`)
|
|
77
|
+
let data
|
|
78
|
+
try {
|
|
79
|
+
data = JSON.parse(payloadOf(text, res.headers.get('content-type') ?? ''))
|
|
80
|
+
} catch {
|
|
81
|
+
data = null
|
|
82
|
+
}
|
|
83
|
+
if (data === null || typeof data !== 'object') throw new KiokuFailure('Kioku 的响应格式不对')
|
|
84
|
+
if (data.error) {
|
|
85
|
+
// 服务端写的原因压成一行再给
|
|
86
|
+
const reason = plain(data.error.message)
|
|
87
|
+
throw new KiokuFailure(reason ? `Kioku 没有接受这次调用:${reason}` : 'Kioku 没有接受这次调用')
|
|
88
|
+
}
|
|
89
|
+
return data.result
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// 清单里能用的工具:名字、说明、参数的 schema 都在的
|
|
93
|
+
export function toolsOf(result) {
|
|
94
|
+
const tools = Array.isArray(result?.tools) ? result.tools : []
|
|
95
|
+
return tools
|
|
96
|
+
.filter(
|
|
97
|
+
(tool) =>
|
|
98
|
+
typeof tool?.name === 'string' &&
|
|
99
|
+
tool.name &&
|
|
100
|
+
typeof tool.description === 'string' &&
|
|
101
|
+
tool.inputSchema !== null &&
|
|
102
|
+
typeof tool.inputSchema === 'object' &&
|
|
103
|
+
!Array.isArray(tool.inputSchema),
|
|
104
|
+
)
|
|
105
|
+
.map(({ name, description, inputSchema }) => ({ name, description, inputSchema }))
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export async function listTools(target, signal) {
|
|
109
|
+
return toolsOf(await mcpCall(target, 'tools/list', {}, TOOLS_TIMEOUT, signal))
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// 调用一个工具,返回 { text, isError }:结果里的文字块连成一段
|
|
113
|
+
export async function callTool(target, name, args, signal) {
|
|
114
|
+
const result = await mcpCall(
|
|
115
|
+
target,
|
|
116
|
+
'tools/call',
|
|
117
|
+
{ name, arguments: args ?? {} },
|
|
118
|
+
TOOL_CALL_TIMEOUT,
|
|
119
|
+
signal,
|
|
120
|
+
)
|
|
121
|
+
const blocks = Array.isArray(result?.content) ? result.content : []
|
|
122
|
+
const text = blocks
|
|
123
|
+
.filter((block) => block?.type === 'text' && typeof block.text === 'string')
|
|
124
|
+
.map((block) => block.text)
|
|
125
|
+
.join('\n')
|
|
126
|
+
return { text, isError: result?.isError === true }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// 工具清单在本机留一份:平台要求登记工具时当场给出清单、等不了一次请求的(OpenClaw 的工具工厂是同步的),
|
|
130
|
+
// 先用这一份,取到新的再换。和地址、访问密钥放在同一个目录,记着是哪个地址的清单
|
|
131
|
+
export function toolCacheFile(platform, env) {
|
|
132
|
+
return profileFile(platform, env).replace(/\.json$/, '-tools.json')
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// 同步读这一份;没有、读不懂时为 null。at 是取到这份清单的时刻(毫秒),没记时为 0
|
|
136
|
+
export function readToolCacheSync(platform, env) {
|
|
137
|
+
try {
|
|
138
|
+
const data = JSON.parse(readFileSync(toolCacheFile(platform, env), 'utf8'))
|
|
139
|
+
if (typeof data?.url !== 'string') return null
|
|
140
|
+
const at = Number.isFinite(data.at) && data.at > 0 ? data.at : 0
|
|
141
|
+
const keyHash = typeof data.keyHash === 'string' && data.keyHash ? data.keyHash : undefined
|
|
142
|
+
return { url: data.url, ...(keyHash ? { keyHash } : {}), at, tools: toolsOf(data) }
|
|
143
|
+
} catch {
|
|
144
|
+
return null
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// 写不进去不算失败:下次再取
|
|
149
|
+
export async function writeToolCache(
|
|
150
|
+
platform,
|
|
151
|
+
{ url, keyHash = undefined, tools, at = Date.now() },
|
|
152
|
+
env,
|
|
153
|
+
) {
|
|
154
|
+
const file = toolCacheFile(platform, env)
|
|
155
|
+
const temp = `${file}.${randomUUID()}.tmp`
|
|
156
|
+
try {
|
|
157
|
+
await mkdir(profileDir(env), { recursive: true, mode: 0o700 })
|
|
158
|
+
const body = { url, ...(keyHash ? { keyHash } : {}), at, tools }
|
|
159
|
+
await writeFile(temp, `${JSON.stringify(body)}\n`, { mode: 0o600, flag: 'wx' })
|
|
160
|
+
await chmod(temp, 0o600)
|
|
161
|
+
await rename(temp, file)
|
|
162
|
+
return true
|
|
163
|
+
} catch {
|
|
164
|
+
await rm(temp, { force: true }).catch(() => {})
|
|
165
|
+
return false
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export async function removeToolCache(platform, env) {
|
|
170
|
+
await rm(toolCacheFile(platform, env), { force: true }).catch(() => {})
|
|
171
|
+
}
|
|
@@ -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
|
+
}
|