dsh-mobile-ios 0.2.12 → 0.2.14

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.
@@ -9,7 +9,7 @@ import fs from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import { createGateway } from '../src/server.mjs';
11
11
  import { createFileLog } from '../src/file-log.mjs';
12
- import { sweepOrphanTunnels } from '../src/tunnel.mjs';
12
+ import { findCloudflared, sweepOrphanTunnels } from '../src/tunnel.mjs';
13
13
  import { createMockHost } from '../src/adapter/mock-host.mjs';
14
14
  import { createMuxHost } from '../src/adapter/mux-host.mjs';
15
15
  import { createCordisHost } from '../src/adapter/cordis-host.mjs';
@@ -20,35 +20,13 @@ export const name = 'dsh-mobile-ios';
20
20
  export const version = PLUGIN_VERSION;
21
21
 
22
22
  /**
23
- * 本机 cloudflared 发现链:config.tunnelBin → env CLOUDFLARED_BIN(tunnel.mjs 处理)
24
- * → ~/.dsh/mobile-access/components/cloudflared/<版本>/cloudflared(社区 dsh-mobile
25
- * 组件目录,只借用可执行文件不共享状态)→ PATH('auto')。
23
+ * 本机 cloudflared 发现链统一在 src/tunnel.mjs 的 findCloudflared:
24
+ * config.tunnelBin → env CLOUDFLARED_BIN → 组件目录(~/.dsh/mobile-access/components/cloudflared/<版本>/)
25
+ * → PATH。这里不再自己扫一遍目录 —— 两份实现曾经对 .exe 后缀的判断不一致,
26
+ * 直接导致「装好了但开通器找不到」。
26
27
  */
