dsh-zterm 0.1.13 → 0.1.15

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/lib/index.js CHANGED
@@ -2,7 +2,62 @@
2
2
  import { homedir as homedir3 } from "node:os";
3
3
  import { join as join3 } from "node:path";
4
4
  import { randomUUID as randomUUID5 } from "node:crypto";
5
- import ssh24 from "ssh2";
5
+
6
+ // src/core/sshPrivateKey.ts
7
+ import { createPrivateKey, randomBytes } from "node:crypto";
8
+ import ssh2 from "ssh2";
9
+ function uint32(value) {
10
+ const bytes = Buffer.alloc(4);
11
+ bytes.writeUInt32BE(value);
12
+ return bytes;
13
+ }
14
+ function sshString(value) {
15
+ const bytes = typeof value === "string" ? Buffer.from(value) : value;
16
+ return Buffer.concat([uint32(bytes.length), bytes]);
17
+ }
18
+ function ed25519OpenSsh(key) {
19
+ const jwk = key.export({ format: "jwk" });
20
+ if (!jwk.x || !jwk.d) throw new Error("Invalid Ed25519 key");
21
+ const publicKey = Buffer.from(jwk.x, "base64url"), seed = Buffer.from(jwk.d, "base64url");
22
+ if (publicKey.length !== 32 || seed.length !== 32) throw new Error("Invalid Ed25519 key");
23
+ const algorithm = sshString("ssh-ed25519"), check = randomBytes(4);
24
+ const publicBlock = Buffer.concat([algorithm, sshString(publicKey)]);
25
+ const privateBlock = Buffer.concat([check, check, algorithm, sshString(publicKey), sshString(Buffer.concat([seed, publicKey])), sshString("")]);
26
+ const padding = Buffer.from(Array.from({ length: 8 - privateBlock.length % 8 }, (_, i) => i + 1));
27
+ const encoded = Buffer.concat([Buffer.from("openssh-key-v1\0"), sshString("none"), sshString("none"), sshString(""), uint32(1), sshString(publicBlock), sshString(Buffer.concat([privateBlock, padding]))]);
28
+ return `-----BEGIN OPENSSH PRIVATE KEY-----
29
+ ${encoded.toString("base64").match(/.{1,70}/g).join("\n")}
30
+ -----END OPENSSH PRIVATE KEY-----
31
+ `;
32
+ }
33
+ function normalizeSshPrivateKey(value, passphrase) {
34
+ try {
35
+ let compatible = value;
36
+ const text2 = value.trim();
37
+ if (/^-----BEGIN (?:ENCRYPTED )?PRIVATE KEY-----/.test(text2)) {
38
+ if (!/^-----BEGIN ((?:ENCRYPTED )?PRIVATE KEY)-----\r?\n[A-Za-z0-9+/=\r\n]+\r?\n-----END \1-----$/.test(text2)) throw new Error("Invalid PKCS#8 envelope");
39
+ const key = createPrivateKey({ key: text2, format: "pem", passphrase });
40
+ switch (key.asymmetricKeyType) {
41
+ case "rsa":
42
+ compatible = key.export({ type: "pkcs1", format: "pem" }).toString();
43
+ break;
44
+ case "ec":
45
+ compatible = key.export({ type: "sec1", format: "pem" }).toString();
46
+ break;
47
+ case "ed25519":
48
+ compatible = ed25519OpenSsh(key);
49
+ break;
50
+ default:
51
+ throw new Error("Unsupported SSH key algorithm");
52
+ }
53
+ }
54
+ const parsed = ssh2.utils.parseKey(compatible, passphrase);
55
+ if (parsed instanceof Error || !(Array.isArray(parsed) ? parsed : [parsed]).some((key) => key.getPrivatePEM())) throw new Error("Not a private SSH key");
56
+ return compatible;
57
+ } catch {
58
+ throw new Error("\u79C1\u94A5\u65E0\u6CD5\u89E3\u6790\uFF0C\u8BF7\u68C0\u67E5\u5B8C\u6574\u5185\u5BB9\u3001\u79C1\u94A5\u7B97\u6CD5\u548C\u53E3\u4EE4");
59
+ }
60
+ }
6
61
 
7
62
  // src/host/config.ts
8
63
  import Schema from "@deepseek-ai/schemastery";
@@ -12,7 +67,7 @@ import { isAbsolute } from "node:path";
12
67
  import { createHash } from "node:crypto";
13
68
  import { isIP } from "node:net";
14
69
  import { domainToASCII, URL as URL2 } from "node:url";
15
- import ssh2 from "ssh2";
70
+ import ssh22 from "ssh2";
16
71
  var CONTROL_CHARACTER = /[\u0000-\u001F\u007F]/;
17
72
  var SHA256_FINGERPRINT = /^SHA256:[A-Za-z0-9+/]{43}$/;
18
73
  function canonicalizeIp(host) {
@@ -77,7 +132,7 @@ function createSshHostTrustCandidate(input) {
77
132
  };
78
133
  }
