/** * ============================================================ * plugins/workflow-runner/src/util.ts —— 引擎内共用小件 * ------------------------------------------------------------ * 只放「多处要用、又不值得单开文件」的纯函数。有任何状态或 IO 的都不该进这里。 * ============================================================ */ import { resolve, sep } from 'node:path'; /** 截断到 n 个字符,超出补省略号。 */ export function truncate(s: string, n: number): string { return s.length > n ? `${s.slice(0, n)}…` : s; } /** * 把一个声明产物路径收敛成「相对 workingDir 的安全相对路径」;越界返回 null。 * * 自 legacy `types.ts` 原样移植,两处判据都是踩出来的,改之前先读: * * ① **前缀匹配必须带路径分隔符边界**。裸 `startsWith(base)` 会让 `/repo` 匹配上 * `/repo-hack/evil` —— 一个只差几个字符的兄弟目录就能骗过越界检查。 * * ② **Windows 上比较前要统一大小写**。NTFS 不区分大小写,`D:\Code` 与 `D:\code` * 是同一个目录,逐字节比较会把合法路径判成越界。(相关教训见记忆 * `project_windows_path_separator_gotcha`:同一类判据写死 `/` 分隔符时, * Windows 上条件恒为 false,缓存清理曾因此静默失效。) */ export function safeArtifactPath( workingDir: string, rawPath: string, ): string | null { if (!rawPath || typeof rawPath !== 'string') return null; const base = resolve(workingDir); const baseWithSep = base.endsWith(sep) ? base : base + sep; let abs: string; try { abs = resolve(workingDir, rawPath); } catch { return null; } const sameCase = (p: string): string => process.platform === 'win32' ? p.toLowerCase() : p; const nAbs = sameCase(abs); const nBase = sameCase(base); const nBaseSep = sameCase(baseWithSep); // 恰好等于 base 本身(rawPath='.' 这种极端情形)也算合法。 if (nAbs !== nBase && !nAbs.startsWith(nBaseSep)) return null; const rel = abs.slice(base.length).replace(/^[/\\]/, ''); return rel.length === 0 ? '.' : rel; }