Skip to content

Commit 2a1c7d0

Browse files
committed
Mask api key for api key page(protect from screenshot etc)
1 parent d854bc9 commit 2a1c7d0

2 files changed

Lines changed: 24 additions & 3 deletions

File tree

src/FE/components/settings/tabs/ApiKeysTab.tsx

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import { useRouter } from 'next/router';
66

77
import useTranslation from '@/hooks/useTranslation';
88

9-
import { getApiUrl } from '@/utils/common';
9+
import { getApiUrl, maskApiKey } from '@/utils/common';
1010
import { formatDate } from '@/utils/date';
1111

1212
import { UsageSource } from '@/types/chat';
@@ -151,7 +151,7 @@ const ApiKeysTab = () => {
151151
className="max-w-[180px] truncate cursor-pointer text-blue-600 hover:underline"
152152
onClick={() => viewApiKeyUsage(x.id)}
153153
>
154-
{x.key}
154+
{maskApiKey(x.key)}
155155
</span>
156156
<CopyButton value={x.key} />
157157
</div>
@@ -220,7 +220,7 @@ const ApiKeysTab = () => {
220220
className="overflow-hidden text-ellipsis whitespace-nowrap text-blue-600 hover:underline cursor-pointer"
221221
onClick={() => viewApiKeyUsage(x.id)}
222222
>
223-
{x.key}
223+
{maskApiKey(x.key)}
224224
</div>
225225
<CopyButton value={x.key} />
226226
</div>

src/FE/utils/common.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,3 +80,24 @@ export function resolveTheme(theme?: string): 'dark' | 'light' {
8080
}
8181
return theme === 'dark' ? 'dark' : 'light';
8282
}
83+
84+
/**
85+
* 遮蔽API密钥,显示前缀和后缀,隐藏中间部分
86+
* @param key API密钥
87+
* @param prefixLength 前缀长度,默认6
88+
* @param suffixLength 后缀长度,默认4
89+
* @returns 遮蔽后的密钥,例如 "sk-abc1***xyz9"
90+
*/
91+
export function maskApiKey(
92+
key: string,
93+
prefixLength: number = 6,
94+
suffixLength: number = 4,
95+
): string {
96+
if (!key) return '';
97+
if (key.length <= prefixLength + suffixLength) {
98+
return key;
99+
}
100+
const prefix = key.slice(0, prefixLength);
101+
const suffix = key.slice(-suffixLength);
102+
return `${prefix}***${suffix}`;
103+
}

0 commit comments

Comments
 (0)