install.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. """Install two pinned, public Skills into a host-supplied Skills directory.
  2. No guessed host directories, credential discovery, account creation or business writes.
  3. The official VOC artifact is downloaded from npm and verified before extraction.
  4. """
  5. import argparse
  6. import hashlib
  7. import io
  8. import json
  9. import os
  10. from pathlib import Path, PurePosixPath
  11. import re
  12. import shutil
  13. import subprocess
  14. import sys
  15. import tarfile
  16. import tempfile
  17. import urllib.request
  18. class InstallError(Exception):
  19. pass
  20. def require(condition, code):
  21. if not condition:
  22. raise InstallError(code)
  23. def digest(raw):
  24. return hashlib.sha256(raw).hexdigest()
  25. def encode(value):
  26. return (json.dumps(value, ensure_ascii=False, indent=2) + '\n').encode('utf-8')
  27. def safe_name(name):
  28. parts = PurePosixPath(name).parts
  29. return (isinstance(name, str) and bool(name) and '\\' not in name and ':' not in name
  30. and not name.startswith('/') and all(p not in ('..', '.') for p in parts)
  31. and name == '/'.join(parts))
  32. def plain_path(path):
  33. path = Path(os.path.abspath(path))
  34. for part in [*reversed(path.parents), path]:
  35. require(not part.is_symlink(), 'SYMLINK_PATH')
  36. if part.exists():
  37. require(not hasattr(part, 'is_junction') or not part.is_junction(), 'JUNCTION_PATH')
  38. return path
  39. def inside(parent, child):
  40. return child != parent and child.is_relative_to(parent)
  41. def verify_package(package):
  42. package = plain_path(package)
  43. manifest = package / 'FILES.sha256'
  44. require(manifest.is_file(), 'PACKAGE_MANIFEST_MISSING')
  45. names = set()
  46. for line in manifest.read_text(encoding='utf-8').splitlines():
  47. match = re.fullmatch(r'([a-f0-9]{64}) (.+)', line)
  48. require(match is not None, 'INVALID_PACKAGE_MANIFEST')
  49. h, name = match.groups()
  50. require(safe_name(name) and name not in names, 'INVALID_PACKAGE_PATH')
  51. names.add(name)
  52. p = plain_path(package / name)
  53. require(p.is_file() and digest(p.read_bytes()) == h, 'PACKAGE_HASH_MISMATCH')
  54. meta = json.loads((package / 'release.json').read_bytes())
  55. require(meta['schema'] == 'ksf.workshop-onboarding.v1', 'INVALID_RELEASE')
  56. return meta
  57. def voc_archive_files(raw, expected):
  58. require(len(raw) == expected['bytes'] and digest(raw) == expected['sha256'], 'VOC_ARCHIVE_HASH_MISMATCH')
  59. result = {}
  60. with tarfile.open(fileobj=io.BytesIO(raw), mode='r:gz') as archive:
  61. for member in archive.getmembers():
  62. require(member.name.startswith('package/'), 'INVALID_VOC_ARCHIVE_PATH')
  63. name = member.name[len('package/'):]
  64. require(safe_name(name), 'INVALID_VOC_ARCHIVE_PATH')
  65. require(member.isfile(), 'NON_FILE_VOC_ARCHIVE_MEMBER')
  66. require(name not in result and name in expected['files'], 'UNEXPECTED_VOC_ARCHIVE_FILE')
  67. require(member.size <= 8_000_000, 'VOC_ARCHIVE_MEMBER_TOO_LARGE')
  68. raw_file = archive.extractfile(member).read()
  69. require(digest(raw_file) == expected['files'][name], 'VOC_FILE_HASH_MISMATCH')
  70. result[name] = raw_file
  71. require(set(result) == set(expected['files']), 'VOC_ARCHIVE_INCOMPLETE')
  72. return result
  73. def source_files(package, meta, archive=None):
  74. expected = meta['voc']
  75. if archive:
  76. raw = plain_path(archive).read_bytes()
  77. else:
  78. require(expected['url'] == 'https://registry.npmjs.org/@vocmarket/voc-skill/-/voc-skill-0.3.42.tgz', 'UNEXPECTED_VOC_SOURCE')
  79. request = urllib.request.Request(expected['url'], headers={'User-Agent': 'ksf-workshop-onboarding/1'})
  80. with urllib.request.urlopen(request, timeout=30) as response:
  81. require(response.status == 200, 'VOC_DOWNLOAD_FAILED')
  82. raw = response.read(expected['bytes'] + 1)
  83. voc = voc_archive_files(raw, expected)
  84. workshop = {}
  85. for name, h in meta['workshop']['files'].items():
  86. require(safe_name(name), 'INVALID_WORKSHOP_PATH')
  87. raw_file = plain_path(package / 'skills/ksf-workshop-runtime' / name).read_bytes()
  88. require(digest(raw_file) == h, 'WORKSHOP_FILE_HASH_MISMATCH')
  89. workshop[name] = raw_file
  90. return {'ksf-workshop-runtime': workshop, 'voc-intelligence': voc}
  91. def mcp_fragment(voc_dir):
  92. return {'mcpServers': {'voc': {'command': 'node',
  93. 'args': [str(voc_dir / 'mcp/src/server.js')], 'cwd': str(voc_dir),
  94. 'env': {'VOC_SKILL_NO_UPDATE_CHECK': '1'}}}}
  95. def verify_component(target, files):
  96. require(target.is_dir(), 'EXISTING_SKILL_NOT_DIRECTORY')
  97. for name, raw in files.items():
  98. p = plain_path(target / name)
  99. require(p.is_file() and digest(p.read_bytes()) == digest(raw), 'EXISTING_SKILL_DIFFERS')
  100. def verify_hashes(target, hashes):
  101. for name, expected in hashes.items():
  102. require(safe_name(name), 'INVALID_UPGRADE_PATH')
  103. p = plain_path(target / name)
  104. require(p.is_file() and digest(p.read_bytes()) == expected, 'UPGRADE_BASELINE_CHANGED')
  105. def verify_upgrade_target(target, content, before):
  106. verify_hashes(target, before)
  107. for name in set(content) - set(before):
  108. require(not plain_path(target / name).exists(), 'UPGRADE_NEW_FILE_ALREADY_EXISTS')
  109. def plan(skills_dir, files, upgrade_from=None):
  110. actions = []
  111. for name, content in files.items():
  112. target = plain_path(skills_dir / name)
  113. if target.exists():
  114. try:
  115. verify_component(target, content)
  116. action = 'verify-only'
  117. except InstallError:
  118. require(name == 'ksf-workshop-runtime' and upgrade_from, 'EXISTING_SKILL_DIFFERS')
  119. baseline = None
  120. for version, hashes in upgrade_from.items():
  121. try:
  122. verify_hashes(target, hashes)
  123. baseline = (version, hashes)
  124. break
  125. except InstallError:
  126. continue
  127. require(baseline is not None, 'UPGRADE_BASELINE_CHANGED')
  128. # Code, locks and unknown local files are never rewritten by this upgrade.
  129. for path, raw in content.items():
  130. if path.startswith('scripts/') or path == 'runtime-lock.json':
  131. require(digest(raw) == baseline[1].get(path), 'PROTECTED_RUNTIME_CHANGED')
  132. require(set(baseline[1]) <= set(content), 'UPGRADE_FILE_SET_CHANGED')
  133. additions = set(content) - set(baseline[1])
  134. require(all(p.startswith('references/') and p.endswith('.md') for p in additions),
  135. 'UPGRADE_ADDITION_NOT_DOCUMENTATION')
  136. verify_upgrade_target(target, content, baseline[1])
  137. require(all(plain_path(target / p).parent.is_dir() for p in additions),
  138. 'UPGRADE_ADDITION_PARENT_MISSING')
  139. actions.append({'skill': name, 'path': str(target), 'action': 'upgrade',
  140. 'files': len(content), 'fromVersion': baseline[0],
  141. 'before': baseline[1]})
  142. continue
  143. else:
  144. action = 'create'
  145. actions.append({'skill': name, 'path': str(target), 'action': action, 'files': len(content)})
  146. return actions
  147. def remove_created(path, intended_parent):
  148. """Only remove our own newly created directory, after checking its final location."""
  149. path = plain_path(path)
  150. intended_parent = plain_path(intended_parent)
  151. require(inside(intended_parent, path), 'CLEANUP_PATH_OUTSIDE_TARGET')
  152. require(path.name.startswith('.ksf-init-') or path.name in ('ksf-workshop-runtime', 'voc-intelligence'),
  153. 'CLEANUP_TARGET_NOT_OWNED')
  154. shutil.rmtree(path)
  155. def install_files(skills_dir, files, actions, backup_dir=None):
  156. skills_dir.mkdir(parents=True, exist_ok=True)
  157. staging = Path(tempfile.mkdtemp(prefix='.ksf-init-', dir=skills_dir))
  158. created = []
  159. upgraded = []
  160. try:
  161. for row in actions:
  162. if row['action'] != 'create':
  163. continue
  164. staged = staging / row['skill']
  165. for name, raw in files[row['skill']].items():
  166. p = staged / name
  167. p.parent.mkdir(parents=True, exist_ok=True)
  168. p.write_bytes(raw)
  169. verify_component(staged, files[row['skill']])
  170. # Recheck both targets before committing either component.
  171. for row in actions:
  172. target = skills_dir / row['skill']
  173. if row['action'] == 'create':
  174. require(not target.exists(), 'CONCURRENT_INSTALL_CHANGE')
  175. elif row['action'] == 'upgrade':
  176. verify_upgrade_target(target, files[row['skill']], row['before'])
  177. else:
  178. verify_component(target, files[row['skill']])
  179. # Save every changed public file before replacing any file. Extra files stay untouched.
  180. for row in actions:
  181. if row['action'] != 'upgrade':
  182. continue
  183. require(backup_dir is not None, 'UPGRADE_BACKUP_REQUIRED')
  184. for name, raw in files[row['skill']].items():
  185. if digest(raw) == row['before'].get(name):
  186. continue
  187. if name not in row['before']:
  188. continue
  189. dest = backup_dir / row['skill'] / name
  190. dest.parent.mkdir(parents=True, exist_ok=True)
  191. dest.write_bytes((skills_dir / row['skill'] / name).read_bytes())
  192. (backup_dir / 'upgrade-plan.json').write_bytes(encode(row))
  193. for row in actions:
  194. if row['action'] == 'create':
  195. target = skills_dir / row['skill']
  196. require(not target.exists(), 'CONCURRENT_INSTALL_CHANGE')
  197. (staging / row['skill']).rename(target)
  198. created.append(target)
  199. elif row['action'] == 'upgrade':
  200. target = skills_dir / row['skill']
  201. verify_upgrade_target(target, files[row['skill']], row['before'])
  202. names = sorted(files[row['skill']], key=lambda n: n == 'SKILL.md')
  203. for name in names:
  204. raw = files[row['skill']][name]
  205. if digest(raw) == row['before'].get(name):
  206. continue
  207. dest = plain_path(target / name)
  208. before_hash = row['before'].get(name)
  209. if before_hash is None:
  210. require(not dest.exists(), 'CONCURRENT_INSTALL_CHANGE')
  211. else:
  212. require(digest(dest.read_bytes()) == before_hash, 'CONCURRENT_INSTALL_CHANGE')
  213. temporary = dest.with_name(dest.name + '.ksf-upgrade-new')
  214. require(not temporary.exists(), 'UPGRADE_TEMP_EXISTS')
  215. try:
  216. with temporary.open('xb') as stream:
  217. stream.write(raw)
  218. stream.flush()
  219. os.fsync(stream.fileno())
  220. temporary.chmod(dest.stat().st_mode & 0o777 if before_hash is not None else 0o600)
  221. os.replace(temporary, dest)
  222. upgraded.append((dest, row['skill'], name, digest(raw)))
  223. finally:
  224. if temporary.exists():
  225. temporary.unlink()
  226. for row in actions:
  227. verify_component(skills_dir / row['skill'], files[row['skill']])
  228. except Exception:
  229. for dest, skill, name, after_hash in reversed(upgraded):
  230. require(digest(dest.read_bytes()) == after_hash, 'CONCURRENT_CHANGE_PREVENTS_RESTORE')
  231. before = backup_dir / skill / name
  232. if before.exists():
  233. dest.write_bytes(before.read_bytes())
  234. else:
  235. dest.unlink()
  236. for target in reversed(created):
  237. verify_component(target, files[target.name])
  238. remove_created(target, skills_dir)
  239. raise
  240. finally:
  241. if staging.exists():
  242. remove_created(staging, skills_dir)
  243. def node_and_npm():
  244. node = shutil.which('node')
  245. npm = shutil.which('npm')
  246. if not node or not npm:
  247. return None
  248. version = subprocess.run([node, '-p', 'process.versions.node'], capture_output=True, timeout=15, check=False)
  249. require(version.returncode == 0 and int(version.stdout.decode().strip().split('.')[0]) >= 18,
  250. 'NODE_18_REQUIRED')
  251. if os.name == 'nt':
  252. cli = Path(npm).parent / 'node_modules/npm/bin/npm-cli.js'
  253. require(cli.is_file(), 'NPM_CLI_NOT_FOUND')
  254. return [node, str(cli)]
  255. return [npm]
  256. def prepare_runtime(package, voc_dir, output_dir):
  257. npm = node_and_npm()
  258. if not npm:
  259. return {'status': 'pending', 'reason': 'NODE_OR_NPM_NOT_AVAILABLE'}
  260. # Dependency resolution affects this newly installed VOC directory only.
  261. command = npm + ['install', '--omit=dev', '--ignore-scripts', '--no-audit', '--no-fund',
  262. '--registry', 'https://registry.npmjs.org', '--cache', str(output_dir / 'npm-cache')]
  263. result = subprocess.run(command, cwd=voc_dir, capture_output=True, check=False, timeout=240)
  264. # Raw process logs are intentionally not copied into the user-facing receipt.
  265. if result.returncode:
  266. return {'status': 'pending', 'reason': 'VOC_DEPENDENCY_INSTALL_FAILED', 'exitCode': result.returncode}
  267. check = subprocess.run([shutil.which('node'), str(package / 'check-voc.cjs'), str(voc_dir)],
  268. cwd=package, capture_output=True, check=False, timeout=40)
  269. if check.returncode:
  270. return {'status': 'pending', 'reason': 'VOC_LOCAL_CHECK_FAILED', 'exitCode': check.returncode}
  271. value = json.loads(check.stdout)
  272. require(value.get('ok') is True, 'INVALID_VOC_CHECK_RESULT')
  273. return {'status': 'verified', 'check': value}
  274. def run(args, package=None):
  275. package = Path(package).resolve() if package else Path(__file__).resolve().parent
  276. require(Path(args.skills_dir).is_absolute(), 'ABSOLUTE_HOST_SKILLS_DIRECTORY_REQUIRED')
  277. skills_dir = plain_path(args.skills_dir)
  278. require(skills_dir != Path(skills_dir.anchor), 'FILESYSTEM_ROOT_NOT_ALLOWED')
  279. require(not skills_dir.exists() or skills_dir.is_dir(), 'SKILLS_DIRECTORY_REQUIRED')
  280. require(not package.is_relative_to(skills_dir) and not skills_dir.is_relative_to(package), 'PACKAGE_TARGET_OVERLAP')
  281. require(not args.prepare_runtime or args.apply, 'PREPARE_RUNTIME_REQUIRES_APPLY')
  282. if args.apply:
  283. require(args.out and Path(args.out).is_absolute(), 'ABSOLUTE_RESULT_DIRECTORY_REQUIRED')
  284. output = plain_path(args.out)
  285. require(not output.exists(), 'RESULT_DIRECTORY_EXISTS')
  286. require(not output.is_relative_to(skills_dir) and not skills_dir.is_relative_to(output), 'RESULT_TARGET_OVERLAP')
  287. meta = verify_package(package)
  288. files = source_files(package, meta, args.voc_archive)
  289. # The npm artifact contains the author's machine-specific MCP paths.
  290. # Adapt that one generated configuration after verifying the original artifact.
  291. original_mcp_sha = digest(files['voc-intelligence']['.mcp.json'])
  292. files['voc-intelligence']['.mcp.json'] = encode(mcp_fragment(skills_dir / 'voc-intelligence'))
  293. actions = plan(skills_dir, files, meta.get('upgradeFrom'))
  294. if args.apply and any(a['action'] == 'upgrade' for a in actions):
  295. require(getattr(args, 'upgrade', False), 'UPGRADE_FLAG_REQUIRED')
  296. receipt = {'schema': 'ksf.workshop-onboarding-result.v1', 'ok': True,
  297. 'releaseId': meta['releaseId'], 'readOnly': not args.apply, 'actions': actions,
  298. 'filesInstalled': False, 'hostSkillsLoaded': 'not-verified',
  299. 'vocRuntime': {'status': 'not-checked'}, 'hostToolRegistration': 'not-verified',
  300. 'vocLiveAccess': 'not-verified', 'researchLibraryAccess': 'not-verified',
  301. 'businessSaveAccess': 'not-verified', 'accountOrEnterpriseCreated': False,
  302. 'researchOrBusinessDataWritten': False, 'remoteInstalled': False,
  303. 'adaptedVocConfig': {'path': '.mcp.json', 'originalSha256': original_mcp_sha,
  304. 'installedSha256': digest(files['voc-intelligence']['.mcp.json'])},
  305. 'note': 'Files, local runtime, host discovery and live access have separate acceptance.'}
  306. if not args.apply:
  307. return receipt
  308. output.mkdir(parents=True, exist_ok=False)
  309. try:
  310. install_files(skills_dir, files, actions, output / 'before')
  311. receipt['filesInstalled'] = True
  312. voc_dir = skills_dir / 'voc-intelligence'
  313. # A neutral fragment is written to the result directory only; the host owns registration.
  314. (output / 'voc-mcp.fragment.json').write_bytes(encode(mcp_fragment(voc_dir)))
  315. receipt['mcpFragment'] = str(output / 'voc-mcp.fragment.json')
  316. if args.prepare_runtime:
  317. try:
  318. receipt['vocRuntime'] = prepare_runtime(package, voc_dir, output)
  319. except subprocess.TimeoutExpired:
  320. receipt['vocRuntime'] = {'status': 'pending', 'reason': 'RUNTIME_PREPARATION_TIMEOUT'}
  321. else:
  322. receipt['vocRuntime'] = {'status': 'pending', 'reason': 'DEPENDENCIES_NOT_PREPARED'}
  323. except Exception as exc:
  324. receipt['ok'] = False
  325. receipt['errorCode'] = str(exc) if isinstance(exc, InstallError) else 'INSTALL_FAILED'
  326. raise
  327. finally:
  328. (output / 'install-receipt.json').write_bytes(encode(receipt))
  329. return receipt
  330. def main():
  331. parser = argparse.ArgumentParser(description=__doc__)
  332. parser.add_argument('--skills-dir', required=True, help='Actual Skills directory provided by the host')
  333. parser.add_argument('--out', help='New absolute result directory outside the Skills directory')
  334. parser.add_argument('--voc-archive', help='Optional local copy of the exact official npm tarball')
  335. parser.add_argument('--apply', action='store_true')
  336. parser.add_argument('--prepare-runtime', action='store_true')
  337. parser.add_argument('--upgrade', action='store_true', help='Upgrade an integrity-checked supported prior workshop version')
  338. args = parser.parse_args()
  339. try:
  340. receipt = run(args)
  341. print(json.dumps(receipt, ensure_ascii=False, indent=2))
  342. return 0
  343. except Exception as exc:
  344. code = str(exc) if isinstance(exc, InstallError) else 'INITIALIZATION_FAILED'
  345. print(json.dumps({'ok': False, 'errorCode': code, 'note': 'No credentials or raw environment were printed.'}))
  346. return 1
  347. if __name__ == '__main__':
  348. sys.exit(main())