huaweicloud-devkit 2.0.0-next.2 → 2.0.0-next.4
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 +3 -1
- package/package.json +3 -1
- package/plugins/huaweicloud-core/.claude-plugin/plugin.json +16 -3
- package/plugins/huaweicloud-core/.codex-plugin/plugin.json +16 -3
- package/plugins/huaweicloud-core/.cursor-plugin/plugin.json +16 -3
- package/plugins/huaweicloud-core/.hermes-plugin/plugin.json +16 -3
- package/plugins/huaweicloud-core/.mcp.json +55 -1
- package/plugins/huaweicloud-core/.workbuddy-plugin/plugin.json +16 -3
- package/plugins/huaweicloud-core/dist/agents/codex-config.js +374 -0
- package/plugins/huaweicloud-core/dist/agents/codex-desktop.js +8 -1
- package/plugins/huaweicloud-core/dist/agents/codex.js +9 -0
- package/plugins/huaweicloud-core/dist/agents/opencode-config.js +157 -31
- package/plugins/huaweicloud-core/dist/agents/opencode.js +129 -1
- package/plugins/huaweicloud-core/dist/approval-gate.js +1185 -0
- package/plugins/huaweicloud-core/dist/approval-ledger.js +2331 -0
- package/plugins/huaweicloud-core/dist/approval-roster.js +89 -0
- package/plugins/huaweicloud-core/dist/approval-types.js +1 -0
- package/plugins/huaweicloud-core/dist/approvals-cli.js +4 -4
- package/plugins/huaweicloud-core/dist/data/icons-manifest.v1.json +23 -5
- package/plugins/huaweicloud-core/dist/dep/receipts.js +65 -5
- package/plugins/huaweicloud-core/dist/hcloud-cli.js +1 -1
- package/plugins/huaweicloud-core/dist/hcloud-plan.js +77 -56
- package/plugins/huaweicloud-core/dist/lib/approval-mode.js +32 -0
- package/plugins/huaweicloud-core/dist/lib/approval-tokens.js +18 -4
- package/plugins/huaweicloud-core/dist/lib/call-trace.js +7 -14
- package/plugins/huaweicloud-core/dist/lib/confirm-language.js +50 -0
- package/plugins/huaweicloud-core/dist/lib/credentials.js +9 -9
- package/plugins/huaweicloud-core/dist/lib/hdkit/hdkit-gate.js +1398 -0
- package/plugins/huaweicloud-core/dist/lib/hdkit/hdkitservice-api.js +362 -32
- package/plugins/huaweicloud-core/dist/lib/hdkit/sandbox-pool.js +6 -16
- package/plugins/huaweicloud-core/dist/lib/opencode-ask-rule.js +262 -0
- package/plugins/huaweicloud-core/dist/lib/opencode-saved-perms.js +282 -0
- package/plugins/huaweicloud-core/dist/lib/supplemental-redaction.js +116 -0
- package/plugins/huaweicloud-core/dist/lib/tool-schema-parts.js +31 -0
- package/plugins/huaweicloud-core/dist/lib/workspace-glob.js +442 -0
- package/plugins/huaweicloud-core/dist/mcp-config-io.js +28 -1
- package/plugins/huaweicloud-core/dist/mcp-protocol.js +75 -4
- package/plugins/huaweicloud-core/dist/mcp-server.js +6560 -898
- package/plugins/huaweicloud-core/dist/mcp-server.js.map +4 -4
- package/plugins/huaweicloud-core/dist/mcp-stdio-transport.js +14 -4
- package/plugins/huaweicloud-core/dist/packs/auth/approval.js +249 -0
- package/plugins/huaweicloud-core/dist/packs/auth/tools.js +44 -44
- package/plugins/huaweicloud-core/dist/packs/huaweicloud-cli/tools.js +119 -112
- package/plugins/huaweicloud-core/dist/packs/obs/approval.js +110 -0
- package/plugins/huaweicloud-core/dist/packs/obs/tools.js +7 -2
- package/plugins/huaweicloud-core/dist/packs/registry.js +19 -1
- package/plugins/huaweicloud-core/dist/packs/sandbox/approval.js +245 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-account.js +156 -23
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-credentials.js +13 -1
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-hwexec.js +136 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-session.js +11 -1
- package/plugins/huaweicloud-core/dist/packs/sandbox/handlers-tunnel.js +1 -0
- package/plugins/huaweicloud-core/dist/packs/sandbox/schemas.js +79 -9
- package/plugins/huaweicloud-core/dist/packs/sandbox/tools.js +28 -9
- package/plugins/huaweicloud-core/dist/packs/secrets/approval.js +46 -0
- package/plugins/huaweicloud-core/dist/packs/secrets/tools.js +4 -1
- package/plugins/huaweicloud-core/dist/packs/update/approval.js +79 -0
- package/plugins/huaweicloud-core/dist/packs/update/tools.js +8 -1
- package/plugins/huaweicloud-core/dist/packs/voucher/tools.js +1 -1
- package/plugins/huaweicloud-core/dist/packs-configure.js +74 -0
- package/plugins/huaweicloud-core/dist/safety/classify-text.js +36 -0
- package/plugins/huaweicloud-core/dist/safety/policy.js +2 -0
- package/plugins/huaweicloud-core/dist/sandbox/deploy-check.js +1 -1
- package/plugins/huaweicloud-core/dist/sandbox/devbridge-auth.js +65 -14
- package/plugins/huaweicloud-core/dist/sandbox/devbridge-cleanup.js +422 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose-flow.js +66 -16
- package/plugins/huaweicloud-core/dist/sandbox/devbridge-expose.js +13 -10
- package/plugins/huaweicloud-core/dist/sandbox/devbridge-keepalive.js +42 -2
- package/plugins/huaweicloud-core/dist/sandbox/devbridge-key.js +11 -3
- package/plugins/huaweicloud-core/dist/sandbox/devbridge-tunnel.js +6 -0
- package/plugins/huaweicloud-core/dist/sandbox/devbridge-validation.js +10 -1
- package/plugins/huaweicloud-core/dist/sandbox/hwexec-task.js +244 -0
- package/plugins/huaweicloud-core/dist/setup-cli.js +42 -4
- package/plugins/huaweicloud-core/dist/tool-definitions.js +9 -1
- package/plugins/huaweicloud-core/dist/tool-schemas.js +32 -6
- package/plugins/huaweicloud-core/dist/tools.js +76 -9
- package/plugins/huaweicloud-core/dist/update-registry.js +358 -5
- package/plugins/huaweicloud-core/dist/update-upgrade.js +1083 -14
- package/plugins/huaweicloud-core/dist/vendor-gate.js +2 -2
- package/plugins/huaweicloud-core/hooks/huaweicloud-safety.mjs +150 -1
- package/plugins/huaweicloud-core/hooks/huaweicloud-safety.py +53 -3
- package/plugins/huaweicloud-core/openclaw.plugin.json +1 -1
- package/plugins/huaweicloud-core/safety/policy.json +18 -11
- package/plugins/huaweicloud-core/safety/rules/cloud-risk-rules.json +114 -10
- package/plugins/huaweicloud-core/skills/huawei-sandbox/SKILL.md +190 -138
- package/plugins/huaweicloud-core/skills/huawei-sandbox/references/resource-pool.md +36 -12
- package/plugins/huaweicloud-core/skills/huawei-voucher/SKILL.md +2 -0
- package/plugins/huaweicloud-core/skills/huaweicloud-cli-and-auth/SKILL.md +5 -5
- package/plugins/huaweicloud-core/skills/huaweicloud-safety/SKILL.md +13 -8
- package/plugins/huaweicloud-core/skills/huaweicloud-safety/references/approvals.md +78 -23
- package/plugins/huaweicloud-core/skills/huaweicloud-troubleshooting/SKILL.md +21 -19
- package/plugins/huaweicloud-core/src/agents/codex-config.ts +432 -0
- package/plugins/huaweicloud-core/src/agents/codex-desktop.ts +8 -1
- package/plugins/huaweicloud-core/src/agents/codex.ts +10 -0
- package/plugins/huaweicloud-core/src/agents/opencode-config.ts +198 -30
- package/plugins/huaweicloud-core/src/agents/opencode.ts +157 -1
- package/plugins/huaweicloud-core/src/approval-gate.ts +1306 -0
- package/plugins/huaweicloud-core/src/approval-ledger.ts +2446 -0
- package/plugins/huaweicloud-core/src/approval-roster.ts +127 -0
- package/plugins/huaweicloud-core/src/approval-types.ts +237 -0
- package/plugins/huaweicloud-core/src/approvals-cli.ts +4 -4
- package/plugins/huaweicloud-core/src/data/icons-manifest.v1.json +23 -5
- package/plugins/huaweicloud-core/src/dep/receipts.ts +84 -5
- package/plugins/huaweicloud-core/src/hcloud-cli.ts +3 -0
- package/plugins/huaweicloud-core/src/hcloud-plan.ts +93 -63
- package/plugins/huaweicloud-core/src/lib/approval-mode.ts +34 -0
- package/plugins/huaweicloud-core/src/lib/approval-tokens.ts +19 -4
- package/plugins/huaweicloud-core/src/lib/call-trace.ts +7 -17
- package/plugins/huaweicloud-core/src/lib/confirm-language.ts +51 -0
- package/plugins/huaweicloud-core/src/lib/credentials.ts +9 -8
- package/plugins/huaweicloud-core/src/lib/hdkit/hdkit-gate.ts +1428 -0
- package/plugins/huaweicloud-core/src/lib/hdkit/hdkitservice-api.ts +377 -30
- package/plugins/huaweicloud-core/src/lib/hdkit/sandbox-pool.ts +8 -15
- package/plugins/huaweicloud-core/src/lib/opencode-ask-rule.ts +350 -0
- package/plugins/huaweicloud-core/src/lib/opencode-saved-perms.ts +354 -0
- package/plugins/huaweicloud-core/src/lib/supplemental-redaction.ts +129 -0
- package/plugins/huaweicloud-core/src/lib/tool-schema-parts.ts +40 -0
- package/plugins/huaweicloud-core/src/lib/workspace-glob.ts +414 -0
- package/plugins/huaweicloud-core/src/mcp-config-io.ts +27 -1
- package/plugins/huaweicloud-core/src/mcp-protocol.ts +88 -5
- package/plugins/huaweicloud-core/src/mcp-server.ts +13 -0
- package/plugins/huaweicloud-core/src/mcp-stdio-transport.ts +14 -4
- package/plugins/huaweicloud-core/src/packs/auth/approval.ts +302 -0
- package/plugins/huaweicloud-core/src/packs/auth/tools.ts +54 -45
- package/plugins/huaweicloud-core/src/packs/huaweicloud-cli/tools.ts +139 -120
- package/plugins/huaweicloud-core/src/packs/obs/approval.ts +122 -0
- package/plugins/huaweicloud-core/src/packs/obs/tools.ts +7 -2
- package/plugins/huaweicloud-core/src/packs/registry.ts +42 -1
- package/plugins/huaweicloud-core/src/packs/sandbox/approval.ts +296 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-account.ts +168 -23
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-credentials.ts +11 -1
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-hwexec.ts +228 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-session.ts +11 -1
- package/plugins/huaweicloud-core/src/packs/sandbox/handlers-tunnel.ts +1 -0
- package/plugins/huaweicloud-core/src/packs/sandbox/schemas.ts +100 -8
- package/plugins/huaweicloud-core/src/packs/sandbox/tools.ts +31 -8
- package/plugins/huaweicloud-core/src/packs/secrets/approval.ts +50 -0
- package/plugins/huaweicloud-core/src/packs/secrets/tools.ts +4 -1
- package/plugins/huaweicloud-core/src/packs/update/approval.ts +87 -0
- package/plugins/huaweicloud-core/src/packs/update/tools.ts +8 -1
- package/plugins/huaweicloud-core/src/packs/voucher/tools.ts +1 -1
- package/plugins/huaweicloud-core/src/packs-configure.ts +75 -0
- package/plugins/huaweicloud-core/src/safety/classify-text.ts +40 -0
- package/plugins/huaweicloud-core/src/safety/policy.ts +7 -0
- package/plugins/huaweicloud-core/src/sandbox/deploy-check.ts +1 -1
- package/plugins/huaweicloud-core/src/sandbox/devbridge-auth.ts +74 -14
- package/plugins/huaweicloud-core/src/sandbox/devbridge-cleanup.ts +509 -0
- package/plugins/huaweicloud-core/src/sandbox/devbridge-expose-flow.ts +70 -18
- package/plugins/huaweicloud-core/src/sandbox/devbridge-expose.ts +26 -10
- package/plugins/huaweicloud-core/src/sandbox/devbridge-keepalive.ts +41 -2
- package/plugins/huaweicloud-core/src/sandbox/devbridge-key.ts +9 -3
- package/plugins/huaweicloud-core/src/sandbox/devbridge-tunnel.ts +24 -0
- package/plugins/huaweicloud-core/src/sandbox/devbridge-validation.ts +11 -1
- package/plugins/huaweicloud-core/src/sandbox/hwexec-task.ts +304 -0
- package/plugins/huaweicloud-core/src/setup-cli.ts +45 -3
- package/plugins/huaweicloud-core/src/tool-definitions.ts +9 -1
- package/plugins/huaweicloud-core/src/tool-schemas.ts +39 -6
- package/plugins/huaweicloud-core/src/tools.ts +124 -10
- package/plugins/huaweicloud-core/src/update-registry.ts +340 -5
- package/plugins/huaweicloud-core/src/update-upgrade.ts +1130 -14
- package/plugins/huaweicloud-core/src/vendor-gate.ts +2 -2
|
@@ -38,6 +38,8 @@ export function loadPolicy(path) {
|
|
|
38
38
|
blockedSecretOperations: toStringArray(raw.blockedSecretOperations, 'blockedSecretOperations'),
|
|
39
39
|
blockedSecretCliPatterns: toStringArray(raw.blockedSecretCliPatterns, 'blockedSecretCliPatterns'),
|
|
40
40
|
blockedApprovalCliPatterns: toStringArray(raw.blockedApprovalCliPatterns, 'blockedApprovalCliPatterns'),
|
|
41
|
+
blockedAccountSwitchCliPatterns: toStringArray(raw.blockedAccountSwitchCliPatterns, 'blockedAccountSwitchCliPatterns'),
|
|
42
|
+
blockedGatedCliPatterns: toStringArray(raw.blockedGatedCliPatterns, 'blockedGatedCliPatterns'),
|
|
41
43
|
writeOperationPrefixes,
|
|
42
44
|
readOperationPrefixes: toStringArray(raw.readOperationPrefixes, 'readOperationPrefixes'),
|
|
43
45
|
readOperationExceptions: toStringArray(raw.readOperationExceptions, 'readOperationExceptions'),
|
|
@@ -11,7 +11,7 @@ import { DEVBRIDGE_BAD_GATEWAY_MARKER, DEVBRIDGE_PORT_NOT_CONFIGURED_MARKER, DEV
|
|
|
11
11
|
import { stripTerminalEscapes } from "./sandbox-output.js";
|
|
12
12
|
export const TUNNEL_URL_PATTERN = /TUNNEL_URL:(https:\/\/[A-Za-z0-9_-]+-\d+\.devbridge-s2\.hwtunnel\.com)/;
|
|
13
13
|
export function buildExposeRemediation(port) {
|
|
14
|
-
return `In the sandbox: source /tmp/hw_api_key 2>/dev/null; devbridge
|
|
14
|
+
return `In the sandbox: source /tmp/hw_api_key 2>/dev/null; for T in $(devbridge list 2>/dev/null | awk '{gsub(/\\033\\]133;C\\007/, ""); if ($1 !~ /^Tunnel/ && $1 !~ /^No$/) print $1}'); do devbridge port list "$T" 2>/dev/null | awk -v P=${port} '{gsub(/\\033\\]133;C\\007/, ""); if ($1 == P) f=1} END {exit f ? 0 : 1}' && devbridge delete "$T" 2>/dev/null || true; done; devbridge create <name>; devbridge port create <tunnelId> -p ${port} --protocol http -a; if command -v setsid >/dev/null 2>&1; then setsid nohup devbridge host <tunnelId> -p ${port} -e 72 > /tmp/host.log 2>&1 < /dev/null & else nohup devbridge host <tunnelId> -p ${port} -e 72 > /tmp/host.log 2>&1 < /dev/null & fi; disown 2>/dev/null || true; the loop deletes ONLY the tunnels whose port list contains ${port} (any tunnel name — query each tunnel's ports with devbridge port list; a name-based match would miss the custom-named tunnels this flow itself creates), INCLUDING a keepalive-protected tunnel bound to THIS port — a port cannot have two tunnels, so the same-port tunnel is always replaced; all OTHER ports, other sessions and keepalive-protected tunnels on other ports are preserved (never wipe every tunnel here — a global delete kills every session's tunnels). The gsub strips OSC 133 shell-integration markers that wrap every output line on integration-enabled terminals — without it the CLI receives glued tunnel IDs it rejects and the delete silently no-ops. If deploy_nginx reported a different (auto-incremented) port in its "port" field, use THAT port instead of the one shown here. Full procedure in huawei-sandbox skill, Step 7 (Expose via DevBridge).`;
|
|
15
15
|
}
|
|
16
16
|
export function parseDeployCheckOutput(stdout) {
|
|
17
17
|
// Strip ANSI escape sequences (CSI color/cursor codes and OSC shell-integration markers)
|
|
@@ -1,6 +1,27 @@
|
|
|
1
1
|
import { stripTerminalEscapes } from "./sandbox-output.js";
|
|
2
2
|
import { runOneShot } from "./devbridge-exec.js";
|
|
3
3
|
import { evaluateDevbridgeVersion } from "./devbridge-validation.js";
|
|
4
|
+
import { canonCode, cleanMessage, gateFoldPayload, isVersionGateError, safeMessageText, safeReadField, } from "../lib/hdkit/hdkit-gate.js";
|
|
5
|
+
// 409 门禁在 relay 出口的统一折叠(v2 扩展,台账记录):三个 catch 位共用——
|
|
6
|
+
// 自动创建、自愈重建、配额清单读取。authMode/attempts 保留(探测到的真实状态,
|
|
7
|
+
// 与配额失败信封同款,台账记录该取舍)。
|
|
8
|
+
function versionGateFailure(error, port, authMode, attempts) {
|
|
9
|
+
const fold = gateFoldPayload(error);
|
|
10
|
+
return {
|
|
11
|
+
ok: false,
|
|
12
|
+
failure: {
|
|
13
|
+
ok: false,
|
|
14
|
+
port,
|
|
15
|
+
error: fold.message,
|
|
16
|
+
error_code: fold.code,
|
|
17
|
+
...(fold.clientVersion ? { clientVersion: fold.clientVersion } : {}),
|
|
18
|
+
...(fold.minVersion ? { minVersion: fold.minVersion } : {}),
|
|
19
|
+
gateRemediation: fold.remediation,
|
|
20
|
+
authMode: authMode || 'UNKNOWN',
|
|
21
|
+
attempts,
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
}
|
|
4
25
|
// The DevBridge auth waterfall, extracted from devbridge-tunnel so the auth
|
|
5
26
|
// probe script, its stdout parser, and (with the devbridge-tunnel
|
|
6
27
|
// modularization) the expose flow's auth/version gate form one cohesive auth
|
|
@@ -16,8 +37,12 @@ import { evaluateDevbridgeVersion } from "./devbridge-validation.js";
|
|
|
16
37
|
// fallback (devbridge-key.ts) when keyring injection is unavailable.
|
|
17
38
|
// AK/SK login (--access-key/--secret-key) was REMOVED: devbridge authentication is
|
|
18
39
|
// now fixed to API Key only (定稿决策,2026-11-04).
|
|
19
|
-
// Every tier performs a real `devbridge auth login --api-key`
|
|
20
|
-
// `auth status`
|
|
40
|
+
// Every tier performs a real `devbridge auth login --api-key` (exit code checked),
|
|
41
|
+
// then verifies with `auth status` AND a real authenticated API call
|
|
42
|
+
// (`devbridge list`); on failure the waterfall falls through. The list check is
|
|
43
|
+
// required because a stale key can leave a "Logged in" local token while
|
|
44
|
+
// server-side calls return 40100 — without it the probe reports a usable auth
|
|
45
|
+
// and the auto-create self-heal never triggers.
|
|
21
46
|
// DB_ATTEMPT_* lines are non-sensitive diagnostics for support escalation.
|
|
22
47
|
// The HOST orchestrates an auto-create fallback between probe rounds: when the
|
|
23
48
|
// first probe returns NO_CREDENTIAL, the host calls ensureDevbridgeKey() and
|
|
@@ -37,7 +62,13 @@ export function buildDevbridgeAuthProbe() {
|
|
|
37
62
|
`DB_VERSION=$(devbridge version 2>/dev/null | head -1)`,
|
|
38
63
|
`echo "DB_VERSION=\${DB_VERSION}"`,
|
|
39
64
|
`DB_OK=0`,
|
|
40
|
-
`db_login_ok() {
|
|
65
|
+
`db_login_ok() {`,
|
|
66
|
+
// 本地 token 可能仍显示 Logged in,但 API key 已在服务端失效(实测
|
|
67
|
+
// list/renew 返回 40100)。因此额外做一次真实鉴权 API 调用,确保探针
|
|
68
|
+
// 结果可用(否则 auto-create 自愈不会触发)。
|
|
69
|
+
` devbridge auth status 2>/dev/null | grep -q "Logged in" || return 1`,
|
|
70
|
+
` devbridge list >/dev/null 2>&1`,
|
|
71
|
+
`}`,
|
|
41
72
|
`db_diag() { echo "DB_ATTEMPT_$1=$2"; }`,
|
|
42
73
|
``,
|
|
43
74
|
`# ---- Tier 1: API Key from the sandbox keyring (platform auto-injection) ----`,
|
|
@@ -67,8 +98,7 @@ export function buildDevbridgeAuthProbe() {
|
|
|
67
98
|
` db_diag KEYRING "hwcloud-not-installed"`,
|
|
68
99
|
`fi`,
|
|
69
100
|
`if [ -n "$HW_DB_KEY" ]; then`,
|
|
70
|
-
` devbridge auth login --api-key "$HW_DB_KEY" >/tmp/db_auth.log 2>&1`,
|
|
71
|
-
` if db_login_ok; then`,
|
|
101
|
+
` if devbridge auth login --api-key "$HW_DB_KEY" >/tmp/db_auth.log 2>&1 && db_login_ok; then`,
|
|
72
102
|
` echo "DB_AUTH_MODE=API_KEY_KEYRING"`,
|
|
73
103
|
` DB_OK=1`,
|
|
74
104
|
` else`,
|
|
@@ -82,8 +112,7 @@ export function buildDevbridgeAuthProbe() {
|
|
|
82
112
|
`if [ "$DB_OK" -eq 0 ]; then`,
|
|
83
113
|
` source /tmp/hw_api_key 2>/dev/null`,
|
|
84
114
|
` if [ -n "$HW_API_KEY" ]; then`,
|
|
85
|
-
` devbridge auth login --api-key "$HW_API_KEY" >/tmp/db_auth.log 2>&1`,
|
|
86
|
-
` if db_login_ok; then`,
|
|
115
|
+
` if devbridge auth login --api-key "$HW_API_KEY" >/tmp/db_auth.log 2>&1 && db_login_ok; then`,
|
|
87
116
|
` echo "DB_AUTH_MODE=API_KEY_FILE"`,
|
|
88
117
|
` DB_OK=1`,
|
|
89
118
|
` else`,
|
|
@@ -188,8 +217,11 @@ export async function gateExposeAuth(workspaceId, username, port, { poolType, ke
|
|
|
188
217
|
effectiveAuthMode = 'API_KEY_AUTO';
|
|
189
218
|
}
|
|
190
219
|
}
|
|
191
|
-
catch {
|
|
192
|
-
//
|
|
220
|
+
catch (error) {
|
|
221
|
+
// 409 门禁即时折叠:自愈 catch 原样吞掉会多跑一轮泛化 relay 调用才折
|
|
222
|
+
// 叠(round 3);其余自愈失败仍走泛化降级
|
|
223
|
+
if (isVersionGateError(error))
|
|
224
|
+
return versionGateFailure(error, port, authMode, attempts);
|
|
193
225
|
}
|
|
194
226
|
}
|
|
195
227
|
// keyring/文件均无 key → host 调 relay API 自动创建 → 注入沙箱 → 重跑 probe
|
|
@@ -204,15 +236,33 @@ export async function gateExposeAuth(workspaceId, username, port, { poolType, ke
|
|
|
204
236
|
}
|
|
205
237
|
}
|
|
206
238
|
catch (error) {
|
|
207
|
-
//
|
|
208
|
-
|
|
209
|
-
|
|
239
|
+
// 门禁先裁(round 25/MUST 4):配额比较此前先求值且自选分支——登记
|
|
240
|
+
// 过的载体 code 视图谎报配额码即被误路由进清 key 信封(配额 hint、空
|
|
241
|
+
// currentKeys、gateRemediation 丢失)。isVersionGateError 对登记载体零
|
|
242
|
+
// 读返回种类裁决(round 24),谎报视图无从介入;未登记载体照旧先经安
|
|
243
|
+
// 全读判配额——canonCode 读过卫队(round 14),抛出型 getter 按缺失
|
|
244
|
+
if (isVersionGateError(error))
|
|
245
|
+
return versionGateFailure(error, port, authMode, attempts);
|
|
246
|
+
if (canonCode(safeReadField(error, 'code')) === 'HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED') {
|
|
247
|
+
// 配额清单读取本身遭遇 409:门禁优先(清 key 引导拿不出 currentKeys);
|
|
248
|
+
// 其余读取失败仍降级为空清单
|
|
249
|
+
let keysHint = [];
|
|
250
|
+
try {
|
|
251
|
+
keysHint = await keyUpgrade.listKeysForQuotaHint();
|
|
252
|
+
}
|
|
253
|
+
catch (listError) {
|
|
254
|
+
if (isVersionGateError(listError))
|
|
255
|
+
return versionGateFailure(listError, port, authMode, attempts);
|
|
256
|
+
}
|
|
257
|
+
// 消息读同样过卫队与清洗口(round 14):拒读/空白按缺失——字段缺省,
|
|
258
|
+
// 信封的 error_code/hint/currentKeys 不受影响
|
|
259
|
+
const quotaMessage = cleanMessage(safeMessageText(error));
|
|
210
260
|
return {
|
|
211
261
|
ok: false,
|
|
212
262
|
failure: {
|
|
213
263
|
ok: false,
|
|
214
264
|
port,
|
|
215
|
-
error:
|
|
265
|
+
...(quotaMessage ? { error: quotaMessage } : {}),
|
|
216
266
|
error_code: 'HDKIT_DEVBRIDGE_KEY_QUOTA_EXCEEDED',
|
|
217
267
|
authMode: authMode || 'UNKNOWN',
|
|
218
268
|
attempts,
|
|
@@ -221,7 +271,8 @@ export async function gateExposeAuth(workspaceId, username, port, { poolType, ke
|
|
|
221
271
|
},
|
|
222
272
|
};
|
|
223
273
|
}
|
|
224
|
-
// 其他自动创建失败 → 继续走原有降级路径(可能 keyring/file
|
|
274
|
+
// 其他自动创建失败 → 继续走原有降级路径(可能 keyring/file 后续可用);
|
|
275
|
+
// 门禁折叠已在本 catch 顶部先裁(round 25/MUST 4)
|
|
225
276
|
}
|
|
226
277
|
}
|
|
227
278
|
}
|
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
import { runOneShot } from "./devbridge-exec.js";
|
|
2
|
+
import { stripTerminalEscapes } from "./sandbox-output.js";
|
|
3
|
+
import { DEVBRIDGE_TUNNEL_ID_PATTERN } from "./devbridge-validation.js";
|
|
4
|
+
import { buildKeepaliveTunnelsReadScript, installKeepaliveWatchdog, parseKeepaliveTunnelsOutput, } from "./devbridge-keepalive.js";
|
|
5
|
+
// The DevBridge selective-cleanup family, ported from dev's 1.1.x cleanup wave
|
|
6
|
+
// (97c4bc8a + 7118d61f + 603554d0 + 6100026e + 43fa459e): delete-all is
|
|
7
|
+
// intentionally NOT used in any automated path — it kills other sessions' and
|
|
8
|
+
// other ports' tunnels on a shared sandbox. Cleanup removes only orphan tunnel
|
|
9
|
+
// records/hosts and (for expose) tunnels bound to the same port, preserving
|
|
10
|
+
// other ports, other sessions, and keepalive-protected tunnels. Same-port is
|
|
11
|
+
// the one documented exception: a keepalive-protected tunnel on the target
|
|
12
|
+
// port is replaced, because a port cannot have two tunnels.
|
|
13
|
+
// The lock serializes concurrent cleanups (connect + expose can overlap on one
|
|
14
|
+
// sandbox); the stale threshold (10min) sits above the worst-case hold
|
|
15
|
+
// (state 60x2 + apply 60x2 + sync ~150 + release ≈ 450s) so a second cleanup
|
|
16
|
+
// cannot break a lock that is still legitimately held.
|
|
17
|
+
// v2 divergence from dev (recorded): the state and apply scripts carry the
|
|
18
|
+
// data-disk PATH export on the same first line as a distinguishing token
|
|
19
|
+
// (#999 anchor doctrine — the e2e fake recognizes scripts by first line, and a
|
|
20
|
+
// standalone export first line is byte-identical to the auth probe's opening
|
|
21
|
+
// line; dev has no first-line-recognizing fake, so dev's scripts keep the
|
|
22
|
+
// export standalone).
|
|
23
|
+
const DEVBRIDGE_PATH_EXPORT = 'export PATH="/workspace/.local/bin:$HOME/.huawei/bin:$PATH"';
|
|
24
|
+
const DEVBRIDGE_LOCK_PATH = '/tmp/devbridge-cleanup.lock';
|
|
25
|
+
// Worst-case hold: state 60x2 + apply 60x2 + sync ~150 + release 60 ≈ 450s.
|
|
26
|
+
const DEVBRIDGE_LOCK_STALE_MINUTES = 10;
|
|
27
|
+
const DEVBRIDGE_CLEANUP_TIMEOUT_MS = 60000;
|
|
28
|
+
// Tunnel IDs share validateTunnelId's charset — real IDs may contain 0/1/8/9,
|
|
29
|
+
// so parsing must not assume the base32 subset.
|
|
30
|
+
export function normalizeCleanupMode(raw) {
|
|
31
|
+
return raw === 'stale' || raw === 'all' || raw === 'none' ? raw : 'stale';
|
|
32
|
+
}
|
|
33
|
+
// Parse `devbridge list` (0.2.x plain table) behind OSC/CRLF noise. The header
|
|
34
|
+
// row is skipped explicitly; data rows start with the tunnel ID. A non-string
|
|
35
|
+
// input reads as empty (the stripTerminalEscapes seam's contract).
|
|
36
|
+
export function parseDevbridgeTunnelList(stdout) {
|
|
37
|
+
const text = stripTerminalEscapes(stdout);
|
|
38
|
+
const tunnels = [];
|
|
39
|
+
for (const line of text.split(/\r?\n/)) {
|
|
40
|
+
if (/^\s*Tunnel\s+ID\b/i.test(line))
|
|
41
|
+
continue;
|
|
42
|
+
const m = line.match(/^\s*([A-Za-z0-9_-]{4,32})\s+(.+)$/);
|
|
43
|
+
if (!m || !DEVBRIDGE_TUNNEL_ID_PATTERN.test(m[1]))
|
|
44
|
+
continue;
|
|
45
|
+
const id = m[1];
|
|
46
|
+
const rest = m[2];
|
|
47
|
+
const name = rest.trim().split(/\s{2,}|\t+/)[0] || '';
|
|
48
|
+
const portMatch = rest.match(/tunnel-(\d+)-/);
|
|
49
|
+
// The expiry read is anchored to the expiry column by the trailing Port
|
|
50
|
+
// Count (lookahead, so the matched text stays the clean "N unit"): a
|
|
51
|
+
// description that itself reads like a duration — `1minute`, `5days`,
|
|
52
|
+
// legal because descriptions reject spaces — must not poison the
|
|
53
|
+
// quota-mode oldest-first targeting (interrogate port-pr4 B-F2; dev's
|
|
54
|
+
// 97c4bc8a/43fa459e scan the whole row tail unanchored — deliberate
|
|
55
|
+
// v2 hardening now that the quota wiring makes the expiry load-bearing).
|
|
56
|
+
// A row whose shape no longer matches reads as null → sorts last in quota
|
|
57
|
+
// mode (fail-safe: never deleted on a guess). One arbitration remains:
|
|
58
|
+
// when EVERY candidate reads null the stable sort degenerates to list
|
|
59
|
+
// order and the first listed is deleted — the delete stays confined to
|
|
60
|
+
// live non-protected tunnels (the keepalive invariant holds regardless).
|
|
61
|
+
const expMatch = rest.match(/(\d+)\s*(day|days|hour|hours|minute|minutes)(?=\s+\d+\s*$)/i);
|
|
62
|
+
const unit = expMatch ? expMatch[2].toLowerCase() : '';
|
|
63
|
+
const multiplier = { day: 86400, days: 86400, hour: 3600, hours: 3600, minute: 60, minutes: 60 }[unit];
|
|
64
|
+
tunnels.push({
|
|
65
|
+
id,
|
|
66
|
+
name,
|
|
67
|
+
port: portMatch ? Number(portMatch[1]) : null,
|
|
68
|
+
expiryText: expMatch ? expMatch[0] : '',
|
|
69
|
+
expirySeconds: expMatch && multiplier ? Number(expMatch[1]) * multiplier : null,
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
return tunnels;
|
|
73
|
+
}
|
|
74
|
+
// Parse the DB_CLEANUP_PORTS section: one `TUNNEL_PORTS_<id>=<p>,<p>,` line
|
|
75
|
+
// per tunnel (the state script's per-tunnel `devbridge port list` queries).
|
|
76
|
+
// An absent or empty section yields an empty map — the callers then fall back
|
|
77
|
+
// to the name-shape/keepalive-URL port reads.
|
|
78
|
+
export function parseDevbridgePortQueries(stdout) {
|
|
79
|
+
const text = stripTerminalEscapes(stdout);
|
|
80
|
+
const out = new Map();
|
|
81
|
+
for (const m of text.matchAll(/^TUNNEL_PORTS_([A-Za-z0-9_-]{4,32})=(.*)$/gm)) {
|
|
82
|
+
const ports = (m[2] ?? '')
|
|
83
|
+
.split(',')
|
|
84
|
+
.map((p) => Number(p))
|
|
85
|
+
.filter((n) => Number.isSafeInteger(n) && n >= 1 && n <= 65535);
|
|
86
|
+
out.set(m[1], ports);
|
|
87
|
+
}
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
// Parse `pgrep -af "devbridge host"` output. The executable is anchored so a
|
|
91
|
+
// shell wrapper (`bash -c "...devbridge host..."`) is never mistaken for a
|
|
92
|
+
// real host process; the args are tokenized flag-by-flag so an ID can sit in
|
|
93
|
+
// any position. An unparseable host (no id, no port) is dropped — never killed
|
|
94
|
+
// blindly on a guess.
|
|
95
|
+
export function parseDevbridgeHostProcesses(stdout) {
|
|
96
|
+
const text = stripTerminalEscapes(stdout);
|
|
97
|
+
const hosts = [];
|
|
98
|
+
for (const line of text.split(/\r?\n/)) {
|
|
99
|
+
const m = line.match(/^\s*(\d+)\s+(.*)$/);
|
|
100
|
+
if (!m)
|
|
101
|
+
continue;
|
|
102
|
+
const execMatch = m[2].match(/^(?:\S*\/)?devbridge\s+host\b(.*)$/);
|
|
103
|
+
if (!execMatch)
|
|
104
|
+
continue;
|
|
105
|
+
const rest = execMatch[1].trim();
|
|
106
|
+
const tokens = rest ? rest.split(/\s+/) : [];
|
|
107
|
+
let id = null;
|
|
108
|
+
let port = null;
|
|
109
|
+
for (let i = 0; i < tokens.length; i += 1) {
|
|
110
|
+
const token = tokens[i];
|
|
111
|
+
if (token === '-p' && /^\d+$/.test(tokens[i + 1] || '')) {
|
|
112
|
+
port = Number(tokens[i + 1]);
|
|
113
|
+
i += 1;
|
|
114
|
+
}
|
|
115
|
+
else if (token === '-e') {
|
|
116
|
+
i += 1;
|
|
117
|
+
}
|
|
118
|
+
else if (token.startsWith('-')) {
|
|
119
|
+
// unknown flag: skip it
|
|
120
|
+
}
|
|
121
|
+
else if (!id && DEVBRIDGE_TUNNEL_ID_PATTERN.test(token) && !/^\d+$/.test(token)) {
|
|
122
|
+
id = token;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (!id && port == null)
|
|
126
|
+
continue;
|
|
127
|
+
hosts.push({ pid: Number(m[1]), id, port });
|
|
128
|
+
}
|
|
129
|
+
return hosts;
|
|
130
|
+
}
|
|
131
|
+
// Decide which tunnels/hosts to remove.
|
|
132
|
+
// - protected: keepalive TUNNELS entries (never removed unless mode=all or
|
|
133
|
+
// samePort — the one documented exception)
|
|
134
|
+
// - orphan: tunnel record with no live host — removed in stale/quota
|
|
135
|
+
// - orphan host: host process with no matching tunnel record — killed
|
|
136
|
+
// - quota: also removes the oldest non-protected live tunnels (maxExtra per
|
|
137
|
+
// call) until the new tunnel fits
|
|
138
|
+
export function planDevbridgeCleanup({ tunnels = [], hosts = [], keepalive = [], mode = 'stale', samePort = null, maxExtra = 1, } = {}) {
|
|
139
|
+
if (mode === 'none')
|
|
140
|
+
return { deleteIds: [], killPids: [] };
|
|
141
|
+
const tunnelIds = new Set(tunnels.map((t) => t.id));
|
|
142
|
+
const protectedIds = new Set(keepalive.map((k) => k.tunnelId).filter(Boolean));
|
|
143
|
+
// Port attribution as a per-tunnel SET: the authoritative port-list queries
|
|
144
|
+
// first (t.ports, any tunnel name), then the name-shape/keepalive-URL single
|
|
145
|
+
// reads. Sets cover multi-port tunnels for every same-port/host match.
|
|
146
|
+
const portsById = new Map();
|
|
147
|
+
for (const t of tunnels) {
|
|
148
|
+
const set = t.ports && t.ports.length > 0 ? t.ports : t.port != null ? [t.port] : [];
|
|
149
|
+
if (set.length > 0)
|
|
150
|
+
portsById.set(t.id, set);
|
|
151
|
+
}
|
|
152
|
+
for (const k of keepalive) {
|
|
153
|
+
const m = String(k.url || '').match(/-(\d+)\.devbridge-s2\./);
|
|
154
|
+
if (m && tunnelIds.has(k.tunnelId) && !portsById.has(k.tunnelId)) {
|
|
155
|
+
portsById.set(k.tunnelId, [Number(m[1])]);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
const hasPort = (id, port) => portsById.get(id)?.includes(port) ?? false;
|
|
159
|
+
if (mode === 'all') {
|
|
160
|
+
return { deleteIds: [...tunnelIds], killPids: hosts.map((h) => h.pid) };
|
|
161
|
+
}
|
|
162
|
+
const liveIds = new Set();
|
|
163
|
+
const mappedPids = new Set();
|
|
164
|
+
for (const h of hosts) {
|
|
165
|
+
if (!h.id && h.port == null)
|
|
166
|
+
continue; // unattributable host: never kill blindly
|
|
167
|
+
if (h.id && tunnelIds.has(h.id)) {
|
|
168
|
+
liveIds.add(h.id);
|
|
169
|
+
mappedPids.add(h.pid);
|
|
170
|
+
}
|
|
171
|
+
else if (h.port != null) {
|
|
172
|
+
for (const [id] of portsById) {
|
|
173
|
+
if (hasPort(id, h.port)) {
|
|
174
|
+
liveIds.add(id);
|
|
175
|
+
mappedPids.add(h.pid);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
const killPids = new Set(hosts.filter((h) => (h.id || h.port != null) && !mappedPids.has(h.pid)).map((h) => h.pid));
|
|
181
|
+
const samePortIds = samePort == null ? [] : tunnels.filter((t) => hasPort(t.id, samePort)).map((t) => t.id);
|
|
182
|
+
const orphanIds = tunnels.filter((t) => !protectedIds.has(t.id) && !liveIds.has(t.id)).map((t) => t.id);
|
|
183
|
+
const deleteSet = new Set([...orphanIds, ...samePortIds]);
|
|
184
|
+
if (mode === 'quota') {
|
|
185
|
+
const candidates = tunnels
|
|
186
|
+
.filter((t) => !protectedIds.has(t.id) && !deleteSet.has(t.id) && liveIds.has(t.id))
|
|
187
|
+
.sort((a, b) => (a.expirySeconds ?? Number.MAX_SAFE_INTEGER) - (b.expirySeconds ?? Number.MAX_SAFE_INTEGER));
|
|
188
|
+
for (let i = 0; i < Math.max(0, maxExtra) && i < candidates.length; i += 1) {
|
|
189
|
+
deleteSet.add(candidates[i].id);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
for (const h of hosts) {
|
|
193
|
+
// A host id-attributed to a record we are KEEPING is never a kill target,
|
|
194
|
+
// even when some deleted record's port claim matches the host's port (the
|
|
195
|
+
// structural guard makes the live-host invariant independent of the
|
|
196
|
+
// gateway's one-port-one-record doctrine). A host whose own record IS in
|
|
197
|
+
// the delete set still dies.
|
|
198
|
+
if (h.id && mappedPids.has(h.pid) && !deleteSet.has(h.id))
|
|
199
|
+
continue;
|
|
200
|
+
if (h.id && deleteSet.has(h.id))
|
|
201
|
+
killPids.add(h.pid);
|
|
202
|
+
else if (h.port != null) {
|
|
203
|
+
// A port-only host (the expose launch form, `devbridge host -p <port>`)
|
|
204
|
+
// cannot be attributed to a specific record. When ANY surviving record
|
|
205
|
+
// still claims the host's port, we cannot prove the host belongs to a
|
|
206
|
+
// deleted record — never kill on that guess; the next cleanup after the
|
|
207
|
+
// survivor is gone (or a same-port expose that replaced every same-port
|
|
208
|
+
// record) still fires.
|
|
209
|
+
const survivorClaimsPort = [...tunnelIds].some((id) => !deleteSet.has(id) && hasPort(id, h.port));
|
|
210
|
+
if (!survivorClaimsPort && [...deleteSet].some((id) => hasPort(id, h.port)))
|
|
211
|
+
killPids.add(h.pid);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return { deleteIds: [...deleteSet], killPids: [...killPids] };
|
|
215
|
+
}
|
|
216
|
+
export function buildDevbridgeCleanupApplyScript({ deleteIds = [], killPids = [] } = {}) {
|
|
217
|
+
for (const id of deleteIds) {
|
|
218
|
+
if (!DEVBRIDGE_TUNNEL_ID_PATTERN.test(String(id))) {
|
|
219
|
+
throw new Error(`devbridge cleanup: invalid tunnel id ${JSON.stringify(id)}`);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
for (const pid of killPids) {
|
|
223
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) {
|
|
224
|
+
throw new Error(`devbridge cleanup: invalid pid ${JSON.stringify(pid)}`);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return [
|
|
228
|
+
// #999 anchor doctrine: the export rides the APPLY marker line so the
|
|
229
|
+
// apply exec can never be misrecognized as the auth probe (a standalone
|
|
230
|
+
// export first line is byte-identical to the probe's).
|
|
231
|
+
`${DEVBRIDGE_PATH_EXPORT}; echo "DB_CLEANUP_APPLY"`,
|
|
232
|
+
// Re-check the process identity before killing: state→apply can take
|
|
233
|
+
// minutes, so a recycled PID must not hit an unrelated process.
|
|
234
|
+
...killPids.map((pid) => `if ps -p ${pid} -o args= 2>/dev/null | grep -q "devbridge host"; then kill ${pid} >/dev/null 2>&1 || true; fi`),
|
|
235
|
+
`sleep 1`,
|
|
236
|
+
...deleteIds.map((id) => `devbridge delete ${id} >/dev/null 2>&1 || true`),
|
|
237
|
+
`echo "DB_CLEANUP_DELETED=${deleteIds.join(',')}"`,
|
|
238
|
+
`echo "DB_CLEANUP_KILLED=${killPids.join(',')}"`,
|
|
239
|
+
].join('\n');
|
|
240
|
+
}
|
|
241
|
+
// The candidate-row filter shared by the PORTS query loop: strip the OSC 133
|
|
242
|
+
// shell-integration markers that wrap every line on integration-enabled
|
|
243
|
+
// shells (#946 — the plugin's TS parsers fold stripTerminalEscapes in for
|
|
244
|
+
// exactly this; a raw-ID extraction would hand the CLI glued IDs it rejects),
|
|
245
|
+
// then keep the first token of every non-header row. "No tunnels found." is
|
|
246
|
+
// excluded so an empty world yields zero candidates.
|
|
247
|
+
const DEVBRIDGE_OSC_FILTER = `{gsub(/\\033\\]133;C\\007/, ""); if ($1 !~ /^Tunnel/ && $1 !~ /^No$/) print $1}`;
|
|
248
|
+
export function buildDevbridgeCleanupStateScript() {
|
|
249
|
+
return [
|
|
250
|
+
// #999 anchor doctrine: the export rides the token-refresh init — a
|
|
251
|
+
// standalone export first line is byte-identical to the auth probe's
|
|
252
|
+
// opening line, and first-line readers cannot tell them apart.
|
|
253
|
+
`${DEVBRIDGE_PATH_EXPORT}; DB_KEY=""`,
|
|
254
|
+
// 40100 self-heal: a valid API key can coexist with an expired CLI token;
|
|
255
|
+
// without this refresh `devbridge list` returns 40100 and the cleanup
|
|
256
|
+
// silently skips even though the key is usable. Re-login from
|
|
257
|
+
// keyring/file only — never creates a key here.
|
|
258
|
+
`if command -v hwcloud >/dev/null 2>&1; then`,
|
|
259
|
+
` DB_KEY=$(hwcloud keyring get HW_DEVBRIDGE_API_KEY 2>&1 || true)`,
|
|
260
|
+
` case "$DB_KEY" in "devbridge_"*) : ;; *) DB_KEY="";; esac`,
|
|
261
|
+
`fi`,
|
|
262
|
+
`if [ -z "$DB_KEY" ] && [ -s /tmp/hw_api_key ]; then`,
|
|
263
|
+
` source /tmp/hw_api_key 2>/dev/null || true`,
|
|
264
|
+
` DB_KEY="\${HW_API_KEY:-}"`,
|
|
265
|
+
`fi`,
|
|
266
|
+
`if [ -n "$DB_KEY" ]; then devbridge auth login --api-key "$DB_KEY" >/dev/null 2>&1 || true; fi`,
|
|
267
|
+
`unset DB_KEY HW_API_KEY 2>/dev/null`,
|
|
268
|
+
`echo "DB_CLEANUP_TUNNELS_BEGIN"`,
|
|
269
|
+
`devbridge list 2>&1 || true`,
|
|
270
|
+
`echo "DB_CLEANUP_TUNNELS_END"`,
|
|
271
|
+
// Port attribution that works for ANY tunnel name: the list table has no
|
|
272
|
+
// port column, so same-port targeting would otherwise key on the
|
|
273
|
+
// auto-name shape `tunnel-<port>-` and miss custom-named tunnels (the
|
|
274
|
+
// remediation's own `devbridge create <name>` flow). Query each tunnel's
|
|
275
|
+
// real port list — the authoritative attribution, with the name-shape and
|
|
276
|
+
// keepalive-URL reads kept as fallbacks when the query is missing. The
|
|
277
|
+
// gsub pair strips BOTH noise postures: the OSC 133 markers (#946) and a
|
|
278
|
+
// CR tail — a single-field port row under CRLF leaves $1 as "8787\r",
|
|
279
|
+
// which fails the digit match and silently empties every TUNNEL_PORTS_
|
|
280
|
+
// line (the attribution collapse the wave's own noise doctrine names).
|
|
281
|
+
`echo "DB_CLEANUP_PORTS_BEGIN"`,
|
|
282
|
+
`for T in $(devbridge list 2>&1 | awk '${DEVBRIDGE_OSC_FILTER}'); do`,
|
|
283
|
+
` echo "TUNNEL_PORTS_$T=$(devbridge port list "$T" 2>/dev/null | awk '{gsub(/\\033\\]133;C\\007/, ""); gsub(/\\r/, ""); if ($1 ~ /^[0-9]+$/) printf "%s,", $1}')";`,
|
|
284
|
+
`done`,
|
|
285
|
+
`echo "DB_CLEANUP_PORTS_END"`,
|
|
286
|
+
`echo "DB_CLEANUP_HOSTS_BEGIN"`,
|
|
287
|
+
`pgrep -af "devbridge host" 2>&1 || true`,
|
|
288
|
+
`echo "DB_CLEANUP_HOSTS_END"`,
|
|
289
|
+
buildKeepaliveTunnelsReadScript(),
|
|
290
|
+
].join('\n');
|
|
291
|
+
}
|
|
292
|
+
export function buildDevbridgeCleanupLockScript() {
|
|
293
|
+
return [
|
|
294
|
+
`LOCK=${DEVBRIDGE_LOCK_PATH}`,
|
|
295
|
+
`if mkdir "$LOCK" 2>/dev/null; then echo LOCK_OK; else`,
|
|
296
|
+
` if find "$LOCK" -maxdepth 0 -mmin +${DEVBRIDGE_LOCK_STALE_MINUTES} 2>/dev/null | grep -q .; then rmdir "$LOCK" 2>/dev/null || true; fi`,
|
|
297
|
+
` if mkdir "$LOCK" 2>/dev/null; then echo LOCK_OK; else echo LOCK_BUSY; fi`,
|
|
298
|
+
`fi`,
|
|
299
|
+
].join('\n');
|
|
300
|
+
}
|
|
301
|
+
function cleanupSection(text, name) {
|
|
302
|
+
const m = String(text || '').match(new RegExp(`DB_CLEANUP_${name}_BEGIN\\r?\\n([\\s\\S]*?)DB_CLEANUP_${name}_END`));
|
|
303
|
+
return m ? (m[1] ?? '') : '';
|
|
304
|
+
}
|
|
305
|
+
// The sandbox terminal occasionally needs >10s to open, so every cleanup exec
|
|
306
|
+
// gets a generous budget and one retry on a transient timeout (each op is
|
|
307
|
+
// idempotent — a retried lock/apply/release converges to the same state).
|
|
308
|
+
async function execCleanupWithRetry(workspaceId, script, username, timeoutMs = DEVBRIDGE_CLEANUP_TIMEOUT_MS) {
|
|
309
|
+
let lastError;
|
|
310
|
+
for (let i = 1; i <= 2; i += 1) {
|
|
311
|
+
try {
|
|
312
|
+
return await runOneShot(workspaceId, script, username, timeoutMs);
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
lastError = error;
|
|
316
|
+
if (i === 2 || !/timeout|websocket/i.test(String(error?.message || '')))
|
|
317
|
+
throw error;
|
|
318
|
+
await new Promise((r) => setTimeout(r, 1000));
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
throw lastError;
|
|
322
|
+
}
|
|
323
|
+
// Prune the watchdog roster after a cleanup: deleted IDs AND entries that no
|
|
324
|
+
// longer exist in the management plane (ghost tunnels from earlier delete-all
|
|
325
|
+
// calls would otherwise be re-hosted and renewed forever). "Absent" entries
|
|
326
|
+
// are only pruned when at least one live tunnel is confirmed (or an explicit
|
|
327
|
+
// all-mode reset) — a transient empty list must not wipe the watchdog and
|
|
328
|
+
// silently stop renewals. An empty roster stops the watchdog outright.
|
|
329
|
+
async function syncKeepaliveAfterCleanup(workspaceId, { deletedIds, liveTunnelIds, pruneMissing, username, }) {
|
|
330
|
+
let current;
|
|
331
|
+
try {
|
|
332
|
+
const read = await execCleanupWithRetry(workspaceId, buildKeepaliveTunnelsReadScript(), username, 30000);
|
|
333
|
+
current = parseKeepaliveTunnelsOutput(read.stdout);
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
if (!current.length)
|
|
339
|
+
return;
|
|
340
|
+
const deleted = new Set(deletedIds || []);
|
|
341
|
+
const remaining = current.filter((t) => !deleted.has(t.tunnelId) && (!pruneMissing || liveTunnelIds.has(t.tunnelId)));
|
|
342
|
+
if (remaining.length === current.length)
|
|
343
|
+
return;
|
|
344
|
+
if (remaining.length === 0) {
|
|
345
|
+
try {
|
|
346
|
+
await execCleanupWithRetry(workspaceId, `pkill -f "tunnel-keepalive.sh" 2>/dev/null || true; rm -f /tmp/tunnel-keepalive.sh`, username, 30000);
|
|
347
|
+
}
|
|
348
|
+
catch {
|
|
349
|
+
// best-effort: a dead watchdog's leftovers do not need renewal anyway
|
|
350
|
+
}
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
try {
|
|
354
|
+
await installKeepaliveWatchdog(workspaceId, { tunnels: remaining }, username, 30000);
|
|
355
|
+
}
|
|
356
|
+
catch {
|
|
357
|
+
// best-effort: the pre-existing coverage stands; the deleted tunnels may
|
|
358
|
+
// be re-hosted by the watchdog once more
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
// The cleanup orchestration: lock → refresh token + read state → plan →
|
|
362
|
+
// apply → sync the watchdog roster → release. A busy/failed lock or a failed
|
|
363
|
+
// list NEVER degrades into deleting anything on a guess.
|
|
364
|
+
export async function cleanupDevbridgeTunnels(workspaceId, { mode = 'stale', samePort = null, maxExtra = 1, username = 'root' } = {}) {
|
|
365
|
+
if (!workspaceId)
|
|
366
|
+
throw new Error('devbridge cleanup: workspace_id is required.');
|
|
367
|
+
if (mode === 'none')
|
|
368
|
+
return { ok: true, skipped: true, deleteIds: [], killPids: [] };
|
|
369
|
+
let lockResult;
|
|
370
|
+
try {
|
|
371
|
+
lockResult = await runOneShot(workspaceId, buildDevbridgeCleanupLockScript(), username, 30000);
|
|
372
|
+
}
|
|
373
|
+
catch {
|
|
374
|
+
return { ok: false, locked: true, deleteIds: [], killPids: [] };
|
|
375
|
+
}
|
|
376
|
+
if (!stripTerminalEscapes(lockResult.stdout).includes('LOCK_OK')) {
|
|
377
|
+
return { ok: false, locked: true, deleteIds: [], killPids: [] };
|
|
378
|
+
}
|
|
379
|
+
try {
|
|
380
|
+
const stateResult = await execCleanupWithRetry(workspaceId, buildDevbridgeCleanupStateScript(), username, 60000);
|
|
381
|
+
const text = stripTerminalEscapes(stateResult.stdout);
|
|
382
|
+
const tunnelSection = cleanupSection(text, 'TUNNELS');
|
|
383
|
+
const listOk = /Tunnel ID|No tunnels found/i.test(tunnelSection);
|
|
384
|
+
if (!listOk) {
|
|
385
|
+
// list/auth/network failed — do not delete or kill anything on a guess.
|
|
386
|
+
return { ok: false, listFailed: true, deleteIds: [], killPids: [] };
|
|
387
|
+
}
|
|
388
|
+
const queriedPorts = parseDevbridgePortQueries(cleanupSection(text, 'PORTS'));
|
|
389
|
+
const tunnels = parseDevbridgeTunnelList(tunnelSection).map((t) => {
|
|
390
|
+
const ports = queriedPorts.get(t.id);
|
|
391
|
+
// The queried port list is authoritative (any tunnel name — the
|
|
392
|
+
// name-shape read misses custom-named tunnels, B-R2-3); without a query
|
|
393
|
+
// result the name-shape/keepalive reads stand.
|
|
394
|
+
return ports && ports.length > 0 ? { ...t, ports, port: ports[0] } : t;
|
|
395
|
+
});
|
|
396
|
+
const hosts = parseDevbridgeHostProcesses(cleanupSection(text, 'HOSTS'));
|
|
397
|
+
// Output-format drift guard: header matched but rows didn't parse, while
|
|
398
|
+
// host processes exist. Never mass-kill hosts on a parse we don't trust.
|
|
399
|
+
if (tunnels.length === 0 && hosts.length > 0 && !/No tunnels found/i.test(tunnelSection)) {
|
|
400
|
+
return { ok: false, listFailed: true, deleteIds: [], killPids: [] };
|
|
401
|
+
}
|
|
402
|
+
const keepalive = parseKeepaliveTunnelsOutput(text);
|
|
403
|
+
const liveTunnelIds = new Set(tunnels.map((t) => t.id));
|
|
404
|
+
const pruneMissing = mode === 'all' || liveTunnelIds.size > 0;
|
|
405
|
+
const plan = planDevbridgeCleanup({ tunnels, hosts, keepalive, mode, samePort, maxExtra });
|
|
406
|
+
if (plan.deleteIds.length === 0 && plan.killPids.length === 0) {
|
|
407
|
+
await syncKeepaliveAfterCleanup(workspaceId, { deletedIds: [], liveTunnelIds, pruneMissing, username });
|
|
408
|
+
return { ok: true, deleteIds: [], killPids: [], tunnelCount: tunnels.length };
|
|
409
|
+
}
|
|
410
|
+
await execCleanupWithRetry(workspaceId, buildDevbridgeCleanupApplyScript(plan), username, DEVBRIDGE_CLEANUP_TIMEOUT_MS);
|
|
411
|
+
await syncKeepaliveAfterCleanup(workspaceId, { deletedIds: plan.deleteIds, liveTunnelIds, pruneMissing, username });
|
|
412
|
+
return { ok: true, ...plan, tunnelCount: tunnels.length };
|
|
413
|
+
}
|
|
414
|
+
finally {
|
|
415
|
+
try {
|
|
416
|
+
await execCleanupWithRetry(workspaceId, `rmdir ${DEVBRIDGE_LOCK_PATH} 2>/dev/null || true`, username, 30000);
|
|
417
|
+
}
|
|
418
|
+
catch {
|
|
419
|
+
// best-effort: the 10-minute stale threshold reclaims an abandoned lock
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
}
|