@mebular/mcp 0.3.7 → 0.3.8
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/package.json +4 -4
- package/src/clients.mjs +130 -9
- package/src/memory-capability.mjs +15 -0
- package/src/memory-runtime-supervisor.mjs +15 -2
- package/src/serve.mjs +636 -11
- package/src/tools.mjs +8 -0
- package/src/version.mjs +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mebular/mcp",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.8",
|
|
4
4
|
"description": "Mebular MCP server (stdio + Streamable HTTP): exposes Mebular memory and task capabilities to any MCP client. | Mebular MCP server(stdio + Streamable HTTP):把 Mebular 的记忆与任务能力暴露给任意 MCP client。",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": {
|
|
@@ -29,10 +29,10 @@
|
|
|
29
29
|
"access": "public"
|
|
30
30
|
},
|
|
31
31
|
"dependencies": {
|
|
32
|
-
"@mebular/core": "^0.3.
|
|
33
|
-
"@mebular/memory-runtime": "^0.3.
|
|
32
|
+
"@mebular/core": "^0.3.8",
|
|
33
|
+
"@mebular/memory-runtime": "^0.3.8",
|
|
34
34
|
"@modelcontextprotocol/server": "^2.3.1",
|
|
35
35
|
"zod": "^4.6.7",
|
|
36
|
-
"@mebular/fleet": "^0.3.
|
|
36
|
+
"@mebular/fleet": "^0.3.8"
|
|
37
37
|
}
|
|
38
38
|
}
|
package/src/clients.mjs
CHANGED
|
@@ -449,11 +449,19 @@ export function builtinAssistants(options = {}) {
|
|
|
449
449
|
probe: {
|
|
450
450
|
signals: [
|
|
451
451
|
{ kind: 'config-path', paths: [opencodePath] },
|
|
452
|
-
{ kind: 'cli', command: 'opencode --version', timeoutMs: 1500 },
|
|
452
|
+
{ kind: 'cli', command: 'opencode --version', timeoutMs: 1500, version: true },
|
|
453
453
|
{ kind: 'app-bundle', paths: ['/Applications/OpenChamber.app'] },
|
|
454
454
|
{ kind: 'process', pattern: 'opencode serve --service' },
|
|
455
455
|
],
|
|
456
456
|
},
|
|
457
|
+
// OpenChamber 复用 OpenCode 插件 → 同一 host 版本门。
|
|
458
|
+
compatibility: {
|
|
459
|
+
minVersion: MIN_OPENCODE_VERSION,
|
|
460
|
+
actionHint: 'upgrade_opencode',
|
|
461
|
+
reason: 'opencode_version_unsupported',
|
|
462
|
+
unknownActionHint: 'verify_host_version',
|
|
463
|
+
unknownReason: 'opencode_version_unknown',
|
|
464
|
+
},
|
|
457
465
|
writer: { strategy: 'merge-key', command: null, backup: 'byte-level', atomic: true },
|
|
458
466
|
verify: { cli: { command: 'opencode mcp list', expect: 'mebular', timeoutMs: 4000 }, configReadback: true },
|
|
459
467
|
activation: { kind: 'user-reload', note: 'OpenChamber:由用户在 App 侧重载/重启生效;产品不得发 opencode reload 干扰运行服务' },
|
|
@@ -510,10 +518,18 @@ export function builtinAssistants(options = {}) {
|
|
|
510
518
|
probe: {
|
|
511
519
|
signals: [
|
|
512
520
|
{ kind: 'config-path', paths: [opencodePath] },
|
|
513
|
-
{ kind: 'cli', command: 'opencode --version', timeoutMs: 1500 },
|
|
521
|
+
{ kind: 'cli', command: 'opencode --version', timeoutMs: 1500, version: true },
|
|
514
522
|
{ kind: 'dir', paths: [join(userHome, '.config', 'opencode')] },
|
|
515
523
|
],
|
|
516
524
|
},
|
|
525
|
+
// `@mebular/opencode-plugin` 的启动门:宿主 < 2.2.0 时插件 disabled(自动记忆不可用)。
|
|
526
|
+
compatibility: {
|
|
527
|
+
minVersion: MIN_OPENCODE_VERSION,
|
|
528
|
+
actionHint: 'upgrade_opencode',
|
|
529
|
+
reason: 'opencode_version_unsupported',
|
|
530
|
+
unknownActionHint: 'verify_host_version',
|
|
531
|
+
unknownReason: 'opencode_version_unknown',
|
|
532
|
+
},
|
|
517
533
|
writer: { strategy: 'merge-key', command: null, backup: 'byte-level', atomic: true },
|
|
518
534
|
verify: { cli: { command: 'opencode mcp list', expect: 'mebular', timeoutMs: 4000 }, configReadback: true },
|
|
519
535
|
activation: { kind: 'user-reload', note: 'OpenCode 侧重载/重启后生效' },
|
|
@@ -1167,6 +1183,62 @@ export function landingState(assistant, options = {}) {
|
|
|
1167
1183
|
|
|
1168
1184
|
export const DEFAULT_CLI_TIMEOUT_MS = 1500;
|
|
1169
1185
|
|
|
1186
|
+
/**
|
|
1187
|
+
* OpenCode 插件启动门(与 `@mebular/opencode-plugin` 的 `MIN_OPENCODE_VERSION` 保持一致)。
|
|
1188
|
+
* 这是 host 兼容性下限:低版本宿主无法加载插件,自动记忆在运行时是关闭的。测试里用
|
|
1189
|
+
* `tests/mcp/clients.test.mjs` 的 drift guard 断言两处常量相等。
|
|
1190
|
+
*/
|
|
1191
|
+
export const MIN_OPENCODE_VERSION = '2.2.0';
|
|
1192
|
+
|
|
1193
|
+
/** 从 `opencode --version` 之类的输出里取第一个 semver(容忍前缀/后缀)。 */
|
|
1194
|
+
export function parseHostVersion(value) {
|
|
1195
|
+
if (typeof value !== 'string') return null;
|
|
1196
|
+
const match = /(?:^|[^\d])(\d+)\.(\d+)\.(\d+)(?:[^\d]|$)/.exec(value);
|
|
1197
|
+
return match ? `${match[1]}.${match[2]}.${match[3]}` : null;
|
|
1198
|
+
}
|
|
1199
|
+
|
|
1200
|
+
/** 数值段比较(只用于本文件的 host 门;不含 prerelease 语义)。 */
|
|
1201
|
+
export function compareHostVersion(left, right) {
|
|
1202
|
+
const a = parseHostVersion(left);
|
|
1203
|
+
const b = parseHostVersion(right);
|
|
1204
|
+
if (!a || !b) return null;
|
|
1205
|
+
const av = a.split('.').map(Number);
|
|
1206
|
+
const bv = b.split('.').map(Number);
|
|
1207
|
+
for (let index = 0; index < 3; index += 1) {
|
|
1208
|
+
if (av[index] !== bv[index]) return av[index] < bv[index] ? -1 : 1;
|
|
1209
|
+
}
|
|
1210
|
+
return 0;
|
|
1211
|
+
}
|
|
1212
|
+
|
|
1213
|
+
/**
|
|
1214
|
+
* 由 descriptor 的 `compatibility` + 版本探针结果计算 host 兼容性。
|
|
1215
|
+
* 版本未知时 `supported=null`(fail-open:不凭猜测禁用,保持原有状态);
|
|
1216
|
+
* 版本已知且低于下限时 `supported=false`(fail-closed:绝不投影成「已接入」)。
|
|
1217
|
+
*/
|
|
1218
|
+
export function evaluateHostCompatibility(assistant, signals) {
|
|
1219
|
+
const spec = assistant?.compatibility;
|
|
1220
|
+
if (!spec || typeof spec.minVersion !== 'string') return null;
|
|
1221
|
+
const hostVersion = (signals ?? [])
|
|
1222
|
+
.map((signal) => signal?.version)
|
|
1223
|
+
.find((version) => typeof version === 'string' && version.length > 0) ?? null;
|
|
1224
|
+
const compared = hostVersion === null ? null : compareHostVersion(hostVersion, spec.minVersion);
|
|
1225
|
+
const supported = compared === null ? null : compared >= 0;
|
|
1226
|
+
return {
|
|
1227
|
+
supported,
|
|
1228
|
+
hostVersion,
|
|
1229
|
+
requiredVersion: spec.minVersion,
|
|
1230
|
+
automaticMemory: supported === true ? true : supported === false ? false : null,
|
|
1231
|
+
...(supported === false
|
|
1232
|
+
? { actionHint: spec.actionHint ?? 'upgrade_host', reason: spec.reason ?? null }
|
|
1233
|
+
: supported === null
|
|
1234
|
+
? {
|
|
1235
|
+
actionHint: spec.unknownActionHint ?? 'verify_host_version',
|
|
1236
|
+
reason: spec.unknownReason ?? 'host_version_unknown',
|
|
1237
|
+
}
|
|
1238
|
+
: {}),
|
|
1239
|
+
};
|
|
1240
|
+
}
|
|
1241
|
+
|
|
1170
1242
|
function defaultRun(command, timeoutMs, options = {}) {
|
|
1171
1243
|
const res = spawnSync(command, { shell: true, encoding: 'utf-8', timeout: timeoutMs, env: spawnEnv(options) });
|
|
1172
1244
|
return { ok: res.status === 0, code: res.status ?? 1, stdout: res.stdout ?? '', stderr: res.stderr ?? '' };
|
|
@@ -1216,7 +1288,16 @@ export function probeSignal(signal, options = {}) {
|
|
|
1216
1288
|
}
|
|
1217
1289
|
if (signal.kind === 'cli') {
|
|
1218
1290
|
const r = run(signal.command, signal.timeoutMs ?? DEFAULT_CLI_TIMEOUT_MS, options);
|
|
1219
|
-
|
|
1291
|
+
const version = signal.version === true
|
|
1292
|
+
? (parseHostVersion(String(r.stdout ?? '')) ?? parseHostVersion(String(r.stderr ?? '')))
|
|
1293
|
+
: null;
|
|
1294
|
+
return {
|
|
1295
|
+
kind: signal.kind,
|
|
1296
|
+
source,
|
|
1297
|
+
hit: r.ok === true,
|
|
1298
|
+
detail: version ? `版本:${version}` : `rc=${r.code}`,
|
|
1299
|
+
...(signal.version === true ? { version } : {}),
|
|
1300
|
+
};
|
|
1220
1301
|
}
|
|
1221
1302
|
if (signal.kind === 'process') {
|
|
1222
1303
|
const list = options.processList ?? (() => defaultProcessList(options));
|
|
@@ -1252,16 +1333,31 @@ export async function probeSignalAsync(signal, options = {}) {
|
|
|
1252
1333
|
// (本机 hermes --version ≈763ms),`refresh` 只重算**列表/落面**,不必重复 spawn 版本探测。
|
|
1253
1334
|
// 注:注入的 `run`/`runAsync`(测试)不缓存,保证替身语义确定。
|
|
1254
1335
|
const injected = options.runAsync !== undefined || options.run !== undefined;
|
|
1255
|
-
const cacheKey = `${signal.command}::${signal.timeoutMs ?? DEFAULT_CLI_TIMEOUT_MS}`;
|
|
1336
|
+
const cacheKey = `${signal.command}::${signal.timeoutMs ?? DEFAULT_CLI_TIMEOUT_MS}::${signal.version === true ? 'version' : 'plain'}`;
|
|
1256
1337
|
if (!injected && options.refreshProbes !== true) {
|
|
1257
1338
|
const cachedCli = cliProbeCache.get(cacheKey);
|
|
1258
1339
|
if (cachedCli && Date.now() - cachedCli.at < PROBE_CACHE_TTL_MS) {
|
|
1259
|
-
return {
|
|
1340
|
+
return {
|
|
1341
|
+
kind: signal.kind,
|
|
1342
|
+
source,
|
|
1343
|
+
hit: cachedCli.hit,
|
|
1344
|
+
detail: cachedCli.version ? `版本:${cachedCli.version}` : `rc=${cachedCli.code}`,
|
|
1345
|
+
...(signal.version === true ? { version: cachedCli.version ?? null } : {}),
|
|
1346
|
+
};
|
|
1260
1347
|
}
|
|
1261
1348
|
}
|
|
1262
1349
|
const r = await runAsync(signal.command, signal.timeoutMs ?? DEFAULT_CLI_TIMEOUT_MS, options);
|
|
1263
|
-
|
|
1264
|
-
|
|
1350
|
+
const version = signal.version === true
|
|
1351
|
+
? (parseHostVersion(String(r.stdout ?? '')) ?? parseHostVersion(String(r.stderr ?? '')))
|
|
1352
|
+
: null;
|
|
1353
|
+
if (!injected) cliProbeCache.set(cacheKey, { at: Date.now(), hit: r.ok === true, code: r.code, version });
|
|
1354
|
+
return {
|
|
1355
|
+
kind: signal.kind,
|
|
1356
|
+
source,
|
|
1357
|
+
hit: r.ok === true,
|
|
1358
|
+
detail: version ? `版本:${version}` : `rc=${r.code}`,
|
|
1359
|
+
...(signal.version === true ? { version } : {}),
|
|
1360
|
+
};
|
|
1265
1361
|
}
|
|
1266
1362
|
if (signal.kind === 'process') {
|
|
1267
1363
|
const out = String((await listAsync()) ?? '');
|
|
@@ -1310,7 +1406,16 @@ function buildStateItem(assistant, signals, landing, options = {}) {
|
|
|
1310
1406
|
else if (staleStdio) state = 'stale'; // 已写入但过时(stdio)→ 升级直连
|
|
1311
1407
|
else if (!anyHit) state = anyError ? 'detect-failed' : 'not-installed';
|
|
1312
1408
|
else state = 'not-connected';
|
|
1313
|
-
|
|
1409
|
+
// Host 兼容性门:只在原本会投影成绿色「已接入」时接管。
|
|
1410
|
+
// 版本已知且低于插件下限 → 自动记忆不可用;版本未知(超时/无输出/空版本)→ 无法确认。
|
|
1411
|
+
// stale / needs-confirmation 等更具体的可修复态保留原语义(它们本来也不是绿色)。
|
|
1412
|
+
const compatibility = evaluateHostCompatibility(assistant, signals);
|
|
1413
|
+
const compatibilityApplies = state === 'connected';
|
|
1414
|
+
const unsupported = compatibility?.supported === false && compatibilityApplies;
|
|
1415
|
+
const compatibilityUnknown = compatibility?.supported === null && compatibilityApplies;
|
|
1416
|
+
if (unsupported) state = 'unsupported';
|
|
1417
|
+
else if (compatibilityUnknown) state = 'compatibility-unknown';
|
|
1418
|
+
const STATE_LABEL = { 'not-installed': '未安装', 'not-connected': '未接入', connected: '已接入 ✓', manual: '需手动', 'detect-failed': '检测失败', stale: '已写入·需升级为直连', 'needs-confirmation': '需要修复/请确认', unsupported: '自动记忆不可用 · 需升级', 'compatibility-unknown': '无法确认兼容性 · 请重新检测' };
|
|
1314
1419
|
const staleReason = needsConfirmation || staleUrl ? (landing.staleReason ?? 'MCP 地址与当前端点不一致,请确认或手动修复') : null;
|
|
1315
1420
|
const nativeMemory = assistant.nativeMemoryProbe === 'openchamber'
|
|
1316
1421
|
? detectOpenChamberNativeMemory(options)
|
|
@@ -1336,7 +1441,23 @@ function buildStateItem(assistant, signals, landing, options = {}) {
|
|
|
1336
1441
|
type: assistant.kind === 'snippet' ? 'snippet' : 'file', // file | snippet(descriptor 形态)
|
|
1337
1442
|
registryKind: assistant.registryKind ?? 'builtin',
|
|
1338
1443
|
state,
|
|
1339
|
-
stateLabel: needsConfirmation
|
|
1444
|
+
stateLabel: needsConfirmation
|
|
1445
|
+
? '需要修复/请确认'
|
|
1446
|
+
: staleUrl
|
|
1447
|
+
? '配置已过期 · 请自动修复'
|
|
1448
|
+
: unsupported && compatibility?.hostVersion
|
|
1449
|
+
? `需升级(需要 >= ${compatibility.requiredVersion},当前 ${compatibility.hostVersion})`
|
|
1450
|
+
: compatibilityUnknown
|
|
1451
|
+
? `无法确认当前版本(需要 >= ${compatibility.requiredVersion})`
|
|
1452
|
+
: (STATE_LABEL[state] ?? state),
|
|
1453
|
+
...(compatibility
|
|
1454
|
+
? {
|
|
1455
|
+
compatibility,
|
|
1456
|
+
automaticMemory: compatibility.automaticMemory,
|
|
1457
|
+
requiredVersion: compatibility.requiredVersion,
|
|
1458
|
+
...(compatibility.actionHint ? { actionHint: compatibility.actionHint } : {}),
|
|
1459
|
+
}
|
|
1460
|
+
: {}),
|
|
1340
1461
|
evidence: signals.map((s) => ({ ...s, detail: redactSecrets(s.detail) })),
|
|
1341
1462
|
anySignalHit: anyHit,
|
|
1342
1463
|
landing: {
|
|
@@ -1180,6 +1180,11 @@ function clampOffset(value) {
|
|
|
1180
1180
|
return Math.max(n, 0);
|
|
1181
1181
|
}
|
|
1182
1182
|
|
|
1183
|
+
/** 可选 asOf:只接受有限数字;缺省/非法不写入请求(读路径回落当前时间)。 */
|
|
1184
|
+
function parseAsOf(value) {
|
|
1185
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1183
1188
|
function clampDepth(value) {
|
|
1184
1189
|
const n = typeof value === 'number' && Number.isFinite(value) ? Math.floor(value) : 2;
|
|
1185
1190
|
return Math.min(Math.max(n, 0), MAX_DEPTH);
|
|
@@ -1409,6 +1414,7 @@ function recordView(memory, node, { userId = 'user', withScore = false, detailAv
|
|
|
1409
1414
|
ownerType: owner.ownerType,
|
|
1410
1415
|
ownerId: owner.ownerId,
|
|
1411
1416
|
provenance: buildProvenance(metadata, domain, owner, node),
|
|
1417
|
+
...(isObject(memory?.provenance) ? { retrievalProvenance: memory.provenance } : {}),
|
|
1412
1418
|
content,
|
|
1413
1419
|
text,
|
|
1414
1420
|
tags,
|
|
@@ -4925,6 +4931,7 @@ export function createMemoryCapabilityHandler({
|
|
|
4925
4931
|
});
|
|
4926
4932
|
const limit = clampLimit(payload.limit);
|
|
4927
4933
|
const offset = clampOffset(payload.offset);
|
|
4934
|
+
const asOf = parseAsOf(payload.asOf);
|
|
4928
4935
|
const types = parseTypes(payload.types ?? undefined);
|
|
4929
4936
|
if (resolved.domains.length === 0) {
|
|
4930
4937
|
return sendOk({
|
|
@@ -4945,6 +4952,7 @@ export function createMemoryCapabilityHandler({
|
|
|
4945
4952
|
offset,
|
|
4946
4953
|
...(payload.includeHistory !== undefined ? { includeHistory: payload.includeHistory === true } : {}),
|
|
4947
4954
|
...(payload.includeArchived !== undefined ? { includeArchived: payload.includeArchived === true } : {}),
|
|
4955
|
+
...(asOf !== undefined ? { asOf } : {}),
|
|
4948
4956
|
filters: { ...(filters ?? {}), namespace: resolved.domains },
|
|
4949
4957
|
});
|
|
4950
4958
|
const cache = new Map();
|
|
@@ -4963,12 +4971,16 @@ export function createMemoryCapabilityHandler({
|
|
|
4963
4971
|
detailAvailability,
|
|
4964
4972
|
}));
|
|
4965
4973
|
const total = typeof result?.totalMatches === 'number' ? result.totalMatches : records.length;
|
|
4974
|
+
const truncated = result?.truncated === true;
|
|
4966
4975
|
return sendOk({
|
|
4967
4976
|
records,
|
|
4968
4977
|
total,
|
|
4969
4978
|
offset,
|
|
4970
4979
|
limit,
|
|
4980
|
+
// hasMore 只表示“当前分页是否还有下一页”;truncated 单独表达
|
|
4981
|
+
// “结果是否被图扩展预算截断”,避免空页也永远 hasMore=true。
|
|
4971
4982
|
hasMore: offset + records.length < total,
|
|
4983
|
+
...(truncated ? { truncated: true } : {}),
|
|
4972
4984
|
tookMs: typeof result?.queryTimeMs === 'number' ? result.queryTimeMs : 0,
|
|
4973
4985
|
usedDomains: resolved.domains,
|
|
4974
4986
|
}, resolved.warnings);
|
|
@@ -4997,6 +5009,7 @@ export function createMemoryCapabilityHandler({
|
|
|
4997
5009
|
service: currentService,
|
|
4998
5010
|
});
|
|
4999
5011
|
const limit = clampLimit(payload.limit);
|
|
5012
|
+
const asOf = parseAsOf(payload.asOf);
|
|
5000
5013
|
const types = parseTypes(payload.types ?? undefined);
|
|
5001
5014
|
if (resolved.domains.length === 0) {
|
|
5002
5015
|
return sendOk({ records: [], relations: [], total: 0, tookMs: 0 }, resolved.warnings);
|
|
@@ -5009,6 +5022,7 @@ export function createMemoryCapabilityHandler({
|
|
|
5009
5022
|
...(payload.includeHistory !== undefined ? { includeHistory: payload.includeHistory === true } : {}),
|
|
5010
5023
|
...(payload.includeRelations !== undefined ? { includeRelations: payload.includeRelations === true } : {}),
|
|
5011
5024
|
...(payload.includeArchived !== undefined ? { includeArchived: payload.includeArchived === true } : {}),
|
|
5025
|
+
...(asOf !== undefined ? { asOf } : {}),
|
|
5012
5026
|
filters: { ...(filters ?? {}), namespace: resolved.domains },
|
|
5013
5027
|
});
|
|
5014
5028
|
const cache = new Map();
|
|
@@ -5038,6 +5052,7 @@ export function createMemoryCapabilityHandler({
|
|
|
5038
5052
|
records,
|
|
5039
5053
|
relations,
|
|
5040
5054
|
total: records.length,
|
|
5055
|
+
...(result?.truncated === true ? { truncated: true } : {}),
|
|
5041
5056
|
tookMs: typeof result?.queryTimeMs === 'number' ? result.queryTimeMs : 0,
|
|
5042
5057
|
usedDomains: resolved.domains,
|
|
5043
5058
|
}, resolved.warnings);
|
|
@@ -479,8 +479,20 @@ function traceOutcomeView(outcome) {
|
|
|
479
479
|
};
|
|
480
480
|
}
|
|
481
481
|
|
|
482
|
+
/**
|
|
483
|
+
* 旧 trace:schema<2,或 0.3.2/0.3.5 等旧写入方没有 decision/applied。
|
|
484
|
+
* 这类记录不是“当前策略沉默”,调用方必须按“无策略信息”展示。
|
|
485
|
+
*/
|
|
486
|
+
function traceIsLegacy(trace, decision, applied) {
|
|
487
|
+
const schema = traceNumber(trace?.schema);
|
|
488
|
+
if (schema === null || schema < 2) return true;
|
|
489
|
+
return decision === null && applied === null;
|
|
490
|
+
}
|
|
491
|
+
|
|
482
492
|
function traceSummaryView(trace) {
|
|
483
493
|
const feedback = trace?.feedback;
|
|
494
|
+
const decision = traceDecisionView(trace?.decision);
|
|
495
|
+
const applied = traceAppliedView(trace?.applied);
|
|
484
496
|
return {
|
|
485
497
|
id: traceText(trace?.id, 160),
|
|
486
498
|
recallId: traceText(trace?.recallId, 160),
|
|
@@ -504,8 +516,9 @@ function traceSummaryView(trace) {
|
|
|
504
516
|
injected: traceNumber(trace?.counts?.injected),
|
|
505
517
|
tokens: traceNumber(trace?.counts?.tokens),
|
|
506
518
|
},
|
|
507
|
-
|
|
508
|
-
|
|
519
|
+
legacy: traceIsLegacy(trace, decision, applied),
|
|
520
|
+
decision,
|
|
521
|
+
applied,
|
|
509
522
|
outcome: traceOutcomeView(trace?.outcome),
|
|
510
523
|
timing: { totalMs: traceNumber(trace?.timing?.totalMs) },
|
|
511
524
|
model: {
|
package/src/serve.mjs
CHANGED
|
@@ -216,13 +216,15 @@ import { renderSvgQr } from './qr.mjs';
|
|
|
216
216
|
import { clearRuntimeFile, writeRuntimeFile } from './runtime-file.mjs';
|
|
217
217
|
|
|
218
218
|
// R1.3:记忆面 memory.* + 任务面 task.*(两轴独立;同一轴内 write ⇒ read、admin ⇒ 其余)
|
|
219
|
-
const SCOPES = ['memory.read', 'memory.write', 'memory.admin', 'task.read', 'task.write'];
|
|
219
|
+
const SCOPES = ['memory.read', 'memory.write', 'memory.admin', 'task.read', 'task.write', 'mobile.access'];
|
|
220
220
|
const SCOPE_IMPLIES = {
|
|
221
221
|
'memory.read': ['memory.read'],
|
|
222
222
|
'memory.write': ['memory.read', 'memory.write'],
|
|
223
223
|
'memory.admin': ['memory.read', 'memory.write', 'memory.admin'],
|
|
224
224
|
'task.read': ['task.read'],
|
|
225
225
|
'task.write': ['task.read', 'task.write'],
|
|
226
|
+
// MAS 专用:不蕴含 memory.*/task.*;也不被 memory.admin 蕴含(必须显式签发)。
|
|
227
|
+
'mobile.access': ['mobile.access'],
|
|
226
228
|
};
|
|
227
229
|
const DEFAULT_SCOPES = ['memory.read'];
|
|
228
230
|
const ACCESS_TTL = 900; // 15min
|
|
@@ -274,6 +276,8 @@ const CONSOLE_FILES = {
|
|
|
274
276
|
'assistant-status.js': 'text/javascript; charset=utf-8',
|
|
275
277
|
'deep-link.js': 'text/javascript; charset=utf-8',
|
|
276
278
|
'settings-ia.js': 'text/javascript; charset=utf-8',
|
|
279
|
+
'mobile.js': 'text/javascript; charset=utf-8',
|
|
280
|
+
'qrcode.js': 'text/javascript; charset=utf-8',
|
|
277
281
|
'i18n.mjs': 'text/javascript; charset=utf-8',
|
|
278
282
|
'starfield.js': 'text/javascript; charset=utf-8',
|
|
279
283
|
'wizard.js': 'text/javascript; charset=utf-8',
|
|
@@ -890,6 +894,48 @@ function hasScope(granted, required) {
|
|
|
890
894
|
* 启动 HTTP MCP server。
|
|
891
895
|
* @returns {Promise<{ server: import('node:http').Server, host: string, port: number, auth: string, close: () => Promise<void> }>}
|
|
892
896
|
*/
|
|
897
|
+
const MOBILE_PAIRING_CONTEXT_FILES = ['mobile-access/context.json', 'mobile-access/mas.json'];
|
|
898
|
+
|
|
899
|
+
function containsPrivatePairingKey(value) {
|
|
900
|
+
if (value === null || typeof value !== 'object') return false;
|
|
901
|
+
if (Array.isArray(value)) return value.some((entry) => containsPrivatePairingKey(entry));
|
|
902
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
903
|
+
if (/private|password|passphrase|seed/i.test(key)) return true;
|
|
904
|
+
if (containsPrivatePairingKey(entry)) return true;
|
|
905
|
+
}
|
|
906
|
+
return false;
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/** Read the public MAS/network context used to sign a pairing payload. Fail closed. */
|
|
910
|
+
async function readControllerPairingContext(home) {
|
|
911
|
+
if (typeof home !== 'string' || home.length === 0) return null;
|
|
912
|
+
for (const relative of MOBILE_PAIRING_CONTEXT_FILES) {
|
|
913
|
+
try {
|
|
914
|
+
const raw = JSON.parse(await readFile(join(home, relative), 'utf-8'));
|
|
915
|
+
const record = raw?.context && typeof raw.context === 'object' ? raw.context : raw;
|
|
916
|
+
const network = record?.network;
|
|
917
|
+
const mas = record?.mas;
|
|
918
|
+
if (!network || typeof network !== 'object' || !mas || typeof mas !== 'object') continue;
|
|
919
|
+
if (containsPrivatePairingKey(record)) continue;
|
|
920
|
+
return {
|
|
921
|
+
network,
|
|
922
|
+
mas,
|
|
923
|
+
...(Array.isArray(record.additionalMas) ? { additionalMas: record.additionalMas } : {}),
|
|
924
|
+
};
|
|
925
|
+
} catch {
|
|
926
|
+
// Try the next candidate; a corrupt file never becomes a fake context.
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
return null;
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
function rootIssuerDeviceId(grant) {
|
|
933
|
+
const chain = grant?.issuer?.certificateChain;
|
|
934
|
+
if (!Array.isArray(chain) || chain.length === 0) return undefined;
|
|
935
|
+
const root = chain[chain.length - 1];
|
|
936
|
+
return root !== null && typeof root === 'object' && typeof root.deviceId === 'string' ? root.deviceId : undefined;
|
|
937
|
+
}
|
|
938
|
+
|
|
893
939
|
export async function startHttpServer({
|
|
894
940
|
home,
|
|
895
941
|
app: initialApp = null,
|
|
@@ -1897,6 +1943,8 @@ export async function startHttpServer({
|
|
|
1897
1943
|
recovery: { registered: false },
|
|
1898
1944
|
pendingApprovals: [],
|
|
1899
1945
|
recentApprovals: [],
|
|
1946
|
+
controllerGrants: [],
|
|
1947
|
+
controllerRevokes: [],
|
|
1900
1948
|
});
|
|
1901
1949
|
}
|
|
1902
1950
|
const state = await lib.readSecurityState(app);
|
|
@@ -1922,6 +1970,9 @@ export async function startHttpServer({
|
|
|
1922
1970
|
},
|
|
1923
1971
|
pendingApprovals: lib.pendingApprovals(events),
|
|
1924
1972
|
recentApprovals: lib.approvalsFromEvents(events).slice(-50),
|
|
1973
|
+
// MAS 撤销校验读路径:controller_revoke 是权威;grant 记录给配对/诊断用。
|
|
1974
|
+
controllerGrants: lib.controllerGrantsFromEvents(events),
|
|
1975
|
+
controllerRevokes: lib.controllerRevokesFromEvents(events),
|
|
1925
1976
|
});
|
|
1926
1977
|
}
|
|
1927
1978
|
|
|
@@ -2219,6 +2270,8 @@ export async function startHttpServer({
|
|
|
2219
2270
|
/^\/admin\/api\/security\/approvals\/([^/]+)\/(approve|deny)$/,
|
|
2220
2271
|
/^\/admin\/api\/security\/totp\/(show|import)$/,
|
|
2221
2272
|
/^\/admin\/api\/security\/recovery\/(generate|rotate)$/,
|
|
2273
|
+
// Mobile v1:控制器 pairing session / grant / revoke / access(scope mobile.access;grant 绑定 session+secret)。
|
|
2274
|
+
/^\/admin\/api\/controllers\/(pairing|grant|revoke|mobile-access)$/,
|
|
2222
2275
|
/^\/admin\/api\/namespaces\/([^/]+)\/(rejoin|leave)$/,
|
|
2223
2276
|
/^\/admin\/api\/service\/(install|uninstall)$/,
|
|
2224
2277
|
/^\/admin\/api\/repair$/,
|
|
@@ -2899,6 +2952,442 @@ export async function startHttpServer({
|
|
|
2899
2952
|
return sendJson(res, result.status, result.body);
|
|
2900
2953
|
}
|
|
2901
2954
|
|
|
2955
|
+
// Mobile v1:控制器端点只接受 mobile.access(MAS 无 memory.admin);grant 必须
|
|
2956
|
+
// 绑定 pairing session/secret + 手机 controllerProof,不是通用签名 oracle。
|
|
2957
|
+
const controllerAction = path.match(/^\/admin\/api\/controllers\/(pairing|grant|mobile-access|revoke)$/);
|
|
2958
|
+
if (controllerAction) {
|
|
2959
|
+
const lib = await loadFleetSecurity();
|
|
2960
|
+
if (!lib || typeof lib.issueControllerGrant !== 'function') {
|
|
2961
|
+
return sendJson(res, 503, { ok: false, error: 'security_unavailable', message: '控制器授权模块不可用(@mebular/fleet 未构建)' });
|
|
2962
|
+
}
|
|
2963
|
+
const input = parseJsonBody(body);
|
|
2964
|
+
if (!input) return sendJson(res, 400, { ok: false, error: 'bad_request', message: '需要 JSON 请求体' });
|
|
2965
|
+
const action = controllerAction[1];
|
|
2966
|
+
|
|
2967
|
+
if (action === 'pairing') {
|
|
2968
|
+
const masterPublicKey = app.identity?.getUserMasterPublicKey?.();
|
|
2969
|
+
if (!(masterPublicKey instanceof Uint8Array) || masterPublicKey.length !== 32) {
|
|
2970
|
+
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机用户主公钥不可用,无法创建配对会话' });
|
|
2971
|
+
}
|
|
2972
|
+
const networkId = createHash('sha256').update(masterPublicKey).digest('hex');
|
|
2973
|
+
const requestedNetworkId = typeof input.networkId === 'string' ? input.networkId.trim().toLowerCase() : '';
|
|
2974
|
+
if (requestedNetworkId.length > 0 && requestedNetworkId !== networkId) {
|
|
2975
|
+
return sendJson(res, 400, { ok: false, error: 'bad_request', message: 'networkId 与本机网络不一致' });
|
|
2976
|
+
}
|
|
2977
|
+
const localDeviceId = typeof app.deviceId === 'string' && app.deviceId.length > 0 ? app.deviceId : deviceId;
|
|
2978
|
+
const identity = localDeviceId ? app.identity?.getDeviceKey?.(localDeviceId) : undefined;
|
|
2979
|
+
if (!identity || identity.privateKey === undefined) {
|
|
2980
|
+
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机设备身份不可用,无法签名配对载荷' });
|
|
2981
|
+
}
|
|
2982
|
+
const chain = Array.isArray(identity.certificateChain) && identity.certificateChain.length > 0
|
|
2983
|
+
? identity.certificateChain
|
|
2984
|
+
: identity.certificate !== undefined ? [identity.certificate] : [];
|
|
2985
|
+
if (chain.length === 0 || chain[0]?.deviceId !== localDeviceId) {
|
|
2986
|
+
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机设备证书链不可用,无法签名配对载荷' });
|
|
2987
|
+
}
|
|
2988
|
+
const masterPublicKeyB64 = b64url(masterPublicKey);
|
|
2989
|
+
if (!(await lib.verifyControllerIssuerChain(chain, masterPublicKeyB64, localDeviceId))) {
|
|
2990
|
+
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机设备证书链无效,无法签名配对载荷' });
|
|
2991
|
+
}
|
|
2992
|
+
const context = input.context !== null && typeof input.context === 'object'
|
|
2993
|
+
? input.context
|
|
2994
|
+
: await readControllerPairingContext(home);
|
|
2995
|
+
if (context === null || context.mas === null || typeof context.mas !== 'object') {
|
|
2996
|
+
return sendJson(res, 409, {
|
|
2997
|
+
ok: false,
|
|
2998
|
+
error: 'PAIRING_CONTEXT_INCOMPLETE',
|
|
2999
|
+
message: '缺少 MAS 公共上下文(<home>/mobile-access/context.json 或 mas.json),不生成未签名二维码',
|
|
3000
|
+
});
|
|
3001
|
+
}
|
|
3002
|
+
const contextMasId = typeof context.mas.id === 'string' ? context.mas.id.trim().toLowerCase() : '';
|
|
3003
|
+
const requestedMasId = typeof input.masId === 'string' ? input.masId.trim().toLowerCase() : '';
|
|
3004
|
+
if (requestedMasId.length > 0 && requestedMasId !== contextMasId) {
|
|
3005
|
+
return sendJson(res, 400, { ok: false, error: 'bad_request', message: 'masId 与 MAS 公共上下文不一致' });
|
|
3006
|
+
}
|
|
3007
|
+
if (requestedMasId.length > 0 && !/^[0-9a-f]{64}$/i.test(requestedMasId)) {
|
|
3008
|
+
return sendJson(res, 400, { ok: false, error: 'bad_request', message: 'masId 必须是 64 位 hex(sha256(MAS signPublicKey))' });
|
|
3009
|
+
}
|
|
3010
|
+
let networkName = 'Mebular';
|
|
3011
|
+
try {
|
|
3012
|
+
const cloudName = typeof app.getCloudName === 'function' ? await app.getCloudName() : null;
|
|
3013
|
+
if (cloudName !== null && typeof cloudName?.name === 'string' && cloudName.name.trim().length > 0) {
|
|
3014
|
+
networkName = cloudName.name;
|
|
3015
|
+
}
|
|
3016
|
+
} catch {
|
|
3017
|
+
return sendJson(res, 409, { ok: false, error: 'cloud_name_unavailable', message: '忆云名称暂不可用,无法签名配对载荷' });
|
|
3018
|
+
}
|
|
3019
|
+
try {
|
|
3020
|
+
const pairingIssuedAt = Date.now();
|
|
3021
|
+
const session = await lib.createControllerPairingSession(home, {
|
|
3022
|
+
networkId,
|
|
3023
|
+
now: pairingIssuedAt,
|
|
3024
|
+
...(contextMasId.length > 0 ? { masId: contextMasId } : {}),
|
|
3025
|
+
...(Number.isSafeInteger(input.ttlMs) && input.ttlMs > 0 ? { ttlMs: input.ttlMs } : {}),
|
|
3026
|
+
});
|
|
3027
|
+
const payload = await lib.signControllerPairingPayload({
|
|
3028
|
+
network: {
|
|
3029
|
+
id: networkId,
|
|
3030
|
+
name: networkName,
|
|
3031
|
+
masterPublicKey: masterPublicKeyB64,
|
|
3032
|
+
fingerprint: lib.controllerNetworkFingerprint(networkId),
|
|
3033
|
+
},
|
|
3034
|
+
mas: context.mas,
|
|
3035
|
+
...(Array.isArray(context.additionalMas) ? { additionalMas: context.additionalMas } : {}),
|
|
3036
|
+
session: { id: session.sessionId, secret: session.secret, expiresAt: session.expiresAt },
|
|
3037
|
+
issuedAt: pairingIssuedAt,
|
|
3038
|
+
issuer: { deviceId: localDeviceId, privateKey: identity.privateKey, certificateChain: chain },
|
|
3039
|
+
});
|
|
3040
|
+
return sendJson(res, 201, { ok: true, ...session, payload });
|
|
3041
|
+
} catch (error) {
|
|
3042
|
+
return sendJson(res, 400, {
|
|
3043
|
+
ok: false,
|
|
3044
|
+
error: 'PAIRING_CONTEXT_INVALID',
|
|
3045
|
+
message: String(error?.message ?? error),
|
|
3046
|
+
});
|
|
3047
|
+
}
|
|
3048
|
+
}
|
|
3049
|
+
|
|
3050
|
+
if (action === 'grant') {
|
|
3051
|
+
const sessionId = typeof input.sessionId === 'string' ? input.sessionId : '';
|
|
3052
|
+
const secret = typeof input.secret === 'string' ? input.secret : '';
|
|
3053
|
+
const controller = input.controller !== null && typeof input.controller === 'object' ? input.controller : null;
|
|
3054
|
+
const networkId = typeof input.networkId === 'string' ? input.networkId.trim().toLowerCase() : '';
|
|
3055
|
+
const masId = typeof input.masId === 'string' ? input.masId.trim() : '';
|
|
3056
|
+
const controllerProof = input.controllerProof !== null && typeof input.controllerProof === 'object'
|
|
3057
|
+
? input.controllerProof
|
|
3058
|
+
: null;
|
|
3059
|
+
if (sessionId.length === 0 || secret.length === 0 || controller === null
|
|
3060
|
+
|| networkId.length === 0 || masId.length === 0 || controllerProof === null) {
|
|
3061
|
+
return sendJson(res, 400, {
|
|
3062
|
+
ok: false,
|
|
3063
|
+
error: 'bad_request',
|
|
3064
|
+
message: '需要 sessionId、secret、networkId、masId、controller 与 controllerProof',
|
|
3065
|
+
});
|
|
3066
|
+
}
|
|
3067
|
+
if (typeof controller.id !== 'string'
|
|
3068
|
+
|| typeof controller.signPublicKey !== 'string'
|
|
3069
|
+
|| typeof controller.encPublicKey !== 'string'
|
|
3070
|
+
|| (controller.platform !== 'ios' && controller.platform !== 'android')
|
|
3071
|
+
|| typeof controller.name !== 'string'
|
|
3072
|
+
|| controller.name.trim().length === 0
|
|
3073
|
+
|| typeof controller.appVersion !== 'string'
|
|
3074
|
+
|| controller.appVersion.trim().length === 0
|
|
3075
|
+
|| controller.protocolVersion !== 1
|
|
3076
|
+
|| controllerProof.sigAlg !== 'P256-SHA256'
|
|
3077
|
+
|| typeof controllerProof.signature !== 'string') {
|
|
3078
|
+
return sendJson(res, 400, {
|
|
3079
|
+
ok: false,
|
|
3080
|
+
error: 'bad_request',
|
|
3081
|
+
message: 'controller 需要 id、signPublicKey、encPublicKey、platform、name、appVersion、protocolVersion=1;controllerProof 需要 P256-SHA256 签名',
|
|
3082
|
+
});
|
|
3083
|
+
}
|
|
3084
|
+
try {
|
|
3085
|
+
lib.decodeP256PublicKey(controller.signPublicKey);
|
|
3086
|
+
lib.decodeP256PublicKey(controller.encPublicKey);
|
|
3087
|
+
} catch {
|
|
3088
|
+
return sendJson(res, 400, {
|
|
3089
|
+
ok: false,
|
|
3090
|
+
error: 'bad_request',
|
|
3091
|
+
message: 'controller 公钥必须是 65 字节未压缩 P-256 公钥(首字节 0x04)',
|
|
3092
|
+
});
|
|
3093
|
+
}
|
|
3094
|
+
|
|
3095
|
+
// 预检本机身份/证书链/网络名:可预见的本地不可用不能消费一次性 session。
|
|
3096
|
+
const localDeviceId = typeof app.deviceId === 'string' && app.deviceId.length > 0 ? app.deviceId : deviceId;
|
|
3097
|
+
const identity = localDeviceId ? app.identity?.getDeviceKey?.(localDeviceId) : undefined;
|
|
3098
|
+
const masterPublicKey = app.identity?.getUserMasterPublicKey?.();
|
|
3099
|
+
if (!identity || identity.privateKey === undefined
|
|
3100
|
+
|| !(masterPublicKey instanceof Uint8Array) || masterPublicKey.length !== 32) {
|
|
3101
|
+
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机设备身份或用户主公钥不可用,无法签发控制器授权' });
|
|
3102
|
+
}
|
|
3103
|
+
const chain = Array.isArray(identity.certificateChain) && identity.certificateChain.length > 0
|
|
3104
|
+
? identity.certificateChain
|
|
3105
|
+
: identity.certificate !== undefined ? [identity.certificate] : [];
|
|
3106
|
+
if (chain.length === 0 || chain[0]?.deviceId !== localDeviceId) {
|
|
3107
|
+
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机设备证书链不可用,无法签发控制器授权' });
|
|
3108
|
+
}
|
|
3109
|
+
const masterPublicKeyB64 = b64url(masterPublicKey);
|
|
3110
|
+
if (!(await lib.verifyControllerIssuerChain(chain, masterPublicKeyB64, localDeviceId))) {
|
|
3111
|
+
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机设备证书链无效,无法签发控制器授权' });
|
|
3112
|
+
}
|
|
3113
|
+
let networkName = 'Mebular';
|
|
3114
|
+
try {
|
|
3115
|
+
const cloudName = typeof app.getCloudName === 'function' ? await app.getCloudName() : null;
|
|
3116
|
+
if (cloudName !== null && typeof cloudName?.name === 'string' && cloudName.name.trim().length > 0) {
|
|
3117
|
+
networkName = cloudName.name;
|
|
3118
|
+
}
|
|
3119
|
+
} catch {
|
|
3120
|
+
return sendJson(res, 409, { ok: false, error: 'cloud_name_unavailable', message: '忆云名称暂不可用,无法签发控制器授权' });
|
|
3121
|
+
}
|
|
3122
|
+
|
|
3123
|
+
// C-02:手机必须证明自己持有 controller sign key,且 transcript 绑定 session/network/MAS。
|
|
3124
|
+
const networkIdFromMaster = createHash('sha256').update(masterPublicKey).digest('hex');
|
|
3125
|
+
if (networkId !== networkIdFromMaster) {
|
|
3126
|
+
return sendJson(res, 403, { ok: false, error: 'AUTH_INVALID', message: 'networkId 与本机网络不一致' });
|
|
3127
|
+
}
|
|
3128
|
+
const sessions = await lib.readControllerPairingSessions(home);
|
|
3129
|
+
const pending = sessions.find((session) => session.sessionId === sessionId);
|
|
3130
|
+
if (pending === undefined) {
|
|
3131
|
+
return sendJson(res, 410, { ok: false, error: 'PAIRING_EXPIRED', message: '配对会话已过期或不存在:请重新生成配对二维码' });
|
|
3132
|
+
}
|
|
3133
|
+
if (pending.consumedAt !== undefined) {
|
|
3134
|
+
return sendJson(res, 409, { ok: false, error: 'PAIRING_CONSUMED', message: '配对会话已使用(一次性):请重新生成配对二维码' });
|
|
3135
|
+
}
|
|
3136
|
+
if (pending.networkId !== undefined && pending.networkId !== networkId) {
|
|
3137
|
+
return sendJson(res, 403, { ok: false, error: 'AUTH_INVALID', message: 'controllerProof 的 networkId 与配对会话不一致' });
|
|
3138
|
+
}
|
|
3139
|
+
if (pending.masId !== undefined && pending.masId !== masId) {
|
|
3140
|
+
return sendJson(res, 403, { ok: false, error: 'AUTH_INVALID', message: 'controllerProof 的 masId 与配对会话不一致' });
|
|
3141
|
+
}
|
|
3142
|
+
const proof = await lib.verifyControllerPairRequestProof(
|
|
3143
|
+
{ sessionId, networkId, masId, controller, controllerProof },
|
|
3144
|
+
{
|
|
3145
|
+
expectedSessionId: sessionId,
|
|
3146
|
+
expectedNetworkId: networkId,
|
|
3147
|
+
...(pending.masId !== undefined ? { expectedMasId: pending.masId } : {}),
|
|
3148
|
+
},
|
|
3149
|
+
);
|
|
3150
|
+
if (!proof.ok) {
|
|
3151
|
+
return sendJson(res, 403, {
|
|
3152
|
+
ok: false,
|
|
3153
|
+
error: 'AUTH_INVALID',
|
|
3154
|
+
message: `controllerProof 校验失败(${proof.reason})`,
|
|
3155
|
+
});
|
|
3156
|
+
}
|
|
3157
|
+
|
|
3158
|
+
// 预检全部通过后才原子消费 session:并发/重放无法换到第二张 grant。
|
|
3159
|
+
const consumed = await lib.consumeControllerPairingSession(home, { sessionId, secret });
|
|
3160
|
+
if (!consumed.ok) {
|
|
3161
|
+
const status = consumed.reason === 'PAIRING_CONSUMED'
|
|
3162
|
+
? 409
|
|
3163
|
+
: consumed.reason === 'PAIRING_SECRET_INVALID' ? 403 : 410;
|
|
3164
|
+
return sendJson(res, status, {
|
|
3165
|
+
ok: false,
|
|
3166
|
+
error: consumed.reason,
|
|
3167
|
+
message: consumed.reason === 'PAIRING_CONSUMED'
|
|
3168
|
+
? '配对会话已使用(一次性):请重新生成配对二维码'
|
|
3169
|
+
: consumed.reason === 'PAIRING_SECRET_INVALID'
|
|
3170
|
+
? '配对密钥无效'
|
|
3171
|
+
: '配对会话已过期或不存在:请重新生成配对二维码',
|
|
3172
|
+
});
|
|
3173
|
+
}
|
|
3174
|
+
|
|
3175
|
+
try {
|
|
3176
|
+
const grant = await lib.issueControllerGrant({
|
|
3177
|
+
issuer: { deviceId: localDeviceId, privateKey: identity.privateKey, certificateChain: chain },
|
|
3178
|
+
masterPublicKey: masterPublicKeyB64,
|
|
3179
|
+
networkName,
|
|
3180
|
+
subject: {
|
|
3181
|
+
signPublicKey: controller.signPublicKey,
|
|
3182
|
+
encPublicKey: controller.encPublicKey,
|
|
3183
|
+
platform: controller.platform,
|
|
3184
|
+
name: controller.name,
|
|
3185
|
+
},
|
|
3186
|
+
...(Array.isArray(input.scope) ? { scope: input.scope } : {}),
|
|
3187
|
+
...(typeof input.maxSecurityTier === 'string' ? { maxSecurityTier: input.maxSecurityTier } : {}),
|
|
3188
|
+
...(Number.isSafeInteger(input.ttlMs) && input.ttlMs > 0 ? { ttlMs: input.ttlMs } : {}),
|
|
3189
|
+
});
|
|
3190
|
+
const event = await lib.appendControllerGrantRecord(app, grant);
|
|
3191
|
+
return sendJson(res, 201, { ok: true, sessionId, networkId, masId, grant, eventId: event.id });
|
|
3192
|
+
} catch (error) {
|
|
3193
|
+
return sendJson(res, 400, { ok: false, error: 'grant_failed', message: String(error?.message ?? error) });
|
|
3194
|
+
}
|
|
3195
|
+
}
|
|
3196
|
+
|
|
3197
|
+
if (action === 'mobile-access') {
|
|
3198
|
+
// MAS 专用:验证手机 ControllerGrant + AccessRequest + AccessApproval 后,
|
|
3199
|
+
// 由 daemon 内部完成 high-tier security_approval、invite 与本地 join。
|
|
3200
|
+
const grant = input.grant ?? input.controllerGrant;
|
|
3201
|
+
const request = input.request ?? input.accessRequest;
|
|
3202
|
+
const approval = input.approval ?? input.accessApproval;
|
|
3203
|
+
const ns = typeof input.namespace === 'string' && input.namespace.length > 0 ? input.namespace : namespace;
|
|
3204
|
+
const tier = typeof input.tier === 'string' ? input.tier : '';
|
|
3205
|
+
if (grant === null || typeof grant !== 'object'
|
|
3206
|
+
|| request === null || typeof request !== 'object'
|
|
3207
|
+
|| approval === null || typeof approval !== 'object'
|
|
3208
|
+
|| (tier !== 'low' && tier !== 'medium' && tier !== 'high')) {
|
|
3209
|
+
return sendJson(res, 400, {
|
|
3210
|
+
ok: false,
|
|
3211
|
+
error: 'bad_request',
|
|
3212
|
+
message: '需要 grant、request、approval、namespace 与 tier=low|medium|high',
|
|
3213
|
+
});
|
|
3214
|
+
}
|
|
3215
|
+
if (approval.tier !== tier) {
|
|
3216
|
+
return sendJson(res, 400, { ok: false, error: 'bad_request', message: 'tier 与 AccessApproval.tier 不一致' });
|
|
3217
|
+
}
|
|
3218
|
+
const localDeviceId = typeof app.deviceId === 'string' && app.deviceId.length > 0 ? app.deviceId : deviceId;
|
|
3219
|
+
const identity = localDeviceId ? app.identity?.getDeviceKey?.(localDeviceId) : undefined;
|
|
3220
|
+
const masterPublicKey = app.identity?.getUserMasterPublicKey?.();
|
|
3221
|
+
if (!identity || identity.privateKey === undefined
|
|
3222
|
+
|| !(masterPublicKey instanceof Uint8Array) || masterPublicKey.length !== 32) {
|
|
3223
|
+
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机设备身份或用户主公钥不可用,无法处理手机接入' });
|
|
3224
|
+
}
|
|
3225
|
+
const chain = Array.isArray(identity.certificateChain) && identity.certificateChain.length > 0
|
|
3226
|
+
? identity.certificateChain
|
|
3227
|
+
: identity.certificate !== undefined ? [identity.certificate] : [];
|
|
3228
|
+
if (chain.length === 0 || chain[0]?.deviceId !== localDeviceId) {
|
|
3229
|
+
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机设备证书链不可用,无法处理手机接入' });
|
|
3230
|
+
}
|
|
3231
|
+
const masterPublicKeyB64 = b64url(masterPublicKey);
|
|
3232
|
+
if (!(await lib.verifyControllerIssuerChain(chain, masterPublicKeyB64, localDeviceId))) {
|
|
3233
|
+
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机设备证书链无效,无法处理手机接入' });
|
|
3234
|
+
}
|
|
3235
|
+
const events = await lib.listPolicyEvents(app);
|
|
3236
|
+
const revocation = lib.controllerRevocationSets(lib.controllerRevokesFromEvents(events));
|
|
3237
|
+
const revokedIssuerDeviceIds = lib.controllerRevokedIssuerDeviceIds(events);
|
|
3238
|
+
const rootIssuer = rootIssuerDeviceId(grant);
|
|
3239
|
+
const state = await lib.readSecurityState(app);
|
|
3240
|
+
const relayAllowlist = Array.isArray(config?.mobileAccess?.relayAllowlist)
|
|
3241
|
+
? config.mobileAccess.relayAllowlist.filter((entry) => typeof entry === 'string')
|
|
3242
|
+
: undefined;
|
|
3243
|
+
const checked = await lib.verifyControllerAccessApproval(grant, request, approval, {
|
|
3244
|
+
masterPublicKey: masterPublicKeyB64,
|
|
3245
|
+
expectedNamespace: ns,
|
|
3246
|
+
revokedGrantIds: revocation.grantIds,
|
|
3247
|
+
revokedSubjects: revocation.subjects,
|
|
3248
|
+
revokedIssuerDeviceIds,
|
|
3249
|
+
// Empty admitted is fail closed: only the network root issuer is trusted
|
|
3250
|
+
// until the policy names admitted devices.
|
|
3251
|
+
isIssuerAdmitted: (issuer) => state.admitted.length > 0
|
|
3252
|
+
? state.admitted.includes(issuer)
|
|
3253
|
+
: issuer === rootIssuer,
|
|
3254
|
+
...(relayAllowlist !== undefined ? { relayAllowlist } : {}),
|
|
3255
|
+
});
|
|
3256
|
+
if (!checked.ok) {
|
|
3257
|
+
return sendJson(res, 403, {
|
|
3258
|
+
ok: false,
|
|
3259
|
+
error: 'mobile_access_denied',
|
|
3260
|
+
message: `手机接入校验失败(${checked.reason})`,
|
|
3261
|
+
});
|
|
3262
|
+
}
|
|
3263
|
+
|
|
3264
|
+
const mobile = {
|
|
3265
|
+
v: 1,
|
|
3266
|
+
grantId: grant.grantId,
|
|
3267
|
+
controllerId: grant.subject.id,
|
|
3268
|
+
requestHash: checked.requestHash,
|
|
3269
|
+
requestId: request.requestId,
|
|
3270
|
+
deviceId: request.device.id,
|
|
3271
|
+
devicePublicKey: request.device.publicKey,
|
|
3272
|
+
tier: approval.tier,
|
|
3273
|
+
namespace: approval.namespace,
|
|
3274
|
+
approvalNonce: approval.nonce,
|
|
3275
|
+
approvalTs: approval.ts,
|
|
3276
|
+
approvalSignature: approval.signature,
|
|
3277
|
+
digest: checked.mobileDigest,
|
|
3278
|
+
};
|
|
3279
|
+
let securityApproval;
|
|
3280
|
+
if (tier === 'high') {
|
|
3281
|
+
const approvalId = randomUUID();
|
|
3282
|
+
const nonce = lib.controllerMobileApprovalNonce(checked.mobileDigest);
|
|
3283
|
+
const digest = lib.securityActionDigest({
|
|
3284
|
+
op: 'join',
|
|
3285
|
+
initiator: request.device.id,
|
|
3286
|
+
namespace: ns,
|
|
3287
|
+
nonce,
|
|
3288
|
+
});
|
|
3289
|
+
const baseRecord = {
|
|
3290
|
+
approvalId,
|
|
3291
|
+
op: 'join',
|
|
3292
|
+
initiator: request.device.id,
|
|
3293
|
+
namespace: ns,
|
|
3294
|
+
nonce,
|
|
3295
|
+
digest,
|
|
3296
|
+
pairingCode: lib.pairingCodeForDigest(digest),
|
|
3297
|
+
expiresAt: Date.now() + 10 * 60_000,
|
|
3298
|
+
mobile,
|
|
3299
|
+
};
|
|
3300
|
+
await lib.writeSecurityApproval(app, { ...baseRecord, decision: 'request', issuedAt: Date.now() });
|
|
3301
|
+
const cosign = await lib.signCosignProof({
|
|
3302
|
+
privateKey: identity.privateKey,
|
|
3303
|
+
approver: localDeviceId,
|
|
3304
|
+
approverCertificateChain: chain,
|
|
3305
|
+
approvalId,
|
|
3306
|
+
op: 'join',
|
|
3307
|
+
digest,
|
|
3308
|
+
pairingCode: baseRecord.pairingCode,
|
|
3309
|
+
});
|
|
3310
|
+
await lib.writeSecurityApproval(app, {
|
|
3311
|
+
...baseRecord,
|
|
3312
|
+
decision: 'approve',
|
|
3313
|
+
cosign,
|
|
3314
|
+
issuedAt: Date.now(),
|
|
3315
|
+
});
|
|
3316
|
+
securityApproval = { approvalId, nonce, initiator: request.device.id, cosign };
|
|
3317
|
+
}
|
|
3318
|
+
|
|
3319
|
+
if (typeof localDeviceId !== 'string' || typeof joinEndpoint !== 'string') {
|
|
3320
|
+
return sendJson(res, 409, {
|
|
3321
|
+
ok: false,
|
|
3322
|
+
error: 'join_disabled',
|
|
3323
|
+
message: '未启用加入服务:在「设置 → 常用配置」开启 joinService.enabled 并重启 serve',
|
|
3324
|
+
});
|
|
3325
|
+
}
|
|
3326
|
+
try {
|
|
3327
|
+
const token = await buildJoinToken({
|
|
3328
|
+
mebular: app,
|
|
3329
|
+
deviceId: localDeviceId,
|
|
3330
|
+
namespace: ns,
|
|
3331
|
+
endpoint: joinEndpoint,
|
|
3332
|
+
ttlMs: 900_000,
|
|
3333
|
+
...collectInviteHints(app, config),
|
|
3334
|
+
...(securityApproval !== undefined ? { securityApproval } : {}),
|
|
3335
|
+
});
|
|
3336
|
+
await activateJoinInvite(joinStateStoragePath, token.nonce);
|
|
3337
|
+
const inline = Buffer.from(JSON.stringify(token), 'utf-8').toString('base64');
|
|
3338
|
+
const issued = await lib.requestJoin({
|
|
3339
|
+
endpoint: joinEndpoint,
|
|
3340
|
+
token: inline,
|
|
3341
|
+
deviceId: request.device.id,
|
|
3342
|
+
devicePublicKeyHex: request.device.publicKey,
|
|
3343
|
+
});
|
|
3344
|
+
return sendJson(res, 201, {
|
|
3345
|
+
ok: true,
|
|
3346
|
+
namespace: issued.namespace ?? ns,
|
|
3347
|
+
...(securityApproval !== undefined ? { approvalId: securityApproval.approvalId, securityApproval } : {}),
|
|
3348
|
+
identity: {
|
|
3349
|
+
deviceId: request.device.id,
|
|
3350
|
+
certificate: issued.certificate,
|
|
3351
|
+
certificateChain: issued.chain,
|
|
3352
|
+
},
|
|
3353
|
+
inviter: {
|
|
3354
|
+
deviceId: issued.inviterDeviceId ?? localDeviceId,
|
|
3355
|
+
multiaddrs: issued.inviterMultiaddrs ?? [],
|
|
3356
|
+
},
|
|
3357
|
+
});
|
|
3358
|
+
} catch (error) {
|
|
3359
|
+
return sendJson(res, 502, {
|
|
3360
|
+
ok: false,
|
|
3361
|
+
error: 'mobile_access_join_failed',
|
|
3362
|
+
message: String(error?.message ?? error),
|
|
3363
|
+
});
|
|
3364
|
+
}
|
|
3365
|
+
}
|
|
3366
|
+
|
|
3367
|
+
// revoke
|
|
3368
|
+
const grantId = typeof input.grantId === 'string' ? input.grantId.trim() : '';
|
|
3369
|
+
if (grantId.length === 0) {
|
|
3370
|
+
return sendJson(res, 400, { ok: false, error: 'bad_request', message: '需要 grantId' });
|
|
3371
|
+
}
|
|
3372
|
+
let subject = typeof input.subject === 'string' ? input.subject.trim() : '';
|
|
3373
|
+
if (subject.length === 0) {
|
|
3374
|
+
const events = await lib.listPolicyEvents(app);
|
|
3375
|
+
const grant = lib.findControllerGrant(events, grantId);
|
|
3376
|
+
if (grant !== null) subject = grant.subject.id;
|
|
3377
|
+
}
|
|
3378
|
+
if (subject.length === 0) {
|
|
3379
|
+
return sendJson(res, 400, { ok: false, error: 'bad_request', message: '未找到该 grant 的 subject:请显式提供 subject' });
|
|
3380
|
+
}
|
|
3381
|
+
const record = {
|
|
3382
|
+
grantId,
|
|
3383
|
+
subject,
|
|
3384
|
+
issuedAt: Date.now(),
|
|
3385
|
+
...(typeof input.note === 'string' && input.note.length > 0 ? { note: input.note } : {}),
|
|
3386
|
+
};
|
|
3387
|
+
const event = await lib.appendControllerRevoke(app, record);
|
|
3388
|
+
return sendJson(res, 200, { ok: true, record, eventId: event.id });
|
|
3389
|
+
}
|
|
3390
|
+
|
|
2902
3391
|
// S2:安全三档写端点门禁(medium 动态码 / high 会签或恢复码;low 放行)。
|
|
2903
3392
|
const gateInput = parseJsonBody(body) ?? {};
|
|
2904
3393
|
const gate = await securityWriteGate({ app, home, path, input: gateInput, namespace });
|
|
@@ -3180,11 +3669,85 @@ export async function startHttpServer({
|
|
|
3180
3669
|
}
|
|
3181
3670
|
const lib = await loadFleetSecurity();
|
|
3182
3671
|
if (!lib) return sendJson(res, 503, { ok: false, error: 'security_unavailable', message: '安全模块不可用' });
|
|
3672
|
+
// E2 MAS 单机 high 档接入:join 可显式指定新设备为 initiator,daemon 仅代为 cosign。
|
|
3673
|
+
// 该覆盖只允许 join;事件 author 仍是本机 daemon,cosign approver 仍是本机 deviceId。
|
|
3674
|
+
let initiator = deviceId;
|
|
3675
|
+
let mobile;
|
|
3676
|
+
let mobileNonce;
|
|
3677
|
+
if (input.initiator !== undefined) {
|
|
3678
|
+
if (op !== 'join') {
|
|
3679
|
+
return sendJson(res, 400, { ok: false, error: 'bad_request', message: '仅 join 批准允许覆盖 initiator' });
|
|
3680
|
+
}
|
|
3681
|
+
if (typeof input.initiator !== 'string' || input.initiator.trim().length === 0) {
|
|
3682
|
+
return sendJson(res, 400, { ok: false, error: 'bad_request', message: 'join 的 initiator 必须是非空设备 ID' });
|
|
3683
|
+
}
|
|
3684
|
+
initiator = input.initiator.trim();
|
|
3685
|
+
|
|
3686
|
+
// H-01:手机 join 不得只靠本地 admin 自批。必须带 ControllerGrant + AccessRequest + AccessApproval。
|
|
3687
|
+
const grant = input.grant ?? input.controllerGrant;
|
|
3688
|
+
const request = input.request ?? input.accessRequest;
|
|
3689
|
+
const approval = input.approval ?? input.accessApproval;
|
|
3690
|
+
if (grant === null || typeof grant !== 'object'
|
|
3691
|
+
|| request === null || typeof request !== 'object'
|
|
3692
|
+
|| approval === null || typeof approval !== 'object') {
|
|
3693
|
+
return sendJson(res, 400, {
|
|
3694
|
+
ok: false,
|
|
3695
|
+
error: 'mobile_proof_required',
|
|
3696
|
+
message: '手机 join 批准需要 grant、request、approval(ControllerGrant + AccessRequest + AccessApproval)',
|
|
3697
|
+
});
|
|
3698
|
+
}
|
|
3699
|
+
const masterPublicKey = app.identity?.getUserMasterPublicKey?.();
|
|
3700
|
+
if (!(masterPublicKey instanceof Uint8Array) || masterPublicKey.length !== 32) {
|
|
3701
|
+
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机用户主公钥不可用,无法校验手机批准' });
|
|
3702
|
+
}
|
|
3703
|
+
const events = await lib.listPolicyEvents(app);
|
|
3704
|
+
const revocation = lib.controllerRevocationSets(lib.controllerRevokesFromEvents(events));
|
|
3705
|
+
const state = await lib.readSecurityState(app);
|
|
3706
|
+
const checked = await lib.verifyControllerAccessApproval(grant, request, approval, {
|
|
3707
|
+
masterPublicKey: b64url(masterPublicKey),
|
|
3708
|
+
expectedNamespace: input.namespace,
|
|
3709
|
+
revokedGrantIds: revocation.grantIds,
|
|
3710
|
+
revokedSubjects: revocation.subjects,
|
|
3711
|
+
...(state.admitted.length > 0
|
|
3712
|
+
? { isIssuerAdmitted: (issuer) => state.admitted.includes(issuer) }
|
|
3713
|
+
: {}),
|
|
3714
|
+
});
|
|
3715
|
+
if (!checked.ok) {
|
|
3716
|
+
return sendJson(res, 400, {
|
|
3717
|
+
ok: false,
|
|
3718
|
+
error: 'mobile_proof_invalid',
|
|
3719
|
+
message: `手机批准校验失败(${checked.reason})`,
|
|
3720
|
+
});
|
|
3721
|
+
}
|
|
3722
|
+
if (initiator !== request.device.id) {
|
|
3723
|
+
return sendJson(res, 400, {
|
|
3724
|
+
ok: false,
|
|
3725
|
+
error: 'mobile_proof_invalid',
|
|
3726
|
+
message: 'join initiator 必须等于 AccessRequest.device.id',
|
|
3727
|
+
});
|
|
3728
|
+
}
|
|
3729
|
+
mobile = {
|
|
3730
|
+
v: 1,
|
|
3731
|
+
grantId: grant.grantId,
|
|
3732
|
+
controllerId: grant.subject.id,
|
|
3733
|
+
requestHash: checked.requestHash,
|
|
3734
|
+
requestId: request.requestId,
|
|
3735
|
+
deviceId: request.device.id,
|
|
3736
|
+
devicePublicKey: request.device.publicKey,
|
|
3737
|
+
tier: approval.tier,
|
|
3738
|
+
namespace: approval.namespace,
|
|
3739
|
+
approvalNonce: approval.nonce,
|
|
3740
|
+
approvalTs: approval.ts,
|
|
3741
|
+
approvalSignature: approval.signature,
|
|
3742
|
+
digest: checked.mobileDigest,
|
|
3743
|
+
};
|
|
3744
|
+
mobileNonce = lib.controllerMobileApprovalNonce(checked.mobileDigest);
|
|
3745
|
+
}
|
|
3183
3746
|
const approvalId = randomUUID();
|
|
3184
|
-
const nonce = randomUUID();
|
|
3747
|
+
const nonce = mobileNonce ?? randomUUID();
|
|
3185
3748
|
const digest = lib.securityActionDigest({
|
|
3186
3749
|
op,
|
|
3187
|
-
initiator
|
|
3750
|
+
initiator,
|
|
3188
3751
|
...(op === 'kick' || op === 'restore' ? { subject: input.target } : {}),
|
|
3189
3752
|
...(op === 'join' ? { namespace: input.namespace } : {}),
|
|
3190
3753
|
...(op === 'tier' ? { level: input.level } : {}),
|
|
@@ -3194,7 +3757,7 @@ export async function startHttpServer({
|
|
|
3194
3757
|
approvalId,
|
|
3195
3758
|
op,
|
|
3196
3759
|
decision: 'request',
|
|
3197
|
-
initiator
|
|
3760
|
+
initiator,
|
|
3198
3761
|
...(op === 'kick' || op === 'restore' ? { target: input.target } : {}),
|
|
3199
3762
|
...(op === 'join' ? { namespace: input.namespace } : {}),
|
|
3200
3763
|
...(op === 'tier' ? { level: input.level } : {}),
|
|
@@ -3204,6 +3767,7 @@ export async function startHttpServer({
|
|
|
3204
3767
|
expiresAt: Date.now() + 10 * 60_000,
|
|
3205
3768
|
issuedAt: Date.now(),
|
|
3206
3769
|
...(typeof input.note === 'string' ? { note: input.note } : {}),
|
|
3770
|
+
...(mobile !== undefined ? { mobile } : {}),
|
|
3207
3771
|
};
|
|
3208
3772
|
const event = await lib.writeSecurityApproval(app, record);
|
|
3209
3773
|
return sendJson(res, 201, { ok: true, ...record, eventId: event.id });
|
|
@@ -3218,9 +3782,7 @@ export async function startHttpServer({
|
|
|
3218
3782
|
const events = await lib.listPolicyEvents(app);
|
|
3219
3783
|
const request = lib.approvalsFromEvents(events).find((record) => record.approvalId === approvalId && record.decision === 'request');
|
|
3220
3784
|
if (!request) return sendJson(res, 404, { ok: false, error: 'approval_not_found', message: '待批准请求不存在或已处理' });
|
|
3221
|
-
|
|
3222
|
-
return sendJson(res, 403, { ok: false, error: 'self_approval', message: '发起设备不能批准自己的动作' });
|
|
3223
|
-
}
|
|
3785
|
+
// deny 是清理动作:不因发起者=本机而被挡(approve 失败时 MAS 仍要能记录拒绝)。
|
|
3224
3786
|
if (decision === 'deny') {
|
|
3225
3787
|
const record = {
|
|
3226
3788
|
...request,
|
|
@@ -3230,6 +3792,9 @@ export async function startHttpServer({
|
|
|
3230
3792
|
const event = await lib.writeSecurityApproval(app, record);
|
|
3231
3793
|
return sendJson(res, 200, { ok: true, approvalId, decision: 'deny', eventId: event.id });
|
|
3232
3794
|
}
|
|
3795
|
+
if (request.initiator === deviceId) {
|
|
3796
|
+
return sendJson(res, 403, { ok: false, error: 'self_approval', message: '发起设备不能批准自己的动作' });
|
|
3797
|
+
}
|
|
3233
3798
|
const identity = app.identity?.getDeviceKey?.(deviceId);
|
|
3234
3799
|
if (!identity || identity.privateKey === undefined) {
|
|
3235
3800
|
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机设备身份不可用,无法会签' });
|
|
@@ -4096,15 +4661,17 @@ export async function startHttpServer({
|
|
|
4096
4661
|
if (typeof reqOrigin === 'string' && reqOrigin.length > 0 && reqOrigin !== origin) {
|
|
4097
4662
|
return sendJson(res, 403, { error: 'forbidden', message: `跨站点写被拒(Origin=${reqOrigin})` });
|
|
4098
4663
|
}
|
|
4099
|
-
// 1)
|
|
4100
|
-
const
|
|
4664
|
+
// 1) 鉴权:mobile controller 端点要求 mobile.access(不是 memory.admin)。
|
|
4665
|
+
const controllerWrite = path.startsWith('/admin/api/controllers/');
|
|
4666
|
+
const requiredScope = controllerWrite ? 'mobile.access' : 'memory.admin';
|
|
4667
|
+
const check = await authenticate(req, Buffer.alloc(0), requiredScope);
|
|
4101
4668
|
if (!check.ok) {
|
|
4102
4669
|
res.statusCode = check.status;
|
|
4103
4670
|
if (check.challenge) res.setHeader('www-authenticate', check.challenge);
|
|
4104
4671
|
return sendJson(res, check.status, { error: 'unauthorized', message: check.message });
|
|
4105
4672
|
}
|
|
4106
|
-
// 2) CSRF
|
|
4107
|
-
if (!csrfValid(req)) {
|
|
4673
|
+
// 2) CSRF 双提交:桌面浏览器写端点;MAS 的 mobile.access 是机器 bearer,不带 cookie。
|
|
4674
|
+
if (!controllerWrite && !csrfValid(req)) {
|
|
4108
4675
|
return sendJson(res, 403, { error: 'forbidden', message: 'CSRF token 缺失或无效' });
|
|
4109
4676
|
}
|
|
4110
4677
|
// 3) D1:只读降级;D2 起由 applyAdminWrite 处理
|
|
@@ -4556,6 +5123,64 @@ export async function startHttpServer({
|
|
|
4556
5123
|
return sendJson(res, 404, { error: 'not_found', path });
|
|
4557
5124
|
}
|
|
4558
5125
|
if (path.startsWith('/admin/api/')) {
|
|
5126
|
+
// 桌面/控制台控制器列表(admin 读面;只读,不签发)。
|
|
5127
|
+
if (path === '/admin/api/controllers' && req.method === 'GET') {
|
|
5128
|
+
if (!app || !service) {
|
|
5129
|
+
return sendJson(res, 503, { ok: false, error: 'console_unavailable', message: 'Mebular 尚未初始化' });
|
|
5130
|
+
}
|
|
5131
|
+
const check = await authenticate(req, Buffer.alloc(0), 'memory.read');
|
|
5132
|
+
if (!check.ok) {
|
|
5133
|
+
res.statusCode = check.status;
|
|
5134
|
+
if (check.challenge) res.setHeader('www-authenticate', check.challenge);
|
|
5135
|
+
return sendJson(res, check.status, { ok: false, error: 'unauthorized', message: check.message });
|
|
5136
|
+
}
|
|
5137
|
+
const lib = await loadFleetSecurity();
|
|
5138
|
+
if (!lib) {
|
|
5139
|
+
return sendJson(res, 200, { ok: true, controllers: [], revoked: [] });
|
|
5140
|
+
}
|
|
5141
|
+
const events = await lib.listPolicyEvents(app);
|
|
5142
|
+
const grants = lib.controllerGrantsFromEvents(events);
|
|
5143
|
+
const revokes = lib.controllerRevokesFromEvents(events);
|
|
5144
|
+
return sendJson(res, 200, {
|
|
5145
|
+
ok: true,
|
|
5146
|
+
controllers: grants.map((grant) => ({ grant, lastSeen: null })),
|
|
5147
|
+
revoked: revokes,
|
|
5148
|
+
});
|
|
5149
|
+
}
|
|
5150
|
+
// MAS policy snapshot:独立 mobile.access(不含 memory.read/admin)。
|
|
5151
|
+
if (path === '/admin/api/controllers/policy' && req.method === 'GET') {
|
|
5152
|
+
if (!app || !service) {
|
|
5153
|
+
return sendJson(res, 503, { ok: false, error: 'console_unavailable', message: 'Mebular 尚未初始化' });
|
|
5154
|
+
}
|
|
5155
|
+
const check = await authenticate(req, Buffer.alloc(0), 'mobile.access');
|
|
5156
|
+
if (!check.ok) {
|
|
5157
|
+
res.statusCode = check.status;
|
|
5158
|
+
if (check.challenge) res.setHeader('www-authenticate', check.challenge);
|
|
5159
|
+
return sendJson(res, check.status, { ok: false, error: 'unauthorized', message: check.message });
|
|
5160
|
+
}
|
|
5161
|
+
const lib = await loadFleetSecurity();
|
|
5162
|
+
if (!lib) {
|
|
5163
|
+
return sendJson(res, 200, {
|
|
5164
|
+
ok: true,
|
|
5165
|
+
level: 'low',
|
|
5166
|
+
admitted: [],
|
|
5167
|
+
controllerGrants: [],
|
|
5168
|
+
controllerRevokes: [],
|
|
5169
|
+
});
|
|
5170
|
+
}
|
|
5171
|
+
const state = await lib.readSecurityState(app);
|
|
5172
|
+
const events = await lib.listPolicyEvents(app);
|
|
5173
|
+
return sendJson(res, 200, {
|
|
5174
|
+
ok: true,
|
|
5175
|
+
level: state.level,
|
|
5176
|
+
admitted: state.admitted,
|
|
5177
|
+
controllerGrants: lib.controllerGrantsFromEvents(events),
|
|
5178
|
+
controllerRevokes: lib.controllerRevokesFromEvents(events),
|
|
5179
|
+
deviceRevokes: events
|
|
5180
|
+
.filter((event) => event.type === 'device_revoke')
|
|
5181
|
+
.map((event) => event.data?.deviceRevoke ?? event),
|
|
5182
|
+
});
|
|
5183
|
+
}
|
|
4559
5184
|
if (req.method === 'GET' && (path === '/admin/api/security' || path === '/admin/api/security/approvals')) return handleSecurityRead(req, res);
|
|
4560
5185
|
const planMatch = path.match(/^\/admin\/api\/namespaces\/([^/]+)\/handoff-plan$/);
|
|
4561
5186
|
if (req.method === 'GET' && planMatch) {
|
package/src/tools.mjs
CHANGED
|
@@ -132,6 +132,8 @@ export const TOOL_SPECS = [
|
|
|
132
132
|
limit: z.number().optional(),
|
|
133
133
|
offset: z.number().optional(),
|
|
134
134
|
includeHistory: z.boolean().optional(),
|
|
135
|
+
/** 评估 fact 有效性的时间点(Unix ms);缺省当前时间 */
|
|
136
|
+
asOf: z.number().optional(),
|
|
135
137
|
/** G-ML-1:默认 false(归档不进入召回);显式 true 才可见已归档 */
|
|
136
138
|
includeArchived: z.boolean().optional(),
|
|
137
139
|
filters: z
|
|
@@ -153,6 +155,7 @@ export const TOOL_SPECS = [
|
|
|
153
155
|
limit: clampLimit(args.limit),
|
|
154
156
|
...(args.offset !== undefined ? { offset: args.offset } : {}),
|
|
155
157
|
...(args.includeHistory !== undefined ? { includeHistory: args.includeHistory } : {}),
|
|
158
|
+
...(args.asOf !== undefined ? { asOf: args.asOf } : {}),
|
|
156
159
|
...(args.includeArchived !== undefined ? { includeArchived: args.includeArchived } : {}),
|
|
157
160
|
...(args.filters ? { filters: args.filters } : {}),
|
|
158
161
|
}));
|
|
@@ -170,6 +173,8 @@ export const TOOL_SPECS = [
|
|
|
170
173
|
types: z.array(z.string()).optional(),
|
|
171
174
|
limit: z.number().optional(),
|
|
172
175
|
includeRelations: z.boolean().optional(),
|
|
176
|
+
/** 评估 fact 有效性的时间点(Unix ms);缺省当前时间 */
|
|
177
|
+
asOf: z.number().optional(),
|
|
173
178
|
/** G-ML-1:默认 false(归档不进入召回) */
|
|
174
179
|
includeArchived: z.boolean().optional(),
|
|
175
180
|
filters: z
|
|
@@ -177,6 +182,8 @@ export const TOOL_SPECS = [
|
|
|
177
182
|
tags: z.array(z.string()).optional(),
|
|
178
183
|
createdAfter: z.number().optional(),
|
|
179
184
|
createdBefore: z.number().optional(),
|
|
185
|
+
entity: z.string().optional(),
|
|
186
|
+
minConfidence: z.number().optional(),
|
|
180
187
|
namespace: namespaceFilter,
|
|
181
188
|
})
|
|
182
189
|
.optional(),
|
|
@@ -188,6 +195,7 @@ export const TOOL_SPECS = [
|
|
|
188
195
|
...(args.types ? { types: args.types } : {}),
|
|
189
196
|
limit: clampLimit(args.limit),
|
|
190
197
|
...(args.includeRelations !== undefined ? { includeRelations: args.includeRelations } : {}),
|
|
198
|
+
...(args.asOf !== undefined ? { asOf: args.asOf } : {}),
|
|
191
199
|
...(args.includeArchived !== undefined ? { includeArchived: args.includeArchived } : {}),
|
|
192
200
|
...(args.filters ? { filters: args.filters } : {}),
|
|
193
201
|
}));
|
package/src/version.mjs
CHANGED