dsh-plugin-mesh 0.0.0-stage → 0.3.30

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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1199 -2
  3. package/client/client.js +958 -0
  4. package/cordis.patch.yml +80 -0
  5. package/install.sh +142 -0
  6. package/lib/_rehearsal-peer.mjs +229 -0
  7. package/lib/_selftest-capabilities.mjs +631 -0
  8. package/lib/_selftest-client.mjs +249 -0
  9. package/lib/_selftest-discovery.mjs +51 -0
  10. package/lib/_selftest-newsession.mjs +124 -0
  11. package/lib/_selftest-prompt.mjs +97 -0
  12. package/lib/_selftest-tsnet-live.mjs +169 -0
  13. package/lib/_selftest-tsnet-tailnet.mjs +418 -0
  14. package/lib/_selftest-tsnet.mjs +647 -0
  15. package/lib/capabilities.js +786 -0
  16. package/lib/conversation.js +59 -0
  17. package/lib/discovery.js +744 -0
  18. package/lib/identity.js +136 -0
  19. package/lib/index.js +2079 -0
  20. package/lib/prompt.js +50 -0
  21. package/lib/scan.js +118 -0
  22. package/lib/tsnet/bridge.js +71 -0
  23. package/lib/tsnet/checksums.js +19 -0
  24. package/lib/tsnet/download.js +384 -0
  25. package/lib/tsnet/manager.js +655 -0
  26. package/package.json +118 -4
  27. package/scripts/__pycache__/mesh-tsnet-merge.cpython-312.pyc +0 -0
  28. package/scripts/_selftest-tsnet-merge.py +168 -0
  29. package/scripts/build-sidecar.sh +372 -0
  30. package/scripts/check-loadable.mjs +154 -0
  31. package/scripts/check-tarball.mjs +106 -0
  32. package/scripts/check-tdz.mjs +78 -0
  33. package/scripts/check-version.mjs +32 -0
  34. package/scripts/fix-android-tls-align.py +87 -0
  35. package/scripts/mesh-tsnet-merge.py +345 -0
  36. package/scripts/mesh-tsnet-onboarding.md +98 -0
  37. package/scripts/publish-assets.py +213 -0
  38. package/scripts/push-via-api.py +262 -0
  39. package/scripts/release-plugin.sh +129 -0
  40. package/scripts/restart-dsh.sh +308 -0
  41. package/scripts/submit-to-awesome.py +212 -0
  42. package/scripts/verify-lan-mirror.mjs +57 -0
  43. package/sidecar/androidbin_linux.go +39 -0
  44. package/sidecar/androidnet_linux.go +414 -0
  45. package/sidecar/androidnet_other.go +15 -0
  46. package/sidecar/go.mod +51 -0
  47. package/sidecar/go.sum +239 -0
  48. package/sidecar/main.go +850 -0
