remote-workspace-identity.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. // 远程 workspace identity 的统一解析工具(Workspace Identity 约束:构造与解析
  2. // 必须复用统一工具,禁止业务代码手写拼接/拆解规则)。
  3. // 构造侧(对偶):packages/ui/src/lib/remoteWorkspaceHistory.ts 的
  4. // buildRemoteWorkspaceIdentity —— 格式契约:
  5. // remote:ssh:<host>:<port>:<username>:<posixPath>
  6. // remote:wsl:<distro>[:<user>]:<posixPath>
  7. // remote:docker:<container>:<posixPath>
  8. // path 段经 normalizeWorkspacePathForIdentity 归一(分隔符 → "/",去收尾斜杠,
  9. // 空 → "/"),因此恒以 "/" 开头;authority 各段不含 "/"(host 小写、port 数字、
  10. // docker 容器名/wsl 发行版名的合法字符集均不含 ":" 与 "/")。
  11. // 消费方:CLI v4 createSession 的 workspaceId(远程 pane 里 workspaceKey =
  12. // identity)需要还原出真实 workspacePath 作为会话 workingDirectory。
  13. import type { RemoteTarget } from "./remoteTarget.js";
  14. export type RemoteWorkspaceIdentityKind = "ssh" | "wsl" | "docker" | "server";
  15. export interface ParsedRemoteWorkspaceIdentity {
  16. kind: RemoteWorkspaceIdentityKind;
  17. /** 远端真实路径(posix 归一形态)。 */
  18. workspacePath: string;
  19. }
  20. const REMOTE_IDENTITY_PREFIX = "remote:";
  21. /** authority 必选段数(不含 kind):ssh = host/port/username,其余远端类型 = 单段。 */
  22. const AUTHORITY_SEGMENTS: Record<RemoteWorkspaceIdentityKind, number> = {
  23. ssh: 3,
  24. wsl: 1,
  25. docker: 1,
  26. server: 1,
  27. };
  28. function isRemoteWorkspaceIdentityKind(
  29. value: string,
  30. ): value is RemoteWorkspaceIdentityKind {
  31. return value === "ssh" || value === "wsl" || value === "docker" || value === "server";
  32. }
  33. function normalizeWorkspacePathForIdentity(workspacePath: string): string {
  34. const normalized = workspacePath.replace(/\\/g, "/").replace(/\/+/g, "/");
  35. const trimmed = normalized.replace(/^\/+|\/+$/g, "");
  36. return `/${trimmed}`;
  37. }
  38. function resolveServerIdentityId(target: Extract<RemoteTarget, { kind: "server" }>): string {
  39. const explicit = target.serverId?.trim() || target.name?.trim();
  40. if (explicit) {
  41. return explicit;
  42. }
  43. try {
  44. return new URL(target.url.trim()).host;
  45. } catch {
  46. return target.url.trim();
  47. }
  48. }
  49. function normalizeServerIdForIdentity(serverId: string): string {
  50. const normalized = serverId
  51. .trim()
  52. .toLowerCase()
  53. .replace(/[^a-z0-9._-]+/g, "-")
  54. .replace(/^-+|-+$/g, "");
  55. if (!normalized) {
  56. throw new Error("serverId must contain at least one identity-safe character");
  57. }
  58. return normalized;
  59. }
  60. export interface BuildServerRemoteWorkspaceIdentityOptions {
  61. serverId: string;
  62. workspacePath: string;
  63. }
  64. export function buildServerRemoteWorkspaceIdentity(
  65. options: BuildServerRemoteWorkspaceIdentityOptions,
  66. ): string {
  67. const serverId = normalizeServerIdForIdentity(options.serverId);
  68. const workspacePath = normalizeWorkspacePathForIdentity(options.workspacePath);
  69. return `${REMOTE_IDENTITY_PREFIX}server:${serverId}:${workspacePath}`;
  70. }
  71. /**
  72. * 统一构造远程 workspace identity。Host、Main 和 UI 禁止自行拼接 authority;
  73. * `workspacePath` 只在这里归一后进入身份键,实际 IO 仍使用调用方原路径。
  74. */
  75. export function buildRemoteWorkspaceIdentity(
  76. workspacePath: string,
  77. target: RemoteTarget,
  78. ): string {
  79. const normalizedPath = normalizeWorkspacePathForIdentity(workspacePath);
  80. switch (target.kind) {
  81. case "ssh":
  82. return `remote:ssh:${target.host.trim().toLowerCase()}:${target.port ?? 22}:${target.username.trim()}:${normalizedPath}`;
  83. case "wsl": {
  84. const distro = target.distro?.trim() || "default";
  85. const user = target.user?.trim();
  86. return user
  87. ? `remote:wsl:${distro}:${user}:${normalizedPath}`
  88. : `remote:wsl:${distro}:${normalizedPath}`;
  89. }
  90. case "docker":
  91. return `remote:docker:${target.container}:${normalizedPath}`;
  92. case "server":
  93. return buildServerRemoteWorkspaceIdentity({
  94. serverId: resolveServerIdentityId(target),
  95. workspacePath: normalizedPath,
  96. });
  97. }
  98. }
  99. /**
  100. * 解析远程 workspace identity;非法/非远程 identity 返回 null(调用方回落
  101. * 「按本地 workspacePath 处理」)。只提取 workspacePath——authority 细节
  102. * (host/port 等)对消费方(CLI 运行在远端机器上)无意义,不透出。
  103. */
  104. export function parseRemoteWorkspaceIdentity(
  105. identity: string,
  106. ): ParsedRemoteWorkspaceIdentity | null {
  107. if (!identity.startsWith(REMOTE_IDENTITY_PREFIX)) {
  108. return null;
  109. }
  110. const rest = identity.slice(REMOTE_IDENTITY_PREFIX.length);
  111. const kindEnd = rest.indexOf(":");
  112. if (kindEnd <= 0) {
  113. return null;
  114. }
  115. const kind = rest.slice(0, kindEnd);
  116. if (!isRemoteWorkspaceIdentityKind(kind)) {
  117. return null;
  118. }
  119. // 逐段消费 authority;path 段可能含 ":"(理论上 posix 路径允许),
  120. // 因此不能整体 split——按段推进后取剩余整段为 path。
  121. let cursor = kindEnd + 1;
  122. for (let i = 0; i < AUTHORITY_SEGMENTS[kind]; i++) {
  123. const next = rest.indexOf(":", cursor);
  124. if (next <= cursor) {
  125. return null;
  126. }
  127. cursor = next + 1;
  128. }
  129. // WSL identity 为区分默认用户与显式用户增加了可选 user 段,旧解析器
  130. // 仍只消费 distro,导致 user 被误判为路径并让 identity 整体解析失败。远端路径
  131. // 必须以 "/" 开头,因此可以无歧义地区分 legacy 无 user 格式与显式 user 格式。
  132. if (kind === "wsl" && rest[cursor] !== "/") {
  133. const userEnd = rest.indexOf(":", cursor);
  134. if (userEnd <= cursor) {
  135. return null;
  136. }
  137. cursor = userEnd + 1;
  138. }
  139. const workspacePath = rest.slice(cursor);
  140. if (!workspacePath.startsWith("/")) {
  141. return null;
  142. }
  143. return { kind, workspacePath };
  144. }
  145. /** identity 是否是远程 workspace identity(可被 parseRemoteWorkspaceIdentity 解析)。 */
  146. export function isRemoteWorkspaceIdentity(identity: string): boolean {
  147. return parseRemoteWorkspaceIdentity(identity) !== null;
  148. }