79
134
  function inspectSshHostKey(rawHostKey, connection) {
80
- const parsedKey = ssh2.utils.parseKey(rawHostKey);
135
+ const parsedKey = ssh22.utils.parseKey(rawHostKey);
81
136
  if (parsedKey instanceof Error || Array.isArray(parsedKey) || !parsedKey.type) return null;
82
137
  const fingerprint = createSshHostFingerprint(rawHostKey);
83
138
  if (!fingerprint) return null;
@@ -450,12 +505,12 @@ var TerminalOutputBuffer = class {
450
505
  };
451
506
 
452
507
  // src/core/terminalSessionManager.ts
453
- import ssh22 from "ssh2";
508
+ import ssh23 from "ssh2";
454
509
  import { EventEmitter } from "events";
455
510
  import { randomUUID as randomUUID2 } from "node:crypto";
456
511
  var HOST_TRUST_TIMEOUT_MS = 6e4;
457
512
  var TerminalSession = class extends EventEmitter {
458
- constructor(tabId, generation, clientFactory = () => new ssh22.Client(), trust = memoryHostTrustStore()) {
513
+ constructor(tabId, generation, clientFactory = () => new ssh23.Client(), trust = memoryHostTrustStore()) {
459
514
  super();
460
515
  this.clientFactory = clientFactory;
461
516
  this.trust = trust;
@@ -586,6 +641,7 @@ var TerminalSession = class extends EventEmitter {
586
641
  return { success: true };
587
642
  }
588
643
  async connect(opts) {
644
+ const privateKey = opts.privateKey ? normalizeSshPrivateKey(opts.privateKey, opts.passphrase) : void 0;
589
645
  return new Promise((resolve, reject) => {
590
646
  this.currentHost = { host: opts.host, port: opts.port || 22, username: opts.username };
591
647
  this.verifiedHostKey = void 0;
@@ -603,8 +659,8 @@ var TerminalSession = class extends EventEmitter {
603
659
  };
604
660
  config.hostVerifier = (key, verify) => this.verifyHostKey(opts, key, verify);
605
661
  if (opts.agent) config.agent = opts.agent;
606
- if (opts.privateKey) {
607
- config.privateKey = opts.privateKey;
662
+ if (privateKey) {
663
+ config.privateKey = privateKey;
608
664
  if (opts.passphrase) config.passphrase = opts.passphrase;
609
665
  } else if (opts.password) {
610
666
  config.password = opts.password;
@@ -892,7 +948,7 @@ function getPlatformShell() {
892
948
  }
893
949
 
894
950
  // src/core/terminalBridge.ts
895
- import { randomBytes } from "node:crypto";
951
+ import { randomBytes as randomBytes2 } from "node:crypto";
896
952
  import { stripVTControlCharacters } from "node:util";
897
953
  var CAPTURE_LIMIT = 64e3;
898
954
  var PROBE_TIMEOUT_MS = 3e3;
@@ -1083,7 +1139,7 @@ var TerminalBridge = class {
1083
1139
  return result("unsupported", "\u672C\u5730 Windows cmd/PowerShell \u5C1A\u672A\u5B9E\u73B0\u53EF\u4FE1\u5B8C\u6210\u534F\u8BAE", false);
1084
1140
  }
1085
1141
  const targetId = this.getBoundTargetId();
1086
- const probeNonce = randomBytes(16).toString("hex");
1142
+ const probeNonce = randomBytes2(16).toString("hex");
1087
1143
  const probeMarker = `__ZTERM_AGENT_READY_${probeNonce}__`;
1088
1144
  const probe = `command sh -c 'exit 37'; __zterm_agent_probe=$?; printf '\\n%s%s:%d\\n' '__ZTERM_AGENT_READY_' '${probeNonce}__' "$__zterm_agent_probe"
1089
1145
  `;
@@ -1097,7 +1153,7 @@ var TerminalBridge = class {
1097
1153
  if (authorizeBeforeSend && !authorizeBeforeSend()) {
1098
1154
  return { ...result("aborted", "\u6267\u884C\u6388\u6743\u5DF2\u64A4\u9500\uFF0C\u4E1A\u52A1\u547D\u4EE4\u672A\u4E0B\u53D1", false), authorizationDenied: true };
1099
1155
  }
1100
- const nonce = randomBytes(16).toString("hex");
1156
+ const nonce = randomBytes2(16).toString("hex");
1101
1157
  const marker = `__ZTERM_AGENT_END_${nonce}__`;
1102
1158
  const startMarker = `__ZTERM_AGENT_BEGIN_${nonce}__`;
1103
1159
  const script = `${command}
@@ -1658,7 +1714,7 @@ var definitions = [
1658
1714
  {
1659
1715
  name: "read_bound_file",
1660
1716
  label: "\u8BFB\u53D6\u6587\u4EF6",
1661
- description: "\u8BFB\u53D6\u7ED1\u5B9A\u76EE\u6807\u7684\u6587\u672C\u6587\u4EF6\u6216\u5DF2\u652F\u6301\u7684 /proc \u4FE1\u606F\u3002\u5F00\u5934/\u672B\u5C3E\u7A97\u53E3\u6700\u591A 64 KiB\uFF08\u53E6\u8BFB\u4E00\u4E2A\u8FB9\u754C\u5B57\u8282\uFF09\uFF0C\u6587\u672C\u8F93\u51FA\u6700\u591A 7000 \u5B57\u8282\u3002\u8FD4\u56DE\u5B9E\u9645\u884C\u533A\u95F4\u3001\u622A\u65AD\u539F\u56E0\u548C\u53EF\u7528\u7684 nextStartLine\u3002\u53EA\u6709\u5B8C\u6574\u89C2\u5BDF\u6587\u4EF6\u65F6 totalLines \u624D\u6709\u503C\uFF1B\u672B\u5C3E\u7A97\u53E3\u7684\u7EDD\u5BF9\u884C\u53F7\u53EF\u80FD\u672A\u77E5\u3002\u8D85\u51FA\u6587\u4EF6\u4E0E\u8D85\u51FA\u7A97\u53E3\u5206\u522B\u62A5\u9519\u3002\u62D2\u7EDD\u8BBE\u5907\u3001\u7BA1\u9053\u548C\u51ED\u636E\u6587\u4EF6\u3002",
1717
+ description: "\u8BFB\u53D6\u7ED1\u5B9A\u76EE\u6807\u7684\u6587\u672C\u6587\u4EF6\u6216\u5DF2\u652F\u6301\u7684 /proc \u4FE1\u606F\u3002\u5F00\u5934/\u672B\u5C3E\u8FD4\u56DE\u7A97\u53E3\u6700\u591A 64 KiB\uFF08\u53E6\u8BFB\u4E00\u4E2A\u8FB9\u754C\u5B57\u8282\uFF09\uFF0C\u672B\u5C3E\u8BFB\u53D6\u53E6\u68C0\u67E5\u524D 64 KiB \u7684\u51ED\u636E\u7C7B\u578B\uFF0C\u6587\u672C\u8F93\u51FA\u6700\u591A 7000 \u5B57\u8282\u3002\u8FD4\u56DE\u5B9E\u9645\u884C\u533A\u95F4\u3001\u622A\u65AD\u539F\u56E0\u548C\u53EF\u7528\u7684 nextStartLine\u3002\u53EA\u6709\u5B8C\u6574\u89C2\u5BDF\u6587\u4EF6\u65F6 totalLines \u624D\u6709\u503C\uFF1B\u672B\u5C3E\u7A97\u53E3\u7684\u7EDD\u5BF9\u884C\u53F7\u53EF\u80FD\u672A\u77E5\u3002\u8D85\u51FA\u6587\u4EF6\u4E0E\u8D85\u51FA\u7A97\u53E3\u5206\u522B\u62A5\u9519\u3002\u62D2\u7EDD\u8BBE\u5907\u3001\u7BA1\u9053\u3001\u51ED\u636E\u8DEF\u5F84\u53CA\u6837\u672C\u4E2D\u8BC6\u522B\u51FA\u7684\u5E38\u89C1\u51ED\u636E\u5185\u5BB9\u3002",
1662
1718
  parameters: Type.Object({
1663
1719
  path: pathParam,
1664
1720
  start_line: Type.Optional(Type.Integer({ minimum: 1, maximum: 1e4, default: 1 })),
@@ -1669,7 +1725,7 @@ var definitions = [
1669
1725
  {
1670
1726
  name: "search_bound_text",
1671
1727
  label: "\u641C\u7D22\u6587\u672C",
1672
- description: "\u5728\u5DF2\u7ED1\u5B9A\u76EE\u6807\u7684\u4E00\u4E2A\u6587\u672C\u6587\u4EF6\u6216\u76EE\u5F55\u76F4\u63A5\u5B50\u6587\u4EF6\u4E2D\u505A\u5B57\u9762\u5173\u952E\u8BCD\u641C\u7D22\uFF0C\u4E0D\u6267\u884C\u6B63\u5219\u6216\u811A\u672C\uFF0C\u4E0D\u9012\u5F52\u3002\u76EE\u5F55\u6700\u591A\u68C0\u67E5 100 \u4E2A\u6587\u4EF6\uFF0C\u6BCF\u4E2A\u6587\u4EF6\u6700\u591A\u68C0\u67E5\u524D 64 KiB\uFF1B\u8DF3\u8FC7\u7B26\u53F7\u94FE\u63A5\u548C\u5E38\u89C1\u51ED\u636E\u6587\u4EF6\u3002",
1728
+ description: "\u5728\u5DF2\u7ED1\u5B9A\u76EE\u6807\u7684\u4E00\u4E2A\u6587\u672C\u6587\u4EF6\u6216\u76EE\u5F55\u76F4\u63A5\u5B50\u6587\u4EF6\u4E2D\u505A\u5B57\u9762\u5173\u952E\u8BCD\u641C\u7D22\uFF0C\u4E0D\u6267\u884C\u6B63\u5219\u6216\u811A\u672C\uFF0C\u4E0D\u9012\u5F52\u3002\u76EE\u5F55\u6700\u591A\u68C0\u67E5 100 \u4E2A\u6587\u4EF6\uFF0C\u6BCF\u4E2A\u6587\u4EF6\u6700\u591A\u68C0\u67E5\u524D 64 KiB\uFF1B\u5355\u6587\u4EF6\u8BC6\u522B\u5230\u5E38\u89C1\u51ED\u636E\u5185\u5BB9\u65F6\u62D2\u7EDD\uFF0C\u76EE\u5F55\u641C\u7D22\u8DF3\u8FC7\u7B26\u53F7\u94FE\u63A5\u3001\u51ED\u636E\u8DEF\u5F84\u53CA\u8BC6\u522B\u5230\u7684\u51ED\u636E\u5185\u5BB9\u5E76\u62A5\u544A\u6570\u91CF\u3002",
1673
1729
  parameters: Type.Object({
1674
1730
  path: pathParam,
1675
1731
  query: Type.String({ minLength: 1, maxLength: 256 }),
@@ -1726,18 +1782,89 @@ function boolean2(value, fallback) {
1726
1782
  if (typeof value !== "boolean") throw new Error("\u5E03\u5C14\u53C2\u6570\u683C\u5F0F\u65E0\u6548");
1727
1783
  return value;
1728
1784
  }
1785
+ var credentialDirectories = [
1786
+ ".ssh",
1787
+ ".aws",
1788
+ ".kube",
1789
+ ".docker",
1790
+ ".gnupg",
1791
+ ".azure",
1792
+ ".gcloud",
1793
+ ".config/gcloud",
1794
+ ".aliyun"
1795
+ ];
1796
+ var credentialBasenames = [".env", "credentials", "secrets", ".netrc", ".pgpass", ".git-credentials", ".htpasswd", "kubeconfig"];
1797
+ var credentialNameSuffixes = [".kubeconfig"];
1798
+ var credentialExtensions = ["pem", "key", "p12", "pfx", "ppk", "jks", "kdbx"];
1799
+ var sshKeyBasenames = ["id_rsa", "id_dsa", "id_ecdsa", "id_ed25519"];
1800
+ var CREDENTIAL_CONTENT_EXIT = 77;
1801
+ var CREDENTIAL_CONTENT_MESSAGE = "\u68C0\u6D4B\u5230\u51ED\u636E\u6587\u4EF6\u5185\u5BB9\uFF0C\u8BFB\u53D6\u88AB\u62D2\u7EDD\u3002";
1802
+ var credentialContentAwk = String.raw`
1803
+ function jsonObjectField(value, field, start, pos, depth, quoted, escaped, ch) {
1804
+ if (!match(value, "\"" field "\"[[:space:]]*:[[:space:]]*[{]")) return "";
1805
+ start = RSTART + RLENGTH - 1;
1806
+ for (pos = start; pos <= length(value); pos++) {
1807
+ ch = substr(value, pos, 1);
1808
+ if (quoted) {
1809
+ if (escaped) escaped = 0;
1810
+ else if (ch == "\\") escaped = 1;
1811
+ else if (ch == "\"") quoted = 0;
1812
+ } else if (ch == "\"") quoted = 1;
1813
+ else if (ch == "{") depth++;
1814
+ else if (ch == "}") { depth--; if (depth == 0) return substr(value, start, pos - start + 1); }
1815
+ }
1816
+ return substr(value, start);
1817
+ }
1818
+ function credentialContent(value, lower, root, auths) {
1819
+ lower = tolower(value);
1820
+ sub(/^\357\273\277/, "", lower);
1821
+ if (lower ~ /(^|\n)[[:blank:]]*-----[[:blank:]]*(begin|end)[[:blank:]]+((rsa|ec|dsa|openssh|encrypted)[[:blank:]]+)?private key[[:blank:]]*-----[[:blank:]]*(\r?\n|$)/) return 1;
1822
+ if (lower ~ /(^|\n)[[:blank:]]*-----[[:blank:]]*(begin|end)[[:blank:]]+pgp private key block[[:blank:]]*-----[[:blank:]]*(\r?\n|$)/) return 1;
1823
+ if (lower ~ /(^|\n)[[:blank:]]*----[[:blank:]]*(begin|end)[[:blank:]]+ssh2[[:blank:]]+(encrypted[[:blank:]]+)?private key[[:blank:]]*----[[:blank:]]*(\r?\n|$)/) return 1;
1824
+ if (lower ~ /(^|\n)[[:blank:]]*putty-user-key-file-[123]:/) return 1;
1825
+ if (lower ~ /(^|\n)[[:blank:]]*(export[[:blank:]]+)?aws_(access_key_id|secret_access_key|session_token)[[:blank:]]*=[[:blank:]]*("[^"]|'[^']|[^[:space:]"'#;])/) return 1;
1826
+ root = lower;
1827
+ sub(/^[[:space:]]+/, "", root);
1828
+ while (root ~ /^(#[^\n]*|---[[:blank:]]*(#[^\n]*)?)\r?\n/) { sub(/^[^\n]*\n/, "", root); sub(/^[[:space:]]+/, "", root); }
1829
+ if (root ~ /^\{/) {
1830
+ if (root ~ /"aws_(access_key_id|secret_access_key|session_token)"[[:space:]]*:[[:space:]]*"[^"]/) return 1;
1831
+ if (root ~ /"(private_key|privatekey)"[[:space:]]*:[[:space:]]*"-----begin[[:blank:]]+((rsa|ec|dsa|openssh|encrypted)[[:blank:]]+)?private key-----(\\r)?\\n[a-z0-9+]/) return 1;
1832
+ auths = jsonObjectField(root, "auths");
1833
+ if (auths ~ /"(auth|identitytoken)"[[:space:]]*:[[:space:]]*"[^"]/) return 1;
1834
+ if (root ~ /"kind"[[:space:]]*:[[:space:]]*"config"/ && root ~ /"(users|clusters)"[[:space:]]*:[[:space:]]*\[/) return 1;
1835
+ if (root ~ /"type"[[:space:]]*:[[:space:]]*"(service_account|authorized_user)"/ && root ~ /"(private_key|refresh_token|client_secret)"[[:space:]]*:[[:space:]]*"[^"]/) return 1;
1836
+ }
1837
+ if (root ~ /^["']?(apiversion|kind|users|clusters|contexts|current-context|preferences|extensions)["']?[[:blank:]]*:/ && lower ~ /(^|\n)["']?kind["']?[[:blank:]]*:[[:blank:]]*["']?config["']?[[:blank:]]*(#[^\n]*)?(\r?\n|$)/ && lower ~ /(^|\n)["']?(users|clusters)["']?[[:blank:]]*:[[:blank:]]*(\[|(#[^\n]*)?\r?\n([[:blank:]]*(#[^\n]*)?\r?\n)*[[:blank:]]*-[[:space:]])/) return 1;
1838
+ return 0;
1839
+ }`;
1840
+ var denyCredentialContentAwk = `if (credentialContent(sample)) { printf "%s", "${CREDENTIAL_CONTENT_MESSAGE}"; exit ${CREDENTIAL_CONTENT_EXIT}; }`;
1841
+ var escaped = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1842
+ var globCharClass = (character) => {
1843
+ const lower = character.toLowerCase(), upper = character.toUpperCase();
1844
+ return lower === upper ? character : `[${lower}${upper}]`;
1845
+ };
1729
1846
  var deniedPathCases = [
1730
1847
  "/dev|/dev/*|/sys|/sys/*",
1731
1848
  "/etc/shadow|/etc/gshadow|/etc/shadow-*|/etc/gshadow-*",
1732
- "*/.ssh|*/.ssh/*|*/.aws|*/.aws/*|*/.kube|*/.kube/*",
1733
- "*/.env|*/.env.*|*/credentials|*/credentials.*|*/secrets|*/secrets.*|*.[pP][eE][mM]|*.[kK][eE][yY]"
1849
+ ...credentialDirectories.flatMap((directory) => [`*/${directory}`, `*/${directory}/*`]),
1850
+ ...credentialBasenames.flatMap((name2) => [`*/${name2}`, `*/${name2}.*`]),
1851
+ ...credentialNameSuffixes.map((suffix) => `*${suffix}`),
1852
+ ...credentialExtensions.map((extension) => "*." + [...extension].map(globCharClass).join("")),
1853
+ ...sshKeyBasenames.map((name2) => `*/${name2}`)
1734
1854
  ].join("|");
1735
1855
  var allowedProcCases = "/proc/meminfo|/proc/loadavg|/proc/uptime|/proc/cpuinfo|/proc/version|/proc/net/tcp|/proc/net/tcp6|/proc/net/udp|/proc/net/udp6";
1856
+ var credentialPatterns = [
1857
+ new RegExp(`(?:^|/)(${credentialDirectories.map(escaped).join("|")})(?:/|$)`),
1858
+ new RegExp(`/(?:${credentialBasenames.map(escaped).join("|")})(?:\\..*)?$`),
1859
+ new RegExp(`(?:${credentialNameSuffixes.map(escaped).join("|")})$`),
1860
+ new RegExp(`\\.(?:${credentialExtensions.join("|")})$`, "i"),
1861
+ new RegExp(`/(?:${sshKeyBasenames.join("|")})$`)
1862
+ ];
1736
1863
  function filePath(value) {
1737
1864
  const path = text(value, "path", 2048);
1738
1865
  if (!path.startsWith("/")) throw new ReadParameterError("relative_path", "\u8BF7\u4F7F\u7528\u76EE\u6807\u4E0A\u7684\u7EDD\u5BF9\u8DEF\u5F84");
1739
1866
  const normalized = posix2.normalize(path);
1740
- if (/^\/(?:dev|sys)(?:\/|$)/.test(normalized) || /^\/etc\/(?:shadow|gshadow)(?:-|$)/.test(normalized) || /\/\.(?:ssh|aws|kube)(?:\/|$)/.test(normalized) || /\/(?:\.env(?:\..*)?|credentials(?:\..*)?|secrets(?:\..*)?)$/.test(normalized) || /\.(?:pem|key)$/i.test(normalized)) {
1867
+ if (/^\/(?:dev|sys)(?:\/|$)/.test(normalized) || /^\/etc\/(?:shadow|gshadow)(?:-|$)/.test(normalized) || credentialPatterns.some((pattern) => pattern.test(normalized))) {
1741
1868
  throw new ReadParameterError("path_denied", "\u8BE5\u8DEF\u5F84\u5C5E\u4E8E\u8BBE\u5907\u6216\u51ED\u636E\u8303\u56F4\uFF0C\u5185\u7F6E\u8BFB\u5DE5\u5177\u4E0D\u5F00\u653E");
1742
1869
  }
1743
1870
  return normalized;
@@ -1778,8 +1905,9 @@ var sourceExitAwk = String.raw`
1778
1905
  function fileSample(reader, pathVariable, bytes) {
1779
1906
  return "{ command " + reader + " -c " + bytes + ' "$' + pathVariable + '" 2>/dev/null; zterm_read_ec=$?; printf "\\n__ZTERM_SOURCE_EXIT_%d__\\n" "$zterm_read_ec"; } | LC_ALL=C command od -An -v -tu1 | ';
1780
1907
  }
1781
- function checkedTextSearch(matches) {
1782
- const script = String.raw`
1908
+ function inspectedTextSample(action) {
1909
+ return String.raw`
1910
+ ${credentialContentAwk}
1783
1911
  BEGIN { for (i = 1; i < 256; i++) characters[i] = sprintf("%c", i); }
1784
1912
  {
1785
1913
  for (i = 1; i <= NF; i++) {
@@ -1793,19 +1921,33 @@ function checkedTextSearch(matches) {
1793
1921
  sample = sample chunk;
1794
1922
  trailer = substr(sample, length(sample) > 48 ? length(sample) - 47 : 1);
1795
1923
  ${sourceExitAwk}
1796
- if (ec != 0) printf "文本搜索读取失败(源退出码 %d)。\n", ec;
1797
- else if (!binary) {
1798
- lines = split(substr(sample, 1, size), rows, "\n");
1799
- for (i = 1; i <= lines && count < limit; i++) {
1800
- if (index(rows[i], ENVIRON["ZTERM_READ_QUERY"])) { print i ":" rows[i]; count++; }
1801
- }
1802
- }
1803
- exit ec;
1924
+ sample = substr(sample, 1, size);
1925
+ ${action}
1804
1926
  }`.trim().replace(/\s*\n\s*/g, " ");
1927
+ }
1928
+ function credentialPrefixGuard() {
1929
+ const script = inspectedTextSample(String.raw`
1930
+ if (ec != 0) { printf "凭据类型检查读取失败(源退出码 %d)。\n", ec; exit ec; }
1931
+ ${denyCredentialContentAwk}
1932
+ exit 0;`);
1933
+ return fileSample("head", "p", SOURCE_BYTES) + "LC_ALL=C command awk " + quote(script) + '; zterm_check_ec=$?; if [ "$zterm_check_ec" -ne 0 ]; then exit "$zterm_check_ec"; fi; ';
1934
+ }
1935
+ function checkedTextSearch(matches) {
1936
+ const script = inspectedTextSample(String.raw`
1937
+ if (ec != 0) { printf "文本搜索读取失败(源退出码 %d)。\n", ec; exit ec; }
1938
+ ${denyCredentialContentAwk}
1939
+ if (!binary) {
1940
+ lines = split(sample, rows, "\n");
1941
+ for (i = 1; i <= lines && count < limit; i++) {
1942
+ if (index(rows[i], ENVIRON["ZTERM_READ_QUERY"])) { print i ":" rows[i]; count++; }
1943
+ }
1944
+ }
1945
+ exit 0;`);
1805
1946
  return fileSample("head", "f", SOURCE_BYTES) + 'ZTERM_READ_QUERY="$q" LC_ALL=C command awk -v limit=' + matches + " " + quote(script);
1806
1947
  }
1807
1948
  function fileWindowCommand(start, lines, fromEnd) {
1808
1949
  const script = String.raw`
1950
+ ${credentialContentAwk}
1809
1951
  function prefix(s, cap) {
1810
1952
  while (cap > 0 && substr(s, cap + 1, 1) ~ /[\200-\277]/) cap--;
1811
1953
  return substr(s, 1, cap);
@@ -1819,6 +1961,12 @@ function fileWindowCommand(start, lines, fromEnd) {
1819
1961
  END {
1820
1962
  for (i = (size > 48 ? size - 48 : 1); i <= size; i++) trailer = trailer sprintf("%c", bytes[i]);
1821
1963
  ${sourceExitAwk}
1964
+ for (i = 1; i <= size; i++) {
1965
+ chunk = chunk (bytes[i] == 0 ? " " : sprintf("%c", bytes[i]));
1966
+ if (i % 1024 == 0) { sample = sample chunk; chunk = ""; }
1967
+ }
1968
+ sample = sample chunk;
1969
+ if (ec == 0) { ${denyCredentialContentAwk} }
1822
1970
  limited = size > sourceLimit; observed = limited ? sourceLimit : size;
1823
1971
  lo = tail && limited ? size - sourceLimit + 1 : 1;
1824
1972
  hi = tail ? size : observed;
@@ -1867,7 +2015,7 @@ function fileWindowCommand(start, lines, fromEnd) {
1867
2015
  exit ec;
1868
2016
  }`.trim().replace(/\s*\n\s*/g, " ");
1869
2017
  const reader = fromEnd ? "tail" : "head";
1870
- return 'if ! command -v od >/dev/null 2>&1 || ! command -v awk >/dev/null 2>&1; then printf "%s\\n" "\u6587\u4EF6\u67E5\u8BE2\u80FD\u529B\u4E0D\u53EF\u7528\uFF1A\u9700\u8981 od \u548C awk"; exit 127; fi; ' + fileSample(reader, "p", SOURCE_BYTES + 1) + "LC_ALL=C command awk -v sourceLimit=" + SOURCE_BYTES + " -v outputLimit=" + FILE_OUTPUT_BYTES + " -v startLine=" + start + " -v maxLines=" + lines + " -v tail=" + Number(fromEnd) + " " + quote(script);
2018
+ return 'if ! command -v od >/dev/null 2>&1 || ! command -v awk >/dev/null 2>&1; then printf "%s\\n" "\u6587\u4EF6\u67E5\u8BE2\u80FD\u529B\u4E0D\u53EF\u7528\uFF1A\u9700\u8981 od \u548C awk"; exit 127; fi; ' + (fromEnd ? credentialPrefixGuard() : "") + fileSample(reader, "p", SOURCE_BYTES + 1) + "LC_ALL=C command awk -v sourceLimit=" + SOURCE_BYTES + " -v outputLimit=" + FILE_OUTPUT_BYTES + " -v startLine=" + start + " -v maxLines=" + lines + " -v tail=" + Number(fromEnd) + " " + quote(script);
1871
2019
  }
1872
2020
  function prepareBuiltinRead(name2, params) {
1873
2021
  const definition = definitions.find((item) => item.name === name2);
@@ -1894,14 +2042,14 @@ function prepareBuiltinRead(name2, params) {
1894
2042
  if (fromEnd && start !== 1) throw new Error("\u8BFB\u53D6\u672B\u5C3E\u65F6\u4E0D\u80FD\u540C\u65F6\u6307\u5B9A start_line");
1895
2043
  fileWindow = { startLine: start, fromEnd };
1896
2044
  command = pathPrelude(path) + 'if [ ! -f "$p" ] || [ ! -r "$p" ]; then printf "%s\\n" "\u8DEF\u5F84\u4E0D\u662F\u53EF\u8BFB\u666E\u901A\u6587\u4EF6"; exit 2; fi; ' + fileWindowCommand(start, lines, fromEnd);
1897
- scope += fromEnd ? "\uFF0C\u6587\u4EF6\u672B\u5C3E\u7A97\u53E3\uFF0C\u6700\u591A 64 KiB" : "\uFF0C\u6587\u4EF6\u5F00\u5934 64 KiB \u5185\u7684\u884C\u7A97\u53E3";
2045
+ scope += fromEnd ? "\uFF0C\u6587\u4EF6\u672B\u5C3E\u7A97\u53E3\uFF0C\u6700\u591A 64 KiB\uFF1B\u53E6\u68C0\u67E5\u524D 64 KiB \u7684\u51ED\u636E\u7C7B\u578B" : "\uFF0C\u6587\u4EF6\u5F00\u5934 64 KiB \u5185\u7684\u884C\u7A97\u53E3";
1898
2046
  break;
1899
2047
  }
1900
2048
  case "search_bound_text": {
1901
2049
  const path = filePath(params.path);
1902
2050
  const query = text(params.query, "query", 256);
1903
2051
  const matches = integer2(params.max_matches, 30, 1, 100);
1904
- command = pathPrelude(path) + "q=" + quote(query) + '; count=0; unread=0; if [ ! -r "$p" ] || { [ -d "$p" ] && [ ! -x "$p" ]; }; then printf "%s\\n" "\u641C\u7D22\u8DEF\u5F84\u4E0D\u53EF\u8BFB\u6216\u76EE\u5F55\u4E0D\u53EF\u8BBF\u95EE"; exit 2; fi; if ! command -v od >/dev/null 2>&1 || ! command -v awk >/dev/null 2>&1; then printf "%s\\n" "\u6587\u672C\u641C\u7D22\u80FD\u529B\u4E0D\u53EF\u7528\uFF1A\u9700\u8981 od \u548C awk"; exit 127; fi; if [ -f "$p" ]; then set -- "$p"; elif [ -d "$p" ]; then set -- "$p"/* "$p"/.[!.]* "$p"/..?*; else printf "%s\\n" "\u8DEF\u5F84\u4E0D\u662F\u666E\u901A\u6587\u4EF6\u6216\u76EE\u5F55"; exit 2; fi; for f do [ -f "$f" ] && [ ! -L "$f" ] || continue; case "$f" in ' + deniedPathCases + ') continue;; esac; if [ ! -r "$f" ]; then unread=$((unread+1)); continue; fi; [ "$count" -lt 100 ] || break; count=$((count+1)); hits=$(' + checkedTextSearch(matches) + '); ec=$?; if [ "$ec" -ne 0 ]; then printf "%s\\n" "$hits"; exit "$ec"; fi; if [ -n "$hits" ]; then printf "\\nFILE %s\\n%s\\n" "$f" "$hits"; fi; done; printf "\\n\u641C\u7D22\u8303\u56F4\uFF1A\u5DF2\u68C0\u67E5 %s \u4E2A\u6587\u4EF6\uFF0C\u8DF3\u8FC7 %s \u4E2A\u4E0D\u53EF\u8BFB\u6587\u4EF6\u3002\\n" "$count" "$unread"; exit 0';
2052
+ command = pathPrelude(path) + "q=" + quote(query) + '; count=0; unread=0; credentials=0; directory=0; if [ ! -r "$p" ] || { [ -d "$p" ] && [ ! -x "$p" ]; }; then printf "%s\\n" "\u641C\u7D22\u8DEF\u5F84\u4E0D\u53EF\u8BFB\u6216\u76EE\u5F55\u4E0D\u53EF\u8BBF\u95EE"; exit 2; fi; if ! command -v od >/dev/null 2>&1 || ! command -v awk >/dev/null 2>&1; then printf "%s\\n" "\u6587\u672C\u641C\u7D22\u80FD\u529B\u4E0D\u53EF\u7528\uFF1A\u9700\u8981 od \u548C awk"; exit 127; fi; if [ -f "$p" ]; then set -- "$p"; elif [ -d "$p" ]; then directory=1; set -- "$p"/* "$p"/.[!.]* "$p"/..?*; else printf "%s\\n" "\u8DEF\u5F84\u4E0D\u662F\u666E\u901A\u6587\u4EF6\u6216\u76EE\u5F55"; exit 2; fi; for f do [ -f "$f" ] && [ ! -L "$f" ] || continue; case "$f" in ' + deniedPathCases + ') continue;; esac; if [ ! -r "$f" ]; then unread=$((unread+1)); continue; fi; [ "$count" -lt 100 ] || break; count=$((count+1)); hits=$(' + checkedTextSearch(matches) + '); ec=$?; if [ "$ec" -eq ' + CREDENTIAL_CONTENT_EXIT + ' ] && [ "$hits" = ' + quote(CREDENTIAL_CONTENT_MESSAGE) + ' ] && [ "$directory" -eq 1 ]; then credentials=$((credentials+1)); continue; fi; if [ "$ec" -ne 0 ]; then printf "%s" "$hits"; exit "$ec"; fi; if [ -n "$hits" ]; then printf "\\nFILE %s\\n%s\\n" "$f" "$hits"; fi; done; printf "\\n\u641C\u7D22\u8303\u56F4\uFF1A\u5DF2\u68C0\u67E5 %s \u4E2A\u6587\u4EF6\uFF0C\u8DF3\u8FC7 %s \u4E2A\u4E0D\u53EF\u8BFB\u6587\u4EF6\uFF0C\u8DF3\u8FC7 %s \u4E2A\u51ED\u636E\u5185\u5BB9\u6587\u4EF6\u3002\\n" "$count" "$unread" "$credentials"; exit 0';
1905
2053
  scope += "\uFF0C\u975E\u9012\u5F52\u5B57\u9762\u641C\u7D22\uFF0C\u6700\u591A 100 \u4E2A\u6587\u4EF6\uFF0C\u6BCF\u6587\u4EF6\u524D 64 KiB";
1906
2054
  break;
1907
2055
  }
@@ -2112,6 +2260,27 @@ function createBuiltinReadTools(execute) {
2112
2260
  details: { ...result.details, displayOutput: displayOutput2, command: prepared?.label ?? definition.label }
2113
2261
  };
2114
2262
  }
2263
+ if (result.details.exitCode === CREDENTIAL_CONTENT_EXIT && output.trim() === CREDENTIAL_CONTENT_MESSAGE) {
2264
+ const error = { code: "credential_content_denied", phase: "content", message: CREDENTIAL_CONTENT_MESSAGE };
2265
+ return {
2266
+ ...result,
2267
+ content: [{ type: "text", text: readResultText(
2268
+ definition.name,
2269
+ prepared?.scope ?? "\u5F53\u524D\u7ED1\u5B9A\u76EE\u6807",
2270
+ { format: prepared?.fileWindow ? "file" : "text", text: CREDENTIAL_CONTENT_MESSAGE },
2271
+ { status: "error", exitCode: CREDENTIAL_CONTENT_EXIT, error }
2272
+ ) }],
2273
+ details: {
2274
+ ...result.details,
2275
+ output: void 0,
2276
+ command: prepared?.label ?? definition.label,
2277
+ displayOutput: CREDENTIAL_CONTENT_MESSAGE,
2278
+ truncated: false,
2279
+ truncationReasons: [],
2280
+ readErrorCode: error.code
2281
+ }
2282
+ };
2283
+ }
2115
2284
  if (prepared?.fileWindow && (result.details.exitCode === 0 || output.startsWith("__ZTERM_FILE_V1__|"))) {
2116
2285
  const parsed = fileResult(output, prepared.fileWindow);
2117
2286
  const error = parsed?.error ?? (parsed ? null : {
@@ -2692,43 +2861,16 @@ async function fetchJumpserverNodeAssets(params, nodeId, query) {
2692
2861
  }
2693
2862
  async function fetchJumpserverAccounts(params, assetId) {
2694
2863
  const normalizedBase = normalizeJumpserverBaseUrl(params.baseUrl);
2695
- const profilePath = "/api/v1/users/profile/";
2696
- const profileDate = rfc1123Date();
2697
- const profileAuth = buildAuthHeader("GET", profilePath, profileDate, params);
2698
- if (profileAuth === null) {
2864
+ const accountsPath = `/api/v1/perms/users/self/assets/${assetId}/accounts/`;
2865
+ const accountsDate = rfc1123Date();
2866
+ const accountsAuth = buildAuthHeader("GET", accountsPath, accountsDate, params);
2867
+ if (accountsAuth === null) {
2699
2868
  return { success: false, accounts: [], error: "\u7F3A\u5C11\u51ED\u636E\uFF0C\u8BF7\u5148\u5B8C\u5584\u914D\u7F6E" };
2700
2869
  }
2701
- const profileHeaders = buildJumpserverHeaders(profileDate, {
2702
- "Authorization": profileAuth
2870
+ const accountsHeaders = buildJumpserverHeaders(accountsDate, {
2871
+ "Authorization": accountsAuth
2703
2872
  });
2704
2873
  try {
2705
- const { statusCode: profileCode, body: profileBody } = await makeRequest(
2706
- normalizedBase,
2707
- { method: "GET", path: profilePath, headers: profileHeaders, timeout: 15e3 },
2708
- params.verifyTls
2709
- );
2710
- if (profileCode < 200 || profileCode >= 300) {
2711
- return { success: false, accounts: [], error: translateJumpserverHttpStatus(profileCode, profileBody, "\u7528\u6237\u4FE1\u606F") };
2712
- }
2713
- let profile;
2714
- try {
2715
- profile = JSON.parse(profileBody);
2716
- } catch {
2717
- return { success: false, accounts: [], error: "\u670D\u52A1\u5668\u8FD4\u56DE\u4E86\u65E0\u6CD5\u89E3\u6790\u7684\u54CD\u5E94" };
2718
- }
2719
- const userId = String(profile.id || "");
2720
- if (!userId) {
2721
- return { success: false, accounts: [], error: "\u65E0\u6CD5\u83B7\u53D6\u5F53\u524D\u7528\u6237 ID" };
2722
- }
2723
- const accountsPath = `/api/v1/perms/users/${userId}/assets/${assetId}/accounts/`;
2724
- const accountsDate = rfc1123Date();
2725
- const accountsAuth = buildAuthHeader("GET", accountsPath, accountsDate, params);
2726
- if (accountsAuth === null) {
2727
- return { success: false, accounts: [], error: "\u7F3A\u5C11\u51ED\u636E\uFF0C\u8BF7\u5148\u5B8C\u5584\u914D\u7F6E" };
2728
- }
2729
- const accountsHeaders = buildJumpserverHeaders(accountsDate, {
2730
- "Authorization": accountsAuth
2731
- });
2732
2874
  const { statusCode: accountsCode, body: accountsBody } = await makeRequest(
2733
2875
  normalizedBase,
2734
2876
  { method: "GET", path: accountsPath, headers: accountsHeaders, timeout: 15e3 },
@@ -2940,7 +3082,6 @@ function resolveKokoSshParams(freshToken, clientUrl, baseUrl) {
2940
3082
  import { open } from "node:fs/promises";
2941
3083
  import { homedir, userInfo } from "node:os";
2942
3084
  import { isAbsolute as isAbsolute2, join as join2 } from "node:path";
2943
- import ssh23 from "ssh2";
2944
3085
 
2945
3086
  // src/host/errors.ts
2946
3087
  var ZtermError = class extends Error {
@@ -2976,10 +3117,11 @@ async function readDefaultPrivateKey(configured, passphrase, signal, home = home
2976
3117
  const value = await file.readFile({ encoding: "utf8" });
2977
3118
  checkCancelled(signal);
2978
3119
  if (Buffer.byteLength(value) > 1024 * 1024) throw new ZtermError("invalid_private_key", "\u9ED8\u8BA4 SSH \u79C1\u94A5\u6587\u4EF6\u8FC7\u5927");
2979
- const parsed = ssh23.utils.parseKey(value, passphrase);
2980
- if (parsed instanceof Error) throw new ZtermError("invalid_private_key", "\u9ED8\u8BA4 SSH \u79C1\u94A5\u65E0\u6CD5\u89E3\u6790\uFF1B\u82E5\u6587\u4EF6\u5DF2\u52A0\u5BC6\uFF0C\u8BF7\u5728\u8BE5\u4E3B\u673A\u7684\u7F16\u8F91\u9875\u9762\u586B\u5199\u79C1\u94A5\u53E3\u4EE4");
2981
- const keys = Array.isArray(parsed) ? parsed : [parsed];
2982
- if (!keys.some((key) => key.getPrivatePEM())) throw new ZtermError("invalid_private_key", "\u9ED8\u8BA4 SSH \u6587\u4EF6\u4E0D\u662F\u79C1\u94A5");
3120
+ try {
3121
+ normalizeSshPrivateKey(value, passphrase);
3122
+ } catch {
3123
+ throw new ZtermError("invalid_private_key", "\u9ED8\u8BA4 SSH \u79C1\u94A5\u65E0\u6CD5\u89E3\u6790\uFF1B\u8BF7\u68C0\u67E5\u5B8C\u6574\u79C1\u94A5\u548C\u7B97\u6CD5\uFF0C\u82E5\u6587\u4EF6\u5DF2\u52A0\u5BC6\uFF0C\u8BF7\u586B\u5199\u6B63\u786E\u7684\u79C1\u94A5\u53E3\u4EE4");
3124
+ }
2983
3125
  return value;
2984
3126
  } finally {
2985
3127
  await file.close();
@@ -3979,8 +4121,11 @@ Host ${host.id.replace(/[^\w-]/g, "_")}
3979
4121
  if (raw2.authType === "key" && (content || phrase || payload.clearPassphrase === true)) {
3980
4122
  const key = content || (await ctx.credentials.resolve(previous?.credentialRef))?.value;
3981
4123
  const passphrase = payload.clearPassphrase === true ? void 0 : phrase || (next.passphraseRef ? (await ctx.credentials.resolve(next.passphraseRef))?.value : void 0);
3982
- const parsed = key ? ssh24.utils.parseKey(key, passphrase) : void 0;
3983
- if (!parsed || parsed instanceof Error || !(Array.isArray(parsed) ? parsed : [parsed]).some((k) => k.getPrivatePEM())) throw new ZtermError("invalid_private_key", "\u79C1\u94A5\u5185\u5BB9\u65E0\u6548\u6216\u53E3\u4EE4\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5\u6587\u4EF6\u548C\u53E3\u4EE4");
4124
+ try {
4125
+ normalizeSshPrivateKey(key ?? "", passphrase);
4126
+ } catch {
4127
+ throw new ZtermError("invalid_private_key", "\u79C1\u94A5\u5185\u5BB9\u65E0\u6548\u6216\u53E3\u4EE4\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5\u6587\u4EF6\u548C\u53E3\u4EE4");
4128
+ }
3984
4129
  }
3985
4130
  const credential = validateCredential(next);
3986
4131
  await saveWithCredentials({ credentials: [...config().credentials.filter((c) => c.id !== credentialId), credential] }, payload.revision, secrets);