Skip to content
Merged
14 changes: 14 additions & 0 deletions .changeset/skills-v021-hardening.md
Original file line number Diff line number Diff line change
@@ -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`.
41 changes: 0 additions & 41 deletions packages/cli/src/control/skills.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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<Uint8Array>;
Expand All @@ -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,
Expand Down
34 changes: 32 additions & 2 deletions packages/cli/test/control-skills.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {},
}),
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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(
Expand Down
88 changes: 72 additions & 16 deletions packages/skills/src/archive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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}"`);
}
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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})`);
Expand Down Expand Up @@ -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;
}
16 changes: 15 additions & 1 deletion packages/skills/src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,12 @@ function parseFlags(argv: readonly string[]): { pos: string[]; flags: Map<string
return { pos, flags };
}

function trimTrailingSlashes(s: string): string {
let end = s.length;
while (end > 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);
Expand Down Expand Up @@ -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, {
Expand Down
Loading
Loading