@mebular/mcp 0.2.2 → 0.2.3

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/bin/mebular.mjs CHANGED
@@ -187,21 +187,117 @@ async function runKeygen(flags) {
187
187
  console.error('(主私钥是信任根,请妥善保管;权限 0600)');
188
188
  }
189
189
 
190
+ function initError(message, code) {
191
+ const error = new Error(message);
192
+ error.code = code;
193
+ return error;
194
+ }
195
+
196
+ async function readInitJson(file, { label, code }) {
197
+ try {
198
+ const parsed = JSON.parse(await readFile(file, 'utf-8'));
199
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
200
+ throw new Error('顶层必须是对象');
201
+ }
202
+ return parsed;
203
+ } catch (error) {
204
+ throw initError(`${label}损坏:${file}(${error?.message ?? error})`, code);
205
+ }
206
+ }
207
+
190
208
  async function runInit(flags) {
191
209
  const home = homeDir();
192
210
  const configFile = join(home, 'config.json');
193
211
  const keyFile = join(home, 'user-master-key.json');
194
212
  await mkdir(home, { recursive: true });
195
213
 
196
- if (!existsSync(keyFile)) await runKeygen({ out: keyFile });
214
+ const config = existsSync(configFile)
215
+ ? await readInitJson(configFile, { label: 'config.json', code: 'CONFIG_INVALID' })
216
+ : null;
217
+ const storagePath = typeof config?.storagePath === 'string'
218
+ ? config.storagePath
219
+ : (typeof flags['storage'] === 'string' ? flags['storage'] : join(home, 'store.jsonl'));
220
+ const explicit = {
221
+ ...(typeof flags['device-id'] === 'string' && flags['device-id'].trim().length > 0
222
+ ? { deviceId: flags['device-id'].trim() }
223
+ : {}),
224
+ ...(typeof flags['device-name'] === 'string' && flags['device-name'].trim().length > 0
225
+ ? { deviceName: flags['device-name'].trim() }
226
+ : {}),
227
+ };
197
228
 
198
- if (existsSync(configFile)) {
229
+ const {
230
+ assertFreshStore,
231
+ cleanLegacyConfig,
232
+ createIdentity,
233
+ prepareIdentity,
234
+ } = await import('../src/home-identity.mjs');
235
+ const prepared = prepareIdentity({ config: config ?? {}, storagePath, explicit });
236
+ if (!prepared.ok) throw initError(prepared.message, prepared.code);
237
+ for (const warning of prepared.warnings) console.error(`warning: ${warning}`);
238
+
239
+ let identity = prepared.identity;
240
+ const { identityMode, readMasterKeyRecord } = await import('../src/config.mjs');
241
+ if (prepared.status === 'missing') {
242
+ // 缺身份但 store 已有数据 = 自动换钥风险:先拒绝,绝不写任何文件。
243
+ assertFreshStore(storagePath);
244
+ if (!existsSync(keyFile)) await runKeygen({ out: keyFile });
245
+ let master;
246
+ try {
247
+ master = await readMasterKeyRecord(keyFile);
248
+ } catch (error) {
249
+ throw initError(`主密钥文件损坏:${keyFile}(${error?.message ?? error})`, 'MASTER_KEY_INVALID');
250
+ }
251
+ if (!master.userMasterPrivateKey) {
252
+ throw initError(`主密钥文件缺少私钥:${keyFile}`, 'MASTER_KEY_INVALID');
253
+ }
254
+ const created = await createIdentity({
255
+ storagePath,
256
+ deviceId: identity.deviceId,
257
+ deviceName: identity.deviceName,
258
+ userMasterPrivateKey: master.userMasterPrivateKey,
259
+ userMasterPublicKey: master.userMasterKey,
260
+ });
261
+ identity = { deviceId: created.deviceId, deviceName: created.deviceName };
262
+ } else if (identityMode(home, config ?? {}, storagePath) === 'root') {
263
+ // 已有 root 身份但信任根缺失/损坏:init 不能假装成功,更不能生成新主密钥。
264
+ // 委派身份没有 root 主私钥是正常的,因此只对 root 校验。
265
+ const envInline = process.env.MEBULAR_USER_MASTER_KEY;
266
+ const keySource = envInline
267
+ ? envInline
268
+ : (process.env.MEBULAR_USER_MASTER_KEY_FILE
269
+ || (typeof config?.encryption?.keyFile === 'string' && config.encryption.keyFile.length > 0
270
+ ? config.encryption.keyFile
271
+ : keyFile));
272
+ if (!envInline && !existsSync(keySource)) {
273
+ throw initError(
274
+ `已有 root 身份,但缺少用户主密钥:${keySource}`
275
+ + '(不会自动生成新的信任根;请恢复原主密钥或从备份恢复)',
276
+ 'IDENTITY_TRUST_ROOT_MISSING',
277
+ );
278
+ }
279
+ let master;
280
+ try {
281
+ master = await readMasterKeyRecord(keySource);
282
+ } catch (error) {
283
+ throw initError(`主密钥文件损坏:${keySource}(${error?.message ?? error})`, 'MASTER_KEY_INVALID');
284
+ }
285
+ if (!master.userMasterPrivateKey) {
286
+ throw initError(`主密钥文件缺少私钥:${keySource}`, 'MASTER_KEY_INVALID');
287
+ }
288
+ }
289
+
290
+ if (config !== null) {
291
+ const migrated = await cleanLegacyConfig({ configPath: configFile, identity });
199
292
  console.log(`配置已存在,未覆盖:${configFile}`);
293
+ if (migrated.migrated) {
294
+ console.log(`已备份旧 config 身份字段:${migrated.backupPath},并以身份 ${identity.deviceId} 为准`);
295
+ }
200
296
  } else {
201
- const config = {
202
- storagePath: typeof flags['storage'] === 'string' ? flags['storage'] : join(home, 'store.jsonl'),
297
+ // F-IDENT-1:新 config 不写 deviceId/deviceName;身份文件是唯一权威。
298
+ const nextConfig = {
299
+ storagePath,
203
300
  storageAdapter: 'json',
204
- deviceId: typeof flags['device-id'] === 'string' ? flags['device-id'] : `device-${process.env.HOSTNAME ?? 'local'}`,
205
301
  encryption: { level: 'none', keyFile },
206
302
  network: { enabled: false, libp2p: { listen: [], relayServers: [], relayUnlimited: false } },
207
303
  // 常驻入口默认实时(写入即推 + 周期 anti-entropy);可显式关闭
@@ -209,8 +305,8 @@ async function runInit(flags) {
209
305
  semantic: { enabled: false, minScore: 0.2 },
210
306
  mcp: { http: { host: '127.0.0.1', port: 7331, auth: 'none', tls: false, tokensFile: join(home, 'auth', 'tokens.json') } },
211
307
  };
212
- await writeFile(configFile, JSON.stringify(config, null, 2), 'utf-8');
213
- console.log(`已写入配置:${configFile}`);
308
+ await writeFile(configFile, JSON.stringify(nextConfig, null, 2), 'utf-8');
309
+ console.log(`已写入配置:${configFile}(deviceId=${identity.deviceId},由身份文件提供)`);
214
310
  }
215
311
  console.log(
216
312
  [
@@ -494,11 +590,13 @@ async function runNetDoctor() {
494
590
 
495
591
  async function runStatus() {
496
592
  const { loadConfigFile, homeDir: resolveHome, identityMode: resolveIdentityMode } = await import('../src/config.mjs');
593
+ const { readIdentityFile, storagePathForHome } = await import('../src/home-identity.mjs');
497
594
  const home = resolveHome();
498
595
  const configFile = await loadConfigFile(home).catch(() => ({}));
499
- const storagePath = process.env.MEBULAR_STORAGE_PATH
500
- ?? configFile.storagePath
501
- ?? join(home, (configFile.storageAdapter ?? 'json') === 'sqlite' ? 'store.sqlite' : 'store.jsonl');
596
+ const storagePath = storagePathForHome(home, configFile, process.env);
597
+ // F-IDENT-1:status 的 deviceId 只认身份文件;env/config 仅旧布局兜底(且仅用于展示)。
598
+ const identityRead = readIdentityFile(storagePath);
599
+ const identityDeviceId = identityRead.status === 'valid' ? identityRead.deviceId : null;
502
600
  // store 锁持有者(单写者证据)
503
601
  let storeLock = null;
504
602
  const lockPath = join(home, 'lock');
@@ -520,12 +618,19 @@ async function runStatus() {
520
618
  ok: true,
521
619
  running: true,
522
620
  reused: true,
523
- deviceId: process.env.MEBULAR_DEVICE_ID ?? configFile.deviceId ?? `device-${process.env.HOSTNAME ?? 'local'}`,
621
+ deviceId: identityDeviceId,
524
622
  peerId: null,
525
623
  nodeCount: null,
526
624
  stateHash: null,
527
625
  home,
528
626
  storagePath,
627
+ ...(identityDeviceId === null
628
+ ? {
629
+ identityError: identityRead.status === 'invalid'
630
+ ? { status: 'invalid', code: 'IDENTITY_INVALID', problems: identityRead.problems ?? [] }
631
+ : { status: identityRead.status, code: identityRead.status === 'missing' ? 'IDENTITY_MISSING' : null },
632
+ }
633
+ : {}),
529
634
  identityMode: resolveIdentityMode(home, configFile, storagePath),
530
635
  network: { enabled: configFile.network?.enabled ?? false, listen: configFile.network?.libp2p?.listen ?? [], reused: true },
531
636
  storeLock,
@@ -1586,7 +1691,7 @@ async function main() {
1586
1691
  ' token grant|list|revoke [--scope a,b] [--id x] [--tokens-file p] bearer 令牌管理',
1587
1692
  ' token client add|list|remove [--redirect uri] [--scope a,b] [--id x] OAuth 客户端预注册',
1588
1693
  ' token consent [--scope a,b] [--ttl sec] 生成一次性本地同意码(/authorize 用)',
1589
- ' init / keygen / print-config / status|doctor 初始化、状态与自检(身份模式/网络/锁/域/join)',
1694
+ ' init / keygen / print-config / status|doctor 初始化(已有身份时沿用其 deviceId)、状态与自检',
1590
1695
  ' doctor --net 网络排障:地址簿/路径状态 + relay 可达性 + 下一步建议',
1591
1696
  ' tools 打印 MCP 工具 ↔ CLI 对照表',
1592
1697
  ' memory_write|memory_write_batch|memory_query|memory_search|memory_profile|memory_skills|',
@@ -1596,7 +1701,12 @@ async function main() {
1596
1701
  process.exit(0);
1597
1702
  return;
1598
1703
  case 'init':
1599
- await runInit(flags);
1704
+ try {
1705
+ await runInit(flags);
1706
+ } catch (error) {
1707
+ console.error(`✗ init 失败(${error?.code ?? 'ERROR'}):${error?.message ?? error}`);
1708
+ process.exit(2);
1709
+ }
1600
1710
  return;
1601
1711
  case 'keygen':
1602
1712
  await runKeygen(flags);
@@ -1610,14 +1720,24 @@ async function main() {
1610
1720
  return;
1611
1721
  }
1612
1722
  case 'status':
1613
- await runStatus();
1723
+ try {
1724
+ await runStatus();
1725
+ } catch (error) {
1726
+ console.error(`✗ status 失败(${error?.code ?? 'ERROR'}):${error?.message ?? error}`);
1727
+ process.exit(2);
1728
+ }
1614
1729
  return;
1615
1730
  case 'doctor':
1616
1731
  if (flags.net === true || flags.net === 'true') {
1617
1732
  await runNetDoctor();
1618
1733
  return;
1619
1734
  }
1620
- await runStatus();
1735
+ try {
1736
+ await runStatus();
1737
+ } catch (error) {
1738
+ console.error(`✗ doctor 失败(${error?.code ?? 'ERROR'}):${error?.message ?? error}`);
1739
+ process.exit(2);
1740
+ }
1621
1741
  return;
1622
1742
  default: {
1623
1743
  const { toolByName } = await import('../src/tools.mjs');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mebular/mcp",
3
- "version": "0.2.2",
3
+ "version": "0.2.3",
4
4
  "description": "Mebular MCP server(stdio + Streamable HTTP):把 Mebular 记忆能力暴露给任意 MCP client",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -29,9 +29,9 @@
29
29
  "access": "public"
30
30
  },
31
31
  "dependencies": {
32
- "@mebular/core": "^0.2.2",
32
+ "@mebular/core": "^0.2.3",
33
33
  "@modelcontextprotocol/server": "^2.3.1",
34
34
  "zod": "^4.6.7",
35
- "@mebular/fleet": "^0.2.2"
35
+ "@mebular/fleet": "^0.2.3"
36
36
  }
37
37
  }
package/src/admin.mjs CHANGED
@@ -408,7 +408,7 @@ export function collectOnlinePeers(app) {
408
408
  }
409
409
 
410
410
  /** GET /admin/api/overview */
411
- export async function buildOverview({ app, service, cloud, config, runtime }) {
411
+ export async function buildOverview({ app, service, cloud, runtime }) {
412
412
  const status = await service.status();
413
413
  const { peers } = collectOnlinePeers(app);
414
414
  let blockedCount = 0;
@@ -434,7 +434,6 @@ export async function buildOverview({ app, service, cloud, config, runtime }) {
434
434
  }
435
435
  const selfDeviceName = deviceNames[app.deviceId]?.name
436
436
  ?? runtime?.deviceName
437
- ?? config?.deviceName
438
437
  ?? null;
439
438
  // 忆云身份:旧守护无此字段 → 前端自行隐藏;注册表不可读时同样省略(不阻塞总览)。
440
439
  let cloudView = null;
@@ -608,19 +607,19 @@ export async function collectKnownDevices(app, policy, online) {
608
607
  }
609
608
 
610
609
  /** GET /admin/api/devices */
611
- export async function buildDevices({ app, config, runtime }) {
610
+ export async function buildDevices({ app, runtime }) {
612
611
  const self = app.deviceId;
613
612
  const online = collectOnlinePeers(app);
614
613
  const policy = await collectPolicy(app);
615
614
  const known = await collectKnownDevices(app, policy, online);
616
- // 设备名来自网络派生(本人可改);无事件时本机用 config/runtime 回退,其他设备只显示 deviceId。
615
+ // 设备名来自网络派生(本人可改);无事件时本机用 runtime(身份文件派生)回退,其他设备只显示 deviceId。
617
616
  let deviceNames = {};
618
617
  try {
619
618
  deviceNames = (await app.getDeviceNames?.()) ?? {};
620
619
  } catch {
621
620
  deviceNames = {};
622
621
  }
623
- const selfNameFallback = runtime?.deviceName ?? config?.deviceName ?? null;
622
+ const selfNameFallback = runtime?.deviceName ?? null;
624
623
 
625
624
  let syncStatus = null;
626
625
  try {
@@ -891,7 +890,7 @@ export async function buildSettings({ app, service, config, runtime, home }) {
891
890
  } catch {
892
891
  // 忽略:门面未就绪
893
892
  }
894
- // 设备名:网络派生优先;无共享事件时回退 config/runtime(旧安装迁移)。
893
+ // 设备名:网络派生优先;无共享事件时回退 runtime(身份文件派生)。
895
894
  let selfDeviceName = null;
896
895
  try {
897
896
  const names = (await app.getDeviceNames?.()) ?? {};
@@ -904,8 +903,8 @@ export async function buildSettings({ app, service, config, runtime, home }) {
904
903
  const payload = {
905
904
  identity: {
906
905
  deviceId: app.deviceId,
907
- name: selfDeviceName ?? runtime?.deviceName ?? config?.deviceName ?? null,
908
- nameSource: selfDeviceName ? 'network' : (runtime?.deviceName ?? config?.deviceName ? 'local' : null),
906
+ name: selfDeviceName ?? runtime?.deviceName ?? null,
907
+ nameSource: selfDeviceName ? 'network' : (runtime?.deviceName ? 'local' : null),
909
908
  // W2:root(持主私钥)/ delegated(仅委派链)
910
909
  mode: runtime?.identityMode ?? config?.identity?.mode ?? null,
911
910
  peerId: status.peerId,
@@ -609,8 +609,6 @@ export const CONFIG_SCHEMA = [
609
609
  { path: 'semantic.cacheDir', kind: 'string', exposure: 'internal', writable: false, requiresRestart: true, default: null, ui: { type: 'text', label: '模型缓存目录' } },
610
610
  { path: 'storagePath', kind: 'string', exposure: 'internal', writable: false, requiresRestart: true, default: null, ui: { type: 'text', label: '存储路径' } },
611
611
  { path: 'storageAdapter', kind: 'enum', spec: { values: ['json', 'sqlite'] }, exposure: 'internal', writable: false, requiresRestart: true, default: 'json', ui: { type: 'select', label: '存储适配器' } },
612
- { path: 'deviceId', kind: 'string', exposure: 'internal', writable: false, requiresRestart: true, default: null, ui: { type: 'text', label: '设备标识' } },
613
- { path: 'deviceName', kind: 'string', exposure: 'internal', writable: false, requiresRestart: true, default: null, ui: { type: 'text', label: '设备名' } },
614
612
  { path: 'identity.mode', kind: 'enum', spec: { values: ['root', 'delegated'] }, exposure: 'internal', writable: false, requiresRestart: true, default: 'root', ui: { type: 'select', label: '身份模式' } },
615
613
  { path: 'encryption.level', kind: 'enum', spec: { values: ['none', 'at-rest'] }, exposure: 'internal', writable: false, requiresRestart: true, default: 'none', ui: { type: 'select', label: '加密级别' } },
616
614
  { path: 'encryption.passphraseEnv', kind: 'string', exposure: 'internal', writable: false, requiresRestart: true, default: null, ui: { type: 'text', label: '口令环境变量名' } },
package/src/config.mjs CHANGED
@@ -9,6 +9,12 @@ import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises';
9
9
  import { dirname, join } from 'node:path';
10
10
  import { Mebular, IdentityManager, FileEndpointStore, EndpointBook } from '@mebular/core';
11
11
  import { homeDir } from './home.mjs';
12
+ import {
13
+ cleanLegacyConfig,
14
+ createIdentityForStorage,
15
+ prepareHomeIdentity,
16
+ storagePathForHome,
17
+ } from './home-identity.mjs';
12
18
 
13
19
  /** 统一家目录(唯一真源,F-INST-1):见 `./home.mjs`。 */
14
20
  export { homeDir };
@@ -81,8 +87,16 @@ async function readKeyRecord(source) {
81
87
  };
82
88
  }
83
89
 
84
- /** 解析用户主密钥;按 env > config.keyFile > <home>/user-master-key.json > 生成并持久化 */
85
- export async function resolveMasterKeys(home, config) {
90
+ /** 只读主密钥记录(CLI init / provision 在签发身份前校验 keyFile)。 */
91
+ export async function readMasterKeyRecord(source) {
92
+ return readKeyRecord(source);
93
+ }
94
+
95
+ /**
96
+ * 解析用户主密钥;按 env > config.keyFile > <home>/user-master-key.json > 生成并持久化。
97
+ * `allowGenerate:false` 用于「已有身份」:绝不自动生成新的信任根。
98
+ */
99
+ export async function resolveMasterKeys(home, config, { allowGenerate = true } = {}) {
86
100
  const envFile = process.env.MEBULAR_USER_MASTER_KEY_FILE;
87
101
  const envInline = process.env.MEBULAR_USER_MASTER_KEY;
88
102
  if (envFile) return readKeyRecord(envFile);
@@ -94,6 +108,14 @@ export async function resolveMasterKeys(home, config) {
94
108
  const defaultFile = join(home, 'user-master-key.json');
95
109
  if (existsSync(defaultFile)) return readKeyRecord(defaultFile);
96
110
 
111
+ if (!allowGenerate) {
112
+ const error = new Error(
113
+ `已有设备身份,但缺少用户主密钥:${defaultFile}(不会自动生成新的信任根;请恢复原主密钥或从备份恢复)`,
114
+ );
115
+ error.code = 'IDENTITY_TRUST_ROOT_MISSING';
116
+ throw error;
117
+ }
118
+
97
119
  const master = await new IdentityManager().generateUserMasterKey();
98
120
  const record = {
99
121
  publicKey: Buffer.from(master.publicKey).toString('base64'),
@@ -114,27 +136,50 @@ export function identityMode(home, config, storagePath) {
114
136
  const explicit = config.identity?.mode;
115
137
  if (explicit === 'root' || explicit === 'delegated') return explicit;
116
138
  const identityFile = `${storagePath}.identity.json`;
139
+ if (!existsSync(identityFile)) return 'root';
140
+ try {
141
+ const identity = JSON.parse(readFileSync(identityFile, 'utf-8'));
142
+ // 主密钥直签的 root 身份没有 issuer/委派链;即使本地主密钥缺失也仍是 root
143
+ // (交给「信任根缺失」错误处理,而不是误判成 delegated)。
144
+ const chain = Array.isArray(identity?.certificateChain) ? identity.certificateChain : [];
145
+ if (identity?.certificate?.issuer !== undefined || chain.length > 1) return 'delegated';
146
+ if (identity?.certificate !== undefined) return 'root';
147
+ } catch {
148
+ // 身份文件损坏:交给 preflight 以 IDENTITY_INVALID fail closed。
149
+ return 'root';
150
+ }
151
+ // 旧/异构身份文件:沿用历史判定(主私钥在场 = root)。
117
152
  const masterFile = config.encryption?.keyFile ?? join(home, 'user-master-key.json');
118
- if (existsSync(identityFile)) {
119
- try {
120
- const rec = JSON.parse(readFileSync(masterFile, 'utf-8'));
121
- if (typeof rec.privateKeyPkcs8 !== 'string') return 'delegated';
122
- } catch {
123
- return 'delegated';
124
- }
153
+ try {
154
+ const rec = JSON.parse(readFileSync(masterFile, 'utf-8'));
155
+ if (typeof rec.privateKeyPkcs8 !== 'string') return 'delegated';
156
+ } catch {
157
+ return 'delegated';
125
158
  }
126
159
  return 'root';
127
160
  }
128
161
 
129
- /** 读取**用户主公钥**(委派模式只需公钥;`config.encryption.userMasterPublicKeyFile` 或 <home>/user-master-key.json)。 */
162
+ /**
163
+ * 读取**用户主公钥**(委派模式只需公钥)。
164
+ * 候选:`config.encryption.userMasterPublicKeyFile` → <home>/user-master-key.json → <home>/master-key.json
165
+ * (后两者覆盖 config 缺失时的既有布局;只读公开材料)。
166
+ */
130
167
  export async function resolveMasterPublicKey(home, config) {
131
- const file = config.encryption?.userMasterPublicKeyFile ?? join(home, 'user-master-key.json');
132
- if (!existsSync(file)) {
133
- throw new Error(`委派身份模式需要用户主公钥:${file}(配置 encryption.userMasterPublicKeyFile 或放入该文件)`);
168
+ const candidates = [
169
+ config.encryption?.userMasterPublicKeyFile,
170
+ join(home, 'user-master-key.json'),
171
+ join(home, 'master-key.json'),
172
+ ].filter((file) => typeof file === 'string' && file.length > 0);
173
+ for (const file of candidates) {
174
+ if (!existsSync(file)) continue;
175
+ const data = JSON.parse(await readFile(file, 'utf-8'));
176
+ if (typeof data.publicKey !== 'string') throw new Error(`主公钥文件形状非法:${file}`);
177
+ return new Uint8Array(Buffer.from(data.publicKey, 'base64'));
134
178
  }
135
- const data = JSON.parse(await readFile(file, 'utf-8'));
136
- if (typeof data.publicKey !== 'string') throw new Error(`主公钥文件形状非法:${file}`);
137
- return new Uint8Array(Buffer.from(data.publicKey, 'base64'));
179
+ throw new Error(
180
+ `委派身份模式需要用户主公钥(已尝试:${candidates.join(' / ')});`
181
+ + '请配置 encryption.userMasterPublicKeyFile 或恢复主公钥文件',
182
+ );
138
183
  }
139
184
 
140
185
  /** 依配置构建并初始化 Mebular 门面 */
@@ -142,15 +187,29 @@ export async function createMebular() {
142
187
  const home = homeDir();
143
188
  const config = await loadConfigFile(home);
144
189
  const storageAdapter = config.storageAdapter ?? 'json';
145
- const storagePath = process.env.MEBULAR_STORAGE_PATH
146
- ?? config.storagePath
147
- ?? join(home, storageAdapter === 'sqlite' ? 'store.sqlite' : 'store.jsonl');
148
- const deviceId = process.env.MEBULAR_DEVICE_ID ?? config.deviceId ?? `device-${process.env.HOSTNAME ?? 'local'}`;
149
- const deviceName = process.env.MEBULAR_DEVICE_NAME ?? config.deviceName;
190
+ const storagePath = storagePathForHome(home, config, process.env);
191
+ // F-IDENT-1:身份文件是 deviceId/deviceName 的唯一权威;env/config 只在身份缺失时作为 bootstrap。
192
+ const prepared = prepareHomeIdentity({ home, config, env: process.env });
193
+ if (!prepared.ok) {
194
+ const error = new Error(prepared.message);
195
+ error.code = prepared.code;
196
+ error.identityPath = prepared.identityPath;
197
+ if (prepared.problems) error.problems = prepared.problems;
198
+ throw error;
199
+ }
200
+ for (const warning of prepared.warnings) console.error(`warning: ${warning}`);
150
201
  const mode = identityMode(home, config, storagePath);
202
+ if (prepared.status === 'missing' && mode === 'delegated') {
203
+ const error = new Error(
204
+ `委派身份缺少身份文件:${prepared.identityPath}。委派设备需要既有证书链,不能在本机新签发。`,
205
+ );
206
+ error.code = 'IDENTITY_NOT_INITIALIZED';
207
+ error.identityPath = prepared.identityPath;
208
+ throw error;
209
+ }
151
210
  // 生效值快照(console 设置卡应展示这些,而不是静态 config,否则 CLI/env 覆盖后卡片会失真)
152
211
  const effective = {
153
- deviceName: deviceName ?? null,
212
+ deviceName: prepared.identity.deviceName,
154
213
  identityMode: mode,
155
214
  storageAdapter,
156
215
  encryptionLevel: config.encryption?.level ?? 'none',
@@ -174,7 +233,23 @@ export async function createMebular() {
174
233
  const masterKeys =
175
234
  mode === 'delegated'
176
235
  ? { userMasterKey: await resolveMasterPublicKey(home, config) }
177
- : await resolveMasterKeys(home, config);
236
+ // 已有身份时禁止自动生成新主密钥(避免静默更换信任根)。
237
+ : await resolveMasterKeys(home, config, { allowGenerate: prepared.status === 'missing' });
238
+
239
+ let deviceId = prepared.identity.deviceId;
240
+ let deviceName = prepared.identity.deviceName;
241
+ if (prepared.status === 'missing') {
242
+ const created = await createIdentityForStorage({
243
+ storagePath,
244
+ deviceId,
245
+ deviceName,
246
+ userMasterPrivateKey: masterKeys.userMasterPrivateKey,
247
+ userMasterPublicKey: masterKeys.userMasterKey,
248
+ });
249
+ deviceId = created.deviceId;
250
+ deviceName = created.deviceName;
251
+ effective.deviceName = created.deviceName;
252
+ }
178
253
 
179
254
  // C2:地址簿里的 seeds(配对时随令牌写入)+ 配置 seeds → 客户端 relay 列表
180
255
  const bookSeeds = effective.networkEnabled ? await relaySeedsFromBook(home) : [];
@@ -249,6 +324,18 @@ export async function createMebular() {
249
324
  },
250
325
  });
251
326
  await app.initialize();
327
+ // 身份已就绪:备份并移除 legacy config 身份字段(即使旧值与身份不同也以身份为准)。
328
+ // 失败不阻断启动:身份仍是唯一权威,下次启动重试迁移。
329
+ try {
330
+ const migrated = await cleanLegacyConfig({ configPath: configPath(home), identity: { deviceId, deviceName } });
331
+ for (const warning of migrated.warnings) console.error(`warning: ${warning}`);
332
+ if (migrated.migrated) {
333
+ delete config.deviceId;
334
+ delete config.deviceName;
335
+ }
336
+ } catch (error) {
337
+ console.error(`warning: 无法清理 config.json 旧身份字段(${error?.message ?? error})`);
338
+ }
252
339
  // W2:按 config.network.peers 主动拨号(daemon 形态的点对点建立;只有一方需地址)
253
340
  for (const peer of config.network?.peers ?? []) {
254
341
  if (typeof peer?.addr !== 'string' || peer.addr.length === 0) continue;
@@ -0,0 +1,389 @@
1
+ // 设备身份契约(F-IDENT-1):`<storagePath>.identity.json` 是 deviceId/deviceName 的唯一权威。
2
+ //
3
+ // 本模块只做 MCP/CLI 侧策略:读取与结构校验、bootstrap 取值、显式创建身份、清理旧 config 字段。
4
+ // 证书链的密码学校验仍由 core 在使用身份时完成;这里不做额外的链验证。
5
+ //
6
+ // 关键不变量:
7
+ // - identity 存在且有效 → 以 identity 为准;env 只警告,legacy config 字段备份后删除;
8
+ // - identity 缺失 → 仅允许在 store 为空时 bootstrap;绝不覆盖已有事件(避免自动换钥);
9
+ // - identity 无效 → fail closed,不写任何文件。
10
+ //
11
+ // 本模块的读路径刻意不依赖 @mebular/core(root/委派判定与 preflight 需要轻量):
12
+ // 只有显式创建设备身份时才动态加载 IdentityManager。
13
+
14
+ import { existsSync, readFileSync, statSync } from 'node:fs';
15
+ import { chmod, copyFile, mkdir, readFile, rename, writeFile } from 'node:fs/promises';
16
+ import { hostname } from 'node:os';
17
+ import { dirname, join } from 'node:path';
18
+
19
+ /** 旧 config 身份字段的备份名(与 config-apply 的 config.json.bak 区分)。 */
20
+ export const LEGACY_CONFIG_BACKUP_SUFFIX = '.identity-legacy.bak';
21
+
22
+ const HEX_32_BYTES = /^[0-9a-f]{64}$/i;
23
+
24
+ export function identityPathFor(storagePath) {
25
+ return `${storagePath}.identity.json`;
26
+ }
27
+
28
+ /** 解析存储路径(与 createMebular 同序:env > config > home 默认)。 */
29
+ export function storagePathForHome(home, config = {}, env = process.env) {
30
+ const envPath = typeof env?.MEBULAR_STORAGE_PATH === 'string' ? env.MEBULAR_STORAGE_PATH.trim() : '';
31
+ if (envPath.length > 0) return envPath;
32
+ const configPath = typeof config?.storagePath === 'string' ? config.storagePath.trim() : '';
33
+ if (configPath.length > 0) return configPath;
34
+ return join(home, (config?.storageAdapter ?? 'json') === 'sqlite' ? 'store.sqlite' : 'store.jsonl');
35
+ }
36
+
37
+ function errorWith(code, message, extra = {}) {
38
+ const error = new Error(message);
39
+ error.code = code;
40
+ Object.assign(error, extra);
41
+ return error;
42
+ }
43
+
44
+ function sanitize(value) {
45
+ return String(value ?? '').trim().replace(/[^0-9A-Za-z._-]+/g, '-').replace(/^-+|-+$/g, '');
46
+ }
47
+
48
+ /** 缺省 bootstrap deviceId:沿用旧口径(主机名),但做字符集归一化。 */
49
+ export function defaultDeviceId(env = process.env) {
50
+ const host = env?.HOSTNAME || hostname() || 'local';
51
+ return `device-${sanitize(host) || 'local'}`;
52
+ }
53
+
54
+ function defaultDeviceName() {
55
+ return hostname() || 'mebular-device';
56
+ }
57
+
58
+ function asRecord(value) {
59
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null;
60
+ }
61
+
62
+ function hasOwn(object, key) {
63
+ return Object.prototype.hasOwnProperty.call(object, key);
64
+ }
65
+
66
+ /**
67
+ * 读取并做**结构**校验(不触碰私钥、不验证证书签名)。
68
+ * @returns {{status:'missing',path:string}
69
+ * | {status:'invalid',path:string,problems:string[]}
70
+ * | {status:'valid',path:string,record:object,deviceId:string,deviceName:string}}
71
+ */
72
+ export function readIdentityFile(storagePath) {
73
+ const path = identityPathFor(storagePath);
74
+ if (!existsSync(path)) return { status: 'missing', path };
75
+
76
+ let raw;
77
+ try {
78
+ raw = readFileSync(path, 'utf-8');
79
+ } catch (error) {
80
+ return { status: 'invalid', path, problems: [`身份文件读取失败:${error?.message ?? error}`] };
81
+ }
82
+
83
+ let record;
84
+ try {
85
+ record = JSON.parse(raw);
86
+ } catch (error) {
87
+ return { status: 'invalid', path, problems: [`身份文件损坏:${error?.message ?? error}`] };
88
+ }
89
+ record = asRecord(record);
90
+ if (record === null) return { status: 'invalid', path, problems: ['身份文件顶层必须是对象'] };
91
+
92
+ const problems = [];
93
+ const deviceId = typeof record.deviceId === 'string' ? record.deviceId.trim() : '';
94
+ if (deviceId.length === 0) problems.push('缺少有效 deviceId');
95
+ const publicKeyHex = typeof record.publicKeyHex === 'string' ? record.publicKeyHex : '';
96
+ if (!HEX_32_BYTES.test(publicKeyHex)) problems.push('publicKeyHex 不是 32 字节十六进制');
97
+
98
+ const certificate = asRecord(record.certificate);
99
+ if (certificate === null) {
100
+ problems.push('缺少设备证书');
101
+ } else {
102
+ if (certificate.deviceId !== deviceId) problems.push('证书 deviceId 与身份不一致');
103
+ if (HEX_32_BYTES.test(publicKeyHex)
104
+ && String(certificate.devicePublicKey ?? '').toLowerCase() !== publicKeyHex.toLowerCase()) {
105
+ problems.push('证书公钥与 publicKeyHex 不一致');
106
+ }
107
+ if (typeof certificate.signature !== 'string' || certificate.signature.length === 0) {
108
+ problems.push('证书缺少签名');
109
+ }
110
+ }
111
+
112
+ if (record.certificateChain !== undefined) {
113
+ if (!Array.isArray(record.certificateChain)) problems.push('certificateChain 必须是数组');
114
+ else if (record.certificateChain.length === 0) problems.push('certificateChain 不能为空');
115
+ else if (asRecord(record.certificateChain[0])?.deviceId !== deviceId) {
116
+ problems.push('certificateChain 叶证书与 deviceId 不一致');
117
+ }
118
+ }
119
+
120
+ const hasPlain = typeof record.privateKeyPkcs8 === 'string' && record.privateKeyPkcs8.length > 0;
121
+ const hasSealed = asRecord(record.privateKeyEncrypted) !== null;
122
+ if (!hasPlain && !hasSealed) problems.push('缺少设备私钥材料');
123
+
124
+ if (problems.length > 0) return { status: 'invalid', path, problems };
125
+
126
+ const deviceName = typeof record.deviceName === 'string' && record.deviceName.trim().length > 0
127
+ ? record.deviceName
128
+ : deviceId;
129
+ return { status: 'valid', path, record, deviceId, deviceName };
130
+ }
131
+
132
+ /**
133
+ * 只读准备:返回 identity 或 bootstrap 取值,绝不写盘。
134
+ *
135
+ * @returns {{ok:true,status:'valid'|'missing',identityPath:string,
136
+ * identity:{deviceId:string,deviceName:string},source:'identity'|'bootstrap',
137
+ * warnings:string[],legacyConfigFields:string[]}
138
+ * | {ok:false,status:'invalid'|'mismatch',code:string,identityPath:string,
139
+ * message:string,problems?:string[]}}
140
+ */
141
+ export function prepareIdentity({ config = {}, storagePath, env = process.env, explicit = null } = {}) {
142
+ const read = readIdentityFile(storagePath);
143
+ const warnings = [];
144
+
145
+ if (read.status === 'invalid') {
146
+ return {
147
+ ok: false,
148
+ status: 'invalid',
149
+ code: 'IDENTITY_INVALID',
150
+ identityPath: read.path,
151
+ message: `身份文件无效:${read.path}(${(read.problems ?? []).join(';')})`,
152
+ problems: read.problems ?? [],
153
+ };
154
+ }
155
+
156
+ const explicitId = typeof explicit?.deviceId === 'string' ? explicit.deviceId.trim() : '';
157
+ const explicitName = typeof explicit?.deviceName === 'string' ? explicit.deviceName.trim() : '';
158
+
159
+ if (read.status === 'valid') {
160
+ const identity = { deviceId: read.deviceId, deviceName: read.deviceName };
161
+ // 显式 --device-id 与已有身份冲突 = 硬错误(身份不能被 init/配置改写)。
162
+ if (explicitId.length > 0 && explicitId !== identity.deviceId) {
163
+ return {
164
+ ok: false,
165
+ status: 'mismatch',
166
+ code: 'IDENTITY_MISMATCH',
167
+ identityPath: read.path,
168
+ message: `--device-id ${explicitId} 与已有身份 ${identity.deviceId} 不一致;已有身份不能被改写。`,
169
+ };
170
+ }
171
+ // 设备名不是身份不可变项:忽略显式/env 覆盖,但明确告知(改名需要改写身份文件,不在本契约内)。
172
+ if (explicitName.length > 0 && explicitName !== identity.deviceName) {
173
+ warnings.push(`忽略 --device-name ${explicitName}:已有身份设备名 ${identity.deviceName} 是唯一权威`);
174
+ }
175
+ if (typeof env?.MEBULAR_DEVICE_ID === 'string' && env.MEBULAR_DEVICE_ID.trim().length > 0
176
+ && env.MEBULAR_DEVICE_ID.trim() !== identity.deviceId) {
177
+ warnings.push(`忽略 MEBULAR_DEVICE_ID=${env.MEBULAR_DEVICE_ID}:已有身份 ${identity.deviceId} 是唯一权威`);
178
+ }
179
+ if (typeof env?.MEBULAR_DEVICE_NAME === 'string' && env.MEBULAR_DEVICE_NAME.trim().length > 0
180
+ && env.MEBULAR_DEVICE_NAME.trim() !== identity.deviceName) {
181
+ warnings.push(`忽略 MEBULAR_DEVICE_NAME=${env.MEBULAR_DEVICE_NAME}:已有身份设备名 ${identity.deviceName} 是唯一权威`);
182
+ }
183
+
184
+ const legacyConfigFields = [];
185
+ if (hasOwn(config ?? {}, 'deviceId')) legacyConfigFields.push('deviceId');
186
+ if (hasOwn(config ?? {}, 'deviceName')) legacyConfigFields.push('deviceName');
187
+ if (legacyConfigFields.includes('deviceId') && config.deviceId !== identity.deviceId) {
188
+ warnings.push(
189
+ `legacy config.deviceId=${String(config.deviceId)} 与身份 ${identity.deviceId} 不一致:`
190
+ + '按身份继续,并备份后移除旧字段',
191
+ );
192
+ }
193
+ return {
194
+ ok: true,
195
+ status: 'valid',
196
+ identityPath: read.path,
197
+ identity,
198
+ source: 'identity',
199
+ warnings,
200
+ legacyConfigFields,
201
+ };
202
+ }
203
+
204
+ // identity 缺失:只生成 bootstrap 候选,不创建、不写 config。
205
+ // 优先级:显式参数 > env(仅 bootstrap)> legacy config > 默认。
206
+ const configId = typeof config?.deviceId === 'string' ? config.deviceId.trim() : '';
207
+ const configName = typeof config?.deviceName === 'string' ? config.deviceName.trim() : '';
208
+ const envId = typeof env?.MEBULAR_DEVICE_ID === 'string' ? env.MEBULAR_DEVICE_ID.trim() : '';
209
+ const envName = typeof env?.MEBULAR_DEVICE_NAME === 'string' ? env.MEBULAR_DEVICE_NAME.trim() : '';
210
+ const deviceId = explicitId || envId || configId || defaultDeviceId(env);
211
+ const deviceName = explicitName || envName || configName || defaultDeviceName();
212
+ return {
213
+ ok: true,
214
+ status: 'missing',
215
+ identityPath: read.path,
216
+ identity: { deviceId, deviceName: deviceName || deviceId },
217
+ source: 'bootstrap',
218
+ warnings,
219
+ legacyConfigFields: [],
220
+ };
221
+ }
222
+
223
+ /**
224
+ * 只读 preflight:prepareIdentity + 身份缺失时的空 store 断言。
225
+ * 运行期(CLI/App/DSH 子进程前)与 createMebular 共用,确保「无效身份」以明确原因失败。
226
+ */
227
+ export function prepareHomeIdentity({ home, config = {}, env = process.env, explicit = null } = {}) {
228
+ const storagePath = storagePathForHome(home, config, env);
229
+ const prepared = prepareIdentity({ config, storagePath, env, explicit });
230
+ if (!prepared.ok) return { ...prepared, storagePath };
231
+ if (prepared.status === 'missing') {
232
+ try {
233
+ assertFreshStore(storagePath);
234
+ } catch (error) {
235
+ return {
236
+ ok: false,
237
+ status: 'occupied',
238
+ code: error?.code ?? 'IDENTITY_STORE_OCCUPIED',
239
+ identityPath: identityPathFor(storagePath),
240
+ message: error?.message ?? String(error),
241
+ storagePath,
242
+ };
243
+ }
244
+ }
245
+ return { ...prepared, storagePath };
246
+ }
247
+
248
+ /** 已有 store 数据时禁止自动签发新身份(避免自动换钥)。 */
249
+ export function assertFreshStore(storagePath) {
250
+ let stat;
251
+ try {
252
+ stat = statSync(storagePath);
253
+ } catch (error) {
254
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') return;
255
+ throw error;
256
+ }
257
+ if (stat.size === 0) return;
258
+ // JSONL:只有空白/空行 = 空 store;SQLite 等二进制文件按体积判空(无法证明为空即拒绝)。
259
+ if (/\.jsonl?$/i.test(storagePath)) {
260
+ const text = readFileSync(storagePath, 'utf-8');
261
+ if (text.split('\n').every((line) => line.trim().length === 0)) return;
262
+ }
263
+ throw errorWith(
264
+ 'IDENTITY_STORE_OCCUPIED',
265
+ `存储已有数据但身份文件缺失:拒绝自动生成新身份(${storagePath})。请恢复原身份文件或从备份恢复。`,
266
+ { storagePath, identityPath: identityPathFor(storagePath) },
267
+ );
268
+ }
269
+
270
+ /**
271
+ * 显式创建设备身份文件(仅用于 bootstrap:init / provision create / restore / 空 home 首启)。
272
+ * 不加密私钥;若配置了口令,core 首次 initialize 会按既有逻辑迁移为加密封套。
273
+ */
274
+ export async function createIdentity({
275
+ storagePath,
276
+ deviceId,
277
+ deviceName,
278
+ userMasterPrivateKey,
279
+ userMasterPublicKey = undefined,
280
+ }) {
281
+ const path = identityPathFor(storagePath);
282
+ const requestedId = String(deviceId ?? '').trim();
283
+ if (requestedId.length === 0) throw errorWith('IDENTITY_INVALID', '创建设备身份需要非空 deviceId');
284
+
285
+ if (existsSync(path)) {
286
+ const existing = readIdentityFile(storagePath);
287
+ if (existing.status === 'valid') {
288
+ if (existing.deviceId !== requestedId) {
289
+ throw errorWith('IDENTITY_MISMATCH', `已有身份 ${existing.deviceId} 与请求 ${requestedId} 不一致`);
290
+ }
291
+ return { deviceId: existing.deviceId, deviceName: existing.deviceName, path, created: false };
292
+ }
293
+ throw errorWith('IDENTITY_INVALID', `身份文件已存在但无效:${path}`);
294
+ }
295
+ if (!userMasterPrivateKey) {
296
+ throw errorWith('IDENTITY_TRUST_ROOT_MISSING', '创建设备身份需要用户主私钥(user-master-key.json)');
297
+ }
298
+
299
+ const { IdentityManager } = await import('@mebular/core');
300
+ const manager = new IdentityManager();
301
+ if (userMasterPublicKey) manager.setUserMasterPublicKey(userMasterPublicKey);
302
+ manager.setUserMasterPrivateKey(userMasterPrivateKey);
303
+ const name = String(deviceName ?? '').trim() || requestedId;
304
+ const identity = await manager.generateDeviceKey(requestedId, name);
305
+ identity.certificate = await manager.issueDeviceCertificate(requestedId);
306
+ const record = {
307
+ deviceId: identity.deviceId,
308
+ deviceName: identity.name,
309
+ publicKeyHex: Buffer.from(identity.publicKey).toString('hex'),
310
+ certificate: identity.certificate,
311
+ ...(identity.certificateChain !== undefined ? { certificateChain: identity.certificateChain } : {}),
312
+ createdAt: identity.createdAt,
313
+ privateKeyPkcs8: await IdentityManager.exportPrivateKey(identity.privateKey),
314
+ };
315
+ await mkdir(dirname(path), { recursive: true });
316
+ try {
317
+ await writeFile(path, JSON.stringify(record, null, 2), { mode: 0o600, flag: 'wx' });
318
+ } catch (error) {
319
+ if (error?.code === 'EEXIST') {
320
+ const existing = readIdentityFile(storagePath);
321
+ if (existing.status === 'valid' && existing.deviceId === requestedId) {
322
+ return { deviceId: existing.deviceId, deviceName: existing.deviceName, path, created: false };
323
+ }
324
+ throw errorWith('IDENTITY_MISMATCH', `身份文件在创建过程中被占用:${path}`);
325
+ }
326
+ throw error;
327
+ }
328
+ try { await chmod(path, 0o600); } catch { /* Windows ACL 兜底 */ }
329
+ return { deviceId: identity.deviceId, deviceName: identity.name, path, created: true, record };
330
+ }
331
+
332
+ /** 文件系统写失败统一映射为 storage 初始化失败(身份文件与 store 同路径域)。 */
333
+ export async function createIdentityForStorage(input) {
334
+ try {
335
+ return await createIdentity(input);
336
+ } catch (error) {
337
+ if (typeof error?.code === 'string' && error.code.startsWith('IDENTITY_')) throw error;
338
+ const wrapped = errorWith(
339
+ 'STORAGE_INIT_FAILED',
340
+ `身份文件写入失败(${identityPathFor(input.storagePath)}):${error?.message ?? error}`,
341
+ );
342
+ wrapped.cause = error;
343
+ throw wrapped;
344
+ }
345
+ }
346
+
347
+ /**
348
+ * 旧 config 的 deviceId/deviceName:备份整份 config 后删除字段,原子写回。
349
+ * 无论旧值是否与身份一致都移除(身份是唯一权威);文件不存在或无字段时 no-op。
350
+ * 备份只在首次迁移时创建,保留最早的 legacy 快照。
351
+ */
352
+ export async function cleanLegacyConfig({ configPath: cfgPath, identity = null } = {}) {
353
+ if (typeof cfgPath !== 'string' || cfgPath.length === 0 || !existsSync(cfgPath)) {
354
+ return { migrated: false, backupPath: null, warnings: [] };
355
+ }
356
+ let current;
357
+ try {
358
+ current = JSON.parse(await readFile(cfgPath, 'utf-8'));
359
+ } catch (error) {
360
+ throw errorWith('CONFIG_INVALID', `配置文件损坏:${cfgPath}(${error?.message ?? error})`);
361
+ }
362
+ if (current === null || typeof current !== 'object' || Array.isArray(current)) {
363
+ throw errorWith('CONFIG_INVALID', `配置文件损坏:${cfgPath}(顶层必须是对象)`);
364
+ }
365
+ const hasDeviceId = hasOwn(current, 'deviceId');
366
+ const hasDeviceName = hasOwn(current, 'deviceName');
367
+ if (!hasDeviceId && !hasDeviceName) {
368
+ return { migrated: false, backupPath: null, warnings: [] };
369
+ }
370
+
371
+ const backupPath = `${cfgPath}${LEGACY_CONFIG_BACKUP_SUFFIX}`;
372
+ if (!existsSync(backupPath)) {
373
+ await copyFile(cfgPath, backupPath);
374
+ try { await chmod(backupPath, 0o600); } catch { /* Windows ACL 兜底 */ }
375
+ }
376
+ delete current.deviceId;
377
+ delete current.deviceName;
378
+
379
+ const tmp = `${cfgPath}.tmp-${process.pid}`;
380
+ await writeFile(tmp, JSON.stringify(current, null, 2), 'utf-8');
381
+ await rename(tmp, cfgPath);
382
+ try { await chmod(cfgPath, 0o600); } catch { /* Windows ACL 兜底 */ }
383
+
384
+ const warnings = [];
385
+ if (identity && typeof identity.deviceId === 'string') {
386
+ warnings.push(`已从 config.json 移除旧身份字段,设备身份以 ${identity.deviceId} 为准`);
387
+ }
388
+ return { migrated: true, backupPath, warnings };
389
+ }
package/src/profiles.mjs CHANGED
@@ -164,6 +164,23 @@ function inferKind(home, config) {
164
164
  }
165
165
  }
166
166
 
167
+ /**
168
+ * 档案展示用 deviceId:身份文件优先;config.deviceId 仅旧布局回退(只读展示,不写盘)。
169
+ * 运行期由 createMebular preflight 对无效/缺失身份 fail closed。
170
+ */
171
+ function deviceIdForHome(home, config = {}) {
172
+ const storage = typeof config?.storagePath === 'string' && config.storagePath.length > 0
173
+ ? resolve(home, config.storagePath)
174
+ : join(home, 'store.jsonl');
175
+ try {
176
+ const record = JSON.parse(readFileSync(`${storage}.identity.json`, 'utf-8'));
177
+ if (typeof record?.deviceId === 'string' && record.deviceId.length > 0) return record.deviceId;
178
+ } catch {
179
+ // 身份文件缺失/损坏 → 旧布局回退。
180
+ }
181
+ return typeof config?.deviceId === 'string' ? config.deviceId : null;
182
+ }
183
+
167
184
  /** 公开指纹:sha256(bytes) 前 12 hex。输入无效返回 null(不阻塞加入/展示)。 */
168
185
  export function masterFingerprintFromBytes(bytes) {
169
186
  try {
@@ -244,7 +261,7 @@ function synthesizeDefaultRegistry(home) {
244
261
  createdAt,
245
262
  lastUsedAt: null,
246
263
  masterFingerprint: masterFingerprintForHome(home, config),
247
- deviceId: typeof config.deviceId === 'string' ? config.deviceId : null,
264
+ deviceId: deviceIdForHome(home, config),
248
265
  }],
249
266
  };
250
267
  }
package/src/provision.mjs CHANGED
@@ -12,7 +12,13 @@ import { chmod, mkdir, readFile, rm, writeFile } from 'node:fs/promises';
12
12
  import { createServer } from 'node:net';
13
13
  import { hostname } from 'node:os';
14
14
  import { dirname, join, resolve } from 'node:path';
15
- import { configPath, resolveMasterKeys } from './config.mjs';
15
+ import { configPath, readMasterKeyRecord, resolveMasterKeys } from './config.mjs';
16
+ import {
17
+ assertFreshStore,
18
+ createIdentityForStorage,
19
+ identityPathFor,
20
+ readIdentityFile,
21
+ } from './home-identity.mjs';
16
22
  import {
17
23
  DEFAULT_PROFILE_NAME,
18
24
  masterFingerprintForHome,
@@ -123,8 +129,13 @@ const PROVISION_STATE_PATHS = [
123
129
  * P1:create/join 的落盘事务快照。热初始化失败时只删除**本次新建**的文件,
124
130
  * 不触碰调用前已存在的任何内容(home 锁始终由当前进程持有)。
125
131
  */
126
- export async function snapshotProvisionState(home) {
132
+ export async function snapshotProvisionState(home, { storagePath } = {}) {
127
133
  const paths = new Set(PROVISION_STATE_PATHS.map((rel) => join(home, rel)));
134
+ const effectiveStorage = typeof storagePath === 'string' && storagePath.length > 0
135
+ ? storagePath
136
+ : join(home, 'store.jsonl');
137
+ paths.add(identityPathFor(effectiveStorage));
138
+ paths.add(`${configPath(home)}.identity-legacy.bak`);
128
139
  paths.add(configPath(home));
129
140
  const cloud = resolveCloudRoot({ home, env: process.env });
130
141
  if (cloud.available) {
@@ -235,16 +246,21 @@ async function writeConfigFile(home, config) {
235
246
  * 写引导态 config.json(create/restore 共用)。调用方必须已确保 `<home>/user-master-key.json` 存在
236
247
  * (create 由 resolveMasterKeys 生成;restore 由备份解密落盘)。
237
248
  */
238
- async function writeInitialProvisionConfig({ home, deviceName, deviceId, mcpPort, joinPort, listenPort, action = 'create', notes = [] }) {
249
+ async function writeInitialProvisionConfig({ home, storagePath, deviceName, deviceId, mcpPort, joinPort, listenPort, action = 'create', notes = [] }) {
239
250
  const name = String(deviceName ?? '').trim() || defaultDeviceName();
240
- const id = normalizeExplicitDeviceId(deviceId) ?? deriveDeviceId(name);
251
+ // 调用方传入的身份值即权威;仅在缺省时按名字派生(保持旧内部契约)。
252
+ const id = String(deviceId ?? '').trim() || deriveDeviceId(name);
253
+ // 与 isProvisionHome/createMebular 同序:env 覆盖 > <home>/store.jsonl。
254
+ const effectiveStorage = typeof storagePath === 'string' && storagePath.length > 0
255
+ ? storagePath
256
+ : (process.env.MEBULAR_STORAGE_PATH ?? join(home, 'store.jsonl'));
241
257
  // 端口预检(避免重启即失败):mcp 端口 = 当前引导服务端口(我们自己持有,无需探测)
242
258
  const joinChoice = await findFreePort(Number(joinPort) > 0 ? Number(joinPort) : 4002);
243
259
  const listenChoice = await findFreePort(Number(listenPort) > 0 ? Number(listenPort) : 4001);
244
260
 
261
+ // F-IDENT-1:config 不写身份字段;deviceId/deviceName 由 <storagePath>.identity.json 提供。
245
262
  const config = {
246
- deviceId: id,
247
- deviceName: name,
263
+ storagePath: effectiveStorage,
248
264
  encryption: { level: 'none' },
249
265
  network: {
250
266
  enabled: true,
@@ -298,17 +314,30 @@ export async function provisionCreate({ home, cloudName, deviceName, deviceId, m
298
314
  const registryBackupPath = cloud.available ? join(cloud.root, 'profiles.json.bak') : null;
299
315
  const registryExisted = registryPath !== null && existsSync(registryPath);
300
316
  const registryBackupExisted = registryBackupPath !== null && existsSync(registryBackupPath);
317
+ const storagePath = process.env.MEBULAR_STORAGE_PATH ?? join(home, 'store.jsonl');
318
+ const identityFile = identityPathFor(storagePath);
319
+ const identityExisted = existsSync(identityFile);
301
320
  try {
321
+ // 缺身份但 store 已有数据 = 自动换钥风险:先拒绝,绝不写主密钥/配置。
322
+ assertFreshStore(storagePath);
302
323
  const master = await resolveMasterKeys(home, {});
303
324
  if (master.userMasterPrivateKey === undefined) {
304
325
  const error = new Error('建新需要 root 主密钥(生成失败:未获得私钥)');
305
326
  error.code = 'MASTER_KEY_FAILED';
306
327
  throw error;
307
328
  }
329
+ const identity = await createIdentityForStorage({
330
+ storagePath,
331
+ deviceId: normalizeExplicitDeviceId(deviceId) ?? deriveDeviceId(name),
332
+ deviceName: name,
333
+ userMasterPrivateKey: master.userMasterPrivateKey,
334
+ userMasterPublicKey: master.userMasterKey,
335
+ });
308
336
  const result = await writeInitialProvisionConfig({
309
337
  home,
310
- deviceName: name,
311
- deviceId,
338
+ storagePath,
339
+ deviceName: identity.deviceName,
340
+ deviceId: identity.deviceId,
312
341
  mcpPort,
313
342
  joinPort,
314
343
  listenPort,
@@ -340,6 +369,7 @@ export async function provisionCreate({ home, cloudName, deviceName, deviceId, m
340
369
  } catch (error) {
341
370
  if (!keyExisted) await rm(keyPath, { force: true }).catch(() => undefined);
342
371
  if (!configExisted) await rm(cfgPath, { force: true }).catch(() => undefined);
372
+ if (!identityExisted) await rm(identityFile, { force: true }).catch(() => undefined);
343
373
  if (registryPath !== null && !registryExisted) await rm(registryPath, { force: true }).catch(() => undefined);
344
374
  if (registryBackupPath !== null && !registryBackupExisted) await rm(registryBackupPath, { force: true }).catch(() => undefined);
345
375
  throw error;
@@ -370,6 +400,10 @@ export async function provisionRestore({ home, file, code, cloudName, deviceName
370
400
  }
371
401
  const fleet = await import('../../fleet/dist/index.js');
372
402
  const keyPath = join(home, 'user-master-key.json');
403
+ const storagePath = process.env.MEBULAR_STORAGE_PATH ?? join(home, 'store.jsonl');
404
+ // 缺身份但 store 已有数据 = 自动换钥风险:写主密钥前先拒绝。
405
+ assertFreshStore(storagePath);
406
+ const transaction = await snapshotProvisionState(home, { storagePath });
373
407
  let restored;
374
408
  try {
375
409
  restored = await fleet.restoreMasterKeyBackup({
@@ -384,12 +418,25 @@ export async function provisionRestore({ home, file, code, cloudName, deviceName
384
418
  wrapped.code = 'RESTORE_FAILED';
385
419
  throw wrapped;
386
420
  }
387
- const transaction = await snapshotProvisionState(home);
388
421
  try {
422
+ const master = await readMasterKeyRecord(keyPath);
423
+ if (master.userMasterPrivateKey === undefined) {
424
+ const error = new Error('恢复失败:主密钥文件缺少私钥(无法签发设备身份)');
425
+ error.code = 'RESTORE_FAILED';
426
+ throw error;
427
+ }
428
+ const identity = await createIdentityForStorage({
429
+ storagePath,
430
+ deviceId: normalizeExplicitDeviceId(deviceId) ?? deriveDeviceId(name),
431
+ deviceName: name,
432
+ userMasterPrivateKey: master.userMasterPrivateKey,
433
+ userMasterPublicKey: master.userMasterKey,
434
+ });
389
435
  const result = await writeInitialProvisionConfig({
390
436
  home,
391
- deviceName: name,
392
- deviceId,
437
+ storagePath,
438
+ deviceName: identity.deviceName,
439
+ deviceId: identity.deviceId,
393
440
  mcpPort,
394
441
  joinPort,
395
442
  listenPort,
@@ -456,11 +503,10 @@ async function resolveJoinPorts({ ports = {}, mcpPort, joinPort, listenPort }) {
456
503
  return { mcp, join, listen };
457
504
  }
458
505
 
459
- function delegatedConfig({ home, id, name, namespace, ports, peers = [] }) {
506
+ function delegatedConfig({ home, namespace, ports, peers = [] }) {
460
507
  return {
461
508
  storagePath: join(home, 'store.jsonl'),
462
- deviceId: id,
463
- deviceName: name,
509
+ // F-IDENT-1:不写身份字段;deviceId/deviceName 由身份文件提供。
464
510
  identity: { mode: 'delegated' },
465
511
  encryption: { level: 'none', userMasterPublicKeyFile: join(home, 'master-key.json') },
466
512
  network: {
@@ -508,6 +554,8 @@ export async function provisionJoinInto({
508
554
  error.code = 'ALREADY_PROVISIONED';
509
555
  throw error;
510
556
  }
557
+ // 身份缺失但 store 已有数据 = 自动换钥风险:在写 config / 请求加入前拒绝。
558
+ assertFreshStore(join(home, 'store.jsonl'));
511
559
  if (typeof token !== 'string' || token.trim().length === 0) {
512
560
  const error = new Error('需要令牌文本(邀请面板生成的 base64 令牌)');
513
561
  error.code = 'TOKEN_REQUIRED';
@@ -540,7 +588,7 @@ export async function provisionJoinInto({
540
588
  };
541
589
 
542
590
  // 预写 config:兑换前完成本机落盘(端口复用当前忆云;准备阶段不 bind)。
543
- await writeConfigFile(home, delegatedConfig({ home, id, name, namespace, ports: resolvedPorts }));
591
+ await writeConfigFile(home, delegatedConfig({ home, namespace, ports: resolvedPorts }));
544
592
 
545
593
  let joined;
546
594
  try {
@@ -548,6 +596,7 @@ export async function provisionJoinInto({
548
596
  dir: home,
549
597
  token: token.trim(),
550
598
  device: id,
599
+ deviceName: name,
551
600
  namespace,
552
601
  listen: `/ip4/0.0.0.0/tcp/${resolvedPorts.listen}`,
553
602
  agents: [{ name: 'echo', kind: 'echo' }],
@@ -579,21 +628,33 @@ export async function provisionJoinInto({
579
628
  const masterKeyPublic = join(home, 'master-key.json');
580
629
  const fingerprint = typeof joined.fingerprint === 'string' ? joined.fingerprint : null;
581
630
  try {
582
- const path = await writeConfigFile(home, delegatedConfig({ home, id, name, namespace, ports: resolvedPorts, peers }));
631
+ // 加入后身份文件必须可用且与请求一致——config 与档案都只引用身份提供的 deviceId。
632
+ const identity = readIdentityFile(join(home, 'store.jsonl'));
633
+ if (identity.status !== 'valid') {
634
+ const error = new Error(`加入后身份文件不可用:${identity.path}`);
635
+ error.code = 'IDENTITY_INVALID';
636
+ throw error;
637
+ }
638
+ if (identity.deviceId !== id) {
639
+ const error = new Error(`加入后身份 ${identity.deviceId} 与请求 ${id} 不一致`);
640
+ error.code = 'IDENTITY_MISMATCH';
641
+ throw error;
642
+ }
643
+ const path = await writeConfigFile(home, delegatedConfig({ home, namespace, ports: resolvedPorts, peers }));
583
644
  const profile = registerCurrentProfile
584
645
  ? await writeInitialProfile({
585
646
  home,
586
647
  name: profileName,
587
648
  kind: 'delegated',
588
- deviceId: id,
649
+ deviceId: identity.deviceId,
589
650
  masterFingerprint: fingerprint,
590
651
  })
591
652
  : { written: false, reason: 'not_current_profile' };
592
653
  return {
593
654
  ok: true,
594
655
  action: 'join',
595
- deviceId: id,
596
- deviceName: name,
656
+ deviceId: identity.deviceId,
657
+ deviceName: identity.deviceName,
597
658
  inviterDeviceId: parsed.inviterDeviceId,
598
659
  namespace,
599
660
  hinted: joined.hinted,
@@ -29,6 +29,7 @@ import {
29
29
  readRegistry,
30
30
  resolveCloudRoot,
31
31
  } from './profiles.mjs';
32
+ import { prepareHomeIdentity } from './home-identity.mjs';
32
33
  import { readRuntimeFile, runtimePath } from './runtime-file.mjs';
33
34
  import {
34
35
  readRuntimeProviders,
@@ -1146,6 +1147,29 @@ async function inspectRuntime(options = {}) {
1146
1147
  }
1147
1148
  }
1148
1149
 
1150
+ // F-IDENT-1:spawn/service 之前完成身份 preflight——无效身份或「身份缺失 + 非空 store」
1151
+ // 以明确 reason fail closed,而不是 child 退出后只剩 unreachable。
1152
+ const homeConfig = await readHomeConfig(context.home);
1153
+ const identity = prepareHomeIdentity({ home: context.home, config: homeConfig, env });
1154
+ if (!identity.ok) {
1155
+ const result = baseResult(context, { http, checkedAt });
1156
+ result.ok = false;
1157
+ result.mode = 'error';
1158
+ result.reason = identity.status === 'invalid'
1159
+ ? 'identity_invalid'
1160
+ : identity.status === 'occupied'
1161
+ ? 'identity_store_occupied'
1162
+ : 'identity_mismatch';
1163
+ result.code = identity.code ?? null;
1164
+ result.message = identity.message;
1165
+ result.identity = {
1166
+ status: identity.status,
1167
+ path: identity.identityPath ?? null,
1168
+ ...(identity.problems ? { problems: identity.problems } : {}),
1169
+ };
1170
+ return result;
1171
+ }
1172
+
1149
1173
  const probeHealth = probeHealthFn
1150
1174
  ?? ((target, probeOptions) => probeRuntimeHealth(fetchImpl, target, probeOptions));
1151
1175
  let health;
package/src/serve.mjs CHANGED
@@ -3204,7 +3204,9 @@ export async function startHttpServer({
3204
3204
  phase = 'INITIALIZING';
3205
3205
  let transaction = null;
3206
3206
  try {
3207
- transaction = await snapshotProvisionState(home);
3207
+ transaction = await snapshotProvisionState(home, {
3208
+ storagePath: process.env.MEBULAR_STORAGE_PATH ?? join(home, 'store.jsonl'),
3209
+ });
3208
3210
  const result = action === 'create'
3209
3211
  ? await provisionCreate({
3210
3212
  home,
package/src/server.mjs CHANGED
@@ -140,9 +140,8 @@ export async function startServeServer(options = {}) {
140
140
  // F-NET-1(C):**先取单实例锁,再初始化网络**——第二写者应在绑定监听端口前就得到
141
141
  // 可读的 MCP_STORAGE_LOCKED(此前 createMebular 先启网络 → 抢 4001 → 裸 EADDRINUSE)。
142
142
  const preConfig = provisionStart ? {} : await loadConfigFile(home).catch(() => ({}));
143
- const preStoragePath = process.env.MEBULAR_STORAGE_PATH
144
- ?? preConfig.storagePath
145
- ?? join(home, (preConfig.storageAdapter ?? 'json') === 'sqlite' ? 'store.sqlite' : 'store.jsonl');
143
+ const { storagePathForHome } = await import('./home-identity.mjs');
144
+ const preStoragePath = storagePathForHome(home, preConfig, process.env);
146
145
  const lock = await acquireLock(home, preStoragePath);
147
146
 
148
147
  // 热初始化 / 正常启动共用:app、join 服务、运行时快照与生命周期资源。
package/src/version.mjs CHANGED
@@ -5,4 +5,4 @@
5
5
  // scripts/bump-version.mjs 只改这一处,scripts/verify-release-version.mjs
6
6
  // 校验它等于发布版本;不要在其它文件再写版本字面量。
7
7
 
8
- export const APP_VERSION = '0.2.2';
8
+ export const APP_VERSION = '0.2.3';