skillmkt 0.2.7 → 0.2.9

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.
@@ -10,7 +10,7 @@ import { readLibrary, readLock, readConfig, writeConfig, registerSkill, updateLo
10
10
  import { readUpstream } from '../lib/state.js';
11
11
  import { readYAML } from '../../pipeline/lib/util.js';
12
12
  import { detectHarnesses } from '../lib/scanner.js';
13
- import { probeEndpoints, chat, upsertEnvFile, resolveKeyRef } from '../lib/llm.js';
13
+ import { probeEndpoints, chat, encryptSecret, resolveKeyRef } from '../lib/llm.js';
14
14
  import { projectSkill, unproject, targetDirFor } from '../lib/project.js';
15
15
  import { treeHash } from '../lib/package.js';
16
16
  import { ok, info } from '../lib/render.js';
@@ -85,12 +85,12 @@ export async function startServer(ctx, { quiet = false, port = 0 } = {}) {
85
85
  }
86
86
  if (u.pathname === '/api/config') { // init:合并写 config
87
87
  const raw = readConfig(ctx.hub)._raw;
88
- let keyEnv = false;
88
+ let keyEnc = false;
89
89
  if (b.llm !== undefined) {
90
- if (b.llm.api_key && !String(b.llm.api_key).startsWith('env:')) {
91
- upsertEnvFile(path.join(ctx.hub, '.env'), 'SKILLMKT_LLM_KEY', b.llm.api_key);
92
- b.llm.api_key = 'env:SKILLMKT_LLM_KEY'; // config.yml 只留引用
93
- keyEnv = true;
90
+ const k = String(b.llm.api_key || '');
91
+ if (k && !k.startsWith('env:') && !k.startsWith('enc:')) {
92
+ b.llm.api_key = encryptSecret(k); // 机器码加密后存 config.yml
93
+ keyEnc = true;
94
94
  }
95
95
  raw.llm = b.llm;
96
96
  }
@@ -99,7 +99,7 @@ export async function startServer(ctx, { quiet = false, port = 0 } = {}) {
99
99
  if (b.policy) raw.policy = b.policy;
100
100
  writeConfig(ctx.hub, raw);
101
101
  emit('config', {});
102
- return res.end(JSON.stringify({ ok: true, key_env: keyEnv }));
102
+ return res.end(JSON.stringify({ ok: true, key_enc: keyEnc }));
103
103
  }
104
104
  if (u.pathname === '/api/llm-smoke') { // init 冒烟
105
105
  const key = resolveKeyRef(b.api_key, ctx); // env: 引用走 hub/.env 等解析链
package/client/lib/llm.js CHANGED
@@ -2,6 +2,8 @@
2
2
  // 批次6 补:chatJSON 真调用、probeEndpoints、端口探测。铁律:非 init/config 零探测。
3
3
  import fs from 'node:fs';
4
4
  import path from 'node:path';
5
+ import os from 'node:os';
6
+ import crypto from 'node:crypto';
5
7
  import { execFileSync } from 'node:child_process';
6
8
 
7
9
  function loadDotEnv(file) {
@@ -15,20 +17,47 @@ function loadDotEnv(file) {
15
17
  } catch { return {}; }
16
18
  }
17
19
 
18
- // upsert KEY=value 到 env 文件(600 权限)——web 保存明文密钥时落到 hub/.env,config.yml 只留 env: 引用
19
- export function upsertEnvFile(file, key, value) {
20
- let lines = [];
21
- try { lines = fs.readFileSync(file, 'utf8').split('\n'); } catch { /* 新文件 */ }
22
- const idx = lines.findIndex((l) => l.startsWith(`${key}=`));
23
- const entry = `${key}=${value}`;
24
- if (idx >= 0) lines[idx] = entry; else lines.push(entry);
25
- fs.mkdirSync(path.dirname(file), { recursive: true });
26
- fs.writeFileSync(file, lines.filter(Boolean).join('\n') + '\n', { mode: 0o600 });
27
- try { fs.chmodSync(file, 0o600); } catch { /* windows 无 mode */ }
20
+ // 机器码绑定密钥加密:config.yml 只存 enc:v1: 密文,文件离开本机解不开
21
+ let _machineId = null;
22
+ function machineId() {
23
+ if (_machineId !== null) return _machineId;
24
+ try {
25
+ if (process.platform === 'darwin') {
26
+ _machineId = execFileSync('ioreg', ['-rd1', '-c', 'IOPlatformExpertDevice'], { encoding: 'utf8', timeout: 3000 })
27
+ .match(/"IOPlatformUUID" = "([0-9A-F-]+)"/)?.[1];
28
+ } else if (process.platform === 'linux') {
29
+ _machineId = fs.readFileSync('/etc/machine-id', 'utf8').trim() || fs.readFileSync('/var/lib/dbus/machine-id', 'utf8').trim();
30
+ } else if (process.platform === 'win32') {
31
+ _machineId = execFileSync('reg', ['query', 'HKLM\\SOFTWARE\\Microsoft\\Cryptography', '/v', 'MachineGuid'], { encoding: 'utf8' })
32
+ .match(/MachineGuid\s+REG_SZ\s+(\S+)/)?.[1];
33
+ }
34
+ } catch { /* 走兜底 */ }
35
+ if (!_machineId) _machineId = `${os.hostname()}:${os.userInfo().username}`;
36
+ return _machineId;
37
+ }
38
+
39
+ const encKey = () => crypto.scryptSync(`skillmkt:${machineId()}`, 'skillmkt-secret-v1', 32);
40
+
41
+ export function encryptSecret(plain) {
42
+ const iv = crypto.randomBytes(12);
43
+ const c = crypto.createCipheriv('aes-256-gcm', encKey(), iv);
44
+ const ct = Buffer.concat([c.update(String(plain), 'utf8'), c.final()]);
45
+ return `enc:v1:${iv.toString('base64')}:${c.getAuthTag().toString('base64')}:${ct.toString('base64')}`;
46
+ }
47
+
48
+ export function decryptSecret(payload) {
49
+ const m = String(payload ?? '').match(/^enc:v1:([A-Za-z0-9+/=]+):([A-Za-z0-9+/=]+):([A-Za-z0-9+/=]+)$/);
50
+ if (!m) return null;
51
+ try {
52
+ const d = crypto.createDecipheriv('aes-256-gcm', encKey(), Buffer.from(m[1], 'base64'));
53
+ d.setAuthTag(Buffer.from(m[2], 'base64'));
54
+ return Buffer.concat([d.update(Buffer.from(m[3], 'base64')), d.final()]).toString('utf8');
55
+ } catch { return null; } // 别的机器/篡改 → 解不开
28
56
  }
29
57
 
30
- // "env:VAR" → 真值(hub/.env + cwd/.env + 环境变量);裸值原样返回
58
+ // "env:VAR" → 真值(hub/.env + cwd/.env + 环境变量);"enc:v1:…" → 本机解密;裸值原样返回
31
59
  export function resolveKeyRef(keyRef, ctx) {
60
+ if (keyRef?.startsWith('enc:')) return decryptSecret(keyRef) ?? '';
32
61
  if (!keyRef?.startsWith('env:')) return keyRef || '';
33
62
  const v = keyRef.slice(4);
34
63
  const env = {
@@ -48,8 +77,8 @@ export function resolveLLM(ctx) {
48
77
  const model = ctx.flags.model || env.SKILLMKT_LLM_MODEL || env.OMLX_MODEL || cfg.model;
49
78
  const keyRef = ctx.flags.apiKeyEnv || env.SKILLMKT_LLM_API_KEY || env.OMLX_API_KEY || cfg.api_key;
50
79
  if (!base || !model) return null;
51
- // api_key 形如 "env:VAR" → 取环境变量;裸值(不建议)原样用
52
- const key = keyRef?.startsWith('env:') ? env[keyRef.slice(4)] : keyRef;
80
+ // api_key:"env:VAR"→环境变量;"enc:v1:…"→本机解密;裸值(不建议)原样用
81
+ const key = keyRef?.startsWith('env:') ? env[keyRef.slice(4)] : keyRef?.startsWith('enc:') ? decryptSecret(keyRef) : keyRef;
53
82
  return {
54
83
  base_url: base.replace(/\/+$/, ''),
55
84
  model,
@@ -148,10 +148,10 @@ async function render() {
148
148
  <div class="row"><button id="probe">扫描本机模型服务</button><span id="probe-out" class="mut"></span></div>
149
149
  <div id="eps"></div>
150
150
  <label class="field">服务地址</label><input type="text" id="murl" placeholder="http://localhost:1234/v1" value="${esc(cfg.llm?.base_url || '')}">
151
+ <label class="field">访问密钥 <span class="field-hint" id="key-hint"></span></label><input type="text" id="mkey" value="${esc(cfg.llm?.api_key || '')}">
152
+ <p class="mut">本机服务一般留空。填了密钥会用本机机器码加密后存入 config.yml——文件拷到别的机器解不开,换机需重填。</p>
151
153
  <label class="field">模型名称</label><input type="text" id="mmodel" list="model-opts" placeholder="可输入关键字搜索,扫描后自动列出发现的模型" value="${esc(cfg.llm?.model || '')}">
152
154
  <datalist id="model-opts"></datalist>
153
- <label class="field">访问密钥</label><input type="text" id="mkey" value="${esc(cfg.llm?.api_key || '')}">
154
- <p class="mut">本机服务一般留空。填了明文密钥会存到 <code>~/.skillmkt/.env</code>(仅本人可读),配置文件里只留引用——不会以明文落进 config.yml。</p>
155
155
  <div class="row"><button id="smoke">测试连接</button><span id="smoke-out" class="mut"></span></div></div>
156
156
  <div class="card"><h3>第 2 步 · skill 默认安装位置</h3>
157
157
  <p class="mut">勾选的 AI 工具会在你安装新 skill 时自动收到一份副本。已勾过的话保存即生效。</p>
@@ -187,6 +187,7 @@ async function render() {
187
187
  app.querySelectorAll('#eps .ep').forEach((x) => x.classList.remove('sel'));
188
188
  d.classList.add('sel');
189
189
  app.querySelector('#murl').value = d.dataset.b;
190
+ markKeyNeed(epsList.find((e) => e.base_url === d.dataset.b)?.needs_key);
190
191
  refreshOpts();
191
192
  });
192
193
  };
@@ -195,19 +196,33 @@ async function render() {
195
196
  const b = modelMap.get(e.target.value);
196
197
  if (b) { app.querySelector('#murl').value = b; refreshOpts(); }
197
198
  });
199
+ // 填完服务地址自动检测是否需要密钥:已知端点直接看 needs_key,手输地址真发 /models 探
200
+ const markKeyNeed = (need) => {
201
+ app.querySelector('#mkey').classList.toggle('req', !!need);
202
+ app.querySelector('#key-hint').textContent = need ? '← 此服务需要密钥' : '';
203
+ };
198
204
  app.querySelector('#murl').addEventListener('input', () => refreshOpts());
205
+ app.querySelector('#murl').addEventListener('change', async () => {
206
+ const cur = app.querySelector('#murl').value.trim().replace(/\/+$/, '');
207
+ const ep = epsList.find((e) => e.base_url === cur);
208
+ if (ep) return markKeyNeed(ep.needs_key);
209
+ if (!/^https?:\/\//.test(cur)) return markKeyNeed(false);
210
+ const r = await api('/models', { method: 'POST', body: JSON.stringify({ base_url: cur, api_key: '' }) });
211
+ markKeyNeed(!!r.error && /401|403/.test(r.error));
212
+ });
199
213
  // 需要密钥的端点:密钥填完自动拉它的模型列表
200
214
  app.querySelector('#mkey').addEventListener('change', async () => {
201
215
  const cur = app.querySelector('#murl').value.trim().replace(/\/+$/, '');
202
216
  const ep = epsList.find((e) => e.base_url === cur);
203
217
  const key = app.querySelector('#mkey').value.trim();
204
- if (!ep?.needs_key || !key) return;
218
+ if (!key || !(ep?.needs_key || (!ep && /^https?:\/\//.test(cur)))) return;
205
219
  const out = app.querySelector('#smoke-out');
206
220
  out.textContent = '读取模型列表…';
207
221
  const r = await api('/models', { method: 'POST', body: JSON.stringify({ base_url: cur, api_key: key }) });
208
222
  if (r.models?.length) {
209
223
  for (const m of r.models) { modelMap.set(m, cur); loadedModels.set(m, cur); }
210
- ep.needs_key = false; ep.models = r.models;
224
+ if (ep) { ep.needs_key = false; ep.models = r.models; }
225
+ markKeyNeed(false);
211
226
  refreshOpts();
212
227
  out.textContent = `已加载 ${r.models.length} 个模型`;
213
228
  } else out.textContent = r.error ? `读取失败:${r.error}` : '密钥通了,但没读到模型';
@@ -222,7 +237,7 @@ async function render() {
222
237
  app.querySelector('#save').onclick = async () => {
223
238
  const targets = [...app.querySelectorAll('[data-h]:checked')].map((x) => x.dataset.h);
224
239
  const r = await api('/config', { method: 'POST', body: JSON.stringify({ llm: { base_url: app.querySelector('#murl').value || null, model: app.querySelector('#mmodel').value || null, api_key: app.querySelector('#mkey').value || undefined, concurrency: 2, timeout_ms: 60000 }, default_targets: targets }) });
225
- app.querySelector('#save-out').textContent = r.ok ? `已保存到 config.yml${r.key_env ? ',密钥存入 .env' : ''}` : `保存失败:${r.error}`;
240
+ app.querySelector('#save-out').textContent = r.ok ? `已保存到 config.yml${r.key_enc ? ',密钥已加密' : ''}` : `保存失败:${r.error}`;
226
241
  refresh();
227
242
  };
228
243
  }
@@ -71,6 +71,8 @@ input[type=text], input:not([type]), textarea, select {
71
71
  border-radius: 8px; background: var(--color-paper); color: var(--color-ink); }
72
72
  textarea { min-height: 7rem; resize: vertical; font-family: var(--font-mono); font-size: 14.5px; }
73
73
  input[type=checkbox] { width: 17px; height: 17px; accent-color: var(--color-accent); margin-right: 2px; }
74
+ input.req { border-color: var(--color-accent); box-shadow: 0 0 0 3px color-mix(in oklch, var(--color-accent) 16%, transparent); }
75
+ .field-hint { font-size: 14px; color: var(--color-accent); font-weight: 600; }
74
76
  label.check { display: flex; gap: 10px; align-items: center; padding: 7px 4px; cursor: pointer; border-radius: 6px; }
75
77
  label.check:hover { background: color-mix(in oklch, var(--color-ink) 4%, var(--color-surface)); }
76
78
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skillmkt",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "type": "module",
5
5
  "description": "Local-first agent skill manager: install, audit, merge, distribute.",
6
6
  "license": "MIT",