@kingsleyasher/dsh-knowledge-base 3.1.4 → 3.1.6

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/src/host/index.js CHANGED
@@ -31,7 +31,8 @@ import { installCommandDescriptionFallback } from './command-description.js'
31
31
  import { apply as applyTodoLifecycle } from './todo-lifecycle.js'
32
32
  import { createFlowEngine } from './flows.js'
33
33
  import { createFlowWorkspaceManager, prepareFlowConversation } from './flow-workspace.js'
34
- import { createUpdateChecker, createUpdateDownloader, startAutomaticChecks, downloadBrowserExtension } from './updates.js'
34
+ import { startAutomaticChecks, downloadBrowserExtension } from './updates.js'
35
+ import { createNpmUpdateChecker } from '../../packages/kb-service/host-updates.js'
35
36
  import { runSelftest } from './selftest.js'
36
37
  import { walkTree, privateRootOf, normSegs, toPosix as toPosixFile, DEFAULT_PRIVATE_DIRS, readImportSources, derivedPrivatePartitions, effectivePrivateDirs, knowledgeCount } from './fsindex.js'
37
38
  import { createImportService } from './import-service.js'
@@ -280,10 +281,7 @@ export function apply(ctx, config) {
280
281
  return () => { clearInterval(timer); embeddedKernel.dispose() }
281
282
  }, 'kb-workbench: opt-in background maintenance')
282
283
  const flowWorkspaceManager = createFlowWorkspaceManager({ getRegistry: () => ctx.get('workspaceRegistry') })
283
- const updateChecker = createUpdateChecker({ currentVersion: PLUGIN_VERSION })
284
- const updateProfile = ctx.get('profileContext')
285
- const updateDownloader = createUpdateDownloader({ checker: updateChecker,
286
- cacheDir: typeof updateProfile?.dir === 'string' ? path.join(updateProfile.dir, '.kb-plugin-updates') : null })
284
+ const updateChecker = createNpmUpdateChecker({ currentVersion: PLUGIN_VERSION })
287
285
  // 自动检查属于宿主后台机制,页面关闭后仍继续按周期检查。
288
286
  ctx.effect(() => startAutomaticChecks(updateChecker), 'kb-core: automatic update checks')
289
287
  // R1:UI 与工具共用的导入服务。在 install() 里创建(要等 core 就绪后才拿得到配置)。
@@ -1061,7 +1059,11 @@ let parsingService = null
1061
1059
  isConcurrencySafe: () => false,
1062
1060
  async execute(args) {
1063
1061
  // 与自检共用同一条路径:recover 的前置闸门在 drainRecoverTodo 里
1064
- return core.checkEntry(args ?? {})
1062
+ try {
1063
+ return await core.checkEntry(args ?? {})
1064
+ } catch (error) {
1065
+ return { ok: false, execution: 'error', quality: 'unknown', defects: [], reason: error.code || 'CHECK_FAILED', detail: error.message }
1066
+ }
1065
1067
  },
1066
1068
  },
1067
1069
  {
@@ -1837,9 +1839,7 @@ let parsingService = null
1837
1839
  (origin && (() => { try { return new URL(origin).host !== req.headers.host } catch { return true } })())) {
1838
1840
  return kbSendJson(res, 403, { ok: false, error: '更新请求必须来自当前客户端' })
1839
1841
  }
1840
- return kbSendJson(res,409,{ok:false,error:'嵌入模式尚无可证明的安全停服协议,自动安装已延后,请使用过渡安装入口。'})
1841
- try { return kbSendJson(res, 200, await updateDownloader.prepare({ expectedVersion: body.expectedVersion })) }
1842
- catch (error) { return kbSendJson(res, 400, { ok: false, error: String(error.message || error) }) }
1842
+ return kbSendJson(res,409,{ok:false,error:'嵌入模式暂不支持安全停服,请通过 DSH 插件管理器更新 npm 版。'})
1843
1843
  }
