@kioku-memory/cli 0.0.0 → 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.
package/lib/import.mjs ADDED
@@ -0,0 +1,262 @@
1
+ // kioku import:把平台自带的本地长期记忆迁进 Kioku。先读本地文件出一份计划(每条放到哪个坐标),
2
+ // 和 Kioku 里已有的比过之后列出来,确认了才写。坐标由来源决定,所以重复运行不会重复写:
3
+ // 已经有、内容一样的跳过;已经有、内容不一样的不覆盖(可能在 Kioku 里改过),要覆盖得明说。
4
+ // 本地的文件不删、不改
5
+
6
+ import { whoami } from './api.mjs'
7
+ import { loadConfig } from './config.mjs'
8
+ import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
9
+ import { platformNames, PLATFORMS } from './platforms.mjs'
10
+ import { sourceNames, SOURCES, UNSUPPORTED_SOURCES } from './sources.mjs'
11
+ import { plain, shownUrl } from './text.mjs'
12
+ import { UsageError } from './usage.mjs'
13
+
14
+ export const IMPORT_USAGE = `用法:kioku import --from <来源> [--path <目录>] [--platform <平台>] [--dry-run] [--yes] [--overwrite]
15
+
16
+ 把平台自带的本地长期记忆迁进 Kioku:先列出每条会放到哪个坐标,确认之后才写。
17
+
18
+ --from <来源> ${sourceNames()}
19
+ --path <目录> 不用默认的位置时指明(Claude Code 是 projects 目录或某个项目的 memory 目录)
20
+ --platform <平台> 用 kioku setup 给这个平台配好的地址与访问密钥(codex、pi、hermes、openclaw、dsh);不写时读环境变量
21
+ --dry-run 只列出计划,不写
22
+ --yes 不问,直接写(不在终端里运行时要带上)
23
+ --overwrite Kioku 里同一个坐标已经有、内容不一样的也覆盖(默认跳过)
24
+
25
+ 本地的文件不删、不改。重复运行不会重复写:已经迁过、内容没变的会跳过。
26
+ 疑似明文凭据的不写,列出是哪个文件的哪一行:先把值存成凭据,或者从文件里去掉再迁。
27
+ 地址与访问密钥读 KIOKU_SERVER_URL 与 KIOKU_API_KEY(Claude Code 的会话里已经配好),或者用 --platform 指明。
28
+ 记忆迁进这个访问密钥所属的应用。
29
+ 指令文件(AGENTS.md、CLAUDE.md)不是记忆,不迁。
30
+ `
31
+
32
+ const TIMEOUT = 15_000
33
+
34
+ export function parseImportArgs(argv) {
35
+ const options = {
36
+ from: undefined,
37
+ path: undefined,
38
+ platform: undefined,
39
+ dryRun: false,
40
+ yes: false,
41
+ overwrite: false,
42
+ }
43
+ for (let i = 0; i < argv.length; i++) {
44
+ const arg = argv[i]
45
+ if (arg === '--dry-run') options.dryRun = true
46
+ else if (arg === '--yes') options.yes = true
47
+ else if (arg === '--overwrite') options.overwrite = true
48
+ else if (arg === '--from' || arg === '--path' || arg === '--platform') {
49
+ const value = argv[++i]
50
+ if (!value) throw new UsageError(`${arg} 后面要写值`)
51
+ options[arg.slice(2)] = value
52
+ } else throw new UsageError(`不认识的参数 ${arg}`)
53
+ }
54
+ if (!options.from) throw new UsageError('要写来源:--from <来源>')
55
+ if (Object.hasOwn(UNSUPPORTED_SOURCES, options.from)) {
56
+ throw new KiokuFailure(UNSUPPORTED_SOURCES[options.from])
57
+ }
58
+ if (!Object.hasOwn(SOURCES, options.from)) {
59
+ throw new UsageError(`不认识的来源 ${options.from},可以用的:${sourceNames()}`)
60
+ }
61
+ if (options.platform !== undefined && !PLATFORMS[options.platform]?.readConfig) {
62
+ throw new UsageError(
63
+ `--platform 只收用 kioku setup 写下配置的平台,可以用的:${platformNames()}`,
64
+ )
65
+ }
66
+ return options
67
+ }
68
+
69
+ async function request({ url, key }, method, path, body) {
70
+ let res
71
+ let data
72
+ try {
73
+ res = await fetch(`${url}${path}`, {
74
+ method,
75
+ headers: {
76
+ authorization: `Bearer ${key}`,
77
+ ...(body ? { 'content-type': 'application/json' } : {}),
78
+ },
79
+ ...(body ? { body: JSON.stringify(body) } : {}),
80
+ // 不跟着跳转走:访问密钥只发给配置的地址
81
+ redirect: 'manual',
82
+ signal: AbortSignal.timeout(TIMEOUT),
83
+ })
84
+ data = await res.json().catch(() => null)
85
+ } catch (err) {
86
+ throw new KiokuFailure(fetchFailure(err, TIMEOUT))
87
+ }
88
+ if (isRedirect(res.status)) {
89
+ throw new KiokuFailure(redirectError(res.status, res.headers.get('location'), url))
90
+ }
91
+ return { status: res.status, data }
92
+ }
93
+
94
+ // 服务端的错误文字压成一行;万一带着访问密钥也盖掉
95
+ function serverText(data, status, key) {
96
+ const text = typeof data?.error === 'string' ? data.error.split(key).join('***') : ''
97
+ return plain(text) || `HTTP ${status}`
98
+ }
99
+
100
+ // 和 Kioku 里现有的比:new 没有,same 有且正文一样,differs 有但不一样(含读不到正文的机密)
101
+ async function compare(config, item) {
102
+ const { status, data } = await request(
103
+ config,
104
+ 'GET',
105
+ `/v1/memories?uri=${encodeURIComponent(item.uri)}`,
106
+ )
107
+ if (status === 404) return { ...item, state: 'new' }
108
+ if (status !== 200)
109
+ return { ...item, state: 'failed', reason: serverText(data, status, config.key) }
110
+ const same = typeof data?.content === 'string' && data.content.trim() === item.content
111
+ return { ...item, state: same ? 'same' : 'differs', version: data?.version, id: data?.id }
112
+ }
113
+
114
+ // 写一条:新建,或者覆盖已有的。返回 { ok } 或 { ok: false, reason, plaintext }
115
+ async function write(config, item) {
116
+ const fields = {
117
+ uri: item.uri,
118
+ title: item.title,
119
+ content: item.content,
120
+ ...(item.disclosure ? { disclosure: item.disclosure } : {}),
121
+ }
122
+ const { status, data } =
123
+ item.state === 'differs'
124
+ ? await request(config, 'PATCH', '/v1/memories', {
125
+ ...fields,
126
+ ...(Number.isInteger(item.version) ? { expectedVersion: item.version } : {}),
127
+ ...(item.id ? { expectedId: item.id } : {}),
128
+ })
129
+ : await request(config, 'POST', '/v1/memories', fields)
130
+ if (status === 200 || status === 201) return { ok: true }
131
+ const plaintext = Array.isArray(data?.plaintext) ? data.plaintext : null
132
+ return { ok: false, reason: serverText(data, status, config.key), plaintext }
133
+ }
134
+
135
+ const KINDS = { new: '新建', same: '已有,内容一样', differs: '已有,内容不一样' }
136
+
137
+ // 问一句是或否;只认 y 开头的回答
138
+ async function confirm(question, { stdin, out }) {
139
+ out.write(question)
140
+ for await (const chunk of stdin) {
141
+ return /^\s*y/i.test(chunk.toString('utf8'))
142
+ }
143
+ return false
144
+ }
145
+
146
+ export async function importMemories(
147
+ argv,
148
+ { env = process.env, out = process.stdout, stdin = process.stdin } = {},
149
+ ) {
150
+ const options = parseImportArgs(argv)
151
+ const source = SOURCES[options.from]
152
+ // 地址与访问密钥:指明了平台就用 kioku setup 给它写下的,否则读环境变量
153
+ let config
154
+ if (options.platform) {
155
+ config = await PLATFORMS[options.platform].readConfig(env)
156
+ if (!config) {
157
+ throw new KiokuFailure(
158
+ `还没有给 ${options.platform} 配过:先运行 kioku setup ${options.platform}`,
159
+ )
160
+ }
161
+ } else config = await loadConfig(env)
162
+ const who = await whoami(config)
163
+ out.write(
164
+ `Kioku:${shownUrl(config.url)},应用 ${plain(who.app.name)}(${plain(who.app.slug)})\n`,
165
+ )
166
+
167
+ const { root, found, entries } = await source.read({
168
+ env,
169
+ path: options.path,
170
+ app: who.app.slug,
171
+ })
172
+ if (!found)
173
+ throw new KiokuFailure(`没有找到${source.name}:${plain(root)} 不是目录,用 --path 指明位置`)
174
+ out.write(`来源:${source.name}(${plain(root)})\n`)
175
+ if (!entries.length) {
176
+ out.write('没有可以迁的记忆\n')
177
+ return 0
178
+ }
179
+
180
+ // 两条落到同一个坐标的(名字规整之后撞了)只留第一条
181
+ const seen = new Set()
182
+ const usable = []
183
+ const skipped = []
184
+ for (const item of entries) {
185
+ if (item.skipped) skipped.push(item)
186
+ else if (seen.has(item.uri))
187
+ skipped.push({ ...item, skipped: `和前面的一条落到同一个坐标 ${item.uri}` })
188
+ else {
189
+ seen.add(item.uri)
190
+ usable.push(item)
191
+ }
192
+ }
193
+ const compared = []
194
+ for (const item of usable) compared.push(await compare(config, item))
195
+
196
+ out.write('\n')
197
+ for (const item of compared) {
198
+ const kind = item.state === 'failed' ? `读取失败(${item.reason})` : KINDS[item.state]
199
+ out.write(`${kind} ${item.uri}\n ${plain(item.title)}\n ← ${plain(item.source)}\n`)
200
+ }
201
+ for (const item of skipped) out.write(`不迁 ${plain(item.source)}\n ${item.skipped}\n`)
202
+
203
+ const count = (state) => compared.filter((item) => item.state === state).length
204
+ const todo = compared.filter(
205
+ (item) => item.state === 'new' || (item.state === 'differs' && options.overwrite),
206
+ )
207
+ out.write(
208
+ `\n新建 ${count('new')} 条,已有且一样 ${count('same')} 条,已有但不一样 ${count('differs')} 条` +
209
+ `(${options.overwrite ? '覆盖' : '跳过,要覆盖加 --overwrite'}),不迁 ${skipped.length} 条\n`,
210
+ )
211
+ if (options.dryRun) {
212
+ out.write('没有写入(--dry-run)\n')
213
+ return 0
214
+ }
215
+ if (!todo.length) {
216
+ out.write('没有要写的\n')
217
+ return compared.some((item) => item.state === 'failed') ? 1 : 0
218
+ }
219
+ if (!options.yes) {
220
+ if (!stdin.isTTY)
221
+ throw new KiokuFailure('不在终端里运行时要带 --yes 才写;先用 --dry-run 看计划')
222
+ if (!(await confirm(`写入这 ${todo.length} 条?[y/N] `, { stdin, out }))) {
223
+ out.write('没有写入\n')
224
+ return 0
225
+ }
226
+ }
227
+
228
+ let written = 0
229
+ const failed = []
230
+ // 连不上、超时这类不是某一条的问题:停下来,把已经写了多少、还剩多少说清楚,不让它跳出整个命令
231
+ let stopped = null
232
+ for (const [index, item] of todo.entries()) {
233
+ let result
234
+ try {
235
+ result = await write(config, item)
236
+ } catch (err) {
237
+ if (!(err instanceof KiokuFailure)) throw err
238
+ stopped = { reason: err.message, left: todo.length - index }
239
+ break
240
+ }
241
+ if (result.ok) written++
242
+ else failed.push({ item, ...result })
243
+ }
244
+ out.write(`\n写入 ${written} 条\n`)
245
+ for (const { item, reason, plaintext } of failed) {
246
+ out.write(`没有写入 ${item.uri}\n ← ${plain(item.source)}\n ${reason}\n`)
247
+ // 只说第几行、哪一类,不带值;行号按正文算(文件头之后)
248
+ for (const spot of plaintext ?? []) {
249
+ out.write(` 正文第 ${Number(spot.line) || '?'} 行:${plain(spot.kind)}\n`)
250
+ }
251
+ }
252
+ if (failed.some((entry) => entry.plaintext)) {
253
+ out.write('疑似明文凭据的没有写:把值存成凭据、正文里写占位符,或者从文件里去掉,再运行一次\n')
254
+ }
255
+ if (stopped) {
256
+ out.write(
257
+ `${stopped.reason}:还有 ${stopped.left} 条没有写,重新运行会接着写(已经写进去的会跳过)\n`,
258
+ )
259
+ }
260
+ out.write('本地的文件没有动。\n')
261
+ return stopped || failed.length || compared.some((item) => item.state === 'failed') ? 1 : 0
262
+ }
package/lib/kioku.mjs CHANGED
@@ -7,9 +7,19 @@ import { spawn } from 'node:child_process'
7
7
  import { constants } from 'node:os'
