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.

✨ feat(api-key): issue 64-character API keys by default (#23654)

Lobehub Coderf2127c0fd517
diff --git a/docs/development/api/authentication.mdx b/docs/development/api/authentication.mdx
index 3597e4c598b..970d042546c 100644
--- a/docs/development/api/authentication.mdx
+++ b/docs/development/api/authentication.mdx
@@ -22,7 +22,7 @@ Authorization: Bearer <token>
The server decides what kind of token it is by its shape:
-- A token in the API key format (`sk-lh-` plus 16 lowercase letters and digits) is looked up as an **API key**. The key must be enabled and not expired.
+- A token in the API key format (`sk-lh-` plus 58 lowercase letters and digits, or 16 for keys created earlier) is looked up as an **API key**. The key must be enabled and not expired.
- Any other token is validated as an **OIDC access token** (an RS256 JWT for the audience `urn:lobehub:chat`), signed by the deployment's OIDC provider. Self-hosted instances accept OIDC tokens only when `JWKS_KEY` is configured.
There is no `X-API-Key` header. A missing or invalid token returns `401`.
diff --git a/docs/development/api/authentication.zh-CN.mdx b/docs/development/api/authentication.zh-CN.mdx
index cce99ee0a16..e1c2374c795 100644
--- a/docs/development/api/authentication.zh-CN.mdx
+++ b/docs/development/api/authentication.zh-CN.mdx
@@ -22,7 +22,7 @@ Authorization: Bearer <token>
服务端根据令牌的形态判断其类型:
-- 符合 API Key 格式(`sk-lh-` 加 16 位小写字母和数字)的令牌按 **API Key** 查找。Key 必须处于启用状态且未过期。
+- 符合 API Key 格式(`sk-lh-` 加 58 位小写字母和数字,较早创建的 Key 为 16 位)的令牌按 **API Key** 查找。Key 必须处于启用状态且未过期。
- 其他令牌一律按 **OIDC 访问令牌** 校验(受众为 `urn:lobehub:chat` 的 RS256 JWT),由部署自身的 OIDC 提供方签发。自托管实例只有在配置了 `JWKS_KEY` 时才接受 OIDC 令牌。
不存在 `X-API-Key` 请求头。缺少令牌或令牌无效时返回 `401`。
diff --git a/docs/development/api/overview.mdx b/docs/development/api/overview.mdx
index 4d86693e307..f96a7a59e93 100644
--- a/docs/development/api/overview.mdx
+++ b/docs/development/api/overview.mdx
@@ -56,7 +56,7 @@ The full list of merged and pending changes is in the [API Changelog](/docs/deve
1. Open the Workspace where your data lives and go to **Settings → API Keys** (`/<workspace>/settings/apikey`).
2. Create a key. Choose **Full access** or pick only the [scopes](/docs/development/api/authentication#scopes) your integration needs.
-3. Copy the key. It starts with `sk-lh-` and is followed by 16 lowercase letters and digits.
+3. Copy the key. It starts with `sk-lh-` and is followed by 58 lowercase letters and digits. Keys created earlier have 16 and keep working.
You can change a key's scopes later on its detail page. Only the key's creator can do this.
diff --git a/docs/development/api/overview.zh-CN.mdx b/docs/development/api/overview.zh-CN.mdx
index 09a8b26c613..80b1a08afd7 100644
--- a/docs/development/api/overview.zh-CN.mdx
+++ b/docs/development/api/overview.zh-CN.mdx
@@ -56,7 +56,7 @@ tags:
1. 打开数据所在的工作区,进入 **设置 → API Keys**(`/<workspace>/settings/apikey`)。
2. 创建一个 Key。选择 **完全访问**,或只勾选集成所需的 [scope](/zh/docs/development/api/authentication#scopes)。
-3. 复制 Key。它以 `sk-lh-` 开头,后跟 16 位小写字母和数字。
+3. 复制 Key。它以 `sk-lh-` 开头,后跟 58 位小写字母和数字。较早创建的 Key 为 16 位,仍可继续使用。
之后可以在 Key 的详情页修改 scope,只有 Key 的创建者可以修改。
diff --git a/packages/database/src/models/__tests__/apiKey.test.ts b/packages/database/src/models/__tests__/apiKey.test.ts
index 3baaf03afc9..894e79873b1 100644
--- a/packages/database/src/models/__tests__/apiKey.test.ts
+++ b/packages/database/src/models/__tests__/apiKey.test.ts
@@ -1,8 +1,13 @@
// @vitest-environment node
-import { API_KEY_PREFIX, validateApiKeyFormat } from '@lobechat/utils/apiKey';
+import {
+ API_KEY_PREFIX,
+ MAX_API_KEY_PREFIX_BYTES,
+ validateApiKeyFormat,
+} from '@lobechat/utils/apiKey';
import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { hashApiKey, hashApiKeyWithSecret } from '@/utils/server/apiKeyHash';
import { getTestDB } from '../../core/getTestDB';
@@ -80,12 +85,30 @@ describe('ApiKeyModel', () => {
const created = await apiKeyModel.createWithPlaintext({ name: 'One-time Key' });
expect(created.key.startsWith(API_KEY_PREFIX)).toBe(true);
- expect(created.key.slice(API_KEY_PREFIX.length)).toMatch(/^[\da-z]{16}$/);
+ expect(created.key.slice(API_KEY_PREFIX.length)).toMatch(/^[\da-z]{58}$/);
const stored = await apiKeyModel.findById(created.id);
expect(stored?.key).not.toBe(created.key);
expect(stored?.key).toContain(':');
});
+
+ it.each([
+ ['ascii', 'p'.repeat(MAX_API_KEY_PREFIX_BYTES)],
+ ['multibyte', `${'界'.repeat(22)}p`],
+ ])('stores the longest supported %s-prefixed key in the key column', async (_, prefix) => {
+ const key = `${prefix}${'a'.repeat(32)}`;
+ const gateKeeper = await KeyVaultsGateKeeper.initWithEnvKey();
+ const encrypted = await gateKeeper.encrypt(key);
+
+ expect(encrypted).toHaveLength(256);
+
+ const [row] = await serverDB
+ .insert(apiKeys)
+ .values({ key: encrypted, keyHash: hashApiKey(key), name: 'Longest Key', userId })
+ .returning();
+
+ expect(row.key).toBe(encrypted);
+ });
});
describe('delete', () => {
@@ -164,7 +187,7 @@ describe('ApiKeyModel', () => {
const keys = await apiKeyModel.query();
expect(keys).toHaveLength(2);
expect(keys[0].key.startsWith(API_KEY_PREFIX)).toBe(true);
- expect(keys[0].key.slice(API_KEY_PREFIX.length)).toMatch(/^[\da-z]{16}$/);
+ expect(keys[0].key.slice(API_KEY_PREFIX.length)).toMatch(/^[\da-z]{58}$/);
});
it('keeps metadata queries free of decrypted plaintext', async () => {
@@ -213,7 +236,7 @@ describe('ApiKeyModel', () => {
expect(staleResult).toMatchObject({ key: '', keyDecryptionFailed: true });
expect(freshResult).toMatchObject({ keyDecryptionFailed: false });
expect(freshResult?.key.startsWith(API_KEY_PREFIX)).toBe(true);
- expect(freshResult?.key.slice(API_KEY_PREFIX.length)).toMatch(/^[\da-z]{16}$/);
+ expect(freshResult?.key.slice(API_KEY_PREFIX.length)).toMatch(/^[\da-z]{58}$/);
});
it('lets workspace admins list all keys while members only see their own', async () => {
diff --git a/packages/utils/src/apiKey.test.ts b/packages/utils/src/apiKey.test.ts
index dd1df979859..6d282659668 100644
--- a/packages/utils/src/apiKey.test.ts
+++ b/packages/utils/src/apiKey.test.ts
@@ -1,13 +1,21 @@
-import { describe, expect, it } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
-import { API_KEY_PREFIX, generateApiKey, isApiKeyExpired, validateApiKeyFormat } from './apiKey';
+import {
+ API_KEY_LENGTH,
+ API_KEY_PREFIX,
+ generateApiKey,
+ isApiKeyExpired,
+ validateApiKeyFormat,
+} from './apiKey';
describe('apiKey', () => {
describe('generateApiKey', () => {
- it('should generate API key with correct format', () => {
+ it('should generate a 64-character API key with correct format', () => {
const apiKey = generateApiKey();
+ expect(API_KEY_LENGTH).toBe(64);
+ expect(apiKey).toHaveLength(64);
expect(apiKey.startsWith(API_KEY_PREFIX)).toBe(true);
- expect(apiKey.slice(API_KEY_PREFIX.length)).toMatch(/^[\da-z]{16}$/);
+ expect(apiKey.slice(API_KEY_PREFIX.length)).toMatch(/^[\da-z]+$/);
});
it('should generate unique API keys', () => {
const keys = new Set();
@@ -17,6 +25,75 @@ describe('apiKey', () => {
// All 100 keys should be unique
expect(keys.size).toBe(100);
});
+
+ describe('with a customized prefix', () => {
+ const loadWithPrefix = async (prefix: string) => {
+ vi.resetModules();
+ vi.doMock('@lobechat/business-const', () => ({ API_KEY_PREFIX: prefix }));
+ return import('./apiKey');
+ };
+
+ afterEach(() => {
+ vi.doUnmock('@lobechat/business-const');
+ vi.resetModules();
+ });
+
+ it('should keep the 64-character total while 32 random characters still fit', async () => {
+ const prefix = 'p'.repeat(32);
+ const { generateApiKey, validateApiKeyFormat } = await loadWithPrefix(prefix);
+
+ const apiKey = generateApiKey();
+
+ expect(apiKey).toHaveLength(64);
+ expect(validateApiKeyFormat(apiKey)).toBe(true);
+ });
+
+ it.each([33, 63, 64, 67])(
+ 'should keep 32 random characters with a %i-character prefix',
+ async (prefixLength) => {
+ const prefix = 'p'.repeat(prefixLength);
+ const { generateApiKey, validateApiKeyFormat } = await loadWithPrefix(prefix);
+
+ const apiKey = generateApiKey();
+
+ expect(apiKey.startsWith(prefix)).toBe(true);
+ expect(apiKey.slice(prefix.length)).toMatch(/^[\da-z]{32}$/);
+ expect(validateApiKeyFormat(apiKey)).toBe(true);
+ },
+ );
+
+ it.each([68, 100])(
+ 'should refuse to issue a key that cannot be stored with a %i-character prefix',
+ async (prefixLength) => {
+ const { generateApiKey } = await loadWithPrefix('p'.repeat(prefixLength));
+
+ expect(() => generateApiKey()).toThrow(/API_KEY_PREFIX.*at most 67/);
+ },
+ );
+
+ it.each([
+ { prefixCharacters: 18, suffixLength: 45 },
+ { prefixCharacters: 22, suffixLength: 33 },
+ ])(
+ 'should fit the storage budget with a $prefixCharacters-character multibyte prefix',
+ async ({ prefixCharacters, suffixLength }) => {
+ const prefix = '界'.repeat(prefixCharacters);
+ const { generateApiKey, validateApiKeyFormat } = await loadWithPrefix(prefix);
+
+ const apiKey = generateApiKey();
+
+ expect(apiKey.slice(prefix.length)).toHaveLength(suffixLength);
+ expect(new TextEncoder().encode(apiKey).length).toBeLessThanOrEqual(99);
+ expect(validateApiKeyFormat(apiKey)).toBe(true);
+ },
+ );
+
+ it('should measure the prefix limit in UTF-8 bytes', async () => {
+ const { generateApiKey } = await loadWithPrefix('界'.repeat(23));
+
+ expect(() => generateApiKey()).toThrow(/API_KEY_PREFIX.*at most 67 UTF-8 bytes, got 69/);
+ });
+ });
});
describe('isApiKeyExpired', () => {
@@ -41,6 +118,17 @@ describe('apiKey', () => {
const validKey = `${API_KEY_PREFIX}abc123def456789a`;
expect(validateApiKeyFormat(validKey)).toBe(true);
});
+ it('should keep accepting legacy keys with a 16-character suffix', () => {
+ expect(validateApiKeyFormat(`${API_KEY_PREFIX}abc123def456789a`)).toBe(true);
+ });
+ it('should reject lengths between the legacy and current formats', () => {
+ const suffix = 'a'.repeat(API_KEY_LENGTH - API_KEY_PREFIX.length - 1);
+ expect(validateApiKeyFormat(`${API_KEY_PREFIX}${suffix}`)).toBe(false);
+ });
+ it('should reject keys longer than the current format', () => {
+ const suffix = 'a'.repeat(API_KEY_LENGTH - API_KEY_PREFIX.length + 1);
+ expect(validateApiKeyFormat(`${API_KEY_PREFIX}${suffix}`)).toBe(false);
+ });
it('should reject keys with wrong prefix', () => {
const invalidKey = 'lb-1234567890abcdef';
expect(validateApiKeyFormat(invalidKey)).toBe(false);
diff --git a/packages/utils/src/apiKey.ts b/packages/utils/src/apiKey.ts
index 13f272f1066..af1e04c732a 100644
--- a/packages/utils/src/apiKey.ts
+++ b/packages/utils/src/apiKey.ts
@@ -12,43 +12,65 @@ const configuredApiKeyPrefix = (businessConst as Record<string, unknown>).API_KE
export const API_KEY_PREFIX =
typeof configuredApiKeyPrefix === 'string' ? configuredApiKeyPrefix : 'sk-lh-';
-// Global counter for additional uniqueness
-let apiKeyCounter = 0;
-
/**
- * Generate API Key
- * Format: `${API_KEY_PREFIX}{16 lowercase alphanumerics}`
- * @returns Generated API Key
+ * Target length of a newly issued key in characters, prefix included. A long or
+ * multibyte prefix can move it: the key always keeps
+ * {@link MIN_KEY_SUFFIX_LENGTH} random characters and fits {@link MAX_STORED_KEY_BYTES}.
*/
-export function generateApiKey(): string {
- // Use high-resolution timestamp for better uniqueness
- const timestamp = performance.now().toString(36).replaceAll('.', '');
+export const API_KEY_LENGTH = 64;
- // Generate multiple random components
- const random1 = Math.random().toString(36).slice(2);
- const random2 = Math.random().toString(36).slice(2);
- const random3 = Math.random().toString(36).slice(2);
+/** Random-part length of keys issued before {@link API_KEY_LENGTH}; they stay valid. */
+const LEGACY_KEY_SUFFIX_LENGTH = 16;
- // Add a counter-based component for additional uniqueness
- apiKeyCounter = (apiKeyCounter + 1) % 1_000_000;
- const counter = apiKeyCounter.toString(36);
+/** Random characters every new key keeps (about 165 bits), whatever the prefix. */
+const MIN_KEY_SUFFIX_LENGTH = 32;
- // Combine all components
- const combined = (timestamp + random1 + random2 + random3 + counter).replaceAll(/[^\da-z]/g, '');
+/**
+ * Longest plaintext key, in UTF-8 bytes, the `api_keys.key` column can hold:
+ * encryption adds 58 characters of IV, auth tag and separators and hex-encodes
+ * the bytes, so 99 bytes become exactly the column's 256 characters.
+ */
+const MAX_STORED_KEY_BYTES = 99;
+
+/** Longest prefix, in UTF-8 bytes, that leaves room for {@link MIN_KEY_SUFFIX_LENGTH} characters. */
+export const MAX_API_KEY_PREFIX_BYTES = MAX_STORED_KEY_BYTES - MIN_KEY_SUFFIX_LENGTH;
- // Ensure we have enough entropy
- let randomPart = combined.slice(0, 16);
+const API_KEY_PREFIX_BYTES = new TextEncoder().encode(API_KEY_PREFIX).length;
- // If we don't have enough characters, generate more
- while (randomPart.length < 16) {
- const additional = Math.random().toString(36).slice(2);
- randomPart += additional;
+// The suffix is ASCII, so each of its characters costs one stored byte.
+const KEY_SUFFIX_LENGTH = Math.min(
+ Math.max(API_KEY_LENGTH - API_KEY_PREFIX.length, MIN_KEY_SUFFIX_LENGTH),
+ MAX_STORED_KEY_BYTES - API_KEY_PREFIX_BYTES,
+);
+const KEY_ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
+// Largest multiple of the alphabet size in a byte; higher bytes are discarded
+// so that `byte % 36` stays uniform.
+const MAX_UNBIASED_BYTE = 256 - (256 % KEY_ALPHABET.length);
+
+/**
+ * Generate API Key
+ * Format: `${API_KEY_PREFIX}{lowercase alphanumerics}`, {@link API_KEY_LENGTH} characters in total
+ * unless the prefix requires a different length
+ * @returns Generated API Key
+ * @throws When the configured prefix is too long for the key to be stored
+ */
+export function generateApiKey(): string {
+ if (API_KEY_PREFIX_BYTES > MAX_API_KEY_PREFIX_BYTES) {
+ throw new Error(
+ `API_KEY_PREFIX must be at most ${MAX_API_KEY_PREFIX_BYTES} UTF-8 bytes, got ${API_KEY_PREFIX_BYTES}.`,
+ );
}
- // Take exactly 16 characters
- randomPart = randomPart.slice(0, 16);
+ let randomPart = '';
+
+ while (randomPart.length < KEY_SUFFIX_LENGTH) {
+ for (const byte of crypto.getRandomValues(new Uint8Array(KEY_SUFFIX_LENGTH))) {
+ if (byte >= MAX_UNBIASED_BYTE) continue;
+ randomPart += KEY_ALPHABET[byte % KEY_ALPHABET.length];
+ if (randomPart.length === KEY_SUFFIX_LENGTH) break;
+ }
+ }
- // Combine to form the final API Key
return `${API_KEY_PREFIX}${randomPart}`;
}
@@ -62,8 +84,8 @@ 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}$/;
+/** The random half of a key: lowercase alphanumerics only. */
+const KEY_SUFFIX_PATTERN = /^[\da-z]+$/;
/**
* Validate API Key format.
@@ -83,5 +105,10 @@ const KEY_SUFFIX_PATTERN = /^[\da-z]{16}$/;
*/
export function validateApiKeyFormat(key: string): boolean {
if (!key.startsWith(API_KEY_PREFIX)) return false;
- return KEY_SUFFIX_PATTERN.test(key.slice(API_KEY_PREFIX.length));
+
+ const suffix = key.slice(API_KEY_PREFIX.length);
+ if (suffix.length !== KEY_SUFFIX_LENGTH && suffix.length !== LEGACY_KEY_SUFFIX_LENGTH) {
+ return false;
+ }
+ return KEY_SUFFIX_PATTERN.test(suffix);
}
diff --git a/src/features/Settings/apikey/features/ApiKeyDisplay/index.tsx b/src/features/Settings/apikey/features/ApiKeyDisplay/index.tsx
index ca017d19460..0a134250d4e 100644
--- a/src/features/Settings/apikey/features/ApiKeyDisplay/index.tsx
+++ b/src/features/Settings/apikey/features/ApiKeyDisplay/index.tsx
@@ -13,6 +13,12 @@ const styles = stylex.create({
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
},
+ // A full key is wider than the list column; wrap it so revealing one row
+ // does not push the table's other columns and row actions out of view.
+ revealed: {
+ whiteSpace: 'normal',
+ wordBreak: 'break-all',
+ },
});
interface ApiKeyDisplayProps {
@@ -44,7 +50,7 @@ const ApiKeyDisplay: FC<ApiKeyDisplayProps> = ({ apiKey }) => {
return (
<Flexbox horizontal align={'center'} gap={4}>
- <span {...stylex.props(styles.key)}>{displayValue}</span>
+ <span {...stylex.props(styles.key, isVisible && styles.revealed)}>{displayValue}</span>
<ActionIcon
icon={isVisible ? EyeOff : Eye}
size={'small'}
diff --git a/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx b/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx
index ed9dffe1f2e..1f7dfd5272c 100644
--- a/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx
+++ b/src/features/Settings/apikey/features/ApiKeyModal/Content.tsx
@@ -41,6 +41,7 @@ const styles = stylex.create({
flex: '1',
fontFamily: cssVar.fontFamilyCode,
fontSize: '12px',
+ textWrap: 'balance',
wordBreak: 'break-all',
},
successIcon: { color: cssVar.colorSuccess },
diff --git a/src/features/Settings/apikey/features/ApiKeyModal/index.tsx b/src/features/Settings/apikey/features/ApiKeyModal/index.tsx
index 70fa5ff3db7..7269649fc41 100644
--- a/src/features/Settings/apikey/features/ApiKeyModal/index.tsx
+++ b/src/features/Settings/apikey/features/ApiKeyModal/index.tsx
@@ -14,5 +14,6 @@ export const createApiKeyModal = (props: ApiKeyModalContentProps): ModalInstance
content: { paddingBlock: 16, paddingInline: 24 },
},
title: t('apikey.form.title', { ns: 'auth' }),
- width: 'min(90vw, 560px)',
+ // Wide enough to show a 64-character key on one line.
+ width: 'min(90vw, 600px)',
});