@mebular/mcp 0.2.2 → 0.2.4
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 +145 -15
- package/package.json +3 -3
- package/src/admin.mjs +7 -8
- package/src/clients.mjs +472 -34
- package/src/config-schema.mjs +0 -2
- package/src/config.mjs +110 -23
- package/src/home-identity.mjs +389 -0
- package/src/profiles.mjs +18 -1
- package/src/provision.mjs +80 -19
- package/src/runtime-supervisor.mjs +24 -0
- package/src/serve.mjs +34 -1
- package/src/server.mjs +20 -5
- package/src/tools.mjs +20 -17
- package/src/version.mjs +1 -1
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
|
-
/**
|
|
85
|
-
export async function
|
|
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
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
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
|
-
/**
|
|
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
|
|
132
|
-
|
|
133
|
-
|
|
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
|
-
|
|
136
|
-
|
|
137
|
-
|
|
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
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
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
|
|
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
|
-
|
|
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:
|
|
264
|
+
deviceId: deviceIdForHome(home, config),
|
|
248
265
|
}],
|
|
249
266
|
};
|
|
250
267
|
}
|