dsh-mobile-plugin 0.5.80 → 0.5.82
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/docs/extension-authoring.md +32 -0
- package/lib/frpc/provision.cjs +21 -17
- package/lib/frpc/runner.cjs +193 -165
- package/lib/impl.js +66 -81
- package/lib/mirror/pusher.cjs +60 -10
- package/lib/mobile/auth.js +20 -5
- package/lib/mobile/claim-identity.js +116 -0
- package/lib/mobile/events.js +2 -1
- package/lib/mobile/feedback.js +6 -5
- package/lib/mobile/file-read.js +4 -2
- package/lib/mobile/mux.js +148 -21
- package/lib/mobile/paired-devices.js +2 -1
- package/lib/mobile/pairing.js +3 -2
- package/lib/mobile/permissions.js +2 -0
- package/lib/mobile/relay-control.js +27 -33
- package/lib/mobile/session-changes.js +8 -2
- package/lib/mobile/session-delivery.js +5 -1
- package/lib/mobile/session-file.js +46 -25
- package/lib/mobile/session-head.js +7 -3
- package/lib/mobile/session-snapshot.js +5 -1
- package/lib/mobile/session-step.js +13 -7
- package/lib/mobile/session-stop-summary.js +6 -1
- package/lib/mobile/stream-registry.js +48 -53
- package/lib/mobile/stream.js +17 -2
- package/lib/mobile/uploads.js +190 -163
- package/lib/p2p/session.cjs +169 -70
- package/lib/p2p/wiring.cjs +4 -2
- package/lib/panel/index.html +17 -15
- package/lib/relay/blob-upload.cjs +103 -0
- package/lib/relay/config-store.js +81 -0
- package/lib/relay/control.js +132 -48
- package/lib/relay/core.js +34 -14
- package/lib/relay/identity-rotate.cjs +27 -0
- package/lib/relay/lan-proxy.js +71 -12
- package/lib/relay/pairing-payload.cjs +14 -5
- package/lib/relay/preview-webapp.cjs +150 -0
- package/lib/relay/preview.js +35 -8
- package/lib/relay/protocol.js +6 -4
- package/lib/relay/relay-probe.js +112 -21
- package/lib/relay/tunnel-forwarder.cjs +4 -2
- package/lib/relay/tunnel.js +39 -8
- package/lib/remote/controller.cjs +33 -3
- package/lib/remote/host-control.cjs +11 -2
- package/lib/remote/router.cjs +83 -33
- package/lib/remote/transport.cjs +32 -5
- package/lib/remote/tunnel-helper.cjs +51 -25
- package/lib/remote/tunnels.cjs +27 -3
- package/lib/routes/control-plane.js +25 -17
- package/lib/routes/mobile-api.js +32 -18
- package/lib/shared/fresh-request.js +32 -1
- package/lib/shared/route-order.cjs +118 -132
- package/lib/shared/sse-write.js +29 -10
- package/lib/shared/via-header.js +5 -12
- package/lib/shell/transport-host.js +15 -1
- package/lib/sidecar-facade-worker.cjs +176 -118
- package/lib/sidecar-facade.cjs +6 -1
- package/lib/sidecar-lifecycle.cjs +6 -2
- package/lib/tailcat/host-process.cjs +32 -8
- package/lib/tailcat/session.cjs +27 -10
- package/package.json +6 -6
package/lib/impl.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
//
|
|
1
|
+
// 配置 schema 与投影拆到 lib/relay/config-store.js,装配层只留装配与状态仓外壳(行数兜底)。
|
|
2
|
+
// 装配移动 API、设备吊销与独立直连生命周期,并向本机面板提供真实上报目的地。
|
|
2
3
|
/**
|
|
3
4
|
* 插件实现(随包发布的基础代):装配路由、移动端 API 网关与 sidecar 生命周期。
|
|
4
5
|
* 只做装配——镜像推送在 `lib/mirror/pusher.cjs`、sidecar 生命周期在
|
|
@@ -11,10 +12,10 @@ import { createRequire } from 'node:module'
|
|
|
11
12
|
import os from 'node:os'
|
|
12
13
|
import path from 'node:path'
|
|
13
14
|
import { fileURLToPath } from 'node:url'
|
|
14
|
-
import z from '@deepseek-ai/schemastery'
|
|
15
15
|
|
|
16
16
|
const require = createRequire(import.meta.url)
|
|
17
17
|
const core = require('./relay/core.js')
|
|
18
|
+
const { RemoteControlSettingsSchema, configOf } = require('./relay/config-store.js')
|
|
18
19
|
const pairingApproval = require('./relay/pairing-policy.js')
|
|
19
20
|
const { sendJson, sendHtml, htmlEtag } = require('./shared/http-util.js')
|
|
20
21
|
// 控制面守卫(localOnly)与移动端守卫(guarded)都住在这里;两套守卫并排放,
|
|
@@ -37,6 +38,7 @@ const { lanUrls, advertisedCandidates, phoneCandidates, ipv6Candidates, withManu
|
|
|
37
38
|
const { pairingPayload, pairingText } = require('./relay/pairing-payload.cjs')
|
|
38
39
|
// 总控上报客户端:把本机全部连接地址报给总控、拿回设备令牌(见 lib/relay/control.js)。
|
|
39
40
|
const { createControlClient } = require('./relay/control.js')
|
|
41
|
+
const { createIdentityRotator } = require('./relay/identity-rotate.cjs')
|
|
40
42
|
const { createLanPortPolicy } = require('./relay/lan-port-policy.cjs')
|
|
41
43
|
const { mountTailcat } = require('./tailcat/wiring.cjs') // 直连隧道:入口 + 落点代理 + 助手会话 + 启停
|
|
42
44
|
const { mountP2P } = require('./p2p/wiring.cjs') // 点对点隧道:助手会话 + 落点代理(连接从隧道里进来,不必开回环门)
|
|
@@ -109,77 +111,7 @@ export const inject = ['webServer']
|
|
|
109
111
|
const API_PROXY_GRACE_MS = 3000
|
|
110
112
|
|
|
111
113
|
export const REMOTE_CONTROL_SETTINGS_NAMESPACE = 'mobile-remote-control'
|
|
112
|
-
export
|
|
113
|
-
enabled: z.boolean().default(false),
|
|
114
|
-
relayUrl: z.string().default(''),
|
|
115
|
-
// 完整的中转地址列表,`relayUrls[0]` 恒等于 `relayUrl`(见 docs/relay-multi-address.md)。
|
|
116
|
-
// 这一轮**行为不变**:隧道仍然只按 `relayUrl` 连,列表只是「以后要有地方落」的形状。
|
|
117
|
-
relayUrls: z.array(z.string()).default([]),
|
|
118
|
-
lanEnabled: z.boolean().default(true),
|
|
119
|
-
lanPort: z.number().step(1).min(1024).max(65535).default(18787),
|
|
120
|
-
name: z.string().default(''),
|
|
121
|
-
// Pairing approval policy; see lib/relay/pairing-policy.js for the two modes and
|
|
122
|
-
// why 'code' is not the old popup. Kept in the config schema so /api/relay/config
|
|
123
|
-
// can change it, and so an unknown value is rejected on write.
|
|
124
|
-
pairingPolicy: z.union(pairingApproval.POLICIES.map(value => z.const(value))).default(pairingApproval.DEFAULT_POLICY),
|
|
125
|
-
// 新配对设备的权限档位(只读 / 可答审批 / 全权)。配对时在电脑侧选定,展开成 permissions
|
|
126
|
-
// 写进凭据记录(见 lib/mobile/permissions.js)。缺省 full = 与今天单 token 全给等价。
|
|
127
|
-
pairingTier: z.union(permissions.TIER_NAMES.map(t => z.const(t))).default(permissions.DEFAULT_TIER), approvalAutoReview: z.boolean().default(false), // 审批自动审阅档(默认关,见 mobile/auto-review.js)
|
|
128
|
-
// 是否把本机网络地址加密上报给「总控」(地址目录)。默认开 = 与历史行为一致;
|
|
129
|
-
// 关掉后宿主不再跑总控上报客户端,手机换网后拿不到这台电脑的新地址(见 relay/control.js)。
|
|
130
|
-
controlReportEnabled: z.boolean().default(true),
|
|
131
|
-
// 桌面设置页那两颗侧边栏图标(手机 / 电脑)的可见性。默认全开;老 relay.json 没这两格时
|
|
132
|
-
// 由 configOf 收成 true,界面不会在升级后突然少一颗。只给桌面控制面写,手机端配置口不收。
|
|
133
|
-
desktopPhoneIcon: z.boolean().default(true),
|
|
134
|
-
desktopComputerIcon: z.boolean().default(true),
|
|
135
|
-
// 中转注册密钥(对偶于中转的 TUNNEL_REGISTER_SECRET)。桌面版拿不到 shell
|
|
136
|
-
// 环境变量,所以它和其他配置一样存在 relay.json(0600),由 /api/relay/config
|
|
137
|
-
// 在回环上写入;status / pairing / 二维码都不回显它。
|
|
138
|
-
registerSecret: z.string().max(512).default(''),
|
|
139
|
-
// 手机优先用哪条地址:空 = 不指定(按宿主网卡优先级排)。选择只挪候选顺序、不删候选,
|
|
140
|
-
// 理由与边界见 relay/lan-network.cjs 的 orderCandidates 与 relay.json 那条地图条目。
|
|
141
|
-
preferredLanAddress: z.string().max(64).default(''),
|
|
142
|
-
// 用户手填的直连地址(`manualLanUrl`,内网穿透域名)也随二维码一起走,见 lan-network.cjs。
|
|
143
|
-
manualLanUrl: z.string().max(200).default(''),
|
|
144
|
-
// 用户手填的 IPv6 直连地址(`manualIpv6Url`,形如 `http://[240e::1]:18787`):与上一条并列,
|
|
145
|
-
// 只是拨的是 IPv6;网卡扫不到的那条固定地址靠它兜底,候选口径见 lan-network.cjs。
|
|
146
|
-
manualIpv6Url: z.string().max(200).default(''),
|
|
147
|
-
// 用户手填的「TCP 直连」目标(`manualTcpUrl`,形如 `主机:端口` / `http://主机:端口`,IPv6 方括号)。
|
|
148
|
-
// 与上面两条并列、同样不进 sidecar;它只决定手机用裸 TCP 拨哪个目标(详见 lan-network.cjs)。
|
|
149
|
-
manualTcpUrl: z.string().max(200).default(''),
|
|
150
|
-
})
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
function configOf(state) {
|
|
154
|
-
// 两格必须一起算:`relayUrls` 是完整列表、`relayUrl` 是它的首项(契约见
|
|
155
|
-
// docs/relay-multi-address.md),任何一处只写一个都会让读的一方看到矛盾的两份值。
|
|
156
|
-
const relay = core.relayAddressesOf(state)
|
|
157
|
-
return {
|
|
158
|
-
enabled: Boolean(state.enabled),
|
|
159
|
-
relayUrl: relay.relayUrl,
|
|
160
|
-
relayUrls: relay.relayUrls,
|
|
161
|
-
lanEnabled: Boolean(state.lanEnabled),
|
|
162
|
-
lanPort: Number.isInteger(state.lanPort) ? state.lanPort : 18787,
|
|
163
|
-
name: typeof state.name === 'string' ? state.name : '',
|
|
164
|
-
// The schema rejects anything outside the enum, so in practice this only
|
|
165
|
-
// ever normalises a value written before pairingPolicy existed.
|
|
166
|
-
pairingPolicy: pairingApproval.normalize(state.pairingPolicy),
|
|
167
|
-
pairingTier: permissions.isKnownTier(state.pairingTier) ? state.pairingTier : permissions.DEFAULT_TIER, // 未知值收敛回 full
|
|
168
|
-
approvalAutoReview: state.approvalAutoReview === true, // 非 true 一律当关
|
|
169
|
-
// 只有明确写成 false 才算关;老状态文件没这一格时按开(与历史行为一致)。
|
|
170
|
-
controlReportEnabled: state.controlReportEnabled !== false,
|
|
171
|
-
// 没写过的老配置按显示处理:这两颗是入口,不因为升级就凭空消失。
|
|
172
|
-
desktopPhoneIcon: state.desktopPhoneIcon !== false,
|
|
173
|
-
desktopComputerIcon: state.desktopComputerIcon !== false,
|
|
174
|
-
// 密钥只往 sidecar 和状态文件走:status() / pairingPayload() 都单独取字段,
|
|
175
|
-
// 不会把它回显给手机、二维码或日志。
|
|
176
|
-
registerSecret: typeof state.registerSecret === 'string' ? state.registerSecret : '',
|
|
177
|
-
preferredLanAddress: typeof state.preferredLanAddress === 'string' ? state.preferredLanAddress : '',
|
|
178
|
-
manualLanUrl: typeof state.manualLanUrl === 'string' ? state.manualLanUrl : '',
|
|
179
|
-
manualIpv6Url: typeof state.manualIpv6Url === 'string' ? state.manualIpv6Url : '',
|
|
180
|
-
manualTcpUrl: typeof state.manualTcpUrl === 'string' ? state.manualTcpUrl : '',
|
|
181
|
-
}
|
|
182
|
-
}
|
|
114
|
+
export { RemoteControlSettingsSchema }
|
|
183
115
|
|
|
184
116
|
// 0.2.0 之前这份配置注册在宿主 settings 的 `mobile-remote-control` 命名空间里
|
|
185
117
|
// (`ctx.settings.register(ns, schema, { base: configOf(state), applies: 'live' })`),
|
|
@@ -232,6 +164,7 @@ function createConfigStore(state) {
|
|
|
232
164
|
// 函数),否则界面说停用了、实际还在连公用。放在收敛之后、落盘之前,保证
|
|
233
165
|
// relayUrls[0] === relayUrl 的不变式与「真停用」一起成立。
|
|
234
166
|
core.stripPublicRelay(parsed)
|
|
167
|
+
core.expandDefaultPublicRelays(parsed)
|
|
235
168
|
Object.assign(state, parsed)
|
|
236
169
|
core.saveState(state)
|
|
237
170
|
if (options.notify !== false) notify()
|
|
@@ -366,7 +299,7 @@ function apply(ctx) {
|
|
|
366
299
|
const lanPorts = createLanPortPolicy({ state, saveState: core.saveState })
|
|
367
300
|
const lanPortInUse = lanPorts.port
|
|
368
301
|
const resolveLanPort = lanPorts.resolve
|
|
369
|
-
const advertisedLanPort = () =>
|
|
302
|
+
const advertisedLanPort = () => sidecarLifecycle.getAdvertisedLanPort()
|
|
370
303
|
// 总控上报客户端:把本机全部地址报给总控,拿回设备令牌交给 APP(见 relay/control.js)。
|
|
371
304
|
// 生命周期挂在下面的 effect 上;配置变更由 applyServices → control.sync() 驱动。
|
|
372
305
|
// 隧道状态取值器在下面 sidecar 装配完成后才拿到,这里先放占位,装配完换成权威那个。
|
|
@@ -390,7 +323,12 @@ function apply(ctx) {
|
|
|
390
323
|
// sidecar 子进程的全部生命周期:起停、配置下发、自重启、健康轮询。
|
|
391
324
|
// **传输进程归稳定外壳**:优先取外壳持有的那份(换代时它不重启,隧道跨代存活);外壳不在
|
|
392
325
|
// (实现被单独挂载 / 测试)时退回本地创建,行为与从前一致。配置由这一代组装后交给它。
|
|
393
|
-
|
|
326
|
+
// 父进程地址在这一代挂载时取一次缓存住。下发配置的闭包会被外壳持有的 sidecar 跨代调用,
|
|
327
|
+
// 那时本代 ctx 已 inactive,现读 ctx.webServer 会抛 "cannot get required service webServer
|
|
328
|
+
// in inactive context",导致重启与配置下发全失败(隧道、frpc、P2P 都起不来)。
|
|
329
|
+
const webPortForSidecar = ctx.webServer.port
|
|
330
|
+
const webHostForSidecar = ctx.webServer.host
|
|
331
|
+
const buildSidecarConfig = (lanPort) => ({ enabled: state.enabled, relayUrl: state.relayUrl, relayUrls: core.relayAddressesOf(state).relayUrls, instanceId: state.instanceId, previousInstanceId: state.previousInstanceId || '', pairingCode: state.pairingCode, pairingTicket: state.pairingTicket || '', pairingTier: permissions.isKnownTier(state.pairingTier) ? state.pairingTier : permissions.DEFAULT_TIER, name: state.name, upstreamPort: webPortForSidecar, upstreamHost: webHostForSidecar, lanPort, lanEnabled: effectiveLanEnabled(), lanSecret: state.lanSecret, registerSecret: state.registerSecret })
|
|
394
332
|
let hostedSidecar = null
|
|
395
333
|
try { hostedSidecar = typeof ctx.get === 'function' ? ctx.get('dshMobileSidecarHost') || null : null } catch { hostedSidecar = null }
|
|
396
334
|
const sidecarLifecycle = hostedSidecar || createSidecarLifecycle({
|
|
@@ -423,6 +361,9 @@ function apply(ctx) {
|
|
|
423
361
|
const { sidecarToken, syncSidecar, restartSidecar, tunnelConnected } = sidecarLifecycle
|
|
424
362
|
relayConnectedOf = tunnelConnected
|
|
425
363
|
|
|
364
|
+
// 身份冲突时换身份:实现在 relay/identity-rotate.cjs,装配层只把它挂上(含重入保护)。
|
|
365
|
+
const rotateNow = createIdentityRotator({ state, rotateIdentity: core.rotateIdentity, saveState: core.saveState, syncSidecar, syncControl: () => control.sync() })
|
|
366
|
+
|
|
426
367
|
// 总控上报:优先用**稳定外壳**持有的那份(换代不断开上报连接);外壳不在时本地创建兜底。
|
|
427
368
|
// getPort 依赖上面刚就位的 sidecar/advertisedLanPort,所以放在这里建。
|
|
428
369
|
let controlHost = null
|
|
@@ -433,6 +374,9 @@ function apply(ctx) {
|
|
|
433
374
|
getPort: advertisedLanPort,
|
|
434
375
|
getHistoryKey: () => core.ensureHistoryKey(state),
|
|
435
376
|
getRelayConnected: () => relayConnectedOf(),
|
|
377
|
+
getConnectedRelay: () => { const tunnel = sidecarLifecycle.getSnapshot()?.tunnel; return tunnel?.state === 'connected' ? tunnel.relayUrl || tunnel.route?.url || '' : '' },
|
|
378
|
+
log: warn,
|
|
379
|
+
onIdentityConflict: rotateNow,
|
|
436
380
|
})
|
|
437
381
|
if (controlHost && controlHost.client && typeof controlHost.setProviders === 'function') {
|
|
438
382
|
controlHost.setProviders({
|
|
@@ -441,6 +385,8 @@ function apply(ctx) {
|
|
|
441
385
|
getPort: advertisedLanPort,
|
|
442
386
|
getHistoryKey: () => core.ensureHistoryKey(state),
|
|
443
387
|
getRelayConnected: () => relayConnectedOf(),
|
|
388
|
+
getConnectedRelay: () => { const tunnel = sidecarLifecycle.getSnapshot()?.tunnel; return tunnel?.state === 'connected' ? tunnel.relayUrl || tunnel.route?.url || '' : '' },
|
|
389
|
+
onIdentityConflict: rotateNow,
|
|
444
390
|
})
|
|
445
391
|
}
|
|
446
392
|
|
|
@@ -563,6 +509,14 @@ function apply(ctx) {
|
|
|
563
509
|
try { frpHost = typeof ctx.get === 'function' ? ctx.get('dshMobileTransportFrp') || null : null } catch { frpHost = null }
|
|
564
510
|
const frpRunner = frpHost && frpHost.runner ? frpHost.runner : createFrpcRunner({ portOf: advertisedLanPort })
|
|
565
511
|
if (frpHost && typeof frpHost.setPortProvider === 'function') frpHost.setPortProvider(advertisedLanPort)
|
|
512
|
+
mount('frpc 公网地址', () => ctx.effect(() => {
|
|
513
|
+
if (typeof frpRunner.setAddressListener !== 'function') return () => {}
|
|
514
|
+
frpRunner.setAddressListener(async (address, isCurrent) => {
|
|
515
|
+
if (!isCurrent() || state.manualTcpUrl === address) return
|
|
516
|
+
await settings.update({ manualTcpUrl: address })
|
|
517
|
+
})
|
|
518
|
+
return () => frpRunner.setAddressListener(null)
|
|
519
|
+
}, `${name}: frpc address`))
|
|
566
520
|
if (!(frpHost && frpHost.runner)) {
|
|
567
521
|
mount('frpc 直连进程', () => ctx.effect(() => {
|
|
568
522
|
if (frpRunner.shouldAutoStart()) void frpRunner.start()
|
|
@@ -570,6 +524,14 @@ function apply(ctx) {
|
|
|
570
524
|
}, `${name}: frpc runner`))
|
|
571
525
|
}
|
|
572
526
|
|
|
527
|
+
// closed按唯一连接计数;仅承载本次回执的mux由service有界排空后关闭。
|
|
528
|
+
const dropDeviceStreams = (deviceId, res) => {
|
|
529
|
+
return streamRegistry.drop(deviceId, state.instanceId)
|
|
530
|
+
+ preview.dropDevice(deviceId, state.instanceId)
|
|
531
|
+
+ (mux.dropDevice?.(deviceId, state.instanceId, res) || 0)
|
|
532
|
+
}
|
|
533
|
+
const dropAllDeviceStreams = (res) => streamRegistry.dropAll(state.instanceId) + preview.dropAll(state.instanceId) + (mux.dropAll?.(state.instanceId, res) || 0)
|
|
534
|
+
|
|
573
535
|
mount('控制面路由', () => registerControlPlaneRoutes({
|
|
574
536
|
registerRoute,
|
|
575
537
|
// 更新的机制住在外壳(`lib/index.js`)里,代这边只把它开成本机接口。取不到就如实报
|
|
@@ -600,6 +562,7 @@ function apply(ctx) {
|
|
|
600
562
|
p2p,
|
|
601
563
|
// FRP 直连:导入配置后的启停与运行状态(见 lib/frpc/runner.cjs)。
|
|
602
564
|
frp: frpRunner,
|
|
565
|
+
getControlTargetUrl: () => control.targetUrl,
|
|
603
566
|
restartSidecar,
|
|
604
567
|
// 「手机上最近来过没有」——控制面状态里补给面板用(见 ./mobile/activity.cjs)。
|
|
605
568
|
mobileActivity: activity.snapshot,
|
|
@@ -615,7 +578,8 @@ function apply(ctx) {
|
|
|
615
578
|
getLanProxyStats: () => sidecarLifecycle.getSnapshot()?.streams?.lan ?? null,
|
|
616
579
|
// 吊销时收掉这台设备已经开着的流(§3.3):token 换了只保证「下一次请求」被拒,
|
|
617
580
|
// 一条已经开着的 SSE 不会自己停,被踢的手机还能继续收消息直到它自己重连。
|
|
618
|
-
dropDeviceStreams
|
|
581
|
+
dropDeviceStreams,
|
|
582
|
+
dropAllDeviceStreams,
|
|
619
583
|
}))
|
|
620
584
|
|
|
621
585
|
|
|
@@ -627,7 +591,13 @@ function apply(ctx) {
|
|
|
627
591
|
* 主进程里可写。
|
|
628
592
|
*/
|
|
629
593
|
const envelope = {
|
|
630
|
-
keyFor: (keyId) =>
|
|
594
|
+
keyFor: (keyId) => {
|
|
595
|
+
const live = credentials.findByKeyId(state.instanceId, keyId)
|
|
596
|
+
if (live) return live
|
|
597
|
+
// 换身份的过渡期:还没换过来的手机仍按旧号的 keyId 签名。
|
|
598
|
+
const prev = typeof state.previousInstanceId === 'string' ? state.previousInstanceId : ''
|
|
599
|
+
return prev ? credentials.findByKeyId(prev, keyId) : null
|
|
600
|
+
},
|
|
631
601
|
readBody: (req) => readRawBody(req),
|
|
632
602
|
}
|
|
633
603
|
const guarded = createGuarded(ctx, authOutcome, activity.note, {
|
|
@@ -655,7 +625,13 @@ function apply(ctx) {
|
|
|
655
625
|
// `ownWebPort` 是同一条边界上的唯一例外:用户显式要求手机能打开网页版(2026-11-03),
|
|
656
626
|
// 所以 `mode=webapp` 那一档只放行这一个端口(且目标必须是环回)。同样用取值器。
|
|
657
627
|
const preview = createPreviewService({
|
|
658
|
-
authorized
|
|
628
|
+
authorized: (req) => {
|
|
629
|
+
const outcome = authOutcome(req)
|
|
630
|
+
if (!outcome.ok) return false
|
|
631
|
+
req.__dshRecord = outcome.record
|
|
632
|
+
req.__dshInstanceId = state.instanceId
|
|
633
|
+
return true
|
|
634
|
+
},
|
|
659
635
|
protectedPorts: () => {
|
|
660
636
|
const ports = new Set([ctx.webServer.port, lanPortInUse()])
|
|
661
637
|
ports.delete(0)
|
|
@@ -670,8 +646,14 @@ function apply(ctx) {
|
|
|
670
646
|
// 对话页长连接(mux):一条手机 WS 上按 id 多路复用,逐条转成本地回环请求打到移动 API。
|
|
671
647
|
// 鉴权口径与预览升级路由同一套(设备凭据有效即可);逐路由权限仍由回环 HTTP 的 guarded 判,
|
|
672
648
|
// mux 只是搬运工,不另立权限面。帧契约见 `docs/mux-long-connection-design.md` §11。
|
|
673
|
-
const
|
|
674
|
-
|
|
649
|
+
const muxAuthorize = (req) => {
|
|
650
|
+
try {
|
|
651
|
+
const outcome = authOutcome(req)
|
|
652
|
+
if (!outcome.ok || !outcome.record) return false
|
|
653
|
+
req.__dshRecord = outcome.record
|
|
654
|
+
return true
|
|
655
|
+
} catch { return false }
|
|
656
|
+
}
|
|
675
657
|
// mux 优先用**稳定外壳**持有的那份(换代时已建立的手机 WS 不断);外壳不在时本地创建兜底。
|
|
676
658
|
// 升级路由由外壳直接挂(见 shell/transport-host.js),这一代不再重复注册。
|
|
677
659
|
let muxHost = null
|
|
@@ -723,7 +705,8 @@ function apply(ctx) {
|
|
|
723
705
|
// 「这台电脑上还连着哪些手机」的两条路由(见 mobile/paired-devices.js):凭据库真源 +
|
|
724
706
|
// 吊销时收掉被踢设备在途的 SSE。
|
|
725
707
|
credentials,
|
|
726
|
-
dropDeviceStreams
|
|
708
|
+
dropDeviceStreams,
|
|
709
|
+
dropAllDeviceStreams,
|
|
727
710
|
// 取值器而非快照对象:snapshot 会被 applySidecarConfig 整体替换,闭包捕获对象会让
|
|
728
711
|
// 连接信息永远停在进程启动那一刻。
|
|
729
712
|
getSidecarSnapshot: sidecarLifecycle.getSnapshot,
|
|
@@ -758,6 +741,8 @@ function apply(ctx) {
|
|
|
758
741
|
getSidecar: sidecarLifecycle.getSidecar,
|
|
759
742
|
credentials,
|
|
760
743
|
activeGuard,
|
|
744
|
+
dropDeviceStreams,
|
|
745
|
+
dropAllDeviceStreams,
|
|
761
746
|
},
|
|
762
747
|
}))
|
|
763
748
|
mount('服务同步', () => ctx.effect(() => {
|
package/lib/mirror/pusher.cjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// blob后台轮次绑定effect代次,停止后不续发旧快照或记录迟到确认。
|
|
1
2
|
'use strict';
|
|
2
3
|
|
|
3
4
|
/**
|
|
@@ -355,7 +356,7 @@ function createMirrorPusher(deps) {
|
|
|
355
356
|
*
|
|
356
357
|
* `scope=file` 的 key 按当初记账的归属会话一起删。
|
|
357
358
|
*/
|
|
358
|
-
const deleteRemovedSessionBlobs = async (sidecar) => {
|
|
359
|
+
const deleteRemovedSessionBlobs = async (sidecar, isCurrent) => {
|
|
359
360
|
if (typeof sidecar.deleteBlobs !== 'function') return;
|
|
360
361
|
const deleted = deletedSessionIdsOf(ctx);
|
|
361
362
|
if (!deleted || deleted.size === 0) return;
|
|
@@ -366,22 +367,28 @@ function createMirrorPusher(deps) {
|
|
|
366
367
|
.filter(([, rec]) => rec && goneSet.has(rec.sessionId))
|
|
367
368
|
.map(([key]) => key);
|
|
368
369
|
for (let i = 0; i < goneMessages.length; i += MAX_DELETE_KEYS_PER_FRAME) {
|
|
370
|
+
if (!isCurrent()) return;
|
|
369
371
|
const keys = goneMessages.slice(i, i + MAX_DELETE_KEYS_PER_FRAME);
|
|
370
372
|
try {
|
|
371
373
|
await sidecar.deleteBlobs({ scope: 'messages', keys });
|
|
374
|
+
if (!isCurrent()) return;
|
|
372
375
|
for (const key of keys) pushedMessageBlobs.delete(key);
|
|
373
376
|
blobLogClear(`delete:messages:${keys[0]}`);
|
|
374
377
|
} catch (error) {
|
|
378
|
+
if (!isCurrent()) return;
|
|
375
379
|
blobLog(`delete:messages:${keys[0]}`, errorText(error));
|
|
376
380
|
}
|
|
377
381
|
}
|
|
378
382
|
for (let i = 0; i < goneFiles.length; i += MAX_DELETE_KEYS_PER_FRAME) {
|
|
383
|
+
if (!isCurrent()) return;
|
|
379
384
|
const keys = goneFiles.slice(i, i + MAX_DELETE_KEYS_PER_FRAME);
|
|
380
385
|
try {
|
|
381
386
|
await sidecar.deleteBlobs({ scope: 'file', keys });
|
|
387
|
+
if (!isCurrent()) return;
|
|
382
388
|
for (const key of keys) pushedFileBlobs.delete(key);
|
|
383
389
|
blobLogClear(`delete:file:${keys[0]}`);
|
|
384
390
|
} catch (error) {
|
|
391
|
+
if (!isCurrent()) return;
|
|
385
392
|
blobLog(`delete:file:${keys[0]}`, errorText(error));
|
|
386
393
|
}
|
|
387
394
|
}
|
|
@@ -398,17 +405,41 @@ function createMirrorPusher(deps) {
|
|
|
398
405
|
* `MAX_BLOB_MESSAGE_FRAMES_PER_ROUND` 条、文件最多 `MAX_BLOB_FILE_FRAMES_PER_ROUND` 条,
|
|
399
406
|
* 超出的下一轮再推。
|
|
400
407
|
*/
|
|
401
|
-
|
|
408
|
+
let blobRoundRunning = false;
|
|
409
|
+
let blobStopped = false;
|
|
410
|
+
let blobGeneration = 0;
|
|
411
|
+
let nextBlobRound = null;
|
|
412
|
+
const scheduleHistoryBlobs = (payload, creds) => {
|
|
413
|
+
if (blobStopped) return;
|
|
414
|
+
// 只保留最新一份待办,不让慢上行阻塞镜像tick、revision广播或堆积快照。
|
|
415
|
+
nextBlobRound = { payload, creds, generation: blobGeneration };
|
|
416
|
+
if (blobRoundRunning) return;
|
|
417
|
+
blobRoundRunning = true;
|
|
418
|
+
const run = async () => {
|
|
419
|
+
try {
|
|
420
|
+
while (!blobStopped && nextBlobRound) {
|
|
421
|
+
const round = nextBlobRound;
|
|
422
|
+
nextBlobRound = null;
|
|
423
|
+
await pushHistoryBlobs(round.payload, round.creds, round.generation);
|
|
424
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
425
|
+
}
|
|
426
|
+
} finally { blobRoundRunning = false; }
|
|
427
|
+
};
|
|
428
|
+
void run();
|
|
429
|
+
};
|
|
430
|
+
const pushHistoryBlobs = async (payload, creds, generation) => {
|
|
402
431
|
// blob 是加法:它自己炸了不许把一次已经成功的镜像推送翻成失败(调用方会把异常记成
|
|
403
432
|
// 推送失败)。所以整趟兜一层,失败只留一行诊断。
|
|
404
433
|
try {
|
|
405
|
-
await pushHistoryBlobsUnlocked(payload, creds);
|
|
434
|
+
await pushHistoryBlobsUnlocked(payload, creds, generation);
|
|
406
435
|
} catch (error) {
|
|
407
436
|
blobLog('round', errorText(error));
|
|
408
437
|
}
|
|
409
438
|
};
|
|
410
439
|
|
|
411
|
-
const pushHistoryBlobsUnlocked = async (payload, creds) => {
|
|
440
|
+
const pushHistoryBlobsUnlocked = async (payload, creds, generation) => {
|
|
441
|
+
const isCurrent = () => !blobStopped && generation === blobGeneration;
|
|
442
|
+
if (!isCurrent()) return;
|
|
412
443
|
let hk = '';
|
|
413
444
|
try { hk = getHistoryKey() || ''; } catch { hk = ''; }
|
|
414
445
|
if (!hk) return;
|
|
@@ -435,7 +466,8 @@ function createMirrorPusher(deps) {
|
|
|
435
466
|
}
|
|
436
467
|
blobHistoryKey = hk;
|
|
437
468
|
|
|
438
|
-
await deleteRemovedSessionBlobs(sidecar);
|
|
469
|
+
await deleteRemovedSessionBlobs(sidecar, isCurrent);
|
|
470
|
+
if (!isCurrent()) return;
|
|
439
471
|
|
|
440
472
|
// 一台设备凭据都没有(还没配对过 / 刚吊销完):推上去也没人能拉,中转那边还要求 creds
|
|
441
473
|
// 非空。删除已经在上面做过了,剩下的不发,省得每轮撞一条注定被拒的帧。
|
|
@@ -454,8 +486,14 @@ function createMirrorPusher(deps) {
|
|
|
454
486
|
for (let i = 0; i < targets.length; i += MAX_CREDS_ONLY_BATCH) {
|
|
455
487
|
const batch = targets.slice(i, i + MAX_CREDS_ONLY_BATCH);
|
|
456
488
|
for (const target of batch) {
|
|
457
|
-
|
|
458
|
-
|
|
489
|
+
if (!isCurrent()) return;
|
|
490
|
+
try {
|
|
491
|
+
await sidecar.pushBlob({ ...target, creds: digestList, cipher: '' });
|
|
492
|
+
if (!isCurrent()) return;
|
|
493
|
+
} catch (error) {
|
|
494
|
+
if (!isCurrent()) return;
|
|
495
|
+
allOk = false; blobLog(`creds:${target.scope}:${target.key}`, errorText(error));
|
|
496
|
+
}
|
|
459
497
|
}
|
|
460
498
|
if (!allOk) break; // 下一轮再来,别在这一轮把 stderr 刷满
|
|
461
499
|
}
|
|
@@ -469,6 +507,7 @@ function createMirrorPusher(deps) {
|
|
|
469
507
|
let fileBudget = MAX_BLOB_FILE_FRAMES_PER_ROUND;
|
|
470
508
|
const messages = payload && payload.messages && typeof payload.messages === 'object' ? payload.messages : {};
|
|
471
509
|
for (const [sessionId, body] of Object.entries(messages)) {
|
|
510
|
+
if (!isCurrent()) return;
|
|
472
511
|
if (messageBudget <= 0) break;
|
|
473
512
|
if (!canMessages) break;
|
|
474
513
|
if (!isBlobEligible(body)) continue;
|
|
@@ -481,10 +520,12 @@ function createMirrorPusher(deps) {
|
|
|
481
520
|
catch (error) { blobLog(`build:messages:${sessionId}`, errorText(error)); continue; }
|
|
482
521
|
try {
|
|
483
522
|
await sidecar.pushBlob(frame);
|
|
523
|
+
if (!isCurrent()) return;
|
|
484
524
|
pushedMessageBlobs.set(sessionId, { fingerprint });
|
|
485
525
|
blobLogClear(`put:messages:${sessionId}`);
|
|
486
526
|
messageBudget -= 1;
|
|
487
527
|
} catch (error) {
|
|
528
|
+
if (!isCurrent()) return;
|
|
488
529
|
blobLog(`put:messages:${sessionId}`, errorText(error));
|
|
489
530
|
}
|
|
490
531
|
}
|
|
@@ -495,6 +536,7 @@ function createMirrorPusher(deps) {
|
|
|
495
536
|
// 这一段今天在 `history-blob.cjs` 里没有生产者(见 decisions 里 d2838e82 那条:文件 scope
|
|
496
537
|
// 「今天没有」),所以 `canFiles` 为假时整段不跑 —— 不跑不等于没写,真接上了这里自己就通。
|
|
497
538
|
for (const source of (canFiles ? collectFileBlobSources(payload) : [])) {
|
|
539
|
+
if (!isCurrent()) return;
|
|
498
540
|
if (fileBudget <= 0) break;
|
|
499
541
|
const stat = statFileSource(source);
|
|
500
542
|
if (!stat) continue;
|
|
@@ -514,11 +556,13 @@ function createMirrorPusher(deps) {
|
|
|
514
556
|
catch (error) { blobLog(`build:file:${source.key}`, errorText(error)); continue; }
|
|
515
557
|
try {
|
|
516
558
|
await sidecar.pushBlob(frame);
|
|
559
|
+
if (!isCurrent()) return;
|
|
517
560
|
pushedFileBlobs.set(source.key, { fingerprint, sessionId: source.sessionId });
|
|
518
561
|
blobLogClear(`put:file:${source.key}`);
|
|
519
562
|
blobLogClear(`file-too-large:${source.key}`);
|
|
520
563
|
fileBudget -= 1;
|
|
521
564
|
} catch (error) {
|
|
565
|
+
if (!isCurrent()) return;
|
|
522
566
|
blobLog(`put:file:${source.key}`, errorText(error));
|
|
523
567
|
}
|
|
524
568
|
}
|
|
@@ -555,7 +599,7 @@ function createMirrorPusher(deps) {
|
|
|
555
599
|
// 镜像判重跳过时**仍然过一遍 blob**:blob 自己有指纹判重(推成功才记账),所以这里
|
|
556
600
|
// 通常一条都不发;但上一轮 blob 推送失败、或设备集合刚变过,就得靠这一趟补上 ——
|
|
557
601
|
// 否则镜像内容不变的那些轮次里,失败的 blob 永远等不到重试。
|
|
558
|
-
|
|
602
|
+
scheduleHistoryBlobs(payload, payload.creds);
|
|
559
603
|
return false;
|
|
560
604
|
}
|
|
561
605
|
try {
|
|
@@ -568,7 +612,7 @@ function createMirrorPusher(deps) {
|
|
|
568
612
|
lastPushedCreds = credsKey;
|
|
569
613
|
recordMirrorPush(true, null)
|
|
570
614
|
// 镜像已落地之后再推历史 blob:同一份载荷、同一批凭据摘要。失败不影响上面这次成功。
|
|
571
|
-
|
|
615
|
+
scheduleHistoryBlobs(payload, payload.creds);
|
|
572
616
|
// 基准只在真的推进去(或被判重跳过)之后才前移:推送失败必须能在下一轮重试,
|
|
573
617
|
// 否则「清单变了」会被一次失败吃掉,中转镜像永远停在旧版(见 processBgQueue 的门)。
|
|
574
618
|
lastPushedListRevision = listRevision;
|
|
@@ -1139,6 +1183,8 @@ function createMirrorPusher(deps) {
|
|
|
1139
1183
|
|
|
1140
1184
|
/** 返回 effect 的清理函数,交给 index.js 用 ctx.effect 挂载(与原有形状一致)。 */
|
|
1141
1185
|
const start = () => {
|
|
1186
|
+
const generation = ++blobGeneration;
|
|
1187
|
+
blobStopped = false;
|
|
1142
1188
|
let disposed = false;
|
|
1143
1189
|
const ac = new AbortController();
|
|
1144
1190
|
void (async () => {
|
|
@@ -1190,7 +1236,11 @@ function createMirrorPusher(deps) {
|
|
|
1190
1236
|
// 已经 clearInterval,unref 是给「宿主进程要退出、effect 清理还没轮到」的那一瞬间兜底。
|
|
1191
1237
|
if (bgTimer && typeof bgTimer.unref === 'function') bgTimer.unref();
|
|
1192
1238
|
void pushMirror();
|
|
1193
|
-
return () => {
|
|
1239
|
+
return () => {
|
|
1240
|
+
disposed = true;
|
|
1241
|
+
if (generation === blobGeneration) { blobStopped = true; blobGeneration += 1; nextBlobRound = null; }
|
|
1242
|
+
ac.abort(); clearInterval(bgTimer);
|
|
1243
|
+
};
|
|
1194
1244
|
};
|
|
1195
1245
|
|
|
1196
1246
|
return {
|
package/lib/mobile/auth.js
CHANGED
|
@@ -31,12 +31,22 @@ function loadRelayState() {
|
|
|
31
31
|
}
|
|
32
32
|
}
|
|
33
33
|
|
|
34
|
-
/**
|
|
34
|
+
/** 本机此刻认的实例号:换身份的过渡期里新号 + 旧号都在(见 core.rotateIdentity)。 */
|
|
35
|
+
function instanceIdsOf(state) {
|
|
36
|
+
const ids = [];
|
|
37
|
+
const cur = state && typeof state.instanceId === 'string' ? state.instanceId.trim() : '';
|
|
38
|
+
const prev = state && typeof state.previousInstanceId === 'string' ? state.previousInstanceId.trim() : '';
|
|
39
|
+
if (cur) ids.push(cur);
|
|
40
|
+
if (prev && prev !== cur) ids.push(prev);
|
|
41
|
+
return ids;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** 校验旧的无状态移动 token:`<instanceId>.<exp>.<hmac(lanSecret)>`。新旧号都试。 */
|
|
35
45
|
function verifyMobileToken(token) {
|
|
36
46
|
if (!token) return false;
|
|
37
47
|
const state = loadRelayState();
|
|
38
|
-
if (!state || !state.lanSecret
|
|
39
|
-
return sharedToken.verifyLanToken(state.lanSecret, token,
|
|
48
|
+
if (!state || !state.lanSecret) return false;
|
|
49
|
+
return instanceIdsOf(state).some((id) => sharedToken.verifyLanToken(state.lanSecret, token, id));
|
|
40
50
|
}
|
|
41
51
|
|
|
42
52
|
/**
|
|
@@ -77,7 +87,12 @@ function authOutcome(req) {
|
|
|
77
87
|
if (presented) {
|
|
78
88
|
const state = loadRelayState();
|
|
79
89
|
if (state && state.instanceId) {
|
|
80
|
-
|
|
90
|
+
// 过渡期里同一台手机的凭据可能还挂在旧号下(换身份尚未完成),新旧号都查一遍。
|
|
91
|
+
let known = null;
|
|
92
|
+
for (const id of instanceIdsOf(state)) {
|
|
93
|
+
known = credentials.lookup(presented, id);
|
|
94
|
+
if (known) break;
|
|
95
|
+
}
|
|
81
96
|
if (known) {
|
|
82
97
|
if (known.revokedAt) return { ok: false, reason: 'revoked' };
|
|
83
98
|
if (known.expiresAt && known.expiresAt <= Date.now()) return { ok: false, reason: 'expired' };
|
|
@@ -95,4 +110,4 @@ function authOutcome(req) {
|
|
|
95
110
|
return { ok: false, reason: 'unauthorized' };
|
|
96
111
|
}
|
|
97
112
|
|
|
98
|
-
module.exports = { loadRelayState, presentedCredential, verifyMobileToken, authorized, authOutcome };
|
|
113
|
+
module.exports = { loadRelayState, presentedCredential, verifyMobileToken, authorized, authOutcome, instanceIdsOf };
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 认领当前身份:`POST /api/mobile/v1/device-credential/sync-identity`。
|
|
5
|
+
*
|
|
6
|
+
* 场景是「换身份」的过渡期:宿主把实例号从旧号换成新号后,已配对的手机手上的凭据还挂在
|
|
7
|
+
* 旧号下(凭据串整串哈希查库,改号那枚就查不到了)。这条接口让手机用**旧号下仍有效的凭据**
|
|
8
|
+
* 换一枚**当前号**的新凭据:deviceKey / keyId / 权限 / 设备信息原样继承,旧记录**不立刻吊销**
|
|
9
|
+
* (手机可能还没把新的存下来,立刻吊销会把它锁在门外——与 credential-upgrade 同一口径)。
|
|
10
|
+
*
|
|
11
|
+
* 鉴权在路由守卫那层完成(它已经同时认新旧号,见 mobile/auth.js 的 instanceIdsOf);这里只
|
|
12
|
+
* 按出示的凭据反查记录,判断它挂在当前号还是旧号:
|
|
13
|
+
* - 已是当前号 → 原样返回出示的那一枚(幂等,续期交给鉴权顺手做);
|
|
14
|
+
* - 挂在旧号 → 按当前号重签一枚返回(供 APP 复用 upgrade 那套 patch 逻辑原子替换)。
|
|
15
|
+
*
|
|
16
|
+
* 响应形状与 `device-credential/upgrade` 对齐:`{ ok, instanceId, token, cookie,
|
|
17
|
+
* deviceCredential, keyId?, permissions?, credentialExpiresAt, serverTime }`。
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const { sendJson } = require('../shared/http-util.js');
|
|
21
|
+
const permissions = require('./permissions.js');
|
|
22
|
+
const { presentedCredential } = require('./credential-upgrade.js');
|
|
23
|
+
|
|
24
|
+
/** 一条记录的有效权限位:设过就照抄,没设过(老记录)按全权回。 */
|
|
25
|
+
function effectivePermissions(record) {
|
|
26
|
+
return Array.isArray(record && record.permissions) ? record.permissions.slice() : permissions.permissionsForTier('full');
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** 从记录里挑出重建凭据要继承的设备元信息。 */
|
|
30
|
+
function deviceMetaOf(record) {
|
|
31
|
+
const src = record && typeof record === 'object' ? record : {};
|
|
32
|
+
const meta = {};
|
|
33
|
+
for (const key of ['deviceId', 'name', 'model', 'platform', 'osVersion', 'appVersion', 'packageId', 'buildNumber', 'channel']) {
|
|
34
|
+
if (typeof src[key] === 'string' && src[key]) meta[key] = src[key];
|
|
35
|
+
}
|
|
36
|
+
return meta;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** 一枚凭据对应的 cookie 值(与 upgrade 回包同口径)。 */
|
|
40
|
+
function cookieOf(token) {
|
|
41
|
+
return 'dsh_lan=' + token;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 处理认领当前身份。
|
|
46
|
+
*
|
|
47
|
+
* @param {object} req
|
|
48
|
+
* @param {object} res
|
|
49
|
+
* @param {{ instanceId: string, previousInstanceId?: string, store: object }} deps
|
|
50
|
+
*/
|
|
51
|
+
async function handleSyncIdentity(req, res, deps) {
|
|
52
|
+
const currentId = String((deps && deps.instanceId) || '');
|
|
53
|
+
const previousId = String((deps && deps.previousInstanceId) || '');
|
|
54
|
+
const store = deps && deps.store;
|
|
55
|
+
if (!store || !currentId) {
|
|
56
|
+
return sendJson(res, 503, { ok: false, error: { code: 'unavailable', message: '凭据库不可用' } });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const presented = presentedCredential(req);
|
|
60
|
+
if (!presented) {
|
|
61
|
+
return sendJson(res, 401, { ok: false, error: { code: 'unauthorized', message: '缺少凭据' } });
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// 出示的凭据挂在哪个号下:当前号优先,再试旧号(过渡期手机还没换过来)。
|
|
65
|
+
const ids = [currentId, previousId].filter((id, index, all) => id && all.indexOf(id) === index);
|
|
66
|
+
let record = null;
|
|
67
|
+
let ownerId = '';
|
|
68
|
+
for (const id of ids) {
|
|
69
|
+
const found = store.lookup(presented, id);
|
|
70
|
+
if (found) { record = found; ownerId = id; break; }
|
|
71
|
+
}
|
|
72
|
+
if (!record) {
|
|
73
|
+
return sendJson(res, 401, { ok: false, error: { code: 'unauthorized', message: '凭据无法识别' } });
|
|
74
|
+
}
|
|
75
|
+
if (record.revokedAt) {
|
|
76
|
+
return sendJson(res, 401, { ok: false, error: { code: 'revoked', message: '凭据已失效' } });
|
|
77
|
+
}
|
|
78
|
+
if (record.expiresAt && record.expiresAt <= Date.now()) {
|
|
79
|
+
return sendJson(res, 401, { ok: false, error: { code: 'expired', message: '凭据已过期' } });
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// 已经是当前号:幂等返回出示的那一枚。
|
|
83
|
+
if (ownerId === currentId) {
|
|
84
|
+
return sendJson(res, 200, {
|
|
85
|
+
ok: true,
|
|
86
|
+
instanceId: currentId,
|
|
87
|
+
token: presented,
|
|
88
|
+
cookie: cookieOf(presented),
|
|
89
|
+
deviceCredential: presented,
|
|
90
|
+
...(typeof record.keyId === 'string' && record.keyId ? { keyId: record.keyId } : {}),
|
|
91
|
+
permissions: effectivePermissions(record),
|
|
92
|
+
credentialExpiresAt: record.expiresAt || null,
|
|
93
|
+
serverTime: Date.now(),
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// 挂在旧号下:按当前号重签一枚,继承设备密钥 / 权限 / 设备信息;旧记录保持有效。
|
|
98
|
+
const issued = store.issue(currentId, deviceMetaOf(record), '', undefined, {
|
|
99
|
+
...(typeof record.deviceKey === 'string' && record.deviceKey ? { deviceKey: record.deviceKey } : {}),
|
|
100
|
+
...(typeof record.keyId === 'string' && record.keyId ? { keyId: record.keyId } : {}),
|
|
101
|
+
...(Array.isArray(record.permissions) ? { permissions: record.permissions.slice() } : {}),
|
|
102
|
+
});
|
|
103
|
+
return sendJson(res, 200, {
|
|
104
|
+
ok: true,
|
|
105
|
+
instanceId: currentId,
|
|
106
|
+
token: issued.credential,
|
|
107
|
+
cookie: cookieOf(issued.credential),
|
|
108
|
+
deviceCredential: issued.credential,
|
|
109
|
+
...(typeof issued.keyId === 'string' && issued.keyId ? { keyId: issued.keyId } : {}),
|
|
110
|
+
permissions: Array.isArray(issued.permissions) ? issued.permissions : permissions.permissionsForTier('full'),
|
|
111
|
+
credentialExpiresAt: issued.expiresAt || null,
|
|
112
|
+
serverTime: Date.now(),
|
|
113
|
+
});
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
module.exports = { handleSyncIdentity, effectivePermissions, deviceMetaOf, cookieOf };
|
package/lib/mobile/events.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 转发设备事件,并按已鉴权实例登记可吊销的 SSE 连接。
|
|
1
2
|
/**
|
|
2
3
|
* 设备流响应声明心跳周期,供客户端检测首帧缺失。
|
|
3
4
|
* 设备级事件流(GET /api/mobile/v1/events/stream):手机上侧栏那条 SSE。
|
|
@@ -137,7 +138,7 @@ async function handleDeviceStream(ctx, req, res) {
|
|
|
137
138
|
res.write(': connected\n\n');
|
|
138
139
|
const ac = new AbortController();
|
|
139
140
|
// 按设备登记这条流:吊销时宿主主动断它(§3.3)。设备级流同样是「开着就一直收」。
|
|
140
|
-
const untrack = streamRegistry.track(req.__dshRecord && req.__dshRecord.deviceId, res);
|
|
141
|
+
const untrack = streamRegistry.track(req.__dshRecord && req.__dshRecord.deviceId, res, req.__dshRecord?.instanceId);
|
|
141
142
|
// 听**响应**的关闭,不是请求的:`req` 那条 'close' 在 IncomingMessage 上表示「入站请求已经
|
|
142
143
|
// 读完」,一次普通 GET 走完就会触发,而这条 SSE 连接此刻还好好的 —— 听它会当场把自己掐掉。
|
|
143
144
|
// 真正的「手机那头走了」落在 `res` 上;与 `/session/stream` 同一个口径。
|