8
8
  import { isatty } from 'node:tty'
9
9
 
10
+ import { killTree, launch } from './command.mjs'
10
11
  import { loadConfig } from './config.mjs'
12
+ import { IMPORT_USAGE, importMemories } from './import.mjs'
13
+ import { login, LOGIN_USAGE } from './login.mjs'
11
14
  import { doctor, DOCTOR_USAGE } from './doctor.mjs'
12
- import { errorKind, fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
15
+ import {
16
+ errorKind,
17
+ failureText,
18
+ fetchFailure,
19
+ isRedirect,
20
+ KiokuFailure,
21
+ redirectError,
22
+ } from './http.mjs'
13
23
  import { setup, SETUP_USAGE } from './setup.mjs'
14
24
  import { UsageError } from './usage.mjs'
15
25
  import { createRedactor, MIN_REDACT_CHARS, redactable } from './redact.mjs'
@@ -251,11 +261,23 @@ function exitBySignal(signal) {
251
261
  function runCommand(command, args, env, values) {
252
262
  return new Promise((resolve) => {
253
263
  let child
264
+ let run
254
265
  try {
266
+ // Windows 上 npm、pnpm 这类命令是 .cmd,要经 cmd.exe 起(launch 算好怎么起)
267
+ run = launch(command, args, env)
268
+ if (!run) {
269
+ process.stderr.write(`kioku:找不到命令 ${command}\n`)
270
+ resolve(127)
271
+ return
272
+ }
255
273
  // 不用 detached:命令留在 kioku 的进程组里,整组被结束时它不会变成带着值的孤儿进程
256
- child = spawn(command, args, { env, stdio: ['inherit', 'pipe', 'pipe'] })
274
+ child = spawn(run.file, run.args, {
275
+ env,
276
+ stdio: ['inherit', 'pipe', 'pipe'],
277
+ ...run.options,
278
+ })
257
279
  } catch (err) {
258
- process.stderr.write(`kioku:无法启动 ${command}(${errorKind(err)})\n`)
280
+ process.stderr.write(`kioku:无法启动 ${command}(${failureText(err)})\n`)
259
281
  resolve(126)
260
282
  return
261
283
  }
@@ -270,7 +292,8 @@ function runCommand(command, args, env, values) {
270
292
  }
271
293
  const onSignal = (signal) => {
272
294
  if (child.exitCode === null && child.signalCode === null) {
273
- if (signal !== 'SIGINT' || !FROM_TERMINAL) child.kill(signal)
295
+ // 隔着 cmd.exe 时连它下面真正的命令一起结束,不留一个带着值的进程
296
+ if (signal !== 'SIGINT' || !FROM_TERMINAL) killTree(child, signal, { shell: run.shell })
274
297
  return
275
298
  }
276
299
  if (late === undefined) {
@@ -356,8 +379,10 @@ async function run(argv) {
356
379
  const OVERVIEW = `用法:kioku <子命令> [参数…]
357
380
 
358
381
  run 向 Kioku 取凭据的值,放进环境变量交给命令
382
+ login 用浏览器授权签发访问密钥并配好这个平台
359
383
  setup 停用平台自带的长期记忆,由 Kioku 接管
360
384
  doctor 检查地址、访问密钥与平台的配置
385
+ import 把平台自带的本地长期记忆迁进 Kioku
361
386
 
362
387
  各子命令的说明:kioku <子命令> --help
363
388
  `
@@ -390,8 +415,10 @@ export async function main(argv) {
390
415
  return 0
391
416
  }
392
417
  if (sub === 'run') return run(rest)
418
+ if (sub === 'login') return guarded('login', LOGIN_USAGE, login, rest)
393
419
  if (sub === 'setup') return guarded('setup', SETUP_USAGE, setup, rest)
394
420
  if (sub === 'doctor') return guarded('doctor', DOCTOR_USAGE, doctor, rest)
421
+ if (sub === 'import') return guarded('import', IMPORT_USAGE, importMemories, rest)
395
422
  process.stderr.write(sub === undefined ? OVERVIEW : `kioku:不认识的子命令 ${sub}\n\n${OVERVIEW}`)
396
423
  return 2
397
424
  }
package/lib/lifecycle.mjs CHANGED
@@ -3,7 +3,7 @@
3
3
  // 报错和 kioku 命令一样不带访问密钥:格式不对的访问密钥不发出去,fetch 的报错只取类别,
4
4
  // 也不跟着跳转走,访问密钥只发给配置的地址
5
5
 
6
- import { execFileSync } from 'node:child_process'
6
+ import { execFile, execFileSync } from 'node:child_process'
7
7
  import { basename } from 'node:path'
8
8
 
9
9
  import { fetchFailure, isRedirect, keyFormatError, KiokuFailure, redirectError } from './http.mjs'
@@ -62,17 +62,38 @@ export function projectOf(cwd) {
62
62
  return project
63
63
  }
64
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
+
65
84
  // 服务端要注入的上下文文本;没有时为 undefined。只取文本,输出里的其他字段一律不用:
66
85
  // 记忆服务能决定注入什么内容,但不能挡住用户的输入或改变会话
67
86
  export function contextOf(hostOutput) {
68
87
  if (hostOutput?.mode === 'stdout_json')
69
88
  return hostOutput.value?.hookSpecificOutput?.additionalContext
70
89
  if (hostOutput?.mode === 'stdout_text') return hostOutput.value
90
+ // 没有专门输出格式的运行时:服务端直接给文本
91
+ if (hostOutput?.mode === 'return_value') return hostOutput.value?.context
71
92
  return undefined
72
93
  }
73
94
 
74
- // 把一个生命周期事件交给服务端;连不上、超时、跳转与非 2xx 都以 KiokuFailure 抛出
75
- export async function postEvent(base, key, body, timeout) {
95
+ // 把一个生命周期事件交给服务端;连不上、超时、取消、跳转与非 2xx 都以 KiokuFailure 抛出
96
+ export async function postEvent(base, key, body, timeout, signal) {
76
97
  let res
77
98
  try {
78
99
  res = await fetch(`${base}/v1/lifecycle/event`, {
@@ -80,9 +101,13 @@ export async function postEvent(base, key, body, timeout) {
80
101
  headers: { 'content-type': 'application/json', authorization: `Bearer ${key}` },
81
102
  body: JSON.stringify(body),
82
103
  redirect: 'manual',
83
- signal: AbortSignal.timeout(timeout),
104
+ // 宿主给了中止信号时(用户取消了这次输入)一起听
105
+ signal: signal
106
+ ? AbortSignal.any([AbortSignal.timeout(timeout), signal])
107
+ : AbortSignal.timeout(timeout),
84
108
  })
85
109
  } catch (err) {
110
+ if (signal?.aborted) throw new KiokuFailure('已取消')
86
111
  throw new KiokuFailure(fetchFailure(err, timeout))
87
112
  }
88
113
  if (isRedirect(res.status)) {
package/lib/login.mjs ADDED
@@ -0,0 +1,257 @@
1
+ // kioku login:浏览器授权。命令行向 Kioku 申请,显示一个确认码;用户在管理界面的确认页输入它、
2
+ // 选好空间与权限后确认,命令行取走访问密钥,交给这个平台的 kioku setup 写下。
3
+ // 访问密钥不显示、不写进输出;确认码不放进打开的地址里,要用户照着终端输入:别人发来的链接带不了它。
4
+ // 服务端的回答不全信:确认页的路径只收一种写法,时限与间隔收在一个范围里
5
+
6
+ import { spawn } from 'node:child_process'
7
+ import { hostname } from 'node:os'
8
+
9
+ import { fetchFailure, isRedirect, KiokuFailure, redirectError } from './http.mjs'
10
+ import { platformNames, PLATFORMS } from './platforms.mjs'
11
+ import { resolveServerUrl } from './target.mjs'
12
+ import { plain } from './text.mjs'
13
+ import { UsageError } from './usage.mjs'
14
+
15
+ export const LOGIN_USAGE = `用法:kioku login <平台> [--server-url <地址>] [--no-browser]
16
+
17
+ 用浏览器授权给这个平台签发一个访问密钥并配好,不用手动复制:终端显示一个确认码,
18
+ 在 Kioku 管理界面的确认页输入它,选好空间与权限后确认。
19
+
20
+ <平台> ${platformNames()}(Claude Code 的访问密钥在它的 /plugin 里填,不走这里)
21
+ --server-url <地址> Kioku 的服务地址,例如 https://kioku.example.com(也可以用 KIOKU_SERVER_URL;配过的沿用上次的)
22
+ --no-browser 不自动打开浏览器,只显示地址
23
+
24
+ 只在自己刚运行了这条命令时确认:确认之后,这台机器会拿到一个能按所选权限读写记忆的访问密钥。
25
+ `
26
+
27
+ const TIMEOUT = 8000
28
+ // 连着这么多次没得到回答(连不上、服务端 5xx)才放弃:等确认的这几分钟里抖一下不算失败
29
+ const MAX_FAILURES = 5
30
+ // 确认页的路径只收这种写法:接在服务地址后面打开,不带查询参数与别的符号
31
+ const VERIFICATION_PATH = /^\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/
32
+ // 服务端给的时限与间隔收在这个范围里(秒):给得再离谱也不会一直等、不会忙等
33
+ const MAX_EXPIRES = 1800
34
+ const MIN_INTERVAL = 1
35
+ const MAX_INTERVAL = 60
36
+
37
+ // 地址返回了跳转:配置的问题,重试没有用
38
+ class Redirected extends KiokuFailure {}
39
+
40
+ // 取走访问密钥这一步之后出的问题:访问密钥可能已经签发、却没有落到这台机器上
41
+ const ORPHAN_HINT =
42
+ '如果确认页上已经点了确认,可能已经签发了一个没被取走的访问密钥:到管理界面的应用页吊销它,再重新运行'
43
+
44
+ async function post(url, path, body) {
45
+ let res
46
+ let data
47
+ try {
48
+ res = await fetch(`${url}${path}`, {
49
+ method: 'POST',
50
+ headers: { 'content-type': 'application/json' },
51
+ body: JSON.stringify(body),
52
+ // 不跟着跳转走:设备码只发给配置的地址
53
+ redirect: 'manual',
54
+ signal: AbortSignal.timeout(TIMEOUT),
55
+ })
56
+ data = await res.json().catch(() => null)
57
+ } catch (err) {
58
+ throw new KiokuFailure(fetchFailure(err, TIMEOUT))
59
+ }
60
+ if (isRedirect(res.status)) {
61
+ throw new Redirected(redirectError(res.status, res.headers.get('location'), url))
62
+ }
63
+ return { status: res.status, data }
64
+ }
65
+
66
+ // 服务端给的秒数收进范围;不是有限的正数时用默认值
67
+ function seconds(value, fallback, min, max) {
68
+ const number = typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback
69
+ return Math.min(max, Math.max(min, number))
70
+ }
71
+
72
+ // 申请:返回设备码、确认码、确认页的地址与时限
73
+ export async function requestGrant(url, { runtimeFamily, clientName }) {
74
+ const { status, data } = await post(url, '/v1/device/authorize', {
75
+ runtimeFamily,
76
+ ...(clientName ? { clientName } : {}),
77
+ })
78
+ if (status === 404) {
79
+ throw new KiokuFailure(
80
+ '这个 Kioku 还不支持浏览器授权:升级服务端,或者用 kioku setup 手动填访问密钥',
81
+ )
82
+ }
83
+ if (status === 429) throw new KiokuFailure('待确认的申请太多,稍后再试')
84
+ if (status !== 201) throw new KiokuFailure(`Kioku 返回 HTTP ${status}`)
85
+ if (
86
+ typeof data?.deviceCode !== 'string' ||
87
+ !data.deviceCode ||
88
+ typeof data.userCode !== 'string' ||
89
+ typeof data.verificationPath !== 'string' ||
90
+ !VERIFICATION_PATH.test(data.verificationPath)
91
+ ) {
92
+ throw new KiokuFailure('Kioku 的响应格式不对')
93
+ }
94
+ return {
95
+ deviceCode: data.deviceCode,
96
+ userCode: data.userCode,
97
+ verificationUrl: `${url}${data.verificationPath}`,
98
+ expiresIn: seconds(data.expiresIn, 600, 1, MAX_EXPIRES),
99
+ interval: seconds(data.interval, 3, MIN_INTERVAL, MAX_INTERVAL),
100
+ }
101
+ }
102
+
103
+ // 等确认:按服务端给的间隔轮询,返回访问密钥与应用;被拒绝、过期时抛 KiokuFailure。
104
+ // sleep 与 now 可以换掉,给用例用;now 要是只往前走的钟,系统时间被改不影响什么时候停
105
+ export async function waitForKey(
106
+ url,
107
+ grant,
108
+ {
109
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
110
+ now = () => performance.now(),
111
+ } = {},
112
+ ) {
113
+ const deadline = now() + grant.expiresIn * 1000
114
+ let interval = grant.interval * 1000
115
+ let failures = 0
116
+ // 有过没得到回答的轮询:那一次服务端可能已经把访问密钥签出来了
117
+ let missed = false
118
+ while (now() < deadline) {
119
+ await sleep(interval)
120
+ let answer
121
+ try {
122
+ answer = await post(url, '/v1/device/token', { deviceCode: grant.deviceCode })
123
+ } catch (err) {
124
+ if (err instanceof Redirected) throw err
125
+ missed = true
126
+ if (++failures >= MAX_FAILURES) throw new KiokuFailure(`${err.message}。${ORPHAN_HINT}`)
127
+ continue
128
+ }
129
+ const { status, data } = answer
130
+ // 服务端嫌太勤:隔久一点
131
+ if (status === 429) {
132
+ interval = Math.min(interval + 1000, MAX_INTERVAL * 1000)
133
+ continue
134
+ }
135
+ // 服务端一时出错(重启、网关)和连不上一样,过会儿再问
136
+ if (status >= 500) {
137
+ missed = true
138
+ if (++failures >= MAX_FAILURES) {
139
+ throw new KiokuFailure(`Kioku 返回 HTTP ${status}。${ORPHAN_HINT}`)
140
+ }
141
+ continue
142
+ }
143
+ if (status !== 200) throw new KiokuFailure(`Kioku 返回 HTTP ${status}`)
144
+ failures = 0
145
+ if (data?.status === 'pending') continue
146
+ if (data?.status === 'denied') {
147
+ throw new KiokuFailure('申请被拒绝了,或者确认之后确认人的权限变了:没有签发访问密钥')
148
+ }
149
+ if (data?.status === 'approved' && typeof data.key === 'string' && data.key) {
150
+ return { key: data.key, app: data.app ?? {} }
151
+ }
152
+ if (data?.status === 'expired') break
153
+ throw new KiokuFailure('Kioku 的响应格式不对')
154
+ }
155
+ throw new KiokuFailure(
156
+ missed
157
+ ? `申请已经不在了,没有取到访问密钥。${ORPHAN_HINT}`
158
+ : '申请过期了,没有等到确认:重新运行 kioku login',
159
+ )
160
+ }
161
+
162
+ // 用系统默认的浏览器打开地址;打不开就算了,地址已经显示在终端里。都不经过 shell:
163
+ // Windows 上用 rundll32,不用 cmd 的 start(它会把地址里的 & 这类符号当成命令)
164
+ function openBrowser(address) {
165
+ const [command, args] =
166
+ process.platform === 'darwin'
167
+ ? ['open', [address]]
168
+ : process.platform === 'win32'
169
+ ? ['rundll32', ['url.dll,FileProtocolHandler', address]]
170
+ : ['xdg-open', [address]]
171
+ try {
172
+ const child = spawn(command, args, { stdio: 'ignore', detached: true })
173
+ child.on('error', () => {})
174
+ child.unref()
175
+ } catch {
176
+ // 没有图形界面
177
+ }
178
+ }
179
+
180
+ // 走一遍浏览器授权,返回访问密钥。提示写到 out,访问密钥不写
181
+ export async function deviceLogin(
182
+ { url, runtimeFamily },
183
+ { out, open = openBrowser, browser = true, clientName = hostname(), sleep, now } = {},
184
+ ) {
185
+ // 机器名是自报的:去掉控制字符,太长就截断,服务端只把它显示在确认页上
186
+ const name = Array.from(plain(clientName)).slice(0, 64).join('')
187
+ const grant = await requestGrant(url, { runtimeFamily, clientName: name })
188
+ out.write(`确认码:${plain(grant.userCode)}\n`)
189
+ // 显示的和打开的是同一个地址
190
+ out.write(`在浏览器里打开 ${plain(grant.verificationUrl)},登录后输入这个确认码\n`)
191
+ out.write(`等待确认(${Math.ceil(grant.expiresIn / 60)} 分钟内有效)…\n`)
192
+ if (browser) open(grant.verificationUrl)
193
+ const { key, app } = await waitForKey(url, grant, { sleep, now })
194
+ out.write(`✓ 已确认:应用 ${plain(app.name ?? '')}(${plain(app.slug ?? '')})\n`)
195
+ return key
196
+ }
197
+
198
+ export function parseLoginArgs(argv) {
199
+ const options = { serverUrl: undefined, browser: true }
200
+ const names = []
201
+ for (let i = 0; i < argv.length; i++) {
202
+ const arg = argv[i]
203
+ if (arg === '--no-browser') options.browser = false
204
+ else if (arg === '--server-url') {
205
+ options.serverUrl = argv[++i]
206
+ if (!options.serverUrl) throw new UsageError('--server-url 后面要写地址')
207
+ } else if (arg.startsWith('-')) throw new UsageError(`不认识的选项 ${arg}`)
208
+ else names.push(arg)
209
+ }
210
+ if (names.length !== 1) throw new UsageError('要写一个平台')
211
+ if (!Object.hasOwn(PLATFORMS, names[0])) {
212
+ throw new UsageError(`不认识的平台 ${names[0]},可以用的:${platformNames()}`)
213
+ }
214
+ if (!PLATFORMS[names[0]].setup) {
215
+ throw new UsageError(
216
+ `${PLATFORMS[names[0]].name} 的访问密钥在它自己的插件配置里填,不走 kioku login`,
217
+ )
218
+ }
219
+ return { ...options, platform: names[0] }
220
+ }
221
+
222
+ export async function login(
223
+ argv,
224
+ {
225
+ env = process.env,
226
+ out = process.stdout,
227
+ cwd = process.cwd(),
228
+ open,
229
+ sleep,
230
+ now,
231
+ clientName,
232
+ } = {},
233
+ ) {
234
+ const options = parseLoginArgs(argv)
235
+ const platform = PLATFORMS[options.platform]
236
+ const saved = await Promise.resolve(platform.readConfig?.(env)).catch(() => null)
237
+ const url = resolveServerUrl(options, env, saved)
238
+ // 申请之前先看这个平台的配置写不写得进去:访问密钥只在签发时给一次
239
+ await platform.preflight?.({ env, cwd })
240
+ const key = await deviceLogin(
241
+ { url, runtimeFamily: platform.runtimeFamily },
242
+ { out, open, browser: options.browser, sleep, now, ...(clientName ? { clientName } : {}) },
243
+ )
244
+ // 拿到的访问密钥交给这个平台的 setup:核对、写文件都照它的规矩
245
+ try {
246
+ return await platform.setup(
247
+ { serverUrl: url, dryRun: false, undo: false, check: true },
248
+ { env, out, cwd, readKey: async () => key, plain, login: null },
249
+ )
250
+ } catch (err) {
251
+ if (!(err instanceof KiokuFailure)) throw err
252
+ // 访问密钥已经签发、却没有写下来:说清楚,别让它悄悄留着
253
+ throw new KiokuFailure(
254
+ `${err.message}。访问密钥已经签发、但没有写下:到管理界面的应用页吊销它,解决上面的问题后重新运行`,
255
+ )
256
+ }
257
+ }