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.

💄 style(settings): vault rows open a detail view, keys generated server-side (#23700)

Rdmclin2dcf8dfe113ae
diff --git a/apps/server/src/routers/lambda/market/creds.ts b/apps/server/src/routers/lambda/market/creds.ts
index 937477ba79e..8f84b476b25 100644
--- a/apps/server/src/routers/lambda/market/creds.ts
+++ b/apps/server/src/routers/lambda/market/creds.ts
@@ -18,6 +18,7 @@ import {
mergeCredsEnvListing,
resolveInjectedEnvVarsByKey,
} from '@/server/services/sandbox/credsEnv';
+import { resolveCredKey } from '@/server/utils/credKey';
const log = debug('lambda-router:market:creds');
@@ -85,7 +86,8 @@ export const credsRouter = router({
description: z.string().optional(),
fileHashId: z.string().length(64),
fileName: z.string().min(1),
- key: z.string().min(1).max(100),
+ /** Generated from the name when omitted; only agents and skills pass a fixed key. */
+ key: z.string().max(100).optional(),
name: z.string().min(1).max(255),
}),
)
@@ -93,7 +95,10 @@ export const credsRouter = router({
log('createFile input: %O', { ...input, fileHashId: '[HIDDEN]' });
try {
- const result = await ctx.marketService.market.creds.createFile(input);
+ const result = await ctx.marketService.market.creds.createFile({
+ ...input,
+ key: resolveCredKey(input),
+ });
log('createFile success: id=%d', result.id);
return result;
} catch (error) {
@@ -111,7 +116,8 @@ export const credsRouter = router({
.input(
z.object({
description: z.string().optional(),
- key: z.string().min(1).max(100),
+ /** Generated from the name when omitted; only agents and skills pass a fixed key. */
+ key: z.string().max(100).optional(),
name: z.string().min(1).max(255),
type: z.enum(['kv-env', 'kv-header']),
values: z.record(z.string(), z.string()),
@@ -121,7 +127,10 @@ export const credsRouter = router({
log('createKV input: %O', { ...input, values: '[HIDDEN]' });
try {
- const result = await ctx.marketService.market.creds.createKV(input);
+ const result = await ctx.marketService.market.creds.createKV({
+ ...input,
+ key: resolveCredKey(input),
+ });
log('createKV success: id=%d', result.id);
return result;
} catch (error) {
@@ -139,7 +148,8 @@ export const credsRouter = router({
.input(
z.object({
description: z.string().optional(),
- key: z.string().min(1).max(100),
+ /** Generated from the name when omitted; only agents and skills pass a fixed key. */
+ key: z.string().max(100).optional(),
name: z.string().min(1).max(255),
oauthConnectionId: z.number(),
}),
@@ -148,7 +158,10 @@ export const credsRouter = router({
log('createOAuth input: %O', input);
try {
- const result = await ctx.marketService.market.creds.createOAuth(input);
+ const result = await ctx.marketService.market.creds.createOAuth({
+ ...input,
+ key: resolveCredKey(input),
+ });
log('createOAuth success: id=%d', result.id);
return result;
} catch (error) {
diff --git a/apps/server/src/utils/credKey.test.ts b/apps/server/src/utils/credKey.test.ts
new file mode 100644
index 00000000000..5d8961b036c
--- /dev/null
+++ b/apps/server/src/utils/credKey.test.ts
@@ -0,0 +1,48 @@
+import { describe, expect, it } from 'vitest';
+
+import { generateCredKey, resolveCredKey } from './credKey';
+
+describe('generateCredKey', () => {
+ it('slugifies the name and appends a 6-character suffix', () => {
+ expect(generateCredKey('OpenAI API Key')).toMatch(/^openai-api-key-[\da-z]{6}$/);
+ });
+
+ it('falls back to cred when the name has no ASCII letters or digits', () => {
+ expect(generateCredKey('我的测试环境变量')).toMatch(/^cred-[\da-z]{6}$/);
+ });
+
+ it('keeps only the ASCII part of a mixed name', () => {
+ expect(generateCredKey('飞书小葵 App Secret')).toMatch(/^app-secret-[\da-z]{6}$/);
+ });
+
+ it('keeps accented words whole', () => {
+ expect(generateCredKey('Résumé token')).toMatch(/^resume-token-[\da-z]{6}$/);
+ });
+
+ it('caps the slug length and never ends it with a hyphen', () => {
+ const key = generateCredKey(`${'a'.repeat(39)} b`);
+ expect(key).toMatch(/^a{39}-[\da-z]{6}$/);
+ });
+
+ it('produces keys that pass the credential key pattern', () => {
+ expect(generateCredKey('Vercel Token (lobehub-pro)')).toMatch(/^[\w-]+$/);
+ });
+
+ it('differs between calls for the same name', () => {
+ expect(generateCredKey('Same')).not.toBe(generateCredKey('Same'));
+ });
+});
+
+describe('resolveCredKey', () => {
+ it('keeps a caller-supplied key', () => {
+ expect(resolveCredKey({ key: 'claude-code', name: 'Anything' })).toBe('claude-code');
+ });
+
+ it('generates a key when none is supplied', () => {
+ expect(resolveCredKey({ name: 'GitHub Token' })).toMatch(/^github-token-[\da-z]{6}$/);
+ });
+
+ it('generates a key when the supplied key is blank', () => {
+ expect(resolveCredKey({ key: ' ', name: 'GitHub Token' })).toMatch(/^github-token-/);
+ });
+});
diff --git a/apps/server/src/utils/credKey.ts b/apps/server/src/utils/credKey.ts
new file mode 100644
index 00000000000..1f84b070d9f
--- /dev/null
+++ b/apps/server/src/utils/credKey.ts
@@ -0,0 +1,36 @@
+import { randomBytes } from 'node:crypto';
+
+const SUFFIX_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789';
+const SUFFIX_LENGTH = 6;
+const SLUG_MAX_LENGTH = 40;
+const FALLBACK_SLUG = 'cred';
+
+const randomSuffix = () =>
+ Array.from(
+ randomBytes(SUFFIX_LENGTH),
+ (byte) => SUFFIX_ALPHABET[byte % SUFFIX_ALPHABET.length],
+ ).join('');
+
+/**
+ * The identifier agents look a credential up by. Users never type or see it:
+ * it is derived from the display name (`OpenAI API Key` → `openai-api-key-x7k2m9`)
+ * so an agent reading the credential list can still tell rows apart, and the
+ * random suffix keeps it unique within the account without a lookup.
+ * Names with no ASCII letters or digits fall back to `cred-<suffix>`.
+ */
+export const generateCredKey = (name: string): string => {
+ const slug = name
+ .normalize('NFKD')
+ // Drop the combining marks NFKD splits off, so `é` becomes `e` rather than a word break.
+ .replaceAll(/\p{M}/gu, '')
+ .toLowerCase()
+ .replaceAll(/[^\da-z]+/g, '-')
+ .slice(0, SLUG_MAX_LENGTH)
+ .replaceAll(/^-+|-+$/g, '');
+
+ return `${slug || FALLBACK_SLUG}-${randomSuffix()}`;
+};
+
+/** A caller-supplied key wins (agents and skills ask for fixed keys); otherwise one is generated. */
+export const resolveCredKey = (input: { key?: string; name: string }): string =>
+ input.key?.trim() || generateCredKey(input.name);
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 37d642b2012..0343903c1b5 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -478,6 +478,8 @@
"creds.createModal.titles.kv-header": "New HTTP header",
"creds.createModal.titles.oauth": "New OAuth credential",
"creds.detail.account": "Account",
+ "creds.detail.author": "Owner",
+ "creds.detail.visibility": "Visible to",
"creds.empty": "No credentials configured yet",
"creds.errors.createFailed": "Failed to create the credential. Please try again.",
"creds.errors.deleteFailed": "Failed to delete the credential. Please try again.",
@@ -499,10 +501,6 @@
"creds.form.file": "Credential File",
"creds.form.fileRequired": "Please upload a file",
"creds.form.headers": "Headers",
- "creds.form.key": "Identifier",
- "creds.form.keyDesc": "Agents find this credential by its identifier. Letters, numbers, hyphens and underscores only.",
- "creds.form.keyPattern": "Identifier can only contain letters, numbers, underscores, and hyphens",
- "creds.form.keyRequired": "Identifier is required",
"creds.form.name": "Display Name",
"creds.form.nameRequired": "Display name is required",
"creds.form.removePair": "Remove",
@@ -542,7 +540,6 @@
"creds.signIn": "Sign In to Market",
"creds.signInRequired": "Please sign in to the Market to manage your credentials",
"creds.table.actions": "Actions",
- "creds.table.key": "Identifier",
"creds.table.lastUsed": "Last Used",
"creds.table.name": "Name",
"creds.table.neverUsed": "Never",
@@ -558,6 +555,7 @@
"creds.view.noValues": "No Values",
"creds.view.oauthNote": "OAuth credentials are managed by the connected service.",
"creds.view.show": "Show",
+ "creds.view.showValues": "Show values",
"creds.view.title": "View Credential: {{name}}",
"creds.view.values": "Credential Values",
"creds.view.warning": "These values are sensitive. Do not share them with others.",
@@ -565,7 +563,6 @@
"creds.visibility.publish": "Publish to Workspace",
"creds.visibility.publishConfirmTitle": "Publish this credential to the workspace?",
"creds.writeOnly.editHint": "Stored values are not shown. Leave the pairs empty to keep them, or enter every pair to replace them all.",
- "creds.writeOnly.tag": "Write-only",
"creds.writeOnly.tooltip": "Shared with the workspace: its values are no longer shown in settings and can only be replaced.",
"danger.reset.action": "Reset Now",
"danger.reset.confirm": "Reset all settings?",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 9861f02e23f..9a7d57644e8 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -478,6 +478,8 @@
"creds.createModal.titles.kv-header": "新建 HTTP 请求头",
"creds.createModal.titles.oauth": "新建 OAuth 凭证",
"creds.detail.account": "账户",
+ "creds.detail.author": "所有者",
+ "creds.detail.visibility": "可见范围",
"creds.empty": "暂无凭证配置",
"creds.errors.createFailed": "创建凭证失败,请重试。",
"creds.errors.deleteFailed": "删除凭证失败,请重试。",
@@ -499,10 +501,6 @@
"creds.form.file": "凭证文件",
"creds.form.fileRequired": "请上传文件",
"creds.form.headers": "请求头",
- "creds.form.key": "标识符",
- "creds.form.keyDesc": "智能体通过标识符找到这个凭证,只能包含字母、数字、连字符和下划线。",
- "creds.form.keyPattern": "标识符只能包含字母、数字、下划线和连字符",
- "creds.form.keyRequired": "请输入标识符",
"creds.form.name": "显示名称",
"creds.form.nameRequired": "请输入显示名称",
"creds.form.removePair": "移除",
@@ -542,7 +540,6 @@
"creds.signIn": "登录 Market",
"creds.signInRequired": "请登录 Market 以管理您的凭证",
"creds.table.actions": "操作",
- "creds.table.key": "标识符",
"creds.table.lastUsed": "上次使用",
"creds.table.name": "名称",
"creds.table.neverUsed": "从未使用",
@@ -558,6 +555,7 @@
"creds.view.noValues": "无值",
"creds.view.oauthNote": "OAuth 凭证由连接的服务管理。",
"creds.view.show": "显示",
+ "creds.view.showValues": "显示值",
"creds.view.title": "查看凭证:{{name}}",
"creds.view.values": "凭证值",
"creds.view.warning": "这些值是敏感信息,请勿与他人分享。",
@@ -565,7 +563,6 @@
"creds.visibility.publish": "发布到工作区",
"creds.visibility.publishConfirmTitle": "将此凭证发布到工作区?",
"creds.writeOnly.editHint": "已保存的值不会显示。键值对留空则保留原值;填写则用填写的全部键值对替换。",
- "creds.writeOnly.tag": "只写",
"creds.writeOnly.tooltip": "已共享到工作区:设置里不再显示值,只能替换。",
"danger.reset.action": "立即重置",
"danger.reset.confirm": "确认重置所有设置吗?",
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index fe2c52155c2..53620148d09 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -788,6 +788,8 @@ export default {
'creds.createModal.titles.kv-header': 'New HTTP header',
'creds.createModal.titles.oauth': 'New OAuth credential',
'creds.detail.account': 'Account',
+ 'creds.detail.author': 'Owner',
+ 'creds.detail.visibility': 'Visible to',
'creds.empty': 'No credentials configured yet',
'creds.errors.createFailed': 'Failed to create the credential. Please try again.',
'creds.errors.deleteFailed': 'Failed to delete the credential. Please try again.',
@@ -806,8 +808,6 @@ export default {
'creds.form.addHeader': 'Add header',
'creds.form.envVars': 'Environment variables',
'creds.form.headers': 'Headers',
- 'creds.form.keyDesc':
- 'Agents find this credential by its identifier. Letters, numbers, hyphens and underscores only.',
'creds.form.removePair': 'Remove',
'creds.form.valuesDesc.kv-env':
'Set as environment variables when an agent uses this credential.',
@@ -850,9 +850,6 @@ export default {
'creds.form.descriptionPlaceholder': 'Optional description for this credential',
'creds.form.file': 'Credential File',
'creds.form.fileRequired': 'Please upload a file',
- 'creds.form.key': 'Identifier',
- 'creds.form.keyPattern': 'Identifier can only contain letters, numbers, underscores, and hyphens',
- 'creds.form.keyRequired': 'Identifier is required',
'creds.form.name': 'Display Name',
'creds.form.nameRequired': 'Display name is required',
'creds.form.save': 'Save',
@@ -865,7 +862,6 @@ export default {
'creds.form.valuePlaceholder': 'Enter value',
'creds.oauth.noConnections': 'No OAuth connections available. Please connect an account first.',
'creds.table.actions': 'Actions',
- 'creds.table.key': 'Identifier',
'creds.table.lastUsed': 'Last Used',
'creds.table.name': 'Name',
'creds.table.neverUsed': 'Never',
@@ -881,6 +877,7 @@ export default {
'creds.view.noValues': 'No Values',
'creds.view.oauthNote': 'OAuth credentials are managed by the connected service.',
'creds.view.show': 'Show',
+ 'creds.view.showValues': 'Show values',
'creds.view.title': 'View Credential: {{name}}',
'creds.view.values': 'Credential Values',
'creds.view.warning': 'These values are sensitive. Do not share them with others.',
@@ -4820,7 +4817,6 @@ When I am ___, I need ___
'tab.environmentsAndCreds': 'Environments & Vault',
'environmentsAndCreds.tabs.environments': 'Environments',
'environmentsAndCreds.tabs.vault': 'Vault',
- 'creds.writeOnly.tag': 'Write-only',
'creds.writeOnly.tooltip':
'Shared with the workspace: its values are no longer shown in settings and can only be replaced.',
'creds.writeOnly.editHint':
diff --git a/src/features/Settings/creds/features/CreateCredModal/FileCredForm.tsx b/src/features/Settings/creds/features/CreateCredModal/FileCredForm.tsx
index d7a5947253d..3c65a53c6b4 100644
--- a/src/features/Settings/creds/features/CreateCredModal/FileCredForm.tsx
+++ b/src/features/Settings/creds/features/CreateCredModal/FileCredForm.tsx
@@ -22,7 +22,6 @@ interface FileCredFormProps {
interface FormValues {
description?: string;
- key: string;
name: string;
}
@@ -52,7 +51,6 @@ const FileCredForm: FC<FileCredFormProps> = ({ credsApi, disabled, onCancel, onS
description: values.description,
fileHashId,
fileName,
- key: values.key,
name: values.name,
...createExtras(credsApi),
});
@@ -151,18 +149,6 @@ const FileCredForm: FC<FileCredFormProps> = ({ credsApi, disabled, onCancel, onS
<Input disabled={disabled} placeholder="e.g., GCP Service Account" />
</Form.Field>
- <Form.Field
- desc={t('creds.form.keyDesc')}
- label={t('creds.form.key')}
- name="key"
- required={t('creds.form.keyRequired')}
- validate={(value?: string) =>
- value && !/^[\w-]+$/.test(value) ? t('creds.form.keyPattern') : undefined
- }
- >
- <Input disabled={disabled} placeholder="e.g., gcp-service-account" />
- </Form.Field>
-
<Form.Field label={t('creds.form.description')} name="description">
<TextArea
disabled={disabled}
diff --git a/src/features/Settings/creds/features/CreateCredModal/KVCredForm.test.tsx b/src/features/Settings/creds/features/CreateCredModal/KVCredForm.test.tsx
new file mode 100644
index 00000000000..ed3aea33a96
--- /dev/null
+++ b/src/features/Settings/creds/features/CreateCredModal/KVCredForm.test.tsx
@@ -0,0 +1,54 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { describe, expect, it, vi } from 'vitest';
+
+import { type CredsApi } from '../useCredsApi';
+import KVCredForm from './KVCredForm';
+
+const renderForm = (props: Partial<Parameters<typeof KVCredForm>[0]>) => {
+ const mutate = vi.fn().mockResolvedValue({});
+ const credsApi = { client: { createKV: { mutate } } } as unknown as CredsApi;
+ render(
+ <QueryClientProvider client={new QueryClient()}>
+ <KVCredForm
+ credsApi={credsApi}
+ type={'kv-env'}
+ onCancel={vi.fn()}
+ onSuccess={vi.fn()}
+ {...props}
+ />
+ </QueryClientProvider>,
+ );
+ return mutate;
+};
+
+const fillAndSubmit = async (name?: string) => {
+ if (name)
+ fireEvent.change(screen.getByPlaceholderText('OpenAI API Key'), { target: { value: name } });
+ const variable = screen.getAllByPlaceholderText('OPENAI_API_KEY')[0] as HTMLInputElement;
+ if (!variable.value) fireEvent.change(variable, { target: { value: 'OPENAI_API_KEY' } });
+ fireEvent.change(screen.getAllByPlaceholderText('creds.form.valuePlaceholder')[0], {
+ target: { value: 'secret' },
+ });
+ fireEvent.click(screen.getByRole('button', { name: 'creds.form.submit' }));
+};
+
+describe('KVCredForm', () => {
+ it('lets the server derive the key when the person creates a credential', async () => {
+ const mutate = renderForm({});
+ await fillAndSubmit('OpenAI');
+
+ await waitFor(() => expect(mutate).toHaveBeenCalledTimes(1));
+ expect(mutate.mock.calls[0][0].key).toBeUndefined();
+ });
+
+ it('keeps a preset fixed key, which skills look the credential up by', async () => {
+ const mutate = renderForm({
+ preset: { key: 'github', keys: ['GITHUB_TOKEN'], name: 'GitHub' },
+ });
+ await fillAndSubmit();
+
+ await waitFor(() => expect(mutate).toHaveBeenCalledTimes(1));
+ expect(mutate.mock.calls[0][0]).toMatchObject({ key: 'github', name: 'GitHub' });
+ });
+});
diff --git a/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx b/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx
index 97f2556b6d3..9f115337b6d 100644
--- a/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx
+++ b/src/features/Settings/creds/features/CreateCredModal/KVCredForm.tsx
@@ -34,7 +34,6 @@ interface KVCredFormProps {
interface FormValues {
description?: string;
- key: string;
kvPairs: Array<{ key: string; value: string }>;
name: string;
}
@@ -52,7 +51,6 @@ const KVCredForm: FC<KVCredFormProps> = ({
initialValues: (preset
? {
description: preset.description,
- key: preset.key,
kvPairs: preset.keys.map((key) => ({ key, value: '' })),
name: preset.name,
}
@@ -83,7 +81,9 @@ const KVCredForm: FC<KVCredFormProps> = ({
await credsApi.client.createKV.mutate({
description: values.description,
- key: values.key,
+ // A preset keeps its fixed key, which skills look the credential up by;
+ // otherwise the server derives one from the name.
+ key: preset?.key,
name: values.name,
type,
values: valuesObj,
@@ -115,18 +115,6 @@ const KVCredForm: FC<KVCredFormProps> = ({
/>
</Form.Field>
- <Form.Field
- desc={t('creds.form.keyDesc')}
- label={t('creds.form.key')}
- name="key"
- required={t('creds.form.keyRequired')}
- validate={(value?: string) =>
- value && !/^[\w-]+$/.test(value) ? t('creds.form.keyPattern') : undefined
- }
- >
- <Input disabled={disabled} placeholder={type === 'kv-env' ? 'openai' : 'internal-api'} />
- </Form.Field>
-
<KVPairsField disabled={disabled} type={type} />
<Form.Field label={t('creds.form.description')} name="description">
diff --git a/src/features/Settings/creds/features/CreateCredModal/OAuthCredForm.tsx b/src/features/Settings/creds/features/CreateCredModal/OAuthCredForm.tsx
index 2b8ee41f3a9..9ec1862b2a4 100644
--- a/src/features/Settings/creds/features/CreateCredModal/OAuthCredForm.tsx
+++ b/src/features/Settings/creds/features/CreateCredModal/OAuthCredForm.tsx
@@ -30,7 +30,6 @@ interface OAuthCredFormProps {
interface FormValues {
description?: string;
- key: string;
name: string;
oauthConnectionId: number;
}
@@ -73,7 +72,6 @@ const OAuthCredForm: FC<OAuthCredFormProps> = ({ credsApi, disabled, onCancel, o
await credsApi.client.createOAuth.mutate({
description: values.description,
- key: values.key,
name: values.name,
oauthConnectionId: values.oauthConnectionId,
...createExtras(credsApi),
@@ -134,18 +132,6 @@ const OAuthCredForm: FC<OAuthCredFormProps> = ({ credsApi, disabled, onCancel, o
<Input disabled={disabled} placeholder="e.g., GitHub Connection" />
</Form.Field>
- <Form.Field
- desc={t('creds.form.keyDesc')}
- label={t('creds.form.key')}
- name="key"
- required={t('creds.form.keyRequired')}
- validate={(value?: string) =>
- value && !/^[\w-]+$/.test(value) ? t('creds.form.keyPattern') : undefined
- }
- >
- <Input disabled={disabled} placeholder="e.g., github-oauth" />
- </Form.Field>
-
<Form.Field label={t('creds.form.description')} name="description">
<TextArea
disabled={disabled}
diff --git a/src/features/Settings/creds/features/CredItem.tsx b/src/features/Settings/creds/features/CredItem.tsx
index 7df9edc0de8..a2c41befed5 100644
--- a/src/features/Settings/creds/features/CredItem.tsx
+++ b/src/features/Settings/creds/features/CredItem.tsx
@@ -4,6 +4,7 @@ import { type UserCredSummary } from '@lobechat/types';
import { Flexbox } from '@lobehub/ui';
import * as stylex from '@stylexjs/stylex';
import { type FC, memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
import { useDensity } from '@/styles/density';
@@ -12,6 +13,8 @@ import { styles } from './style';
interface CredItemProps {
cred: UserCredSummary;
+ /** Right-aligned row meta, e.g. the workspace visibility tag and the author avatar. */
+ extra?: ReactNode;
/** Opens the item's detail, which holds its edit, remove and sharing actions. */
onClick: (cred: UserCredSummary) => void;
/** Tags shown after the name (owner, sharing state). */
@@ -22,15 +25,22 @@ interface CredItemProps {
/**
* One vault item: the website's logo (else the OAuth avatar or the type icon),
- * the name with its markers, and the description. The whole row opens it.
+ * the name with its markers, and one line of "type · account · description".
+ * The whole row opens it.
*/
-const CredItem: FC<CredItemProps> = memo(({ cred, onClick, tags, titleSuffix }) => {
+const CredItem: FC<CredItemProps> = memo(({ cred, extra, onClick, tags, titleSuffix }) => {
+ const { t } = useTranslation('setting');
const { compact, tokens } = useDensity();
+ const subtitle = [t(`creds.types.${cred.type}`), cred.oauthUsername, cred.description]
+ .filter(Boolean)
+ .join(' · ');
+
return (
<Flexbox
horizontal
align="center"
+ aria-label={cred.name}
gap={tokens.sectionGap}
role="button"
tabIndex={0}
@@ -55,12 +65,15 @@ const CredItem: FC<CredItemProps> = memo(({ cred, onClick, tags, titleSuffix })
{titleSuffix}
{tags}
</Flexbox>
- {cred.description && (
- <span {...stylex.props(styles.description, compact && styles.descriptionCompact)}>
- {cred.description}
- </span>
- )}
+ <span {...stylex.props(styles.description, compact && styles.descriptionCompact)}>
+ {subtitle}
+ </span>
</Flexbox>
+ {extra && (
+ <Flexbox horizontal align="center" flex={'none'} gap={8}>
+ {extra}
+ </Flexbox>
+ )}
</Flexbox>
);
});
diff --git a/src/features/Settings/creds/features/ViewCredModal/Content.tsx b/src/features/Settings/creds/features/ViewCredModal/Content.tsx
index c0827e16925..53ee123fb1b 100644
--- a/src/features/Settings/creds/features/ViewCredModal/Content.tsx
+++ b/src/features/Settings/creds/features/ViewCredModal/Content.tsx
@@ -82,14 +82,16 @@ const MASK = '••••••••••••';
interface FieldRowProps {
children: ReactNode;
extra?: ReactNode;
+ /** Let a long label (`Credential Values`) take the width it needs, like a value name. */
+ fitLabel?: boolean;
label: ReactNode;
mono?: boolean;
}
-const FieldRow: FC<FieldRowProps> = ({ children, extra, label, mono }) => (
+const FieldRow: FC<FieldRowProps> = ({ children, extra, fitLabel, label, mono }) => (
<div {...stylex.props(styles.row)}>
<div
- {...stylex.props(styles.label, mono && styles.code, mono && styles.labelFit)}
+ {...stylex.props(styles.label, mono && styles.code, (mono || fitLabel) && styles.labelFit)}
title={mono && typeof label === 'string' ? label : undefined}
>
{label}
@@ -102,7 +104,8 @@ const FieldRow: FC<FieldRowProps> = ({ children, extra, label, mono }) => (
/** One stored value: masked until revealed, copyable either way. */
const SecretRow: FC<{ name: string; value: string }> = ({ name, value }) => {
const { t } = useTranslation('setting');
- const [visible, setVisible] = useState(false);
+ // Rows appear only after the viewer asked to see the values.
+ const [visible, setVisible] = useState(true);
return (
<FieldRow
@@ -144,10 +147,21 @@ export interface ViewCredModalContentProps {
canReadValues?: boolean;
cred: UserCredSummary;
credsApi: CredsApi;
+ /** Host-specific fields after the item's own, e.g. the workspace visibility and owner. */
+ extraItems?: CredDetailItem[];
/** Removes the item after a confirmation; no Remove button when omitted. */
onDelete?: (id: number) => Promise<unknown>;
/** Opens the edit form; no Edit button when omitted. */
onEdit?: (cred: UserCredSummary) => void;
+ /** Shown instead of the values when they exist but may not be read (write-only). */
+ valuesHint?: string;
+}
+
+/** One extra field row in the detail. */
+export interface CredDetailItem {
+ children: ReactNode;
+ key: string;
+ label: ReactNode;
}
/**
@@ -160,16 +174,20 @@ const ViewCredModalContent: FC<ViewCredModalContentProps> = ({
canReadValues = false,
cred,
credsApi,
+ extraItems = [],
onDelete,
onEdit,
+ valuesHint,
}) => {
const { t } = useTranslation('setting');
const { close } = useModalContext();
const isKV = cred.type === 'kv-env' || cred.type === 'kv-header';
const showValues = isKV && canReadValues;
+ // Plaintext is decrypted only once the viewer asks for it, not on open.
+ const [revealed, setRevealed] = useState(false);
const { data, isLoading, error } = useQuery({
- enabled: showValues,
+ enabled: showValues && revealed,
queryFn: () => credsApi.client.get.query({ decrypt: true, id: cred.id }),
queryKey: ['cred-plaintext', cred.id],
});
@@ -220,20 +238,44 @@ const ViewCredModalContent: FC<ViewCredModalContentProps> = ({
<>
<div {...stylex.props(styles.fields)}>
<FieldRow label={t('creds.table.type')}>{t(`creds.types.${cred.type}`)}</FieldRow>
- <FieldRow label={t('creds.table.key')}>
- <span {...stylex.props(styles.code)}>{cred.key}</span>
- </FieldRow>
{cred.type === 'oauth' && cred.oauthUsername && (
<FieldRow label={t('creds.detail.account')}>{cred.oauthUsername}</FieldRow>
)}
{cred.type === 'file' && cred.fileName && (
<FieldRow label={t('creds.form.file')}>{cred.fileName}</FieldRow>
)}
+ {extraItems.map((item) => (
+ <FieldRow key={item.key} label={item.label}>
+ {item.children}
+ </FieldRow>
+ ))}
{cred.description && (
<FieldRow label={t('creds.form.description')}>{cred.description}</FieldRow>
)}
+ {isKV && !showValues && valuesHint && (
+ <FieldRow fitLabel label={t('creds.view.values')}>
+ {valuesHint}
+ </FieldRow>
+ )}
{showValues &&
- (isLoading ? (
+ (!revealed ? (
+ <FieldRow
+ fitLabel
+ label={t('creds.view.values')}
+ extra={
+ <Button
+ icon={<Icon icon={Eye} />}
+ size={'small'}
+ type={'text'}
+ onClick={() => setRevealed(true)}
+ >
+ {t('creds.view.showValues')}
+ </Button>
+ }
+ >
+ <span {...stylex.props(styles.code, styles.masked)}>{MASK}</span>
+ </FieldRow>
+ ) : isLoading ? (
<FieldRow label={<SkeletonBar height={12} width={72} />}>
<SkeletonBar height={12} width={160} />
</FieldRow>
diff --git a/src/features/Settings/creds/features/WorkspaceCredsList.test.tsx b/src/features/Settings/creds/features/WorkspaceCredsList.test.tsx
index 200a941165b..53efde3ec9f 100644
--- a/src/features/Settings/creds/features/WorkspaceCredsList.test.tsx
+++ b/src/features/Settings/creds/features/WorkspaceCredsList.test.tsx
@@ -1,5 +1,5 @@
import { type UserCredSummary } from '@lobechat/types';
-import { fireEvent, render, screen, within } from '@testing-library/react';
+import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { type CredsApi } from './useCredsApi';
@@ -15,6 +15,11 @@ vi.mock('@/hooks/usePermission', () => ({
vi.mock('@/libs/trpc/client', () => ({ lambdaClient: { market: { creds: {} } } }));
+vi.mock('@/store/user', () => ({
+ useUserStore: (selector: (s: unknown) => unknown) =>
+ selector({ user: { avatar: 'me.png', fullName: 'Me' } }),
+}));
+
const { createViewCredModal } = vi.hoisted(() => ({ createViewCredModal: vi.fn() }));
vi.mock('./ViewCredModal', () => ({ createViewCredModal }));
@@ -49,45 +54,55 @@ const credsApiWith = (rows: UserCredSummary[]) =>
}) as unknown as CredsApi;
describe('WorkspaceCredsList', () => {
- it('lists shared and private credentials together and locks only the private ones', () => {
+ it("shows each row's visibility and, for the viewer's own credentials, their avatar", () => {
render(
<WorkspaceCredsList
credsApi={credsApiWith([
cred({ id: 1, key: 'TEAM_TOKEN', name: 'Team token', visibility: 'public' }),
cred({ id: 2, key: 'MY_TOKEN', name: 'My token', visibility: 'private' }),
+ cred({ createdByAccountId: 9, id: 3, key: 'OTHER', name: 'Other', visibility: 'public' }),
])}
/>,
);
- const shared = screen.getByText('Team token').parentElement!;
- const mine = screen.getByText('My token').parentElement!;
-
- expect(within(shared).queryByTestId('private-lock')).toBeNull();
- expect(within(mine).getByTestId('private-lock')).toBeInTheDocument();
- expect(screen.getAllByTestId('private-lock')).toHaveLength(1);
+ // Visibility is an icon beside the name (team or lock), labelled for screen readers.
+ const workspaceIcon = screen.getByTestId('cred-visibility-1');
+ expect(workspaceIcon).toHaveAttribute('data-visibility', 'workspace');
+ expect(workspaceIcon).toHaveAccessibleName('visibilityFilter.workspace');
+ expect(workspaceIcon.parentElement).toHaveTextContent('Team token');
+ expect(screen.getByTestId('cred-visibility-2')).toHaveAttribute('data-visibility', 'private');
+ expect(screen.queryByText('visibilityFilter.workspace')).toBeNull();
+ expect(screen.getByTestId('cred-author-1')).toBeInTheDocument();
+ // Market returns no profile for another member's workspace credential.
+ expect(screen.queryByTestId('cred-author-3')).toBeNull();
+ // The row no longer carries a write-only tag or a private lock.
+ expect(screen.queryByText('creds.writeOnly.tag')).toBeNull();
+ expect(screen.queryByTestId('private-lock')).toBeNull();
});
- it('marks only workspace credentials shared with everyone as write-only', () => {
+ it('explains write-only values in the detail instead of reading them', () => {
render(
<WorkspaceCredsList
credsApi={credsApiWith([
cred({ id: 1, key: 'TEAM_TOKEN', name: 'Team token', visibility: 'public' }),
cred({ id: 2, key: 'MY_TOKEN', name: 'My token', visibility: 'private' }),
- cred({
- id: 3,
- key: 'SHARED_IN',
- name: 'Shared in',
- ownerAccountId: 1,
- ownerType: 'user',
- visibility: 'public',
- }),
])}
/>,
);
- // Only "Team token": the private one stays readable by its creator, and a
- // personal credential shared in stays readable by its owner.
- expect(screen.getAllByText('creds.writeOnly.tag')).toHaveLength(1);
+ fireEvent.click(screen.getByRole('button', { name: /Team token/ }));
+ fireEvent.click(screen.getByRole('button', { name: /My token/ }));
+
+ const [team, mine] = createViewCredModal.mock.calls.map((call) => call[0]);
+ expect(team.canReadValues).toBe(false);
+ expect(team.valuesHint).toBe('creds.writeOnly.tooltip');
+ expect(mine.canReadValues).toBe(true);
+ expect(mine.valuesHint).toBeUndefined();
+ expect(mine.extraItems.map((item: { key: string }) => item.key)).toEqual([
+ 'visibility',
+ 'author',
+ ]);
+ createViewCredModal.mockClear();
});
it('opens the detail from the row, carrying its remove, edit and visibility actions', () => {
diff --git a/src/features/Settings/creds/features/WorkspaceCredsList.tsx b/src/features/Settings/creds/features/WorkspaceCredsList.tsx
index a8f403596d0..33cea0b3a01 100644
--- a/src/features/Settings/creds/features/WorkspaceCredsList.tsx
+++ b/src/features/Settings/creds/features/WorkspaceCredsList.tsx
@@ -1,19 +1,22 @@
'use client';
import { type UserCredSummary } from '@lobechat/types';
-import { Empty, Flexbox, Tag, toast, Tooltip } from '@lobehub/ui';
-import { EyeOffIcon, GlobeIcon } from 'lucide-react';
+import { Empty, Flexbox, Icon, toast, Tooltip } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import { EyeOffIcon, GlobeIcon, LockIcon, UsersIcon } from 'lucide-react';
import { type FC } from 'react';
import { useTranslation } from 'react-i18next';
import AsyncBoundary from '@/components/AsyncBoundary';
-import PrivateLockIcon from '@/components/PrivateLockIcon';
+import Avatar from '@/components/Avatar';
import { CredsListSkeleton } from '@/components/Skeleton/Settings/tabs/Creds';
import { matchesVisibilityFilter, type VisibilityFilterValue } from '@/components/VisibilityFilter';
import VisibilityConfirmContent from '@/features/VisibilityConfirmContent';
import { usePermission } from '@/hooks/usePermission';
import { useMarketAuth } from '@/layout/AuthProvider/MarketAuth';
import { lambdaClient } from '@/libs/trpc/client';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
import { confirmCredModal } from './confirmCredModal';
import { isOwnCredRow, isWriteOnlyCredRow, workspaceCredRowAccess } from './credAccess';
@@ -52,6 +55,8 @@ const WorkspaceCredsList: FC<WorkspaceCredsListProps> = ({
const { session } = useMarketAuth();
const { allowed: isAdmin } = usePermission('manage_provider_key');
const myAccountId = session?.userInfo?.accountId;
+ const myAvatar = useUserStore(userProfileSelectors.userAvatar);
+ const myName = useUserStore(userProfileSelectors.displayUserName);
const { data, error, isLoading, refetch } = credsApi.query.list.useQuery();
const credentials = data?.data ?? [];
@@ -108,6 +113,30 @@ const WorkspaceCredsList: FC<WorkspaceCredsListProps> = ({
const handleDelete = (id: number) => run(() => credsApi.client.delete.mutate({ id }));
+ /**
+ * Who a row belongs to: a shared personal credential names its owner; a
+ * workspace credential is attributed only when the viewer created it —
+ * Market returns no profile for other creators.
+ */
+ const authorOf = (cred: UserCredSummary): { avatar?: string; name: string } | undefined => {
+ if (cred.ownerType === 'user') {
+ return isOwnCredRow(cred, myAccountId)
+ ? { avatar: myAvatar, name: myName }
+ : cred.ownerDisplayName
+ ? { name: cred.ownerDisplayName }
+ : undefined;
+ }
+ if (myAccountId !== undefined && cred.createdByAccountId === myAccountId) {
+ return { avatar: myAvatar, name: myName };
+ }
+ return undefined;
+ };
+
+ const visibilityLabel = (cred: UserCredSummary) =>
+ cred.visibility === 'private'
+ ? t('visibilityFilter.private', { ns: 'common' })
+ : t('visibilityFilter.workspace', { ns: 'common' });
+
return (
<AsyncBoundary
data={data}
@@ -129,6 +158,7 @@ const WorkspaceCredsList: FC<WorkspaceCredsListProps> = ({
{visibleCredentials.map((cred) => {
const access = workspaceCredRowAccess(cred, { isAdmin, myAccountId });
const writeOnly = isWriteOnlyCredRow(cred);
+ const author = authorOf(cred);
const actions: CredDetailAction[] = [
...(access.publish
? [
@@ -166,21 +196,38 @@ const WorkspaceCredsList: FC<WorkspaceCredsListProps> = ({
<CredItem
cred={cred}
key={cred.id}
- titleSuffix={cred.visibility === 'private' && <PrivateLockIcon />}
- tags={
- cred.ownerType === 'user' ? (
- <Tag>
- {isOwnCredRow(cred, myAccountId)
- ? t('creds.owner.fromPersonal')
- : t('creds.owner.sharedBy', { name: cred.ownerDisplayName })}
- </Tag>
- ) : (
- writeOnly && (
- <Tooltip title={t('creds.writeOnly.tooltip')}>
- <Tag>{t('creds.writeOnly.tag')}</Tag>
+ extra={
+ <>
+ {author && (
+ <Tooltip title={author.name}>
+ <span data-testid={`cred-author-${cred.id}`} style={{ display: 'flex' }}>
+ <Avatar
+ avatar={author.avatar}
+ name={author.name}
+ size={24}
+ title={author.name}
+ />
+ </span>
</Tooltip>
- )
- )
+ )}
+ </>
+ }
+ titleSuffix={
+ <Tooltip title={visibilityLabel(cred)}>
+ <span
+ aria-label={visibilityLabel(cred)}
+ data-testid={`cred-visibility-${cred.id}`}
+ data-visibility={cred.visibility === 'private' ? 'private' : 'workspace'}
+ role={'img'}
+ style={{
+ color: cssVar.colorTextTertiary,
+ display: 'inline-flex',
+ flex: 'none',
+ }}
+ >
+ <Icon icon={cred.visibility === 'private' ? LockIcon : UsersIcon} size={14} />
+ </span>
+ </Tooltip>
}
onClick={() =>
createViewCredModal({
@@ -188,6 +235,25 @@ const WorkspaceCredsList: FC<WorkspaceCredsListProps> = ({
canReadValues: access.manage && !writeOnly,
cred,
credsApi,
+ extraItems: [
+ {
+ children: visibilityLabel(cred),
+ key: 'visibility',
+ label: t('creds.detail.visibility'),
+ },
+ ...(author
+ ? [
+ {
+ children:
+ cred.ownerType === 'user' && isOwnCredRow(cred, myAccountId)
+ ? t('creds.owner.fromPersonal')
+ : author.name,
+ key: 'author',
+ label: t('creds.detail.author'),
+ },
+ ]
+ : []),
+ ],
onDelete: access.manage ? handleDelete : undefined,
onEdit: access.manage
? () =>
@@ -198,6 +264,7 @@ const WorkspaceCredsList: FC<WorkspaceCredsListProps> = ({
writeOnly,
})
: undefined,
+ valuesHint: access.manage && writeOnly ? t('creds.writeOnly.tooltip') : undefined,
})
}
/>
diff --git a/src/features/Settings/creds/features/credFilter.test.ts b/src/features/Settings/creds/features/credFilter.test.ts
index 60f279e0ec7..c408b274b76 100644
--- a/src/features/Settings/creds/features/credFilter.test.ts
+++ b/src/features/Settings/creds/features/credFilter.test.ts
@@ -14,12 +14,15 @@ describe('filterCreds', () => {
expect(filterCreds([...creds], { keyword: ' ', type: 'all' })).toHaveLength(3);
});
- it('matches the keyword against name, key and description, ignoring case', () => {
+ it('matches the keyword against name and description, ignoring case', () => {
expect(filterCreds([...creds], { keyword: 'OPENAI' }).map((c) => c.key)).toEqual(['openai']);
- expect(filterCreds([...creds], { keyword: 'gcp-sa' }).map((c) => c.key)).toEqual(['gcp-sa']);
expect(filterCreds([...creds], { keyword: 'coder' }).map((c) => c.key)).toEqual(['openai']);
});
+ it('does not match the hidden key', () => {
+ expect(filterCreds([...creds], { keyword: 'gcp-sa' })).toEqual([]);
+ });
+
it('narrows by type and combines with the keyword', () => {
expect(filterCreds([...creds], { type: 'oauth' }).map((c) => c.key)).toEqual(['github']);
expect(filterCreds([...creds], { keyword: 'openai', type: 'file' })).toEqual([]);
diff --git a/src/features/Settings/creds/features/credFilter.ts b/src/features/Settings/creds/features/credFilter.ts
index b6ff5d71131..9d8ce97f833 100644
--- a/src/features/Settings/creds/features/credFilter.ts
+++ b/src/features/Settings/creds/features/credFilter.ts
@@ -26,9 +26,9 @@ export const filterCreds = <
if (type && type !== 'all' && cred.type !== type) return false;
if (!needle) return true;
- return [cred.name, cred.key, cred.description].some((text) =>
- text?.toLowerCase().includes(needle),
- );
+ // Not the key: it is generated and never shown, so matching it would
+ // surface rows for text the user cannot see.
+ return [cred.name, cred.description].some((text) => text?.toLowerCase().includes(needle));
});
};