27
- function discoverCloudflared() {
28
- const dir = path.join(os.homedir(), '.dsh', 'mobile-access', 'components', 'cloudflared');
29
- try {
30
- const versions = fs
31
- .readdirSync(dir)
32
- .filter((v) => !v.startsWith('.'))
33
- .sort()
34
- .reverse();
35
- // Windows 组件目录里的可执行文件名带 .exe;先按平台列候选,命中即用。
36
- const binNames = process.platform === 'win32' ? ['cloudflared.exe', 'cloudflared'] : ['cloudflared'];
37
- for (const v of versions) {
38
- for (const binName of binNames) {
39
- const bin = path.join(dir, v, binName);
40
- try {
41
- fs.accessSync(bin, fs.constants.X_OK);
42
- return bin;
43
- } catch {
44
- /* 版本目录里没有该可执行文件,继续 */
45
- }
46
- }
47
- }
48
- } catch {
49
- /* 目录不存在 */
50
- }
51
- return 'auto';
28
+ function resolveCloudflared(config = {}) {
29
+ return config.tunnelBin || findCloudflared('auto') || 'auto';
52
30
  }
53
31
 
54
32
  /** 兼容 Cordis 的两种清理注册方式;都不可用时退化为 no-op 并明确记录 */
@@ -128,13 +106,12 @@ export function apply(ctx = {}, config = {}) {
128
106
  const tunnelCfg = config.tunnel || {};
129
107
  const tunnelStateFile = tunnelCfg.stateFile || path.join(os.homedir(), '.dsh', 'mobile-access', 'tunnel-named.json');
130
108
  const baseDomain = tunnelCfg.baseDomain || process.env.DSH_TUNNEL_BASE_DOMAIN || 'matrixboard.cn';
131
- const cloudflareBin = config.tunnelBin || discoverCloudflared();
109
+ const cloudflareBin = resolveCloudflared(config);
132
110
  const common = {
133
111
  baseDomain,
134
112
  prefix: tunnelCfg.prefix || 'dsh',
135
- executable: cloudflareBin === 'auto'
136
- ? (process.platform === 'win32' ? 'cloudflared.exe' : 'cloudflared')
137
- : cloudflareBin,
113
+ // 没找到就留 'auto':让发现链在真正要用的那一刻再解析一次(自动安装发生在启动之后)
114
+ executable: cloudflareBin,
138
115
  };
139
116
  const explicit = tunnelCfg.provisioner ? String(tunnelCfg.provisioner) : null;
140
117
  const apiToken = tunnelCfg.apiToken || process.env.DSH_CF_API_TOKEN;
@@ -192,8 +169,8 @@ export function apply(ctx = {}, config = {}) {
192
169
  || path.join(os.homedir(), '.dsh', 'mobile-access', 'dsh-mobile-ios-devices.json'),
193
170
  // 插件形态默认开隧道自动重拉(sidecar/dev 形态不开,避免测试时空转)
194
171
  tunnelAutoRestart: config.autoRestart !== undefined ? Boolean(config.autoRestart) : true,
195
- // 隧道可执行文件发现链(见 discoverCloudflared);显式 config.tunnelBin 优先
196
- tunnelExecutable: config.tunnelBin || discoverCloudflared(),
172
+ // 隧道可执行文件发现链(见 resolveCloudflared);显式 config.tunnelBin 优先
173
+ tunnelExecutable: cloudflareBin,
197
174
  tunnelProvisioner: provisioner,
198
175
  log,
199
176
  })
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mobile-ios",
3
- "version": "0.2.12",
3
+ "version": "0.2.14",
4
4
  "type": "module",
5
5
  "description": "DSH iOS移动伴侣:iPhone/iPad 扫码连接 DSH 桌面端,局域网直连 + Cloudflare Tunnel 固定域名远程两种通道",
6
6
  "main": "entries/plugin.mjs",
@@ -29,8 +29,7 @@
29
29
  "scripts": {
30
30
  "start": "node entries/sidecar.mjs --host=mock --dev",
31
31
  "start:lan": "node entries/sidecar.mjs --host=mock --dev --lan=true",
32
- "probe": "node spike0/probe.mjs",
33
- "test": "node test/selftest.mjs && node test/version.mjs && node test/update-dialog.mjs && node test/ops.mjs && node test/resilience.mjs && node test/borrowed.mjs && node test/mux-table.mjs && node test/live-frames.mjs && node test/artifacts.mjs && node test/attachments.mjs && node test/session-actions.mjs && node test/enhance.mjs && node test/tunnel-named.mjs && node test/cloudflared-install.mjs && node test/install-continue.mjs && node test/dns-recheck.mjs && node test/plugin-selfupdate.mjs && node test/zone-moved.mjs"
32
+ "test": "node test/selftest.mjs && node test/version.mjs && node test/lan-ip.mjs && node test/update-dialog.mjs && node test/ops.mjs && node test/resilience.mjs && node test/borrowed.mjs && node test/mux-table.mjs && node test/live-frames.mjs && node test/artifacts.mjs && node test/attachments.mjs && node test/session-actions.mjs && node test/enhance.mjs && node test/tunnel-named.mjs && node test/tar.mjs && node test/cloudflared-install.mjs && node test/install-continue.mjs && node test/dns-recheck.mjs && node test/plugin-selfupdate.mjs && node test/zone-moved.mjs"
34
33
  },
35
34
  "dsh": {
36
35
  "bundle": {
@@ -0,0 +1,148 @@
1
+ // adapter/mock-data.mjs — 契约回放用的内置样本数据
2
+ //
3
+ // 历史包袱:mock 宿主原来从仓库 `spec/fixtures/**` 读 9 个 JSON,而这份夹具从未随
4
+ // 插件分包一起提交(路径还多上了一级),于是 mock 一创建就 ENOENT ——
5
+ // `npm start`、sidecar 开发模式、以及 9 个测试套件全部连带崩掉。
6
+ // 样本数据本来就只为「形状正确」服务,放在代码里比放在一个易丢的目录更可靠:
7
+ // · 装到哪台机器都能跑(不依赖相对路径,Windows/macOS 一致)
8
+ // · 时间戳按创建时刻生成,截图里不会出现「三天前」的假数据
9
+ //
10
+ // 这里只塑造宿主真实会返回的形状,不模拟「智能」。
11
+
12
+ const RUNNING_TASK = 'tsk_a41f9c';
13
+ const IDLE_TASK = 'tsk_b7c21e';
14
+
15
+ export function createMockData({ now = Date.now() } = {}) {
16
+ const at = (offsetSec = 0) => new Date(now - offsetSec * 1000).toISOString();
17
+
18
+ const hostInfo = {
19
+ hostId: 'host_mock',
20
+ hostName: 'DSH 桌面端(mock)',
21
+ hostVersion: '0.2.14-mock',
22
+ platform: process.platform,
23
+ protocolVersion: '1.0',
24
+ caps: ['tasks.read', 'tasks.write', 'tasks.cancel', 'artifacts.read', 'tasks.settings', 'tasks.sessionActions', 'prompt.enhance'],
25
+ };
26
+
27
+ const workspaces = [{ id: 'ws_mock', name: 'mock 工作区' }];
28
+
29
+ const taskList = [
30
+ {
31
+ taskId: RUNNING_TASK,
32
+ storedKey: 'sk_mock_a41f9c',
33
+ title: '把隧道重连逻辑抽成独立模块',
34
+ status: 'running',
35
+ phase: { index: 2, total: 5, label: '正在改代码' },
36
+ elapsedSec: 132,
37
+ startedAt: at(132),
38
+ lastActivityAt: at(3),
39
+ hostId: hostInfo.hostId,
40
+ hostName: hostInfo.hostName,
41
+ cwd: '/mock/workspace',
42
+ permission: 'requireApproval',
43
+ budgetMin: 10,
44
+ needsYou: false,
45
+ pendingTodoCount: 1,
46
+ artifactsCount: 2,
47
+ workspaceId: 'ws_mock',
48
+ workspaceName: 'mock 工作区',
49
+ origin: 'user',
50
+ },
51
+ {
52
+ taskId: IDLE_TASK,
53
+ storedKey: 'sk_mock_b7c21e',
54
+ title: '整理 iOS 配对页文案',
55
+ status: 'completed',
56
+ phase: null,
57
+ elapsedSec: 96,
58
+ startedAt: at(3600),
59
+ lastActivityAt: at(1800),
60
+ hostId: hostInfo.hostId,
61
+ hostName: hostInfo.hostName,
62
+ cwd: '/mock/workspace',
63
+ permission: 'autoApprove',
64
+ budgetMin: 15,
65
+ needsYou: false,
66
+ pendingTodoCount: 0,
67
+ artifactsCount: 0,
68
+ workspaceId: 'ws_mock',
69
+ workspaceName: 'mock 工作区',
70
+ origin: 'user',
71
+ },
72
+ ];
73
+
74
+ const artifacts = {
75
+ items: [
76
+ {
77
+ artifactId: 'art_notes',
78
+ name: 'tunnel-notes.md',
79
+ kind: 'file',
80
+ mime: 'text/markdown',
81
+ sizeBytes: 2048,
82
+ updatedAt: at(120),
83
+ },
84
+ {
85
+ artifactId: 'art_qr',
86
+ name: 'qr-preview.png',
87
+ kind: 'image',
88
+ mime: 'image/png',
89
+ sizeBytes: 10240,
90
+ updatedAt: at(90),
91
+ },
92
+ ],
93
+ };
94
+
95
+ const detail = {
96
+ task: { ...taskList[0] },
97
+ budget: { limitMin: 10, usedSec: 132, remainingSec: 468, warnAt: 480 },
98
+ pendingTodos: [
99
+ {
100
+ todoId: 'todo_1',
101
+ question: '重连退避要不要做成可配置?',
102
+ options: [
103
+ { id: 'yes', label: '做成配置项' },
104
+ { id: 'no', label: '先写死 10s' },
105
+ ],
106
+ createdAt: at(20),
107
+ },
108
+ ],
109
+ artifactsPreview: artifacts.items.map((a) => ({
110
+ artifactId: a.artifactId, name: a.name, kind: a.kind, sizeBytes: a.sizeBytes,
111
+ })),
112
+ tokenUsage: { inputTokens: 8123, outputTokens: 2048, totalTokens: 10171 },
113
+ lastSeq: 0,
114
+ serverTime: at(0),
115
+ };
116
+
117
+ // 一次完整运行的 10 帧事件;kind 覆盖 state / turn / todo / log / artifact。
118
+ const scenario = {
119
+ frames: [
120
+ { delayMs: 60, frame: { kind: 'turn', data: { type: 'user_message', text: '把隧道重连逻辑抽成独立模块' } } },
121
+ { delayMs: 240, frame: { kind: 'turn', data: { type: 'thought_delta', delta: '先看 tunnel.mjs 里重连的那几段,确认边界。' } } },
122
+ { delayMs: 180, frame: { kind: 'turn', data: { type: 'assistant_delta', delta: '我把重连拆成独立模块,' } } },
123
+ { delayMs: 220, frame: { kind: 'turn', data: { type: 'tool_call', callId: 'call_mock_1', toolName: 'read_file', argSummary: 'src/tunnel.mjs' } } },
124
+ { delayMs: 160, frame: { kind: 'turn', data: { type: 'tool_result', callId: 'call_mock_1', toolName: 'read_file', summary: '已读取 523 行' } } },
125
+ { delayMs: 200, frame: { kind: 'turn', data: { type: 'assistant_delta', delta: '并把退避与进程回收都收进去。' } } },
126
+ { delayMs: 180, frame: { kind: 'todo', data: { todoId: 'todo_1', state: 'pending', question: '重连退避要不要做成可配置?' } } },
127
+ { delayMs: 140, frame: { kind: 'log', data: { level: 'info', text: '写入 src/tunnel-reconnect.mjs' } } },
128
+ { delayMs: 160, frame: { kind: 'artifact', data: { artifactId: 'art_notes', name: 'tunnel-notes.md', kind: 'file' } } },
129
+ { delayMs: 200, frame: { kind: 'state', data: { status: 'completed', phase: { index: 5, total: 5, label: '已完成' }, elapsedSec: 96, needsYou: false } } },
130
+ ],
131
+ };
132
+
133
+ return {
134
+ hostInfo,
135
+ workspaces,
136
+ taskList,
137
+ detail,
138
+ artifacts,
139
+ scenario,
140
+ createOk: { accepted: true, replayed: false, duplicate: false },
141
+ messageOk: { accepted: true, duplicate: false },
142
+ cancelOk: { accepted: true },
143
+ todoOk: { applied: true },
144
+ listBody: { items: taskList, workspaces, nextCursor: null, serverTime: at(0) },
145
+ RUNNING_TASK,
146
+ IDLE_TASK,
147
+ };
148
+ }
@@ -1,28 +1,21 @@
1
- // adapter/mock-host.mjs — 用契约夹具驱动宿主(决策 D3:Mock 载体)
1
+ // adapter/mock-host.mjs — 用契约样本驱动宿主(决策 D3:Mock 载体)
2
2
  // 目的:让客户端与网关在真实宿主不可用时也能跑到端到端;它不模拟"智能",
3
3
  // 只忠实回放契约里已有的报文形状,避免 UI 在假数据上长歪。
4
4
 
5
- import fs from 'node:fs';
6
- import path from 'node:path';
7
- import { fileURLToPath } from 'node:url';
8
5
  import { fail, newId } from '../protocol.mjs';
9
-
10
- const HERE = path.dirname(fileURLToPath(import.meta.url));
11
- // 目录重构后:夹具统一在项目根的 spec/fixtures/(gateway/src/adapter → 上三级即项目根)
12
- const DEFAULT_FIXTURES = path.resolve(HERE, '../../../spec/fixtures');
13
-
14
- const read = (dir, name) => JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8'));
15
-
16
- export function createMockHost({ fixturesDir = DEFAULT_FIXTURES, log = () => {}, autoPlay = false, speed = 1 } = {}) {
17
- const hostInfo = read(fixturesDir, 'host/host.info.json').response.body;
18
- const listBody = read(fixturesDir, 'tasks/tasks.list.json').response.body;
19
- const detail = read(fixturesDir, 'tasks/task.detail.json').response.body;
20
- const createOk = read(fixturesDir, 'tasks/task.create.ok.json').response.body;
21
- const messageOk = read(fixturesDir, 'tasks/task.message.ok.json').response.body;
22
- const cancelOk = read(fixturesDir, 'tasks/task.cancel.ok.json').response.body;
23
- const artifacts = read(fixturesDir, 'tasks/task.artifacts.json').response.body;
24
- const todoOk = read(fixturesDir, 'tasks/todo.answer.ok.json').response.body;
25
- const scenario = read(fixturesDir, 'ws/stream.running.json');
6
+ import { createMockData } from './mock-data.mjs';
7
+
8
+ export function createMockHost({ log = () => {}, autoPlay = false, speed = 1, data = null } = {}) {
9
+ const fixtures = data || createMockData();
10
+ const hostInfo = fixtures.hostInfo;
11
+ const listBody = fixtures.listBody;
12
+ const detail = fixtures.detail;
13
+ const createOk = fixtures.createOk;
14
+ const messageOk = fixtures.messageOk;
15
+ const cancelOk = fixtures.cancelOk;
16
+ const artifacts = fixtures.artifacts;
17
+ const todoOk = fixtures.todoOk;
18
+ const scenario = fixtures.scenario;
26
19
 
27
20
  const tasks = new Map(listBody.items.map((t) => [t.taskId, { ...t }]));
28
21
  // 工作区分组:与 cordis alike,从夹具顶层 workspaces 下发,任务行带同源 id/name。
@@ -396,7 +389,7 @@ export function createMockHost({ fixturesDir = DEFAULT_FIXTURES, log = () => {},
396
389
  },
397
390
 
398
391
  async diag() {
399
- return { adapter: 'mock', fixturesDir, tasks: tasks.size };
392
+ return { adapter: 'mock', data: 'builtin', tasks: tasks.size };
400
393
  },
401
394
 
402
395
  subscribe(fn) {
@@ -405,7 +398,7 @@ export function createMockHost({ fixturesDir = DEFAULT_FIXTURES, log = () => {},
405
398
  },
406
399
 
407
400
  /** 回放契约里的 10 帧事件流(间隔按 speed 缩放),用于验收"实时"而不只是"首屏" */
408
- playScenario(taskId = 'tsk_a41f9c', { speed: s = speed } = {}) {
401
+ playScenario(taskId = fixtures.RUNNING_TASK, { speed: s = speed } = {}) {
409
402
  clearTimers();
410
403
  playing = taskId;
411
404
  let acc = 0;
@@ -436,7 +436,10 @@ export class CloudflareProvisioner extends BaseProvisioner {
436
436
  'GET',
437
437
  `/accounts/${this.accountId}/cfd_tunnel?name=${encodeURIComponent(name)}&is_deleted=false`,
438
438
  );
439
- const hit = (Array.isArray(list) ? list : []).find((t) => t && t.name === name && !t.deleted_at);
439
+ // REST 这边未删除给的是 null,与 CLI 的 "0001-01-01T00:00:00Z" 不同;
440
+ // 两种都按「没删」处理,免得两条开通路径对同一条隧道得出相反结论。
441
+ const hit = (Array.isArray(list) ? list : []).find((t) => t && t.name === name
442
+ && (!t.deleted_at || String(t.deleted_at).startsWith('0001-01-01')));
440
443
  if (hit) {
441
444
  // 本地管理型 tunnel 不接受远端 ingress 下发,拿 token 跑起来会没有路由。
442
445
  if (hit.remote_config === false) {
@@ -4,39 +4,47 @@
4
4
  // 1. **只在用户确认后下载**:调用方(桌面面板)必须先弹窗得到同意,本模块不静默下载执行。
5
5
  // 2. **只用官方源、只落私有目录**:从 Cloudflare 官方 GitHub Release 下载,写到
6
6
  // ~/.dsh/mobile-access/components/cloudflared/<version>/,不改系统 PATH、不装到 Program Files。
7
- // 3. **如实校验**:GitHub Release 不提供 checksum 文件,故校验 HTTPS + HTTP 200 + 预期字节数;
8
- // 校验不过就删除临时文件并报错,绝不把残缺二进制交给启动器。
7
+ // 3. **如实校验**:GitHub Release 不提供 checksum 文件,故校验 HTTPS + HTTP 200 + 官方字节数
8
+ // + 落盘后按平台嗅探可执行文件魔数(PE / Mach-O / ELF)。任何一步不过就删临时文件并报错,
9
+ // 绝不把残缺或错平台的文件交给启动器。
9
10
  // 4. **幂等**:目标已存在且大小吻合直接返回,不重复下载。
10
11
 
11
- import { mkdirSync, writeFileSync, existsSync, statSync, unlinkSync, chmodSync, renameSync } from 'node:fs';
12
+ import { closeSync, mkdirSync, openSync, readSync, writeFileSync, existsSync, statSync, unlinkSync, chmodSync, renameSync } from 'node:fs';
12
13
  import path from 'node:path';
13
14
  import os from 'node:os';
15
+ import { extractTgzEntry } from './tar.mjs';
16
+
17
+ export { extractTgzEntry as extractTarGz } from './tar.mjs';
14
18
 
15
19
  export const CLOUDFLARED_RELEASE = '2026.11.1';
16
20
  const RELEASE_BASE = `https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_RELEASE}`;
17
21
 
18
- // 官方 Release 资产与预期字节数(2026-11-20 实测 api.github.com/releases/latest 的 size 字段)。
22
+ // 官方 Release 资产与预期字节数(2026-11-20 实测 api.github.com 的 size 字段)。
19
23
  // 只列出我们支持的平台;未知平台由调用方降级为「手动安装」,不猜测下载地址。
24
+ //
25
+ // macOS 只提供 .tgz(内含 cloudflared),Linux/Windows 是裸二进制 —— 这条差别曾经被忽略:
26
+ // 早先的实现把 .tgz 整个写成了目标文件,装完 chmod 也「成功」,但一执行就报格式错误。
27
+ // archive 字段就是为这条差别显式建模的。
20
28
  const ASSETS = {
21
29
  win32: {
22
- x64: { file: 'cloudflared-windows-amd64.exe', size: 55483112, bin: 'cloudflared.exe' },
23
- ia32: { file: 'cloudflared-windows-386.exe', size: 38157960, bin: 'cloudflared.exe' },
30
+ x64: { file: 'cloudflared-windows-amd64.exe', size: 55483112, bin: 'cloudflared.exe', archive: null, magic: 'pe' },
31
+ ia32: { file: 'cloudflared-windows-386.exe', size: 38157960, bin: 'cloudflared.exe', archive: null, magic: 'pe' },
24
32
  },
25
33
  darwin: {
26
- x64: { file: 'cloudflared-darwin-amd64.tgz', size: 21857340, bin: 'cloudflared' },
27
- arm64: { file: 'cloudflared-darwin-arm64.tgz', size: 0, bin: 'cloudflared' },
34
+ x64: { file: 'cloudflared-darwin-amd64.tgz', size: 21857340, bin: 'cloudflared', archive: 'tgz', magic: 'macho' },
35
+ arm64: { file: 'cloudflared-darwin-arm64.tgz', size: 19898712, bin: 'cloudflared', archive: 'tgz', magic: 'macho' },
28
36
  },
29
37
  linux: {
30
- x64: { file: 'cloudflared-linux-amd64', size: 40346301, bin: 'cloudflared' },
31
- arm64: { file: 'cloudflared-linux-arm64', size: 0, bin: 'cloudflared' },
38
+ x64: { file: 'cloudflared-linux-amd64', size: 40346301, bin: 'cloudflared', archive: null, magic: 'elf' },
39
+ arm64: { file: 'cloudflared-linux-arm64', size: 37818397, bin: 'cloudflared', archive: null, magic: 'elf' },
32
40
  },
33
41
  };
34
42
 
35
- /** 解析当前平台对应的资产。size=0 表示未实测,跳过严格大小校验(仍校验 HTTP 200 + 非空)。 */
43
+ /** 解析当前平台对应的资产。未知平台/架构返回 null(调用方降级为手动安装)。 */
36
44
  export function resolveAsset({ platform = process.platform, arch = process.arch } = {}) {
37
45
  const byArch = ASSETS[platform];
38
46
  if (!byArch) return null;
39
- const asset = byArch[arch] || (arch === 'x64' ? byArch.amd64 : null);
47
+ const asset = byArch[arch];
40
48
  if (!asset) return null;
41
49
  return { ...asset, url: `${RELEASE_BASE}/${asset.file}` };
42
50
  }
@@ -46,12 +54,42 @@ export function resolveHome(env = process.env) {
46
54
  return env.USERPROFILE || env.HOME || os.homedir();
47
55
  }
48
56
 
49
- /** 组件目录:与 entries/plugin.mjs 的 discoverCloudflared 保持同一路径约定。 */
57
+ /** 组件目录:与 tunnel.mjs 的 findCloudflared 保持同一路径约定。 */
50
58
  export function componentBinDir({ home, version = CLOUDFLARED_RELEASE, env = process.env } = {}) {
51
59
  const base = home || resolveHome(env);
52
60
  return path.join(base, '.dsh', 'mobile-access', 'components', 'cloudflared', version);
53
61
  }
54
62
 
63
+ /** 只读前 8 字节判魔数:别为了嗅探把 50MB 的二进制整个读进内存。 */
64
+ function readHead(file, bytes = 8) {
65
+ let fd;
66
+ try {
67
+ fd = openSync(file, 'r');
68
+ const buf = Buffer.alloc(bytes);
69
+ const n = readSync(fd, buf, 0, bytes, 0);
70
+ return buf.subarray(0, n);
71
+ } finally {
72
+ if (fd !== undefined) closeSync(fd);
73
+ }
74
+ }
75
+
76
+ /**
77
+ * 可执行文件魔数嗅探。
78
+ *
79
+ * 为什么值得做:字节数与 HTTP 200 都只能证明「下载完整」,证明不了「这是本平台的可执行文件」。
80
+ * macOS 的 .tgz 事故(把压缩包当二进制写盘)就是靠这条能立刻拦住。
81
+ */
82
+ export function sniffBinary(buf, platform = process.platform) {
83
+ if (!buf || buf.length < 4) return 'unknown';
84
+ const want = platform === 'win32' ? 'pe' : platform === 'darwin' ? 'macho' : 'elf';
85
+ const unix =
86
+ buf[0] === 0x7f && buf[1] === 0x45 && buf[2] === 0x4c && buf[3] === 0x46 ? 'elf'
87
+ : buf[0] === 0x4d && buf[1] === 0x5a ? 'pe'
88
+ : [0xfeedfacf, 0xfeedface, 0xcafebabe, 0xcefaedfe, 0xcffaedfe].includes(buf.readUInt32BE(0)) ? 'macho'
89
+ : 'unknown';
90
+ return unix === want ? want : unix;
91
+ }
92
+
55
93
  /**
56
94
  * 确保 cloudflared 二进制存在于组件目录。返回 { installed, executable, version, reused }。
57
95
  * fetchImpl 注入便于测试;默认用全局 fetch。
@@ -74,13 +112,22 @@ export async function ensureCloudflared({
74
112
  const target = path.join(dir, asset.bin);
75
113
  const expected = asset.size;
76
114
 
77
- // 幂等:已存在且大小吻合(或 size=0 未登记)直接复用
115
+ // 幂等:已存在且大小吻合、且魔数正确才复用(只看大小会把「上次写坏的 .tgz」当成装好了)
78
116
  if (existsSync(target)) {
79
117
  const actual = statSync(target).size;
80
- if (expected === 0 || actual === expected) {
118
+ const okSize = expected === 0 || actual === expected;
119
+ let okMagic = true;
120
+ if (okSize) {
121
+ try {
122
+ okMagic = sniffBinary(readHead(target), platform) !== 'unknown';
123
+ } catch {
124
+ okMagic = false;
125
+ }
126
+ }
127
+ if (okSize && okMagic) {
81
128
  return { installed: true, executable: target, version, reused: true };
82
129
  }
83
- // 大小不符:视为残缺,删除后重下
130
+ // 残缺或格式不对:删掉重下(旧版把 .tgz 当二进制写坏的机器靠这一步自愈)
84
131
  try { unlinkSync(target); } catch { /* 落到下面覆盖写 */ }
85
132
  }
86
133
 
@@ -106,28 +153,33 @@ export async function ensureCloudflared({
106
153
  throw e;
107
154
  }
108
155
 
109
- let buf;
156
+ let raw;
110
157
  try {
111
- buf = Buffer.from(await res.arrayBuffer());
158
+ raw = Buffer.from(await res.arrayBuffer());
112
159
  } catch (err) {
113
160
  const e = new Error(`读取 cloudflared 内容失败:${err?.message || err}`);
114
161
  e.code = 'DOWNLOAD_FAILED';
115
162
  throw e;
116
163
  }
117
- if (buf.length === 0 || (expected > 0 && buf.length !== expected)) {
118
- const e = new Error(`cloudflared 大小校验失败:期望 ${expected},实际 ${buf.length}`);
164
+ if (raw.length === 0 || (expected > 0 && raw.length !== expected)) {
165
+ const e = new Error(`cloudflared 大小校验失败:期望 ${expected},实际 ${raw.length}`);
119
166
  e.code = 'SIZE_MISMATCH';
120
167
  throw e;
121
168
  }
122
169
 
170
+ let bin = raw;
171
+ if (asset.archive === 'tgz') bin = extractTgzEntry(raw, asset.bin);
172
+ if (sniffBinary(bin, platform) !== asset.magic) {
173
+ const e = new Error(`cloudflared 二进制格式不符(期望 ${asset.magic})`);
174
+ e.code = 'BAD_BINARY';
175
+ throw e;
176
+ }
177
+
123
178
  try {
124
- writeFileSync(partial, buf, { mode: 0o700 });
125
- if (expected > 0 && statSync(partial).size !== expected) {
126
- throw new Error('落盘后大小校验失败');
127
- }
179
+ writeFileSync(partial, bin, { mode: 0o700 });
128
180
  renameSync(partial, target);
129
181
  // Windows 的 chmod 只认读写位;POSIX 补执行位
130
- try { chmodSync(target, 0o700); } catch { /* Windows 忽略 */ }
182
+ try { chmodSync(target, 0o755); } catch { /* Windows 忽略 */ }
131
183
  } catch (err) {
132
184
  try { if (existsSync(partial)) unlinkSync(partial); } catch { /* 尽力清理 */ }
133
185
  const e = new Error(`写入 cloudflared 失败:${err?.message || err}`);
@@ -135,5 +187,12 @@ export async function ensureCloudflared({
135
187
  throw e;
136
188
  }
137
189
 
138
- return { installed: true, executable: target, version, reused: false, size: buf.length };
190
+ return {
191
+ installed: true,
192
+ executable: target,
193
+ version,
194
+ reused: false,
195
+ size: bin.length,
196
+ archiveSize: raw.length,
197
+ };
139
198
  }
@@ -6,8 +6,9 @@
6
6
  // 于是「一键更新」在最需要它的机器上恰恰用不了。
7
7
  //
8
8
  // 这里走的是网关进程自己动手:从 npm registry 取 tarball → 按 dist.shasum 校验 →
9
- // 解包到临时目录 → 备份旧目录 → 覆盖安装目录。全程不依赖宿主 API、不依赖 shell 别名,
10
- // 只用 Node 内置能力 + 系统 tar(Win10 1803+ 自带的 bsdtar 命名为 tar.exe)。
9
+ // 解包到临时目录 → 备份旧目录 → 覆盖安装目录。全程不依赖宿主 API,
10
+ // 解包优先用内置实现(src/tar.mjs,零依赖、三平台一致),
11
+ // 只有遇到内置解析不了的老式归档才回退到系统 tar(Win10 1803+ 的 bsdtar)。
11
12
  //
12
13
  // 边界与克制:
13
14
  // · 只装本插件自己的 npm 包,不接受任意包名/任意 URL(避免变成通用下载执行器);
@@ -22,6 +23,7 @@ import os from 'node:os';
22
23
  import path from 'node:path';
23
24
  import { promisify } from 'node:util';
24
25
  import { fileURLToPath } from 'node:url';
26
+ import { extractTgzToDir } from './tar.mjs';
25
27
 
26
28
  const execFileAsync = promisify(nodeExecFile);
27
29
 
@@ -123,7 +125,18 @@ export async function selfUpdatePlugin({
123
125
  fs.writeFileSync(tgz, buf);
124
126
 
125
127
  fs.mkdirSync(outDir, { recursive: true });
126
- await execImpl('tar', ['-xzf', tgz, '-C', outDir], { timeout: 120_000 });
128
+ try {
129
+ extractTgzToDir(buf, outDir);
130
+ } catch (err) {
131
+ // 内置解析只认 ustar/GNU 常规文件;老式归档或特殊条目回退到系统 tar。
132
+ // Windows 老版本可能没有 tar.exe,那时错误会同时列出两条原因。
133
+ log(`plugin 内置解包失败(${err.message}),改用系统 tar`);
134
+ try {
135
+ await execImpl('tar', ['-xzf', tgz, '-C', outDir], { timeout: 120_000 });
136
+ } catch (tarErr) {
137
+ throw new Error(`解包失败:${err.message};系统 tar 亦不可用(${tarErr?.message || tarErr})`);
138
+ }
139
+ }
127
140
 
128
141
  const unpacked = path.join(outDir, 'package');
129
142
  if (!fs.existsSync(path.join(unpacked, 'package.json'))) throw new Error('解包后缺少 package.json');
@@ -24,6 +24,7 @@ import { fail } from './protocol.mjs';
24
24
  import { deriveSubdomain, isValidLabel } from './dns-label.mjs';
25
25
  import { dnsWarningFor, evaluateDnsAnswer, probeDns, resolveNs } from './dns-probe.mjs';
26
26
  import { cnameBelongsTo, readZoneCert } from './zone-health.mjs';
27
+ import { findCloudflared } from './tunnel.mjs';
27
28
 
28
29
  const execFileAsync = promisify(nodeExecFile);
29
30
  const CLI_TIMEOUT_MS = 45_000;
@@ -31,6 +32,22 @@ const STATE_VERSION = 1;
31
32
 
32
33
  const UUID_PATTERN = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;
33
34
 
35
+ /**
36
+ * 这条隧道是否还活着(未删除)。
37
+ *
38
+ * 坑:`cloudflared tunnel list --output json` 对**未删除**的隧道给的是 Go 的零值时间
39
+ * `"deleted_at": "0001-01-01T00:00:00Z"`,既不是 null 也不是空串。所以 `!t.deleted_at`
40
+ * 会把账号里每一条活隧道都判成已删除 —— 后果是「按名查找」永远落空,每次开通都去
41
+ * create 然后撞 `tunnel with name already exists`(0.2.12 现场就是这个)。
42
+ * 判定必须同时接受:字段缺失 / null / 空串 / 零值时间。
43
+ */
44
+ function isLiveTunnel(t) {
45
+ if (!t || !t.id) return false;
46
+ const deleted = t.deleted_at;
47
+ if (!deleted) return true;
48
+ return String(deleted).startsWith('0001-01-01');
49
+ }
50
+
34
51
  function readState(file, log) {
35
52
  if (!file) return null;
36
53
  try {
@@ -98,6 +115,8 @@ export class LocalProvisioner {
98
115
  homeDir = os.homedir(),
99
116
  log = () => {},
100
117
  run = null,
118
+ // 可注入:解析 cloudflared 时用的环境(PATH / HOME)。测试必须能隔离真实 PATH。
119
+ env = process.env,
101
120
  // 可注入:测试里不该真发 DNS 查询(会等 NXDOMAIN 重试,还依赖外网)
102
121
  probe = null,
103
122
  // 可注入:解析失败时进一步问「这个域名现在归哪个 Cloudflare 账号」。
@@ -113,6 +132,7 @@ export class LocalProvisioner {
113
132
  this.configFile = configFile || path.join(path.dirname(stateFile || path.join(homeDir, 'x')), 'tunnel-config.yml');
114
133
  this.seed = seed;
115
134
  this.homeDir = homeDir;
135
+ this.env = env;
116
136
  this.log = log;
117
137
  this._state = undefined;
118
138
  // 可注入,测试里不必真起 cloudflared
@@ -143,7 +163,37 @@ export class LocalProvisioner {
143
163
  }
144
164
 
145
165
  get notConfiguredDetail() {
146
- return `在这台电脑的终端执行:${this.executable} tunnel login(浏览器里选 matrixboard.cn 授权)`;
166
+ const exe = findCloudflared(this.executable, this.env) || findCloudflared('auto', this.env) || this.executable;
167
+ return `在这台电脑的终端执行:${exe} tunnel login(浏览器里选 ${this.baseDomain} 授权)`;
168
+ }
169
+
170
+ /**
171
+ * 安装完成后回填刚下载的可执行文件路径。
172
+ *
173
+ * 必要性:插件启动那一刻就决定了本实例用哪个 executable,而「自动安装」发生在启动
174
+ * 之后。新机器(尤其 Windows)上 PATH 里没有 cloudflared,回填前开通会在
175
+ * `execFile('cloudflared.exe')` 直接 ENOENT —— 用户看到的是「装好了但开通失败」。
176
+ */
177
+ useExecutable(executable) {
178
+ if (executable) this.executable = executable;
179
+ }
180
+
181
+ /**
182
+ * 解析本次真正要执行的 cloudflared。
183
+ *
184
+ * 用发现链而不是信任构造参数:安装落点(组件目录)并不在 PATH 里,裸名字在 Windows
185
+ * 上会直接 ENOENT,在 macOS 上则要依赖用户 brew 装过。发现链已经把三处都覆盖了。
186
+ */
187
+ #resolveExecutable() {
188
+ const found = findCloudflared(this.executable, this.env) || findCloudflared('auto', this.env);
189
+ if (!found) {
190
+ throw fail(4021, '主机未安装 cloudflared,无法开通固定地址', {
191
+ detail: process.platform === 'win32'
192
+ ? '在面板点「安装 cloudflared 并开启远程」自动下载,或手动安装后把目录加入 PATH'
193
+ : '执行 `brew install cloudflared`,或设置 CLOUDFLARED_BIN 指向可执行文件',
194
+ });
195
+ }
196
+ return found;
147
197
  }
148
198
 
149
199
  /** 公网当前 NS(查询失败就当没有:少一句提示不该让整条诊断崩掉)。 */
@@ -239,7 +289,7 @@ export class LocalProvisioner {
239
289
  }
240
290
 
241
291
  async #exec(args) {
242
- const { stdout, stderr } = await execFileAsync(this.executable, args, {
292
+ const { stdout, stderr } = await execFileAsync(this.#resolveExecutable(), args, {
243
293
  timeout: CLI_TIMEOUT_MS,
244
294
  maxBuffer: 4 * 1024 * 1024,
245
295
  env: process.env,
@@ -273,7 +323,7 @@ export class LocalProvisioner {
273
323
  async #findTunnelByName(label) {
274
324
  const list = await this.#listTunnels();
275
325
  if (!list) return null; // 老版本不支持 --output;交给 create 的报错去说明
276
- const hit = list.find((t) => t && t.name === label && !t.deleted_at);
326
+ const hit = list.find((t) => isLiveTunnel(t) && t.name === label);
277
327
  return hit?.id ? { id: hit.id } : null;
278
328
  }
279
329
 
@@ -286,7 +336,7 @@ export class LocalProvisioner {
286
336
  if (!tunnelId) return undefined;
287
337
  const list = await this.#listTunnels();
288
338
  if (!list) return null;
289
- return list.some((t) => t && t.id === tunnelId && !t.deleted_at);
339
+ return list.some((t) => isLiveTunnel(t) && t.id === tunnelId);
290
340
  }
291
341
 
292
342
  async ensure({ port, force = false } = {}) {
@@ -295,15 +345,23 @@ export class LocalProvisioner {
295
345
  // 旧 tunnel 属于上一个账号,继续拿它的 id 去 route dns 只会得到 "tunnel not found",
296
346
  // 或者更糟——静默写不进去却以为自己开通成功。真判定有两条线:
297
347
  // 1) 状态文件记了 account 且与当前 cert 不一致 → 确知换了账号;
298
- // 2) 没记(老状态文件)或记不清 → 直接问 Cloudflare 这条 tunnel 还在不在当前账号。
299
- // 只靠 1) 不够:0.2.11 之前写下的状态文件根本没有 account 字段,那才是升级后的真实起点。
348
+ // 2) 没记(0.2.11 之前的状态文件没有这个字段)→ 直接问 Cloudflare 这条 tunnel
349
+ // 还在不在当前账号(`tunnel list --output json`)。
350
+ // 注意线 2) 只在「不知道归属」时才走:两种情况都清楚了还去拉子进程,会让面板每次
351
+ // 点开通都多几百毫秒(tunnel-named 里「重复开通不再调 CLI」这条契约就是拦这个的)。
300
352
  // 账号变了就当新装:重建隧道、保留同一个子域(地址不变,用户不用重新记/重新扫码)。
301
353
  const account = readZoneCert({ homeDir: this.homeDir })?.accountId || null;
302
354
  let cached = this.state;
303
355
  let rebuild = false;
304
356
  if (cached?.tunnelId) {
305
357
  const knownMismatch = Boolean(cached.account && account && cached.account !== account);
306
- const alive = knownMismatch ? false : await this.#tunnelInAccount(cached.tunnelId);
358
+ // 只有「当前证书能读出账号,但状态文件没记」才算归属未知。反过来若连证书都解析
359
+ // 不出账号(cert.pem 被换过/格式不同),那属于凭据异常,此时去 list 再拿不到就
360
+ // 判重建会变成反复重建隧道 —— 比保留旧 id 危险得多,所以这种情况直接信任缓存。
361
+ const unknownOwner = Boolean(account) && !cached.account;
362
+ const alive = knownMismatch
363
+ ? false
364
+ : unknownOwner ? await this.#tunnelInAccount(cached.tunnelId) : true;
307
365
  if (knownMismatch || alive === false) {
308
366
  this.log(knownMismatch
309
367
  ? `tunnel 授权账号已变更(${String(cached.account).slice(0, 8)}… → ${String(account).slice(0, 8)}…),重建隧道`
@@ -319,6 +377,12 @@ export class LocalProvisioner {
319
377
  dnsTampered: false,
320
378
  zone: null,
321
379
  };
380
+ } else if (alive === true && cached.account !== account) {
381
+ // 校验通过:把归属记下来。否则每次开通都因为「不知道归谁」再问一遍 Cloudflare,
382
+ // 白白多一个子进程的延迟(这条路径就是给老状态文件补账的)。
383
+ cached = { ...cached, account };
384
+ this._state = cached;
385
+ writeState(this.stateFile, cached);
322
386
  }
323
387
  }
324
388
  // 走完整开通:缓存里的 port/hostname 看着都可用,但它们描述的是上一个账号的隧道,
package/src/rest.mjs CHANGED
@@ -531,7 +531,7 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
531
531
  if (!config.tunnel) throw fail(4021, '隧道能力未启用', { method: 'tunnel.installCloudflared' });
532
532
  let result;
533
533
  try {
534
- result = await ensureCloudflared({ destDir: config.cloudflaredDir || undefined });
534
+ result = await ensureCloudflared();
535
535
  } catch (err) {
536
536
  log(`rest tunnel install-cloudflared 失败 ${err?.code || ''} ${err?.message || err}`);
537
537
  throw fail(4500, err?.message || '自动安装 cloudflared 失败', {
@@ -539,6 +539,9 @@ export function createRestRouter({ core, pairing, host, tickets, config = {}, lo
539
539
  });
540
540
  }
541
541
  log(`rest tunnel install-cloudflared ${result.reused ? '复用' : '已装'} ${result.executable}`);
542
+ // 回填路径:刚装好的二进制不在 PATH 里,开通器如果还拿裸名字去 execFile 会 ENOENT。
543
+ // 这一步让「装完 → 同一次会话里继续开通」真正成立,不必重启宿主。
544
+ config.tunnelProvisioner?.useExecutable?.(result.executable);
542
545
  // 立即重取状态:findCloudflared 已把组件目录纳入发现链,装完应马上从 missing 变 found。
543
546
  return send(ctx.res, 200, { ...result, status: tunnelSnapshot() }, DESKTOP_CORS);
544
547
  });
package/src/server.mjs CHANGED
@@ -19,14 +19,37 @@ function isPrivateIPv4(addr) {
19
19
  return PRIVATE_IPV4.some((re) => re.test(addr));
20
20
  }
21
21
 
22
- /** 首个非内部私网 IPv4 —— 手机要填的「电脑地址」就来自它 */
23
- export function lanIPv4() {
24
- for (const ifaces of Object.values(os.networkInterfaces())) {
25
- for (const i of ifaces || []) {
26
- if (i.family === 'IPv4' && !i.internal && isPrivateIPv4(i.address)) return i.address;
22
+ // 虚拟网卡:Windows 上 Hyper-V / WSL / VMware 会各造一块 172.x 的网卡,
23
+ // macOS 上 utun* 是 VPN。如果按「第一个私网地址」取,手机拿到的往往是这些
24
+ // 根本不通的地址 —— 扫码后一直转圈,用户只会以为插件坏了。
25
+ const VIRTUAL_IF = /(vEthernet|VMware|VirtualBox|Hyper-?V|Loopback|WSL|Docker|Tailscale|ZeroTier|TAP-|tap\d|utun|tun\d|ppp\d)/i;
26
+ // 物理网卡常见命名(Windows 中文系统是「以太网 / WLAN / Wi-Fi」,macOS 是 en0/en1)
27
+ const PHYSICAL_IF = /^(en\d|eth\d|wlan\d|wi-?fi|ethernet|以太网|wlan|无线)/i;
28
+
29
+ /**
30
+ * 手机要填的「电脑地址」。
31
+ *
32
+ * 优先级:物理网卡 > 其它非虚拟网卡;同类里 192.168 > 10 > 172.16-31
33
+ * (家用路由器几乎都在 192.168,而 172.16/12 更容易是虚拟网段)。
34
+ * 实在挑不出来再退回「第一个私网 IPv4」,保证老行为不至于更差。
35
+ */
36
+ export function lanIPv4(ifaces = os.networkInterfaces()) {
37
+ const candidates = [];
38
+ for (const [name, list] of Object.entries(ifaces)) {
39
+ for (const i of list || []) {
40
+ if (i.family !== 'IPv4' || i.internal || !isPrivateIPv4(i.address)) continue;
41
+ let score = 0;
42
+ if (!VIRTUAL_IF.test(name)) score += 10;
43
+ if (PHYSICAL_IF.test(name)) score += 5;
44
+ if (i.address.startsWith('192.168.')) score += 3;
45
+ else if (i.address.startsWith('10.')) score += 2;
46
+ else score += 1;
47
+ candidates.push({ address: i.address, score, name });
27
48
  }
28
49
  }
29
- return null;
50
+ if (!candidates.length) return null;
51
+ candidates.sort((a, b) => b.score - a.score);
52
+ return candidates[0].address;
30
53
  }
31
54
 
32
55
  export function makeHostAllow(suffixes = []) {
@@ -59,6 +82,9 @@ export async function createGateway({
59
82
  // 有稳定子域就不该再退化成随机域名。为 null 时保持 Quick Tunnel 行为不变。
60
83
  tunnelProvisioner = null,
61
84
  tunnelPidFile = null,
85
+ // 隧道子进程的 spawn 实现。默认用 node:child_process;测试注入假进程,
86
+ // 嵌入式场景也可替换(TunnelManager 本身已支持,这里只是让网关能透传)。
87
+ tunnelSpawn = null,
62
88
  } = {}) {
63
89
  if (!host) throw new Error('createGateway 需要 host 适配器');
64
90
 
@@ -99,6 +125,7 @@ export async function createGateway({
99
125
  port,
100
126
  log,
101
127
  executable: tunnelExecutable,
128
+ ...(tunnelSpawn ? { spawnImpl: tunnelSpawn } : {}),
102
129
  // 插件形态默认开自动重拉:宿主进程长活,cloudflared 意外退出后
103
130
  // 不重拉的话手机会一直显示「在线」但隧道实际已死。
104
131
  autoRestart: tunnelAutoRestart,
package/src/tar.mjs ADDED
@@ -0,0 +1,112 @@
1
+ // tar.mjs — 零依赖 tar/gzip 读取
2
+ //
3
+ // 为什么不用系统 tar:
4
+ // · Windows 只有 1803+ 才自带 bsdtar(且依赖 System32 在 PATH 里);
5
+ // · 解包是「安装」动作的最后一步,这里失败等于前面下载全白费,
6
+ // 不该把成败押在外部命令是否存在上。
7
+ //
8
+ // 只实现安装真正需要的能力:读 ustar/GNU 常规文件、整树解包。
9
+ // 不做符号链接、硬链接、稀疏文件 —— npm 包与 cloudflared 发布包都用不到,
10
+ // 真遇到就跳过(宁可少解一个文件,也不要解出宿主目录以外的路径)。
11
+
12
+ import { gunzipSync } from 'node:zlib';
13
+ import { mkdirSync, writeFileSync } from 'node:fs';
14
+ import path from 'node:path';
15
+
16
+ const BLOCK = 512;
17
+
18
+ /** C 字符串字段(0 结尾或填满) */
19
+ function cstr(buf, start, len) {
20
+ const slice = buf.subarray(start, start + len);
21
+ const end = slice.indexOf(0);
22
+ return slice.subarray(0, end === -1 ? slice.length : end).toString('utf8').trim();
23
+ }
24
+
25
+ /** 八进制字段(可能被空格/NUL 填充) */
26
+ function octal(buf, start, len) {
27
+ const text = cstr(buf, start, len);
28
+ const value = parseInt(text || '0', 8);
29
+ return Number.isFinite(value) ? value : 0;
30
+ }
31
+
32
+ /** 解 gzip;不是 gzip 就抛 BAD_ARCHIVE(调用方据此报「安装包损坏」) */
33
+ export function gunzip(raw) {
34
+ try {
35
+ return gunzipSync(raw);
36
+ } catch (err) {
37
+ const e = new Error(`压缩包解压失败:${err?.message || err}`);
38
+ e.code = 'BAD_ARCHIVE';
39
+ throw e;
40
+ }
41
+ }
42
+
43
+ /**
44
+ * 遍历 tar 条目。回调拿到 (entry),entry.data 是 Buffer 视图。
45
+ * 归档结束(连续两个全零块)即停。
46
+ */
47
+ export function walkTar(buf, onEntry) {
48
+ let off = 0;
49
+ while (off + BLOCK <= buf.length) {
50
+ const header = buf.subarray(off, off + BLOCK);
51
+ if (header.every((b) => b === 0)) break;
52
+ const name = cstr(header, 0, 100);
53
+ const prefix = cstr(header, 345, 155);
54
+ const full = prefix ? `${prefix}/${name}` : name;
55
+ const size = octal(header, 124, 12);
56
+ const typeByte = header[156];
57
+ const type = typeByte === 0 ? '0' : String.fromCharCode(typeByte);
58
+ const dataStart = off + BLOCK;
59
+ const data = buf.subarray(dataStart, dataStart + size);
60
+ // '0'/'\0' 常规文件;'x'/'g' 是 pax 扩展头(跳过,名字仍在下一个条目里);
61
+ // 'L' GNU 长文件名(同样跳过,宁可名字短一点也不越界写文件)
62
+ if (type === '0') onEntry({ name: full, size, data, mode: octal(header, 100, 8) });
63
+ off = dataStart + Math.ceil(size / BLOCK) * BLOCK;
64
+ }
65
+ }
66
+
67
+ /** 把归档内的相对路径收敛到 destDir 内;越界返回 null。 */
68
+ function safeJoin(destDir, name) {
69
+ const clean = String(name).replace(/\\/g, '/').replace(/^\/+/, '');
70
+ const target = path.resolve(destDir, clean);
71
+ const base = path.resolve(destDir);
72
+ if (target !== base && !target.startsWith(base + path.sep)) return null;
73
+ return target;
74
+ }
75
+
76
+ /** 取出归档里指定 basename 的文件(找不到就退化为第一个常规文件)。 */
77
+ export function extractEntry(rawTar, binName) {
78
+ let hit = null;
79
+ let first = null;
80
+ walkTar(rawTar, (entry) => {
81
+ if (hit) return;
82
+ if (!first && entry.size > 0) first = entry;
83
+ if (path.basename(entry.name) === binName && entry.size > 0) hit = entry;
84
+ });
85
+ const chosen = hit || first;
86
+ return chosen ? Buffer.from(chosen.data) : null;
87
+ }
88
+
89
+ /** 解 gzip + 取单文件:安装 cloudflared(macOS 的 .tgz)走这条。 */
90
+ export function extractTgzEntry(raw, binName) {
91
+ const file = extractEntry(gunzip(raw), binName);
92
+ if (!file) {
93
+ const e = new Error(`安装包里找不到 ${binName}`);
94
+ e.code = 'BAD_ARCHIVE';
95
+ throw e;
96
+ }
97
+ return file;
98
+ }
99
+
100
+ /** 整树解包到 destDir(npm tarball 形如 package/**)。返回写出的文件数。 */
101
+ export function extractTgzToDir(raw, destDir) {
102
+ const tar = gunzip(raw);
103
+ let written = 0;
104
+ walkTar(tar, (entry) => {
105
+ const target = safeJoin(destDir, entry.name);
106
+ if (!target) return; // 越界路径直接丢弃:安装器不该有写宿主目录的能力
107
+ mkdirSync(path.dirname(target), { recursive: true });
108
+ writeFileSync(target, entry.data);
109
+ written += 1;
110
+ });
111
+ return written;
112
+ }
package/src/tunnel.mjs CHANGED
@@ -34,34 +34,52 @@ export function redactSecrets(line) {
34
34
  .replace(/(Bearer|Ticket)\s+\S+/gi, '$1 [redacted-credential]');
35
35
  }
36
36
 
37
+ /** 版本目录按数字分段比较:字符串排序会把 2026.9.1 排到 2026.11.1 前面。 */
38
+ function compareVersionDesc(a, b) {
39
+ const pa = String(a).split(/\D+/).filter(Boolean).map(Number);
40
+ const pb = String(b).split(/\D+/).filter(Boolean).map(Number);
41
+ for (let i = 0; i < Math.max(pa.length, pb.length); i += 1) {
42
+ const diff = (pb[i] ?? 0) - (pa[i] ?? 0);
43
+ if (diff !== 0) return diff;
44
+ }
45
+ return 0;
46
+ }
47
+
37
48
  /** 在 PATH 里找可执行文件。找不到返回 null(调用方转成 4021)。 */
38
49
  export function findCloudflared(explicit, env = process.env) {
50
+ // explicit 的三种形态:
51
+ // · 'auto' —— 走完整发现链
52
+ // · 含分隔符的绝对/相对路径 —— 只认它(显式指定却不存在 = 缺失,不偷偷换别处的二进制)
53
+ // · 裸文件名 —— 当作 PATH 里的名字继续找(历史行为是直接判缺失,
54
+ // 于是 sidecar 的 `--tunnel-bin cloudflared` 永远起不来)
55
+ let name = process.platform === 'win32' ? 'cloudflared.exe' : 'cloudflared';
39
56
  if (explicit && explicit !== 'auto') {
40
- try {
41
- accessSync(explicit, constants.X_OK);
42
- return explicit;
43
- } catch {
44
- return null;
57
+ if (explicit.includes('/') || explicit.includes('\\')) {
58
+ try {
59
+ accessSync(explicit, constants.X_OK);
60
+ return explicit;
61
+ } catch {
62
+ return null;
63
+ }
45
64
  }
46
- }
47
- if (env.CLOUDFLARED_BIN) {
65
+ name = explicit;
66
+ } else if (env.CLOUDFLARED_BIN) {
48
67
  try {
49
68
  accessSync(env.CLOUDFLARED_BIN, constants.X_OK);
50
69
  return env.CLOUDFLARED_BIN;
51
70
  } catch {
52
- /* 落到 PATH 搜索 */
71
+ /* 落到组件目录/ PATH 搜索 */
53
72
  }
54
73
  }
55
- const name = process.platform === 'win32' ? 'cloudflared.exe' : 'cloudflared';
56
74
 
57
75
  // 自举安装落点优先于 PATH:面板「自动安装 cloudflared」把二进制写进组件目录后,
58
76
  // 下次 status()/start() 调 findCloudflared 就能立即发现,无需重启插件/宿主。
59
- // 路径约定与 entries/plugin.mjs 的 discoverCloudflared、cloudflared-install.mjs 一致。
77
+ // 路径约定与 entries/plugin.mjs 的 resolveCloudflared、cloudflared-install.mjs 一致。
60
78
  // home 来源与安装侧相同:USERPROFILE/HOME 优先,便于测试隔离与多用户环境。
61
79
  const home = env.USERPROFILE || env.HOME || os.homedir();
62
80
  const componentRoot = path.join(home, '.dsh', 'mobile-access', 'components', 'cloudflared');
63
81
  try {
64
- const versions = readdirSync(componentRoot).filter((v) => !v.startsWith('.')).sort().reverse();
82
+ const versions = readdirSync(componentRoot).filter((v) => !v.startsWith('.')).sort(compareVersionDesc);
65
83
  for (const v of versions) {
66
84
  const candidate = path.join(componentRoot, v, name);
67
85
  try {
@@ -71,7 +89,7 @@ export function findCloudflared(explicit, env = process.env) {
71
89
  }
72
90
  } catch { /* 组件目录不存在,落到 PATH */ }
73
91
 
74
- const dirs = (env.PATH || '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin').split(path.delimiter);
92
+ const dirs = (env.PATH || env.Path || '/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin').split(path.delimiter);
75
93
  for (const dir of dirs) {
76
94
  if (!dir) continue;
77
95
  const candidate = path.join(dir, name);
@@ -307,7 +325,7 @@ export class TunnelManager {
307
325
  return;
308
326
  }
309
327
  this.child = child;
310
- this.#writePid(child.pid);
328
+ this.#writePid(child.pid);
311
329
 
312
330
  timer = setTimeout(() => {
313
331
  this.state = 'failed';
@@ -474,6 +492,9 @@ export class TunnelManager {
474
492
  */
475
493
  export async function sweepOrphanTunnels({ componentDir, log = () => {} } = {}) {
476
494
  if (!componentDir) return { killed: 0 };
495
+ // Windows 没有 pgrep,也不存在「按命令行找进程」的廉价等价物;
496
+ // 孤儿回收在那里靠 pidFile(#reapStale)兜底,这里直接返回,别每次启动都白 throw 一次。
497
+ if (process.platform === 'win32') return { killed: 0 };
477
498
  const { execFile } = await import('node:child_process');
478
499
  const net = await import('node:net');
479
500