diff --git a/.changeset/skills-v021-hardening.md b/.changeset/skills-v021-hardening.md new file mode 100644 index 00000000..c2c8a9b2 --- /dev/null +++ b/.changeset/skills-v021-hardening.md @@ -0,0 +1,14 @@ +--- +"sessionpipe-skills": patch +"sessionpipe": patch +--- + +Harden Agent Skills discovery, bundling, git sync, and control-channel installs: + +- Detect directory symlink cycles (including case-variant paths via `realpathSync.native`), bound directory visits against diamond-DAG DoS, reject non-regular files behind symlinks (e.g. FIFOs), guard unreadable entries against throwing, and check file/total byte limits before reading files into memory. +- Fix `UNSAFE_PROBLEM_RE` in `store.ts` to reject oversized (`skill exceeds … bytes total`) and unreadable skills before `installSkillFromDir` and `adoptSkill` write or delete files. +- Prevent self-symlink data loss on canonical, case-variant, and nested-subdir paths in `linkOnly` overwrites; avoid canonical self-destruction when `skillsDir` equals a harness `skillsDir`; verify `managedCopies` hashes before replacing/unlinking; and use backup-and-restore atomic replacement (`replacePathAtomic`) for writes, `linkOnly`, and `adoptSkill`. +- Reject reserved/ignored slugs (`node_modules`, `__macosx`, etc.) in `isValidSlug` and prevent slug `synced` from touching `~/.claude/skills/synced`. +- Guard `listDirNames` and `listClaudeSyncedSlugs` against regular files and `EACCES`, add random temp suffixes with cleanup on `writeSkillsState`, and check canonical-removal permission in `removeSkill` before unlinking harnesses. +- Fix `splitUstarPath` for multi-segment ustar paths, deduplicate archive paths with Unicode NFC + lowercase, and reject case-variant ignored directory segments (`.GIT`, `NODE_MODULES`, etc.) in `unpackSkillBundle`. +- Harden `syncGitCollection` against `subpath` prefix-collision traversal, symlink escapes, regular-file `ENOTDIR`, duplicate slugs, unsafe skills, harness conflicts, and ghost collections on failed syncs; fix `deriveCollectionId` for Windows backslashes and trailing `.git/`; and route local git repos and case-insensitive `.GIT/` paths to git sync in `skills add`. diff --git a/packages/cli/src/control/skills.ts b/packages/cli/src/control/skills.ts index 0530a140..4c987285 100644 --- a/packages/cli/src/control/skills.ts +++ b/packages/cli/src/control/skills.ts @@ -2,24 +2,18 @@ // Remote skills management for the control daemon (spec/CONTROL.md §2 `skills`, §6 `skill`): // reports the machine's skills inventory in `hello` and executes signed `skill` commands // against the local canonical library (`~/.agents/skills`) and installed harnesses. -import { lstatSync } from "node:fs"; -import path from "node:path"; import type { ControlCommand, ControlFile } from "@sessionpipe/core/control"; import { adoptSkill, - canonicalSkillsDir, detectedHarnesses, discoverSkills, - harnessTargets, installSkillBundle, isSkillHarnessId, isValidSlug, linkSkill, - readSymlinkTarget, removeSkill, type SkillHarnessId, type SkillsEnv, - safeRealpath, unlinkSkill, unpackSkillBundle, } from "@sessionpipe/skills"; @@ -101,37 +95,6 @@ function toSkillHarnesses(ids: readonly string[]): SkillHarnessId[] { return out; } -/** Pre-flight check for unmanaged harness entries before `installSkillBundle` touches disk, - * avoiding partial canonical writes when a subsequent non-forced `linkSkill` would refuse. */ -function findUnmanagedHarnessConflict( - slug: string, - harnesses: readonly SkillHarnessId[], - env?: SkillsEnv, -): string | null { - const canonical = path.join(canonicalSkillsDir(env), slug); - const canonicalReal = safeRealpath(canonical); - const byId = new Map(harnessTargets(env).map((t) => [t.id, t])); - for (const id of harnesses) { - const target = byId.get(id)!; - if (target.readsCanonicalNatively) continue; - const dst = path.join(target.skillsDir, slug); - let exists = false; - try { - lstatSync(dst); - exists = true; - } catch { - exists = false; - } - if (!exists) continue; - const linkTarget = readSymlinkTarget(dst); - const resolved = linkTarget !== null ? safeRealpath(linkTarget) : null; - if (!canonicalReal || resolved !== canonicalReal) { - return `refusing to overwrite unmanaged skill at ${dst} (pass overwrite=true to replace)`; - } - } - return null; -} - export interface SkillRunContext { via: "grant" | "confirm"; fetchBundle: (file: ControlFile) => Promise; @@ -157,10 +120,6 @@ export async function runSkillCommand(cmd: ControlCommand, ctx: SkillRunContext) }; } const harnesses = cmd.skill_harnesses ? toSkillHarnesses(cmd.skill_harnesses) : detectedHarnesses(ctx.env); - if (!cmd.skill_overwrite) { - const conflict = findUnmanagedHarnessConflict(slug, harnesses, ctx.env); - if (conflict) return { outcome: "refused", code: "skill", detail: conflict }; - } const installed = installSkillBundle(slug, bytes, { ...ctx.env, harnesses, diff --git a/packages/cli/test/control-skills.test.ts b/packages/cli/test/control-skills.test.ts index 391a0062..b9a580fa 100644 --- a/packages/cli/test/control-skills.test.ts +++ b/packages/cli/test/control-skills.test.ts @@ -227,7 +227,7 @@ describe("control skills unit helpers", () => { writeFileSync( statePath, JSON.stringify({ - v: 1, + version: 1, collections: [{ id: "Bad Collection!", name: "Bad", source: { kind: "local" }, skills: ["emoji-skill"] }], skills: {}, }), @@ -239,10 +239,19 @@ describe("control skills unit helpers", () => { expect(Array.from(inv.items[1]!.name)).toHaveLength(128); expect(inv.items[1]!.collections).toBeUndefined(); - // Unreadable skillsDir (regular file → ENOTDIR) never throws + // Non-dir skillsDir and unexpected discovery errors never throw const notADir = path.join(tmp, "not-a-dir"); writeFileSync(notADir, "file"); expect(helloSkills({ home, env: {}, skillsDir: notADir })).toEqual({ items: [], harnesses: ["claude-code"] }); + expect( + helloSkills({ + home, + env: {}, + get skillsDir(): string { + throw new Error("unexpected discovery error"); + }, + }), + ).toEqual({ items: [], harnesses: ["claude-code"] }); }); it("gates executable or non-prompt bundle files behind passkey confirm and pre-checks unmanaged conflicts", async () => { @@ -282,6 +291,27 @@ describe("control skills unit helpers", () => { expect(res).toMatchObject({ outcome: "refused", code: "skill" }); expect(existsSync(path.join(home, ".agents", "skills", "foo"))).toBe(false); + // Unmanaged skill in a native-reading harness (~/.codex/skills/codex-conflict) also blocks BEFORE writing canonical + writeSkillFixture(path.join(home, ".codex", "skills", "codex-conflict"), "codex-conflict"); + const codexRes = await runSkillCommand( + { + v: 1, + t: "sessionpipe.control", + machine: rx.machine, + kind: "skill", + session: SKILLS_SESSION, + skill_action: "install", + skill_slug: "codex-conflict", + skill_harnesses: ["codex"], + files: [{ name: "foo.tar.gz", type: "application/gzip", size: packedBytes.length, sha256: "A".repeat(43) }], + nonce: "n".repeat(22), + iat: 1, + } as ControlCommand, + { via: "grant", fetchBundle: async () => packedBytes, env: { home, env: {} } }, + ); + expect(codexRes).toMatchObject({ outcome: "refused", code: "skill" }); + expect(existsSync(path.join(home, ".agents", "skills", "codex-conflict"))).toBe(false); + // An existing canonical symlink passes pre-flight cleanly (then installSkillBundle refuses only because canonical exists) rmSync(path.join(home, ".claude", "skills", "foo"), { recursive: true, force: true }); const first = await runSkillCommand( diff --git a/packages/skills/src/archive.ts b/packages/skills/src/archive.ts index 6b8865ed..dec92b42 100644 --- a/packages/skills/src/archive.ts +++ b/packages/skills/src/archive.ts @@ -2,10 +2,19 @@ // Pure-TypeScript POSIX ustar .tar.gz packer and hardened unpacker for skill bundles. // Zero external dependencies and zero shell calls: validates checksums, entry types, // relative paths, file/byte limits, and optional expected content hash before writing. -import { chmodSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { randomBytes } from "node:crypto"; +import { chmodSync, lstatSync, mkdirSync, renameSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; import { gunzipSync, gzipSync } from "node:zlib"; -import { hashSkillFiles, isSafeRelPath, readSkillDir, type ScannedSkillFile, sha256Hex } from "./format.js"; +import { + hashSkillFiles, + hasUnsafeScanProblem, + isIgnoredSkillName, + isSafeRelPath, + readSkillDir, + type ScannedSkillFile, + sha256Hex, +} from "./format.js"; import { SKILL_LIMITS, type SkillFileEntry, type SkillMeta } from "./types.js"; const BLOCK = 512; @@ -40,13 +49,14 @@ function writeOctal(buf: Buffer, offset: number, length: number, value: number): function splitUstarPath(relPath: string): { prefix: string; name: string } { const bytes = Buffer.byteLength(relPath, "utf8"); if (bytes <= 100) return { prefix: "", name: relPath }; - const slash = relPath.lastIndexOf("/"); - if (slash > 0) { + let slash = relPath.lastIndexOf("/"); + while (slash > 0) { const prefix = relPath.slice(0, slash); const name = relPath.slice(slash + 1); if (Buffer.byteLength(prefix, "utf8") <= 155 && Buffer.byteLength(name, "utf8") <= 100) { return { prefix, name }; } + slash = relPath.lastIndexOf("/", slash - 1); } throw new Error(`path exceeds ustar limits: "${relPath}"`); } @@ -96,7 +106,9 @@ export function packSkillFiles(files: readonly BundleFile[]): Buffer { /** Scan, validate, and pack a skill directory into a content-addressed `.tar.gz` bundle. */ export function packSkillDir(dir: string, slugOverride?: string): PackedBundle { const res = readSkillDir(dir, slugOverride); - if (!res.meta) throw new Error(`cannot pack skill: ${res.problems.join("; ")}`); + if (!res.meta || hasUnsafeScanProblem(res.problems)) { + throw new Error(`cannot pack skill: ${res.problems.join("; ")}`); + } const bytes = packSkillFiles(res.files); return { slug: res.meta.slug, @@ -175,9 +187,12 @@ export function unpackSkillBundle(bundleBytes: Uint8Array, expectedHash?: string } const cleanPath = rawPath.replace(/^\.\//, ""); - if (!isSafeRelPath(cleanPath)) throw new Error(`unsafe archive path "${rawPath}"`); - if (seen.has(cleanPath)) throw new Error(`duplicate archive path "${cleanPath}"`); - seen.add(cleanPath); + if (!isSafeRelPath(cleanPath) || cleanPath.split("/").some((seg) => isIgnoredSkillName(seg))) { + throw new Error(`unsafe archive path "${rawPath}"`); + } + const normPath = cleanPath.normalize("NFC").toLowerCase(); + if (seen.has(normPath)) throw new Error(`duplicate archive path "${cleanPath}"`); + seen.add(normPath); if (files.length >= SKILL_LIMITS.files) { throw new Error(`archive exceeds maximum file count (${SKILL_LIMITS.files})`); @@ -212,26 +227,67 @@ export function unpackSkillBundle(bundleBytes: Uint8Array, expectedHash?: string return { files, hash, totalBytes }; } -/** Atomically extract a verified skill bundle into `destDir`. */ -export function extractSkillBundle(bundleBytes: Uint8Array, destDir: string, expectedHash?: string): UnpackedBundle { - const unpacked = unpackSkillBundle(bundleBytes, expectedHash); +/** Atomically replace `destPath` by moving any existing entry to a hidden backup sibling first, + * restoring the backup if `placeNew` throws so neither old nor new versions are lost. */ +export function replacePathAtomic( + destPath: string, + placeNew: () => void, + cleanupBackup: (backup: string) => void = (b) => rmSync(b, { recursive: true, force: true }), +): void { + const parent = path.dirname(destPath); + mkdirSync(parent, { recursive: true }); + let hadExisting = false; + try { + lstatSync(destPath); + hadExisting = true; + } catch { + hadExisting = false; + } + const backup = hadExisting + ? path.join(parent, `.${path.basename(destPath)}.bak-${process.pid}-${randomBytes(4).toString("hex")}`) + : null; + if (backup) renameSync(destPath, backup); + try { + placeNew(); + } catch (err) { + if (backup) renameSync(backup, destPath); + throw err; + } + if (backup) { + try { + cleanupBackup(backup); + } catch { + // New version is already published; ignore best-effort backup cleanup failure. + } + } +} + +/** Atomically write validated skill files into `destDir` using a hidden staging directory. */ +export function writeSkillFilesAtomic( + files: readonly { path: string; bytes: Uint8Array; executable?: boolean }[], + destDir: string, +): void { const parent = path.dirname(destDir); mkdirSync(parent, { recursive: true }); - const staging = path.join(parent, `.${path.basename(destDir)}.tmp-${process.pid}-${Date.now()}`); - rmSync(staging, { recursive: true, force: true }); + const staging = path.join(parent, `.${path.basename(destDir)}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`); mkdirSync(staging, { recursive: true }); try { - for (const f of unpacked.files) { + for (const f of files) { const target = path.join(staging, ...f.path.split("/")); mkdirSync(path.dirname(target), { recursive: true }); writeFileSync(target, f.bytes); if (f.executable) chmodSync(target, 0o755); } - rmSync(destDir, { recursive: true, force: true }); - renameSync(staging, destDir); + replacePathAtomic(destDir, () => renameSync(staging, destDir)); } catch (err) { rmSync(staging, { recursive: true, force: true }); throw err; } +} + +/** Atomically extract a verified skill bundle into `destDir`. */ +export function extractSkillBundle(bundleBytes: Uint8Array, destDir: string, expectedHash?: string): UnpackedBundle { + const unpacked = unpackSkillBundle(bundleBytes, expectedHash); + writeSkillFilesAtomic(unpacked.files, destDir); return unpacked; } diff --git a/packages/skills/src/commands.ts b/packages/skills/src/commands.ts index 553da420..bc304ff0 100644 --- a/packages/skills/src/commands.ts +++ b/packages/skills/src/commands.ts @@ -63,6 +63,12 @@ function parseFlags(argv: readonly string[]): { pos: string[]; flags: Map 0 && (s[end - 1] === "/" || s[end - 1] === "\\")) end--; + return s.slice(0, end); +} + function parseHarnesses(raw: string | true | undefined, opts?: SkillsEnv): SkillHarnessId[] { if (typeof raw !== "string") { const found = detectedHarnesses(opts); @@ -170,7 +176,15 @@ export function skillsMain( const harnesses = flags.has("--harness") ? parseHarnesses(flags.get("--harness"), opts) : undefined; const collectionId = typeof flags.get("--collection") === "string" ? (flags.get("--collection") as string) : undefined; - const isLocalDir = existsSync(path.resolve(target)) && !target.endsWith(".git"); + const resolvedTarget = path.resolve(target); + const hasGitFlags = flags.has("--ref") || flags.has("--subpath"); + const isBareOrMultiGit = + hasGitFlags || + trimTrailingSlashes(target).toLowerCase().endsWith(".git") || + (existsSync(path.join(resolvedTarget, ".git")) && + !existsSync(path.join(resolvedTarget, "SKILL.md")) && + !existsSync(path.join(resolvedTarget, "skill.md"))); + const isLocalDir = existsSync(resolvedTarget) && !isBareOrMultiGit; if (isLocalDir) { const slug = typeof flags.get("--slug") === "string" ? (flags.get("--slug") as string) : undefined; const skill = installSkillFromDir(target, { diff --git a/packages/skills/src/format.ts b/packages/skills/src/format.ts index 8abe156e..0b50b87d 100644 --- a/packages/skills/src/format.ts +++ b/packages/skills/src/format.ts @@ -2,7 +2,7 @@ // Agent Skills (SKILL.md) parser, validator, safe directory scanner, and deterministic // content hasher. Pure Node builtins, zero runtime dependencies. import { createHash } from "node:crypto"; -import { lstatSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; +import { type Dirent, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs"; import path from "node:path"; import { SKILL_LIMITS, type SkillFileEntry, type SkillMeta } from "./types.js"; @@ -10,15 +10,21 @@ import { SKILL_LIMITS, type SkillFileEntry, type SkillMeta } from "./types.js"; export const SKILL_SLUG_RE = /^[a-z0-9](?:[a-z0-9._-]{0,62}[a-z0-9])?$/; export const SKILL_IGNORED_NAMES = new Set([".git", "node_modules", ".DS_Store", "__MACOSX"]); +const SKILL_IGNORED_LOWER = new Set([...SKILL_IGNORED_NAMES].map((n) => n.toLowerCase())); +const MAX_WALK_DIRS = 1024; + +export function isIgnoredSkillName(name: string): boolean { + return SKILL_IGNORED_LOWER.has(name.toLowerCase()); +} export function isValidSlug(slug: string): boolean { - return SKILL_SLUG_RE.test(slug) && !slug.includes(".."); + return SKILL_SLUG_RE.test(slug) && !slug.includes("..") && !isIgnoredSkillName(slug); } -/** Strict relative POSIX path check: no leading slash, backslashes, NUL, control chars, or dot segments. */ +/** Strict relative POSIX path check: no leading slash, backslashes, colons, NUL, control chars, or dot segments. */ export function isSafeRelPath(relPath: string): boolean { if (!relPath || Buffer.byteLength(relPath, "utf8") > SKILL_LIMITS.pathBytes) return false; - if (relPath.startsWith("/") || relPath.endsWith("/") || relPath.includes("\\")) return false; + if (relPath.startsWith("/") || relPath.endsWith("/") || relPath.includes("\\") || relPath.includes(":")) return false; for (let i = 0; i < relPath.length; i++) { const code = relPath.charCodeAt(i); if (code < 0x20 || code === 0x7f) return false; @@ -30,6 +36,25 @@ export function isSafeRelPath(relPath: string): boolean { return true; } +const UNSAFE_PROBLEM_RE = + /^(?:symlink |broken symlink|unsafe file path|unsupported file type|exceeds |file |skill exceeds |skill path |skill directory |unreadable |missing SKILL\.md)/; + +/** True when `readSkillDir` problems indicate a security, limit, or readability violation. */ +export function hasUnsafeScanProblem(problems: readonly string[]): boolean { + return problems.some((p) => UNSAFE_PROBLEM_RE.test(p)); +} + +const META_KEY_RE = /^[A-Za-z0-9_.-]+$/; +const FIELD_KEY_RE = /^[A-Za-z0-9_-]+$/; + +function splitMappingLine(line: string, keyRe: RegExp): { key: string; value: string } | null { + const colon = line.indexOf(":"); + if (colon <= 0) return null; + const key = line.slice(0, colon).trimEnd(); + if (!keyRe.test(key)) return null; + return { key, value: line.slice(colon + 1).trim() }; +} + export interface ParsedFrontmatter { fields: Record; metadata: Record; @@ -80,20 +105,20 @@ export function parseFrontmatter(markdown: string): ParsedFrontmatter { const line = lines[i]!; if (!line.trim() || line.trimStart().startsWith("#")) continue; - if (inMetadata && /^\s+/.test(line)) { - const m = /^\s+([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(line); - if (m) metadata[m[1]!] = unquoteScalar(m[2]!); + if (inMetadata && line !== line.trimStart()) { + const m = splitMappingLine(line.trimStart(), META_KEY_RE); + if (m) metadata[m.key] = unquoteScalar(m.value); continue; } inMetadata = false; - const match = /^([A-Za-z0-9_-]+)\s*:\s*(.*)$/.exec(line); + const match = splitMappingLine(line, FIELD_KEY_RE); if (!match) { problems.push(`frontmatter line ${i + 1} is not a key: value mapping`); continue; } - const key = match[1]!; - const rawVal = match[2]!.trim(); + const key = match.key; + const rawVal = match.value; if (key === "metadata" && rawVal === "") { inMetadata = true; @@ -169,7 +194,7 @@ export function readSkillDir(dir: string, slugOverride?: string): ReadSkillResul let rootReal: string; try { - rootReal = realpathSync(dir); + rootReal = realpathSync.native(dir); if (!statSync(rootReal).isDirectory()) { return { meta: null, files: [], problems: [...problems, "skill path is not a directory"] }; } @@ -178,12 +203,30 @@ export function readSkillDir(dir: string, slugOverride?: string): ReadSkillResul } const files: ScannedSkillFile[] = []; + const ancestors = new Set([rootReal]); let totalBytes = 0; + let visitedDirs = 0; + let dirLimitHit = false; + + const walk = (absDir: string, relPrefix: string, dirReal: string): void => { + visitedDirs++; + if (visitedDirs > MAX_WALK_DIRS) { + dirLimitHit = true; + problems.push(`exceeds maximum directory count (${MAX_WALK_DIRS})`); + return; + } + + let entries: Dirent[]; + try { + entries = readdirSync(absDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name, "en")); + } catch { + problems.push(`unreadable directory "${relPrefix || "."}"`); + return; + } - const walk = (absDir: string, relPrefix: string): void => { - const entries = readdirSync(absDir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name, "en")); for (const entry of entries) { - if (SKILL_IGNORED_NAMES.has(entry.name)) continue; + if (dirLimitHit) return; + if (isIgnoredSkillName(entry.name)) continue; const absPath = path.join(absDir, entry.name); const relPath = relPrefix ? `${relPrefix}/${entry.name}` : entry.name; if (!isSafeRelPath(relPath)) { @@ -191,55 +234,72 @@ export function readSkillDir(dir: string, slugOverride?: string): ReadSkillResul continue; } - const lst = lstatSync(absPath); - if (lst.isSymbolicLink()) { - let targetReal: string; - try { - targetReal = realpathSync(absPath); - } catch { - problems.push(`broken symlink "${relPath}"`); + try { + const lst = lstatSync(absPath); + if (lst.isSymbolicLink()) { + let targetReal: string; + try { + targetReal = realpathSync.native(absPath); + } catch { + problems.push(`broken symlink "${relPath}"`); + continue; + } + if (!isInsideRoot(rootReal, targetReal)) { + problems.push(`symlink escapes skill directory: "${relPath}"`); + continue; + } + const st = statSync(targetReal); + if (st.isDirectory()) { + if (ancestors.has(targetReal)) { + problems.push(`symlink cycle "${relPath}"`); + continue; + } + ancestors.add(targetReal); + walk(absPath, relPath, targetReal); + ancestors.delete(targetReal); + continue; + } + if (!st.isFile()) { + problems.push(`unsupported file type "${relPath}"`); + continue; + } + addFile(targetReal, relPath, st.mode, st.size); continue; } - if (!isInsideRoot(rootReal, targetReal)) { - problems.push(`symlink escapes skill directory: "${relPath}"`); + + if (lst.isDirectory()) { + const childReal = path.join(dirReal, entry.name); + ancestors.add(childReal); + walk(absPath, relPath, childReal); + ancestors.delete(childReal); continue; } - const st = statSync(targetReal); - if (st.isDirectory()) { - walk(absPath, relPath); + if (!lst.isFile()) { + problems.push(`unsupported file type "${relPath}"`); continue; } - addFile(targetReal, relPath, st.mode); - continue; - } - - if (lst.isDirectory()) { - walk(absPath, relPath); - continue; + addFile(absPath, relPath, lst.mode, lst.size); + } catch { + problems.push(`unreadable file "${relPath}"`); } - if (!lst.isFile()) { - problems.push(`unsupported file type "${relPath}"`); - continue; - } - addFile(absPath, relPath, lst.mode); } }; - const addFile = (absPath: string, relPath: string, mode: number): void => { + const addFile = (absPath: string, relPath: string, mode: number, size: number): void => { if (files.length >= SKILL_LIMITS.files) { problems.push(`exceeds maximum file count (${SKILL_LIMITS.files})`); return; } - const bytes = readFileSync(absPath); - if (bytes.length > SKILL_LIMITS.fileBytes) { + if (size > SKILL_LIMITS.fileBytes) { problems.push(`file "${relPath}" exceeds ${SKILL_LIMITS.fileBytes} bytes`); return; } - totalBytes += bytes.length; - if (totalBytes > SKILL_LIMITS.bundleBytes) { + if (totalBytes + size > SKILL_LIMITS.bundleBytes) { problems.push(`skill exceeds ${SKILL_LIMITS.bundleBytes} bytes total`); return; } + const bytes = readFileSync(absPath); + totalBytes += bytes.length; files.push({ path: relPath, size: bytes.length, @@ -249,7 +309,7 @@ export function readSkillDir(dir: string, slugOverride?: string): ReadSkillResul }); }; - walk(rootReal, ""); + walk(rootReal, "", rootReal); const skillFile = files.find((f) => f.path === "SKILL.md") ?? files.find((f) => f.path === "skill.md"); if (!skillFile) { diff --git a/packages/skills/src/git.ts b/packages/skills/src/git.ts index 82e58f85..8faeed76 100644 --- a/packages/skills/src/git.ts +++ b/packages/skills/src/git.ts @@ -3,12 +3,20 @@ // Executes `git` directly via execFileSync (no shell) and validates repo/ref arguments // against option injection before invoking git. import { execFileSync } from "node:child_process"; -import { existsSync, mkdtempSync, readdirSync, rmSync } from "node:fs"; +import { existsSync, mkdtempSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs"; import os from "node:os"; import path from "node:path"; -import { isValidSlug, readSkillDir, SKILL_IGNORED_NAMES } from "./format.js"; -import type { LinkDeps } from "./harnesses.js"; -import { installSkillFromDir, listCollections, readSkillsState, upsertCollection } from "./store.js"; +import { hasUnsafeScanProblem, isIgnoredSkillName, isValidSlug, readSkillDir } from "./format.js"; +import { canonicalSkillsDir, detectedHarnesses, type LinkDeps, readSymlinkTarget } from "./harnesses.js"; +import { + assertAllowedHarnessSlug, + assertNoUnmanagedHarnessConflicts, + discoverSkills, + installSkillFromDir, + listCollections, + readSkillsState, + upsertCollection, +} from "./store.js"; import type { DiscoveredSkill, SkillCollection, SkillHarnessId, SkillsEnv } from "./types.js"; const GITHUB_SHORTHAND_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; @@ -47,11 +55,17 @@ function trimChar(s: string, ch: string): string { return s.slice(start, end); } +function trimTrailingSlashes(s: string): string { + let end = s.length; + while (end > 0 && (s[end - 1] === "/" || s[end - 1] === "\\")) end--; + return s.slice(0, end); +} + export function deriveCollectionId(repo: string, subpath?: string): string { - let trimmed = repo.replace(/\.git$/i, ""); - while (trimmed.endsWith("/")) trimmed = trimmed.slice(0, -1); - const base = trimmed.split(/[/:]/).pop()!; - const raw = subpath ? `${base}-${path.basename(subpath)}` : base; + const trimmed = trimTrailingSlashes(trimTrailingSlashes(repo).replace(/\.git$/i, "")); + const base = trimmed.split(/[/\\:]/).pop()!; + const subBase = subpath ? subpath.split(/[/\\]/).filter(Boolean).pop() : undefined; + const raw = subBase ? `${base}-${subBase}` : base; const slug = trimChar(raw.toLowerCase().replace(/[^a-z0-9._-]+/g, "-"), "-").slice(0, 64); return isValidSlug(slug) ? slug : "git-skills"; } @@ -70,7 +84,7 @@ function findSkillDirs(root: string, fallbackSlug: string): { slug: string; dir: if (depth > 3) return; const entries = readdirSync(dir, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name, "en")); for (const entry of entries) { - if (!entry.isDirectory() || entry.name.startsWith(".") || SKILL_IGNORED_NAMES.has(entry.name)) continue; + if (!entry.isDirectory() || entry.name.startsWith(".") || isIgnoredSkillName(entry.name)) continue; const abs = path.join(dir, entry.name); if (existsSync(path.join(abs, "SKILL.md")) || existsSync(path.join(abs, "skill.md"))) { const slug = entry.name.toLowerCase(); @@ -111,6 +125,9 @@ export function syncGitCollection(repoInput: string, opts?: SyncGitOptions): Syn if (opts?.ref && (!SAFE_REF_RE.test(opts.ref) || opts.ref.startsWith("-") || opts.ref.includes(".."))) { throw new Error(`invalid git ref "${opts.ref}"`); } + if (opts?.collectionId !== undefined && !isValidSlug(opts.collectionId)) { + throw new Error(`invalid collection id "${opts.collectionId}"`); + } const git = opts?.git ?? defaultGitRunner; const tmp = mkdtempSync(path.join(os.tmpdir(), "sp-skills-git-")); try { @@ -120,8 +137,16 @@ export function syncGitCollection(repoInput: string, opts?: SyncGitOptions): Syn git.run(cloneArgs); const commit = git.run(["rev-parse", "HEAD"], tmp); - const searchRoot = opts?.subpath ? path.resolve(tmp, opts.subpath) : tmp; - if (!searchRoot.startsWith(tmp) || !existsSync(searchRoot)) { + const tmpReal = realpathSync.native(tmp); + const candidate = opts?.subpath ? path.resolve(tmpReal, opts.subpath) : tmpReal; + let searchRoot: string; + try { + searchRoot = realpathSync.native(candidate); + if (!statSync(searchRoot).isDirectory()) throw new Error("not a directory"); + } catch { + throw new Error(`subpath "${opts?.subpath}" not found in repository`); + } + if (searchRoot !== tmpReal && !searchRoot.startsWith(tmpReal + path.sep)) { throw new Error(`subpath "${opts?.subpath}" not found in repository`); } @@ -133,6 +158,44 @@ export function syncGitCollection(repoInput: string, opts?: SyncGitOptions): Syn const prevState = readSkillsState(opts); const existing = listCollections(opts).find((c) => c.id === collectionId); + const canonRoot = canonicalSkillsDir(opts); + const harnesses = opts?.harnesses ?? detectedHarnesses(opts); + const forceHarnesses = !!opts?.overwrite; + const seenSlugs = new Set(); + for (const d of dirs) { + if (seenSlugs.has(d.slug)) { + throw new Error(`duplicate skill slug "${d.slug}" found in repository`); + } + seenSlugs.add(d.slug); + const scanned = readSkillDir(d.dir, d.slug); + if (hasUnsafeScanProblem(scanned.problems)) { + throw new Error(`invalid skill "${d.slug}" in repository: ${scanned.problems.join("; ")}`); + } + assertAllowedHarnessSlug(d.slug, harnesses, opts); + const sameCollection = prevState.skills[d.slug]?.collectionId === collectionId; + const overwriteCanonical = opts?.overwrite ?? sameCollection; + const dest = path.join(canonRoot, d.slug); + if (!overwriteCanonical && (existsSync(dest) || readSymlinkTarget(dest) !== null)) { + throw new Error(`skill "${d.slug}" already exists in ${canonRoot} (pass overwrite to replace)`); + } + if (!forceHarnesses && harnesses.length > 0) { + assertNoUnmanagedHarnessConflicts(d.slug, harnesses, prevState, opts); + } + } + + const installedSlugs: string[] = []; + for (const d of dirs) { + const sameCollection = prevState.skills[d.slug]?.collectionId === collectionId; + const installed = installSkillFromDir(d.dir, { + ...opts, + slug: d.slug, + collectionId, + overwrite: opts?.overwrite ?? sameCollection, + forceHarnesses, + }); + installedSlugs.push(installed.slug); + } + const collection = upsertCollection( { id: collectionId, @@ -153,24 +216,13 @@ export function syncGitCollection(repoInput: string, opts?: SyncGitOptions): Syn commit, lastSyncedAt: new Date().toISOString(), }, - skills: dirs.map((d) => d.slug), + skills: installedSlugs, }, opts, ); - const installed: DiscoveredSkill[] = []; - for (const d of dirs) { - const sameCollection = prevState.skills[d.slug]?.collectionId === collection.id; - installed.push( - installSkillFromDir(d.dir, { - ...opts, - slug: d.slug, - collectionId: collection.id, - overwrite: opts?.overwrite ?? sameCollection, - }), - ); - } - + const bySlug = new Map(discoverSkills(opts).map((s) => [s.slug, s])); + const installed = installedSlugs.map((slug) => bySlug.get(slug)!); return { repo, commit, collection, installed }; } finally { rmSync(tmp, { recursive: true, force: true }); diff --git a/packages/skills/src/harnesses.ts b/packages/skills/src/harnesses.ts index 77118859..a5728c5c 100644 --- a/packages/skills/src/harnesses.ts +++ b/packages/skills/src/harnesses.ts @@ -94,7 +94,7 @@ export function detectedHarnesses(opts?: SkillsEnv): SkillHarnessId[] { /** Resolve real path when possible, returning null if missing or broken. */ export function safeRealpath(p: string): string | null { try { - return realpathSync(p); + return realpathSync.native(p); } catch { return null; } diff --git a/packages/skills/src/store.ts b/packages/skills/src/store.ts index 40307324..d14bbc80 100644 --- a/packages/skills/src/store.ts +++ b/packages/skills/src/store.ts @@ -2,21 +2,23 @@ // Canonical skills library (~/.agents/skills) + collections store (~/.config/sessionpipe/skills.json): // discover across all harnesses, adopt into canonical library, install from folder or bundle, // project via managed symlinks/copies, and manage collections without clobbering user edits. +import { randomBytes } from "node:crypto"; import { - chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, + readlinkSync, renameSync, rmSync, + statSync, symlinkSync, writeFileSync, } from "node:fs"; import path from "node:path"; -import { extractSkillBundle } from "./archive.js"; -import { isValidSlug, readSkillDir, SKILL_IGNORED_NAMES } from "./format.js"; +import { extractSkillBundle, replacePathAtomic, writeSkillFilesAtomic } from "./archive.js"; +import { hasUnsafeScanProblem, isIgnoredSkillName, isValidSlug, readSkillDir } from "./format.js"; import { canonicalSkillsDir, detectedHarnesses, @@ -65,25 +67,42 @@ export function readSkillsState(opts?: SkillsEnv): SkillsState { export function writeSkillsState(state: SkillsState, opts?: SkillsEnv): void { const file = skillsStateFile(opts); mkdirSync(path.dirname(file), { recursive: true }); - const tmp = `${file}.tmp-${process.pid}-${Date.now()}`; - writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 }); - renameSync(tmp, file); + const tmp = `${file}.tmp-${process.pid}-${randomBytes(4).toString("hex")}`; + try { + writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 }); + renameSync(tmp, file); + } catch (err) { + rmSync(tmp, { force: true }); + throw err; + } +} + +function isDirectory(p: string): boolean { + try { + return statSync(p).isDirectory(); + } catch { + return false; + } } function listDirNames(dir: string): string[] { - if (!existsSync(dir)) return []; - return readdirSync(dir) - .filter((name) => !name.startsWith(".") && !SKILL_IGNORED_NAMES.has(name)) - .sort((a, b) => a.localeCompare(b, "en")); + if (!isDirectory(dir)) return []; + try { + return readdirSync(dir) + .filter((name) => !name.startsWith(".") && !isIgnoredSkillName(name)) + .sort((a, b) => a.localeCompare(b, "en")); + } catch { + return []; + } } function listClaudeSyncedSlugs(claudeSkillsDir: string): { slug: string; dir: string }[] { const syncedRoot = path.join(claudeSkillsDir, "synced"); - if (!existsSync(syncedRoot)) return []; + if (!isDirectory(syncedRoot)) return []; const out: { slug: string; dir: string }[] = []; for (const bucket of listDirNames(syncedRoot)) { const bucketDir = path.join(syncedRoot, bucket); - if (!safeRealpath(bucketDir)) continue; + if (!isDirectory(bucketDir)) continue; for (const slug of listDirNames(bucketDir)) { out.push({ slug, dir: path.join(bucketDir, slug) }); } @@ -130,25 +149,26 @@ export function discoverSkills(opts?: SkillsEnv): DiscoveredSkill[] { } // 2. Scan each harness directory for links, copies, conflicts, or unmanaged discovered skills. + const caseInsensitive = isCaseInsensitivePlatform(opts); + const win32 = (opts?.platform ?? process.platform) === "win32"; const isDefaultCanon = !opts?.skillsDir && !(opts?.env ?? process.env).SESSIONPIPE_SKILLS_DIR; for (const target of targets) { const harnessInstalled = existsSync(target.homeDir) || existsSync(target.skillsDir); for (const slug of listDirNames(target.skillsDir)) { - if (target.id === "claude-code" && slug === "synced") continue; + if (isClaudeSyncedTarget(slug, target.skillsDir, opts)) continue; const entryPath = path.join(target.skillsDir, slug); const scanned = readSkillDir(entryPath, slug); if (!scanned.meta) continue; const symTarget = readSymlinkTarget(entryPath); - const entryReal = safeRealpath(entryPath); const existing = bySlug.get(slug); if (existing?.canonicalPath) { - const canonReal = safeRealpath(existing.canonicalPath); const rec = state.skills[slug]; - const isLinkedToCanon = !!symTarget && !!canonReal && entryReal === canonReal; let status: SkillLinkStatus["status"]; - if (isLinkedToCanon) { + if (isSameDirEntry(entryPath, existing.canonicalPath, caseInsensitive)) { + status = "native"; + } else if (isManagedCanonicalLink(entryPath, symTarget, existing.canonicalPath, caseInsensitive, win32)) { status = "linked"; } else if (rec?.managedCopies?.[target.id] === scanned.meta.hash) { status = "copied"; @@ -297,6 +317,165 @@ function attachToCollection(state: SkillsState, collectionId: string, slug: stri if (col && !col.skills.includes(slug)) col.skills.push(slug); } +function isCaseInsensitivePlatform(opts?: SkillsEnv): boolean { + const platform = opts?.platform ?? process.platform; + return platform === "win32" || platform === "darwin"; +} + +function canonicalSlotPath(p: string): string { + const abs = path.resolve(p); + const tail = [path.basename(abs)]; + let cur = path.dirname(abs); + let real = safeRealpath(cur); + while (real === null) { + tail.push(path.basename(cur)); + cur = path.dirname(cur); + real = safeRealpath(cur); + } + return path.join(real, ...tail.reverse()); +} + +function isSameDirEntry(a: string, b: string, caseInsensitive: boolean): boolean { + const sa = canonicalSlotPath(a); + const sb = canonicalSlotPath(b); + return caseInsensitive ? sa.toLowerCase() === sb.toLowerCase() : sa === sb; +} + +function readRawSymlink(p: string): string | null { + try { + return lstatSync(p).isSymbolicLink() ? readlinkSync(p) : null; + } catch { + return null; + } +} + +function splitRawSegments(raw: string, win32: boolean): string[] { + return raw + .split(win32 ? /[\\/]+/ : path.sep) + .flatMap((s) => s.split("/")) + .filter((s) => s !== "" && s !== "."); +} + +/** POSIX-exact component-by-component symlink walker using raw `readlinkSync` (never lexically collapsing `..`). + * - `mode === "traverse"`: returns true if `startPath` visits `targetPath` at any step (fails closed `true` on `maxHops`). + * - `mode === "resolve"`: returns true if `startPath` resolves to `targetPath` (stopping when reached with no remaining segments; fails safe `false` on `maxHops`). */ +export function walkPathToTarget( + startPath: string, + targetPath: string, + caseInsensitive: boolean, + mode: "traverse" | "resolve", + maxHops = 40, + win32 = process.platform === "win32", +): boolean { + const parsed = path.parse(startPath); + let cur: string; + let queue: string[]; + if (parsed.root) { + cur = parsed.root; + queue = splitRawSegments(startPath.slice(parsed.root.length), win32); + } else { + const cwd = path.resolve("."); + const cwdRoot = path.parse(cwd).root; + cur = cwdRoot; + queue = [...splitRawSegments(cwd.slice(cwdRoot.length), win32), ...splitRawSegments(startPath, win32)]; + } + let hops = 0; + + while (true) { + const matched = isSameDirEntry(cur, targetPath, caseInsensitive); + if (matched && (mode === "traverse" || queue.length === 0)) return true; + + const raw = readRawSymlink(cur); + if (raw !== null) { + hops++; + if (hops > maxHops) return mode === "traverse"; + const rawRoot = path.parse(raw).root; + if (rawRoot) { + cur = rawRoot; + queue.unshift(...splitRawSegments(raw.slice(rawRoot.length), win32)); + } else { + cur = path.dirname(cur); + queue.unshift(...splitRawSegments(raw, win32)); + } + continue; + } + + if (queue.length === 0) return matched; + const seg = queue.shift()!; + cur = seg === ".." ? path.dirname(cur) : path.join(cur, seg); + } +} + +function isManagedCanonicalLink( + dest: string, + symTarget: string | null, + canonPath: string, + caseInsensitive: boolean, + win32: boolean, +): boolean { + if (!symTarget) return false; + return walkPathToTarget(dest, canonPath, caseInsensitive, "resolve", 40, win32); +} + +function isClaudeSyncedTarget(slug: string, targetSkillsDir: string, opts?: SkillsEnv): boolean { + if (slug !== "synced") return false; + const claudeTarget = harnessTargets(opts).find((t) => t.id === "claude-code")!; + const caseInsensitive = isCaseInsensitivePlatform(opts); + const win32 = (opts?.platform ?? process.platform) === "win32"; + return ( + isSameDirEntry( + path.join(targetSkillsDir, "synced"), + path.join(claudeTarget.skillsDir, "synced"), + caseInsensitive, + ) || walkPathToTarget(targetSkillsDir, claudeTarget.skillsDir, caseInsensitive, "resolve", 40, win32) + ); +} + +export function assertAllowedHarnessSlug(slug: string, harnesses: readonly SkillHarnessId[], opts?: SkillsEnv): void { + if (slug !== "synced") return; + const targetMap = new Map(harnessTargets(opts).map((t) => [t.id, t])); + for (const h of harnesses) { + if (isClaudeSyncedTarget(slug, targetMap.get(h)!.skillsDir, opts)) { + throw new Error('skill slug "synced" is reserved in claude-code (~/.claude/skills/synced)'); + } + } +} + +function isUnmodifiedManagedCopy( + dest: string, + slug: string, + expectedHash: string | undefined, + existingSym: string | null, +): boolean { + if (!expectedHash || existingSym !== null) return false; + const scanned = readSkillDir(dest, slug); + return !hasUnsafeScanProblem(scanned.problems) && scanned.meta!.hash === expectedHash; +} + +export function assertNoUnmanagedHarnessConflicts( + slug: string, + harnesses: readonly SkillHarnessId[], + state: SkillsState, + opts?: SkillsEnv, +): void { + const canonPath = path.join(canonicalSkillsDir(opts), slug); + const caseInsensitive = isCaseInsensitivePlatform(opts); + const win32 = (opts?.platform ?? process.platform) === "win32"; + const targetMap = new Map(harnessTargets(opts).map((t) => [t.id, t])); + const rec = state.skills[slug]; + + for (const h of harnesses) { + const target = targetMap.get(h)!; + const dest = path.join(target.skillsDir, slug); + const existingSym = readSymlinkTarget(dest); + if (!existsSync(dest) && !existingSym) continue; + if (isSameDirEntry(dest, canonPath, caseInsensitive)) continue; + if (isManagedCanonicalLink(dest, existingSym, canonPath, caseInsensitive, win32)) continue; + if (isUnmodifiedManagedCopy(dest, slug, rec?.managedCopies?.[h], existingSym)) continue; + throw new Error(`refusing to overwrite unmanaged skill at ${dest} (pass force to replace)`); + } +} + /** Project a canonical skill into the specified harnesses, refusing to clobber unmanaged edits unless forced. */ export function linkSkill( slug: string, @@ -304,36 +483,40 @@ export function linkSkill( opts?: SkillsEnv & { force?: boolean; linkDeps?: LinkDeps }, ): SkillLinkStatus[] { if (!isValidSlug(slug)) throw new Error(`invalid skill slug "${slug}"`); + assertAllowedHarnessSlug(slug, harnesses, opts); const canonPath = path.join(canonicalSkillsDir(opts), slug); const scanned = readSkillDir(canonPath, slug); if (!scanned.meta) throw new Error(`skill "${slug}" is not in canonical library: ${scanned.problems.join("; ")}`); const state = readSkillsState(opts); + if (!opts?.force) { + assertNoUnmanagedHarnessConflicts(slug, harnesses, state, opts); + } const symTarget = readSymlinkTarget(canonPath); const rec = ensureManagedRecord(state, slug, symTarget ? "symlink" : "managed", scanned.meta.hash, { ...(symTarget ? { linkedTarget: symTarget } : {}), }); const targetMap = new Map(harnessTargets(opts).map((t) => [t.id, t])); - const canonReal = safeRealpath(canonPath); const platform = opts?.platform ?? process.platform; + const win32 = platform === "win32"; + const caseInsensitive = isCaseInsensitivePlatform(opts); const results: SkillLinkStatus[] = []; for (const h of harnesses) { const target = targetMap.get(h)!; const dest = path.join(target.skillsDir, slug); const existingSym = readSymlinkTarget(dest); - const existingReal = safeRealpath(dest); - if (existingSym && canonReal && existingReal === canonReal) { - results.push({ harness: h, status: "linked", path: dest, target: existingSym, hash: scanned.meta.hash }); + if (isSameDirEntry(dest, canonPath, caseInsensitive)) { + results.push({ harness: h, status: "native", path: dest, hash: scanned.meta.hash }); + continue; + } + if (isManagedCanonicalLink(dest, existingSym, canonPath, caseInsensitive, win32)) { + results.push({ harness: h, status: "linked", path: dest, target: existingSym!, hash: scanned.meta.hash }); continue; } if (existsSync(dest) || existingSym) { - const isManagedCopy = !!rec.managedCopies?.[h]; - if (!isManagedCopy && !opts?.force) { - throw new Error(`refusing to overwrite unmanaged skill at ${dest} (pass force to replace)`); - } removeProjection(dest); } @@ -363,27 +546,35 @@ export function unlinkSkill( opts?: SkillsEnv & { force?: boolean }, ): SkillHarnessId[] { if (!isValidSlug(slug)) throw new Error(`invalid skill slug "${slug}"`); + assertAllowedHarnessSlug(slug, harnesses, opts); const state = readSkillsState(opts); const canonPath = path.join(canonicalSkillsDir(opts), slug); - const canonReal = safeRealpath(canonPath); + const caseInsensitive = isCaseInsensitivePlatform(opts); + const win32 = (opts?.platform ?? process.platform) === "win32"; const targetMap = new Map(harnessTargets(opts).map((t) => [t.id, t])); const rec = state.skills[slug]; - const removed: SkillHarnessId[] = []; + const toRemove: { harness: SkillHarnessId; dest: string }[] = []; for (const h of harnesses) { const target = targetMap.get(h)!; const dest = path.join(target.skillsDir, slug); const sym = readSymlinkTarget(dest); if (!existsSync(dest) && !sym) continue; + if (isSameDirEntry(dest, canonPath, caseInsensitive)) continue; - const isManagedLink = !!sym && !!canonReal && safeRealpath(dest) === canonReal; - const isManagedCopy = !!rec?.managedCopies?.[h]; + const isManagedLink = isManagedCanonicalLink(dest, sym, canonPath, caseInsensitive, win32); + const isManagedCopy = isUnmodifiedManagedCopy(dest, slug, rec?.managedCopies?.[h], sym); if (!isManagedLink && !isManagedCopy && !opts?.force) { throw new Error(`refusing to remove unmanaged skill at ${dest} (pass force to remove)`); } - removeProjection(dest); - if (rec?.managedCopies) delete rec.managedCopies[h]; - removed.push(h); + toRemove.push({ harness: h, dest }); + } + + const removed: SkillHarnessId[] = []; + for (const item of toRemove) { + removeProjection(item.dest); + if (rec?.managedCopies) delete rec.managedCopies[item.harness]; + removed.push(item.harness); } writeSkillsState(state, opts); @@ -395,73 +586,67 @@ export interface InstallOptions extends SkillsEnv { harnesses?: readonly SkillHarnessId[]; linkOnly?: boolean; overwrite?: boolean; + forceHarnesses?: boolean; collectionId?: string; linkDeps?: LinkDeps; } -function writeValidatedFiles( - files: readonly { path: string; bytes: Uint8Array; executable: boolean }[], - dest: string, -): void { - const parent = path.dirname(dest); - mkdirSync(parent, { recursive: true }); - const stage = `${dest}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2, 8)}`; - mkdirSync(stage, { recursive: true }); - for (const f of files) { - const target = path.join(stage, ...f.path.split("/")); - mkdirSync(path.dirname(target), { recursive: true }); - writeFileSync(target, f.bytes); - if (f.executable) chmodSync(target, 0o755); - } - rmSync(dest, { recursive: true, force: true }); - renameSync(stage, dest); -} - -const UNSAFE_PROBLEM_RE = /^(?:symlink |broken symlink|unsafe file path|unsupported file type|exceeds |file )/; - -function hasUnsafeScanProblem(problems: readonly string[]): boolean { - return problems.some((p) => UNSAFE_PROBLEM_RE.test(p)); -} - /** Install a skill from a local folder into ~/.agents/skills/ and link to harnesses. */ export function installSkillFromDir(sourceDir: string, opts?: InstallOptions): DiscoveredSkill { - const absSource = path.resolve(sourceDir); - const slug = opts?.slug ?? path.basename(absSource); + const platform = opts?.platform ?? process.platform; + const win32 = platform === "win32"; + const caseInsensitive = isCaseInsensitivePlatform(opts); + const rawSource = path.isAbsolute(sourceDir) ? sourceDir : `${process.cwd()}${path.sep}${sourceDir}`; + const hasDotDot = splitRawSegments(rawSource, win32).includes(".."); + const linkTarget = hasDotDot ? (safeRealpath(rawSource) ?? path.resolve(sourceDir)) : path.resolve(sourceDir); + const slug = opts?.slug ?? path.basename(linkTarget); if (!isValidSlug(slug)) throw new Error(`invalid skill slug "${slug}"`); - const scanned = readSkillDir(absSource, slug); - if (!scanned.meta || hasUnsafeScanProblem(scanned.problems)) { - throw new Error(`invalid skill at ${absSource}: ${scanned.problems.join("; ")}`); - } - const canonRoot = canonicalSkillsDir(opts); const dest = path.join(canonRoot, slug); - mkdirSync(canonRoot, { recursive: true }); + if ( + opts?.linkOnly && + (walkPathToTarget(rawSource, dest, caseInsensitive, "traverse", 40, win32) || + walkPathToTarget(linkTarget, dest, caseInsensitive, "traverse", 40, win32)) + ) { + throw new Error(`cannot symlink skill "${slug}" to itself (${dest})`); + } - const destExists = existsSync(dest) || readSymlinkTarget(dest) !== null; + const scanned = readSkillDir(linkTarget, slug); + if (!scanned.meta || hasUnsafeScanProblem(scanned.problems)) { + throw new Error(`invalid skill at ${linkTarget}: ${scanned.problems.join("; ")}`); + } + + const destSym = readSymlinkTarget(dest); + const destExists = existsSync(dest) || destSym !== null; if (destExists && !opts?.overwrite) { throw new Error(`skill "${slug}" already exists in ${canonRoot} (pass overwrite to replace)`); } - const platform = opts?.platform ?? process.platform; + const harnesses = opts?.harnesses ?? detectedHarnesses(opts); + assertAllowedHarnessSlug(slug, harnesses, opts); + const state = readSkillsState(opts); + const forceHarnesses = opts?.forceHarnesses ?? !!opts?.overwrite; + if (!forceHarnesses && harnesses.length > 0) { + assertNoUnmanagedHarnessConflicts(slug, harnesses, state, opts); + } + + mkdirSync(canonRoot, { recursive: true }); if (opts?.linkOnly) { - if (destExists) rmSync(dest, { recursive: true, force: true }); - symlinkSync(absSource, dest, platform === "win32" ? "junction" : "dir"); + replacePathAtomic(dest, () => symlinkSync(linkTarget, dest, platform === "win32" ? "junction" : "dir")); } else { - writeValidatedFiles(scanned.files, dest); + writeSkillFilesAtomic(scanned.files, dest); } - const state = readSkillsState(opts); ensureManagedRecord(state, slug, opts?.linkOnly ? "symlink" : "managed", scanned.meta.hash, { - ...(opts?.linkOnly ? { linkedTarget: absSource } : {}), + ...(opts?.linkOnly ? { linkedTarget: linkTarget } : {}), ...(opts?.collectionId ? { collectionId: opts.collectionId } : {}), }); if (opts?.collectionId) attachToCollection(state, opts.collectionId, slug); writeSkillsState(state, opts); - const harnesses = opts?.harnesses ?? detectedHarnesses(opts); if (harnesses.length > 0) { - linkSkill(slug, harnesses, { ...opts, force: !!opts?.overwrite }); + linkSkill(slug, harnesses, { ...opts, force: forceHarnesses }); } return discoverSkills(opts).find((s) => s.slug === slug)!; } @@ -488,15 +673,20 @@ export function installSkillBundle( throw new Error(`skill "${slug}" already exists in ${canonRoot} (pass overwrite to replace)`); } - const unpacked = extractSkillBundle(bundleBytes, dest, opts?.expectedHash); + const harnesses = opts?.harnesses ?? detectedHarnesses(opts); + assertAllowedHarnessSlug(slug, harnesses, opts); const state = readSkillsState(opts); + if (!opts?.overwrite && harnesses.length > 0) { + assertNoUnmanagedHarnessConflicts(slug, harnesses, state, opts); + } + + const unpacked = extractSkillBundle(bundleBytes, dest, opts?.expectedHash); ensureManagedRecord(state, slug, "managed", unpacked.hash, { ...(opts?.collectionId ? { collectionId: opts.collectionId } : {}), }); if (opts?.collectionId) attachToCollection(state, opts.collectionId, slug); writeSkillsState(state, opts); - const harnesses = opts?.harnesses ?? detectedHarnesses(opts); if (harnesses.length > 0) { linkSkill(slug, harnesses, { ...opts, force: !!opts?.overwrite }); } @@ -524,6 +714,7 @@ export function adoptSkill(slug: string, opts?: AdoptOptions): DiscoveredSkill { let foundPath: string | null = null; let foundHarness: SkillHarnessId | null = null; for (const t of candidates) { + if (isClaudeSyncedTarget(slug, t.skillsDir, opts)) continue; const p = path.join(t.skillsDir, slug); if (existsSync(p) && readSkillDir(p, slug).meta) { foundPath = p; @@ -535,6 +726,9 @@ export function adoptSkill(slug: string, opts?: AdoptOptions): DiscoveredSkill { throw new Error(`skill "${slug}" not found in any searched harness directory`); } + const linkTargets = opts?.harnesses ?? [...new Set([...detectedHarnesses(opts), foundHarness])]; + assertAllowedHarnessSlug(slug, linkTargets, opts); + const symTarget = readSymlinkTarget(foundPath); const canonRoot = canonicalSkillsDir(opts); const canonPath = path.join(canonRoot, slug); @@ -562,13 +756,12 @@ export function adoptSkill(slug: string, opts?: AdoptOptions): DiscoveredSkill { } const platform = opts?.platform ?? process.platform; if (symTarget) { - rmSync(canonPath, { recursive: true, force: true }); - symlinkSync(symTarget, canonPath, platform === "win32" ? "junction" : "dir"); + replacePathAtomic(canonPath, () => symlinkSync(symTarget, canonPath, platform === "win32" ? "junction" : "dir")); rmSync(foundPath, { recursive: true, force: true }); recordSource = "symlink"; recordTarget = symTarget; } else { - writeValidatedFiles(scanned.files, canonPath); + writeSkillFilesAtomic(scanned.files, canonPath); rmSync(foundPath, { recursive: true, force: true }); recordSource = "managed"; } @@ -582,7 +775,6 @@ export function adoptSkill(slug: string, opts?: AdoptOptions): DiscoveredSkill { if (opts?.collectionId) attachToCollection(state, opts.collectionId, slug); writeSkillsState(state, opts); - const linkTargets = opts?.harnesses ?? [...new Set([...detectedHarnesses(opts), foundHarness])]; for (const h of linkTargets) { if (h === foundHarness || opts?.force) { linkSkill(slug, [h], { ...opts, force: true }); @@ -602,17 +794,24 @@ export function removeSkill( opts?: SkillsEnv & { removeCanonical?: boolean; force?: boolean }, ): { unlinked: SkillHarnessId[]; removedCanonical: boolean } { if (!isValidSlug(slug)) throw new Error(`invalid skill slug "${slug}"`); - const allHarnesses = harnessTargets(opts).map((t) => t.id); - const unlinked = unlinkSkill(slug, allHarnesses, opts); - - let removedCanonical = false; const canonPath = path.join(canonicalSkillsDir(opts), slug); - if (opts?.removeCanonical && (existsSync(canonPath) || readSymlinkTarget(canonPath) !== null)) { + const canonExists = existsSync(canonPath) || readSymlinkTarget(canonPath) !== null; + if (opts?.removeCanonical && canonExists) { const state = readSkillsState(opts); const isManaged = !!state.skills[slug] || lstatSync(canonPath).isSymbolicLink(); if (!isManaged && !opts.force) { throw new Error(`refusing to remove unmanaged canonical skill at ${canonPath} (pass force to remove)`); } + } + + const allHarnesses = harnessTargets(opts) + .filter((t) => !isClaudeSyncedTarget(slug, t.skillsDir, opts)) + .map((t) => t.id); + const unlinked = unlinkSkill(slug, allHarnesses, opts); + + let removedCanonical = false; + if (opts?.removeCanonical && canonExists) { + const state = readSkillsState(opts); rmSync(canonPath, { recursive: true, force: true }); delete state.skills[slug]; for (const col of state.collections) { diff --git a/packages/skills/test/archive.test.ts b/packages/skills/test/archive.test.ts index 0e2763f7..35444583 100644 --- a/packages/skills/test/archive.test.ts +++ b/packages/skills/test/archive.test.ts @@ -1,10 +1,26 @@ // SPDX-License-Identifier: Apache-2.0 -import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from "node:fs"; import os from "node:os"; import path from "node:path"; import { gzipSync } from "node:zlib"; import { afterEach, describe, expect, it } from "vitest"; -import { extractSkillBundle, packSkillDir, packSkillFiles, unpackSkillBundle } from "../src/archive.js"; +import { + extractSkillBundle, + packSkillDir, + packSkillFiles, + replacePathAtomic, + unpackSkillBundle, +} from "../src/archive.js"; import { SKILL_LIMITS } from "../src/types.js"; const tmps: string[] = []; @@ -197,4 +213,87 @@ describe("archive pack and unpack", () => { expect(() => extractSkillBundle(badNest, dest)).toThrow(); expect(existsSync(dest)).toBe(false); }); + + it("splits multi-segment ustar paths beyond 155-byte directory prefixes and rejects case collisions and ignored dirs", () => { + const skill = Buffer.from("---\nname: a\ndescription: b\n---\n"); + // Total path 179 bytes: last slash prefix is 172 (>155), but earlier slash fits prefix=91, name=87 + const deepPath = `references/${"a".repeat(80)}/${"b".repeat(80)}/doc.md`; + const packed = packSkillFiles([ + { path: "SKILL.md", bytes: skill }, + { path: deepPath, bytes: Buffer.from("deep") }, + ]); + const unpacked = unpackSkillBundle(packed); + expect(unpacked.files.map((f) => f.path)).toEqual([deepPath, "SKILL.md"]); + + // Case-insensitive & Unicode NFC/NFD duplicate paths (would clobber on macOS/Windows) rejected + const caseDup = packSkillFiles([ + { path: "SKILL.md", bytes: skill }, + { path: "skill.md", bytes: Buffer.from("---\nname: evil\ndescription: overwrite\n---\n") }, + ]); + expect(() => unpackSkillBundle(caseDup)).toThrow("duplicate archive path"); + const unicodeDup = packSkillFiles([ + { path: "SKILL.md", bytes: skill }, + { path: "references/caf\u00e9.md", bytes: Buffer.from("nfc") }, + { path: "references/cafe\u0301.md", bytes: Buffer.from("nfd") }, + ]); + expect(() => unpackSkillBundle(unicodeDup)).toThrow("duplicate archive path"); + + // Ignored segments (.git, .GIT, node_modules, NODE_MODULES) rejected case-insensitively + const smuggledGit = packSkillFiles([ + { path: "SKILL.md", bytes: skill }, + { path: "references/.GIT/config", bytes: Buffer.from("[core]\n") }, + ]); + expect(() => unpackSkillBundle(smuggledGit)).toThrow("unsafe archive path"); + const smuggledMods = packSkillFiles([ + { path: "SKILL.md", bytes: skill }, + { path: "assets/NODE_MODULES/x.js", bytes: Buffer.from("x") }, + ]); + expect(() => unpackSkillBundle(smuggledMods)).toThrow("unsafe archive path"); + }); + + it("restores the previous directory atomically if replacePathAtomic fails mid-replacement", () => { + const root = makeTmp(); + const target = path.join(root, "existing-skill"); + mkdirSync(target, { recursive: true }); + writeFileSync(path.join(target, "SKILL.md"), "original-content"); + + expect(() => + replacePathAtomic(target, () => { + throw new Error("simulated rename failure"); + }), + ).toThrow("simulated rename failure"); + expect(readFileSync(path.join(target, "SKILL.md"), "utf8")).toBe("original-content"); + + // Also covers error when no prior target existed + const fresh = path.join(root, "fresh-skill"); + expect(() => + replacePathAtomic(fresh, () => { + throw new Error("fresh failure"); + }), + ).toThrow("fresh failure"); + expect(existsSync(fresh)).toBe(false); + + // Best-effort backup cleanup failure does NOT fail the already-published replacement + const nextDir = path.join(root, "next-skill"); + mkdirSync(nextDir, { recursive: true }); + writeFileSync(path.join(nextDir, "SKILL.md"), "new-content"); + replacePathAtomic( + target, + () => { + mkdirSync(target, { recursive: true }); + writeFileSync(path.join(target, "SKILL.md"), "published"); + }, + () => { + throw new Error("EPERM"); + }, + ); + expect(readFileSync(path.join(target, "SKILL.md"), "utf8")).toBe("published"); + + // packSkillDir refuses directories with unsafe scan problems (e.g. symlink cycle) + const cycleDir = path.join(root, "cycle-pack"); + mkdirSync(cycleDir, { recursive: true }); + writeFileSync(path.join(cycleDir, "SKILL.md"), "---\nname: cycle-pack\ndescription: Bad\n---\n"); + symlinkSync(cycleDir, path.join(cycleDir, "loop"), process.platform === "win32" ? "junction" : "dir"); + expect(() => packSkillDir(cycleDir)).toThrow("cannot pack skill"); + }); }); diff --git a/packages/skills/test/cli.test.ts b/packages/skills/test/cli.test.ts index ace161e3..2bfe1d0c 100644 --- a/packages/skills/test/cli.test.ts +++ b/packages/skills/test/cli.test.ts @@ -195,6 +195,23 @@ describe("skillsMain CLI", () => { expect(JSON.parse(runCli(["collections", "sync", "--overwrite", "--json"], opts).join("\n")).synced).toHaveLength( 3, ); + + // Local non-bare multi-skill git repo, trailing-slash bare repo (case-insensitive .GIT), and --ref/--subpath flags + const upperBare = `${makeTmp("sp-skills-upper-")}.GIT`; + tmps.push(upperBare); + execFileSync("git", ["clone", "--bare", repo, upperBare], { stdio: "ignore" }); + expect(runCli(["add", repo, "--collection", "local-git", "--overwrite"], opts)[0]).toContain( + 'Synced 1 skill(s) into collection "local-git"', + ); + expect(runCli(["add", `${upperBare}/`, "--collection", "bare-slash", "--overwrite"], opts)[0]).toContain( + 'Synced 1 skill(s) into collection "bare-slash"', + ); + expect( + runCli( + ["add", repo, "--ref", "main", "--subpath", "pack", "--collection", "local-flags", "--overwrite"], + opts, + )[0], + ).toContain('Synced 1 skill(s) into collection "local-flags"'); }); it("reports usage and validation errors cleanly", () => { diff --git a/packages/skills/test/format.test.ts b/packages/skills/test/format.test.ts index 9a136f1b..c875d772 100644 --- a/packages/skills/test/format.test.ts +++ b/packages/skills/test/format.test.ts @@ -34,6 +34,8 @@ describe("slug and path validation", () => { expect(isValidSlug("-bad")).toBe(false); expect(isValidSlug("BadCase")).toBe(false); expect(isValidSlug("a..b")).toBe(false); + expect(isValidSlug("node_modules")).toBe(false); + expect(isValidSlug("__macosx")).toBe(false); }); it("validates safe relative POSIX paths", () => { @@ -48,6 +50,8 @@ describe("slug and path validation", () => { expect(isSafeRelPath("a//b")).toBe(false); expect(isSafeRelPath("a\x00b")).toBe(false); expect(isSafeRelPath("a\x7fb")).toBe(false); + expect(isSafeRelPath("SKILL.md:hidden")).toBe(false); + expect(isSafeRelPath("dir/file:$DATA")).toBe(false); expect(isSafeRelPath("a".repeat(SKILL_LIMITS.pathBytes + 1))).toBe(false); }); }); @@ -94,10 +98,15 @@ describe("parseFrontmatter", () => { expect(parseFrontmatter("---\nname: x\n").problems).toEqual(["SKILL.md frontmatter is not closed with ---"]); }); - it("handles literal block reaching the closing fence", () => { + it("handles literal block reaching the closing fence and rejects invalid/indented keys in linear time", () => { const parsed = parseFrontmatter("---\nname: x\ndescription: |-\n hello\n---\nbody"); expect(parsed.fields.description).toBe("hello"); expect(parsed.problems).toEqual([]); + + const badKeys = parseFrontmatter( + `---\nname: ok\ndescription: ok\n indented: val\nbad key: val\n${"a".repeat(20_000)} ${" ".repeat(20_000)}\n---\n`, + ); + expect(badKeys.problems).toHaveLength(3); }); }); @@ -213,9 +222,11 @@ describe("hashSkillFiles and readSkillDir", () => { } writeFileSync(path.join(cur, "deep.txt"), "x"); - // Non-regular file (FIFO on POSIX) + // Non-regular file (FIFO on POSIX) — both direct and behind a symlink must not hang readFileSync if (process.platform !== "win32") { - execFileSync("mkfifo", [path.join(skillDir, "pipe")]); + const pipePath = path.join(skillDir, "pipe"); + execFileSync("mkfifo", [pipePath]); + symlinkSync(pipePath, path.join(skillDir, "pipe-link")); } const res = readSkillDir(skillDir); @@ -223,7 +234,8 @@ describe("hashSkillFiles and readSkillDir", () => { expect(res.problems.some((p) => p.includes("broken symlink"))).toBe(true); expect(res.problems.some((p) => p.includes("unsafe file path"))).toBe(true); if (process.platform !== "win32") { - expect(res.problems.some((p) => p.includes("unsupported file type"))).toBe(true); + expect(res.problems).toContain('unsupported file type "pipe"'); + expect(res.problems).toContain('unsupported file type "pipe-link"'); } }, ); @@ -248,9 +260,81 @@ describe("hashSkillFiles and readSkillDir", () => { mkdirSync(bigTotalDir); writeFileSync(path.join(bigTotalDir, "SKILL.md"), "---\nname: big-total\ndescription: ok\n---\n"); const chunk = Buffer.alloc(SKILL_LIMITS.fileBytes); - for (let i = 0; i < 6; i++) writeFileSync(path.join(bigTotalDir, `part-${i}.bin`), chunk); - expect(readSkillDir(bigTotalDir).problems.some((p) => p.includes(`${SKILL_LIMITS.bundleBytes} bytes total`))).toBe( - true, - ); + for (let i = 0; i < 6; i++) writeFileSync(path.join(bigTotalDir, `z-${i}.bin`), chunk); + const bigRes = readSkillDir(bigTotalDir); + expect(bigRes.problems.some((p) => p.includes(`${SKILL_LIMITS.bundleBytes} bytes total`))).toBe(true); + expect(bigRes.meta).not.toBeNull(); + expect(bigRes.meta!.totalBytes).toBeLessThanOrEqual(SKILL_LIMITS.bundleBytes); }); + + it("detects directory symlink cycles without hanging or duplicating files", () => { + const root = makeTmp(); + const skillDir = path.join(root, "cycle-skill"); + mkdirSync(path.join(skillDir, "sub"), { recursive: true }); + writeFileSync(path.join(skillDir, "SKILL.md"), "---\nname: cycle-skill\ndescription: Cycle test\n---\n"); + writeFileSync(path.join(skillDir, "sub", "a.txt"), "hello"); + const linkType = process.platform === "win32" ? "junction" : "dir"; + // Two root-pointing cycles would cause exponential recursion without cycle detection + symlinkSync(skillDir, path.join(skillDir, "loop-a"), linkType); + symlinkSync(skillDir, path.join(skillDir, "loop-b"), linkType); + symlinkSync(skillDir, path.join(skillDir, "sub", "up"), linkType); + + const res = readSkillDir(skillDir); + expect(res.problems).toContain('symlink cycle "loop-a"'); + expect(res.problems).toContain('symlink cycle "loop-b"'); + expect(res.problems).toContain('symlink cycle "sub/up"'); + expect(res.files.map((f) => f.path)).toEqual(["SKILL.md", "sub/a.txt"]); + + // Case-variant symlink cycle on case-insensitive FS (macOS/Windows) still caught via realpathSync.native + if (process.platform === "darwin" || process.platform === "win32") { + const caseDir = path.join(root, "case-cycle"); + mkdirSync(path.join(caseDir, "sub"), { recursive: true }); + writeFileSync(path.join(caseDir, "SKILL.md"), "---\nname: case-cycle\ndescription: Case cycle\n---\n"); + symlinkSync(path.join(caseDir, "SUB"), path.join(caseDir, "sub", "loop"), linkType); + expect(readSkillDir(caseDir).problems).toContain('symlink cycle "sub/loop"'); + } + + // Exponential symlink diamond DAG (2^11 = 2048 visits > MAX_WALK_DIRS) terminates quickly and flags limit + const dagDir = path.join(root, "dag-skill"); + mkdirSync(dagDir, { recursive: true }); + writeFileSync(path.join(dagDir, "SKILL.md"), "---\nname: dag-skill\ndescription: DAG\n---\n"); + for (let i = 0; i <= 11; i++) mkdirSync(path.join(dagDir, `d${i}`), { recursive: true }); + for (let i = 0; i < 11; i++) { + symlinkSync(path.join(dagDir, `d${i + 1}`), path.join(dagDir, `d${i}`, "a"), linkType); + symlinkSync(path.join(dagDir, `d${i + 1}`), path.join(dagDir, `d${i}`, "b"), linkType); + } + const dagRes = readSkillDir(dagDir); + expect(dagRes.problems.some((p) => p.includes("exceeds maximum directory count"))).toBe(true); + }); + + it.runIf(process.platform !== "win32" && process.getuid?.() !== 0)( + "records unreadable directories and files as problems instead of throwing", + () => { + const root = makeTmp(); + const skillDir = path.join(root, "perm-skill"); + const lockedSub = path.join(skillDir, "locked-sub"); + const lockedFile = path.join(skillDir, "secret.txt"); + const lockedRoot = path.join(root, "locked-root"); + mkdirSync(lockedSub, { recursive: true }); + mkdirSync(lockedRoot, { recursive: true }); + writeFileSync(path.join(skillDir, "SKILL.md"), "---\nname: perm-skill\ndescription: ok\n---\n"); + writeFileSync(lockedFile, "nope"); + + chmodSync(lockedSub, 0o000); + chmodSync(lockedFile, 0o000); + chmodSync(lockedRoot, 0o000); + try { + const res = readSkillDir(skillDir); + expect(res.problems).toContain('unreadable directory "locked-sub"'); + expect(res.problems).toContain('unreadable file "secret.txt"'); + + const rootRes = readSkillDir(lockedRoot); + expect(rootRes.problems).toContain('unreadable directory "."'); + } finally { + chmodSync(lockedSub, 0o755); + chmodSync(lockedFile, 0o644); + chmodSync(lockedRoot, 0o755); + } + }, + ); }); diff --git a/packages/skills/test/git.test.ts b/packages/skills/test/git.test.ts index 2929c63a..2c31a0d6 100644 --- a/packages/skills/test/git.test.ts +++ b/packages/skills/test/git.test.ts @@ -1,11 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 import { execFileSync } from "node:child_process"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { deriveCollectionId, normalizeGitRepo, syncGitCollection } from "../src/git.js"; -import { listCollections, upsertCollection } from "../src/store.js"; +import { readSymlinkTarget } from "../src/harnesses.js"; +import { installSkillFromDir, listCollections, upsertCollection } from "../src/store.js"; const tmps: string[] = []; function makeTmp(prefix = "sp-skills-git-"): string { @@ -49,9 +50,11 @@ describe("git repo normalization and collection id derivation", () => { it("derives valid collection ids with fallback", () => { expect(deriveCollectionId("https://github.com/acme/my-skills.git")).toBe("my-skills"); + expect(deriveCollectionId("https://github.com/acme/my-skills.git/")).toBe("my-skills"); expect(deriveCollectionId("https://github.com/acme/my-skills///")).toBe("my-skills"); expect(deriveCollectionId("https://github.com/acme/---my-skills---")).toBe("my-skills"); expect(deriveCollectionId("git@github.com:acme/repo.git", "packs/design")).toBe("repo-design"); + expect(deriveCollectionId("C:\\Users\\dev\\my-repo.git\\", "packs\\design\\")).toBe("my-repo-design"); expect(deriveCollectionId("///")).toBe("git-skills"); }); }); @@ -155,6 +158,8 @@ describe("syncGitCollection", () => { expect(() => syncGitCollection(conflictRepo, { home, env: {}, collectionId: "other-col", harnesses: [] })).toThrow( "already exists", ); + // Failed sync must NOT leave a ghost collection in skills.json + expect(listCollections({ home, env: {} }).some((c) => c.id === "other-col")).toBe(false); const forced = syncGitCollection(conflictRepo, { home, env: {}, @@ -184,5 +189,215 @@ describe("syncGitCollection", () => { writeFileSync(path.join(empty, "broken-sub", "SKILL.md", "keep.txt"), "not a skill file\n"); initGitRepo(empty, "main"); expect(() => syncGitCollection(empty, { home, env: {} })).toThrow("no valid SKILL.md folders found"); + + // Regular file as subpath rejected cleanly + expect(() => syncGitCollection(single, { home, env: {}, subpath: "SKILL.md" })).toThrow("not found in repository"); + + // Symlink escape via subpath inside cloned repo is rejected + const outsideSkill = makeTmp("sp-skills-outside-"); + writeFileSync(path.join(outsideSkill, "SKILL.md"), "---\nname: stolen\ndescription: Outside\n---\n"); + const linkType = process.platform === "win32" ? "junction" : "dir"; + expect(() => + syncGitCollection("https://example.com/evil.git", { + home, + env: {}, + subpath: "escape-link", + git: { + run: (args) => { + if (args[0] === "clone") { + const dest = args[args.length - 1]!; + symlinkSync(outsideSkill, path.join(dest, "escape-link"), linkType); + return ""; + } + return "a".repeat(40); + }, + }, + }), + ).toThrow("not found in repository"); + + // Prefix-collision sibling directory (${tmp}-evil) reached via symlink is rejected + let siblingDir = ""; + try { + expect(() => + syncGitCollection("https://example.com/prefix.git", { + home, + env: {}, + subpath: "sibling-link", + git: { + run: (args) => { + if (args[0] === "clone") { + const dest = args[args.length - 1]!; + siblingDir = `${dest}-evil`; + mkdirSync(siblingDir, { recursive: true }); + writeFileSync(path.join(siblingDir, "SKILL.md"), "---\nname: evil\ndescription: Sibling\n---\n"); + symlinkSync(siblingDir, path.join(dest, "sibling-link"), linkType); + return ""; + } + return "b".repeat(40); + }, + }, + }), + ).toThrow("not found in repository"); + } finally { + if (siblingDir) rmSync(siblingDir, { recursive: true, force: true }); + } + + // Full pre-flight validation: duplicate slugs, unsafe skill, and harness conflict fail BEFORE any skill is installed + const preflightHome = makeTmp("sp-skills-pf-"); + mkdirSync(path.join(preflightHome, ".claude", "skills"), { recursive: true }); + const fakeSync = (setup: (dest: string) => void, opts?: Parameters[1]) => + syncGitCollection("https://example.com/multi.git", { + home: preflightHome, + env: {}, + ...opts, + git: { + run: (args) => { + if (args[0] === "clone") { + setup(args[args.length - 1]!); + return ""; + } + return "c".repeat(40); + }, + }, + }); + + // Duplicate slugs in one repo + expect(() => + fakeSync((dest) => { + for (const sub of ["a", "b"]) { + mkdirSync(path.join(dest, sub, "dup"), { recursive: true }); + writeFileSync(path.join(dest, sub, "dup", "SKILL.md"), "---\nname: dup\ndescription: Dup\n---\n"); + } + }), + ).toThrow('duplicate skill slug "dup"'); + expect(existsSync(path.join(preflightHome, ".agents", "skills", "dup"))).toBe(false); + + // Unsafe scan problem (symlink cycle) on second skill aborts BEFORE first skill is installed + expect(() => + fakeSync((dest) => { + mkdirSync(path.join(dest, "aaa-clean"), { recursive: true }); + writeFileSync(path.join(dest, "aaa-clean", "SKILL.md"), "---\nname: aaa-clean\ndescription: Clean\n---\n"); + mkdirSync(path.join(dest, "zzz-cycle"), { recursive: true }); + writeFileSync(path.join(dest, "zzz-cycle", "SKILL.md"), "---\nname: zzz-cycle\ndescription: Bad\n---\n"); + symlinkSync(path.join(dest, "zzz-cycle"), path.join(dest, "zzz-cycle", "loop"), linkType); + }), + ).toThrow("symlink cycle"); + expect(existsSync(path.join(preflightHome, ".agents", "skills", "aaa-clean"))).toBe(false); + + // Unmanaged harness conflict on second skill aborts BEFORE first skill is installed + mkdirSync(path.join(preflightHome, ".claude", "skills", "zzz-conflict"), { recursive: true }); + writeFileSync( + path.join(preflightHome, ".claude", "skills", "zzz-conflict", "SKILL.md"), + "---\nname: zzz-conflict\ndescription: Local\n---\n", + ); + expect(() => + fakeSync( + (dest) => { + mkdirSync(path.join(dest, "aaa-clean"), { recursive: true }); + writeFileSync(path.join(dest, "aaa-clean", "SKILL.md"), "---\nname: aaa-clean\ndescription: Clean\n---\n"); + mkdirSync(path.join(dest, "zzz-conflict"), { recursive: true }); + writeFileSync( + path.join(dest, "zzz-conflict", "SKILL.md"), + "---\nname: zzz-conflict\ndescription: Remote\n---\n", + ); + }, + { harnesses: ["claude-code"] }, + ), + ).toThrow("refusing to overwrite unmanaged skill"); + expect(existsSync(path.join(preflightHome, ".agents", "skills", "aaa-clean"))).toBe(false); + + // Invalid collectionId fails BEFORE cloning or installing any skills + let cloned = false; + expect(() => + syncGitCollection("https://example.com/bad-col.git", { + home: preflightHome, + env: {}, + collectionId: "Bad ID", + git: { + run: () => { + cloned = true; + return ""; + }, + }, + }), + ).toThrow('invalid collection id "Bad ID"'); + expect(cloned).toBe(false); + + // Resyncing an existing collection WITHOUT overwrite: true must NOT clobber user-edited harness copies + const resyncHome = makeTmp("sp-skills-resync-"); + mkdirSync(path.join(resyncHome, ".claude", "skills"), { recursive: true }); + const resyncSync = (desc: string, opts?: Parameters[1]) => + syncGitCollection("https://example.com/resync.git", { + home: resyncHome, + env: {}, + collectionId: "team-resync", + harnesses: ["claude-code"], + linkDeps: { + symlink: () => { + throw new Error("EPERM"); + }, + }, + ...opts, + git: { + run: (args) => { + if (args[0] === "clone") { + const d = args[args.length - 1]!; + mkdirSync(path.join(d, "synced-one"), { recursive: true }); + writeFileSync( + path.join(d, "synced-one", "SKILL.md"), + `---\nname: synced-one\ndescription: ${desc}\n---\n`, + ); + return ""; + } + return "d".repeat(40); + }, + }, + }); + resyncSync("v1"); + // Unedited managed copy resyncs cleanly without overwrite + expect(resyncSync("v2").installed[0]?.description).toBe("v2"); + // User edits the harness copy locally -> resync without overwrite MUST refuse + writeFileSync( + path.join(resyncHome, ".claude", "skills", "synced-one", "SKILL.md"), + "---\nname: synced-one\ndescription: User local edit\n---\n", + ); + expect(() => resyncSync("v3")).toThrow("refusing to overwrite unmanaged skill"); + + // Independent harness symlink -> /ext alongside canonical linkOnly -> /ext must refuse in pre-flight + // WITHOUT replacing canonical or mutating state + const extHome = makeTmp("sp-skills-extlink-"); + const extDir = makeTmp("sp-skills-extsrc-"); + writeFileSync(path.join(extDir, "SKILL.md"), "---\nname: ext-one\ndescription: Ext\n---\n"); + mkdirSync(path.join(extHome, ".claude", "skills"), { recursive: true }); + installSkillFromDir(extDir, { + home: extHome, + env: {}, + slug: "ext-one", + collectionId: "ext-col", + linkOnly: true, + harnesses: [], + }); + symlinkSync(extDir, path.join(extHome, ".claude", "skills", "ext-one"), linkType); + expect(() => + syncGitCollection("https://example.com/ext.git", { + home: extHome, + env: {}, + collectionId: "ext-col", + harnesses: ["claude-code"], + git: { + run: (args) => { + if (args[0] === "clone") { + const d = args[args.length - 1]!; + mkdirSync(path.join(d, "ext-one"), { recursive: true }); + writeFileSync(path.join(d, "ext-one", "SKILL.md"), "---\nname: ext-one\ndescription: Updated\n---\n"); + return ""; + } + return "e".repeat(40); + }, + }, + }), + ).toThrow("refusing to overwrite unmanaged skill"); + // Canonical symlink must remain untouched! + expect(readSymlinkTarget(path.join(extHome, ".agents", "skills", "ext-one"))).toBe(extDir); }); }); diff --git a/packages/skills/test/store.test.ts b/packages/skills/test/store.test.ts index 6be9cee2..7cb73bdd 100644 --- a/packages/skills/test/store.test.ts +++ b/packages/skills/test/store.test.ts @@ -1,5 +1,14 @@ // SPDX-License-Identifier: Apache-2.0 -import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + rmSync, + symlinkSync, + writeFileSync, +} from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; @@ -18,9 +27,10 @@ import { removeSkill, unlinkSkill, upsertCollection, + walkPathToTarget, writeSkillsState, } from "../src/store.js"; -import type { SkillsEnv } from "../src/types.js"; +import { SKILL_LIMITS, type SkillsEnv } from "../src/types.js"; const tmps: string[] = []; function makeHome(): { home: string; env: SkillsEnv } { @@ -355,4 +365,556 @@ describe("install, discover, link, unlink, adopt, and remove", () => { const adoptedOther = adoptSkill("only-other", { ...env, fromHarness: "claude-code", harnesses: ["cursor"] }); expect(adoptedOther.harnesses).toEqual(["cursor"]); }); + + it("hardens against oversized installs/adopts, self-symlinks, synced files, partial mutations, and dangling links", () => { + const { home, env } = makeHome(); + const dirLinkType = process.platform === "win32" ? "junction" : "dir"; + + // 1. Oversized total skill (> bundleBytes) is refused on both installSkillFromDir AND adoptSkill (no data loss!) + // Use z-prefixed filenames so SKILL.md is scanned first (meta !== null) and UNSAFE_PROBLEM_RE must catch "skill exceeds " + const bigSrc = writeSkill(path.join(home, "src", "too-big"), "too-big", "Too big"); + const chunk = Buffer.alloc(SKILL_LIMITS.fileBytes); + for (let i = 0; i < 6; i++) writeFileSync(path.join(bigSrc, `z${i}.bin`), chunk); + expect(() => installSkillFromDir(bigSrc, { ...env, harnesses: [] })).toThrow("bytes total"); + + const bigClaude = writeSkill(path.join(home, ".claude", "skills", "big-adopt"), "big-adopt", "Too big"); + for (let i = 0; i < 6; i++) writeFileSync(path.join(bigClaude, `z${i}.bin`), chunk); + expect(() => adoptSkill("big-adopt", { ...env, fromHarness: "claude-code", harnesses: [] })).toThrow("bytes total"); + // Original files in harness MUST remain intact! + expect(existsSync(path.join(bigClaude, "z5.bin"))).toBe(true); + rmSync(bigClaude, { recursive: true, force: true }); + + // 2. Self-symlink via linkOnly + overwrite refuses instead of deleting source directory + const canonSelf = writeSkill(path.join(home, ".agents", "skills", "self-skill"), "self-skill", "Self"); + expect(() => installSkillFromDir(canonSelf, { ...env, linkOnly: true, overwrite: true, harnesses: [] })).toThrow( + "cannot symlink skill", + ); + expect(existsSync(path.join(canonSelf, "SKILL.md"))).toBe(true); + + // 3. Regular files inside ~/.claude/skills/synced/ (or synced as a regular file) never crash discoverSkills + mkdirSync(path.join(home, ".claude", "skills", "synced", "bucket1"), { recursive: true }); + writeFileSync(path.join(home, ".claude", "skills", "synced", "manifest.json"), "{}"); + writeSkill(path.join(home, ".claude", "skills", "synced", "bucket1", "ok-sync"), "ok-sync", "Synced"); + expect(discoverSkills(env).some((s) => s.slug === "ok-sync")).toBe(true); + + const fileSyncedHome = makeHome(); + mkdirSync(path.join(fileSyncedHome.home, ".claude", "skills"), { recursive: true }); + writeFileSync(path.join(fileSyncedHome.home, ".claude", "skills", "synced"), "not-a-dir"); + expect(discoverSkills(fileSyncedHome.env)).toEqual([]); + + // 4. Atomic pre-flight conflict checks: unmanaged skill in codex blocks installSkillFromDir & installSkillBundle + // BEFORE writing canonical ~/.agents/skills/ + const srcA = writeSkill(path.join(home, "src", "atomic-dir"), "atomic-dir", "Atomic"); + writeSkill(path.join(home, ".codex", "skills", "atomic-dir"), "atomic-dir", "Unmanaged codex"); + expect(() => installSkillFromDir(srcA, { ...env, harnesses: ["claude-code", "codex"] })).toThrow( + "refusing to overwrite unmanaged skill", + ); + expect(existsSync(path.join(home, ".agents", "skills", "atomic-dir"))).toBe(false); + expect(existsSync(path.join(home, ".claude", "skills", "atomic-dir"))).toBe(false); + + const packedA = packSkillDir(srcA, "atomic-bundle"); + writeSkill(path.join(home, ".codex", "skills", "atomic-bundle"), "atomic-bundle", "Unmanaged codex"); + expect(() => + installSkillBundle("atomic-bundle", packedA.bytes, { ...env, harnesses: ["claude-code", "codex"] }), + ).toThrow("refusing to overwrite unmanaged skill"); + expect(existsSync(path.join(home, ".agents", "skills", "atomic-bundle"))).toBe(false); + + // 5. Atomic linkSkill & unlinkSkill across multiple harnesses (no partial mutation on failure) + const multi = writeSkill(path.join(home, "src", "multi-link"), "multi-link", "Multi"); + installSkillFromDir(multi, { ...env, harnesses: [] }); + writeSkill(path.join(home, ".cursor", "skills", "multi-link"), "multi-link", "Unmanaged cursor"); + expect(() => linkSkill("multi-link", ["claude-code", "cursor"], env)).toThrow( + "refusing to overwrite unmanaged skill", + ); + expect(existsSync(path.join(home, ".claude", "skills", "multi-link"))).toBe(false); + + linkSkill("multi-link", ["claude-code"], env); + expect(() => unlinkSkill("multi-link", ["claude-code", "cursor"], env)).toThrow( + "refusing to remove unmanaged skill", + ); + // claude-code link must NOT have been removed when cursor refused! + expect(existsSync(path.join(home, ".claude", "skills", "multi-link"))).toBe(true); + + // 6. Dangling managed symlink (canonical dir deleted out-of-band) is cleanly unlinked without force + rmSync(path.join(home, ".agents", "skills", "multi-link"), { recursive: true, force: true }); + expect(unlinkSkill("multi-link", ["claude-code"], env)).toEqual(["claude-code"]); + expect(readSymlinkTarget(path.join(home, ".claude", "skills", "multi-link"))).toBeNull(); + + // 7. Managed copy passes pre-flight conflict check on reinstall after canonical removal + const copySrc = writeSkill(path.join(home, "src", "re-copy"), "re-copy", "Copy"); + installSkillFromDir(copySrc, { + ...env, + harnesses: ["claude-code"], + linkDeps: { + symlink: () => { + throw new Error("EPERM"); + }, + }, + }); + rmSync(path.join(home, ".agents", "skills", "re-copy"), { recursive: true, force: true }); + const reCopyPacked = packSkillDir(copySrc, "re-copy"); + const reinstalled = installSkillBundle("re-copy", reCopyPacked.bytes, { ...env, harnesses: ["claude-code"] }); + expect(reinstalled.links.find((l) => l.harness === "claude-code")?.status).toBe("linked"); + + // Verify dangling symlink to unrelated target still refused by unlinkSkill + symlinkSync(path.join(home, "elsewhere"), path.join(home, ".claude", "skills", "other-link"), dirLinkType); + expect(() => unlinkSkill("other-link", ["claude-code"], env)).toThrow("refusing to remove unmanaged skill"); + + // Independent symlink to the same external target as a linkOnly canonical skill is unmanaged (refused without force) + const devTarget = writeSkill(path.join(home, "dev", "shared-target"), "shared-target", "Shared"); + installSkillFromDir(devTarget, { ...env, linkOnly: true, harnesses: [] }); + symlinkSync(devTarget, path.join(home, ".claude", "skills", "shared-target"), dirLinkType); + expect(() => unlinkSkill("shared-target", ["claude-code"], env)).toThrow("refusing to remove unmanaged skill"); + + // Indirect symlink resolving to a REAL canonical directory is recognized as managed + const realCanonSrc = writeSkill(path.join(home, "src", "indirect-real"), "indirect-real", "Indirect"); + installSkillFromDir(realCanonSrc, { ...env, harnesses: [] }); + const midLink = path.join(home, "mid-indirect"); + symlinkSync(path.join(home, ".agents", "skills", "indirect-real"), midLink, dirLinkType); + symlinkSync(midLink, path.join(home, ".claude", "skills", "indirect-real"), dirLinkType); + expect(unlinkSkill("indirect-real", ["claude-code"], env)).toEqual(["claude-code"]); + + // 8. Nested subdir and case-variant self-symlink via linkOnly + overwrite refused without data loss + const nestedSrc = writeSkill(path.join(home, ".agents", "skills", "nested-parent", "inner"), "nested-parent", "In"); + expect(() => + installSkillFromDir(nestedSrc, { + ...env, + slug: "nested-parent", + linkOnly: true, + overwrite: true, + harnesses: [], + }), + ).toThrow("cannot symlink skill"); + expect(existsSync(path.join(nestedSrc, "SKILL.md"))).toBe(true); + if (process.platform === "darwin" || process.platform === "win32") { + expect(() => + installSkillFromDir(path.join(home, ".agents", "skills", "SELF-SKILL"), { + ...env, + slug: "self-skill", + linkOnly: true, + overwrite: true, + harnesses: [], + }), + ).toThrow("cannot symlink skill"); + expect(existsSync(path.join(canonSelf, "SKILL.md"))).toBe(true); + } + + // 9. Canonical skillsDir equal to a harness skillsDir never self-destructs on link/unlink (real, linkOnly, or broken) + const sharedHome = makeHome(); + const sharedDir = path.join(sharedHome.home, ".claude", "skills"); + const sharedEnv: SkillsEnv = { ...sharedHome.env, skillsDir: sharedDir }; + const sharedSrc = writeSkill(path.join(sharedHome.home, "src", "same-dir"), "same-dir", "Same"); + installSkillFromDir(sharedSrc, { ...sharedEnv, harnesses: ["claude-code"] }); + expect(existsSync(path.join(sharedDir, "same-dir", "SKILL.md"))).toBe(true); + expect(discoverSkills(sharedEnv)[0]?.links.find((l) => l.harness === "claude-code")?.status).toBe("native"); + expect(linkSkill("same-dir", ["claude-code"], sharedEnv)[0]?.status).toBe("native"); + expect(unlinkSkill("same-dir", ["claude-code"], { ...sharedEnv, force: true })).toEqual([]); + expect(existsSync(path.join(sharedDir, "same-dir", "SKILL.md"))).toBe(true); + + // Same with linkOnly canonical symlink and symlinked parent alias (plus broken canonical symlink) + const linkSharedSrc = writeSkill(path.join(sharedHome.home, "src", "same-link"), "same-link", "Same link"); + const aliasSkills = path.join(sharedHome.home, "skills-alias"); + symlinkSync(sharedDir, aliasSkills, dirLinkType); + const aliasEnv: SkillsEnv = { ...sharedHome.env, skillsDir: aliasSkills }; + installSkillFromDir(linkSharedSrc, { ...aliasEnv, linkOnly: true, harnesses: ["claude-code"] }); + expect( + discoverSkills(aliasEnv) + .find((s) => s.slug === "same-link") + ?.links.find((l) => l.harness === "claude-code")?.status, + ).toBe("native"); + expect(removeSkill("same-link", { ...aliasEnv, removeCanonical: false, force: true }).unlinked).toEqual([]); + expect(readSymlinkTarget(path.join(sharedDir, "same-link"))).toBe(linkSharedSrc); + + symlinkSync(path.join(sharedHome.home, "gone-target"), path.join(sharedDir, "broken-native"), dirLinkType); + expect(unlinkSkill("broken-native", ["claude-code"], { ...aliasEnv, force: true })).toEqual([]); + expect(removeSkill("broken-native", { ...aliasEnv, removeCanonical: false, force: true }).unlinked).toEqual([]); + expect(readSymlinkTarget(path.join(sharedDir, "broken-native"))).toBe(path.join(sharedHome.home, "gone-target")); + + // 10. Stale managedCopies record after user edits harness copy refuses link/unlink without force; + // dangling canonical symlink passes pre-flight conflict check on reinstall + const editHome = makeHome(); + const editSrc = writeSkill(path.join(editHome.home, "src", "edited-copy"), "edited-copy", "Original"); + installSkillFromDir(editSrc, { + ...editHome.env, + harnesses: ["claude-code"], + linkDeps: { + symlink: () => { + throw new Error("EPERM"); + }, + }, + }); + // User edits the managed copy in claude-code + writeSkill(path.join(editHome.home, ".claude", "skills", "edited-copy"), "edited-copy", "User edited"); + expect(() => linkSkill("edited-copy", ["claude-code"], editHome.env)).toThrow("refusing to overwrite unmanaged"); + expect(() => unlinkSkill("edited-copy", ["claude-code"], editHome.env)).toThrow("refusing to remove unmanaged"); + // Dangling canonical symlink passes conflict check on reinstall + const dangSrc = writeSkill(path.join(editHome.home, "src", "dangling-re"), "dangling-re", "Dangling"); + installSkillFromDir(dangSrc, { ...editHome.env, harnesses: ["claude-code"] }); + rmSync(path.join(editHome.home, ".agents", "skills", "dangling-re"), { recursive: true, force: true }); + expect(installSkillFromDir(dangSrc, { ...editHome.env, harnesses: ["claude-code"] }).slug).toBe("dangling-re"); + + // 11. Reserved slug "synced" refused in claude-code (even with force/overwrite), but removeSkill still works + const syncedSrc = writeSkill(path.join(home, "src", "synced"), "synced", "Reserved"); + expect(() => installSkillFromDir(syncedSrc, { ...env, harnesses: ["claude-code"], overwrite: true })).toThrow( + 'skill slug "synced" is reserved in claude-code', + ); + installSkillFromDir(syncedSrc, { ...env, harnesses: ["codex"] }); + expect(() => linkSkill("synced", ["claude-code"], { ...env, force: true })).toThrow( + 'skill slug "synced" is reserved in claude-code', + ); + expect(() => unlinkSkill("synced", ["claude-code"], { ...env, force: true })).toThrow( + 'skill slug "synced" is reserved in claude-code', + ); + expect(removeSkill("synced", { ...env, removeCanonical: true }).removedCanonical).toBe(true); + + // 12. removeSkill checks canonical permission BEFORE unlinking harnesses + const permHome = makeHome(); + const unmanCanon = writeSkill(path.join(permHome.home, ".agents", "skills", "unman-c"), "unman-c", "Manual"); + mkdirSync(path.join(permHome.home, ".claude", "skills"), { recursive: true }); + symlinkSync(unmanCanon, path.join(permHome.home, ".claude", "skills", "unman-c"), dirLinkType); + expect(() => removeSkill("unman-c", { ...permHome.env, removeCanonical: true })).toThrow( + "refusing to remove unmanaged canonical skill", + ); + // Harness symlink MUST remain intact because canonical check ran first! + expect(readSymlinkTarget(path.join(permHome.home, ".claude", "skills", "unman-c"))).toBe(unmanCanon); + + // 13. writeSkillsState cleans up temp file on rename failure (e.g. stateFile is a directory) + const dirState = path.join(home, "state-as-dir"); + mkdirSync(dirState, { recursive: true }); + expect(() => writeSkillsState({ version: 1, skills: {}, collections: [] }, { stateFile: dirState })).toThrow(); + expect(readdirSync(home).filter((n) => n.startsWith("state-as-dir.tmp-"))).toEqual([]); + + // 14. Unreadable harness directory (chmod 000 on POSIX) never crashes discoverSkills + if (process.platform !== "win32" && process.getuid?.() !== 0) { + const lockedSkills = path.join(permHome.home, ".cursor", "skills"); + mkdirSync(lockedSkills, { recursive: true }); + chmodSync(lockedSkills, 0o000); + try { + expect(discoverSkills(permHome.env).some((s) => s.slug === "unman-c")).toBe(true); + } finally { + chmodSync(lockedSkills, 0o755); + } + + // Unreadable local file inside a managed copy causes isUnmodifiedManagedCopy to refuse without force + const unrdHome = makeHome(); + const unrdSrc = writeSkill(path.join(unrdHome.home, "src", "unrd-copy"), "unrd-copy", "Original"); + installSkillFromDir(unrdSrc, { + ...unrdHome.env, + harnesses: ["claude-code"], + linkDeps: { + symlink: () => { + throw new Error("EPERM"); + }, + }, + }); + const localSecret = path.join(unrdHome.home, ".claude", "skills", "unrd-copy", "local-note.txt"); + writeFileSync(localSecret, "private"); + chmodSync(localSecret, 0o000); + try { + expect(() => unlinkSkill("unrd-copy", ["claude-code"], unrdHome.env)).toThrow("refusing to remove unmanaged"); + } finally { + chmodSync(localSecret, 0o644); + } + } + + // 15. linkOnly rejects paths traversing dest even via symlinked dest or internal alias symlink (and on linux) + const travHome = makeHome(); + const extTarget = writeSkill(path.join(travHome.home, "outside", "real-skill"), "y", "Outside"); + const destY = path.join(travHome.home, ".agents", "skills", "y"); + mkdirSync(destY, { recursive: true }); + symlinkSync(extTarget, path.join(destY, "alias"), dirLinkType); + expect(() => + installSkillFromDir(path.join(destY, "alias"), { + ...travHome.env, + slug: "y", + linkOnly: true, + overwrite: true, + harnesses: [], + platform: "linux", + }), + ).toThrow("cannot symlink skill"); + + const dataDir = path.join(travHome.home, "data", "z"); + const innerSkill = writeSkill(path.join(dataDir, "inner"), "z", "Inner"); + const destZ = path.join(travHome.home, ".agents", "skills", "z"); + symlinkSync(dataDir, destZ, dirLinkType); + expect(() => + installSkillFromDir(path.join(destZ, "inner"), { + ...travHome.env, + slug: "z", + linkOnly: true, + overwrite: true, + harnesses: [], + }), + ).toThrow("cannot symlink skill"); + expect(existsSync(path.join(innerSkill, "SKILL.md"))).toBe(true); + + // External symlink pointing inside non-symlink canonical dest is also refused + const destW = writeSkill(path.join(travHome.home, ".agents", "skills", "w"), "w", "W"); + const wInner = writeSkill(path.join(destW, "sub"), "w", "W sub"); + const extShortcut = path.join(travHome.home, "shortcut-w"); + symlinkSync(wInner, extShortcut, dirLinkType); + expect(() => + installSkillFromDir(extShortcut, { + ...travHome.env, + slug: "w", + linkOnly: true, + overwrite: true, + harnesses: [], + platform: "linux", + }), + ).toThrow("cannot symlink skill"); + + // External symlink traversing dest/alias -> external, symlinked parent + real dest/alias, and symlinked parent + symlink dest + const extChain = path.join(travHome.home, "ext-chain"); + symlinkSync(path.join(destY, "alias"), extChain, dirLinkType); + expect(() => + installSkillFromDir(extChain, { + ...travHome.env, + slug: "y", + linkOnly: true, + overwrite: true, + harnesses: [], + }), + ).toThrow("cannot symlink skill"); + + const skillsParentAlias = path.join(travHome.home, "parent-alias"); + symlinkSync(path.join(travHome.home, ".agents", "skills"), skillsParentAlias, dirLinkType); + expect(() => + installSkillFromDir(path.join(skillsParentAlias, "y", "alias"), { + ...travHome.env, + slug: "y", + linkOnly: true, + overwrite: true, + harnesses: [], + }), + ).toThrow("cannot symlink skill"); + expect(() => + installSkillFromDir(path.join(skillsParentAlias, "z", "inner"), { + ...travHome.env, + slug: "z", + linkOnly: true, + overwrite: true, + harnesses: [], + }), + ).toThrow("cannot symlink skill"); + + // walkPathToTarget fails closed on symlink hop limit (traverse=true, resolve=false) and handles relative paths + const loopA = path.join(travHome.home, "loop-a"); + const loopB = path.join(travHome.home, "loop-b"); + symlinkSync(loopB, loopA, dirLinkType); + symlinkSync(loopA, loopB, dirLinkType); + expect(walkPathToTarget(loopA, destY, false, "traverse", 4)).toBe(true); + expect(walkPathToTarget(loopA, destY, false, "resolve", 4)).toBe(false); + expect(walkPathToTarget(path.relative(process.cwd(), destY), destY, false, "traverse")).toBe(true); + + // Raw `..` traversal: both symlink `ext -> dest/out/../../real` (POSIX raw symlink target) AND direct `dest/../bar` are blocked + const realSkill = writeSkill(path.join(travHome.home, "real-out"), "y", "Real"); + if (process.platform !== "win32") { + const extDotDot = path.join(travHome.home, "ext-dotdot"); + symlinkSync(`${destY}${path.sep}alias${path.sep}..${path.sep}..${path.sep}real-out`, extDotDot, dirLinkType); + expect(() => + installSkillFromDir(extDotDot, { + ...travHome.env, + slug: "y", + linkOnly: true, + overwrite: true, + harnesses: [], + }), + ).toThrow("cannot symlink skill"); + } + const barBesideZ = writeSkill(path.join(travHome.home, "data", "bar"), "z", "Bar"); + expect(existsSync(path.join(barBesideZ, "SKILL.md"))).toBe(true); + expect(() => + installSkillFromDir(`${destZ}${path.sep}..${path.sep}bar`, { + ...travHome.env, + slug: "z", + linkOnly: true, + overwrite: true, + harnesses: [], + }), + ).toThrow("cannot symlink skill"); + expect(existsSync(path.join(realSkill, "SKILL.md"))).toBe(true); + + // Multi-hop managed link `harness -> alias -> canonical -> external` IS managed (discover="linked", unlink succeeds) + const chainHome = makeHome(); + const chainExt = writeSkill(path.join(chainHome.home, "ext-chain-src"), "chain-s", "Chain"); + installSkillFromDir(chainExt, { ...chainHome.env, slug: "chain-s", linkOnly: true, harnesses: [] }); + const midAlias = path.join(chainHome.home, "mid-alias"); + symlinkSync(path.join(chainHome.home, ".agents", "skills", "chain-s"), midAlias, dirLinkType); + mkdirSync(path.join(chainHome.home, ".claude", "skills"), { recursive: true }); + symlinkSync(midAlias, path.join(chainHome.home, ".claude", "skills", "chain-s"), dirLinkType); + expect( + discoverSkills(chainHome.env) + .find((s) => s.slug === "chain-s") + ?.links.find((l) => l.harness === "claude-code")?.status, + ).toBe("linked"); + expect(unlinkSkill("chain-s", ["claude-code"], chainHome.env)).toEqual(["claude-code"]); + + // POSIX symlink-before-`..` tests (Windows NTFS junctions canonicalize targets and Win32 collapses `..` before dereferencing) + if (process.platform !== "win32") { + // Relative symlink `harness -> bridge/../demo` where `bridge -> /elsewhere/sub` lands OUTSIDE canonical -> unmanaged! + const bridgeHome = makeHome(); + const elsewhereSub = path.join(bridgeHome.home, "elsewhere", "sub"); + mkdirSync(elsewhereSub, { recursive: true }); + const outsideDemo = writeSkill(path.join(bridgeHome.home, "elsewhere", "demo"), "demo", "Outside demo"); + const canonDemoSrc = writeSkill(path.join(bridgeHome.home, "src", "demo"), "demo", "Canonical demo"); + installSkillFromDir(canonDemoSrc, { ...bridgeHome.env, harnesses: [] }); + symlinkSync(elsewhereSub, path.join(bridgeHome.home, ".agents", "skills", "bridge"), dirLinkType); + mkdirSync(path.join(bridgeHome.home, ".claude", "skills"), { recursive: true }); + symlinkSync( + `..${path.sep}..${path.sep}.agents${path.sep}skills${path.sep}bridge${path.sep}..${path.sep}demo`, + path.join(bridgeHome.home, ".claude", "skills", "demo"), + dirLinkType, + ); + expect(existsSync(path.join(outsideDemo, "SKILL.md"))).toBe(true); + expect(() => unlinkSkill("demo", ["claude-code"], bridgeHome.env)).toThrow("refusing to remove unmanaged skill"); + + // POSIX literal backslash in symlink target (`.agents/skills\demo`) is a filename char, NOT a separator -> unmanaged + const bsHome = makeHome(); + const bsSrc = writeSkill(path.join(bsHome.home, "src", "demo"), "demo", "Canonical demo"); + installSkillFromDir(bsSrc, { ...bsHome.env, harnesses: [] }); + const bsLiteral = writeSkill(path.join(bsHome.home, ".agents", "skills\\demo"), "demo", "Literal backslash"); + mkdirSync(path.join(bsHome.home, ".claude", "skills"), { recursive: true }); + symlinkSync("../../.agents/skills\\demo", path.join(bsHome.home, ".claude", "skills", "demo"), "dir"); + expect(existsSync(path.join(bsLiteral, "SKILL.md"))).toBe(true); + expect( + discoverSkills(bsHome.env) + .find((s) => s.slug === "demo") + ?.links.find((l) => l.harness === "claude-code")?.status, + ).not.toBe("linked"); + expect(() => unlinkSkill("demo", ["claude-code"], bsHome.env)).toThrow("refusing to remove unmanaged skill"); + + // linkOnly with `..` traversing symlink (`~/.agents/skills/bridge/../foo` where `bridge -> ~/elsewhere/sub`): + // links to the real POSIX-resolved `~/elsewhere/foo` (no ELOOP / no self-destruction), and refuses when resolving to dest + const relLinkHome = makeHome(); + const relElsewhereSub = path.join(relLinkHome.home, "elsewhere", "sub"); + mkdirSync(relElsewhereSub, { recursive: true }); + const relElsewhereFoo = writeSkill(path.join(relLinkHome.home, "elsewhere", "foo"), "foo", "Real elsewhere foo"); + const relCanonFoo = writeSkill(path.join(relLinkHome.home, ".agents", "skills", "foo"), "foo", "Old canon foo"); + expect(existsSync(path.join(relCanonFoo, "SKILL.md"))).toBe(true); + symlinkSync(relElsewhereSub, path.join(relLinkHome.home, ".agents", "skills", "bridge"), dirLinkType); + const linkedDotDot = installSkillFromDir( + `${path.join(relLinkHome.home, ".agents", "skills", "bridge")}${path.sep}..${path.sep}foo`, + { ...relLinkHome.env, slug: "foo", linkOnly: true, overwrite: true, harnesses: [] }, + ); + expect(linkedDotDot.description).toBe("Real elsewhere foo"); + expect(readSymlinkTarget(path.join(relLinkHome.home, ".agents", "skills", "foo"))).toBe( + path.join(path.dirname(linkedDotDot.linkedTarget!), "foo"), + ); + expect(existsSync(path.join(relElsewhereFoo, "SKILL.md"))).toBe(true); + + // When `bridge-self/../bar` resolves to dest itself, or `broken-bridge/../bar` falls back to dest -> refused! + const relCanonBar = writeSkill(path.join(relLinkHome.home, ".agents", "skills", "bar"), "bar", "Canon bar"); + mkdirSync(path.join(relLinkHome.home, ".agents", "skills", "sub-real"), { recursive: true }); + symlinkSync( + path.join(relLinkHome.home, ".agents", "skills", "sub-real"), + path.join(relLinkHome.home, "bridge-self"), + dirLinkType, + ); + expect(() => + installSkillFromDir(`${path.join(relLinkHome.home, "bridge-self")}${path.sep}..${path.sep}bar`, { + ...relLinkHome.env, + slug: "bar", + linkOnly: true, + overwrite: true, + harnesses: [], + }), + ).toThrow("cannot symlink skill"); + symlinkSync( + path.join(relLinkHome.home, "nonexistent-parent", "sub"), + path.join(relLinkHome.home, ".agents", "skills", "broken-bridge"), + dirLinkType, + ); + expect(() => + installSkillFromDir( + `${path.join(relLinkHome.home, ".agents", "skills", "broken-bridge")}${path.sep}..${path.sep}bar`, + { + ...relLinkHome.env, + slug: "bar", + linkOnly: true, + overwrite: true, + harnesses: [], + }, + ), + ).toThrow("cannot symlink skill"); + expect(existsSync(path.join(relCanonBar, "SKILL.md"))).toBe(true); + } + // Relative sourceDir (non-absolute) works cleanly + const relPlainHome = makeHome(); + const relPlain = writeSkill(path.join(relPlainHome.home, "src", "rel-plain"), "rel-plain", "Relative"); + expect( + installSkillFromDir(path.relative(process.cwd(), relPlain), { ...relPlainHome.env, harnesses: [] }).slug, + ).toBe("rel-plain"); + + // Byte-identical managed copy with benign frontmatter warning (missing description) unlinks cleanly without force + const warnHome = makeHome(); + const warnSrc = path.join(warnHome.home, "src", "warn-copy"); + mkdirSync(warnSrc, { recursive: true }); + writeFileSync(path.join(warnSrc, "SKILL.md"), "---\nname: warn-copy\n---\nNo description.\n"); + installSkillFromDir(warnSrc, { + ...warnHome.env, + harnesses: ["claude-code"], + linkDeps: { + symlink: () => { + throw new Error("EPERM"); + }, + }, + }); + expect(unlinkSkill("warn-copy", ["claude-code"], warnHome.env)).toEqual(["claude-code"]); + + // 16. adoptSkill refuses reserved slug "synced" in claude-code BEFORE moving or deleting source files, + // never matches ~/.claude/skills/synced as a candidate, AND protects it when another harness aliases .claude/skills + const adoptSyncHome = makeHome(); + const claudeSyncedDir = writeSkill(path.join(adoptSyncHome.home, ".claude", "skills", "synced"), "synced", "C"); + mkdirSync(path.join(adoptSyncHome.home, ".codex"), { recursive: true }); + symlinkSync( + path.join(adoptSyncHome.home, ".claude", "skills"), + path.join(adoptSyncHome.home, ".codex", "skills"), + dirLinkType, + ); + expect(() => adoptSkill("synced", { ...adoptSyncHome.env, harnesses: ["cursor"] })).toThrow( + 'skill "synced" not found in any searched harness directory', + ); + expect(existsSync(path.join(claudeSyncedDir, "SKILL.md"))).toBe(true); + expect(discoverSkills(adoptSyncHome.env).some((s) => s.slug === "synced")).toBe(false); + + const cursorSynced = writeSkill(path.join(adoptSyncHome.home, ".cursor", "skills", "synced"), "synced", "Local"); + expect(() => + adoptSkill("synced", { + ...adoptSyncHome.env, + fromHarness: "cursor", + harnesses: ["claude-code"], + }), + ).toThrow('skill slug "synced" is reserved in claude-code'); + expect(() => + adoptSkill("synced", { + ...adoptSyncHome.env, + fromHarness: "cursor", + harnesses: ["codex"], + }), + ).toThrow('skill slug "synced" is reserved in claude-code'); + expect(() => + installSkillFromDir(cursorSynced, { ...adoptSyncHome.env, harnesses: ["codex"], overwrite: true }), + ).toThrow('skill slug "synced" is reserved in claude-code'); + expect(existsSync(path.join(cursorSynced, "SKILL.md"))).toBe(true); + expect(existsSync(path.join(adoptSyncHome.home, ".agents", "skills", "synced"))).toBe(false); + // Installing "synced" for cursor and removing it leaves aliased .codex/skills -> .claude/skills/synced intact + installSkillFromDir(cursorSynced, { ...adoptSyncHome.env, harnesses: ["cursor"], overwrite: true }); + expect(removeSkill("synced", { ...adoptSyncHome.env, removeCanonical: true }).removedCanonical).toBe(true); + expect(existsSync(path.join(claudeSyncedDir, "SKILL.md"))).toBe(true); + + // Dangling `.codex/skills -> .claude/skills` (before `.claude/skills` exists) still protects reserved slug "synced" + const dangAliasHome = makeHome(); + mkdirSync(path.join(dangAliasHome.home, ".codex"), { recursive: true }); + symlinkSync( + path.join(dangAliasHome.home, ".claude", "skills"), + path.join(dangAliasHome.home, ".codex", "skills"), + dirLinkType, + ); + const dangSyncedSrc = writeSkill(path.join(dangAliasHome.home, "src", "synced"), "synced", "Synced"); + expect(() => + installSkillFromDir(dangSyncedSrc, { ...dangAliasHome.env, harnesses: ["codex"], overwrite: true }), + ).toThrow('skill slug "synced" is reserved in claude-code'); + }); });