dsh-mobile-plugin 0.5.118 → 0.5.120
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/README.md +2 -2
- package/config/agent-presets/standard/skills/dsh-mobile-kb/SKILL.md +3 -2
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/network-guide.md +1 -1
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/network.md +2 -4
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/port-conflict.md +42 -0
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/relay-server.md +1 -1
- package/config/agent-presets/standard/skills/dsh-mobile-kb/references/relay.md +11 -15
- package/lib/cloudflared/wiring.cjs +88 -10
- package/lib/impl.js +59 -22
- package/lib/mirror/pusher.cjs +150 -139
- package/lib/mobile/channel-proxy.js +204 -0
- package/lib/mobile/channels.js +100 -0
- package/lib/mobile/events.js +2 -1
- package/lib/mobile/host-bridge/endpoints.js +3 -0
- package/lib/mobile/host-bridge/event-synthesis.js +38 -10
- package/lib/mobile/permissions.js +5 -2
- package/lib/mobile/push-notify.js +39 -106
- package/lib/mobile/rpc.js +7 -4
- package/lib/mobile/session-cache.js +8 -0
- package/lib/mobile/sessions.js +26 -6
- package/lib/panel/index.html +25 -25
- package/lib/relay/address-slot.cjs +1 -1
- package/lib/relay/config-store.js +23 -4
- package/lib/relay/control.js +2 -2
- package/lib/relay/core.js +27 -156
- package/lib/relay/ingress-guard.cjs +111 -0
- package/lib/relay/lan-proxy.js +56 -2
- package/lib/relay/pairing-check.cjs +181 -0
- package/lib/relay/pairing-payload.cjs +7 -19
- package/lib/relay/protocol.js +1 -2
- package/lib/relay/relay-probe.js +1 -1
- package/lib/relay/status.js +8 -0
- package/lib/remote/host-control.cjs +1 -1
- package/lib/routes/control-plane.js +53 -18
- package/lib/routes/mobile-api.js +11 -21
- package/lib/sidecar-facade-worker.cjs +18 -11
- package/lib/zeronews/runner.cjs +11 -3
- package/lib/zeronews/wiring.cjs +12 -2
- package/package.json +14 -13
- package/lib/mobile/notification-prefs.js +0 -205
- package/lib/mobile/push-notify-route.js +0 -37
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 2026-11-25:专属回环入口随局域网代理一起启动,实绑端口上报宿主落盘;sidecar 白名单放行该运行时字段。
|
|
1
2
|
// 主动重连只重建中转隧道,手工换址先清掉过期的自动选路账。
|
|
2
3
|
// 绑定遵守固定入口策略,网卡变化及时通知宿主上报目录。
|
|
3
4
|
// blob分片等中转持久化确认,发送失败沿本机RPC返回生产者。
|
|
@@ -110,6 +111,8 @@ let lanRequestedPort = 0
|
|
|
110
111
|
let lanGeneration = 0
|
|
111
112
|
// 对外入口只从实际监听的端口生成,未监听时不发布候选。
|
|
112
113
|
let lanBoundPort = 0
|
|
114
|
+
// 专属回环入口的实绑端口:与主入口无关,绑好就上报宿主保存,被占后内核另分的值也走这条路。
|
|
115
|
+
let lanIngressPort = 0
|
|
113
116
|
function lanUrlPort() { return lanBoundPort || config.lanPort }
|
|
114
117
|
/**
|
|
115
118
|
* 隧道/局域网状态一变就**立刻**经 IPC 推给宿主,别等宿主那 10s 一次的健康轮询。
|
|
@@ -128,7 +131,7 @@ function publishState() {
|
|
|
128
131
|
// `route` 是这一轮择路的账:当前连的是哪条、是列表里第几条、试过几条。
|
|
129
132
|
// 宿主拿它决定「该把中选的那条写回队首了」,手机拿它诊断「为什么不是我配的那条」。
|
|
130
133
|
tunnel: { state: tunnelState, error: tunnelError, mirror: relayMirror, relayUrl: tunnelState === 'connected' ? connectedRelayUrl : null, ...(tunnelRoute ? { route: tunnelRoute } : {}) },
|
|
131
|
-
lan: { enabled: Boolean(config.lanEnabled), port: lanUrlPort(), requestedPort: lanRequestedPort || config.lanPort, state: lanState, error: lanError, discovery: lanDiscovery?.snapshot() || { state: 'off', error: null } },
|
|
134
|
+
lan: { enabled: Boolean(config.lanEnabled), port: lanUrlPort(), requestedPort: lanRequestedPort || config.lanPort, ingressPort: lanIngressPort, state: lanState, error: lanError, discovery: lanDiscovery?.snapshot() || { state: 'off', error: null } },
|
|
132
135
|
})
|
|
133
136
|
}
|
|
134
137
|
let networkTimer = null
|
|
@@ -436,7 +439,7 @@ function startNetworkMonitor() {
|
|
|
436
439
|
async function stopLan() {
|
|
437
440
|
lanGeneration += 1
|
|
438
441
|
const previous = lan
|
|
439
|
-
lan = null; lanState = 'off'; lanError = null; lanBoundPort = 0
|
|
442
|
+
lan = null; lanState = 'off'; lanError = null; lanBoundPort = 0; lanIngressPort = 0
|
|
440
443
|
await lanDiscovery?.stop()
|
|
441
444
|
lanDiscovery = null
|
|
442
445
|
if (previous) await previous.stop()
|
|
@@ -742,7 +745,10 @@ async function startLan() {
|
|
|
742
745
|
isCurrent: () => own === lanGeneration,
|
|
743
746
|
createProxy: port => createLanProxy({
|
|
744
747
|
ipv4Enabled: Boolean(config.lanEnabled),
|
|
745
|
-
lanPort: port,
|
|
748
|
+
lanPort: port,
|
|
749
|
+
// 专属回环入口:首选值是宿主从 relay.json 带来的落盘值,0 表示让内核分配。
|
|
750
|
+
ingressPort: config.tunnelIngressPort || 0,
|
|
751
|
+
instanceId: config.instanceId, previousInstanceId: config.previousInstanceId || '', lanSecret: config.lanSecret,
|
|
746
752
|
// 配对码与票据走取值器:配对成功之后宿主会换掉它们(§5.1),而重建局域网代理会把
|
|
747
753
|
// 刚握上的连接全掐掉 —— 换值不该动监听。
|
|
748
754
|
currentPairing: () => ({ code: config.pairingCode, ticket: config.pairingTicket || '' }),
|
|
@@ -796,6 +802,9 @@ async function startLan() {
|
|
|
796
802
|
if (own !== lanGeneration) { await result.proxy.stop(); await discovery.stop(); return }
|
|
797
803
|
lan = result.proxy
|
|
798
804
|
lanBoundPort = result.port
|
|
805
|
+
lanIngressPort = typeof result.proxy.ingressPort === 'function' ? result.proxy.ingressPort() || 0 : 0
|
|
806
|
+
// 端口被占后内核另分的那个值要落盘,下一次启动就稳定在它上面;发布状态让宿主写回。
|
|
807
|
+
if (lanIngressPort && config.tunnelIngressPort !== lanIngressPort) config.tunnelIngressPort = lanIngressPort
|
|
799
808
|
config.lanPort = result.port
|
|
800
809
|
lanState = 'listening'
|
|
801
810
|
publishState()
|
|
@@ -813,7 +822,7 @@ async function configure(next) {
|
|
|
813
822
|
// `relayUrls` 在白名单里,而且从这一轮起**进签名**(见 tunnelSignature):地址组或它的
|
|
814
823
|
// 顺序变了就要重新择路。白名单缺了它,宿主下发这一格会直接抛 unknown configuration
|
|
815
824
|
// field,整次配置下发失败。
|
|
816
|
-
const allowed = ['enabled', 'relayUrl', 'relayUrls', 'instanceId', 'previousInstanceId', 'pairingCode', 'pairingTicket', 'pairingTier', 'name', 'upstreamPort', 'upstreamHost', 'lanPort', 'lanPortLockReason', 'lanEnabled', 'lanSecret', 'registerSecret']
|
|
825
|
+
const allowed = ['enabled', 'relayUrl', 'relayUrls', 'instanceId', 'previousInstanceId', 'pairingCode', 'pairingTicket', 'pairingTier', 'name', 'upstreamPort', 'upstreamHost', 'lanPort', 'lanPortLockReason', 'lanEnabled', 'lanSecret', 'registerSecret', 'tunnelIngressPort']
|
|
817
826
|
if (Object.keys(next).some(key => !allowed.includes(key))) throw new Error('unknown configuration field')
|
|
818
827
|
if (typeof next.instanceId !== 'string' || next.instanceId.length > 128) throw new Error('invalid instanceId')
|
|
819
828
|
if (next.previousInstanceId !== undefined && (typeof next.previousInstanceId !== 'string' || next.previousInstanceId.length > 128)) throw new Error('invalid previousInstanceId')
|
|
@@ -823,6 +832,8 @@ async function configure(next) {
|
|
|
823
832
|
if (typeof next.upstreamPort !== 'number' || !Number.isInteger(next.upstreamPort) || next.upstreamPort < 1 || next.upstreamPort > 65535) throw new Error('invalid upstreamPort')
|
|
824
833
|
if (next.upstreamHost !== undefined && (typeof next.upstreamHost !== 'string' || !next.upstreamHost || next.upstreamHost.length > 64)) throw new Error('invalid upstreamHost')
|
|
825
834
|
if (next.lanPort !== undefined && (!Number.isInteger(next.lanPort) || next.lanPort < 1024 || next.lanPort > 65535)) throw new Error('invalid lanPort')
|
|
835
|
+
// 专属入口端口是运行时字段(默认 0 = 内核分配);坏值宁可退回分配,也不拿它去听一个死端口。
|
|
836
|
+
if (next.tunnelIngressPort !== undefined && (!Number.isInteger(next.tunnelIngressPort) || next.tunnelIngressPort < 0 || next.tunnelIngressPort > 65535)) throw new Error('invalid tunnelIngressPort')
|
|
826
837
|
if (next.registerSecret !== undefined && (typeof next.registerSecret !== 'string' || next.registerSecret.length > 512)) throw new Error('invalid registerSecret')
|
|
827
838
|
// 只重建真正变了的那一半:
|
|
828
839
|
// - 决定隧道「连到哪台、以谁的身份连」的字段变了才重建隧道;
|
|
@@ -840,6 +851,7 @@ async function configure(next) {
|
|
|
840
851
|
const lanNeedsRebuild = lanSignature(previous) !== lanSignature(next)
|
|
841
852
|
const monitorNeedsRestart = monitorSignature(previous) !== monitorSignature(next)
|
|
842
853
|
config = { ...next }
|
|
854
|
+
if (config.tunnelIngressPort === undefined) config.tunnelIngressPort = previous.tunnelIngressPort || 0
|
|
843
855
|
if (tunnelNeedsRebuild) {
|
|
844
856
|
if (relayUrlChanged && config.enabled && config.relayUrl && config.upstreamPort) {
|
|
845
857
|
// 换地址这条路**等新隧道真的注册上**再返回:注册不上要把错误一路回给调用方,
|
|
@@ -890,7 +902,7 @@ function status() {
|
|
|
890
902
|
// 而宿主侧靠它判「当前连的不是队首 → 该写回了」。没试过(隧道没起来)时留空,
|
|
891
903
|
// 别让一份上上轮的账一直挂在那儿。
|
|
892
904
|
const route = tunnelRoute ? tunnelRoute : undefined
|
|
893
|
-
return { ok: true, sidecar: true, enabled: Boolean(config.enabled), relayUrl: config.relayUrl || '', relayUrls: Array.isArray(config.relayUrls) ? config.relayUrls : [], instanceId: config.instanceId, name: config.name, localPort: config.upstreamPort, tunnel: { state: tunnelState, error: tunnelError, mirror: relayMirror, relayUrl: tunnelState === 'connected' ? connectedRelayUrl : null, ...(route ? { route } : {}) }, lan: { enabled: Boolean(config.lanEnabled), port: lanUrlPort(), requestedPort: lanRequestedPort || config.lanPort, state: lanState, error: lanError, discovery: lanDiscovery?.snapshot() || { state: 'off', error: null } }, process: { memoryUsage: process.memoryUsage() }, streams: { lan: lanStreams, relaySseOpen } }
|
|
905
|
+
return { ok: true, sidecar: true, enabled: Boolean(config.enabled), relayUrl: config.relayUrl || '', relayUrls: Array.isArray(config.relayUrls) ? config.relayUrls : [], instanceId: config.instanceId, name: config.name, localPort: config.upstreamPort, tunnel: { state: tunnelState, error: tunnelError, mirror: relayMirror, relayUrl: tunnelState === 'connected' ? connectedRelayUrl : null, ...(route ? { route } : {}) }, lan: { enabled: Boolean(config.lanEnabled), port: lanUrlPort(), requestedPort: lanRequestedPort || config.lanPort, ingressPort: lanIngressPort, state: lanState, error: lanError, discovery: lanDiscovery?.snapshot() || { state: 'off', error: null } }, process: { memoryUsage: process.memoryUsage() }, streams: { lan: lanStreams, relaySseOpen } }
|
|
894
906
|
}
|
|
895
907
|
const server = http.createServer(async (req, res) => {
|
|
896
908
|
try {
|
|
@@ -934,12 +946,7 @@ const server = http.createServer(async (req, res) => {
|
|
|
934
946
|
}
|
|
935
947
|
return send(res, 202, { ok: true });
|
|
936
948
|
}
|
|
937
|
-
|
|
938
|
-
// 决定,不再一律塞进 sync——中转按帧类型分发,塞错类型等于发到黑洞。
|
|
939
|
-
const frameType = body && typeof body === 'object' && body.kind === 'push'
|
|
940
|
-
? (body.pushFrame === 'register' ? T.pushRegister : T.pushSend)
|
|
941
|
-
: T.sync;
|
|
942
|
-
tunnel.sendJson(frameType, 0, frameForTunnel(body, relayMirror === false));
|
|
949
|
+
tunnel.sendJson(T.sync, 0, frameForTunnel(body, relayMirror === false));
|
|
943
950
|
return send(res, 202, { ok: true });
|
|
944
951
|
}
|
|
945
952
|
return send(res, 503, { ok: false, error: 'tunnel not connected' });
|
package/lib/zeronews/runner.cjs
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
// 2026-11-25:CLI status 的 connected 也认作在跑,兼容新版客户端字段,别把活线路抖成掉线重连。
|
|
1
2
|
// 2026-11-25:端口失配带上可识别的 reason,让接线层清掉旧地址(配对码不再带失效线路)。
|
|
2
3
|
// 2026-11-25:running 认守护进程而非早退出的启动进程;连上后可由接线层定时体检判活。
|
|
3
4
|
// 2026-11-25:复用隧道前比对 local_port,旧端口隧道不再静默复用。
|
|
@@ -118,7 +119,7 @@ function parseStatusPayload(raw) {
|
|
|
118
119
|
login: truthy(obj.login),
|
|
119
120
|
loginPending: truthy(obj.login_pending),
|
|
120
121
|
loginError: typeof obj.login_error === 'string' ? obj.login_error.trim() : '',
|
|
121
|
-
running: truthy(obj.running),
|
|
122
|
+
running: truthy(obj.running) || truthy(obj.connected),
|
|
122
123
|
configured: truthy(obj.configured),
|
|
123
124
|
clientEnabled: obj.client_enabled !== false,
|
|
124
125
|
};
|
|
@@ -176,6 +177,9 @@ function createZeroNewsRunner(options = {}) {
|
|
|
176
177
|
*/
|
|
177
178
|
let daemonRunning = false;
|
|
178
179
|
let aliveCheckPromise = null;
|
|
180
|
+
// 已有隧道正指向的本机端口(0 = 还没有隧道)。下次启动原样复用它,别把已经在用
|
|
181
|
+
// 的隧道改到新端口 —— 那会判成端口失配,而官方 CLI 的删除参数没公开,重建有风险。
|
|
182
|
+
let tunnelLocalPort = 0;
|
|
179
183
|
|
|
180
184
|
function status() {
|
|
181
185
|
return {
|
|
@@ -191,6 +195,8 @@ function createZeroNewsRunner(options = {}) {
|
|
|
191
195
|
retryable,
|
|
192
196
|
// 只反映这一进程里见过的身份;落盘的那份由接线层并进来(见 wiring.cjs 的 statusOf)。
|
|
193
197
|
configured,
|
|
198
|
+
// 已有隧道指向的本机端口:接线层据此沿用同一端口,避免把在用的隧道判成失配。
|
|
199
|
+
tunnelLocalPort,
|
|
194
200
|
};
|
|
195
201
|
}
|
|
196
202
|
|
|
@@ -281,6 +287,7 @@ function createZeroNewsRunner(options = {}) {
|
|
|
281
287
|
const found = pickEndpointDetail(await api('/api/v1/endpoints'));
|
|
282
288
|
const current = Number.isInteger(port) && port > 0 ? port : 0;
|
|
283
289
|
if (found) {
|
|
290
|
+
tunnelLocalPort = Number.isInteger(found.localPort) && found.localPort > 0 ? found.localPort : 0;
|
|
284
291
|
// 只有字段明确在、且指向另一个端口才算失配:老接口的 endpoints 没有 local_port,
|
|
285
292
|
// 那种照旧复用。失配不自动删云端隧道(仓里没有删除入口),标红并让用户自己删旧的。
|
|
286
293
|
if (current > 0 && found.localPort > 0 && found.localPort !== current) {
|
|
@@ -308,9 +315,10 @@ function createZeroNewsRunner(options = {}) {
|
|
|
308
315
|
} catch (error) {
|
|
309
316
|
addError = error && error.message ? error.message : String(error);
|
|
310
317
|
}
|
|
311
|
-
|
|
318
|
+
// 新建成功:记住它落在哪个端口上,下次启动沿用,不再判成「旧隧道指向旧端口」。
|
|
319
|
+
if (added) { tunnelLocalPort = port; return added; }
|
|
312
320
|
const waited = await waitEndpoint(START_TIMEOUT_MS, port);
|
|
313
|
-
if (waited) return waited;
|
|
321
|
+
if (waited) { tunnelLocalPort = port; return waited; }
|
|
314
322
|
// 免费档只有 1 条 1Mbps 隧道;额度被旧隧道占住、或账号侧拒绝时,原文要透出来,
|
|
315
323
|
// 别让用户只看到「连上了但拿不到地址」这种猜不出原因的提示。
|
|
316
324
|
if (addError) {
|
package/lib/zeronews/wiring.cjs
CHANGED
|
@@ -182,9 +182,19 @@ function mountZeroNews(options) {
|
|
|
182
182
|
return { ...current, configured: current.configured === true || getState().zeroNewsBound === true };
|
|
183
183
|
};
|
|
184
184
|
|
|
185
|
-
|
|
185
|
+
// 落点端口:已经有隧道在用时沿用它自己的端口(老用户可能仍指向 18787),只在没有隧道时
|
|
186
|
+
// 才用判据给的首选值。反过来做会把在用的隧道判成端口失配 —— 官方 CLI 没公开删除参数,
|
|
187
|
+
// 重建有风险,不如原地复用。
|
|
188
|
+
const preferredPort = () => Number(options.portOf && options.portOf()) || 0;
|
|
189
|
+
let runner = null;
|
|
190
|
+
const tunnelPort = () => {
|
|
191
|
+
const current = runner && typeof runner.status === 'function' ? runner.status() : null;
|
|
192
|
+
const known = current ? Number(current.tunnelLocalPort) : 0;
|
|
193
|
+
return Number.isInteger(known) && known > 0 ? known : preferredPort();
|
|
194
|
+
};
|
|
195
|
+
runner = makeRunner({
|
|
186
196
|
ensure: provision,
|
|
187
|
-
portOf:
|
|
197
|
+
portOf: tunnelPort,
|
|
188
198
|
// 客户端在我们「以为还连着」的时候退出(插件重载 / 自动更新 / 偶发崩溃):安排一次自愈重连。
|
|
189
199
|
onUnexpectedExit: () => scheduleRetry(),
|
|
190
200
|
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-mobile-plugin",
|
|
3
|
-
"version": "0.5.
|
|
3
|
+
"version": "0.5.120",
|
|
4
4
|
"description": "Mobile API (/api/mobile/v1) and relay client for the DSH mobile app — desktop profile build (dsh 0.2.x, peers resolved by the host)",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"icon": "./icon.png",
|
|
@@ -117,22 +117,23 @@
|
|
|
117
117
|
"yaml": "2.9.1"
|
|
118
118
|
},
|
|
119
119
|
"dshMobileReleaseNotes": {
|
|
120
|
-
"version": "0.5.
|
|
120
|
+
"version": "0.5.120",
|
|
121
121
|
"kinds": [
|
|
122
|
+
"feature",
|
|
122
123
|
"fix"
|
|
123
124
|
],
|
|
124
125
|
"notes": {
|
|
125
|
-
"zh-Hans": "-
|
|
126
|
-
"zh-Hant": "-
|
|
127
|
-
"en": "-
|
|
128
|
-
"ja": "-
|
|
129
|
-
"ko": "-
|
|
130
|
-
"de": "-
|
|
131
|
-
"es": "-
|
|
132
|
-
"fr": "-
|
|
133
|
-
"pt": "-
|
|
134
|
-
"ru": "-
|
|
135
|
-
"tr": "-
|
|
126
|
+
"zh-Hans": "- 公用中转已正式下线、不再可用,面板里的相关入口与线路档位已移除;升级后老配置里残留的内置地址会自动清理。\n- 本机 Agent 新增「从电脑导入」:电脑上配好的渠道连名字、地址、模型和 Key 一起带到手机,复核后保存。\n- 手机够不着的渠道(比如只绑本机或内网的)现在由电脑代发模型请求,手机照样能用。\n- 首次连接引导拆成「下载 App / 配网络 / 扫码连接」三页,网络可以先跳过,进控制台再配。\n- 引导页第二页服务商改一行一家,接好之后只显示状态。\n- 出二维码前会先把码里的地址真拨一遍:一条都不通就不出码,只测到本机通时会提示还要满足哪些条件。",
|
|
127
|
+
"zh-Hant": "- 公用中繼已正式下線、不再可用,面板裡的相關入口與線路檔位已移除;升級後舊設定裡殘留的內建位址會自動清理。\n- 本機 Agent 新增「從電腦匯入」:電腦上配好的通路連名字、位址、模型和 Key 一起帶到手機,確認後儲存。\n- 手機連不上的通路(例如只綁本機或內網的)現在由電腦代為發出模型請求,手機照樣能用。\n- 首次連線引導拆成「下載 App/設定網路/掃碼連線」三頁,網路可以先跳過,進控制台再設定。\n- 引導頁第二頁服務商改成一行一家,接好之後只顯示狀態。\n- 出 QR 碼前會先把碼裡的位址真撥一遍:一條都不通就不出碼,只測到本機通時會提示還要滿足哪些條件。",
|
|
128
|
+
"en": "- The public relay has been shut down and is no longer available; its entries and route options are gone from the panel, and built-in relay addresses left in older configurations are cleared on upgrade.\n- Local Agent now offers \"Import from computer\": a channel you already set up on the computer is carried over to the phone — name, address, model and key — for you to review and save.\n- Channels your phone cannot reach, such as ones bound to localhost or an intranet, can now be sent through the computer, so the phone can use them as usual.\n- The first-run guide is split into three pages — download the app, configure the network, scan to connect — and the network step can be skipped and set up later in the console.\n- On the network step, service providers are now one per row and show only their status once connected.\n- Before the QR code appears, every address it will carry is actually dialed: if none responds, no code is shown; if only this computer responds, it tells you what else must be in place.",
|
|
129
|
+
"ja": "- 公開中継は正式に終了し、利用できなくなりました。パネルから関連する入口と回線の選択肢も削除され、アップグレード時に古い設定に残っていた組み込み中継アドレスは自動的に消去されます。\n- ローカル Agent に「パソコンからインポート」を追加しました。パソコンで設定済みのチャネルを、名前・アドレス・モデル・キーごとスマートフォンに取り込み、確認して保存できます。\n- スマートフォンから届かないチャネル(ローカルや社内ネットワークにのみバインドされたものなど)は、パソコンがモデルへのリクエストを代行するので、スマートフォンでもそのまま使えます。\n- 初回接続のガイドを「アプリをダウンロード/ネットワーク設定/QR コードで接続」の 3 ページに分けました。ネットワーク設定は後回しにしてコンソールで設定できます。\n- ガイドの 2 ページ目はサービスごとに 1 行の表示に変わり、接続後は状態だけを表示します。\n- QR コードを出す前に、コードに含まれる各アドレスへ実際に接続を試します。どれも通らなければコードは出さず、このパソコンだけが通る場合は他に必要な条件を案内します。",
|
|
130
|
+
"ko": "- 공용 릴레이가 공식적으로 종료되어 더 이상 사용할 수 없습니다. 패널에서 관련 진입점과 회선 옵션이 제거되었고, 업그레이드 시 이전 설정에 남아 있던 내장 릴레이 주소는 자동으로 정리됩니다.\n- 로컬 Agent에 「컴퓨터에서 가져오기」를 추가했습니다. 컴퓨터에 설정된 채널을 이름, 주소, 모델, 키와 함께 휴대폰으로 가져와 확인 후 저장할 수 있습니다.\n- 휴대폰에서 닿을 수 없는 채널(로컬이나 사내망에만 연결된 채널 등)은 이제 컴퓨터가 모델 요청을 대신 보내므로 휴대폰에서도 그대로 사용할 수 있습니다.\n- 첫 연결 안내를 「앱 다운로드 / 네트워크 설정 / QR 코드 스캔」 세 페이지로 나눴습니다. 네트워크 설정은 건너뛰고 콘솔에서 나중에 설정할 수 있습니다.\n- 안내 두 번째 페이지에서 서비스 제공자가 한 줄에 하나씩 표시되고, 연결 후에는 상태만 보여 줍니다.\n- QR 코드를 표시하기 전에 코드에 담길 주소를 실제로 연결해 봅니다. 하나도 통하지 않으면 코드를 표시하지 않고, 이 컴퓨터만 통하면 추가로 필요한 조건을 안내합니다.",
|
|
131
|
+
"de": "- Der öffentliche Relay wurde abgeschaltet und ist nicht mehr verfügbar; seine Einträge und Routenoptionen wurden aus dem Panel entfernt, und in älteren Konfigurationen verbliebene integrierte Relay-Adressen werden beim Upgrade automatisch gelöscht.\n- Local Agent bietet jetzt „Vom Computer importieren“: Ein bereits auf dem Computer eingerichteter Kanal wird samt Name, Adresse, Modell und Schlüssel aufs Telefon übernommen, zum Prüfen und Speichern.\n- Kanäle, die das Telefon nicht erreicht – etwa solche, die nur an localhost oder ein Intranet gebunden sind – werden jetzt über den Computer angefragt und funktionieren so auch am Telefon.\n- Die Ersteinrichtung ist in drei Seiten aufgeteilt – App herunterladen, Netzwerk einrichten, per QR-Code verbinden – und der Netzwerkschritt lässt sich überspringen und später in der Konsole erledigen.\n- Anbieter stehen im Netzwerkschritt jetzt je Zeile einzeln und zeigen nach dem Verbinden nur noch ihren Status.\n- Bevor der QR-Code erscheint, wird jede darin enthaltene Adresse tatsächlich angewählt: Antwortet keine, wird kein Code gezeigt; antwortet nur dieser Computer, wird erklärt, was sonst noch stimmen muss.",
|
|
132
|
+
"es": "- El relay público se ha desactivado y ya no está disponible; sus accesos y opciones de ruta se han quitado del panel, y las direcciones de relay integradas que quedaran en configuraciones antiguas se borran al actualizar.\n- Local Agent incorpora «Importar desde el ordenador»: un canal ya configurado en el ordenador pasa al teléfono con su nombre, dirección, modelo y clave, para que lo revises y lo guardes.\n- Los canales que el teléfono no alcanza, como los ligados solo a localhost o a una intranet, ahora se envían a través del ordenador y funcionan igualmente en el teléfono.\n- La guía de primera conexión se divide en tres páginas —descargar la app, configurar la red, conectar por QR— y el paso de red se puede omitir para hacerlo después en la consola.\n- En el paso de red, cada proveedor ocupa una fila y, una vez conectado, solo muestra su estado.\n- Antes de mostrar el código QR se marca de verdad cada dirección que incluirá: si ninguna responde no se muestra código, y si solo responde este ordenador se indica qué más hace falta.",
|
|
133
|
+
"fr": "- Le relais public a été arrêté et n'est plus disponible ; ses entrées et options de ligne ont été retirées du panneau, et les adresses de relais intégrées restant dans d'anciennes configurations sont supprimées lors de la mise à jour.\n- Local Agent propose désormais « Importer depuis l'ordinateur » : un canal déjà configuré sur l'ordinateur est repris sur le téléphone avec son nom, son adresse, son modèle et sa clé, à vérifier puis enregistrer.\n- Les canaux que le téléphone ne peut pas joindre, par exemple ceux liés uniquement à localhost ou à un intranet, passent désormais par l'ordinateur et restent utilisables sur le téléphone.\n- Le guide de première connexion est réparti en trois pages — télécharger l'application, configurer le réseau, se connecter par QR code — et l'étape réseau peut être ignorée puis réglée plus tard dans la console.\n- À l'étape réseau, chaque fournisseur occupe une ligne et n'affiche plus que son état une fois connecté.\n- Avant d'afficher le QR code, chaque adresse qu'il contiendra est réellement appelée : si aucune ne répond, aucun code n'est affiché ; si seul cet ordinateur répond, les conditions restantes sont indiquées.",
|
|
134
|
+
"pt": "- O relay público foi encerrado e não está mais disponível; seus acessos e opções de rota foram removidos do painel, e os endereços de relay integrados que restarem em configurações antigas são apagados na atualização.\n- O Local Agent agora tem «Importar do computador»: um canal já configurado no computador passa para o telefone com nome, endereço, modelo e chave, para você conferir e salvar.\n- Canais que o telefone não alcança, como os ligados apenas ao localhost ou a uma intranet, agora passam pelo computador e continuam funcionando no telefone.\n- O guia de primeira conexão foi dividido em três páginas — baixar o app, configurar a rede, conectar por QR code — e a etapa de rede pode ser pulada e feita depois no console.\n- Na etapa de rede, cada provedor ocupa uma linha e, depois de conectado, mostra apenas o estado.\n- Antes de exibir o QR code, cada endereço que ele levará é realmente testado: se nenhum responder, nenhum código aparece; se só este computador responder, o que mais falta é indicado.",
|
|
135
|
+
"ru": "- Публичный релей отключён и больше недоступен; его пункты и варианты маршрутов убраны из панели, а встроенные адреса релея, оставшиеся в старых настройках, удаляются при обновлении.\n- В Local Agent появился «Импорт с компьютера»: канал, уже настроенный на компьютере, переносится на телефон вместе с именем, адресом, моделью и ключом — остаётся проверить и сохранить.\n- Каналы, до которых телефон не достаёт (например, привязанные только к localhost или внутренней сети), теперь обслуживаются через компьютер и работают на телефоне как обычно.\n- Знакомство при первом подключении разделено на три страницы — скачать приложение, настроить сеть, подключиться по QR-коду, — и шаг с сетью можно пропустить и настроить позже в консоли.\n- На шаге с сетью каждый провайдер занимает одну строку и после подключения показывает только состояние.\n- Перед показом QR-кода каждый адрес из него реально проверяется: если не отвечает ни один, код не показывается; если отвечает только этот компьютер, сообщается, что ещё нужно выполнить.",
|
|
136
|
+
"tr": "- Genel relay kapatıldı ve artık kullanılamıyor; paneldeki ilgili girişler ve hat seçenekleri kaldırıldı, eski yapılandırmalarda kalan yerleşik relay adresleri güncellemede otomatik olarak siliniyor.\n- Local Agent'a «Bilgisayardan içe aktar» eklendi: bilgisayarda kurulu bir kanal adı, adresi, modeli ve anahtarıyla telefona taşınır; siz gözden geçirip kaydedersiniz.\n- Telefonun ulaşamadığı kanallar (yalnızca yerel makineye veya kurum içi ağa bağlı olanlar gibi) artık bilgisayar üzerinden gönderilir ve telefonda da çalışır.\n- İlk bağlantı rehberi üç sayfaya ayrıldı — uygulamayı indir, ağı yapılandır, QR kodla bağlan — ve ağ adımı atlanıp konsoldan sonra yapılabilir.\n- Ağ adımında her sağlayıcı tek satırda görünür ve bağlandıktan sonra yalnızca durumunu gösterir.\n- QR kod gösterilmeden önce kodda yer alacak her adres gerçekten denenir: hiçbiri yanıt vermezse kod gösterilmez; yalnızca bu bilgisayar yanıt verirse başka nelerin gerektiği belirtilir."
|
|
136
137
|
}
|
|
137
138
|
}
|
|
138
139
|
}
|
|
@@ -1,205 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* 通知按事件类型分级:每类可设「响铃 / 静默 / 关闭」。
|
|
5
|
-
*
|
|
6
|
-
* ## 为什么落在宿主侧、还按设备分桶
|
|
7
|
-
*
|
|
8
|
-
* 这张表决定的是「这台手机上,哪一类通知该响、哪一类只挂通知栏、哪一类干脆不发」。
|
|
9
|
-
* 声音与通知栏是手机的机身行为,跟会话无关,也跟电脑无关;同一枚 token 可能配过不止一台
|
|
10
|
-
* 手机(换机、平板 + 手机),各人手里的偏好不该互相覆盖,所以按 `deviceId` 各存一份。
|
|
11
|
-
*
|
|
12
|
-
* 桶键取**可信凭据记录**里的 `deviceId`(`req.__dshRecord.deviceId`),不认请求头:
|
|
13
|
-
* 请求头谁都能写,凭据记录是这一条请求已经查库验过的那一份(见 `lib/http/routing.js`
|
|
14
|
-
* 里 `createGuarded` 把记录挂到 `req` 的写法)。
|
|
15
|
-
*
|
|
16
|
-
* ## 两条边界
|
|
17
|
-
*
|
|
18
|
-
* - **读坏不 404**:文件缺失、读一半、结构不对、缺键,一律逐键并到默认表,绝不 404。
|
|
19
|
-
* 这张表的缺省就是「能用」,把它读成故障等于让通知系统凭空瘫掉。
|
|
20
|
-
* - **写整表替换**:PUT 收的是完整 `events`,逐键 clamp 到三档枚举、未知键丢弃,再原子
|
|
21
|
-
* 落盘(mkdir + 临时文件 + rename + 0o600)。写不进去如实回失败。
|
|
22
|
-
*/
|
|
23
|
-
|
|
24
|
-
const fs = require('node:fs');
|
|
25
|
-
const path = require('node:path');
|
|
26
|
-
|
|
27
|
-
const { dshHome } = require('../shared/paths');
|
|
28
|
-
const { sendJson, readJsonBody } = require('../shared/http-util');
|
|
29
|
-
|
|
30
|
-
/** 存储格式版本:将来改形状时据此决定丢弃还是迁移。 */
|
|
31
|
-
const VERSION = 1;
|
|
32
|
-
|
|
33
|
-
/** 五类事件(三端逐字一致,见共享契约)。 */
|
|
34
|
-
const EVENT_TYPES = Object.freeze(['done', 'failed', 'approval', 'question', 'planReview']);
|
|
35
|
-
|
|
36
|
-
/** 三档级别:响铃(通知 + 声音)/ 静默(通知栏不响)/ 关闭(不通知)。 */
|
|
37
|
-
const LEVELS = Object.freeze(['ring', 'silent', 'off']);
|
|
38
|
-
|
|
39
|
-
/** 缺省档:等你动手才响、完成类静默。 */
|
|
40
|
-
const DEFAULT_EVENT_LEVELS = Object.freeze({
|
|
41
|
-
done: 'silent',
|
|
42
|
-
failed: 'ring',
|
|
43
|
-
approval: 'ring',
|
|
44
|
-
question: 'ring',
|
|
45
|
-
planReview: 'ring',
|
|
46
|
-
});
|
|
47
|
-
|
|
48
|
-
/** 拿不到凭据记录时的兜底桶键:正常请求永远带 `deviceId`,这条只防裸调(测试 / 老调用方)。 */
|
|
49
|
-
const FALLBACK_DEVICE_ID = 'unknown-device';
|
|
50
|
-
|
|
51
|
-
/** 通知偏好文件。路径每次调用时按 `DSH_HOME` 解析,测试可注入。 */
|
|
52
|
-
function prefsFile() {
|
|
53
|
-
return path.join(dshHome(), 'storages', 'mobile-plugin', 'notification-prefs.json');
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function isRecord(value) {
|
|
57
|
-
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
/** 请求的桶键:优先可信凭据记录里的 `deviceId`。 */
|
|
61
|
-
function deviceIdOf(req) {
|
|
62
|
-
const record = req && req.__dshRecord;
|
|
63
|
-
if (record && typeof record.deviceId === 'string' && record.deviceId.trim()) {
|
|
64
|
-
return record.deviceId.trim();
|
|
65
|
-
}
|
|
66
|
-
return FALLBACK_DEVICE_ID;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
/** 一份干净的默认表(每次新对象,调用方改了也不污染常量)。 */
|
|
70
|
-
function defaultEvents() {
|
|
71
|
-
return { ...DEFAULT_EVENT_LEVELS };
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/** 单键 clamp:枚举内的原样返回,否则 null(调用方据此回退默认)。 */
|
|
75
|
-
function clampLevel(value) {
|
|
76
|
-
return typeof value === 'string' && LEVELS.includes(value) ? value : null;
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
/**
|
|
80
|
-
* 归一化一张 events 表:**以默认表打底,逐键覆盖**。合法的用值、非法/缺失的用默认、
|
|
81
|
-
* 未知键直接丢。这是「读」与「写」共用的同一套收窄口径。
|
|
82
|
-
*/
|
|
83
|
-
function normalizeEvents(input) {
|
|
84
|
-
const out = defaultEvents();
|
|
85
|
-
if (!isRecord(input)) return out;
|
|
86
|
-
for (const key of EVENT_TYPES) {
|
|
87
|
-
const level = clampLevel(input[key]);
|
|
88
|
-
if (level) out[key] = level;
|
|
89
|
-
}
|
|
90
|
-
return out;
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/** 读整个文件;缺失 / 坏 / 结构不对 → 空的 devices(读坏就当还没有任何偏好)。 */
|
|
94
|
-
function loadStore() {
|
|
95
|
-
let raw;
|
|
96
|
-
try {
|
|
97
|
-
raw = JSON.parse(fs.readFileSync(prefsFile(), 'utf8'));
|
|
98
|
-
} catch {
|
|
99
|
-
return { version: VERSION, updatedAt: 0, devices: {} };
|
|
100
|
-
}
|
|
101
|
-
if (!isRecord(raw)) return { version: VERSION, updatedAt: 0, devices: {} };
|
|
102
|
-
const devices = isRecord(raw.devices) ? raw.devices : {};
|
|
103
|
-
return {
|
|
104
|
-
version: VERSION,
|
|
105
|
-
updatedAt: typeof raw.updatedAt === 'number' ? raw.updatedAt : 0,
|
|
106
|
-
devices,
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* 读这台设备的偏好。缺文件 / 坏文件 / 缺键都逐键并到默认,不 404。
|
|
112
|
-
* @returns {{ version:number, updatedAt:number, events:object }}
|
|
113
|
-
*/
|
|
114
|
-
function readEvents(deviceId) {
|
|
115
|
-
const store = loadStore();
|
|
116
|
-
const entry = isRecord(store.devices[deviceId]) ? store.devices[deviceId] : null;
|
|
117
|
-
return {
|
|
118
|
-
version: store.version,
|
|
119
|
-
updatedAt: entry && typeof entry.updatedAt === 'number' ? entry.updatedAt : 0,
|
|
120
|
-
events: normalizeEvents(entry ? entry.events : null),
|
|
121
|
-
};
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/**
|
|
125
|
-
* 原子写整份文件(mkdir + 临时文件 + rename + 0o600)。
|
|
126
|
-
* 写失败安静返回 false,让调用方如实回 500,不抛。
|
|
127
|
-
*/
|
|
128
|
-
function saveStore(store) {
|
|
129
|
-
const file = prefsFile();
|
|
130
|
-
const next = { ...store, version: VERSION, updatedAt: Date.now() };
|
|
131
|
-
try {
|
|
132
|
-
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
133
|
-
const tmp = `${file}.${process.pid}.tmp`;
|
|
134
|
-
fs.writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600 });
|
|
135
|
-
fs.renameSync(tmp, file);
|
|
136
|
-
return true;
|
|
137
|
-
} catch {
|
|
138
|
-
return false;
|
|
139
|
-
}
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
/**
|
|
143
|
-
* 写这台设备的偏好:整表替换,逐键 clamp、未知键丢弃。
|
|
144
|
-
* @returns {{ ok:boolean, updatedAt:number, events:object }}
|
|
145
|
-
*/
|
|
146
|
-
function writeEvents(deviceId, inputEvents) {
|
|
147
|
-
const events = normalizeEvents(inputEvents);
|
|
148
|
-
const store = loadStore();
|
|
149
|
-
const updatedAt = Date.now();
|
|
150
|
-
const devices = isRecord(store.devices) ? { ...store.devices } : {};
|
|
151
|
-
devices[deviceId] = { updatedAt, events };
|
|
152
|
-
const ok = saveStore({ version: VERSION, updatedAt, devices });
|
|
153
|
-
return { ok, updatedAt, events };
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
/**
|
|
157
|
-
* GET /api/mobile/v1/notification-prefs —— 回 `{ ok, version, updatedAt, events }`。
|
|
158
|
-
* PUT /api/mobile/v1/notification-prefs —— body `{ events }`,整表替换,回 `{ ok, updatedAt, events }`。
|
|
159
|
-
*
|
|
160
|
-
* 两条收在同一路径上由 `req.method` 分派(宿主注册器不按方法分派,与 `/narration` 同一条路)。
|
|
161
|
-
*/
|
|
162
|
-
async function handleNotificationPrefs(_ctx, req, res) {
|
|
163
|
-
const deviceId = deviceIdOf(req);
|
|
164
|
-
|
|
165
|
-
if (req && req.method === 'PUT') {
|
|
166
|
-
const body = await readJsonBody(req);
|
|
167
|
-
if (!body || !isRecord(body.events)) {
|
|
168
|
-
sendJson(res, 400, { ok: false, error: { code: 'bad-request', message: 'events 必须是对象' } });
|
|
169
|
-
return;
|
|
170
|
-
}
|
|
171
|
-
const result = writeEvents(deviceId, body.events);
|
|
172
|
-
if (!result.ok) {
|
|
173
|
-
sendJson(res, 500, {
|
|
174
|
-
ok: false,
|
|
175
|
-
error: { code: 'write-failed', message: '通知偏好没写进去' },
|
|
176
|
-
});
|
|
177
|
-
return;
|
|
178
|
-
}
|
|
179
|
-
sendJson(res, 200, { ok: true, updatedAt: result.updatedAt, events: result.events });
|
|
180
|
-
return;
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
const current = readEvents(deviceId);
|
|
184
|
-
sendJson(res, 200, {
|
|
185
|
-
ok: true,
|
|
186
|
-
version: current.version,
|
|
187
|
-
updatedAt: current.updatedAt,
|
|
188
|
-
events: current.events,
|
|
189
|
-
});
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
module.exports = {
|
|
193
|
-
VERSION,
|
|
194
|
-
EVENT_TYPES,
|
|
195
|
-
LEVELS,
|
|
196
|
-
DEFAULT_EVENT_LEVELS,
|
|
197
|
-
defaultEvents,
|
|
198
|
-
clampLevel,
|
|
199
|
-
normalizeEvents,
|
|
200
|
-
deviceIdOf,
|
|
201
|
-
prefsFile,
|
|
202
|
-
readEvents,
|
|
203
|
-
writeEvents,
|
|
204
|
-
handleNotificationPrefs,
|
|
205
|
-
};
|
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* POST /api/mobile/v1/push-token —— iOS 推送令牌上报。
|
|
5
|
-
*
|
|
6
|
-
* App 拿到 APNs 令牌(应用启动时向系统注册)就打到这里;宿主核对完设备身份
|
|
7
|
-
* (guarded 已做),经隧道帧 `pushRegister` 转交中转落表。中转没配 APNs 密钥时
|
|
8
|
-
* 那头静默忽略——这条路由照常回 ok:「推没推成」不是 App 要操心的事,它没有
|
|
9
|
-
* 可以据此改变行为的下一步。
|
|
10
|
-
*
|
|
11
|
-
* 隧道不在时也回 ok:令牌上报是幂等的,App 下次启动会再报,不值得为它排队重试。
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
const { sendJson, readJsonBody } = require('../shared/http-util');
|
|
15
|
-
|
|
16
|
-
/**
|
|
17
|
-
* @param {object} deps 装配注入。`pushNotify` 是 `mobile/push-notify.js` 的出口
|
|
18
|
-
* (缺了就只回 ok——推送没接线时令牌上报不该 500)。
|
|
19
|
-
*/
|
|
20
|
-
function createPushTokenHandler(deps) {
|
|
21
|
-
const pushNotify = deps.pushNotify || null;
|
|
22
|
-
return function handlePushToken(_ctx, req, res) {
|
|
23
|
-
void readJsonBody(req).then((body) => {
|
|
24
|
-
const deviceId = typeof body?.deviceId === 'string' ? body.deviceId.trim() : '';
|
|
25
|
-
const token = typeof body?.token === 'string' ? body.token.trim() : '';
|
|
26
|
-
const platform = typeof body?.platform === 'string' ? body.platform.trim() : 'ios';
|
|
27
|
-
if (!deviceId || !token) {
|
|
28
|
-
sendJson(res, 400, { ok: false, error: 'deviceId and token are required' });
|
|
29
|
-
return;
|
|
30
|
-
}
|
|
31
|
-
if (pushNotify) pushNotify.registerToken(deviceId, token, platform);
|
|
32
|
-
sendJson(res, 200, { ok: true });
|
|
33
|
-
}, () => sendJson(res, 400, { ok: false, error: 'invalid json' }));
|
|
34
|
-
};
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
module.exports = { createPushTokenHandler };
|