@mebular/mcp 0.3.5 → 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/bin/mebular.mjs +120 -0
- package/package.json +4 -4
- package/src/adapter-health.mjs +213 -0
- package/src/adapter-provision.mjs +405 -0
- package/src/adapter-state.mjs +154 -0
- package/src/adapters/dsh.mjs +830 -0
- package/src/adapters/hermes.mjs +966 -0
- package/src/adapters/index.mjs +91 -0
- package/src/adapters/opencode.mjs +757 -0
- package/src/clients.mjs +184 -13
- package/src/first-run.mjs +343 -0
- package/src/memory-capability.mjs +15 -0
- package/src/memory-runtime-config.mjs +2 -0
- package/src/memory-runtime-effective.mjs +91 -0
- package/src/memory-runtime-supervisor.mjs +247 -2
- package/src/provision.mjs +11 -1
- package/src/serve.mjs +798 -11
- package/src/server.mjs +36 -0
- package/src/tools.mjs +8 -0
- package/src/version.mjs +1 -1
package/src/serve.mjs
CHANGED
|
@@ -35,6 +35,7 @@ import {
|
|
|
35
35
|
normalizeMemoryRuntimeModelSource,
|
|
36
36
|
readMemoryRuntimeModelSource,
|
|
37
37
|
} from './memory-runtime-config.mjs';
|
|
38
|
+
import { resolveMemoryRuntimeEffectiveMode } from './memory-runtime-effective.mjs';
|
|
38
39
|
import { APP_VERSION } from './version.mjs';
|
|
39
40
|
import { acquireConfigFileLock } from './config-lock.mjs';
|
|
40
41
|
import { resolveStaticAssetRoots } from './asset-roots.mjs';
|
|
@@ -57,6 +58,13 @@ import {
|
|
|
57
58
|
snapshotProvisionState,
|
|
58
59
|
writeProvisionRecord,
|
|
59
60
|
} from './provision.mjs';
|
|
61
|
+
import {
|
|
62
|
+
FIRST_RUN_INIT_FAILED,
|
|
63
|
+
firstRunPublicView,
|
|
64
|
+
initializeFirstRunHome,
|
|
65
|
+
markFirstRunAcked,
|
|
66
|
+
readFirstRunMarker,
|
|
67
|
+
} from './first-run.mjs';
|
|
60
68
|
import {
|
|
61
69
|
acquireActiveLock,
|
|
62
70
|
cloudError,
|
|
@@ -208,13 +216,15 @@ import { renderSvgQr } from './qr.mjs';
|
|
|
208
216
|
import { clearRuntimeFile, writeRuntimeFile } from './runtime-file.mjs';
|
|
209
217
|
|
|
210
218
|
// R1.3:记忆面 memory.* + 任务面 task.*(两轴独立;同一轴内 write ⇒ read、admin ⇒ 其余)
|
|
211
|
-
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'];
|
|
212
220
|
const SCOPE_IMPLIES = {
|
|
213
221
|
'memory.read': ['memory.read'],
|
|
214
222
|
'memory.write': ['memory.read', 'memory.write'],
|
|
215
223
|
'memory.admin': ['memory.read', 'memory.write', 'memory.admin'],
|
|
216
224
|
'task.read': ['task.read'],
|
|
217
225
|
'task.write': ['task.read', 'task.write'],
|
|
226
|
+
// MAS 专用:不蕴含 memory.*/task.*;也不被 memory.admin 蕴含(必须显式签发)。
|
|
227
|
+
'mobile.access': ['mobile.access'],
|
|
218
228
|
};
|
|
219
229
|
const DEFAULT_SCOPES = ['memory.read'];
|
|
220
230
|
const ACCESS_TTL = 900; // 15min
|
|
@@ -261,10 +271,13 @@ const CONSOLE_FILES = {
|
|
|
261
271
|
'console.js': 'text/javascript; charset=utf-8',
|
|
262
272
|
'host.js': 'text/javascript; charset=utf-8',
|
|
263
273
|
'dropdown.mjs': 'text/javascript; charset=utf-8',
|
|
274
|
+
'first-run-disclosure.js': 'text/javascript; charset=utf-8',
|
|
264
275
|
'assistants.js': 'text/javascript; charset=utf-8',
|
|
265
276
|
'assistant-status.js': 'text/javascript; charset=utf-8',
|
|
266
277
|
'deep-link.js': 'text/javascript; charset=utf-8',
|
|
267
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',
|
|
268
281
|
'i18n.mjs': 'text/javascript; charset=utf-8',
|
|
269
282
|
'starfield.js': 'text/javascript; charset=utf-8',
|
|
270
283
|
'wizard.js': 'text/javascript; charset=utf-8',
|
|
@@ -881,6 +894,48 @@ function hasScope(granted, required) {
|
|
|
881
894
|
* 启动 HTTP MCP server。
|
|
882
895
|
* @returns {Promise<{ server: import('node:http').Server, host: string, port: number, auth: string, close: () => Promise<void> }>}
|
|
883
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
|
+
|
|
884
939
|
export async function startHttpServer({
|
|
885
940
|
home,
|
|
886
941
|
app: initialApp = null,
|
|
@@ -908,6 +963,8 @@ export async function startHttpServer({
|
|
|
908
963
|
afterConfigRename = null,
|
|
909
964
|
// 引导态(空家目录):只服务 /healthz + /console 引导页 + /app/provision/*;其余 409 provision_required
|
|
910
965
|
provision: initialProvision = false,
|
|
966
|
+
// 0.4.0 W1b:首启初始化失败时给控制台的稳定 warning(不阻塞 READY)。
|
|
967
|
+
firstRunWarning = null,
|
|
911
968
|
// P1:同一进程内热初始化。返回新的运行时上下文;成功后本 server 从 UNINITIALIZED → READY。
|
|
912
969
|
initializeRuntime = null,
|
|
913
970
|
// 关闭钩子:热初始化后由 server.mjs 关闭 app / join / 广播计时器(HTTP server 本身由本函数关闭)
|
|
@@ -1886,6 +1943,8 @@ export async function startHttpServer({
|
|
|
1886
1943
|
recovery: { registered: false },
|
|
1887
1944
|
pendingApprovals: [],
|
|
1888
1945
|
recentApprovals: [],
|
|
1946
|
+
controllerGrants: [],
|
|
1947
|
+
controllerRevokes: [],
|
|
1889
1948
|
});
|
|
1890
1949
|
}
|
|
1891
1950
|
const state = await lib.readSecurityState(app);
|
|
@@ -1911,6 +1970,9 @@ export async function startHttpServer({
|
|
|
1911
1970
|
},
|
|
1912
1971
|
pendingApprovals: lib.pendingApprovals(events),
|
|
1913
1972
|
recentApprovals: lib.approvalsFromEvents(events).slice(-50),
|
|
1973
|
+
// MAS 撤销校验读路径:controller_revoke 是权威;grant 记录给配对/诊断用。
|
|
1974
|
+
controllerGrants: lib.controllerGrantsFromEvents(events),
|
|
1975
|
+
controllerRevokes: lib.controllerRevokesFromEvents(events),
|
|
1914
1976
|
});
|
|
1915
1977
|
}
|
|
1916
1978
|
|
|
@@ -1952,6 +2014,28 @@ export async function startHttpServer({
|
|
|
1952
2014
|
const detail = memoryRuntimeSupervisor
|
|
1953
2015
|
? await memoryRuntimeSupervisor.readStatus().catch(() => null)
|
|
1954
2016
|
: null;
|
|
2017
|
+
// sidecar 可用时以 sidecar 的 effective 为准;轻量/未就绪时用同一张表纯推导。
|
|
2018
|
+
const fallbackSource = detail?.intervention
|
|
2019
|
+
? null
|
|
2020
|
+
: await readMemoryRuntimeModelSource({ home }).catch(() => null);
|
|
2021
|
+
const effective = resolveMemoryRuntimeEffectiveMode({
|
|
2022
|
+
config,
|
|
2023
|
+
modelSource: detail?.model?.configured ?? fallbackSource?.source,
|
|
2024
|
+
sourcePresent: fallbackSource?.sourcePresent
|
|
2025
|
+
?? (detail?.model?.configured !== undefined && detail?.model?.configured !== null),
|
|
2026
|
+
});
|
|
2027
|
+
const intervention = detail?.intervention ?? {
|
|
2028
|
+
mode: effective.effective,
|
|
2029
|
+
planner: effective.planner,
|
|
2030
|
+
source: effective.source,
|
|
2031
|
+
sourcePresent: effective.sourcePresent,
|
|
2032
|
+
derivedMode: effective.derivedMode,
|
|
2033
|
+
legacyModePresent: effective.legacyModePresent,
|
|
2034
|
+
legacyModeIgnored: effective.legacyModeIgnored,
|
|
2035
|
+
legacyModeConflict: effective.legacyModeConflict,
|
|
2036
|
+
diagnosticShadow: effective.diagnosticShadow,
|
|
2037
|
+
warnings: effective.warnings,
|
|
2038
|
+
};
|
|
1955
2039
|
// 进程、capability 与模型是独立观察;不得用进程存活伪造 capability ready。
|
|
1956
2040
|
return sendJson(res, 200, {
|
|
1957
2041
|
...status,
|
|
@@ -1961,6 +2045,7 @@ export async function startHttpServer({
|
|
|
1961
2045
|
capability: detail?.capability ?? null,
|
|
1962
2046
|
capabilityError: detail?.error ?? null,
|
|
1963
2047
|
model: detail?.model ?? null,
|
|
2048
|
+
intervention,
|
|
1964
2049
|
});
|
|
1965
2050
|
}
|
|
1966
2051
|
if (path === '/admin/api/memory-runtime/model-source') {
|
|
@@ -2185,9 +2270,12 @@ export async function startHttpServer({
|
|
|
2185
2270
|
/^\/admin\/api\/security\/approvals\/([^/]+)\/(approve|deny)$/,
|
|
2186
2271
|
/^\/admin\/api\/security\/totp\/(show|import)$/,
|
|
2187
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)$/,
|
|
2188
2275
|
/^\/admin\/api\/namespaces\/([^/]+)\/(rejoin|leave)$/,
|
|
2189
2276
|
/^\/admin\/api\/service\/(install|uninstall)$/,
|
|
2190
2277
|
/^\/admin\/api\/repair$/,
|
|
2278
|
+
/^\/admin\/api\/adapters\/repair$/,
|
|
2191
2279
|
/^\/admin\/api\/clients\/([^/]+)\/(connect|rollback|skills|preview|verify|recheck)$/,
|
|
2192
2280
|
/^\/admin\/api\/assistants$/,
|
|
2193
2281
|
/^\/admin\/api\/assistants\/([^/]+)$/,
|
|
@@ -2196,6 +2284,10 @@ export async function startHttpServer({
|
|
|
2196
2284
|
/^\/admin\/api\/(?:models|inference)\/(install|select|download|pause|resume|cancel|import|uninstall|remove|start|stop|test)$/,
|
|
2197
2285
|
// 0.3 记忆运行时:召回反馈经 MCP 薄代理转发 sidecar;host token 不出服务端。
|
|
2198
2286
|
/^\/admin\/api\/memory-runtime\/feedback$/,
|
|
2287
|
+
// 0.4 W4:console outcome 经 MCP admin 代理;独立 admin secret 不出服务端。
|
|
2288
|
+
/^\/admin\/api\/memory-runtime\/outcome$/,
|
|
2289
|
+
// 0.4 记忆介入策略:重置本机策略状态;同样经薄代理,sidecar 未启用时明确失败。
|
|
2290
|
+
/^\/admin\/api\/memory-runtime\/policy\/reset$/,
|
|
2199
2291
|
// 0.3 高级模型来源:经 sidecar `/inference/settings` 或 `/models/:pack/activate`。
|
|
2200
2292
|
/^\/admin\/api\/memory-runtime\/model-source$/,
|
|
2201
2293
|
];
|
|
@@ -2731,6 +2823,29 @@ export async function startHttpServer({
|
|
|
2731
2823
|
}
|
|
2732
2824
|
}
|
|
2733
2825
|
|
|
2826
|
+
// 内部:App 启动/升级后修复 connected=true 宿主的 Adapter(无 UI)。
|
|
2827
|
+
// 同一 memory.admin + CSRF 门;只报告稳定 code,不回显路径/正文。
|
|
2828
|
+
async function handleAdapterRepair(req, res) {
|
|
2829
|
+
const { listAssistantsAsync, assistantUserHome, daemonMcpUrl } = await import('./clients.mjs');
|
|
2830
|
+
const { ensureAdaptersForConnected } = await import('./adapter-provision.mjs');
|
|
2831
|
+
const mcpUrl = daemonMcpUrl({ host: req.headers?.host, encrypted: Boolean(req.socket?.encrypted) });
|
|
2832
|
+
try {
|
|
2833
|
+
const userHome = assistantUserHome();
|
|
2834
|
+
const list = await listAssistantsAsync({ home, cwd: process.cwd(), userHome, refresh: true, ttlMs: 0, mcpUrl });
|
|
2835
|
+
const connectedHostIds = list.assistants.filter((assistant) => assistant.connected === true).map((assistant) => assistant.id);
|
|
2836
|
+
const result = await ensureAdaptersForConnected({
|
|
2837
|
+
home,
|
|
2838
|
+
cwd: process.cwd(),
|
|
2839
|
+
userHome,
|
|
2840
|
+
connectedHostIds,
|
|
2841
|
+
resourcesPath: process.resourcesPath,
|
|
2842
|
+
});
|
|
2843
|
+
return sendJson(res, 200, result);
|
|
2844
|
+
} catch {
|
|
2845
|
+
return sendJson(res, 500, { ok: false, scope: 'adapter-provisioning', error: 'adapter_repair_failed' });
|
|
2846
|
+
}
|
|
2847
|
+
}
|
|
2848
|
+
|
|
2734
2849
|
// D2 写端点实现(memory.admin scope + CSRF 已在 handleAdminWrite 校验)
|
|
2735
2850
|
async function applyAdminWrite(req, res, path, body) {
|
|
2736
2851
|
if (!app || !service) {
|
|
@@ -2748,6 +2863,8 @@ export async function startHttpServer({
|
|
|
2748
2863
|
|
|
2749
2864
|
// 自动修复:客户端接入修复,**不**经 securityWriteGate(不写记忆/安全状态)。
|
|
2750
2865
|
if (path === '/admin/api/repair') return handleRepair(req, res);
|
|
2866
|
+
// 内部:App 启动/升级后的 Adapter 修复(仍是 memory.admin + CSRF;无 UI)。
|
|
2867
|
+
if (path === '/admin/api/adapters/repair') return handleAdapterRepair(req, res);
|
|
2751
2868
|
|
|
2752
2869
|
// 0.3 高级模型来源:sidecar 拥有 config.model.source;MCP 只做薄代理。
|
|
2753
2870
|
// local 必须带 pack 并通过 sidecar activate;不直接写 config.json、不重启 sidecar。
|
|
@@ -2782,6 +2899,49 @@ export async function startHttpServer({
|
|
|
2782
2899
|
return sendJson(res, result.statusCode, result.body);
|
|
2783
2900
|
}
|
|
2784
2901
|
|
|
2902
|
+
// 0.4 W4 console outcome:同 feedback 的鉴权/CSRF;MCP 只附加独立 admin
|
|
2903
|
+
// secret,host token 不能冒充 console,note/raw 不接受。
|
|
2904
|
+
if (path === '/admin/api/memory-runtime/outcome') {
|
|
2905
|
+
const input = parseJsonBody(body);
|
|
2906
|
+
if (!input) {
|
|
2907
|
+
return sendJson(res, 400, { ok: false, error: 'bad_request', message: '需要 JSON 请求体' });
|
|
2908
|
+
}
|
|
2909
|
+
const traceId = typeof input.traceId === 'string' ? input.traceId : '';
|
|
2910
|
+
const result = memoryRuntimeSupervisor
|
|
2911
|
+
? await memoryRuntimeSupervisor.submitRecallOutcome(traceId, {
|
|
2912
|
+
kind: input.kind,
|
|
2913
|
+
...(input.confidence !== undefined ? { confidence: input.confidence } : {}),
|
|
2914
|
+
})
|
|
2915
|
+
: {
|
|
2916
|
+
statusCode: 409,
|
|
2917
|
+
body: {
|
|
2918
|
+
ok: false,
|
|
2919
|
+
error: 'memory_runtime_disabled',
|
|
2920
|
+
enabled: false,
|
|
2921
|
+
state: 'stopped',
|
|
2922
|
+
message: '记忆运行时未启用',
|
|
2923
|
+
},
|
|
2924
|
+
};
|
|
2925
|
+
return sendJson(res, result.statusCode, result.body);
|
|
2926
|
+
}
|
|
2927
|
+
|
|
2928
|
+
// 0.4 记忆介入策略重置:同 feedback 的鉴权/CSRF/writes-enabled;sidecar 未启用返回 409。
|
|
2929
|
+
if (path === '/admin/api/memory-runtime/policy/reset') {
|
|
2930
|
+
const result = memoryRuntimeSupervisor
|
|
2931
|
+
? await memoryRuntimeSupervisor.resetInterventionPolicy()
|
|
2932
|
+
: {
|
|
2933
|
+
statusCode: 409,
|
|
2934
|
+
body: {
|
|
2935
|
+
ok: false,
|
|
2936
|
+
error: 'memory_runtime_disabled',
|
|
2937
|
+
enabled: false,
|
|
2938
|
+
state: 'stopped',
|
|
2939
|
+
message: '记忆运行时未启用',
|
|
2940
|
+
},
|
|
2941
|
+
};
|
|
2942
|
+
return sendJson(res, result.statusCode, result.body);
|
|
2943
|
+
}
|
|
2944
|
+
|
|
2785
2945
|
// 0.3 本地模型:只代理 sidecar;不经 securityWriteGate(不写记忆/安全状态)。
|
|
2786
2946
|
const modelAction = path.match(/^\/admin\/api\/(?:models|inference)\/([^/]+)$/);
|
|
2787
2947
|
if (modelAction) {
|
|
@@ -2792,6 +2952,442 @@ export async function startHttpServer({
|
|
|
2792
2952
|
return sendJson(res, result.status, result.body);
|
|
2793
2953
|
}
|
|
2794
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
|
+
|
|
2795
3391
|
// S2:安全三档写端点门禁(medium 动态码 / high 会签或恢复码;low 放行)。
|
|
2796
3392
|
const gateInput = parseJsonBody(body) ?? {};
|
|
2797
3393
|
const gate = await securityWriteGate({ app, home, path, input: gateInput, namespace });
|
|
@@ -3073,11 +3669,85 @@ export async function startHttpServer({
|
|
|
3073
3669
|
}
|
|
3074
3670
|
const lib = await loadFleetSecurity();
|
|
3075
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
|
+
}
|
|
3076
3746
|
const approvalId = randomUUID();
|
|
3077
|
-
const nonce = randomUUID();
|
|
3747
|
+
const nonce = mobileNonce ?? randomUUID();
|
|
3078
3748
|
const digest = lib.securityActionDigest({
|
|
3079
3749
|
op,
|
|
3080
|
-
initiator
|
|
3750
|
+
initiator,
|
|
3081
3751
|
...(op === 'kick' || op === 'restore' ? { subject: input.target } : {}),
|
|
3082
3752
|
...(op === 'join' ? { namespace: input.namespace } : {}),
|
|
3083
3753
|
...(op === 'tier' ? { level: input.level } : {}),
|
|
@@ -3087,7 +3757,7 @@ export async function startHttpServer({
|
|
|
3087
3757
|
approvalId,
|
|
3088
3758
|
op,
|
|
3089
3759
|
decision: 'request',
|
|
3090
|
-
initiator
|
|
3760
|
+
initiator,
|
|
3091
3761
|
...(op === 'kick' || op === 'restore' ? { target: input.target } : {}),
|
|
3092
3762
|
...(op === 'join' ? { namespace: input.namespace } : {}),
|
|
3093
3763
|
...(op === 'tier' ? { level: input.level } : {}),
|
|
@@ -3097,6 +3767,7 @@ export async function startHttpServer({
|
|
|
3097
3767
|
expiresAt: Date.now() + 10 * 60_000,
|
|
3098
3768
|
issuedAt: Date.now(),
|
|
3099
3769
|
...(typeof input.note === 'string' ? { note: input.note } : {}),
|
|
3770
|
+
...(mobile !== undefined ? { mobile } : {}),
|
|
3100
3771
|
};
|
|
3101
3772
|
const event = await lib.writeSecurityApproval(app, record);
|
|
3102
3773
|
return sendJson(res, 201, { ok: true, ...record, eventId: event.id });
|
|
@@ -3111,9 +3782,7 @@ export async function startHttpServer({
|
|
|
3111
3782
|
const events = await lib.listPolicyEvents(app);
|
|
3112
3783
|
const request = lib.approvalsFromEvents(events).find((record) => record.approvalId === approvalId && record.decision === 'request');
|
|
3113
3784
|
if (!request) return sendJson(res, 404, { ok: false, error: 'approval_not_found', message: '待批准请求不存在或已处理' });
|
|
3114
|
-
|
|
3115
|
-
return sendJson(res, 403, { ok: false, error: 'self_approval', message: '发起设备不能批准自己的动作' });
|
|
3116
|
-
}
|
|
3785
|
+
// deny 是清理动作:不因发起者=本机而被挡(approve 失败时 MAS 仍要能记录拒绝)。
|
|
3117
3786
|
if (decision === 'deny') {
|
|
3118
3787
|
const record = {
|
|
3119
3788
|
...request,
|
|
@@ -3123,6 +3792,9 @@ export async function startHttpServer({
|
|
|
3123
3792
|
const event = await lib.writeSecurityApproval(app, record);
|
|
3124
3793
|
return sendJson(res, 200, { ok: true, approvalId, decision: 'deny', eventId: event.id });
|
|
3125
3794
|
}
|
|
3795
|
+
if (request.initiator === deviceId) {
|
|
3796
|
+
return sendJson(res, 403, { ok: false, error: 'self_approval', message: '发起设备不能批准自己的动作' });
|
|
3797
|
+
}
|
|
3126
3798
|
const identity = app.identity?.getDeviceKey?.(deviceId);
|
|
3127
3799
|
if (!identity || identity.privateKey === undefined) {
|
|
3128
3800
|
return sendJson(res, 409, { ok: false, error: 'identity_unavailable', message: '本机设备身份不可用,无法会签' });
|
|
@@ -3989,15 +4661,17 @@ export async function startHttpServer({
|
|
|
3989
4661
|
if (typeof reqOrigin === 'string' && reqOrigin.length > 0 && reqOrigin !== origin) {
|
|
3990
4662
|
return sendJson(res, 403, { error: 'forbidden', message: `跨站点写被拒(Origin=${reqOrigin})` });
|
|
3991
4663
|
}
|
|
3992
|
-
// 1)
|
|
3993
|
-
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);
|
|
3994
4668
|
if (!check.ok) {
|
|
3995
4669
|
res.statusCode = check.status;
|
|
3996
4670
|
if (check.challenge) res.setHeader('www-authenticate', check.challenge);
|
|
3997
4671
|
return sendJson(res, check.status, { error: 'unauthorized', message: check.message });
|
|
3998
4672
|
}
|
|
3999
|
-
// 2) CSRF
|
|
4000
|
-
if (!csrfValid(req)) {
|
|
4673
|
+
// 2) CSRF 双提交:桌面浏览器写端点;MAS 的 mobile.access 是机器 bearer,不带 cookie。
|
|
4674
|
+
if (!controllerWrite && !csrfValid(req)) {
|
|
4001
4675
|
return sendJson(res, 403, { error: 'forbidden', message: 'CSRF token 缺失或无效' });
|
|
4002
4676
|
}
|
|
4003
4677
|
// 3) D1:只读降级;D2 起由 applyAdminWrite 处理
|
|
@@ -4244,11 +4918,14 @@ export async function startHttpServer({
|
|
|
4244
4918
|
if (done !== false) return done;
|
|
4245
4919
|
}
|
|
4246
4920
|
if (path === '/app/provision/status' && req.method === 'GET') {
|
|
4921
|
+
const firstRunMarker = await readFirstRunMarker({ home }).catch(() => null);
|
|
4247
4922
|
return sendJson(res, 200, provisionStatus({
|
|
4248
4923
|
home,
|
|
4249
4924
|
mcpPort: boundPort,
|
|
4250
4925
|
phase,
|
|
4251
4926
|
provisioned: !isProvisionHome(home),
|
|
4927
|
+
firstRun: firstRunPublicView(firstRunMarker),
|
|
4928
|
+
firstRunWarning,
|
|
4252
4929
|
}));
|
|
4253
4930
|
}
|
|
4254
4931
|
if (path === '/app/provision/create' || path === '/app/provision/join' || path === '/app/provision/restore') {
|
|
@@ -4363,11 +5040,63 @@ export async function startHttpServer({
|
|
|
4363
5040
|
}
|
|
4364
5041
|
})
|
|
4365
5042
|
.catch((error) => console.error(`CLIENT_ENDPOINT_RECONCILE_FAILED ${error?.code ?? 'ERROR'}`));
|
|
5043
|
+
// 0.4.0 W1b:先确保 provision/应用本身成功,再 ack 披露并初始化 immersive。
|
|
5044
|
+
// 披露成功(Console 显式回传且版本匹配)才写 enabled=true;未回传 / 版本不符 →
|
|
5045
|
+
// marker 保持 pending,不写 enabled=true(fail closed);应用初始化失败时不会 ack。
|
|
5046
|
+
let firstRun = null;
|
|
5047
|
+
if (input.firstRunDisclosure === true) {
|
|
5048
|
+
// 披露版本必须由 Console 显式回传且为整数;缺失/非法一律拒绝 ack。
|
|
5049
|
+
if (!Number.isInteger(input.firstRunDisclosureVersion)) {
|
|
5050
|
+
firstRun = { acknowledged: false };
|
|
5051
|
+
} else {
|
|
5052
|
+
try {
|
|
5053
|
+
const acked = await markFirstRunAcked({
|
|
5054
|
+
home,
|
|
5055
|
+
disclosureVersion: input.firstRunDisclosureVersion,
|
|
5056
|
+
});
|
|
5057
|
+
if (acked) {
|
|
5058
|
+
const initialized = await initializeFirstRunHome({ home, env: process.env });
|
|
5059
|
+
firstRun = {
|
|
5060
|
+
acknowledged: true,
|
|
5061
|
+
initialized: initialized.ok === true && initialized.initialized === true,
|
|
5062
|
+
...(initialized.ok === true ? {} : { warning: FIRST_RUN_INIT_FAILED }),
|
|
5063
|
+
};
|
|
5064
|
+
if (initialized.ok !== true) {
|
|
5065
|
+
console.error(`FIRST_RUN_INIT_FAILED ${initialized.reason ?? 'unknown'}`);
|
|
5066
|
+
}
|
|
5067
|
+
if (initialized.ok === true && initialized.enabled === true) {
|
|
5068
|
+
// 同步路由可见的配置快照,让 supervisor/capability 看到 enabled=true。
|
|
5069
|
+
config = {
|
|
5070
|
+
...config,
|
|
5071
|
+
memoryRuntime: { ...(config.memoryRuntime ?? {}), enabled: true },
|
|
5072
|
+
};
|
|
5073
|
+
}
|
|
5074
|
+
} else {
|
|
5075
|
+
firstRun = { acknowledged: false };
|
|
5076
|
+
}
|
|
5077
|
+
} catch (error) {
|
|
5078
|
+
console.error(`FIRST_RUN_INIT_FAILED ${error?.code ?? 'ERROR'}`);
|
|
5079
|
+
firstRun = { acknowledged: false, warning: FIRST_RUN_INIT_FAILED };
|
|
5080
|
+
}
|
|
5081
|
+
}
|
|
5082
|
+
}
|
|
5083
|
+
// 同进程首次启用:准备 capability token 并启动 sidecar(与设置页开启走同一生命周期)。
|
|
5084
|
+
if (firstRun?.initialized === true && isMemoryRuntimeEnabled(config)) {
|
|
5085
|
+
void enqueueMemoryRuntimeLifecycle(async () => {
|
|
5086
|
+
await memoryCapability.prepare().catch(() => undefined);
|
|
5087
|
+
if (memoryRuntimeSupervisor && isMemoryRuntimeEnabled(config)) {
|
|
5088
|
+
await memoryRuntimeSupervisor.start().catch((error) => {
|
|
5089
|
+
console.error(`MEMORY_RUNTIME_START_FAILED ${error?.code ?? 'ERROR'}`);
|
|
5090
|
+
});
|
|
5091
|
+
}
|
|
5092
|
+
}).catch((error) => console.error(`MEMORY_RUNTIME_START_FAILED ${error?.code ?? 'ERROR'}`));
|
|
5093
|
+
}
|
|
4366
5094
|
return sendJson(res, 200, {
|
|
4367
5095
|
ok: true,
|
|
4368
5096
|
...result,
|
|
4369
5097
|
initialized: true,
|
|
4370
5098
|
phase: 'READY',
|
|
5099
|
+
...(firstRun ? { firstRun } : {}),
|
|
4371
5100
|
});
|
|
4372
5101
|
} catch (error) {
|
|
4373
5102
|
// 回滚本次新建的落盘产物;home 锁仍由当前进程持有(不释放/不重抢)。
|
|
@@ -4394,6 +5123,64 @@ export async function startHttpServer({
|
|
|
4394
5123
|
return sendJson(res, 404, { error: 'not_found', path });
|
|
4395
5124
|
}
|
|
4396
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
|
+
}
|
|
4397
5184
|
if (req.method === 'GET' && (path === '/admin/api/security' || path === '/admin/api/security/approvals')) return handleSecurityRead(req, res);
|
|
4398
5185
|
const planMatch = path.match(/^\/admin\/api\/namespaces\/([^/]+)\/handoff-plan$/);
|
|
4399
5186
|
if (req.method === 'GET' && planMatch) {
|