package/package.json CHANGED
@@ -1,6 +1,120 @@
1
1
  {
2
2
  "name": "dsh-plugin-mesh",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.3.30",
4
+ "type": "module",
5
+ "description": "DSH Mesh:局域网自动发现同网段的 DSH 实例、显示每台机器上报的能力,并双向派发任务;可用内置的用户态 Tailscale 节点跨互联网组网。Discovers other DSH instances on the LAN, shows the capabilities each one reports, and dispatches tasks between machines in both directions, with an optional userspace Tailscale node for links across networks.",
6
+ "license": "MIT",
7
+ "author": "peng456 (https://github.com/peng456)",
8
+ "keywords": [
9
+ "dsh",
10
+ "dsh-plugin",
11
+ "deepseek-harness",
12
+ "dsh-desktop",
13
+ "mesh",
14
+ "lan",
15
+ "multicast",
16
+ "discovery",
17
+ "remote",
18
+ "tailscale",
19
+ "tsnet",
20
+ "tailnet",
21
+ "wireguard"
22
+ ],
23
+ "homepage": "https://github.com/peng456/dsh-plugin-mesh#readme",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/peng456/dsh-plugin-mesh.git"
27
+ },
28
+ "bugs": {
29
+ "url": "https://github.com/peng456/dsh-plugin-mesh/issues"
30
+ },
31
+ "main": "./lib/index.js",
32
+ "exports": {
33
+ ".": "./lib/index.js",
34
+ "./client": "./client/client.js",
35
+ "./cordis.patch.yml": "./cordis.patch.yml",
36
+ "./package.json": "./package.json"
37
+ },
38
+ "files": [
39
+ "lib",
40
+ "client",
41
+ "sidecar",
42
+ "scripts",
43
+ "cordis.patch.yml",
44
+ "README.md",
45
+ "LICENSE",
46
+ "install.sh"
47
+ ],
48
+ "scripts": {
49
+ "selftest": "node lib/_selftest-tsnet.mjs",
50
+ "selftest:tsnet": "node lib/_selftest-tsnet.mjs",
51
+ "selftest:live": "node lib/_selftest-tsnet-live.mjs",
52
+ "selftest:tailnet": "node lib/_selftest-tsnet-tailnet.mjs",
53
+ "selftest:lan": "node lib/_selftest-discovery.mjs",
54
+ "selftest:client": "node lib/_selftest-client.mjs",
55
+ "selftest:prompt": "node lib/_selftest-prompt.mjs",
56
+ "selftest:caps": "node lib/_selftest-capabilities.mjs",
57
+ "selftest:newsession": "node lib/_selftest-newsession.mjs",
58
+ "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:client && npm run selftest:caps",
59
+ "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.js && node --check lib/discovery.js && node --check lib/conversation.js && node --check lib/identity.js && node --check lib/capabilities.js && node --check lib/prompt.js && node --check lib/scan.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check client/client.js && npm run check:loadable",
60
+ "build:sidecar": "bash scripts/build-sidecar.sh",
61
+ "verify:mirror": "node scripts/verify-lan-mirror.mjs",
62
+ "check:loadable": "node scripts/check-loadable.mjs --allow-missing-runtime-dep",
63
+ "check:deploy": "node scripts/check-loadable.mjs",
64
+ "check:scope": "python3 tools/scopecheck.py lib/index.js",
65
+ "prepublishOnly": "npm test && node scripts/check-tarball.mjs"
66
+ },
67
+ "publishConfig": {
68
+ "registry": "https://registry.npmjs.org/",
69
+ "access": "public"
70
+ },
71
+ "peerDependencies": {
72
+ "@deepseek-ai/schemastery": "*",
73
+ "@deepseek-ai/dsh-tools": "*",
74
+ "@deepseek-ai/dsh-llm": "*",
75
+ "@deepseek-ai/dsh-client-connection": "*",
76
+ "@deepseek-ai/dsh-client-ui-primitives": "*",
77
+ "@deepseek-ai/dsh-client-ui-slots": "*",
78
+ "@deepseek-ai/dsh-client-locale": "*"
79
+ },
80
+ "peerDependenciesMeta": {
81
+ "@deepseek-ai/schemastery": {
82
+ "optional": true
83
+ },
84
+ "@deepseek-ai/dsh-tools": {
85
+ "optional": true
86
+ },
87
+ "@deepseek-ai/dsh-llm": {
88
+ "optional": true
89
+ },
90
+ "@deepseek-ai/dsh-client-connection": {
91
+ "optional": true
92
+ },
93
+ "@deepseek-ai/dsh-client-ui-primitives": {
94
+ "optional": true
95
+ },
96
+ "@deepseek-ai/dsh-client-ui-slots": {
97
+ "optional": true
98
+ },
99
+ "@deepseek-ai/dsh-client-locale": {
100
+ "optional": true
101
+ }
102
+ },
103
+ "dsh": {
104
+ "bundle": {
105
+ "patch": "./cordis.patch.yml"
106
+ },
107
+ "client": {
108
+ "platform": "web",
109
+ "inject": [
110
+ "@deepseek-ai/dsh-client-connection",
111
+ "@deepseek-ai/dsh-client-ui-primitives",
112
+ "@deepseek-ai/dsh-client-ui-slots",
113
+ "@deepseek-ai/dsh-client-locale"
114
+ ]
115
+ }
116
+ },
117
+ "engines": {
118
+ "node": ">=20"
119
+ }
120
+ }
@@ -0,0 +1,168 @@
1
+ #!/usr/bin/env python3
2
+ """_selftest-tsnet-merge.py —— 验证 mesh-tsnet-merge.py 真的「只改该改的键」。
3
+
4
+ 核心用例是复现对端 文超-win 的那份 cordis.patch.yml:`- id: mesh` 里已经有
5
+ 22 个键(含 permissionPreset: danger-full-access)、中文注释、以及一个**已经
6
+ 存在的** tsnetDownloadSources(带列表子行)。合格的合并必须做到:
7
+ · permissionPreset 等兄弟键一个不丢
8
+ · tsnetDownloadSources 被整体替换,且不留孤儿 `- 'url'` 子行
9
+ · 幂等(跑两次结果一致)
10
+ · 注释、行尾、BOM 原样
11
+ """
12
+ import os
13
+ import re
14
+ import sys
15
+ import tempfile
16
+
17
+ import yaml
18
+
19
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
20
+
21
+ import importlib.util
22
+
23
+ _spec = importlib.util.spec_from_file_location(
24
+ "mtm", os.path.join(os.path.dirname(os.path.abspath(__file__)), "mesh-tsnet-merge.py")
25
+ )
26
+ mtm = importlib.util.module_from_spec(_spec)
27
+ _spec.loader.exec_module(mtm)
28
+
29
+ FAILS = []
30
+ PASSES = []
31
+
32
+
33
+ def check(name, cond, detail=""):
34
+ if cond:
35
+ PASSES.append(name)
36
+ else:
37
+ FAILS.append("%s %s" % (name, detail))
38
+
39
+
40
+ # 复现对端状态:22 个 config 键 + 注释 + 已存在的 tsnetDownloadSources
41
+ FIXTURE_A = """\
42
+ # Your patch layer for this dsh profile, applied after every bundle layer:
43
+ # a top-level YAML array of loader patch entries.
44
+
45
+ # 2026-09-17 mesh 加固。历史故障记录:permissionPreset 回落 workspace-write 后
46
+ # Windows ACL 沙箱 fail-closed,入站任务全挂,所以这里必须钉死 danger-full-access。
47
+ - id: mesh
48
+ config:
49
+ enabled: true
50
+ machineName: ''
51
+ port: 45917
52
+ useMulticast: true
53
+ scanOnStart: true
54
+ scanIntervalMs: 60000
55
+ scanRanges: []
56
+ scanPorts: []
57
+ scanConcurrency: 64
58
+ scanTimeoutMs: 800
59
+ pingIntervalMs: 10000
60
+ announceIntervalMs: 5000
61
+ peerTtlMs: 20000
62
+ requirePairing: false
63
+ agentPreset: standard
64
+ # 这条是保命设置,不能被 tsnet 的合并冲掉
65
+ permissionPreset: danger-full-access
66
+ workspaceRoot: 'C:\\Users\\86189'
67
+ maxWakesPerThread: 30
68
+ threadWindowMs: 3600000
69
+ threadCooldownMs: 20000
70
+ minTaskChars: 24
71
+ tsnetDownloadSources:
72
+ - 'http://old.example/'
73
+ - id: server-deck
74
+ disabled: true
75
+ """
76
+
77
+ NON_TSNET_KEYS = [
78
+ "enabled", "machineName", "port", "useMulticast", "scanOnStart", "scanIntervalMs",
79
+ "scanRanges", "scanPorts", "scanConcurrency", "scanTimeoutMs", "pingIntervalMs",
80
+ "announceIntervalMs", "peerTtlMs", "requirePairing", "agentPreset",
81
+ "permissionPreset", "workspaceRoot", "maxWakesPerThread", "threadWindowMs",
82
+ "threadCooldownMs", "minTaskChars",
83
+ ]
84
+
85
+ # ── 用例 1:对端的真实场景 ──
86
+ new_text, notes = mtm.merge(FIXTURE_A, {
87
+ "tsnetEnabled": True,
88
+ "tsnetDownloadSources": ["http://192.168.1.6:8791/"],
89
+ })
90
+ doc = yaml.safe_load(new_text)
91
+ mesh = doc[0]["config"]
92
+
93
+ check("1.1 根节点仍是数组且只有 mesh/server-deck 两条", isinstance(doc, list) and len(doc) == 2, repr(doc)[:120])
94
+ check("1.2 `- id: mesh` 仍只有 1 处", len(re.findall(r"^\s*-\s*id:\s*mesh\s*$", new_text, re.M)) == 1)
95
+ check("1.3 保命键 permissionPreset 存活", mesh.get("permissionPreset") == "danger-full-access", repr(mesh.get("permissionPreset")))
96
+ for k in NON_TSNET_KEYS:
97
+ check("1.4 兄弟键保留: %s" % k, k in mesh, "丢失")
98
+ check("1.5 workspaceRoot 原样(Windows 路径没被转义搞坏)", mesh.get("workspaceRoot") == "C:\\Users\\86189", repr(mesh.get("workspaceRoot")))
99
+ check("1.6 port 保持 45917", mesh.get("port") == 45917)
100
+ check("1.7 tsnetEnabled=true", mesh.get("tsnetEnabled") is True)
101
+ check("1.8 tsnetDownloadSources 换成新源", mesh.get("tsnetDownloadSources") == ["http://192.168.1.6:8791/"], repr(mesh.get("tsnetDownloadSources")))
102
+ check("1.9 旧源没有残留", "old.example" not in new_text)
103
+ check("1.10 没有孤儿列表行(每个 `- ` 都在列表键之下)", len(re.findall(r"^\s+- ", new_text, re.M)) == len(re.findall(r"^\s+- ", new_text, re.M)))
104
+ check("1.11 注释保留(含中文)", "保命设置" in new_text and "历史故障记录" in new_text)
105
+ check("1.12 另一个条目未被动过", doc[1] == {"id": "server-deck", "disabled": True})
106
+ check("1.13 tsnetEnabled 只出现一次", len(re.findall(r"^\s*tsnetEnabled:", new_text, re.M)) == 1)
107
+ check("1.14 tsnetDownloadSources 只出现一次", len(re.findall(r"^\s*tsnetDownloadSources:", new_text, re.M)) == 1)
108
+
109
+ # ── 用例 2:幂等 ──
110
+ again, _ = mtm.merge(new_text, {
111
+ "tsnetEnabled": True,
112
+ "tsnetDownloadSources": ["http://192.168.1.6:8791/"],
113
+ })
114
+ check("2.1 跑两次结果逐字节一致(幂等)", again == new_text)
115
+ yaml.safe_load(again)
116
+ check("2.2 二次合并后 permissionPreset 仍在", yaml.safe_load(again)[0]["config"].get("permissionPreset") == "danger-full-access")
117
+
118
+ # ── 用例 3:完全没有 mesh 条目 ──
119
+ fresh = "# 新 profile\n- id: server-deck\n disabled: true\n"
120
+ t3, n3 = mtm.merge(fresh, {"tsnetDownloadSources": ["http://192.168.1.6:8791/"]})
121
+ d3 = yaml.safe_load(t3)
122
+ check("3.1 无 mesh 条目时新建", len(d3) == 2 and d3[1]["id"] == "mesh", repr(d3))
123
+ check("3.2 新条目 config 正确", d3[1]["config"]["tsnetDownloadSources"] == ["http://192.168.1.6:8791/"])
124
+
125
+ # ── 用例 4:CRLF + BOM 原样保留 ──
126
+ crlf = ("\ufeff# 头\n- id: mesh\n config:\n enabled: true\n permissionPreset: danger-full-access\n").replace("\n", "\r\n")
127
+ t4, _ = mtm.merge(crlf, {"tsnetEnabled": True})
128
+ check("4.1 BOM 保留", t4.startswith("\ufeff"))
129
+ check("4.2 CRLF 保留且未混入裸 LF", t4.count("\r\n") == t4.count("\n") and t4.count("\r\n") > 0, "crlf=%d lf=%d" % (t4.count("\r\n"), t4.count("\n")))
130
+ check("4.3 CRLF 下结构正确", yaml.safe_load(t4)[0]["config"]["permissionPreset"] == "danger-full-access")
131
+
132
+ # ── 用例 5:重复 mesh 条目要拒写,而不是猜 ──
133
+ dup = "- id: mesh\n config:\n enabled: true\n- id: mesh\n config:\n enabled: false\n"
134
+ try:
135
+ mtm.merge(dup, {"tsnetEnabled": True})
136
+ check("5.1 重复条目应报错", False, "居然没报错")
137
+ except mtm.MergeError as e:
138
+ check("5.1 重复条目拒写并说明原因", "重复" in str(e) or "2 个" in str(e), str(e))
139
+
140
+ # ── 用例 6:条目存在但没有 config ──
141
+ noconf = "- id: mesh\n name: mesh\n- id: server-deck\n disabled: true\n"
142
+ t6, _ = mtm.merge(noconf, {"tsnetEnabled": True})
143
+ check("6.1 无 config 时补上", yaml.safe_load(t6)[0]["config"]["tsnetEnabled"] is True)
144
+
145
+ # ── 用例 7:真写盘 + 备份 + --check ──
146
+ with tempfile.TemporaryDirectory() as td:
147
+ p = os.path.join(td, "cordis.patch.yml")
148
+ with open(p, "wb") as fh:
149
+ fh.write(FIXTURE_A.encode("utf-8"))
150
+ before = open(p, "rb").read()
151
+ sys.argv = ["x", "--file", p, "--download-source", "http://192.168.1.6:8791/", "--enabled", "--apply"]
152
+ mtm.main()
153
+ after = open(p, "rb").read()
154
+ baks = [f for f in os.listdir(td) if f.startswith("cordis.patch.yml.bak-merge-")]
155
+ check("7.1 写盘后文件真的变了", after != before)
156
+ check("7.2 留下了备份", len(baks) == 1, repr(os.listdir(td)))
157
+ check("7.3 备份内容 == 改动前", open(os.path.join(td, baks[0]), "rb").read() == before)
158
+ check("7.4 写盘结果结构正确", yaml.safe_load(after.decode("utf-8"))[0]["config"]["permissionPreset"] == "danger-full-access")
159
+ check("7.5 写盘后仍是 LF、无 BOM", after.count(b"\r\n") == 0 and not after.startswith(b"\xef\xbb\xbf"))
160
+
161
+ print("=" * 60)
162
+ for p_ in PASSES:
163
+ print(" PASS %s" % p_)
164
+ for f_ in FAILS:
165
+ print(" FAIL %s" % f_)
166
+ print("=" * 60)
167
+ print("通过 %d / 失败 %d" % (len(PASSES), len(FAILS)))
168
+ sys.exit(1 if FAILS else 0)
@@ -0,0 +1,372 @@
1
+ #!/usr/bin/env bash
2
+ # Cross-compile the DSH Mesh tsnet sidecar for every supported platform,
3
+ # gzip each binary, and emit a sha256 manifest for the plugin's downloader.
4
+ #
5
+ # End users never run this: the plugin downloads the published artifacts and
6
+ # verifies them against checksums.txt. This script only runs when cutting a
7
+ # sidecar release.
8
+ #
9
+ # Usage:
10
+ # scripts/build-sidecar.sh # build into dist/sidecar/
11
+ # scripts/build-sidecar.sh --publish # build, then create/update the GitHub release
12
+ #
13
+ # Requires: go (build-time only). No cgo, so no cross toolchain is needed.
14
+ set -euo pipefail
15
+
16
+ REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
17
+ SIDECAR_DIR="$REPO_ROOT/sidecar"
18
+ DIST_DIR="$REPO_ROOT/dist/sidecar"
19
+
20
+ # The release tag is tied to the sidecar control-API protocol, not the plugin
21
+ # version: the plugin pins a protocol number and refuses mismatched binaries.
22
+ PROTOCOL_VERSION=1
23
+ RELEASE_TAG="sidecar-v${PROTOCOL_VERSION}"
24
+ # 发布目标仓库。必须与 lib/tsnet/download.js 里的 REPO 一致,否则插件会去
25
+ # 另一个仓库找二进制。
26
+ REPO="peng456/dsh-plugin-mesh"
27
+
28
+ # Windows/arm64 is omitted deliberately: it is vanishingly rare and each extra
29
+ # target costs a full rebuild of the whole tailscale dependency tree.
30
+ #
31
+ # android/* 是**独立平台**,不是 linux 的别名 —— 它的产物形态必须不同,见
32
+ # 循环里的 ANDROID 分支。两者不能共用一个资产。
33
+ ALL_TARGETS=(
34
+ "darwin/amd64"
35
+ "darwin/arm64"
36
+ "linux/amd64"
37
+ "linux/arm64"
38
+ "android/amd64"
39
+ "android/arm64"
40
+ "windows/amd64"
41
+ )
42
+ TARGETS=("${ALL_TARGETS[@]}")
43
+
44
+ # 构建串行、且限制单个 go build 的包级并行度。
45
+ # 这台机器只有 2 物理核 / 8GB 内存:先前按目标并行的做法把 load average
46
+ # 推到 300+、疯狂换页,总耗时反而长得多。
47
+ JOBS="${DSH_BUILD_JOBS:-2}"
48
+
49
+ PUBLISH=0
50
+ while [ $# -gt 0 ]; do
51
+ case "$1" in
52
+ --publish) PUBLISH=1; shift ;;
53
+ --targets)
54
+ IFS=',' read -r -a TARGETS <<< "$2"
55
+ shift 2
56
+ ;;
57
+ --jobs)
58
+ JOBS="$2"
59
+ shift 2
60
+ ;;
61
+ -h|--help) sed -n '2,20p' "$0"; exit 0 ;;
62
+ *) echo "unknown option: $1" >&2; exit 2 ;;
63
+ esac
64
+ done
65
+
66
+ command -v go >/dev/null 2>&1 || { echo "go toolchain not found; it is required only for building releases" >&2; exit 1; }
67
+
68
+ # Derive the protocol version straight from the source so the tag can never
69
+ # drift from what the binary actually speaks.
70
+ SRC_PROTOCOL="$(grep -E '^const ProtocolVersion = ' "$SIDECAR_DIR/main.go" | grep -oE '[0-9]+')"
71
+ if [ "$SRC_PROTOCOL" != "$PROTOCOL_VERSION" ]; then
72
+ echo "ProtocolVersion mismatch: main.go says $SRC_PROTOCOL, script says $PROTOCOL_VERSION" >&2
73
+ exit 1
74
+ fi
75
+
76
+ # 构建戳用 sidecar 源码的 git 提交哈希,而不是时间戳。
77
+ #
78
+ # Go 构建是可复现的(实测:同输入连编两次逐字节相同),所以拿内容哈希当戳时,
79
+ # **未改动的平台重编后产物完全一致、sha256 不变**。这样补一个新平台(比如后来
80
+ # 才需要 linux/arm64)不会让已装的机器被迫重下 8.5MB。用时间戳则每次发版全平台
81
+ # 哈希都变,所有机器都要重下一遍。
82
+ BUILD_STAMP="$(git -C "$REPO_ROOT" log -1 --format=%h -- sidecar 2>/dev/null || true)"
83
+ [ -n "$BUILD_STAMP" ] || BUILD_STAMP="nogit"
84
+ if [ -n "$(git -C "$REPO_ROOT" status --porcelain -- sidecar 2>/dev/null)" ]; then
85
+ BUILD_STAMP="${BUILD_STAMP}-dirty"
86
+ fi
87
+ rm -rf "$DIST_DIR"
88
+ mkdir -p "$DIST_DIR"
89
+
90
+ echo "==> 编译 tsnet sidecar (protocol=v$PROTOCOL_VERSION, stamp=$BUILD_STAMP)"
91
+ echo "==> Go: $(go version)"
92
+ echo
93
+
94
+ # 串行构建:每个目标都要完整重编整棵 tailscale 依赖树,并行只会互相抢 CPU。
95
+ failed=0
96
+ for target in "${TARGETS[@]}"; do
97
+ os="${target%%/*}"
98
+ arch="${target##*/}"
99
+ asset="dsh-mesh-tsnet-${os}-${arch}"
100
+ [ "$os" = "windows" ] && asset="${asset}.exe"
101
+
102
+ # 默认:CGO_ENABLED=0 的**全静态 ET_EXEC**(-buildmode=exe),没有任何
103
+ # PT_INTERP / DT_NEEDED,glibc 与 musl(Alpine) 上都能直接跑。
104
+ #
105
+ # 刻意**不给桌面 linux 加 -buildmode=pie**:PIE 会把解释器钉成
106
+ # /lib64/ld-linux-x86-64.so.2(arm64 是 /lib/ld-linux-aarch64.so.1),
107
+ # Alpine 这类 musl 发行版根本没有该路径,等于用一点安全加固换掉一整类系统。
108
+ # Android 才真正需要 PIE,而且需要的形态还不一样 → 见下面的分支。
109
+ go_os="$os"
110
+ buildmode=()
111
+ extra_ldflags=""
112
+
113
+ if [ "$os" = "android" ]; then
114
+ # ANDROID:**必须**是 PIE(ET_DYN)。
115
+ #
116
+ # Android 从 5.0 起只允许 PIE 可执行文件,静态 ET_EXEC 会在 exec 阶段被
117
+ # bionic 直接拒掉,原话就一句(真机实测,2026-10):
118
+ # error: "…/dsh-mesh-tsnet" has unexpected e_type: 2
119
+ # 与 glibc/bionic、CGO_ENABLED 与否、权限都无关,就是 ELF 类型不对。
120
+ #
121
+ # 但**只加 -buildmode=pie 还不够**:Go 内部链接器产的 PIE 带
122
+ # PT_INTERP=/lib/ld-linux-aarch64.so.1
123
+ # (实测 go1.25.5 linux/arm64),这个路径在 Android 上不存在 —— Android 的
124
+ # 加载器是 /system/bin/linker64,内核按 PT_INTERP 找 loader 会以 ENOENT
125
+ # 收场。所以必须用 -I 把解释器显式指到 bionic。
126
+ #
127
+ # 这么做的底气来自实测的 ELF 内容:这种 PIE 里
128
+ # · e_type=3(ET_DYN)、DT_NEEDED 为空、动态符号表无未定义符号
129
+ # · 重定位全是 R_AARCH64_RELATIVE(linux/arm64 实测 113089 条)、.rela.plt 为空
130
+ # 也就是说它不依赖任何 libc,bionic 加载时只需要按 load bias 把 RELATIVE
131
+ # 重定位刷一遍即可 —— 正是 Android 自家 PIE 可执行文件的形态。
132
+ #
133
+ # 用 GOOS=android 而不是 GOOS=linux(0.3.11 改)。
134
+ #
135
+ # 真机实测的最后一跳就卡在这里:tailscale 的 tsdial.SystemDial 会走
136
+ # net/netns 的 Dialer,而
137
+ # netns_linux.go 的构建约束是 `linux && !android`
138
+ # netns_android.go 是 `android`
139
+ # 所以 GOOS=linux 编出来的产物用的是 linux 版 controlC —— 它对每个 socket 调
140
+ # netmon.DefaultRouteInterface()
141
+ # 拿默认路由接口名;而 Android 上 /proc/net/route 与 netlink 都是 EACCES,
142
+ # 于是它退化成绑 "lo"(或设 SO_MARK),拨号就出不去(sidecar 内部的裸
143
+ # net.Dialer 直连同一地址却成功,正是这个差别)。GOOS=android 的 controlC
144
+ # 在没有 Java 回调时**什么都不做**,拨号就是普通 net.Dialer。
145
+ #
146
+ # 其余配套:netmon 换成 android 的 polling 实现(不再碰 netlink)、
147
+ # Go 的 x509 走 goos.IsAndroid 分支读 /system/etc/security/cacerts、
148
+ # androidbin/androiddns 的 (android && !cgo) 分支照样注册。不需要 libc,所以
149
+ # CGO_ENABLED=0 即可(本机实测能构建出正确的 ET_DYN + /system/bin/linker64)。
150
+ go_os=android
151
+ buildmode=(-buildmode=pie)
152
+ extra_ldflags="-I /system/bin/linker64"
153
+ # 例外:android/amd64 用内部链接器编不出来 —— Go 直接报
154
+ # android/amd64 requires external (cgo) linking, but cgo is not enabled
155
+ # arm64 没这个限制(实测可编)。我们手上没有 NDK,也没有 x86_64 Android 的
156
+ # 实测机器,所以那一份退回 GOOS=linux:代价是它仍带着上面说的 netns 坑,
157
+ # 但那只影响"模拟器上的 Termux"这种冷门场景,不值得为它引入一整套 NDK 构建。
158
+ if [ "$arch" = "amd64" ]; then
159
+ go_os=linux
160
+ fi
161
+ fi
162
+
163
+ echo " [start] $os/$arch ($(date -u +%H:%M:%S))"
164
+ if GOOS="$go_os" GOARCH="$arch" CGO_ENABLED=0 GOMAXPROCS="$JOBS" \
165
+ go build -C "$SIDECAR_DIR" -p "$JOBS" -trimpath ${buildmode[@]+"${buildmode[@]}"} \
166
+ -ldflags="-s -w -X main.buildStamp=$BUILD_STAMP $extra_ldflags" \
167
+ -o "$DIST_DIR/$asset" . 2>"$DIST_DIR/.build-$os-$arch.err"; then
168
+ if [ "$os" = "android" ]; then
169
+ # Go 内部链接器把 PT_TLS 的 p_align 写成寄存器宽度(8),ARM64 bionic 要求
170
+ # ≥64,不改的话加载期就被拒。见 scripts/fix-android-tls-align.py 的说明。
171
+ python3 "$REPO_ROOT/scripts/fix-android-tls-align.py" "$DIST_DIR/$asset"
172
+ fi
173
+ gzip -9 -f "$DIST_DIR/$asset"
174
+ echo " [done ] $os/$arch $(du -h "$DIST_DIR/${asset}.gz" | cut -f1) ($(date -u +%H:%M:%S))"
175
+ else
176
+ echo " [FAIL ] $os/$arch"
177
+ sed 's/^/ /' "$DIST_DIR/.build-$os-$arch.err" | head -20
178
+ failed=1
179
+ fi
180
+ done
181
+ rm -f "$DIST_DIR"/.build-*.err
182
+
183
+ if [ "$failed" -ne 0 ]; then
184
+ echo
185
+ echo "构建失败,未生成发布产物。" >&2
186
+ exit 1
187
+ fi
188
+
189
+ # 断言 android 产物的 ELF 形态 —— 这一步是为了让这两类坑不可能再溜出去,它们
190
+ # 当初的表现都是「设备上直接起不来」而本地怎么看都"编好了"。构建期检查是唯一
191
+ # 能在发布前拦住它们的地方:
192
+ # 1) ET_EXEC(非 PIE) → bionic: has unexpected e_type: 2
193
+ # 2) PT_TLS p_align=8 → bionic: TLS segment is underaligned (ARM64 要 >=64)
194
+ echo
195
+ echo "==> 校验 android 产物形态(ET_DYN + bionic 解释器 + TLS 对齐)"
196
+ python3 - "$DIST_DIR" <<'PY'
197
+ import gzip, os, struct, sys
198
+
199
+ dist = sys.argv[1]
200
+ EXPECTED_INTERP = b"/system/bin/linker64"
201
+ MIN_TLS_ALIGN = {183: 64, 62: 16} # AArch64 / x86_64 上 bionic 的最低要求
202
+ bad = []
203
+ checked = 0
204
+ for name in sorted(os.listdir(dist)):
205
+ if not (name.startswith("dsh-mesh-tsnet-android-") and name.endswith(".gz")):
206
+ continue
207
+ raw = gzip.open(os.path.join(dist, name), "rb").read()
208
+ if raw[:4] != b"\x7fELF" or raw[4] != 2:
209
+ bad.append(f"{name}: 不是 64 位 ELF")
210
+ continue
211
+ e_machine = struct.unpack_from("<H", raw, 18)[0]
212
+ e_type = struct.unpack_from("<H", raw, 16)[0]
213
+ phoff, = struct.unpack_from("<Q", raw, 32)
214
+ phentsize, phnum = struct.unpack_from("<HH", raw, 54)
215
+ interp, tls_align = None, None
216
+ for i in range(phnum):
217
+ off = phoff + i * phentsize
218
+ p_type = struct.unpack_from("<I", raw, off)[0]
219
+ if p_type == 3: # PT_INTERP
220
+ io_, sz = struct.unpack_from("<QQ", raw, off + 8)[0], struct.unpack_from("<Q", raw, off + 32)[0]
221
+ interp = raw[io_:io_ + sz].rstrip(b"\0")
222
+ elif p_type == 7: # PT_TLS,p_align 在 +48
223
+ tls_align = struct.unpack_from("<Q", raw, off + 48)[0]
224
+ want_tls = MIN_TLS_ALIGN.get(e_machine)
225
+ if e_type != 3:
226
+ bad.append(f"{name}: e_type={e_type},Android 只吃 ET_DYN(3)")
227
+ elif interp != EXPECTED_INTERP:
228
+ bad.append(f"{name}: 解释器是 {interp!r},应为 {EXPECTED_INTERP!r}(Android 上没有 /lib/ld-linux-*)")
229
+ elif want_tls is not None and tls_align is not None and tls_align < want_tls:
230
+ # 只在"确实有 PT_TLS 且对齐不够"时才算错。GOOS=android 的内部链接器
231
+ # 根本不发 PT_TLS 段(TLS 相关的那个分支只对 Hlinux 生效),所以
232
+ # tls_align 为 None 是正常的、也是好事 —— bionic 只在有该段时才挑对齐。
233
+ bad.append(f"{name}: PT_TLS p_align={tls_align},bionic 要求 >= {want_tls}")
234
+ else:
235
+ checked += 1
236
+ print(f" ✓ {name}: ET_DYN + {interp.decode()} + TLS p_align={tls_align}")
237
+
238
+ if bad:
239
+ print("\n".join(" ✗ " + b for b in bad), file=sys.stderr)
240
+ sys.exit("android 产物形态不对,拒绝生成发布清单")
241
+ if checked == 0:
242
+ sys.exit("没有找到任何 android 产物,构建清单不完整")
243
+ PY
244
+
245
+ echo
246
+ echo "==> 生成 sha256 清单"
247
+ (
248
+ cd "$DIST_DIR"
249
+ # sha256sum on Linux, shasum on macOS; the manifest format is identical.
250
+ if command -v sha256sum >/dev/null 2>&1; then
251
+ sha256sum ./*.gz > checksums.txt
252
+ else
253
+ shasum -a 256 ./*.gz > checksums.txt
254
+ fi
255
+ cat checksums.txt
256
+ )
257
+
258
+ echo
259
+ echo "==> 写入 lib/tsnet/checksums.js(插件内置的 sha256 白名单)"
260
+ node - "$DIST_DIR/checksums.txt" "$REPO_ROOT/lib/tsnet/checksums.js" <<'NODE'
261
+ const fs = require("node:fs");
262
+ const [, , manifestPath, outPath] = process.argv;
263
+ const entries = fs
264
+ .readFileSync(manifestPath, "utf8")
265
+ .split("\n")
266
+ .map((line) => line.trim())
267
+ .filter(Boolean)
268
+ .map((line) => {
269
+ const [hash, name] = line.split(/\s+/);
270
+ return [name.replace(/^\.\//, ""), hash];
271
+ })
272
+ .sort(([a], [b]) => a.localeCompare(b));
273
+
274
+ const rows = entries.map(([name, hash]) => ` "${name}": "${hash}",`).join("\n");
275
+ const content = `/**
276
+ * sidecar 二进制的 sha256 白名单 —— 由 scripts/build-sidecar.sh 发布时生成,请勿手改。
277
+ *
278
+ * 为什么钉在这里而不是下载 release 里的 checksums.txt:
279
+ * 下载源在国内必须走第三方镜像(直连 GitHub 实测不通)。如果校验和也跟着
280
+ * 二进制一起从镜像拿,一个恶意镜像就能同时替换两者,校验形同虚设。钉在
281
+ * 插件源码里(与二进制分属不同渠道)才构成真正的完整性约束。
282
+ *
283
+ * 键是资产名,值是 gzip 压缩后的 sha256。
284
+ */
285
+ export const PINNED_CHECKSUMS = {
286
+ ${rows}
287
+ };
288
+ `;
289
+ fs.writeFileSync(outPath, content);
290
+ console.log(` 已写入 ${entries.length} 条校验和 → ${outPath}`);
291
+ NODE
292
+
293
+ echo
294
+ echo "==> 产物目录: $DIST_DIR"
295
+ ls -lh "$DIST_DIR" | tail -n +2 | awk '{printf " %-42s %s\n", $9, $5}'
296
+
297
+ if [ "$PUBLISH" -eq 0 ]; then
298
+ echo
299
+ echo "未发布。加 --publish 会创建 GitHub release $RELEASE_TAG 并上传资产。"
300
+ exit 0
301
+ fi
302
+
303
+ echo
304
+ echo "==> 发布到 GitHub release $RELEASE_TAG"
305
+
306
+ # 优先用 gh;没装就走 REST API(这台机器上没装 gh,且 releases API 与
307
+ # uploads 域名实测都通,所以 API 这条路是可靠的)。
308
+ if command -v gh >/dev/null 2>&1; then
309
+ if gh release view "$RELEASE_TAG" >/dev/null 2>&1; then
310
+ gh release upload "$RELEASE_TAG" "$DIST_DIR"/*.gz "$DIST_DIR"/checksums.txt --clobber
311
+ else
312
+ gh release create "$RELEASE_TAG" \
313
+ --title "tsnet sidecar v$PROTOCOL_VERSION" \
314
+ --notes "DSH Mesh 互联网自组网 sidecar 二进制(协议 v$PROTOCOL_VERSION,构建 $BUILD_STAMP)。" \
315
+ "$DIST_DIR"/*.gz "$DIST_DIR"/checksums.txt
316
+ fi
317
+ else
318
+ TOKEN="$(python3 - <<'PY'
319
+ import os, re
320
+ p = os.path.expanduser("~/.git-credentials")
321
+ for line in open(p):
322
+ m = re.match(r'https://([^:]+):([^@]+)@github\.com\s*$', line.strip())
323
+ if m:
324
+ print(m.group(2))
325
+ break
326
+ PY
327
+ )"
328
+ [ -n "$TOKEN" ] || { echo "找不到 github token(~/.git-credentials),无法发布" >&2; exit 1; }
329
+
330
+ API="https://api.github.com/repos/$REPO"
331
+ # 已存在就复用,不存在就创建。release id 是上传资产的必填项。
332
+ RELEASE_ID="$(curl -s -m 30 -H "Authorization: token $TOKEN" "$API/releases/tags/$RELEASE_TAG" \
333
+ | python3 -c 'import json,sys; print(json.load(sys.stdin).get("id",""))' 2>/dev/null)"
334
+
335
+ if [ -z "$RELEASE_ID" ]; then
336
+ echo " 创建 release $RELEASE_TAG"
337
+ RELEASE_ID="$(curl -s -m 30 -X POST \
338
+ -H "Authorization: token $TOKEN" \
339
+ -H "Content-Type: application/json" \
340
+ "$API/releases" \
341
+ -d "{\"tag_name\":\"$RELEASE_TAG\",\"name\":\"tsnet sidecar v$PROTOCOL_VERSION\",\"body\":\"DSH Mesh 互联网自组网 sidecar 二进制(协议 v$PROTOCOL_VERSION,构建 $BUILD_STAMP)。\\n\\n插件会自动下载对应平台的 .gz 并按 lib/tsnet/checksums.js 里内置的 sha256 校验,终端用户无需安装 Go 或 Tailscale。\"}" \
342
+ | python3 -c 'import json,sys; print(json.load(sys.stdin).get("id",""))' 2>/dev/null)"
343
+ else
344
+ echo " 复用已有 release $RELEASE_TAG (id=$RELEASE_ID)"
345
+ fi
346
+ [ -n "$RELEASE_ID" ] || { echo "创建/查找 release 失败" >&2; exit 1; }
347
+
348
+ for f in "$DIST_DIR"/*.gz "$DIST_DIR"/checksums.txt; do
349
+ name="$(basename "$f")"
350
+ # 同名资产已存在时先删掉,否则 API 会报 already_exists
351
+ OLD_ID="$(curl -s -m 30 -H "Authorization: token $TOKEN" "$API/releases/$RELEASE_ID/assets" \
352
+ | python3 -c "
353
+ import json,sys
354
+ for a in json.load(sys.stdin):
355
+ if a.get('name')=='$name': print(a.get('id')); break
356
+ " 2>/dev/null)"
357
+ if [ -n "$OLD_ID" ]; then
358
+ curl -s -m 30 -X DELETE -H "Authorization: token $TOKEN" "$API/releases/assets/$OLD_ID" >/dev/null
359
+ echo " 替换 $name"
360
+ else
361
+ echo " 上传 $name"
362
+ fi
363
+ curl -s -m 600 -X POST \
364
+ -H "Authorization: token $TOKEN" \
365
+ -H "Content-Type: application/octet-stream" \
366
+ --data-binary "@$f" \
367
+ "https://uploads.github.com/repos/$REPO/releases/$RELEASE_ID/assets?name=$name" \
368
+ | python3 -c 'import json,sys; d=json.load(sys.stdin); print(" ✓", d.get("name"), d.get("size"), "字节") if d.get("id") else print(" ✗", d.get("message"))'
369
+ done
370
+ fi
371
+
372
+ echo "✓ 已发布: https://github.com/$REPO/releases/tag/$RELEASE_TAG"