UNPKG

@code-yeongyu/senpi

Version:

Coding agent CLI with read, bash, edit, write tools and session management

184 lines • 7.76 kB
import { randomBytes } from "node:crypto"; import { chmodSync, constants, lstatSync, mkdirSync, readlinkSync, symlinkSync, unlinkSync } from "node:fs"; import { lstat, mkdir, open, rm, unlink } from "node:fs/promises"; import { homedir } from "node:os"; import { join, resolve } from "node:path"; import { logoutClaudeCli } from "./claude-cli-auth-status.js"; /** * Entries of a CLI-store account dir that point at the shared Claude root, so every account reads one * transcript tree (`projects`) and the user's own settings, memory, agents, commands, skills and output * styles. The credential store and everything else stay per account. */ export const CLAUDE_CLI_SHARED_LINKS = [ "projects", "settings.json", "CLAUDE.md", "agents", "commands", "skills", "output-styles", ]; const SHARED_FILES = new Set(["settings.json", "CLAUDE.md"]); const DIR_ID_PATTERN = /^[0-9a-f]{32}$/; export function newAccountDirId() { return randomBytes(16).toString("hex"); } export function isValidAccountDirId(dirId) { return DIR_ID_PATTERN.test(dirId); } /** `<agentDir>/anthropic-subscription-claude/<dirId>`; a stored id of any other shape is refused. */ export function accountDirFor(agentDir, dirId) { if (!isValidAccountDirId(dirId)) throw new Error("Invalid Claude account dir id"); return join(agentDir, "anthropic-subscription-claude", dirId); } /** * The access token the claude CLI keeps for an account dir, as it stands: read only, never refreshed (senpi#4436). * Undefined when the credential file is missing, unreadable, malformed or already expired; the CLI renews it on * its next turn. Only the file store is read, which the CLI uses on Linux and Windows; on macOS the CLI keeps the * token in the Keychain, so a macOS account offers none. Like `removeAccountDir`, it follows no link: a linked * account dir or credential file (say, to the user's own `~/.claude`) offers none, including one swapped in after * the check. */ export async function readClaudeCliAccessToken(accountDir, now) { const file = join(accountDir, ".credentials.json"); let parsed; try { const [dirStats, fileStats] = await Promise.all([lstat(accountDir), lstat(file)]); if (!dirStats.isDirectory() || !fileStats.isFile()) return undefined; // Checked, then read: a link swapped in between must not be followed. The open refuses a final link where the // platform can (O_NOFOLLOW; Windows has none), and the opened handle must be the very file that was checked. const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)); try { const opened = await handle.stat(); if (!opened.isFile() || opened.ino !== fileStats.ino || opened.dev !== fileStats.dev) return undefined; parsed = JSON.parse(await handle.readFile("utf8")); } finally { await handle.close(); } // The dir is not opened, so a dir swapped for a link during the read shows up as a changed dir afterwards. const dirAfter = await lstat(accountDir); if (!dirAfter.isDirectory() || dirAfter.ino !== dirStats.ino || dirAfter.dev !== dirStats.dev) return undefined; } catch { return undefined; } const oauth = typeof parsed === "object" && parsed !== null ? parsed.claudeAiOauth : undefined; if (typeof oauth !== "object" || oauth === null) return undefined; const { accessToken, expiresAt } = oauth; if (typeof accessToken !== "string" || accessToken === "") return undefined; if (typeof expiresAt === "number" && expiresAt <= now) return undefined; return accessToken; } /** The root the accounts share: an inherited `CLAUDE_CONFIG_DIR`, else `~/.claude`. */ export function claudeCliSharedRoot(env) { const inherited = env.CLAUDE_CONFIG_DIR; return inherited ? resolve(inherited) : join(homedir(), ".claude"); } function isLink(path) { try { return lstatSync(path).isSymbolicLink(); } catch { return false; } } function exists(path) { try { lstatSync(path); return true; } catch { return false; } } async function lstatOrUndefined(path) { try { return await lstat(path); } catch (error) { if (error.code === "ENOENT") return undefined; throw error; } } function linkEntry(entry, target, path) { if (!SHARED_FILES.has(entry)) { mkdirSync(target, { recursive: true }); symlinkSync(target, path, process.platform === "win32" ? "junction" : "dir"); return; } if (!exists(target)) return; try { symlinkSync(target, path, "file"); } catch (error) { // Windows refuses file symlinks without Developer Mode; the account then keeps its own copy. if (process.platform !== "win32") throw error; } } /** * Creates the account dir (0700) and creates or repairs its links to the shared root. A link pointing * elsewhere is replaced; a real file or dir in a link's place is account data and is left alone. */ export function ensureAccountDir(options) { const accountDir = accountDirFor(options.agentDir, options.dirId); mkdirSync(accountDir, { recursive: true, mode: 0o700 }); if (process.platform !== "win32") chmodSync(accountDir, 0o700); for (const entry of CLAUDE_CLI_SHARED_LINKS) { const path = join(accountDir, entry); const target = join(options.sharedRoot, entry); if (isLink(path)) { if (resolve(accountDir, readlinkSync(path)) === resolve(target)) continue; unlinkSync(path); } else if (exists(path)) { continue; } linkEntry(entry, target, path); } return accountDir; } /** * Signs the account out (`claude auth logout` with `CLAUDE_CONFIG_DIR=<accountDir>`, which deletes that dir's * credential store entry), then unlinks the shared links WITHOUT following them and removes the dir. Removal never * depends on the CLI: with no executable, or a sign-out that fails, the dir is still removed and the outcome says * the sign-out did not run, so the caller can tell the user. A missing dir is * still signed out, because the CLI keys its store entry on the path. A link or file in the dir's place is not * an account dir: it is never signed out against, followed or deleted. */ export async function removeAccountDir(options) { const accountDir = accountDirFor(options.agentDir, options.dirId); options.signal?.throwIfAborted(); // A missing dir is recreated empty: the CLI runs inside its config dir, and its store entry is keyed on the path. if ((await lstatOrUndefined(accountDir)) === undefined) await mkdir(accountDir, { recursive: true, mode: 0o700 }); if (!(await lstatOrUndefined(accountDir))?.isDirectory()) return "not_an_account_dir"; const signedOut = options.executable !== undefined && (await logoutClaudeCli({ executable: options.executable, configDir: accountDir, ...(options.parentEnv === undefined ? {} : { parentEnv: options.parentEnv }), }, undefined, options.signal).catch(() => false)); options.signal?.throwIfAborted(); for (const entry of CLAUDE_CLI_SHARED_LINKS) { const path = join(accountDir, entry); if ((await lstatOrUndefined(path))?.isSymbolicLink()) await unlink(path); } await rm(accountDir, { recursive: true, force: true }); return signedOut ? "removed" : "removed_without_sign_out"; } //# sourceMappingURL=claude-cli-account-dir.js.map