Context7 Platform -- Up-to-date docs for AI agents
fix(cli): use XDG dirs for context files (#2678)
Javier Gómezc03bc9c95b48
diff --git a/.changeset/xdg-context7-dirs.md b/.changeset/xdg-context7-dirs.mdnew file mode 100644index 00000000..da9bf821--- /dev/null+++ b/.changeset/xdg-context7-dirs.md@@ -0,0 +1,5 @@+---+"ctx7": patch+---++Store CLI files in XDG Base Directory locations instead of `~/.context7`. Credentials move to `$XDG_CONFIG_HOME/context7` (default `~/.config/context7`), updater state to `$XDG_STATE_HOME/context7` (default `~/.local/state/context7`), and `generate` previews to `$XDG_CACHE_HOME/context7` (default `~/.cache/context7`). Existing files in `~/.context7` are migrated automatically on first use; migration is best-effort and falls back to reading the legacy file if it cannot complete. The credentials file is always re-asserted to `0o600` after migration or write so it is never group/world-readable. Relative or empty `XDG_*` values are ignored per the spec.diff --git a/packages/cli/src/__tests__/auth-utils.test.ts b/packages/cli/src/__tests__/auth-utils.test.tsindex 6b7080c1..f1986a71 100644--- a/packages/cli/src/__tests__/auth-utils.test.ts+++ b/packages/cli/src/__tests__/auth-utils.test.ts@@ -9,6 +9,8 @@ vi.mock("fs", () => {writeFileSync: vi.fn(),readFileSync: vi.fn(),unlinkSync: vi.fn(),+ renameSync: vi.fn(),+ chmodSync: vi.fn(),};return { ...fns, default: fns };});@@ -29,8 +31,9 @@ import {} from "../utils/auth.js";const mfs = vi.mocked(fs);-const CREDENTIALS_PATH = "/fake-home/.context7/credentials.json";-const CONFIG_DIR_PATH = "/fake-home/.context7";+const CREDENTIALS_PATH = "/fake-home/.config/context7/credentials.json";+const LEGACY_CREDENTIALS_PATH = "/fake-home/.context7/credentials.json";+const CONFIG_DIR_PATH = "/fake-home/.config/context7";beforeEach(() => {vi.clearAllMocks();@@ -44,6 +47,7 @@ beforeEach(() => {afterEach(() => {vi.unstubAllGlobals();+ vi.unstubAllEnvs();});describe("saveTokens", () => {@@ -67,6 +71,29 @@ describe("saveTokens", () => {});});+ test("enforces 0o600 even when the credentials file already exists", () => {+ // writeFileSync's mode is ignored for an existing file, so chmod must run.+ mfs.existsSync.mockReturnValue(true);+ saveTokens({ access_token: "tok", token_type: "bearer" });+ expect(mfs.chmodSync).toHaveBeenCalledWith(CREDENTIALS_PATH, 0o600);+ });++ test("honors XDG_CONFIG_HOME for credentials", () => {+ vi.stubEnv("XDG_CONFIG_HOME", "/custom-config");+ mfs.existsSync.mockReturnValue(false);+ saveTokens({ access_token: "tok", token_type: "bearer" });++ expect(mfs.mkdirSync).toHaveBeenCalledWith("/custom-config/context7", {+ recursive: true,+ mode: 0o700,+ });+ expect(mfs.writeFileSync).toHaveBeenCalledWith(+ "/custom-config/context7/credentials.json",+ expect.any(String),+ { mode: 0o600 }+ );+ });+test("computes expires_at from expires_in when expires_at is absent", () => {mfs.existsSync.mockReturnValue(true);const now = 1000000;@@ -97,11 +124,45 @@ describe("loadTokens", () => {expect(loadTokens()).toEqual(tokens);});+ test("migrates credentials from the legacy ~/.context7 path before reading", () => {+ const tokens: TokenData = { access_token: "tok", token_type: "bearer" };+ let migrated = false;+ mfs.existsSync.mockImplementation((filePath) =>+ filePath === CREDENTIALS_PATH+ ? migrated+ : filePath === LEGACY_CREDENTIALS_PATH || filePath === CONFIG_DIR_PATH+ );+ mfs.renameSync.mockImplementation(() => {+ migrated = true;+ });+ mfs.readFileSync.mockReturnValue(JSON.stringify(tokens));++ expect(loadTokens()).toEqual(tokens);+ expect(mfs.renameSync).toHaveBeenCalledWith(LEGACY_CREDENTIALS_PATH, CREDENTIALS_PATH);+ // rename preserves the legacy mode, so migration must re-assert 0o600.+ expect(mfs.chmodSync).toHaveBeenCalledWith(CREDENTIALS_PATH, 0o600);+ expect(mfs.readFileSync).toHaveBeenCalledWith(CREDENTIALS_PATH, "utf-8");+ });+test("returns null on malformed JSON", () => {mfs.existsSync.mockReturnValue(true);mfs.readFileSync.mockReturnValue("not json");expect(loadTokens()).toBeNull();});++ test("falls back to the legacy file (no throw) when migration fails", () => {+ const tokens: TokenData = { access_token: "tok", token_type: "bearer" };+ // Only the legacy file exists; the rename fails (e.g. EXDEV / EACCES).+ mfs.existsSync.mockImplementation((filePath) => filePath === LEGACY_CREDENTIALS_PATH);+ mfs.renameSync.mockImplementation(() => {+ throw new Error("EXDEV: cross-device link not permitted");+ });+ mfs.readFileSync.mockReturnValue(JSON.stringify(tokens));++ expect(() => loadTokens()).not.toThrow();+ expect(loadTokens()).toEqual(tokens);+ expect(mfs.readFileSync).toHaveBeenCalledWith(LEGACY_CREDENTIALS_PATH, "utf-8");+ });});describe("clearTokens", () => {diff --git a/packages/cli/src/__tests__/storage-paths.test.ts b/packages/cli/src/__tests__/storage-paths.test.tsnew file mode 100644index 00000000..16612ce9--- /dev/null+++ b/packages/cli/src/__tests__/storage-paths.test.ts@@ -0,0 +1,67 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { join } from "path";++import {+ getCacheDir,+ getConfigDir,+ getCredentialsFilePath,+ getPreviewsDir,+ getStateDir,+ getUpdateStateFilePath,+} from "../utils/storage-paths.js";++const HOME = "/fake-home";++beforeEach(() => {+ vi.mock("os", async () => {+ const actual = await vi.importActual<typeof import("os")>("os");+ return { ...actual, homedir: () => HOME };+ });+});++afterEach(() => {+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+});++describe("XDG defaults", () => {+ test("config dir defaults to ~/.config/context7", () => {+ expect(getConfigDir()).toBe(join(HOME, ".config", "context7"));+ expect(getCredentialsFilePath()).toBe(join(HOME, ".config", "context7", "credentials.json"));+ });++ test("state dir defaults to ~/.local/state/context7", () => {+ expect(getStateDir()).toBe(join(HOME, ".local", "state", "context7"));+ expect(getUpdateStateFilePath()).toBe(+ join(HOME, ".local", "state", "context7", "cli-state.json")+ );+ });++ test("cache dir defaults to ~/.cache/context7 and previews live under it", () => {+ expect(getCacheDir()).toBe(join(HOME, ".cache", "context7"));+ expect(getPreviewsDir()).toBe(join(HOME, ".cache", "context7", "previews"));+ });+});++describe("XDG overrides", () => {+ test("honors XDG_CONFIG_HOME, XDG_STATE_HOME, and XDG_CACHE_HOME", () => {+ vi.stubEnv("XDG_CONFIG_HOME", "/cfg");+ vi.stubEnv("XDG_STATE_HOME", "/state");+ vi.stubEnv("XDG_CACHE_HOME", "/cache");++ expect(getConfigDir()).toBe(join("/cfg", "context7"));+ expect(getStateDir()).toBe(join("/state", "context7"));+ expect(getCacheDir()).toBe(join("/cache", "context7"));+ expect(getPreviewsDir()).toBe(join("/cache", "context7", "previews"));+ });++ test("ignores empty XDG values and uses the default", () => {+ vi.stubEnv("XDG_CONFIG_HOME", "");+ expect(getConfigDir()).toBe(join(HOME, ".config", "context7"));+ });++ test("ignores relative XDG values per the spec and uses the default", () => {+ vi.stubEnv("XDG_STATE_HOME", "relative/path");+ expect(getStateDir()).toBe(join(HOME, ".local", "state", "context7"));+ });+});diff --git a/packages/cli/src/__tests__/update-check.test.ts b/packages/cli/src/__tests__/update-check.test.tsindex 8c471681..cc615d47 100644--- a/packages/cli/src/__tests__/update-check.test.ts+++ b/packages/cli/src/__tests__/update-check.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";-import { mkdir, readFile, rm } from "fs/promises";+import { mkdir, readFile, rm, writeFile } from "fs/promises";import { join } from "path";import { tmpdir } from "os";@@ -31,6 +31,7 @@ beforeEach(async () => {afterEach(async () => {await rm(tempDir, { recursive: true, force: true });vi.unstubAllGlobals();+ vi.unstubAllEnvs();vi.doUnmock("os");vi.resetModules();vi.restoreAllMocks();@@ -155,7 +156,7 @@ describe("checkForUpdates", () => {});describe("default cli-state persistence", () => {- test("writes updater state under ~/.context7/cli-state.json when using the default path", async () => {+ test("writes updater state under the XDG state directory when using the default path", async () => {const fakeHome = join(tempDir, "fake-home");await mkdir(fakeHome, { recursive: true });@@ -179,7 +180,7 @@ describe("default cli-state persistence", () => {await updateCheck.markUpdateNotificationShown("9.9.9", { now: 2000 });const persisted = JSON.parse(- await readFile(join(fakeHome, ".context7", "cli-state.json"), "utf-8")+ await readFile(join(fakeHome, ".local", "state", "context7", "cli-state.json"), "utf-8")) as {latestVersion?: string;lastCheckedAt?: number;@@ -194,6 +195,82 @@ describe("default cli-state persistence", () => {lastNotifiedAt: 2000,});});++ test("honors XDG_STATE_HOME for updater state", async () => {+ // Mock homedir so the legacy-migration step cannot touch the real ~/.context7.+ const fakeHome = join(tempDir, "fake-home");+ await mkdir(fakeHome, { recursive: true });+ const stateHome = join(tempDir, "xdg-state");+ vi.stubEnv("XDG_STATE_HOME", stateHome);++ vi.resetModules();+ vi.doMock("os", async () => {+ const actual = await vi.importActual<typeof import("os")>("os");+ return { ...actual, homedir: () => fakeHome };+ });++ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ version: "9.9.9" }),+ })+ );++ const updateCheck = await import("../utils/update-check.js");+ await updateCheck.checkForUpdates({ force: true, now: 1000 });++ const persisted = JSON.parse(+ await readFile(join(stateHome, "context7", "cli-state.json"), "utf-8")+ ) as {+ latestVersion?: string;+ lastCheckedAt?: number;+ };++ expect(persisted).toEqual({+ latestVersion: "9.9.9",+ lastCheckedAt: 1000,+ });+ });++ test("migrates legacy ~/.context7 cli-state into the XDG state directory", async () => {+ const fakeHome = join(tempDir, "fake-home");+ const legacyDir = join(fakeHome, ".context7");+ await mkdir(legacyDir, { recursive: true });+ await writeFile(+ join(legacyDir, "cli-state.json"),+ JSON.stringify({ latestVersion: "9.9.9", lastCheckedAt: 1000 }),+ "utf-8"+ );++ vi.resetModules();+ vi.doMock("os", async () => {+ const actual = await vi.importActual<typeof import("os")>("os");+ return { ...actual, homedir: () => fakeHome };+ });++ vi.stubGlobal(+ "fetch",+ vi.fn(() => {+ throw new Error("fetch should not be called for a fresh migrated cache");+ })+ );++ const updateCheck = await import("../utils/update-check.js");++ const info = await updateCheck.checkForUpdates({+ now: 2000,+ cacheTtlMs: 10_000,+ });++ expect(info?.latestVersion).toBe("9.9.9");+ expect(fetch).not.toHaveBeenCalled();+ expect(+ JSON.parse(+ await readFile(join(fakeHome, ".local", "state", "context7", "cli-state.json"), "utf-8")+ )+ ).toEqual({ latestVersion: "9.9.9", lastCheckedAt: 1000 });+ });});describe("update notifications", () => {diff --git a/packages/cli/src/commands/generate.ts b/packages/cli/src/commands/generate.tsindex 5e0d83bf..517e80cf 100644--- a/packages/cli/src/commands/generate.ts+++ b/packages/cli/src/commands/generate.ts@@ -20,6 +20,7 @@ import { promptForInstallTargets, getTargetDirs } from "../utils/ide.js";import selectOrInput from "../utils/selectOrInput.js";import { checkboxWithHover, terminalLink } from "../utils/prompts.js";import { trackEvent } from "../utils/tracking.js";+import { getPreviewsDir } from "../utils/storage-paths.js";import type {GenerateOptions,LibrarySearchResult,@@ -428,7 +429,7 @@ async function generateCommand(options: GenerateOptions): Promise<void> {};const openInEditor = async () => {- const previewDir = join(homedir(), ".context7", "previews");+ const previewDir = getPreviewsDir();await mkdir(previewDir, { recursive: true });previewFile = join(previewDir, `${skillName}.md`);if (!previewFileWritten) {diff --git a/packages/cli/src/utils/auth.ts b/packages/cli/src/utils/auth.tsindex 46a6d930..fecd1b20 100644--- a/packages/cli/src/utils/auth.ts+++ b/packages/cli/src/utils/auth.ts@@ -1,11 +1,15 @@import * as fs from "fs";-import * as path from "path";import * as os from "os";import { CLI_CLIENT_ID } from "../constants.js";import { getBaseUrl } from "./api.js";--const CONFIG_DIR = path.join(os.homedir(), ".context7");-const CREDENTIALS_FILE = path.join(CONFIG_DIR, "credentials.json");+import {+ CREDENTIALS_FILE_NAME,+ getConfigDir,+ getCredentialsFilePath,+ getLegacyFilePath,+ migrateLegacyFileSync,+ resolveReadPathSync,+} from "./storage-paths.js";export interface TokenData {access_token: string;@@ -17,27 +21,41 @@ export interface TokenData {}function ensureConfigDir(): void {- if (!fs.existsSync(CONFIG_DIR)) {- fs.mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });+ const configDir = getConfigDir();+ if (!fs.existsSync(configDir)) {+ fs.mkdirSync(configDir, { recursive: true, mode: 0o700 });}}+// Credentials must never be group/world-readable, even if a migrated or+// pre-existing file carried looser permissions.+const CREDENTIALS_MODE = 0o600;+export function saveTokens(tokens: TokenData): void {+ const credentialsFile = getCredentialsFilePath();+ migrateLegacyFileSync(CREDENTIALS_FILE_NAME, credentialsFile, CREDENTIALS_MODE);ensureConfigDir();const data = {...tokens,expires_at:tokens.expires_at ?? (tokens.expires_in ? Date.now() + tokens.expires_in * 1000 : undefined),};- fs.writeFileSync(CREDENTIALS_FILE, JSON.stringify(data, null, 2), { mode: 0o600 });+ fs.writeFileSync(credentialsFile, JSON.stringify(data, null, 2), { mode: CREDENTIALS_MODE });+ // `mode` is ignored when the file already exists; enforce it explicitly.+ fs.chmodSync(credentialsFile, CREDENTIALS_MODE);}export function loadTokens(): TokenData | null {- if (!fs.existsSync(CREDENTIALS_FILE)) {+ const credentialsFile = resolveReadPathSync(+ CREDENTIALS_FILE_NAME,+ getCredentialsFilePath(),+ CREDENTIALS_MODE+ );+ if (!fs.existsSync(credentialsFile)) {return null;}try {- const data = JSON.parse(fs.readFileSync(CREDENTIALS_FILE, "utf-8"));+ const data = JSON.parse(fs.readFileSync(credentialsFile, "utf-8"));return data as TokenData;} catch {return null;@@ -45,11 +63,18 @@ export function loadTokens(): TokenData | null {}export function clearTokens(): boolean {- if (fs.existsSync(CREDENTIALS_FILE)) {- fs.unlinkSync(CREDENTIALS_FILE);- return true;+ const credentialsFile = getCredentialsFilePath();+ let removed = false;+ if (fs.existsSync(credentialsFile)) {+ fs.unlinkSync(credentialsFile);+ removed = true;+ }+ const legacyCredentialsFile = getLegacyFilePath(CREDENTIALS_FILE_NAME);+ if (fs.existsSync(legacyCredentialsFile)) {+ fs.unlinkSync(legacyCredentialsFile);+ removed = true;}- return false;+ return removed;}export function isTokenExpired(tokens: TokenData): boolean {diff --git a/packages/cli/src/utils/storage-paths.ts b/packages/cli/src/utils/storage-paths.tsnew file mode 100644index 00000000..6ed61932--- /dev/null+++ b/packages/cli/src/utils/storage-paths.ts@@ -0,0 +1,129 @@+import * as fs from "fs";+import { access, chmod, mkdir, rename } from "fs/promises";+import * as os from "os";+import * as path from "path";++const APP_DIR = "context7";+const LEGACY_DIR = ".context7";++export const CREDENTIALS_FILE_NAME = "credentials.json";+export const UPDATE_STATE_FILE_NAME = "cli-state.json";+export const PREVIEWS_DIR_NAME = "previews";++// Per the XDG Base Directory Spec, a relative (or empty) value must be ignored+// and the default used instead.+function xdgBase(envVar: string, ...defaultSegments: string[]): string {+ const value = process.env[envVar];+ const base =+ value && path.isAbsolute(value) ? value : path.join(os.homedir(), ...defaultSegments);+ return path.join(base, APP_DIR);+}++export function getConfigDir(): string {+ return xdgBase("XDG_CONFIG_HOME", ".config");+}++export function getStateDir(): string {+ return xdgBase("XDG_STATE_HOME", ".local", "state");+}++export function getCacheDir(): string {+ return xdgBase("XDG_CACHE_HOME", ".cache");+}++export function getCredentialsFilePath(): string {+ return path.join(getConfigDir(), CREDENTIALS_FILE_NAME);+}++export function getUpdateStateFilePath(): string {+ return path.join(getStateDir(), UPDATE_STATE_FILE_NAME);+}++export function getPreviewsDir(): string {+ return path.join(getCacheDir(), PREVIEWS_DIR_NAME);+}++export function getLegacyFilePath(fileName: string): string {+ return path.join(os.homedir(), LEGACY_DIR, fileName);+}++/**+ * Best-effort move of a legacy `~/.context7/<file>` into its new XDG location.+ * `rename` preserves the source's permissions, so callers pass `mode` for+ * sensitive files (e.g. credentials) to re-assert a restrictive mode on the+ * migrated file. Failures (cross-device rename, permissions) are swallowed so+ * callers fall back to reading the legacy file rather than crashing.+ */+export function migrateLegacyFileSync(fileName: string, targetPath: string, mode?: number): void {+ const legacyPath = getLegacyFilePath(fileName);+ if (legacyPath === targetPath || fs.existsSync(targetPath) || !fs.existsSync(legacyPath)) {+ return;+ }++ try {+ fs.mkdirSync(path.dirname(targetPath), { recursive: true, mode: 0o700 });+ fs.renameSync(legacyPath, targetPath);+ if (mode !== undefined) {+ fs.chmodSync(targetPath, mode);+ }+ } catch {+ // Leave the legacy file in place; readers resolve to it via resolveReadPathSync.+ }+}++export async function migrateLegacyFile(+ fileName: string,+ targetPath: string,+ mode?: number+): Promise<void> {+ const legacyPath = getLegacyFilePath(fileName);+ if (legacyPath === targetPath || (await exists(targetPath)) || !(await exists(legacyPath))) {+ return;+ }++ try {+ await mkdir(path.dirname(targetPath), { recursive: true, mode: 0o700 });+ await rename(legacyPath, targetPath);+ if (mode !== undefined) {+ await chmod(targetPath, mode);+ }+ } catch {+ // Leave the legacy file in place; readers resolve to it via resolveReadPath.+ }+}++/**+ * Returns the path to read from: the XDG target after attempting migration,+ * or the legacy path if migration could not complete and the legacy file+ * still exists. New writes should always target `targetPath`.+ */+export function resolveReadPathSync(fileName: string, targetPath: string, mode?: number): string {+ migrateLegacyFileSync(fileName, targetPath, mode);+ if (fs.existsSync(targetPath)) {+ return targetPath;+ }+ const legacyPath = getLegacyFilePath(fileName);+ return fs.existsSync(legacyPath) ? legacyPath : targetPath;+}++export async function resolveReadPath(+ fileName: string,+ targetPath: string,+ mode?: number+): Promise<string> {+ await migrateLegacyFile(fileName, targetPath, mode);+ if (await exists(targetPath)) {+ return targetPath;+ }+ const legacyPath = getLegacyFilePath(fileName);+ return (await exists(legacyPath)) ? legacyPath : targetPath;+}++async function exists(filePath: string): Promise<boolean> {+ try {+ await access(filePath);+ return true;+ } catch {+ return false;+ }+}diff --git a/packages/cli/src/utils/update-check.ts b/packages/cli/src/utils/update-check.tsindex f4ce927b..808d1445 100644--- a/packages/cli/src/utils/update-check.ts+++ b/packages/cli/src/utils/update-check.ts@@ -1,10 +1,14 @@-import { homedir } from "os";-import { dirname, join } from "path";+import { dirname } from "path";import { mkdir, readFile, writeFile } from "fs/promises";import { NAME, VERSION } from "../constants.js";+import {+ UPDATE_STATE_FILE_NAME,+ getUpdateStateFilePath,+ migrateLegacyFile,+ resolveReadPath,+} from "./storage-paths.js";const DEFAULT_CACHE_TTL_MS = 24 * 60 * 60 * 1000;-const UPDATE_STATE_FILE = join(homedir(), ".context7", "cli-state.json");export type InstallMethod =| "npm-global"@@ -47,12 +51,29 @@ interface CheckForUpdatesOptions {}function getStateFilePath(stateFile?: string): string {- return stateFile ?? UPDATE_STATE_FILE;+ return stateFile ?? getUpdateStateFilePath();+}++// Reads resolve to the legacy `~/.context7` file if migration could not move it.+async function readStateFilePath(stateFile?: string): Promise<string> {+ if (stateFile) {+ return stateFile;+ }+ return resolveReadPath(UPDATE_STATE_FILE_NAME, getUpdateStateFilePath());+}++// Writes always target the XDG path; migrate the legacy file first if present.+async function writeStateFilePath(stateFile?: string): Promise<string> {+ const path = getStateFilePath(stateFile);+ if (!stateFile) {+ await migrateLegacyFile(UPDATE_STATE_FILE_NAME, path);+ }+ return path;}async function readUpdateState(stateFile?: string): Promise<UpdateState> {try {- const raw = await readFile(getStateFilePath(stateFile), "utf-8");+ const raw = await readFile(await readStateFilePath(stateFile), "utf-8");return JSON.parse(raw) as UpdateState;} catch {return {};@@ -60,7 +81,7 @@ async function readUpdateState(stateFile?: string): Promise<UpdateState> {}async function writeUpdateState(state: UpdateState, stateFile?: string): Promise<void> {- const path = getStateFilePath(stateFile);+ const path = await writeStateFilePath(stateFile);await mkdir(dirname(path), { recursive: true });await writeFile(path, JSON.stringify(state, null, 2) + "\n", "utf-8");}