UNPKG

@code-yeongyu/senpi

Version:

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

230 lines • 7.73 kB
import { createHash, randomBytes } from "node:crypto"; import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { getAgentDir } from "../../../../../config.js"; import { lockWithLossHandling } from "../../../../file-lock.js"; import { adoptLegacyRecord, readRecordAsync } from "./legacy-migration.js"; const AUTH_ROOT = "mcp-auth"; const TOKENS_FILE = "tokens.json"; const INDEX_FILE = "index.json"; const DEFAULT_LOCK = { retries: 50, stale: 30_000 }; export class LockAcquireError extends Error { constructor(lockPath, cause) { super(`Could not acquire MCP auth lock at ${lockPath}: ${cause instanceof Error ? cause.message : String(cause)}`); this.name = "LockAcquireError"; this.lockPath = lockPath; } } export function hashServerUrl(serverUrl) { return createHash("sha256").update(serverUrl).digest("hex"); } export function hashServerKey(serverName, serverUrl) { return createHash("sha256").update(`${serverName}\0${serverUrl}`).digest("hex"); } export class McpTokenStore { #agentDir; #hash; #legacyHash; #lock; #disableLock; #held; constructor(options) { this.serverName = options.serverName; this.serverUrl = options.serverUrl; this.#agentDir = options.agentDir ?? getAgentDir(); this.#hash = hashServerKey(options.serverName, options.serverUrl); this.#legacyHash = hashServerUrl(options.serverUrl); this.#lock = { ...DEFAULT_LOCK, ...options.lock }; this.#disableLock = options.disableLock ?? false; } get rootDir() { return join(this.#agentDir, AUTH_ROOT); } get agentDir() { return this.#agentDir; } get dir() { return join(this.rootDir, this.#hash); } get tokensPath() { return join(this.dir, TOKENS_FILE); } get lockPath() { return join(this.dir, `${TOKENS_FILE}.lock`); } get legacyDir() { return join(this.rootDir, this.#legacyHash); } get #legacyLockFile() { return join(this.rootDir, `${this.#legacyHash}.migrate.lock`); } read() { const record = readJsonFile(this.tokensPath); if (record !== undefined) return record; return adoptLegacyRecord(this.#migration()); } async readAsync() { return readRecordAsync(this.#migration()); } #migration() { return { rootDir: this.rootDir, lockPath: this.#legacyLockFile, legacyTokens: join(this.legacyDir, TOKENS_FILE), tokensPath: this.tokensPath, stale: this.#lock.stale, disableLock: this.#disableLock, read: readJsonFile, write: (record) => this.writeUnlocked(record), lockError: (cause) => new LockAcquireError(this.#legacyLockFile, cause), }; } async update(mutate) { const held = await this.#acquire(); this.#held = held; try { const next = mutate(this.read()); if (next === undefined) { this.#removeRecord(); } else { this.#writeAtomic(next); this.#writeIndex(); } return next; } finally { this.#held = undefined; await held.release(); } } async write(record) { await this.update(() => record); } // Run an async critical section under the cross-process lock. The callback // must use readUnlocked/writeUnlocked (never update/write) to avoid // re-entrant lock acquisition, which proper-lockfile rejects immediately. async withLock(fn) { const held = await this.#acquire(); this.#held = held; try { return await fn(); } finally { this.#held = undefined; await held.release(); } } readUnlocked() { return this.read(); } // Inside withLock this is the commit step of a read-refresh-write (the OAuth refresh spends a // rotating refresh token over the network first): each write below refuses once the lock was lost. writeUnlocked(record) { if (record === undefined) { this.#removeRecord(); return; } this.#writeAtomic(record); this.#writeIndex(); } async clear() { const { release, assertHeld } = await this.#acquire(); try { assertHeld(); rmSync(this.dir, { force: true, recursive: true }); rmSync(join(this.legacyDir, TOKENS_FILE), { force: true }); } finally { await release().catch(() => undefined); } removeIndexEntry(this.rootDir, this.serverName, this.#hash); } #ensureDir() { mkdirSync(this.dir, { mode: 0o700, recursive: true }); chmodSync(this.dir, 0o700); } async #acquire() { this.#ensureDir(); if (this.#disableLock) return { release: () => Promise.resolve(), assertHeld: () => { } }; try { return await lockWithLossHandling(this.dir, { lockfilePath: this.lockPath, realpath: false, retries: { retries: this.#lock.retries, factor: 1.2, minTimeout: 20, maxTimeout: 200 }, stale: this.#lock.stale, }); } catch (cause) { throw new LockAcquireError(this.lockPath, cause); } } #writeAtomic(record) { this.#ensureDir(); const tmp = join(this.dir, `${TOKENS_FILE}.${randomBytes(6).toString("hex")}.tmp`); writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 }); chmodSync(tmp, 0o600); try { this.#held?.assertHeld(); } catch (error) { rmSync(tmp, { force: true }); throw error; } renameSync(tmp, this.tokensPath); chmodSync(this.tokensPath, 0o600); } #removeTokens() { rmSync(this.tokensPath, { force: true }); } #removeRecord() { this.#held?.assertHeld(); this.#removeTokens(); removeIndexEntry(this.rootDir, this.serverName, this.#hash); } #writeIndex() { this.#held?.assertHeld(); writeIndexEntry(this.rootDir, this.serverName, this.#hash); } } function readJsonFile(path) { if (!existsSync(path)) return undefined; const raw = readFileSync(path, "utf-8").trim(); if (raw.length === 0) return undefined; return JSON.parse(raw); } function indexPath(rootDir) { return join(rootDir, INDEX_FILE); } function readIndex(rootDir) { return readJsonFile(indexPath(rootDir)) ?? {}; } function writeIndexEntry(rootDir, name, hash) { mkdirSync(rootDir, { mode: 0o700, recursive: true }); const index = readIndex(rootDir); if (index[name] === hash) return; index[name] = hash; writeIndexAtomic(rootDir, index); } function removeIndexEntry(rootDir, name, hash) { if (!existsSync(indexPath(rootDir))) return; const index = readIndex(rootDir); if (index[name] !== hash && index[name] !== undefined) return; delete index[name]; writeIndexAtomic(rootDir, index); } function writeIndexAtomic(rootDir, index) { const tmp = join(rootDir, `${INDEX_FILE}.${randomBytes(6).toString("hex")}.tmp`); writeFileSync(tmp, `${JSON.stringify(index, null, 2)}\n`, { mode: 0o600 }); chmodSync(tmp, 0o600); renameSync(tmp, indexPath(rootDir)); chmodSync(indexPath(rootDir), 0o600); } //# sourceMappingURL=token-store.js.map