A self-hostable bookmark-everything app (links, notes and images) with AI-based automatic tagging and full text search
feat: Add CLI auth config support (#2751)
Mohamed Bassem90382dc391b6
diff --git a/apps/cli/package.json b/apps/cli/package.jsonindex e73ab9ca..f5fd9458 100644--- a/apps/cli/package.json+++ b/apps/cli/package.json@@ -28,7 +28,8 @@"table": "^6.8.2","tsx": "^4.8.1","vite": "^7.0.6",- "vite-tsconfig-paths": "^6.1.1"+ "vite-tsconfig-paths": "^6.1.1",+ "zod": "^4.0.0"},"scripts": {"build": "vite build && chmod +x dist/index.mjs",diff --git a/apps/cli/src/commands/auth.ts b/apps/cli/src/commands/auth.tsnew file mode 100644index 00000000..c780e0ae--- /dev/null+++ b/apps/cli/src/commands/auth.ts@@ -0,0 +1,144 @@+import fsp from "node:fs/promises";+import path from "node:path";+import { stdin as input, stdout as output } from "node:process";+import readline from "node:readline/promises";+import {+ DEFAULT_SERVER_ADDR,+ getConfigPath,+ loadConfigFile,+ normalizeConfig,+} from "@/lib/config";+import { printStatusMessage } from "@/lib/output";+import { Command } from "@commander-js/extra-typings";++async function pathExists(filePath: string) {+ try {+ await fsp.access(filePath);+ return true;+ } catch {+ return false;+ }+}++async function loadExistingConfig(opts: AuthInitOptions) {+ try {+ return loadConfigFile();+ } catch (error) {+ if (opts.force) {+ return {};+ }+ throw error;+ }+}++async function promptForValue(+ rl: readline.Interface,+ prompt: string,+ existing?: string,+) {+ if (!input.isTTY) {+ return existing;+ }++ const suffix = existing ? ` [${existing}]` : "";+ const value = (await rl.question(`${prompt}${suffix}: `)).trim();+ return value || existing;+}++interface AuthInitOptions {+ serverAddr?: string;+ apiKey?: string;+ force?: boolean;+}++export const authCmd = new Command()+ .name("auth")+ .description("authentication commands");++authCmd+ .command("init")+ .description("setup CLI authentication config")+ .option("--server-addr <addr>", "the address of the server to connect to")+ .option("--api-key <key>", "the API key to interact with the API")+ .option("-f, --force", "overwrite an existing config without confirmation")+ .action(async (rawOpts, command) => {+ const rootOpts = command.parent?.parent?.opts() as AuthInitOptions;+ const opts = {+ serverAddr: rootOpts.serverAddr,+ apiKey: rootOpts.apiKey,+ force: Boolean(rawOpts.force),+ };+ const configPath = getConfigPath();++ try {+ const existingConfig = await loadExistingConfig(opts);+ const existingAuth = normalizeConfig(existingConfig);++ if ((await pathExists(configPath)) && !opts.force) {+ if (!input.isTTY) {+ throw new Error(+ `Config file already exists at ${configPath}. Re-run with --force to overwrite it.`,+ );+ }++ const rl = readline.createInterface({ input, output });+ const answer = (+ await rl.question(+ `Config file already exists at ${configPath}. Update it? (yes/no): `,+ )+ )+ .trim()+ .toLowerCase();+ rl.close();++ if (answer !== "y" && answer !== "yes") {+ printStatusMessage(false, "Auth init aborted by user");+ return;+ }+ }++ const rl = readline.createInterface({ input, output });+ const serverAddr =+ opts.serverAddr ??+ (await promptForValue(+ rl,+ "Karakeep server address",+ existingAuth.serverAddr ?? DEFAULT_SERVER_ADDR,+ ));+ const apiKey =+ opts.apiKey ??+ (await promptForValue(rl, "Karakeep API key", existingAuth.apiKey));+ rl.close();++ if (!serverAddr || !apiKey) {+ throw new Error("Both server address and API key are required");+ }++ await fsp.mkdir(path.dirname(configPath), { recursive: true });+ await fsp.writeFile(+ configPath,+ JSON.stringify(+ {+ ...existingConfig,+ serverAddr,+ apiKey,+ },+ null,+ 2,+ ) + "\n",+ {+ encoding: "utf-8",+ mode: 0o600,+ },+ );+ await fsp.chmod(configPath, 0o600);++ printStatusMessage(true, `Wrote auth config to ${configPath}`);+ } catch (error) {+ printStatusMessage(+ false,+ error instanceof Error ? error.message : `${error}`,+ );+ process.exitCode = 1;+ }+ });diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.tsindex e3b73e05..4c5d0f40 100644--- a/apps/cli/src/index.ts+++ b/apps/cli/src/index.ts@@ -1,4 +1,5 @@import { adminCmd } from "@/commands/admin";+import { authCmd } from "@/commands/auth";import { bookmarkCmd } from "@/commands/bookmarks";import { dumpCmd } from "@/commands/dump";import { highlightsCmd } from "@/commands/highlights";@@ -7,24 +8,62 @@ import { migrateCmd } from "@/commands/migrate";import { tagsCmd } from "@/commands/tags";import { whoamiCmd } from "@/commands/whoami";import { wipeCmd } from "@/commands/wipe";+import { DEFAULT_SERVER_ADDR, getConfigPath, loadConfig } from "@/lib/config";+import type { RawGlobalOptions } from "@/lib/globals";import { setGlobalOptions } from "@/lib/globals";import { Command, Option } from "@commander-js/extra-typings";+function resolveGlobalOptions(opts: RawGlobalOptions) {+ if (opts.apiKey && opts.serverAddr) {+ return {+ apiKey: opts.apiKey,+ serverAddr: opts.serverAddr,+ json: opts.json,+ };+ }++ const config = loadConfig();+ const apiKey = opts.apiKey ?? config.apiKey;+ const serverAddr =+ opts.serverAddr ?? config.serverAddr ?? DEFAULT_SERVER_ADDR;++ if (!apiKey) {+ throw new Error(+ `Missing required option: --api-key. Provide it as a CLI option, environment variable, or in ${getConfigPath()}.`,+ );+ }++ return {+ apiKey,+ serverAddr,+ json: opts.json,+ };+}++function isAuthCommand(command: { name(): string; parent?: unknown }) {+ let current: { name(): string; parent?: unknown } | undefined = command;+ while (current) {+ if (current.name() === "auth") {+ return true;+ }+ current = current.parent as typeof current;+ }+ return false;+}+const program = new Command().name("karakeep").description("A CLI interface to interact with the karakeep api").addOption(- new Option("--api-key <key>", "the API key to interact with the API")- .makeOptionMandatory(true)- .env("KARAKEEP_API_KEY"),+ new Option("--api-key <key>", "the API key to interact with the API").env(+ "KARAKEEP_API_KEY",+ ),).addOption(new Option("--server-addr <addr>","the address of the server to connect to",- )- .makeOptionMandatory(true)- .env("KARAKEEP_SERVER_ADDR"),+ ).env("KARAKEEP_SERVER_ADDR"),).addOption(new Option("--json", "to output the result as JSON")).version(@@ -34,6 +73,7 @@ const program = new Command());program.addCommand(adminCmd);+program.addCommand(authCmd);program.addCommand(bookmarkCmd);program.addCommand(highlightsCmd);program.addCommand(listsCmd);@@ -43,6 +83,23 @@ program.addCommand(migrateCmd);program.addCommand(wipeCmd);program.addCommand(dumpCmd);-setGlobalOptions(program.opts());+program.hook("preAction", (_thisCommand, actionCommand) => {+ if (isAuthCommand(actionCommand)) {+ return;+ }++ try {+ setGlobalOptions(resolveGlobalOptions(program.opts()));+ } catch (error) {+ program.error(error instanceof Error ? error.message : `${error}`);+ }+});++async function main() {+ await program.parseAsync();+}-program.parse();+void main().catch((error) => {+ console.error(error instanceof Error ? error.message : error);+ process.exitCode = 1;+});diff --git a/apps/cli/src/lib/config.ts b/apps/cli/src/lib/config.tsnew file mode 100644index 00000000..c63549cc--- /dev/null+++ b/apps/cli/src/lib/config.ts@@ -0,0 +1,47 @@+import * as fs from "node:fs";+import * as os from "node:os";+import * as path from "node:path";+import { z } from "zod";++export interface CliConfig {+ apiKey?: string;+ serverAddr?: string;+}++export const DEFAULT_SERVER_ADDR = "https://cloud.karakeep.app";++export const zCliConfigFileSchema = z+ .object({+ apiKey: z.string().min(1).optional(),+ serverAddr: z.string().min(1).optional(),+ })+ .passthrough();++export type CliConfigFile = z.infer<typeof zCliConfigFileSchema>;++export function normalizeConfig(config: CliConfigFile): CliConfig {+ return {+ apiKey: config.apiKey,+ serverAddr: config.serverAddr,+ };+}++export function getConfigPath() {+ const configHome =+ process.env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");+ return path.join(configHome, "karakeep", "config.json");+}++export function loadConfigFile(): CliConfigFile {+ const configPath = getConfigPath();+ if (!fs.existsSync(configPath)) {+ return {};+ }++ const parsed = JSON.parse(fs.readFileSync(configPath, "utf-8")) as unknown;+ return zCliConfigFileSchema.parse(parsed);+}++export function loadConfig(): CliConfig {+ return normalizeConfig(loadConfigFile());+}diff --git a/apps/cli/src/lib/globals.ts b/apps/cli/src/lib/globals.tsindex 8a301cfe..b2321060 100644--- a/apps/cli/src/lib/globals.ts+++ b/apps/cli/src/lib/globals.ts@@ -4,6 +4,12 @@ export interface GlobalOptions {json?: true;}+export interface RawGlobalOptions {+ apiKey?: string;+ serverAddr?: string;+ json?: true;+}+export let globalOpts: GlobalOptions | undefined = undefined;export function setGlobalOptions(opts: GlobalOptions) {diff --git a/apps/cli/vite.config.mts b/apps/cli/vite.config.mtsindex 5306b24a..400e41f4 100644--- a/apps/cli/vite.config.mts+++ b/apps/cli/vite.config.mts@@ -13,7 +13,7 @@ export default defineConfig({entryFileNames: "index.mjs",banner: "#!/usr/bin/env node",},- external: ["node:fs", "node:path", "node:url", "node:process"],+ external: ["node:fs", "node:os", "node:path", "node:url", "node:process"],},ssr: true,target: "node18",diff --git a/docs/docs/05-integrations/02-command-line.md b/docs/docs/05-integrations/02-command-line.mdindex c8b00696..0844d669 100644--- a/docs/docs/05-integrations/02-command-line.md+++ b/docs/docs/05-integrations/02-command-line.md@@ -34,10 +34,12 @@ A CLI interface to interact with the karakeep apiOptions:--api-key <key> the API key to interact with the API (env: KARAKEEP_API_KEY)--server-addr <addr> the address of the server to connect to (env: KARAKEEP_SERVER_ADDR)+ --json to output the result as JSON-V, --version output the version number-h, --help display help for commandCommands:+ auth authentication commandsbookmarks manipulating bookmarkslists manipulating liststags manipulating tags@@ -108,6 +110,28 @@ karakeep --api-key mysupersecretkey --server-addr https://try.karakeep.app whoam}```+You can also store the server address and API key in+`$XDG_CONFIG_HOME/karakeep/config.json`. If `XDG_CONFIG_HOME` is not set, the+CLI reads `~/.config/karakeep/config.json`.++```json+{+ "serverAddr": "https://try.karakeep.app",+ "apiKey": "mysupersecretkey"+}+```++Command-line options take precedence over environment variables, and+environment variables take precedence over the config file.+If no server address is provided, the CLI defaults to+`https://cloud.karakeep.app`.++To create or update this file interactively, run:++```bash+karakeep auth init+```+## Other clientsdiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 0140754e..512f467e 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -198,6 +198,9 @@ importers:vite-tsconfig-paths:specifier: ^6.1.1version: 6.1.1([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+ zod:+ specifier: ^4.0.0+ version: 4.3.6apps/landing:dependencies: