/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffectEvent } from '../../../../hooks/common/useEffectEvent';
import React, { useEffect, useState, useContext, useRef } from 'react';
import {
API,
showError,
showSuccess,
renderGroupOption,
getModelCategories,
selectFilter,
} from '../../../../helpers';
import { FormQuotaInput } from '../../../common/ui/QuotaInput';
import { useIsMobile } from '../../../../hooks/common/useIsMobile';
import {
Button,
Modal,
Spin,
Form,
Collapsible,
DatePicker,
} from '@/components/ui';
import { IconChevronDown } from '@/components/ui/icons';
import {
Key,
CreditCard,
Shield,
X,
Check,
Settings2,
Calendar,
Hash,
Layers,
Infinity,
} from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { StatusContext } from '../../../../context/Status';
import EditTokenDrawer from './EditTokenDrawer';
const EditTokenModal = (props) => {
const { t: originalT } = useTranslation();
const t = props.labelReplace
? (key, options) => {
const result = originalT(key, options);
return typeof result === 'string'
? result.replace(/密钥/g, props.labelReplace)
: result;
}
: originalT;
const [statusState] = useContext(StatusContext);
const [loading, setLoading] = useState(false);
const [advancedOpen, setAdvancedOpen] = useState(false);
const [neverExpire, setNeverExpire] = useState(true);
const [expireDate, setExpireDate] = useState(null);
const isMobile = useIsMobile();
const formApiRef = useRef(null);
const [models, setModels] = useState([]);
const [skillOptions, setSkillOptions] = useState([]);
const [groups, setGroups] = useState([]);
const isEdit = props.editingToken.id !== undefined;
// 默认分组配置
const DEFAULT_GROUP = 'claude专用分组';
// 生成默认名称:claude + 随机两位整数
const generateDefaultName = () => {
const randomNum = Math.floor(Math.random() * 100)
.toString()
.padStart(2, '0');
return `claude${randomNum}`;
};
const getInitValues = () => ({
name: generateDefaultName(),
remain_quota: 0,
unlimited_quota: true,
model_limits_enabled: false,
model_limits: [],
allow_ips: '',
group: '', // 分组在 loadGroups 后动态设置
tokenCount: 1,
// 技能注入:默认关闭,存量密钥零影响
skill_injection_enabled: false,
skill_ids: [],
});
const handleCancel = () => {
setAdvancedOpen(false);
setNeverExpire(true);
setExpireDate(null);
props.handleClose();
};
const setExpiredTime = (month, day, hour, minute) => {
if (month === 0 && day === 0 && hour === 0 && minute === 0) {
setNeverExpire(true);
setExpireDate(null);
return;
}
setNeverExpire(false);
let now = new Date();
let timestamp = now.getTime();
let ms = month * 30 * 24 * 60 * 60 * 1000;
ms += day * 24 * 60 * 60 * 1000;
ms += hour * 60 * 60 * 1000;
ms += minute * 60 * 1000;
setExpireDate(new Date(timestamp + ms));
};
// 设置默认分组:优先 claude专用分组,否则第一个分组
const setDefaultGroup = (groupOptions) => {
if (!formApiRef.current || groupOptions.length === 0) return;
const hasDefaultGroup = groupOptions.some((g) => g.value === DEFAULT_GROUP);
const defaultValue = hasDefaultGroup
? DEFAULT_GROUP
: groupOptions[0].value;
formApiRef.current.setValue('group', defaultValue);
};
// 绑定技能的候选集取自技能超市目录(平台已发布集)。
// 这里刻意不做治理判定:企业密钥即便勾了企业未启用的技能,
// 后端解析层也只会收窄不会扩权(skillinject.resolveOrganization),
// 前端再判一次只会产生两套口径。
const loadSkillOptions = async () => {
// 必须翻页取全,不能"取一页当全量":服务端单页上限 100,而平台已发布技能
// 有数百个,只取首页会让第 101 个之后的技能永远无法被绑定,且界面上毫无提示。
// 这与 R19 修掉的企业技能市场固定 200 一页是同一型缺陷。
const pageSize = 100;
const maxPages = 20; // 兜底,防止服务端 total 异常时无限翻页
try {
const collected = [];
let offset = 0;
for (let page = 0; page < maxPages; page += 1) {
const res = await API.get('/api/skills/market', {
params: { page_size: pageSize, offset },
});
if (!res.data?.success) break;
const batch = res.data.data || [];
collected.push(...batch);
offset += batch.length;
if (batch.length < pageSize || offset >= (res.data.total || 0)) break;
}
setSkillOptions(
collected.map((skill) => ({
label: skill.name || skill.canonical_id,
value: skill.id,
})),
);
} catch (_error) {
setSkillOptions([]);
}
};
const loadModels = async () => {
let res = await API.get(`/api/user/models`);
const { success, message, data } = res.data;
if (success) {
const categories = getModelCategories(t);
let localModelOptions = data.map((model) => {
let icon = null;
for (const [key, category] of Object.entries(categories)) {
if (key !== 'all' && category.filter({ model_name: model })) {
icon = category.icon;
break;
}
}
return {
label: (
{icon}
{model}
),
value: model,
};
});
setModels(localModelOptions);
} else {
showError(t(message));
}
};
const loadGroups = async () => {
let res = await API.get(`/api/user/self/groups`);
const { success, message, data } = res.data;
if (success) {
let localGroupOptions = Object.entries(data).map(([group, info]) => ({
label: group,
value: group,
ratio: info.ratio,
description: info.desc,
fullLabel: info.desc,
}));
if (statusState?.status?.default_use_auto_group) {
if (localGroupOptions.some((group) => group.value === 'auto')) {
localGroupOptions.sort((a, b) => (a.value === 'auto' ? -1 : 1));
}
}
setGroups(localGroupOptions);
// 新建模式下设置默认分组
if (!isEdit) {
setDefaultGroup(localGroupOptions);
}
} else {
showError(t(message));
}
};
const loadToken = async () => {
setLoading(true);
let res = await API.get(`/api/token/${props.editingToken.id}`);
const { success, message, data } = res.data;
if (success) {
// 处理过期时间
if (data.expired_time === -1) {
setNeverExpire(true);
setExpireDate(null);
} else {
setNeverExpire(false);
setExpireDate(new Date(data.expired_time * 1000));
}
if (data.model_limits !== '') {
data.model_limits = data.model_limits.split(',');
} else {
data.model_limits = [];
}
// tokens.skill_ids 存的是 JSON 数组文本,表单要的是数组。
// 解析失败退化为空数组(=跟随身份有效集),不因一条坏数据卡住整个编辑页。
if (typeof data.skill_ids === 'string') {
try {
const parsed = JSON.parse(data.skill_ids || '[]');
data.skill_ids = Array.isArray(parsed) ? parsed : [];
} catch (_error) {
data.skill_ids = [];
}
} else if (!Array.isArray(data.skill_ids)) {
data.skill_ids = [];
}
// 移除 expired_time,因为我们单独管理
const { expired_time, ...restData } = data;
if (formApiRef.current) {
formApiRef.current.setValues({ ...getInitValues(), ...restData });
}
if (
data.model_limits?.length > 0 ||
data.allow_ips ||
!data.unlimited_quota ||
data.skill_injection_enabled
) {
setAdvancedOpen(true);
}
} else {
showError(message);
}
setLoading(false);
};
const onScopeChange = useEffectEvent(() => {
if (formApiRef.current) {
if (!isEdit) {
formApiRef.current.setValues(getInitValues());
}
}
loadModels();
loadGroups();
loadSkillOptions();
});
useEffect(() => onScopeChange(), [onScopeChange, props.editingToken.id]);
const onVisibilityChange2 = useEffectEvent(() => {
if (props.visiable) {
if (isEdit) {
loadToken();
} else {
formApiRef.current?.setValues(getInitValues());
setAdvancedOpen(false);
setNeverExpire(true);
setExpireDate(null);
// 如果 groups 已加载,设置默认分组
if (groups.length > 0) {
setDefaultGroup(groups);
}
}
} else {
formApiRef.current?.reset();
setAdvancedOpen(false);
setNeverExpire(true);
setExpireDate(null);
}
});
useEffect(
() => onVisibilityChange2(),
[onVisibilityChange2, props.visiable, props.editingToken.id],
);
const generateRandomSuffix = () => {
const characters =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < 6; i++) {
result += characters.charAt(
Math.floor(Math.random() * characters.length),
);
}
return result;
};
// 创建/编辑共用的载荷构造(R26 教训:双分支各自维护同构逻辑,漏一边就出
// skill_ids 未序列化这类漂移故障,统一出口杜绝分叉)。
// - remain_quota 表单值是字符串,落库要整数
// - model_limits 表单值是数组,接口契约是逗号分隔文本
// - skill_ids 表单值是数组,tokens.skill_ids 落库是 JSON 数组文本;
// 空数组语义是"跟随身份有效集",与"未开启注入"不是一回事,
// 因此关闭注入时也如实提交空数组。
const buildTokenPayload = (values, expired_time) => {
const { tokenCount: _tc, ...payload } = values;
payload.remain_quota = parseInt(payload.remain_quota);
payload.expired_time = expired_time;
payload.model_limits = payload.model_limits.join(',');
payload.model_limits_enabled = payload.model_limits.length > 0;
payload.skill_ids = JSON.stringify(payload.skill_ids || []);
return payload;
};
const submit = async (values) => {
// 验证过期时间
if (!neverExpire && !expireDate) {
showError(t('请选择过期时间'));
return;
}
if (!neverExpire && expireDate && expireDate.getTime() <= Date.now()) {
showError(t('过期时间不能早于当前时间'));
return;
}
setLoading(true);
// 计算过期时间
const expired_time = neverExpire
? -1
: Math.ceil(expireDate.getTime() / 1000);
if (isEdit) {
const localInputs = buildTokenPayload(values, expired_time);
let res = await API.put(`/api/token/`, {
...localInputs,
id: parseInt(props.editingToken.id),
});
const { success, message } = res.data;
if (success) {
showSuccess(t('密钥更新成功!'));
props.refresh();
props.handleClose();
} else {
showError(t(message));
}
} else {
const count = parseInt(values.tokenCount, 10) || 1;
let successCount = 0;
for (let i = 0; i < count; i++) {
const localInputs = buildTokenPayload(values, expired_time);
const baseName =
values.name.trim() === '' ? 'default' : values.name.trim();
if (i !== 0 || values.name.trim() === '') {
localInputs.name = `${baseName}-${generateRandomSuffix()}`;
} else {
localInputs.name = baseName;
}
let res = await API.post(`/api/token/`, localInputs);
const { success, message } = res.data;
if (success) {
successCount++;
} else {
showError(t(message));
break;
}
}
if (successCount > 0) {
showSuccess(t('密钥创建成功,请在列表页面点击复制获取密钥!'));
props.refresh();
props.handleClose();
}
}
setLoading(false);
formApiRef.current?.setValues(getInitValues());
};
// 自定义标签组件
const FieldLabel = ({ icon: Icon, iconColor, children, required }) => (
{children}
{required && *}
);
// 密钥管理页使用抽屉形态(密钥管理页面.zip);状态、请求与载荷仍由本组件统一提供。
if (props.presentation === 'drawer') {
return (
);
}
return (
{/* 头部 */}
{isEdit ? t('编辑密钥') : t('创建密钥')}
{isEdit ? t('修改密钥配置') : t('快速创建访问密钥')}
{/* 表单内容 */}
{/* 底部按钮 */}
);
};
export default EditTokenModal;