Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor: make API key prefix and CLI product naming distribution slots (#18637)

LiJianbc08dbe17dca
diff --git a/apps/cli/src/api/client.ts b/apps/cli/src/api/client.ts
index a932cd66015..f3dbcbef7c7 100644
--- a/apps/cli/src/api/client.ts
+++ b/apps/cli/src/api/client.ts
@@ -5,7 +5,9 @@ import type { LambdaRouter } from '@/server/routers/lambda';
import type { ToolsRouter } from '@/server/routers/tools';
import { getValidToken } from '../auth/refresh';
-import { CLI_API_KEY_ENV } from '../constants/auth';
+import { CLI_API_KEY_ENV, readCliApiKeyEnv } from '../constants/auth';
+import { CLI_PRIMARY_BIN } from '../constants/identity';
+import { cliPackageName } from '../pkg';
import { resolveServerUrl } from '../settings';
import { log } from '../utils/logger';
import { resolveWorkspaceId, withWorkspaceHeader } from './workspace';
@@ -29,7 +31,7 @@ async function getAuthAndServer(): Promise<{ headers: Record<string, string>; se
};
}
- const envApiKey = process.env[CLI_API_KEY_ENV];
+ const envApiKey = readCliApiKeyEnv();
if (envApiKey) {
const serverUrl = resolveServerUrl();
@@ -42,7 +44,7 @@ async function getAuthAndServer(): Promise<{ headers: Record<string, string>; se
const result = await getValidToken();
if (!result) {
log.error(
- `No authentication found. Run 'lh login' (or 'npx -y @lobehub/cli login') first, or set ${CLI_API_KEY_ENV}.`,
+ `No authentication found. Run '${CLI_PRIMARY_BIN} login' (or 'npx -y ${cliPackageName} login') first, or set ${CLI_API_KEY_ENV}.`,
);
process.exit(1);
}
diff --git a/apps/cli/src/api/http.ts b/apps/cli/src/api/http.ts
index 76920520241..538536ea74b 100644
--- a/apps/cli/src/api/http.ts
+++ b/apps/cli/src/api/http.ts
@@ -1,5 +1,6 @@
import { getValidToken } from '../auth/refresh';
-import { CLI_API_KEY_ENV } from '../constants/auth';
+import { CLI_API_KEY_ENV, readCliApiKeyEnv } from '../constants/auth';
+import { CLI_PRIMARY_BIN } from '../constants/identity';
import { resolveServerUrl } from '../settings';
import { log } from '../utils/logger';
import { withWorkspaceHeader } from './workspace';
@@ -30,14 +31,14 @@ export async function getAuthInfo(workspaceId?: string): Promise<AuthInfo> {
const result = await getValidToken();
if (!result) {
- if (process.env[CLI_API_KEY_ENV]) {
+ if (readCliApiKeyEnv()) {
log.error(
`API key auth from ${CLI_API_KEY_ENV} is not supported for /webapi/* routes. Run OIDC login instead.`,
);
process.exit(1);
}
- log.error("No authentication found. Run 'lh login' first.");
+ log.error(`No authentication found. Run '${CLI_PRIMARY_BIN} login' first.`);
process.exit(1);
}
@@ -87,7 +88,7 @@ export async function getAgentStreamAuthInfo(workspaceId?: string): Promise<Agen
};
}
- const envApiKey = process.env[CLI_API_KEY_ENV];
+ const envApiKey = readCliApiKeyEnv();
if (envApiKey) {
return {
headers: withWorkspaceHeader({ 'X-API-Key': envApiKey }, workspaceId),
@@ -99,7 +100,9 @@ export async function getAgentStreamAuthInfo(workspaceId?: string): Promise<Agen
const result = await getValidToken();
if (!result) {
- log.error(`No authentication found. Run 'lh login' first, or set ${CLI_API_KEY_ENV}.`);
+ log.error(
+ `No authentication found. Run '${CLI_PRIMARY_BIN} login' first, or set ${CLI_API_KEY_ENV}.`,
+ );
process.exit(1);
return {
diff --git a/apps/cli/src/auth/credentials.ts b/apps/cli/src/auth/credentials.ts
index 79d109de3c3..5e8217f7a1a 100644
--- a/apps/cli/src/auth/credentials.ts
+++ b/apps/cli/src/auth/credentials.ts
@@ -3,13 +3,15 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+import { resolveCliDirName } from '../constants/identity';
+
export interface StoredCredentials {
accessToken: string;
expiresAt?: number; // Unix timestamp (seconds)
refreshToken?: string;
}
-const LOBEHUB_DIR_NAME = process.env.LOBEHUB_CLI_HOME || '.lobehub';
+const LOBEHUB_DIR_NAME = resolveCliDirName();
const CREDENTIALS_DIR = path.join(os.homedir(), LOBEHUB_DIR_NAME);
const CREDENTIALS_FILE = path.join(CREDENTIALS_DIR, 'credentials.json');
diff --git a/apps/cli/src/auth/resolveToken.ts b/apps/cli/src/auth/resolveToken.ts
index 5b41a68e231..2222a5de8c6 100644
--- a/apps/cli/src/auth/resolveToken.ts
+++ b/apps/cli/src/auth/resolveToken.ts
@@ -1,4 +1,5 @@
-import { CLI_API_KEY_ENV } from '../constants/auth';
+import { CLI_API_KEY_ENV, readCliApiKeyEnv } from '../constants/auth';
+import { CLI_PRIMARY_BIN } from '../constants/identity';
import { resolveServerUrl } from '../settings';
import { log } from '../utils/logger';
import { getUserIdFromApiKey } from './apiKey';
@@ -70,7 +71,7 @@ export async function resolveToken(options: ResolveTokenOptions): Promise<Resolv
};
}
- const envApiKey = process.env[CLI_API_KEY_ENV];
+ const envApiKey = readCliApiKeyEnv();
if (envApiKey) {
try {
const serverUrl = resolveServerUrl();
@@ -93,7 +94,7 @@ export async function resolveToken(options: ResolveTokenOptions): Promise<Resolv
const userId = parseJwtSub(credentials.accessToken);
if (!userId) {
- log.error("Stored token is invalid. Run 'lh login' again.");
+ log.error(`Stored token is invalid. Run '${CLI_PRIMARY_BIN} login' again.`);
process.exit(1);
}
@@ -101,7 +102,7 @@ export async function resolveToken(options: ResolveTokenOptions): Promise<Resolv
}
log.error(
- `No authentication found. Run 'lh login' first, or set ${CLI_API_KEY_ENV}, or provide --token.`,
+ `No authentication found. Run '${CLI_PRIMARY_BIN} login' first, or set ${CLI_API_KEY_ENV}, or provide --token.`,
);
process.exit(1);
}
diff --git a/apps/cli/src/commands/completion.test.ts b/apps/cli/src/commands/completion.test.ts
index a34a5ac7b37..507635068ff 100644
--- a/apps/cli/src/commands/completion.test.ts
+++ b/apps/cli/src/commands/completion.test.ts
@@ -1,6 +1,7 @@
import { Command } from 'commander';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { CLI_COMPLETION_CWORD_ENV } from '../constants/identity';
import { registerCompletionCommand } from './completion';
describe('completion command', () => {
@@ -13,7 +14,7 @@ describe('completion command', () => {
afterEach(() => {
consoleSpy.mockRestore();
- delete process.env.LOBEHUB_COMP_CWORD;
+ delete process.env[CLI_COMPLETION_CWORD_ENV];
process.env.SHELL = originalShell;
});
@@ -55,7 +56,7 @@ describe('completion command', () => {
});
it('should suggest root commands and aliases', async () => {
- process.env.LOBEHUB_COMP_CWORD = '0';
+ process.env[CLI_COMPLETION_CWORD_ENV] = '0';
const program = createProgram();
await program.parseAsync(['node', 'test', '__complete', 'g']);
@@ -64,7 +65,7 @@ describe('completion command', () => {
});
it('should suggest nested subcommands in the current command context', async () => {
- process.env.LOBEHUB_COMP_CWORD = '1';
+ process.env[CLI_COMPLETION_CWORD_ENV] = '1';
const program = createProgram();
await program.parseAsync(['node', 'test', '__complete', 'agent']);
@@ -73,7 +74,7 @@ describe('completion command', () => {
});
it('should suggest command options after leaf commands', async () => {
- process.env.LOBEHUB_COMP_CWORD = '1';
+ process.env[CLI_COMPLETION_CWORD_ENV] = '1';
const program = createProgram();
await program.parseAsync(['node', 'test', '__complete', 'usage']);
@@ -82,7 +83,7 @@ describe('completion command', () => {
});
it('should not suggest commands while completing an option value', async () => {
- process.env.LOBEHUB_COMP_CWORD = '2';
+ process.env[CLI_COMPLETION_CWORD_ENV] = '2';
const program = createProgram();
await program.parseAsync(['node', 'test', '__complete', 'usage', '--month']);
@@ -91,7 +92,7 @@ describe('completion command', () => {
});
it('should not expose hidden commands', async () => {
- process.env.LOBEHUB_COMP_CWORD = '0';
+ process.env[CLI_COMPLETION_CWORD_ENV] = '0';
const program = createProgram();
await program.parseAsync(['node', 'test', '__complete']);
diff --git a/apps/cli/src/commands/completion.ts b/apps/cli/src/commands/completion.ts
index a4c095ca135..edd1a0dd2fb 100644
--- a/apps/cli/src/commands/completion.ts
+++ b/apps/cli/src/commands/completion.ts
@@ -1,5 +1,6 @@
import type { Command } from 'commander';
+import { CLI_COMPLETION_CWORD_ENV } from '../constants/identity';
import {
getCompletionCandidates,
parseCompletionWordIndex,
@@ -20,7 +21,10 @@ export function registerCompletionCommand(program: Command) {
.allowUnknownOption()
.argument('[words...]')
.action((words: string[] = []) => {
- const currentWordIndex = parseCompletionWordIndex(process.env.LOBEHUB_COMP_CWORD, words);
+ const currentWordIndex = parseCompletionWordIndex(
+ process.env[CLI_COMPLETION_CWORD_ENV],
+ words,
+ );
const candidates = getCompletionCandidates(program, words, currentWordIndex);
for (const candidate of candidates) {
diff --git a/apps/cli/src/commands/config.ts b/apps/cli/src/commands/config.ts
index 84d9cf7898c..8dd35c2e338 100644
--- a/apps/cli/src/commands/config.ts
+++ b/apps/cli/src/commands/config.ts
@@ -3,6 +3,7 @@ import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
import { resolveWorkspaceId } from '../api/workspace';
+import { CLI_PRODUCT_NAME } from '../constants/identity';
import {
type BoxTableRow,
formatCost,
@@ -177,7 +178,11 @@ export function registerConfigCommand(program: Command) {
const monthLabel = options.month || new Date().toISOString().slice(0, 7);
const mode = options.daily ? 'Daily' : 'Monthly';
- printBoxTable(columns, rows, `LobeHub Token Usage Report - ${mode} (${monthLabel})`);
+ printBoxTable(
+ columns,
+ rows,
+ `${CLI_PRODUCT_NAME} Token Usage Report - ${mode} (${monthLabel})`,
+ );
// Calendar heatmap - fetch past 12 months
const now = new Date();
diff --git a/apps/cli/src/commands/connect.ts b/apps/cli/src/commands/connect.ts
index a6b19a15f61..c4809c754dc 100644
--- a/apps/cli/src/commands/connect.ts
+++ b/apps/cli/src/commands/connect.ts
@@ -24,6 +24,12 @@ import type { Command } from 'commander';
import { createLambdaClient } from '../api/client';
import { resolveToken } from '../auth/resolveToken';
import { CLI_API_KEY_ENV } from '../constants/auth';
+import {
+ CLI_CONFIG_DIR_NAME,
+ CLI_CONNECT_SERVICE_NAME,
+ CLI_DISPLAY_NAME,
+ CLI_PRIMARY_BIN,
+} from '../constants/identity';
import { OFFICIAL_GATEWAY_URL } from '../constants/urls';
import {
appendLog,
@@ -65,7 +71,7 @@ import { executeToolCall } from '../tools';
import { cleanupAllProcesses } from '../tools/shell';
import { log, setVerbose } from '../utils/logger';
-const CONNECT_SERVICE_NAME = 'lobehub-connect.service';
+const CONNECT_SERVICE_NAME = CLI_CONNECT_SERVICE_NAME;
interface ConnectOptions {
daemon?: boolean;
@@ -394,7 +400,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
};
// Print device info
- info('─── LobeHub CLI ───');
+ info(`─── ${CLI_DISPLAY_NAME} ───`);
info(` Device ID : ${client.currentDeviceId}`);
info(` Hostname : ${os.hostname()}`);
info(` Platform : ${process.platform}`);
@@ -693,7 +699,7 @@ async function runConnect(options: ConnectOptions, isDaemonChild: boolean) {
error(`Authentication failed: ${reason}`);
error(
- `Run 'lh login', or set ${CLI_API_KEY_ENV} and run 'lh login --server <url>' to configure API key authentication.`,
+ `Run '${CLI_PRIMARY_BIN} login', or set ${CLI_API_KEY_ENV} and run '${CLI_PRIMARY_BIN} login --server <url>' to configure API key authentication.`,
);
cleanup();
process.exit(1);
@@ -1022,7 +1028,7 @@ function collectSystemInfo(): DeviceSystemInfo {
homePath: home,
musicPath: path.join(home, 'Music'),
picturesPath: path.join(home, 'Pictures'),
- userDataPath: path.join(home, '.lobehub'),
+ userDataPath: path.join(home, CLI_CONFIG_DIR_NAME),
videosPath: path.join(home, videosDir),
workingDirectory: process.cwd(),
};
diff --git a/apps/cli/src/commands/login.ts b/apps/cli/src/commands/login.ts
index 1b67e9d8579..954c023d5e3 100644
--- a/apps/cli/src/commands/login.ts
+++ b/apps/cli/src/commands/login.ts
@@ -7,7 +7,8 @@ import type { Command } from 'commander';
import { getUserIdFromApiKey } from '../auth/apiKey';
import { saveCredentials } from '../auth/credentials';
import { parseJwtSub } from '../auth/resolveToken';
-import { CLI_API_KEY_ENV } from '../constants/auth';
+import { readCliApiKeyEnv } from '../constants/auth';
+import { CLI_PRODUCT_NAME } from '../constants/identity';
import { OFFICIAL_SERVER_URL } from '../constants/urls';
import { registerDevice, resolveDeviceIdentity } from '../device/register';
import { loadSettings, normalizeUrl, saveSettings } from '../settings';
@@ -55,14 +56,16 @@ async function parseJsonResponse<T>(res: Response, endpoint: string): Promise<T>
export function registerLoginCommand(program: Command) {
program
.command('login')
- .description('Log in to LobeHub via browser (Device Code Flow) or configure API key server')
- .option('--server <url>', 'LobeHub server URL', OFFICIAL_SERVER_URL)
+ .description(
+ `Log in to ${CLI_PRODUCT_NAME} via browser (Device Code Flow) or configure API key server`,
+ )
+ .option('--server <url>', `${CLI_PRODUCT_NAME} server URL`, OFFICIAL_SERVER_URL)
.action(async (options: LoginOptions) => {
const serverUrl = normalizeUrl(options.server) || OFFICIAL_SERVER_URL;
log.info('Starting login...');
- const apiKey = process.env[CLI_API_KEY_ENV];
+ const apiKey = readCliApiKeyEnv();
if (apiKey) {
try {
await getUserIdFromApiKey(apiKey, serverUrl);
diff --git a/apps/cli/src/commands/man.ts b/apps/cli/src/commands/man.ts
index 6bfd31696b5..21a4f01ddf4 100644
--- a/apps/cli/src/commands/man.ts
+++ b/apps/cli/src/commands/man.ts
@@ -1,6 +1,7 @@
import type { Argument, Command } from 'commander';
-const ROOT_ALIASES = ['lobe', 'lobehub'];
+import { CLI_BIN_ALIASES as ROOT_ALIASES } from '../constants/identity';
+
const HELP_COMMAND_NAME = 'help';
interface DefinitionItem {
diff --git a/apps/cli/src/commands/provider.ts b/apps/cli/src/commands/provider.ts
index ec70fe86aad..5d67ea78b9c 100644
--- a/apps/cli/src/commands/provider.ts
+++ b/apps/cli/src/commands/provider.ts
@@ -2,6 +2,7 @@ import type { Command } from 'commander';
import pc from 'picocolors';
import { getTrpcClient } from '../api/client';
+import { CLI_PRODUCT_NAME } from '../constants/identity';
import { confirm, outputJson, printTable, truncate } from '../utils/format';
import { log } from '../utils/logger';
@@ -169,7 +170,7 @@ export function registerProviderCommand(program: Command) {
// lobehub is a platform-managed provider, users cannot configure its API key or base URL
if (id === 'lobehub' && (options.apiKey !== undefined || options.baseUrl !== undefined)) {
log.error(
- `Provider "lobehub" is managed by the LobeHub platform. You cannot set --api-key or --base-url for it.`,
+ `Provider "lobehub" is managed by the ${CLI_PRODUCT_NAME} platform. You cannot set --api-key or --base-url for it.`,
);
process.exit(1);
}
diff --git a/apps/cli/src/commands/update.ts b/apps/cli/src/commands/update.ts
index a00efd0c8cf..d299894240c 100644
--- a/apps/cli/src/commands/update.ts
+++ b/apps/cli/src/commands/update.ts
@@ -5,6 +5,7 @@ import type { Command } from 'commander';
import pc from 'picocolors';
import semver from 'semver';
+import { CLI_DISPLAY_NAME } from '../constants/identity';
// Pull package metadata from the shared `src/pkg.ts` module (resolved at the
// bundled entry's depth) rather than a local `require('../../package.json')`,
// which would point outside the package once bundled into dist/index.js.
@@ -117,7 +118,7 @@ function runInstall(command: string, args: string[]): Promise<void> {
export function registerUpdateCommand(program: Command) {
program
.command('update')
- .description('Update the LobeHub CLI to the latest published version')
+ .description(`Update the ${CLI_DISPLAY_NAME} to the latest published version`)
.option('--check', 'Only check for a newer version without installing')
.option('--tag <tag>', 'npm dist-tag to update to', 'latest')
.option(
diff --git a/apps/cli/src/constants/auth.ts b/apps/cli/src/constants/auth.ts
index de3602f00cf..074cf75a322 100644
--- a/apps/cli/src/constants/auth.ts
+++ b/apps/cli/src/constants/auth.ts
@@ -1 +1,10 @@
-export const CLI_API_KEY_ENV = 'LOBEHUB_CLI_API_KEY';
+import { CLI_API_KEY_ENV_NAMES } from './identity';
+
+/**
+ * The API key variable's primary name β€” what error messages tell users to set.
+ *
+ * Reading the environment goes through `readCliApiKeyEnv()` instead, which also
+ * accepts the older names in `CLI_API_KEY_ENV_NAMES`.
+ */
+export const CLI_API_KEY_ENV = CLI_API_KEY_ENV_NAMES[0]!;
+export { CLI_API_KEY_ENV_NAMES, readCliApiKeyEnv } from './identity';
diff --git a/apps/cli/src/constants/identity.ts b/apps/cli/src/constants/identity.ts
new file mode 100644
index 00000000000..0b9f18f88a4
--- /dev/null
+++ b/apps/cli/src/constants/identity.ts
@@ -0,0 +1,88 @@
+/**
+ * Every string that names the product, in one place.
+ *
+ * These were previously literals scattered across a dozen modules β€” the bin
+ * names in `utils/completion.ts`, the config directory in five separate files,
+ * the systemd unit name defined twice, the product name in a handful of
+ * descriptions and one agent-facing prompt. That worked while there was exactly
+ * one distribution, but it meant a white-label build had no seam: the strings
+ * are reached at runtime from paths no UI gating can intercept, and one of them
+ * (`buildNotifyProtocol`) is a prompt the model repeats back to the user.
+ *
+ * The values below are upstream's, unchanged, so the default build is
+ * byte-identical. A distribution replaces this module wholesale.
+ */
+
+/** Product name as it appears inside sentences. */
+export const CLI_PRODUCT_NAME = 'LobeHub';
+
+/** The CLI's own name, e.g. in `--help` and the connect banner. */
+export const CLI_DISPLAY_NAME = 'LobeHub CLI';
+
+/**
+ * The command users type. Also the man page's title (uppercased) and the name
+ * shown in "run `<bin> login`" hints.
+ */
+export const CLI_PRIMARY_BIN = 'lh';
+
+/** Additional command names installed alongside the primary one. */
+export const CLI_BIN_ALIASES: readonly string[] = ['lobe', 'lobehub'];
+
+/** Every installed command name β€” what shell completion has to bind to. */
+export const CLI_BIN_NAMES: readonly string[] = [CLI_PRIMARY_BIN, ...CLI_BIN_ALIASES];
+
+/**
+ * Shell function name emitted by `completion`.
+ *
+ * A shell identifier, so it must stay `[A-Za-z_][A-Za-z0-9_]*` β€” a distribution
+ * overriding this cannot use hyphens or spaces.
+ */
+export const CLI_COMPLETION_FUNCTION = '_lobehub_completion';
+
+/** Directory under $HOME holding settings, credentials and daemon state. */
+export const CLI_CONFIG_DIR_NAME = '.lobehub';
+
+/**
+ * Env var the generated completion script uses to hand `__complete` the
+ * current word index.
+ *
+ * Purely internal plumbing: the completion function sets it and the CLI reads
+ * it back within the same invocation, so a user never sets or sees it
+ * directly β€” unlike `CLI_API_KEY_ENV_NAMES`, there is no back-compat concern
+ * for a rebranded distribution, since both sides always come from the one
+ * binary running. Still collected here rather than left as a literal in
+ * `utils/completion.ts`/`commands/completion.ts`: it is one of the strings
+ * this module's doc comment above promises are all in one place, and it was
+ * the one that got missed the first time around.
+ */
+export const CLI_COMPLETION_CWORD_ENV = 'LOBEHUB_COMP_CWORD';
+
+/** systemd unit name for `connect service`. */
+export const CLI_CONNECT_SERVICE_NAME = 'lobehub-connect.service';
+
+/**
+ * Environment variable names the user may set, most preferred first.
+ *
+ * A list rather than a single name so a rebranded distribution can introduce
+ * its own prefix while still honouring anything already exported in a user's
+ * shell or CI config. Only variables the USER sets belong here β€” the ones the
+ * desktop app and the server inject (LOBEHUB_SERVER, LOBEHUB_JWT, the agent-run
+ * ids) are a cross-process contract and must be renamed on both sides at once.
+ */
+export const CLI_API_KEY_ENV_NAMES: readonly string[] = ['LOBEHUB_CLI_API_KEY'];
+export const CLI_HOME_ENV_NAMES: readonly string[] = ['LOBEHUB_CLI_HOME'];
+
+const firstEnvValue = (names: readonly string[]): string | undefined => {
+ for (const name of names) {
+ const value = process.env[name]?.trim();
+ if (value) return value;
+ }
+ return undefined;
+};
+
+/** API key from the environment, honouring every accepted variable name. */
+export const readCliApiKeyEnv = (): string | undefined => firstEnvValue(CLI_API_KEY_ENV_NAMES);
+
+/** Config directory name, overridable per-install by the home env var. */
+export const resolveCliDirName = (): string =>
+ firstEnvValue(CLI_HOME_ENV_NAMES) ?? CLI_CONFIG_DIR_NAME;
diff --git a/apps/cli/src/daemon/manager.ts b/apps/cli/src/daemon/manager.ts
index 7f7684b1331..d49b4df7785 100644
--- a/apps/cli/src/daemon/manager.ts
+++ b/apps/cli/src/daemon/manager.ts
@@ -3,10 +3,12 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+import { CLI_CONFIG_DIR_NAME } from '../constants/identity';
+
const MAX_LOG_SIZE = 5 * 1024 * 1024; // 5MB
function getLobehubDir() {
- return path.join(os.homedir(), '.lobehub');
+ return path.join(os.homedir(), CLI_CONFIG_DIR_NAME);
}
function getPidPath() {
diff --git a/apps/cli/src/daemon/taskRegistry.ts b/apps/cli/src/daemon/taskRegistry.ts
index 9e1e537189d..60103e1cd47 100644
--- a/apps/cli/src/daemon/taskRegistry.ts
+++ b/apps/cli/src/daemon/taskRegistry.ts
@@ -2,6 +2,8 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+import { CLI_CONFIG_DIR_NAME } from '../constants/identity';
+
export interface TaskEntry {
agentId?: string;
agentType: 'hermes' | 'openclaw';
@@ -19,7 +21,7 @@ export interface TaskEntry {
}
function getRegistryPath(): string {
- return path.join(os.homedir(), '.lobehub', 'task-registry.json');
+ return path.join(os.homedir(), CLI_CONFIG_DIR_NAME, 'task-registry.json');
}
function readRegistry(): Record<string, TaskEntry> {
diff --git a/apps/cli/src/man/roff.ts b/apps/cli/src/man/roff.ts
index acbe282773b..312c23ae80b 100644
--- a/apps/cli/src/man/roff.ts
+++ b/apps/cli/src/man/roff.ts
@@ -1,6 +1,14 @@
import type { Command } from 'commander';
-const ROOT_ALIASES = ['lobe', 'lobehub'];
+import {
+ CLI_BIN_ALIASES as ROOT_ALIASES,
+ CLI_DISPLAY_NAME,
+ CLI_HOME_ENV_NAMES,
+ CLI_PRIMARY_BIN,
+ CLI_PRODUCT_NAME,
+} from '../constants/identity';
+import { cliPackageName } from '../pkg';
+
const HELP_COMMAND_NAME = 'help';
interface RoffDefinition {
@@ -68,14 +76,14 @@ export function generateRootManPage(program: Command, version: string) {
const lines = [
'.\\" Code generated by `npm run man:generate`; DO NOT EDIT.',
'.\\" Manual command details come from the Commander command tree.',
- `.TH LH 1 "" "${escapeRoff(`@lobehub/cli ${version}`)}" "User Commands"`,
+ `.TH ${CLI_PRIMARY_BIN.toUpperCase()} 1 "" "${escapeRoff(`${cliPackageName} ${version}`)}" "User Commands"`,
'.SH NAME',
- `lh \\- ${escapeRoff(program.description() || 'LobeHub CLI')}`,
+ `${CLI_PRIMARY_BIN} \\- ${escapeRoff(program.description() || CLI_DISPLAY_NAME)}`,
'.SH SYNOPSIS',
...formatSynopsisLines(),
'.SH DESCRIPTION',
escapeRoff(
- `${program.name()} is the command-line interface for LobeHub. It provides authentication, device gateway connectivity, content generation, resource search, and management commands for agents, files, models, providers, plugins, knowledge bases, threads, topics, and related resources.`,
+ `${program.name()} is the command-line interface for ${CLI_PRODUCT_NAME}. It provides authentication, device gateway connectivity, content generation, resource search, and management commands for agents, files, models, providers, plugins, knowledge bases, threads, topics, and related resources.`,
),
'.PP',
'For command-specific manuals, use the built-in manual command:',
@@ -96,7 +104,7 @@ export function generateRootManPage(program: Command, version: string) {
]),
'.PP',
'The base directory can be overridden with the',
- '.B LOBEHUB_CLI_HOME',
+ `.B ${CLI_HOME_ENV_NAMES[0]}`,
'environment variable.',
'.SH EXAMPLES',
...EXAMPLES.flatMap((example) => [
@@ -117,7 +125,7 @@ export function generateAliasManPage(target: string) {
}
function formatSynopsisLines() {
- return ['lh', ...ROOT_ALIASES]
+ return [CLI_PRIMARY_BIN, ...ROOT_ALIASES]
.flatMap((binary) => [`.B ${binary}`, '[\\fIOPTION\\fR]...', '[\\fICOMMAND\\fR]', '.br'])
.slice(0, -1);
}
diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.ts
index 283dc0b2dda..695c18e17f0 100644
--- a/apps/cli/src/program.ts
+++ b/apps/cli/src/program.ts
@@ -37,6 +37,7 @@ import { registerUpdateCommand } from './commands/update';
import { registerUserCommand } from './commands/user';
import { registerVerifyCommand } from './commands/verify';
import { registerAcceptanceCommands } from './commands/verifyAcceptance';
+import { CLI_DISPLAY_NAME, CLI_PRIMARY_BIN, CLI_PRODUCT_NAME } from './constants/identity';
import { cliVersion } from './pkg';
import { executeToolCall } from './tools';
@@ -44,8 +45,8 @@ export function createProgram() {
const program = new Command();
program
- .name('lh')
- .description('LobeHub CLI - manage and connect to LobeHub services')
+ .name(CLI_PRIMARY_BIN)
+ .description(`${CLI_DISPLAY_NAME} - manage and connect to ${CLI_PRODUCT_NAME} services`)
.version(cliVersion);
const internalToolWorker = program
diff --git a/apps/cli/src/service/connect.ts b/apps/cli/src/service/connect.ts
index 1b9c5cfb3b2..9172757e474 100644
--- a/apps/cli/src/service/connect.ts
+++ b/apps/cli/src/service/connect.ts
@@ -4,10 +4,16 @@ import os from 'node:os';
import path from 'node:path';
import { loadCredentials } from '../auth/credentials';
-import { CLI_API_KEY_ENV } from '../constants/auth';
+import { CLI_API_KEY_ENV, readCliApiKeyEnv } from '../constants/auth';
+import {
+ CLI_CONNECT_SERVICE_NAME,
+ CLI_DISPLAY_NAME,
+ CLI_PRIMARY_BIN,
+ resolveCliDirName,
+} from '../constants/identity';
import { getRunningDaemonPid } from '../daemon/manager';
-const SERVICE_NAME = 'lobehub-connect.service';
+const SERVICE_NAME = CLI_CONNECT_SERVICE_NAME;
const ENV_NAME_PATTERN = /^[A-Z_]\w*$/i;
const SERVICE_ENV_FILE_NAME = 'connect-service.env';
@@ -38,7 +44,7 @@ function getUserServiceDir(): string {
}
function getCliHomeDir(): string {
- return path.join(os.homedir(), process.env.LOBEHUB_CLI_HOME || '.lobehub');
+ return path.join(os.homedir(), resolveCliDirName());
}
function getServiceEnvFilePath(): string {
@@ -70,7 +76,7 @@ function renderUnit(): string {
return [
'[Unit]',
- 'Description=LobeHub CLI connect service',
+ `Description=${CLI_DISPLAY_NAME} connect service`,
'After=network-online.target',
'Wants=network-online.target',
'StartLimitIntervalSec=60',
@@ -159,10 +165,10 @@ function assertNoConnectDaemonRunning(): void {
}
function assertConnectServiceAuthAvailable(): void {
- if (process.env.LOBEHUB_JWT || process.env[CLI_API_KEY_ENV] || loadCredentials()) return;
+ if (process.env.LOBEHUB_JWT || readCliApiKeyEnv() || loadCredentials()) return;
throw new Error(
- `No authentication found. Run 'lh login' first, or set ${CLI_API_KEY_ENV} before starting the connect service.`,
+ `No authentication found. Run '${CLI_PRIMARY_BIN} login' first, or set ${CLI_API_KEY_ENV} before starting the connect service.`,
);
}
diff --git a/apps/cli/src/settings/index.ts b/apps/cli/src/settings/index.ts
index 7c3e1d1e096..5b150d61340 100644
--- a/apps/cli/src/settings/index.ts
+++ b/apps/cli/src/settings/index.ts
@@ -3,6 +3,7 @@ import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
+import { resolveCliDirName } from '../constants/identity';
import { OFFICIAL_AGENT_GATEWAY_URL, OFFICIAL_SERVER_URL } from '../constants/urls';
import { log } from '../utils/logger';
@@ -12,7 +13,7 @@ export interface StoredSettings {
serverUrl?: string;
}
-const LOBEHUB_DIR_NAME = process.env.LOBEHUB_CLI_HOME || '.lobehub';
+const LOBEHUB_DIR_NAME = resolveCliDirName();
const SETTINGS_DIR = path.join(os.homedir(), LOBEHUB_DIR_NAME);
const SETTINGS_FILE = path.join(SETTINGS_DIR, 'settings.json');
// Kept in its own file rather than settings.json, which is unlinked whenever
diff --git a/apps/cli/src/tools/heteroTask.ts b/apps/cli/src/tools/heteroTask.ts
index d2d21a4993a..2fee588e445 100644
--- a/apps/cli/src/tools/heteroTask.ts
+++ b/apps/cli/src/tools/heteroTask.ts
@@ -6,6 +6,7 @@ import path from 'node:path';
import type { RemoteHeterogeneousAgentType } from '@lobechat/heterogeneous-agents';
import { getTrpcClient } from '../api/client';
+import { CLI_PRODUCT_NAME, resolveCliDirName } from '../constants/identity';
import { getTask, listTasks, removeTask, saveTask } from '../daemon/taskRegistry';
import { log } from '../utils/logger';
@@ -13,7 +14,7 @@ import { log } from '../utils/logger';
// Maps topicId β†’ hermes session_id so multi-turn conversations can resume
// the same session across separate `runHeteroTask` invocations.
-const LOBEHUB_DIR_NAME = process.env.LOBEHUB_CLI_HOME || '.lobehub';
+const LOBEHUB_DIR_NAME = resolveCliDirName();
const HERMES_SESSIONS_FILE = path.join(os.homedir(), LOBEHUB_DIR_NAME, 'hermes-sessions.json');
function parseHermesSessionId(stderr: string): string | undefined {
@@ -144,8 +145,8 @@ async function sendTerminalSignal(
*/
function buildNotifyProtocol(lhPath: string, topicId: string): string {
return (
- `## Context: This task was dispatched by LobeHub\n\n` +
- `This conversation / task was sent to you by the **LobeHub platform** on behalf of a user. You are running as a background agent; the user is waiting for your response inside the LobeHub chat interface.\n\n` +
+ `## Context: This task was dispatched by ${CLI_PRODUCT_NAME}\n\n` +
+ `This conversation / task was sent to you by the **${CLI_PRODUCT_NAME} platform** on behalf of a user. You are running as a background agent; the user is waiting for your response inside the ${CLI_PRODUCT_NAME} chat interface.\n\n` +
`**When to call notify**: any time you have something meaningful to tell the user β€” a key finding, a decision you made, a result, a question, or your final answer. Think of it as speaking directly to the user in the chat window.\n\n` +
`**What to hide**: internal work details such as tool call sequences, file reads, intermediate command output, retries, or low-level reasoning steps. The user cares about outcomes and insights, not your step-by-step mechanics.\n\n` +
`## Sending messages back to the user\n\n` +
diff --git a/apps/cli/src/tools/localSystemRuntime.ts b/apps/cli/src/tools/localSystemRuntime.ts
index c1e21aa8b8a..4db6c50a68c 100644
--- a/apps/cli/src/tools/localSystemRuntime.ts
+++ b/apps/cli/src/tools/localSystemRuntime.ts
@@ -6,6 +6,7 @@ import type {
import { createFileSearchModule } from '@lobechat/local-file-shell';
import { type ILocalSystemService, LocalSystemExecutionRuntime } from '@lobechat/tool-runtime';
+import { CLI_DISPLAY_NAME } from '../constants/identity';
import { editLocalFile, grepContent, listLocalFiles, readLocalFile, writeLocalFile } from './file';
import { getCommandOutput, killCommand, runCommand } from './shell';
@@ -28,7 +29,7 @@ export interface LocalSystemToolOutput {
* interface just requires them, so we fail loudly if one is ever reached.
*/
const unsupported = (method: string) => (): Promise<never> =>
- Promise.reject(new Error(`${method} is not supported by the LobeHub CLI`));
+ Promise.reject(new Error(`${method} is not supported by the ${CLI_DISPLAY_NAME}`));
const DEFAULT_FILE_SEARCH_LIMIT = 100;
diff --git a/apps/cli/src/utils/completion.ts b/apps/cli/src/utils/completion.ts
index 551442d7f61..01321a482eb 100644
--- a/apps/cli/src/utils/completion.ts
+++ b/apps/cli/src/utils/completion.ts
@@ -1,7 +1,12 @@
import type { Command, Option } from 'commander';
import { InvalidArgumentError } from 'commander';
-const CLI_BIN_NAMES = ['lh', 'lobe', 'lobehub'] as const;
+import {
+ CLI_BIN_NAMES,
+ CLI_COMPLETION_CWORD_ENV,
+ CLI_COMPLETION_FUNCTION,
+} from '../constants/identity';
+
const SUPPORTED_SHELLS = ['bash', 'zsh'] as const;
type SupportedShell = (typeof SUPPORTED_SHELLS)[number];
@@ -133,25 +138,25 @@ export function renderCompletionScript(shell: SupportedShell) {
if (shell === 'bash') {
return [
'# shellcheck shell=bash',
- '_lobehub_completion() {',
+ `${CLI_COMPLETION_FUNCTION}() {`,
" local IFS=$'\\n'",
' local current_index=$((COMP_CWORD - 1))',
' local completions',
- ' completions=$(LOBEHUB_COMP_CWORD="$current_index" "${COMP_WORDS[0]}" __complete "${COMP_WORDS[@]:1}")',
+ ` completions=$(${CLI_COMPLETION_CWORD_ENV}="$current_index" "\${COMP_WORDS[0]}" __complete "\${COMP_WORDS[@]:1}")`,
' COMPREPLY=($(printf \'%s\\n\' "$completions"))',
'}',
- `complete -o nosort -F _lobehub_completion ${CLI_BIN_NAMES.join(' ')}`,
+ `complete -o nosort -F ${CLI_COMPLETION_FUNCTION} ${CLI_BIN_NAMES.join(' ')}`,
].join('\n');
}
return [
`#compdef ${CLI_BIN_NAMES.join(' ')}`,
- '_lobehub_completion() {',
+ `${CLI_COMPLETION_FUNCTION}() {`,
' local -a completions',
' local current_index=$((CURRENT - 2))',
- ' completions=("${(@f)$(LOBEHUB_COMP_CWORD="$current_index" "$words[1]" __complete "${(@)words[@]:1}")}")',
+ ` completions=("\${(@f)$(${CLI_COMPLETION_CWORD_ENV}="$current_index" "$words[1]" __complete "\${(@)words[@]:1}")}")`,
" _describe 'values' completions",
'}',
- `compdef _lobehub_completion ${CLI_BIN_NAMES.join(' ')}`,
+ `compdef ${CLI_COMPLETION_FUNCTION} ${CLI_BIN_NAMES.join(' ')}`,
].join('\n');
}
diff --git a/apps/cli/src/utils/skillLocator.ts b/apps/cli/src/utils/skillLocator.ts
index e4c30277114..c4b6fb5b2b9 100644
--- a/apps/cli/src/utils/skillLocator.ts
+++ b/apps/cli/src/utils/skillLocator.ts
@@ -2,6 +2,8 @@ import { existsSync, readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
+import { cliPackageName } from '../pkg';
+
export interface BundledSkill {
cliRoot: string;
skillDir: string;
@@ -19,7 +21,7 @@ export function findCliRoot(startDir: string): string | undefined {
if (existsSync(pkgPath)) {
try {
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
- if (pkg && pkg.name === '@lobehub/cli') return dir;
+ if (pkg && pkg.name === cliPackageName) return dir;
} catch {
// Not a readable/valid package.json β€” keep walking up.
}
@@ -40,7 +42,7 @@ export function locateBundledSkill(
const cliRoot = findCliRoot(startDir);
if (!cliRoot) {
throw new Error(
- `Could not locate the @lobehub/cli package root walking up from ${startDir}. ` +
+ `Could not locate the ${cliPackageName} package root walking up from ${startDir}. ` +
'The CLI install may be corrupted.',
);
}
@@ -49,7 +51,7 @@ export function locateBundledSkill(
if (!existsSync(skillDir)) {
throw new Error(
`Bundled skill "${skillName}" not found at ${skillDir}. ` +
- 'The @lobehub/cli install may be missing its skills/ directory.',
+ `The ${cliPackageName} install may be missing its skills/ directory.`,
);
}
diff --git a/packages/business/const/src/index.ts b/packages/business/const/src/index.ts
index 8812e0f8b83..2282d422665 100644
--- a/packages/business/const/src/index.ts
+++ b/packages/business/const/src/index.ts
@@ -14,6 +14,24 @@ export const ENABLE_BUSINESS_FEATURES = false;
*/
export const AGENT_ONBOARDING_ENABLED = false;
+/**
+ * Prefix on every issued API key.
+ *
+ * Users see and paste this string, so on a white-label distribution it is the
+ * most directly visible piece of vendor branding there is β€” it travels in
+ * support tickets, `.env` files and screenshots long after the UI has been
+ * rebranded.
+ *
+ * It is also load-bearing: `validateApiKeyFormat` is what the OpenAPI auth
+ * middleware uses to tell an API key from an OIDC JWT, so generation and
+ * validation must read the SAME constant or every key stops authenticating.
+ *
+ * Changing it does NOT migrate keys already in the database β€” those stop
+ * matching the format check and are rejected as malformed. A distribution that
+ * has issued keys should accept both spellings for a period instead.
+ */
+export const API_KEY_PREFIX = 'sk-lh-';
+
export const OFFICIAL_PROVIDER_DISABLE_ERROR = 'The official provider cannot be disabled.';
export const isOfficialProvider = (id: string) =>
diff --git a/packages/database/src/models/__tests__/apiKey.test.ts b/packages/database/src/models/__tests__/apiKey.test.ts
index 38af06f3e1e..22cd65eb184 100644
--- a/packages/database/src/models/__tests__/apiKey.test.ts
+++ b/packages/database/src/models/__tests__/apiKey.test.ts
@@ -1,4 +1,5 @@
// @vitest-environment node
+import { API_KEY_PREFIX, validateApiKeyFormat } from '@lobechat/utils/apiKey';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
@@ -45,7 +46,7 @@ describe('ApiKeyModel', () => {
expect(result.name).toBe(params.name);
expect(result.enabled).toBe(params.enabled);
expect(result.key).toBeDefined();
- expect(result.key).not.toMatch(/^sk-lh-[\da-z]{16}$/);
+ expect(validateApiKeyFormat(result.key)).toBe(false);
expect(result.userId).toBe(userId);
const apiKey = await serverDB.query.apiKeys.findFirst({
@@ -72,7 +73,8 @@ describe('ApiKeyModel', () => {
it('reveals plaintext only through the explicit one-time create method', async () => {
const created = await apiKeyModel.createWithPlaintext({ name: 'One-time Key' });
- expect(created.key).toMatch(/^sk-lh-[\da-z]{16}$/);
+ expect(created.key.startsWith(API_KEY_PREFIX)).toBe(true);
+ expect(created.key.slice(API_KEY_PREFIX.length)).toMatch(/^[\da-z]{16}$/);
const stored = await apiKeyModel.findById(created.id);
expect(stored?.key).not.toBe(created.key);
@@ -155,7 +157,8 @@ describe('ApiKeyModel', () => {
const keys = await apiKeyModel.query();
expect(keys).toHaveLength(2);
- expect(keys[0].key).toMatch(/^sk-lh-[\da-z]{16}$/);
+ expect(keys[0].key.startsWith(API_KEY_PREFIX)).toBe(true);
+ expect(keys[0].key.slice(API_KEY_PREFIX.length)).toMatch(/^[\da-z]{16}$/);
});
it('keeps metadata queries free of decrypted plaintext', async () => {
@@ -203,7 +206,8 @@ describe('ApiKeyModel', () => {
expect(keys).toHaveLength(2);
expect(staleResult).toMatchObject({ key: '', keyDecryptionFailed: true });
expect(freshResult).toMatchObject({ keyDecryptionFailed: false });
- expect(freshResult?.key).toMatch(/^sk-lh-[\da-z]{16}$/);
+ expect(freshResult?.key.startsWith(API_KEY_PREFIX)).toBe(true);
+ expect(freshResult?.key.slice(API_KEY_PREFIX.length)).toMatch(/^[\da-z]{16}$/);
});
it('lets workspace admins list all keys while members only see their own', async () => {
@@ -259,7 +263,7 @@ describe('ApiKeyModel', () => {
describe('findByKey', () => {
it('should find API key by key value without custom hasher', async () => {
// Use a valid hex format key since validateApiKeyFormat checks for hex pattern
- const validKey = 'sk-lh-abcdef0123456789';
+ const validKey = `${API_KEY_PREFIX}abcdef0123456789`;
await serverDB.insert(apiKeys).values({
enabled: true,
key: validKey,
@@ -282,7 +286,7 @@ describe('ApiKeyModel', () => {
});
it('should return undefined for non-existent key', async () => {
- const found = await apiKeyModel.findByKey('sk-lh-0123456789abcdef');
+ const found = await apiKeyModel.findByKey(`${API_KEY_PREFIX}0123456789abcdef`);
expect(found).toBeUndefined();
});
@@ -294,7 +298,7 @@ describe('ApiKeyModel', () => {
futureDate.setFullYear(futureDate.getFullYear() + 1);
// Use a valid hex format key
- const validKey = 'sk-lh-0123456789abcdef';
+ const validKey = `${API_KEY_PREFIX}0123456789abcdef`;
await serverDB.insert(apiKeys).values({
enabled: true,
expiresAt: futureDate,
@@ -311,7 +315,7 @@ describe('ApiKeyModel', () => {
it('should validate enabled key without expiration with valid hex format', async () => {
// Use a valid hex format key
- const validKey = 'sk-lh-fedcba9876543210';
+ const validKey = `${API_KEY_PREFIX}fedcba9876543210`;
await serverDB.insert(apiKeys).values({
enabled: true,
key: validKey,
@@ -326,13 +330,13 @@ describe('ApiKeyModel', () => {
});
it('should reject non-existent key', async () => {
- const isValid = await apiKeyModel.validateKey('sk-lh-0123456789abcdef');
+ const isValid = await apiKeyModel.validateKey(`${API_KEY_PREFIX}0123456789abcdef`);
expect(isValid).toBe(false);
});
it('should reject disabled key', async () => {
- const validKey = 'sk-lh-1111111111111111';
+ const validKey = `${API_KEY_PREFIX}1111111111111111`;
await serverDB.insert(apiKeys).values({
enabled: false,
key: validKey,
@@ -350,7 +354,7 @@ describe('ApiKeyModel', () => {
const pastDate = new Date();
pastDate.setFullYear(pastDate.getFullYear() - 1);
- const validKey = 'sk-lh-2222222222222222';
+ const validKey = `${API_KEY_PREFIX}2222222222222222`;
await serverDB.insert(apiKeys).values({
enabled: true,
expiresAt: pastDate,
diff --git a/packages/openapi/src/middleware/auth.test.ts b/packages/openapi/src/middleware/auth.test.ts
index 7a4d5e26e96..58821b158b6 100644
--- a/packages/openapi/src/middleware/auth.test.ts
+++ b/packages/openapi/src/middleware/auth.test.ts
@@ -1,3 +1,4 @@
+import { API_KEY_PREFIX } from '@lobechat/utils/apiKey';
import { Hono } from 'hono';
import { HTTPException } from 'hono/http-exception';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -155,7 +156,7 @@ describe('OpenAPI auth middleware', () => {
});
it('should expose the workspace scope of an API Key to downstream middleware', async () => {
- mockExtractBearerToken.mockReturnValueOnce('sk-lh-workspacekey01');
+ mockExtractBearerToken.mockReturnValueOnce(`${API_KEY_PREFIX}workspacekey01`);
mockValidateApiKeyFormat.mockReturnValueOnce(true);
mockApiKeyFindByKey.mockResolvedValueOnce({
enabled: true,
@@ -167,7 +168,7 @@ describe('OpenAPI auth middleware', () => {
});
const response = await createApp().request('/protected', {
- headers: { Authorization: 'Bearer sk-lh-workspacekey01' },
+ headers: { Authorization: `Bearer ${API_KEY_PREFIX}workspacekey01` },
});
await expect(response.json()).resolves.toEqual({
@@ -179,7 +180,7 @@ describe('OpenAPI auth middleware', () => {
});
it('should expose a null workspace scope for a personal API Key', async () => {
- mockExtractBearerToken.mockReturnValueOnce('sk-lh-personalkey001');
+ mockExtractBearerToken.mockReturnValueOnce(`${API_KEY_PREFIX}personalkey001`);
mockValidateApiKeyFormat.mockReturnValueOnce(true);
mockApiKeyFindByKey.mockResolvedValueOnce({
enabled: true,
@@ -191,7 +192,7 @@ describe('OpenAPI auth middleware', () => {
});
const response = await createApp().request('/protected', {
- headers: { Authorization: 'Bearer sk-lh-personalkey001' },
+ headers: { Authorization: `Bearer ${API_KEY_PREFIX}personalkey001` },
});
await expect(response.json()).resolves.toEqual({
@@ -203,7 +204,7 @@ describe('OpenAPI auth middleware', () => {
});
it('should re-read API Key authorization changes on every request', async () => {
- mockExtractBearerToken.mockReturnValue('sk-lh-workspacekey01');
+ mockExtractBearerToken.mockReturnValue(`${API_KEY_PREFIX}workspacekey01`);
mockValidateApiKeyFormat.mockReturnValue(true);
mockApiKeyFindByKey
.mockResolvedValueOnce({
@@ -229,14 +230,14 @@ describe('OpenAPI auth middleware', () => {
expect(
(
await app.request('/protected', {
- headers: { Authorization: 'Bearer sk-lh-workspacekey01' },
+ headers: { Authorization: `Bearer ${API_KEY_PREFIX}workspacekey01` },
})
).status,
).toBe(200);
expect(
(
await app.request('/protected', {
- headers: { Authorization: 'Bearer sk-lh-workspacekey01' },
+ headers: { Authorization: `Bearer ${API_KEY_PREFIX}workspacekey01` },
})
).status,
).toBe(401);
diff --git a/packages/openapi/src/middleware/auth.ts b/packages/openapi/src/middleware/auth.ts
index acfa87c1595..b46d4f3ae52 100644
--- a/packages/openapi/src/middleware/auth.ts
+++ b/packages/openapi/src/middleware/auth.ts
@@ -45,7 +45,7 @@ export const userAuthMiddleware = async (c: Context, next: Next) => {
if (bearerToken) {
log('Bearer token received: %s...', bearerToken.slice(0, 10));
- // Check if bearerToken matches API Key format (sk-lh-{16 alphanumeric chars})
+ // Check if bearerToken matches API Key format (prefix + 16 alphanumeric chars)
const isApiKeyFormat = validateApiKeyFormat(bearerToken);
log('API Key format validation result: %s', isApiKeyFormat);
diff --git a/packages/openapi/src/spec.ts b/packages/openapi/src/spec.ts
index 1cacd618cf1..2b480651374 100644
--- a/packages/openapi/src/spec.ts
+++ b/packages/openapi/src/spec.ts
@@ -1,3 +1,4 @@
+import { API_KEY_PREFIX } from '@lobechat/utils/apiKey';
import { generateSpecs } from 'hono-openapi';
import { API_KEY_SCOPES } from '@/const/apiKeyScope';
@@ -693,7 +694,7 @@ export const buildSpecDocument = async (app: GenerateSpecsApp) => {
},
securitySchemes: {
bearerAuth: {
- bearerFormat: 'API Key (sk-lh-...) or OIDC JWT',
+ bearerFormat: `API Key (${API_KEY_PREFIX}...) or OIDC JWT`,
scheme: 'bearer',
type: 'http',
},
diff --git a/packages/trpc/src/lambda/context.test.ts b/packages/trpc/src/lambda/context.test.ts
index e1fe3f6ff7c..ea85b3e7b83 100644
--- a/packages/trpc/src/lambda/context.test.ts
+++ b/packages/trpc/src/lambda/context.test.ts
@@ -1,3 +1,4 @@
+import { API_KEY_PREFIX } from '@lobechat/utils/apiKey';
import { NextRequest } from 'next/server';
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -250,7 +251,7 @@ describe('createLambdaContext', () => {
const request = new NextRequest('https://example.com/trpc/lambda', {
headers: {
- 'X-API-Key': 'sk-lh-aaaaaaaaaaaaaaaa',
+ 'X-API-Key': `${API_KEY_PREFIX}aaaaaaaaaaaaaaaa`,
},
});
@@ -283,7 +284,7 @@ describe('createLambdaContext', () => {
const request = new NextRequest('https://example.com/trpc/lambda', {
headers: {
- 'X-API-Key': 'sk-lh-aaaaaaaaaaaaaaaa',
+ 'X-API-Key': `${API_KEY_PREFIX}aaaaaaaaaaaaaaaa`,
'X-Workspace-Id': 'ws-1',
},
});
@@ -300,7 +301,7 @@ describe('createLambdaContext', () => {
const request = new NextRequest('https://example.com/trpc/lambda', {
headers: {
- 'X-API-Key': 'sk-lh-aaaaaaaaaaaaaaaa',
+ 'X-API-Key': `${API_KEY_PREFIX}aaaaaaaaaaaaaaaa`,
'X-Workspace-Id': 'ws-2',
},
});
@@ -316,7 +317,7 @@ describe('createLambdaContext', () => {
const request = new NextRequest('https://example.com/trpc/lambda', {
headers: {
- 'X-API-Key': 'sk-lh-aaaaaaaaaaaaaaaa',
+ 'X-API-Key': `${API_KEY_PREFIX}aaaaaaaaaaaaaaaa`,
},
});
@@ -332,7 +333,7 @@ describe('createLambdaContext', () => {
const request = new NextRequest('https://example.com/trpc/lambda', {
headers: {
- 'X-API-Key': 'sk-lh-aaaaaaaaaaaaaaaa',
+ 'X-API-Key': `${API_KEY_PREFIX}aaaaaaaaaaaaaaaa`,
'X-Workspace-Id': 'ws-1',
},
});
@@ -353,7 +354,7 @@ describe('createLambdaContext', () => {
const request = new NextRequest('https://example.com/trpc/lambda', {
headers: {
- 'X-API-Key': 'sk-lh-aaaaaaaaaaaaaaaa',
+ 'X-API-Key': `${API_KEY_PREFIX}aaaaaaaaaaaaaaaa`,
'X-Workspace-Id': 'ws-1',
},
});
@@ -370,7 +371,7 @@ describe('createLambdaContext', () => {
const request = new NextRequest('https://example.com/trpc/lambda', {
headers: {
- 'X-API-Key': 'sk-lh-aaaaaaaaaaaaaaaa',
+ 'X-API-Key': `${API_KEY_PREFIX}aaaaaaaaaaaaaaaa`,
'X-Workspace-Id': 'ws-1',
},
});
@@ -387,7 +388,7 @@ describe('createLambdaContext', () => {
const request = new NextRequest('https://example.com/trpc/lambda', {
headers: {
'Oidc-Auth': 'oidc-token',
- 'X-API-Key': 'sk-lh-bbbbbbbbbbbbbbbb',
+ 'X-API-Key': `${API_KEY_PREFIX}bbbbbbbbbbbbbbbb`,
},
});
diff --git a/packages/utils/src/apiKey.test.ts b/packages/utils/src/apiKey.test.ts
index 61fbd1ddbac..2d1a2d92c9d 100644
--- a/packages/utils/src/apiKey.test.ts
+++ b/packages/utils/src/apiKey.test.ts
@@ -1,17 +1,18 @@
import { describe, expect, it } from 'vitest';
-import { generateApiKey, isApiKeyExpired, validateApiKeyFormat } from './apiKey';
+import { API_KEY_PREFIX, generateApiKey, isApiKeyExpired, validateApiKeyFormat } from './apiKey';
describe('apiKey', () => {
describe('generateApiKey', () => {
it('should generate API key with correct format', () => {
const apiKey = generateApiKey();
- expect(apiKey).toMatch(/^sk-lh-[\da-z]{16}$/);
+ expect(apiKey.startsWith(API_KEY_PREFIX)).toBe(true);
+ expect(apiKey.slice(API_KEY_PREFIX.length)).toMatch(/^[\da-z]{16}$/);
});
it('should generate API key with correct length', () => {
const apiKey = generateApiKey();
- expect(apiKey).toHaveLength(22); // 'sk-lh-' (6) + 16 characters
+ expect(apiKey).toHaveLength(API_KEY_PREFIX.length + 16);
});
it('should generate unique API keys', () => {
@@ -25,12 +26,12 @@ describe('apiKey', () => {
it('should start with lb- prefix', () => {
const apiKey = generateApiKey();
- expect(apiKey.startsWith('sk-lh-')).toBe(true);
+ expect(apiKey.startsWith(API_KEY_PREFIX)).toBe(true);
});
it('should only contain lowercase alphanumeric characters after prefix', () => {
const apiKey = generateApiKey();
- const randomPart = apiKey.slice(6); // Remove 'sk-lh-' prefix
+ const randomPart = apiKey.slice(API_KEY_PREFIX.length);
expect(randomPart).toMatch(/^[\da-z]+$/);
});
});
@@ -67,26 +68,26 @@ describe('apiKey', () => {
describe('validateApiKeyFormat', () => {
it('should validate correct API key format', () => {
- const validKey = 'sk-lh-1234567890abcdef';
+ const validKey = `${API_KEY_PREFIX}1234567890abcdef`;
expect(validateApiKeyFormat(validKey)).toBe(true);
});
it('should accept keys with only numbers', () => {
- const validKey = 'sk-lh-1234567890123456';
+ const validKey = `${API_KEY_PREFIX}1234567890123456`;
expect(validateApiKeyFormat(validKey)).toBe(true);
});
it('should accept keys with only lowercase letters', () => {
- const validKey = 'sk-lh-abcdefabcdefabcd';
+ const validKey = `${API_KEY_PREFIX}abcdefabcdefabcd`;
expect(validateApiKeyFormat(validKey)).toBe(true);
});
it('should accept keys with mixed alphanumeric characters', () => {
- const validKey = 'sk-lh-abc123def456789a';
+ const validKey = `${API_KEY_PREFIX}abc123def456789a`;
expect(validateApiKeyFormat(validKey)).toBe(true);
});
- it('should reject keys without sk-lh- prefix', () => {
+ it('should reject keys without the configured prefix', () => {
const invalidKey = '1234567890abcdef';
expect(validateApiKeyFormat(invalidKey)).toBe(false);
});
@@ -97,22 +98,22 @@ describe('apiKey', () => {
});
it('should reject keys that are too short', () => {
- const invalidKey = 'sk-lh-123456789abcde';
+ const invalidKey = `${API_KEY_PREFIX}123456789abcde`;
expect(validateApiKeyFormat(invalidKey)).toBe(false);
});
it('should reject keys that are too long', () => {
- const invalidKey = 'sk-lh-1234567890abcdef0';
+ const invalidKey = `${API_KEY_PREFIX}1234567890abcdef0`;
expect(validateApiKeyFormat(invalidKey)).toBe(false);
});
it('should reject keys with uppercase letters', () => {
- const invalidKey = 'sk-lh-1234567890ABCDEF';
+ const invalidKey = `${API_KEY_PREFIX}1234567890ABCDEF`;
expect(validateApiKeyFormat(invalidKey)).toBe(false);
});
it('should reject keys with special characters', () => {
- const invalidKey = 'sk-lh-1234567890abcd-f';
+ const invalidKey = `${API_KEY_PREFIX}1234567890abcd-f`;
expect(validateApiKeyFormat(invalidKey)).toBe(false);
});
@@ -121,7 +122,7 @@ describe('apiKey', () => {
});
it('should reject keys with spaces', () => {
- const invalidKey = 'sk-lh-1234567890abcd f';
+ const invalidKey = `${API_KEY_PREFIX}1234567890abcd f`;
expect(validateApiKeyFormat(invalidKey)).toBe(false);
});
diff --git a/packages/utils/src/apiKey.ts b/packages/utils/src/apiKey.ts
index f8d2ae54a43..13f272f1066 100644
--- a/packages/utils/src/apiKey.ts
+++ b/packages/utils/src/apiKey.ts
@@ -1,9 +1,23 @@
+import * as businessConst from '@lobechat/business-const';
+
+/**
+ * A distribution's `@lobechat/business-const` override replaces the whole
+ * module rather than extending it, so one written before this slot existed
+ * simply omits `API_KEY_PREFIX` β€” that reads as `undefined` here, not as "use
+ * upstream's default". Falling back explicitly keeps behaviour identical to
+ * before this slot existed instead of crashing every issued key on whatever
+ * override the deployment is running.
+ */
+const configuredApiKeyPrefix = (businessConst as Record<string, unknown>).API_KEY_PREFIX;
+export const API_KEY_PREFIX =
+ typeof configuredApiKeyPrefix === 'string' ? configuredApiKeyPrefix : 'sk-lh-';
+
// Global counter for additional uniqueness
let apiKeyCounter = 0;
/**
* Generate API Key
- * Format: sk-lh-{random}
+ * Format: `${API_KEY_PREFIX}{16 lowercase alphanumerics}`
* @returns Generated API Key
*/
export function generateApiKey(): string {
@@ -35,7 +49,7 @@ export function generateApiKey(): string {
randomPart = randomPart.slice(0, 16);
// Combine to form the final API Key
- return `sk-lh-${randomPart}`;
+ return `${API_KEY_PREFIX}${randomPart}`;
}
/**
@@ -48,13 +62,26 @@ export function isApiKeyExpired(expiresAt: Date | null): boolean {
return new Date() > expiresAt;
}
+/** The random half of a key: exactly 16 lowercase alphanumerics. */
+const KEY_SUFFIX_PATTERN = /^[\da-z]{16}$/;
+
/**
- * Validate API Key format
+ * Validate API Key format.
+ *
+ * Prefix compared with `startsWith` rather than interpolated into a RegExp.
+ * The prefix is a build-time constant that a distribution overrides, so it is
+ * data flowing into a pattern; comparing it directly means there is no escaping
+ * to get wrong, and the check stays correct for any prefix somebody chooses.
+ *
+ * Built from the same constant the generator uses. These two drifting apart is
+ * not cosmetic: the OpenAPI auth middleware calls this to decide whether a
+ * bearer token is an API key or an OIDC JWT, so a mismatch makes every issued
+ * key fail authentication as a malformed JWT instead.
+ *
* @param key - API Key to validate
* @returns Whether the key has a valid format
*/
export function validateApiKeyFormat(key: string): boolean {
- // Check format: sk-lh-{random}
- const pattern = /^sk-lh-[\da-z]{16}$/;
- return pattern.test(key);
+ if (!key.startsWith(API_KEY_PREFIX)) return false;
+ return KEY_SUFFIX_PATTERN.test(key.slice(API_KEY_PREFIX.length));
}