1844
1844
  if (body.op === 'index-maintenance.status') {
1845
1845
  const status = await current.status()
@@ -48,7 +48,7 @@ function selectedSources(ids) {
48
48
 
49
49
  // Follow only a bounded set of HTTPS redirects belonging to the selected service.
50
50
  // No cookies, authorization, mirror-provided download URLs or user paths are sent.
51
- async function sourceBytes(fetchFn, source, rel, limit, timeoutMs) {
51
+ export async function readUpdateSourceBytes(fetchFn, source, rel, limit, timeoutMs) {
52
52
  const controller = new AbortController()
53
53
  let timer = setTimeout(() => controller.abort(), timeoutMs)
54
54
  // Large archives may take longer than a metadata request. Bound idle time
@@ -102,7 +102,7 @@ export function createUpdateChecker({ currentVersion, fetch: fetchFn = globalThi
102
102
  async function channel(preview) {
103
103
  const results = await Promise.all(sources.map(async source => {
104
104
  try {
105
- const raw = await sourceBytes(fetchFn, source, preview ? 'preview-manifest.json' : 'release-manifest-v2.json', 1024 * 1024, timeoutMs)
105
+ const raw = await readUpdateSourceBytes(fetchFn, source, preview ? 'preview-manifest.json' : 'release-manifest-v2.json', 1024 * 1024, timeoutMs)
106
106
  const m = JSON.parse(raw.toString('utf8'))
107
107
  if (preview && m.package === '@local/dsh-knowledge-base' && m.channel === 'preview' && m.active === false) return { source, ok: true, inactive: true }
108
108
  const parsedVersion = parseKnowledgeVersion(m.version, { allowLegacyPreview: preview })
@@ -231,7 +231,7 @@ export function createUpdateDownloader({ checker, cacheDir, fetch: fetchFn = glo
231
231
  while (!failed && next < count) {
232
232
  const index = next++, bytes = Math.min(UPDATE_PART_BYTES, release.bytes - index * UPDATE_PART_BYTES)
233
233
  const rel = 'dist/update-parts/' + release.sha256 + '/' + String(index).padStart(4, '0') + '.b64'
234
- const encoded = await sourceBytes(fetchFn, source, rel, Math.ceil(bytes / 3) * 4 + 1, timeoutMs)
234
+ const encoded = await readUpdateSourceBytes(fetchFn, source, rel, Math.ceil(bytes / 3) * 4 + 1, timeoutMs)
235
235
  const text = encoded.toString('utf8').trim()
236
236
  if (text.length % 4 || !/^[A-Za-z0-9+/]*={0,2}$/.test(text)) throw Error('更新分片编码无效')
237
237
  const part = Buffer.from(text, 'base64')
@@ -242,7 +242,7 @@ export function createUpdateDownloader({ checker, cacheDir, fetch: fetchFn = glo
242
242
  const failure = results.find(r => r.status === 'rejected')
243
243
  if (failure) throw failure.reason
244
244
  raw = Buffer.concat(parts)
245
- } else raw = await sourceBytes(fetchFn, source, 'dist/' + encodeURIComponent(release.tgz), release.bytes, timeoutMs)
245
+ } else raw = await readUpdateSourceBytes(fetchFn, source, 'dist/' + encodeURIComponent(release.tgz), release.bytes, timeoutMs)
246
246
  verifyUpdateArchive(raw, release)
247
247
  await writeFile(temporary, raw, { flag: 'wx', mode: 0o600 })
248
248
  try { await unlink(target) } catch (error) { if (error.code !== 'ENOENT') throw error }
@@ -272,7 +272,7 @@ export async function downloadBrowserExtension({ fetch: fetchFn = globalThis.fet
272
272
  const errors = []
273
273
  for (const source of UPDATE_SOURCES) {
274
274
  try {
275
- const raw = await sourceBytes(fetchFn, source, 'dist/knowledge-base-browser-extension.zip', 4 * 1024 * 1024, timeoutMs)
275
+ const raw = await readUpdateSourceBytes(fetchFn, source, 'dist/knowledge-base-browser-extension.zip', 4 * 1024 * 1024, timeoutMs)
276
276
  if (createHash('sha256').update(raw).digest('hex') !== EXTENSION_ARCHIVE_SHA256) throw Error('扩展文件校验失败')
277
277
  return { ok: true, filename: 'knowledge-base-browser-extension.zip', base64: raw.toString('base64') }
278
278
  } catch (error) { errors.push(source.name + ':' + String(error.message || error)) }
@@ -7,7 +7,7 @@ from pathlib import Path
7
7
  from contextlib import contextmanager
8
8
  import argparse, base64, hashlib, json, os, re, shutil, subprocess, sys, tarfile, uuid
9
9
 
10
- PACKAGE = '@local/dsh-knowledge-base'
10
+ PACKAGE = '@kingsleyasher/dsh-knowledge-base'
11
11
  METADATA = ('package.json', 'pnpm-lock.yaml')
12
12
 
13
13
  def sha(data): return hashlib.sha256(data).hexdigest()
@@ -65,13 +65,15 @@ def profile_lock(profile):
65
65
 
66
66
  def locations(profile):
67
67
  profile = profile.resolve(strict=True)
68
- plugin = profile / 'node_modules/@local/dsh-knowledge-base'
68
+ plugin = profile / 'node_modules' / PACKAGE
69
69
  if plugin.is_symlink() or plugin.is_junction(): raise RuntimeError('Linked installations require a Host-managed migration')
70
- return profile, plugin, profile / '.kb-safe-updates/transaction.json'
70
+ return profile, plugin, profile / '.kb-npm-updates/transaction.json'
71
71
 
72
72
  def validate_archive(archive, expected, destination):
73
73
  raw = archive.read_bytes()
74
- if len(raw) != expected['bytes'] or sha(raw) != expected['sha256']: raise RuntimeError('Archive digest mismatch')
74
+ integrity = 'sha512-' + base64.b64encode(hashlib.sha512(raw).digest()).decode('ascii')
75
+ if len(raw) != expected['bytes'] or sha(raw) != expected['sha256'] or integrity != expected['integrity']:
76
+ raise RuntimeError('Archive digest mismatch')
75
77
  seen = set(); total = 0
76
78
  with tarfile.open(archive, 'r:gz') as stream:
77
79
  for entry in stream:
@@ -100,8 +102,7 @@ def validate_archive(archive, expected, destination):
100
102
  for name in files:
101
103
  if name not in extracted: raise RuntimeError('Build inventory path missing')
102
104
  digest.update((name + '\0' + sha((destination / name).read_bytes()) + '\n').encode())
103
- if digest.hexdigest()[:16] != expected['buildId']: raise RuntimeError('Build ID mismatch')
104
- return pkg
105
+ return pkg, digest.hexdigest()[:16]
105
106
 
106
107
  def lock_entries(lines, start, end, indent):
107
108
  rows = []
@@ -174,13 +175,16 @@ def prepare(profile, archive, expected, pnpm=None):
174
175
  if not (plugin / 'package.json').is_file(): raise RuntimeError('Existing plugin is incomplete; use the recovery installer with a trusted old package')
175
176
  work = journal.parent / ('transaction-' + uuid.uuid4().hex); work.mkdir(parents=True)
176
177
  candidate = work / 'candidate'; candidate.mkdir()
177
- pkg = validate_archive(archive, expected, candidate)
178
+ current = json.loads((plugin / 'package.json').read_text(encoding='utf-8'))
179
+ if current.get('name') != PACKAGE or current.get('version') != expected['currentVersion']:
180
+ raise RuntimeError('The installed npm package changed; restart and check again')
181
+ pkg, build_id = validate_archive(archive, expected, candidate)
178
182
  old = {name: base64.b64encode(data).decode() if (data := read(profile / name)) is not None else None for name in METADATA}
179
183
  shadow = work / 'profile'; shadow.mkdir()
180
184
  for name in (*METADATA, '.npmrc', 'pnpm-workspace.yaml'):
181
185
  if (profile / name).is_file(): shutil.copyfile(profile / name, shadow / name)
182
186
  staged_config = json.loads(json.dumps(config))
183
- staged_config['dependencies'][PACKAGE] = 'file:' + archive.resolve().as_posix()
187
+ staged_config['dependencies'][PACKAGE] = pkg['version']
184
188
  save(shadow / 'package.json', staged_config)
185
189
  pnpm = pnpm or Path(os.environ.get('APPDATA', str(Path.home() / 'AppData/Roaming'))) / 'npm/node_modules/pnpm/bin/pnpm.mjs'
186
190
  node = shutil.which('node.exe') or shutil.which('node')
@@ -188,11 +192,15 @@ def prepare(profile, archive, expected, pnpm=None):
188
192
  resolver = work / 'resolver'; resolver.mkdir()
189
193
  save(resolver / 'package.json', {'private': True, 'dependencies': {PACKAGE: staged_config['dependencies'][PACKAGE]}})
190
194
  (resolver / 'pnpm-workspace.yaml').write_text('packages:\n - .\n', encoding='utf-8')
191
- command = [node, str(pnpm), 'install', '--ignore-workspace', '--lockfile-only', '--offline', '--ignore-scripts', '--no-frozen-lockfile']
195
+ command = [node, str(pnpm), 'install', '--ignore-workspace', '--lockfile-only', '--registry=https://registry.npmjs.org/', '--ignore-scripts', '--no-frozen-lockfile']
192
196
  with (work / 'prepare.log').open('wb') as log:
193
197
  result = subprocess.run(command, cwd=resolver, stdout=log, stderr=subprocess.STDOUT, timeout=120)
194
198
  if result.returncode: raise RuntimeError('Staging failed; live profile unchanged. ' + (work / 'prepare.log').read_text(encoding='utf-8', errors='replace')[-2000:])
195
199
  resolved_lock = (resolver / 'pnpm-lock.yaml').read_text(encoding='utf-8')
200
+ lines, blocks = managed_lock_blocks(resolved_lock)
201
+ start, end = blocks[1]
202
+ if not re.search(r'\bintegrity:\s*' + re.escape(expected['integrity']) + r'(?=[,}\s])', ''.join(lines[start:end])):
203
+ raise RuntimeError('Registry lock integrity does not match the verified archive')
196
204
  original_lock = read(profile / 'pnpm-lock.yaml')
197
205
  if original_lock is None:
198
206
  if any(name != PACKAGE for group in ('dependencies', 'devDependencies', 'optionalDependencies') for name in config.get(group, {})): raise RuntimeError('Existing lockfile required to preserve unrelated dependencies')
@@ -203,9 +211,9 @@ def prepare(profile, archive, expected, pnpm=None):
203
211
  next_config = json.loads(base64.b64decode(new['package.json']))
204
212
  check = json.loads(json.dumps(next_config)); check['dependencies'][PACKAGE] = config['dependencies'][PACKAGE]
205
213
  if check != config: raise RuntimeError('Staged package manager changed unrelated profile configuration')
206
- plan = {'phase': 'prepared', 'work': work.name, 'version': pkg['version'], 'buildId': expected['buildId'], 'old': old, 'new': new, 'oldTree': tree(plugin), 'newTree': tree(candidate)}
214
+ plan = {'phase': 'prepared', 'work': work.name, 'version': pkg['version'], 'buildId': build_id, 'old': old, 'new': new, 'oldTree': tree(plugin), 'newTree': tree(candidate)}
207
215
  save(journal, plan)
208
- return {'ok': True, 'phase': 'prepared', 'transactionId': work.name, 'version': pkg['version']}
216
+ return {'ok': True, 'phase': 'prepared', 'transactionId': work.name, 'version': pkg['version'], 'buildId': build_id}
209
217
 
210
218
  def restore(profile, plugin, journal, plan):
211
219
  for name in METADATA: