feat: add model groups, verified registration and CNY credit grants

This commit is contained in:
wlx committed 2026-09-18 17:27:58 +08:00
1 parent f5ba6cb255
commit 7a18db2123
40 files changed
+1980 -263

No files matched your search

+9
View File
@@ -20,6 +20,15 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>4.6.0</version>
</dependency>
<dependency> <dependency>
<groupId>org.springframework.boot</groupId> <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId> <artifactId>spring-boot-starter-web</artifactId>
@@ -6,6 +6,11 @@ import org.springframework.web.bind.annotation.RestController;
@RestController @RestController
public class HealthController { public class HealthController {
private final com.moyi.controlplane.auth.VerificationService verification;
public HealthController(com.moyi.controlplane.auth.VerificationService verification) {
this.verification = verification;
}
@GetMapping("/health") @GetMapping("/health")
public Map<String, Object> health() { public Map<String, Object> health() {
return Map.of( return Map.of(
@@ -13,7 +18,7 @@ public class HealthController {
"service", "moyi-control-plane-java", "service", "moyi-control-plane-java",
"migration", "catalog", "migration", "catalog",
"capabilities", Map.of( "capabilities", Map.of(
"verificationCode", false, "verificationCode", verification.capabilities().containsValue(true),
"passwordReset", false "passwordReset", false
) )
); );
@@ -26,26 +26,44 @@ import org.springframework.web.bind.annotation.RestController;
public class AuthController { public class AuthController {
private static final String SESSION_COOKIE = "moyi_session"; private static final String SESSION_COOKIE = "moyi_session";
private final AuthService authService; private final AuthService authService;
private final VerificationService verification;
private final int sessionTtlHours; private final int sessionTtlHours;
private final boolean secureCookie; private final boolean secureCookie;
public AuthController( public AuthController(
AuthService authService, AuthService authService,
VerificationService verification,
@Value("${moyi.auth.session-ttl-hours}") int sessionTtlHours, @Value("${moyi.auth.session-ttl-hours}") int sessionTtlHours,
@Value("${moyi.auth.secure-cookie}") boolean secureCookie @Value("${moyi.auth.secure-cookie}") boolean secureCookie
) { ) {
this.authService = authService; this.authService = authService;
this.verification = verification;
this.sessionTtlHours = sessionTtlHours; this.sessionTtlHours = sessionTtlHours;
this.secureCookie = secureCookie; this.secureCookie = secureCookie;
} }
public record LoginRequest(String account, String password) {} public record LoginRequest(String account, String password) {}
public record RegisterRequest(String invitationCode, String account, String password, String displayName) {} public record RegisterRequest(String invitationCode, String account, String password, String displayName, String verificationCode) {}
public record CodeRequest(String account, String invitationCode) {}
@GetMapping("/auth/verification")
public Map<String,Boolean> verificationStatus() { return verification.capabilities(); }
@PostMapping("/auth/verification")
public Map<String,Object> sendCode(@RequestBody CodeRequest input,HttpServletRequest request) {
return verification.send(input.account(),input.invitationCode(),request.getRemoteAddr());
}
public record InvitationRequest(String label, Integer maxUses, OffsetDateTime expiresAt) {} public record InvitationRequest(String label, Integer maxUses, OffsetDateTime expiresAt) {}
public record RoleRequest(String role) {} public record RoleRequest(String role) {}
public record CreateUserRequest(String account, String password, String displayName) {}
@PostMapping("/admin/users")
public ResponseEntity<Map<String,Object>> createUser(@RequestBody CreateUserRequest input, HttpServletRequest request) {
return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("user",authService.createUser(sessionToken(request),input.account(),input.password(),input.displayName(),meta(request))));
}
@PostMapping("/auth/login") @PostMapping("/auth/login")
public Map<String, Object> login( public Map<String, Object> login(
@@ -64,6 +82,7 @@ public class AuthController {
HttpServletRequest request, HttpServletRequest request,
HttpServletResponse response HttpServletResponse response
) { ) {
verification.consume(input.account(),input.verificationCode());
AuthService.AuthResult result = authService.register( AuthService.AuthResult result = authService.register(
input.invitationCode(), input.account(), input.password(), input.displayName(), meta(request) input.invitationCode(), input.account(), input.password(), input.displayName(), meta(request)
); );
@@ -234,6 +234,25 @@ public class AuthService {
return jdbc.query("SELECT * FROM users ORDER BY created_at DESC", this::mapUser).stream().map(user -> toView(user, null)).toList(); return jdbc.query("SELECT * FROM users ORDER BY created_at DESC", this::mapUser).stream().map(user -> toView(user, null)).toList();
} }
@Transactional
public UserView createUser(String token, String accountInput, String password, String displayName, RequestMeta meta) {
UserView actor=requireAdmin(token);
String account=normalizeAccount(accountInput);
if(account.isBlank() || account.length()>254 || (!EMAIL.matcher(account).matches() && !PHONE.matcher(account).matches() && !account.matches("[a-z0-9_]{3,64}"))) throw new ApiException("INVALID_ACCOUNT","请输入有效邮箱、手机号或 3 至 64 位字母数字下划线用户名");
if(password==null || password.length()<8 || password.length()>256) throw new ApiException("WEAK_PASSWORD","普通用户密码长度为 8 至 256 位");
if(findUserByAccount(account)!=null) throw new ApiException("ACCOUNT_EXISTS","账号已存在",409);
String name=displayName==null || displayName.isBlank()?defaultDisplayName(account):displayName.trim();
if(name.length()>80) throw new ApiException("INVALID_NAME","显示名称最多 80 字符");
UUID id=UUID.randomUUID();
jdbc.update("INSERT INTO users(id,account,account_kind,password_hash,display_name,role,status) VALUES (?,?,?,?,?,'user','active')",id,account,accountKind(account),passwordHasher.hash(password),name);
authCreatedAudit(actor.id(),id,meta);
return toView(findUserById(id),null);
}
private void authCreatedAudit(UUID actor, UUID user, RequestMeta meta) {
audit("user.admin_created",actor,meta,Map.of("targetUserId",user));
}
@Transactional @Transactional
public Map<String, Object> createInvitation( public Map<String, Object> createInvitation(
String token, String token,
@@ -0,0 +1,63 @@
package com.moyi.controlplane.auth;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.moyi.controlplane.common.ApiException;
import org.springframework.core.env.Environment;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.stereotype.Component;
@Component
public class CloudVerificationSender implements VerificationSender {
private final Environment env;
public CloudVerificationSender(Environment env) { this.env=env; }
private String value(String key) { return env.getProperty(key,"").trim(); }
@Override
public boolean available(String channel) {
if("email".equals(channel)) return !value("MOYI_SMTP_HOST").isEmpty() && !value("MOYI_SMTP_FROM").isEmpty();
return !value("MOYI_SMS_ACCESS_KEY_ID").isEmpty() && !value("MOYI_SMS_ACCESS_KEY_SECRET").isEmpty() && !value("MOYI_SMS_SIGN_NAME").isEmpty() && !value("MOYI_SMS_TEMPLATE_CODE").isEmpty();
}
@Override
public void send(String channel,String account,String code) {
if(!available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
try {
if("email".equals(channel)) {
JavaMailSenderImpl mail=new JavaMailSenderImpl();
mail.setHost(value("MOYI_SMTP_HOST"));
mail.setPort(env.getProperty("MOYI_SMTP_PORT",Integer.class,465));
mail.setUsername(value("MOYI_SMTP_USERNAME"));
mail.setPassword(env.getProperty("MOYI_SMTP_PASSWORD",""));
mail.setDefaultEncoding("UTF-8");
var properties=mail.getJavaMailProperties();
properties.setProperty("mail.smtp.auth",String.valueOf(!value("MOYI_SMTP_USERNAME").isEmpty()));
properties.setProperty("mail.smtp.ssl.enable",env.getProperty("MOYI_SMTP_SSL","true"));
properties.setProperty("mail.smtp.starttls.enable",env.getProperty("MOYI_SMTP_STARTTLS","false"));
properties.setProperty("mail.smtp.starttls.required",env.getProperty("MOYI_SMTP_STARTTLS","false"));
properties.setProperty("mail.smtp.ssl.checkserveridentity","true");
properties.setProperty("mail.smtp.connectiontimeout","5000");
properties.setProperty("mail.smtp.timeout","10000");
properties.setProperty("mail.smtp.writetimeout","10000");
SimpleMailMessage message=new SimpleMailMessage();
message.setFrom(value("MOYI_SMTP_FROM"));
message.setTo(account);
message.setSubject("MOYI 注册验证码");
message.setText("您的注册验证码为:"+code+",5 分钟内有效。请勿向他人泄露。若非本人操作,请忽略此邮件。");
mail.send(message);
} else {
Config config=new Config().setAccessKeyId(value("MOYI_SMS_ACCESS_KEY_ID")).setAccessKeySecret(value("MOYI_SMS_ACCESS_KEY_SECRET")).setEndpoint("dysmsapi.aliyuncs.com").setProtocol("https");
var client=new com.aliyun.dysmsapi20170525.Client(config);
var request=new SendSmsRequest().setPhoneNumbers(account.startsWith("+86")?account.substring(3):account)
.setSignName(value("MOYI_SMS_SIGN_NAME")).setTemplateCode(value("MOYI_SMS_TEMPLATE_CODE")).setTemplateParam("{\"code\":\""+code+"\"}");
var response=client.sendSmsWithOptions(request,new RuntimeOptions().setAutoretry(false).setConnectTimeout(5000).setReadTimeout(10000));
if(response.getBody()==null || !"OK".equals(response.getBody().getCode())) throw new IllegalStateException("SMS rejected");
}
} catch(Exception exception) {
// SDK exceptions may contain credentials or recipients. Never expose them to logs or clients.
throw new ApiException("VERIFICATION_SEND_FAILED","验证码发送失败,请稍后重试或联系管理员检查发送服务",502);
}
}
}
@@ -0,0 +1,6 @@
package com.moyi.controlplane.auth;
public interface VerificationSender {
boolean available(String channel);
void send(String channel, String account, String code);
}
@@ -0,0 +1,69 @@
package com.moyi.controlplane.auth;
import com.moyi.controlplane.common.ApiException;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.nio.charset.StandardCharsets;
import java.time.OffsetDateTime;
import java.util.Locale;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class VerificationService {
private final JdbcTemplate jdbc;
private final VerificationSender sender;
private final String pepper;
private final SecureRandom random=new SecureRandom();
public VerificationService(JdbcTemplate jdbc,VerificationSender sender,@Value("${moyi.auth.password-pepper}") String pepper) {
this.jdbc=jdbc; this.sender=sender; this.pepper=pepper;
}
public Map<String,Boolean> capabilities() { return Map.of("email",sender.available("email"),"phone",sender.available("phone")); }
public String normalize(String raw) {
String account=raw==null?"":raw.trim().toLowerCase(Locale.ROOT);
if(!account.contains("@")) account=account.replaceAll("[\\s-]","");
if(account.length()>254 || (!account.matches("^[^\\s@,;<>]+@[^\\s@,;<>]+\\.[^\\s@,;<>]+$") && !account.matches("^(?:\\+86)?1[3-9][0-9]{9}$"))) throw new ApiException("INVALID_ACCOUNT","请输入有效邮箱或中国大陆手机号");
return account;
}
private String digest(String account,String code) { return AuthService.hashSecret(pepper+":registration:"+account+":"+code); }
@Transactional(noRollbackFor=ApiException.class)
public Map<String,Object> send(String raw,String invitation,String ip) {
String account=normalize(raw), channel=account.contains("@")?"email":"phone";
if(!sender.available(channel)) throw new ApiException("VERIFICATION_UNAVAILABLE","该验证码发送服务尚未配置,请联系管理员",503);
Integer invites=jdbc.queryForObject("SELECT count(*) FROM invitation_codes WHERE code_hash=? AND disabled_at IS NULL AND used_count<max_uses AND (expires_at IS NULL OR expires_at>now())",Integer.class,AuthService.hashSecret(invitation==null?"":invitation.trim()));
if(invites==null || invites==0) throw new ApiException("INVITATION_INVALID","请先填写有效邀请码",403);
String source=ip==null?"unknown":ip;
// One global lock bounds aggregate sending and serializes account/IP limits across replicas.
jdbc.queryForList("SELECT pg_advisory_xact_lock(734092615)");
Integer limited=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '60 seconds'",Integer.class,account);
Integer daily=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account=? AND created_at>now()-interval '24 hours'",Integer.class,account);
Integer hourly=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE ip_address=? AND created_at>now()-interval '1 hour'",Integer.class,source);
Integer total=jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE created_at>now()-interval '24 hours'",Integer.class);
if(limited>0 || daily>=10 || hourly>=30 || total>=1000) throw new ApiException("VERIFICATION_RATE_LIMIT","发送过于频繁,请稍后重试",429);
String code=String.format(Locale.ROOT,"%06d",random.nextInt(1000000));
jdbc.update("INSERT INTO verification_send_events(id,account,ip_address) VALUES (?,?,?)",UUID.randomUUID(),account,source);
jdbc.update("INSERT INTO registration_codes(account,code_hash,expires_at) VALUES (?,?,now()+interval '5 minutes') ON CONFLICT(account) DO UPDATE SET code_hash=excluded.code_hash, expires_at=excluded.expires_at, attempts=0, consumed=false, created_at=now()",account,digest(account,code));
try { sender.send(channel,account,code); }
catch(ApiException exception) { jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account); throw exception; }
jdbc.update("DELETE FROM verification_send_events WHERE created_at<now()-interval '2 days'");
return Map.of("sent",true,"retryAfterSeconds",60,"expiresInSeconds",300);
}
@Transactional(noRollbackFor=ApiException.class)
public void consume(String raw,String code) {
String account=normalize(raw);
var rows=jdbc.queryForList("SELECT * FROM registration_codes WHERE account=? FOR UPDATE",account);
if(rows.isEmpty()) throw new ApiException("VERIFICATION_INVALID","请先获取验证码");
var row=rows.getFirst();
java.time.Instant expiry=((java.sql.Timestamp)row.get("expires_at")).toInstant();
if(Boolean.TRUE.equals(row.get("consumed")) || expiry.isBefore(java.time.Instant.now()) || ((Number)row.get("attempts")).intValue()>=5) throw new ApiException("VERIFICATION_EXPIRED","验证码已失效,请重新获取");
jdbc.update("UPDATE registration_codes SET attempts=attempts+1 WHERE account=?",account);
if(code==null || !code.matches("[0-9]{6}") || !MessageDigest.isEqual(String.valueOf(row.get("code_hash")).getBytes(StandardCharsets.UTF_8),digest(account,code).getBytes(StandardCharsets.UTF_8))) throw new ApiException("VERIFICATION_INVALID","验证码错误");
jdbc.update("UPDATE registration_codes SET consumed=true WHERE account=?",account);
}
}
@@ -8,6 +8,7 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestHeader;
@@ -28,7 +29,7 @@ public class CatalogController {
@GetMapping("/models") @GetMapping("/models")
public Map<String, Object> models(jakarta.servlet.http.HttpServletRequest request) { public Map<String, Object> models(jakarta.servlet.http.HttpServletRequest request) {
authService.requireUser(AuthController.sessionToken(request)); authService.requireUser(AuthController.sessionToken(request));
return Map.of("providers", catalogService.listProviders(false), "models", catalogService.listModels(false)); return Map.of("providers", catalogService.listProviders(false), "models", catalogService.listModels(false), "logicalModels", catalogService.listDefinitions(false));
} }
@GetMapping("/overview") @GetMapping("/overview")
@@ -103,7 +104,27 @@ public class CatalogController {
@GetMapping("/admin/models") @GetMapping("/admin/models")
public Map<String, Object> adminModels(jakarta.servlet.http.HttpServletRequest request) { public Map<String, Object> adminModels(jakarta.servlet.http.HttpServletRequest request) {
authService.requireAdmin(AuthController.sessionToken(request)); authService.requireAdmin(AuthController.sessionToken(request));
return Map.of("models", catalogService.listModels(true)); return Map.of("models", catalogService.listModels(true), "logicalModels", catalogService.listDefinitions(true));
}
@PatchMapping("/admin/providers/{id}")
public Map<String,Object> updateProvider(@PathVariable String id, @RequestBody Map<String,Object> input, jakarta.servlet.http.HttpServletRequest request) {
return Map.of("provider",catalogService.updateProvider(id,input,AuthController.sessionToken(request),authService));
}
@PatchMapping("/admin/models/{id}")
public Map<String,Object> updateGroup(@PathVariable String id, @RequestBody Map<String,Object> input, jakarta.servlet.http.HttpServletRequest request) {
return Map.of("model",catalogService.updateModel(id,input,AuthController.sessionToken(request),authService));
}
@PostMapping("/admin/model-definitions")
public ResponseEntity<Map<String,Object>> createDefinition(@RequestBody Map<String,Object> input, jakarta.servlet.http.HttpServletRequest request) {
return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("model",catalogService.saveDefinition(null,input,AuthController.sessionToken(request),authService)));
}
@PatchMapping("/admin/model-definitions/{id}")
public Map<String,Object> updateDefinition(@PathVariable String id, @RequestBody Map<String,Object> input, jakarta.servlet.http.HttpServletRequest request) {
return Map.of("model",catalogService.saveDefinition(id,input,AuthController.sessionToken(request),authService));
} }
@PostMapping("/admin/models") @PostMapping("/admin/models")
@@ -48,8 +48,56 @@ public class CatalogService {
} }
public List<Map<String, Object>> listModels(boolean includeDisabled) { public List<Map<String, Object>> listModels(boolean includeDisabled) {
String statusClause = includeDisabled ? "" : " WHERE status = 'active'"; String statusClause = includeDisabled ? "" : " WHERE m.status = 'active' AND p.status = 'active' AND d.status = 'active'";
return jdbc.query("SELECT * FROM model_catalog" + statusClause + " ORDER BY public_name", this::mapModel); return jdbc.query("SELECT m.* FROM model_catalog m JOIN model_providers p ON p.id=m.provider_id JOIN model_definitions d ON d.id=m.logical_model_id" + statusClause + " ORDER BY m.public_name, m.source_label", this::mapModel);
}
public List<Map<String, Object>> listDefinitions(boolean includeDisabled) {
return jdbc.query("SELECT * FROM model_definitions" + (includeDisabled ? "" : " WHERE status='active'") + " ORDER BY public_name", (rs, n) -> {
Map<String, Object> item = new LinkedHashMap<>();
item.put("id", rs.getString("id"));
item.put("publicName", rs.getString("public_name"));
item.put("modelKey", rs.getString("model_key"));
item.put("type", rs.getString("model_type"));
item.put("mode", rs.getString("call_mode"));
item.put("description", rs.getString("description"));
item.put("inputTypes", readList(rs.getString("input_types")));
item.put("outputTypes", readList(rs.getString("output_types")));
item.put("status", rs.getString("status"));
return item;
});
}
@Transactional
public Map<String, Object> saveDefinition(String id, Map<String, Object> input, String token, AuthService auth) {
UserView admin = auth.requireAdmin(token);
boolean creating = id == null;
Map<String, Object> value = creating ? new LinkedHashMap<>() : new LinkedHashMap<>(definition(id));
value.putAll(input);
String name = required(value, "publicName");
String type = required(value, "type");
String mode = required(value, "mode");
String status = status(value);
if (name.length() > 160 || !MODEL_TYPES.contains(type) || !CALL_MODES.contains(mode)) throw new ApiException("INVALID_MODEL", "模型名称、类型或调用模式无效");
if (creating) {
id = UUID.randomUUID().toString();
jdbc.update("INSERT INTO model_definitions (id, model_key, public_name, model_type, call_mode, description, input_types, output_types, status) VALUES (?, ?, ?, ?, ?, ?, CAST(? AS jsonb), CAST(? AS jsonb), ?)", id, optional(value, "modelKey", null), name, type, mode, optional(value, "description", ""), jsonArray(value.get("inputTypes")), jsonArray(value.get("outputTypes")), status);
} else {
jdbc.update("UPDATE model_definitions SET model_key=?, public_name=?, model_type=?, call_mode=?, description=?, input_types=CAST(? AS jsonb), output_types=CAST(? AS jsonb), status=?, updated_at=now() WHERE id=?", optional(value,"modelKey",null), name, type, mode, optional(value,"description",""), jsonArray(value.get("inputTypes")), jsonArray(value.get("outputTypes")), status, id);
jdbc.update("UPDATE model_catalog SET model_key=?, public_name=?, model_type=?, call_mode=?, description=?, input_types=CAST(? AS jsonb), output_types=CAST(? AS jsonb), updated_at=now() WHERE logical_model_id=?", optional(value,"modelKey",null), name, type, mode, optional(value,"description",""), jsonArray(value.get("inputTypes")), jsonArray(value.get("outputTypes")), id);
}
auth.audit(creating ? "model_definition.created" : "model_definition.updated", admin.id(), new AuthService.RequestMeta(null,null), Map.of("modelId",id));
return definition(id);
}
private Map<String, Object> definition(String id) {
return listDefinitions(true).stream().filter(item -> id.equals(item.get("id"))).findFirst().orElseThrow(() -> new ApiException("MODEL_NOT_FOUND", "模型不存在", 404));
}
private String status(Map<String, Object> input) {
String value = optional(input,"status","active");
if (!List.of("active","disabled").contains(value)) throw new ApiException("INVALID_STATUS", "状态无效");
return value;
} }
@Transactional @Transactional
@@ -59,54 +107,123 @@ public class CatalogService {
String name = required(input, "name"); String name = required(input, "name");
String protocol = optional(input, "protocol", "http"); String protocol = optional(input, "protocol", "http");
String sourceType = optional(input, "sourceType", "custom"); String sourceType = optional(input, "sourceType", "custom");
if (!code.matches("^[a-z0-9][a-z0-9._-]{1,63}$") || !PROTOCOLS.contains(protocol) || !SOURCE_TYPES.contains(sourceType)) { if (!code.matches("^[a-z0-9][a-z0-9._-]{1,63}$") || name.length() > 120 || !PROTOCOLS.contains(protocol) || !SOURCE_TYPES.contains(sourceType)) {
throw new ApiException("INVALID_PROVIDER", "供应商标识、协议或来源类型无效"); throw new ApiException("INVALID_PROVIDER", "供应商标识、协议或来源类型无效");
} }
String id = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString();
String baseUrl = optional(input, "baseUrl", null); String baseUrl = optional(input, "baseUrl", null);
validateBaseUrl(baseUrl);
String description = optional(input, "description", ""); String description = optional(input, "description", "");
String credentialType = optional(input, "credentialType", null); String credentialType = optional(input, "credentialType", "none");
String secret = optional(input, "credentialSecret", null); if (!List.of("none", "api-key", "bearer", "access-token").contains(credentialType)) throw new ApiException("INVALID_CREDENTIAL_TYPE", "凭据类型无效");
String secret = "none".equals(credentialType) ? null : optional(input, "credentialSecret", null);
String masked = secret == null ? null : mask(secret); String masked = secret == null ? null : mask(secret);
jdbc.update( jdbc.update(
"INSERT INTO model_providers (id, code, name, protocol, source_type, base_url, description, credential_type, credential_ciphertext, credential_masked, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')", "INSERT INTO model_providers (id, code, name, protocol, source_type, base_url, description, credential_type, credential_ciphertext, credential_masked, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
id, code, name, protocol, sourceType, baseUrl, description, credentialType, secret == null ? null : secretCipher.encrypt(secret), masked id, code, name, protocol, sourceType, baseUrl, description, credentialType, secret == null ? null : secretCipher.encrypt(secret), masked, status(input)
); );
auth.audit("provider.created", admin.id(), new AuthService.RequestMeta(null, null), Map.of("providerId", id)); auth.audit("provider.created", admin.id(), new AuthService.RequestMeta(null, null), Map.of("providerId", id));
return findProvider(id); return findProvider(id);
} }
@Transactional
public Map<String, Object> updateProvider(String id, Map<String, Object> input, String token, AuthService auth) {
UserView admin = auth.requireAdmin(token);
Map<String, Object> previous = findProvider(id);
if (previous == null) throw new ApiException("PROVIDER_NOT_FOUND", "渠道不存在", 404);
Map<String, Object> value = new LinkedHashMap<>(previous);
value.putAll(input);
String code=required(value,"code").toLowerCase(), name=required(value,"name"), protocol=required(value,"protocol"), sourceType=required(value,"sourceType");
if (!code.matches("^[a-z0-9][a-z0-9._-]{1,63}$") || name.length()>120 || !PROTOCOLS.contains(protocol) || !SOURCE_TYPES.contains(sourceType)) throw new ApiException("INVALID_PROVIDER", "渠道标识、名称、协议或类型无效");
String baseUrl=optional(value,"baseUrl",null);
validateBaseUrl(baseUrl);
String credentialType=optional(value,"credentialType","none");
if (!List.of("none","api-key","bearer","access-token").contains(credentialType)) throw new ApiException("INVALID_CREDENTIAL_TYPE","凭据类型无效");
jdbc.update("UPDATE model_providers SET code=?, name=?, protocol=?, source_type=?, base_url=?, description=?, credential_type=?, status=?, updated_at=now() WHERE id=?", code,name,protocol,sourceType,baseUrl,optional(value,"description",""),credentialType,status(value),id);
String secret=optional(input,"credentialSecret","");
if ("none".equals(credentialType)) jdbc.update("UPDATE model_providers SET credential_ciphertext=NULL, credential_masked=NULL WHERE id=?",id);
else if (!secret.isBlank()) jdbc.update("UPDATE model_providers SET credential_ciphertext=?, credential_masked=? WHERE id=?",secretCipher.encrypt(secret),mask(secret),id);
auth.audit("provider.updated",admin.id(),new AuthService.RequestMeta(null,null),Map.of("providerId",id));
return findProvider(id);
}
private void validateBaseUrl(String value) {
if (value == null || value.isBlank()) return;
try {
java.net.URI uri=java.net.URI.create(value);
if (!List.of("https","http").contains(uri.getScheme()) || uri.getHost()==null || uri.getUserInfo()!=null || uri.getQuery()!=null || uri.getFragment()!=null) throw new IllegalArgumentException();
} catch (IllegalArgumentException exception) { throw new ApiException("INVALID_BASE_URL","Base URL 必须是 HTTP(S) 地址,不能包含密码、查询参数或片段"); }
}
@Transactional @Transactional
public Map<String, Object> createModel(Map<String, Object> input, String token, AuthService auth) { public Map<String, Object> createModel(Map<String, Object> input, String token, AuthService auth) {
UserView admin = auth.requireAdmin(token); UserView admin = auth.requireAdmin(token);
input = new LinkedHashMap<>(input);
String logicalId = optional(input, "logicalModelId", null);
if (logicalId == null) logicalId = String.valueOf(saveDefinition(null, input, token, auth).get("id"));
Map<String, Object> definition = definition(logicalId);
for (String field : List.of("publicName","modelKey","type","mode","description","inputTypes","outputTypes")) input.put(field,definition.get(field));
String providerId = required(input, "providerId"); String providerId = required(input, "providerId");
if (findProvider(providerId) == null) throw new ApiException("PROVIDER_NOT_FOUND", "供应商不存在", 404); if (findProvider(providerId) == null) throw new ApiException("PROVIDER_NOT_FOUND", "供应商不存在", 404);
String publicName = required(input, "publicName"); String publicName = required(input, "publicName");
String upstreamModel = required(input, "upstreamModel"); String upstreamModel = required(input, "upstreamModel");
if (upstreamModel.length() > 160) throw new ApiException("INVALID_MODEL", "上游模型标识不能超过 160 字符");
String type = required(input, "type"); String type = required(input, "type");
String mode = required(input, "mode"); String mode = required(input, "mode");
if (!MODEL_TYPES.contains(type) || !CALL_MODES.contains(mode)) throw new ApiException("INVALID_MODEL", "模型类型或调用模式无效"); if (!MODEL_TYPES.contains(type) || !CALL_MODES.contains(mode)) throw new ApiException("INVALID_MODEL", "模型类型或调用模式无效");
String id = UUID.randomUUID().toString(); String id = UUID.randomUUID().toString();
String modelKey = optional(input, "modelKey", null); String modelKey = optional(input, "modelKey", null);
String sourceLabel = optional(input, "sourceLabel", null); String sourceLabel = optional(input, "sourceLabel", "默认分组");
if (sourceLabel.isBlank() || sourceLabel.length()>160) throw new ApiException("INVALID_GROUP_NAME","请填写分组名称(最多 160 字符)");
String description = optional(input, "description", ""); String description = optional(input, "description", "");
String inputTypes = jsonArray(input.get("inputTypes")); String inputTypes = jsonArray(input.get("inputTypes"));
String outputTypes = jsonArray(input.get("outputTypes")); String outputTypes = jsonArray(input.get("outputTypes"));
String capabilities = jsonObject(input.get("capabilities")); String capabilities = jsonObject(input.get("capabilities"));
String pricing = jsonObjectOrNull(input.get("pricing")); String pricing = jsonObjectOrNull(input.get("pricing"));
validatePricing(input.get("pricing"));
Integer priority = integerOrNull(input.get("priority")); Integer priority = integerOrNull(input.get("priority"));
Integer maxConcurrency = integerOrNull(input.get("maxConcurrency")); Integer maxConcurrency = integerOrNull(input.get("maxConcurrency"));
if (priority != null && priority < 0) throw new ApiException("INVALID_MODEL_PRIORITY", "模型路由优先级必须大于等于 0"); if (priority != null && priority < 0) throw new ApiException("INVALID_MODEL_PRIORITY", "模型路由优先级必须大于等于 0");
if (maxConcurrency != null && maxConcurrency < 0) throw new ApiException("INVALID_MODEL_CONCURRENCY", "模型并发上限必须大于等于 0"); if (maxConcurrency != null && maxConcurrency < 1) throw new ApiException("INVALID_MODEL_CONCURRENCY", "模型并发上限必须大于等于 1");
jdbc.update( jdbc.update(
"INSERT INTO model_catalog (id, provider_id, model_key, source_label, public_name, upstream_model, model_type, call_mode, description, input_types, output_types, capabilities, pricing, priority, max_concurrency, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb), CAST(? AS jsonb), CAST(? AS jsonb), CAST(? AS jsonb), ?, ?, 'active')", "INSERT INTO model_catalog (id, provider_id, model_key, source_label, public_name, upstream_model, model_type, call_mode, description, input_types, output_types, capabilities, pricing, priority, max_concurrency, logical_model_id, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, CAST(? AS jsonb), CAST(? AS jsonb), CAST(? AS jsonb), CAST(? AS jsonb), ?, ?, ?, ?)",
id, providerId, modelKey, sourceLabel, publicName, upstreamModel, type, mode, description, id, providerId, modelKey, sourceLabel, publicName, upstreamModel, type, mode, description,
inputTypes, outputTypes, capabilities, pricing, priority, maxConcurrency inputTypes, outputTypes, capabilities, pricing, priority, maxConcurrency, logicalId, status(input)
); );
auth.audit("model.created", admin.id(), new AuthService.RequestMeta(null, null), Map.of("modelId", id)); auth.audit("model.created", admin.id(), new AuthService.RequestMeta(null, null), Map.of("modelId", id));
return findModel(id); return findModel(id);
} }
@Transactional
public Map<String, Object> updateModel(String id, Map<String, Object> input, String token, AuthService auth) {
UserView admin=auth.requireAdmin(token);
Map<String,Object> old=findModel(id);
if (old==null) throw new ApiException("MODEL_NOT_FOUND","分组不存在",404);
Map<String,Object> value=new LinkedHashMap<>(old);
value.putAll(input);
String logicalId=required(value,"logicalModelId");
Map<String,Object> definition=definition(logicalId);
String providerId=required(value,"providerId"), groupName=required(value,"sourceLabel"), upstream=required(value,"upstreamModel");
if (findProvider(providerId)==null) throw new ApiException("PROVIDER_NOT_FOUND","渠道不存在",404);
if(groupName.length()>160 || upstream.length()>160) throw new ApiException("INVALID_MODEL","分组名称或上游标识过长");
Integer priority=integerOrNull(value.get("priority")), concurrency=integerOrNull(value.get("maxConcurrency"));
if ((priority!=null && priority<0) || (concurrency!=null && concurrency<1)) throw new ApiException("INVALID_MODEL_LIMIT","优先级不能小于 0,并发上限至少为 1");
validatePricing(value.get("pricing"));
jdbc.update("UPDATE model_catalog SET logical_model_id=?, provider_id=?, source_label=?, upstream_model=?, public_name=?, model_key=?, model_type=?, call_mode=?, description=?, input_types=CAST(? AS jsonb), output_types=CAST(? AS jsonb), pricing=CAST(? AS jsonb), priority=?, max_concurrency=?, status=?, updated_at=now() WHERE id=?",logicalId,providerId,groupName,upstream,definition.get("publicName"),definition.get("modelKey"),definition.get("type"),definition.get("mode"),definition.get("description"),jsonArray(definition.get("inputTypes")),jsonArray(definition.get("outputTypes")),jsonObjectOrNull(value.get("pricing")),priority,concurrency,status(value),id);
auth.audit("model_group.updated",admin.id(),new AuthService.RequestMeta(null,null),Map.of("groupId",id,"modelId",logicalId,"providerId",providerId));
return findModel(id);
}
private void validatePricing(Object input) {
if (!(input instanceof Map<?,?> prices)) return;
for(String field: List.of("input","output")) {
Object amount=prices.get(field);
if(amount==null) continue;
try { if(new java.math.BigDecimal(String.valueOf(amount)).signum()<0) throw new NumberFormatException(); }
catch(NumberFormatException e) { throw new ApiException("INVALID_PRICE","价格必须是非负数"); }
}
}
public List<Map<String, Object>> listProjects(String token, AuthService auth) { public List<Map<String, Object>> listProjects(String token, AuthService auth) {
UserView user = auth.requireUser(token); UserView user = auth.requireUser(token);
return jdbc.query("SELECT * FROM model_projects WHERE owner_user_id = ? AND status = 'active' ORDER BY created_at DESC", this::mapProject, user.id()); return jdbc.query("SELECT * FROM model_projects WHERE owner_user_id = ? AND status = 'active' ORDER BY created_at DESC", this::mapProject, user.id());
@@ -158,8 +275,11 @@ public class CatalogService {
@Transactional @Transactional
public Map<String, Object> updateKeyModels(String token, String keyId, List<String> modelIds, AuthService auth) { public Map<String, Object> updateKeyModels(String token, String keyId, List<String> modelIds, AuthService auth) {
UserView user = auth.requireUser(token); UserView user = auth.requireUser(token);
List<String> uniqueIds = modelIds == null ? List.of() : modelIds.stream().map(String::trim).filter(value -> !value.isBlank()).distinct().toList(); var existing = jdbc.query("SELECT * FROM platform_api_keys WHERE id=? AND user_id=? AND status='active' FOR UPDATE", this::mapApiKey, UUID.fromString(keyId), user.id());
for (String modelId : uniqueIds) if (findActiveModel(modelId) == null) throw new ApiException("MODEL_NOT_FOUND", "模型不存在或已下线", 404); if (existing.isEmpty()) throw new ApiException("KEY_NOT_FOUND", "Key 不存在、已停用或无权修改", 404);
List<?> priorIds = (List<?>) existing.getFirst().get("modelIds");
List<String> uniqueIds = modelIds == null ? List.of() : modelIds.stream().filter(java.util.Objects::nonNull).map(String::trim).filter(value -> !value.isBlank()).distinct().toList();
for (String modelId : uniqueIds) if (!priorIds.contains(modelId) && findActiveModel(modelId) == null) throw new ApiException("MODEL_NOT_FOUND", "分组不存在或已下线", 404);
int changed = jdbc.update("UPDATE platform_api_keys SET model_ids = CAST(? AS jsonb) WHERE id = ? AND user_id = ? AND status = 'active'", writeJson(uniqueIds), UUID.fromString(keyId), user.id()); int changed = jdbc.update("UPDATE platform_api_keys SET model_ids = CAST(? AS jsonb) WHERE id = ? AND user_id = ? AND status = 'active'", writeJson(uniqueIds), UUID.fromString(keyId), user.id());
if (changed == 0) throw new ApiException("KEY_NOT_FOUND", "Key 不存在、已停用或无权修改", 404); if (changed == 0) throw new ApiException("KEY_NOT_FOUND", "Key 不存在、已停用或无权修改", 404);
return Map.of("apiKey", findKey(keyId)); return Map.of("apiKey", findKey(keyId));
@@ -185,13 +305,16 @@ public class CatalogService {
result.put("tasks", Map.of("queued", 0, "running", 0, "succeeded", 0, "failed", 0)); result.put("tasks", Map.of("queued", 0, "running", 0, "succeeded", 0, "failed", 0));
result.put("series", List.of()); result.put("series", List.of());
result.put("ledger", List.of()); result.put("ledger", List.of());
List<java.math.BigDecimal> balances=jdbc.queryForList("SELECT balance FROM user_wallets WHERE user_id=?",java.math.BigDecimal.class,user.id());
result.put("availableCredit",balances.isEmpty()?java.math.BigDecimal.ZERO:balances.getFirst());
result.put("ledger",jdbc.query("SELECT id, reason, amount, created_at FROM wallet_entries WHERE user_id=? ORDER BY created_at DESC LIMIT 100", (rs,n)->Map.of("id",rs.getString("id"),"title",rs.getString("reason"),"amount",rs.getBigDecimal("amount"),"createdAt",rs.getObject("created_at",OffsetDateTime.class)),user.id()));
return result; return result;
} }
public Map<String, Object> authenticateKey(String plaintext) { public Map<String, Object> authenticateKey(String plaintext) {
if (plaintext == null || plaintext.isBlank()) return null; if (plaintext == null || plaintext.isBlank()) return null;
try { try {
return jdbc.queryForObject("SELECT * FROM platform_api_keys WHERE key_hash = ? AND status = 'active'", this::mapApiKey, sha256(plaintext.trim())); return jdbc.queryForObject("SELECT k.* FROM platform_api_keys k JOIN users u ON u.id=k.user_id WHERE k.key_hash = ? AND k.status = 'active' AND u.status='active'", this::mapApiKey, sha256(plaintext.trim()));
} catch (EmptyResultDataAccessException exception) { } catch (EmptyResultDataAccessException exception) {
return null; return null;
} }
@@ -237,7 +360,7 @@ public class CatalogService {
} }
private Map<String, Object> findActiveModel(String id) { private Map<String, Object> findActiveModel(String id) {
try { return jdbc.queryForObject("SELECT * FROM model_catalog WHERE id = ? AND status = 'active'", this::mapModel, id); } try { return jdbc.queryForObject("SELECT m.* FROM model_catalog m JOIN model_providers p ON p.id=m.provider_id JOIN model_definitions d ON d.id=m.logical_model_id WHERE m.id = ? AND m.status = 'active' AND p.status='active' AND d.status='active'", this::mapModel, id); }
catch (EmptyResultDataAccessException exception) { return null; } catch (EmptyResultDataAccessException exception) { return null; }
} }
@@ -274,6 +397,7 @@ public class CatalogService {
private Map<String, Object> mapModel(ResultSet resultSet, int rowNumber) throws SQLException { private Map<String, Object> mapModel(ResultSet resultSet, int rowNumber) throws SQLException {
Map<String, Object> model = new LinkedHashMap<>(); Map<String, Object> model = new LinkedHashMap<>();
model.put("id", resultSet.getString("id")); model.put("id", resultSet.getString("id"));
model.put("logicalModelId", resultSet.getString("logical_model_id"));
model.put("providerId", resultSet.getString("provider_id")); model.put("providerId", resultSet.getString("provider_id"));
putIfNotNull(model, "modelKey", resultSet.getString("model_key")); putIfNotNull(model, "modelKey", resultSet.getString("model_key"));
putIfNotNull(model, "sourceLabel", resultSet.getString("source_label")); putIfNotNull(model, "sourceLabel", resultSet.getString("source_label"));
@@ -0,0 +1,23 @@
package com.moyi.controlplane.wallet;
import com.moyi.controlplane.auth.AuthController;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Map;
import java.util.UUID;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/admin")
public class WalletController {
private final WalletService wallet;
public WalletController(WalletService wallet) { this.wallet=wallet; }
public record GrantRequest(UUID requestId, String amount, String reason) {}
@GetMapping("/wallets")
public Map<String,Object> balances(HttpServletRequest request) { return Map.of("wallets",wallet.balances(AuthController.sessionToken(request))); }
@GetMapping("/users/{id}/wallet")
public Map<String,Object> entries(@PathVariable UUID id,HttpServletRequest request) { return Map.of("entries",wallet.entries(AuthController.sessionToken(request),id)); }
@PostMapping("/users/{id}/wallet/grants")
public Map<String,Object> grant(@PathVariable UUID id,@RequestBody GrantRequest input,HttpServletRequest request) {
return wallet.grant(AuthController.sessionToken(request),id,input.requestId(),input.amount(),input.reason(),AuthController.meta(request));
}
}
@@ -0,0 +1,60 @@
package com.moyi.controlplane.wallet;
import com.moyi.controlplane.auth.AuthService;
import com.moyi.controlplane.common.ApiException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class WalletService {
private final JdbcTemplate jdbc;
private final AuthService auth;
public WalletService(JdbcTemplate jdbc, AuthService auth) { this.jdbc=jdbc; this.auth=auth; }
public List<Map<String,Object>> balances(String token) {
auth.requireAdmin(token);
return jdbc.queryForList("SELECT u.id AS \"userId\", COALESCE(w.balance,0) AS balance FROM users u LEFT JOIN user_wallets w ON w.user_id=u.id");
}
public List<Map<String,Object>> entries(String token, UUID userId) {
auth.requireAdmin(token);
return jdbc.queryForList("SELECT e.id, e.amount, e.balance_after AS \"balanceAfter\", e.currency, e.reason, e.created_at AS \"createdAt\", u.display_name AS actor FROM wallet_entries e JOIN users u ON u.id=e.actor_user_id WHERE e.user_id=? ORDER BY e.created_at DESC LIMIT 100",userId);
}
@Transactional
public Map<String,Object> grant(String token, UUID userId, UUID requestId, String amountInput, String reasonInput, AuthService.RequestMeta meta) {
var actor=auth.requireAdmin(token);
if(requestId==null) throw new ApiException("INVALID_REQUEST_ID","请提供发放请求编号");
BigDecimal amount;
try {
amount=new BigDecimal(amountInput).setScale(2,RoundingMode.UNNECESSARY);
if(amount.signum()<=0 || amount.compareTo(new BigDecimal("1000000"))>0) throw new NumberFormatException();
} catch(Exception exception) { throw new ApiException("INVALID_AMOUNT","金额需大于 0,最多两位小数,单次不超过 100 万元"); }
String reason=reasonInput==null?"":reasonInput.trim();
if(reason.isBlank() || reason.length()>500) throw new ApiException("INVALID_REASON","请填写发放原因(最多 500 字符)");
if(jdbc.queryForObject("SELECT count(*) FROM users WHERE id=? AND status='active'",Integer.class,userId)==0) throw new ApiException("USER_NOT_FOUND","用户不存在或已停用",404);
// Lock the idempotency key before the wallet so concurrent retries cannot grant twice.
jdbc.queryForList("SELECT pg_advisory_xact_lock(hashtextextended(?, 0))",requestId.toString());
List<Map<String,Object>> existing=jdbc.queryForList("SELECT * FROM wallet_entries WHERE request_id=?",requestId);
if(!existing.isEmpty()) {
var entry=existing.getFirst();
if(!userId.equals(entry.get("user_id")) || !actor.id().equals(entry.get("actor_user_id")) || amount.compareTo((BigDecimal)entry.get("amount"))!=0 || !reason.equals(entry.get("reason"))) throw new ApiException("REQUEST_CONFLICT","请求编号已被另一笔发放使用",409);
return Map.of("id",entry.get("id"),"balance",entry.get("balance_after"),"currency","CNY","replayed",true);
}
jdbc.update("INSERT INTO user_wallets(user_id) VALUES (?) ON CONFLICT DO NOTHING",userId);
BigDecimal balance=jdbc.queryForObject("SELECT balance FROM user_wallets WHERE user_id=? FOR UPDATE",BigDecimal.class,userId);
BigDecimal next=balance.add(amount);
UUID id=UUID.randomUUID();
jdbc.update("UPDATE user_wallets SET balance=?, updated_at=now() WHERE user_id=?",next,userId);
jdbc.update("INSERT INTO wallet_entries(id,user_id,actor_user_id,request_id,amount,balance_after,reason) VALUES (?,?,?,?,?,?,?)",id,userId,actor.id(),requestId,amount,next,reason);
auth.audit("wallet.credit_granted",actor.id(),meta,Map.of("userId",userId,"entryId",id,"amount",amount,"currency","CNY","reason",reason));
return Map.of("id",id,"balance",next,"currency","CNY","replayed",false);
}
}
@@ -0,0 +1,58 @@
CREATE TABLE model_definitions (
id varchar(64) PRIMARY KEY,
model_key varchar(160),
public_name varchar(160) NOT NULL,
model_type varchar(24) NOT NULL,
call_mode varchar(16) NOT NULL,
description text NOT NULL DEFAULT '',
input_types jsonb NOT NULL DEFAULT '[]',
output_types jsonb NOT NULL DEFAULT '[]',
status varchar(16) NOT NULL DEFAULT 'active' CHECK (status IN ('active', 'disabled')),
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
-- Keep existing route IDs and key grants intact. Do not guess which legacy names are identical models.
INSERT INTO model_definitions (id, model_key, public_name, model_type, call_mode, description, input_types, output_types, status)
SELECT id, model_key, public_name, model_type, call_mode, description, input_types, output_types, status FROM model_catalog;
ALTER TABLE model_catalog ADD COLUMN logical_model_id varchar(64) REFERENCES model_definitions(id);
UPDATE model_catalog SET logical_model_id = id;
ALTER TABLE model_catalog ALTER COLUMN logical_model_id SET NOT NULL;
UPDATE model_catalog SET source_label = '默认分组' WHERE source_label IS NULL OR trim(source_label) = '';
CREATE INDEX model_catalog_logical_idx ON model_catalog(logical_model_id);
CREATE UNIQUE INDEX model_catalog_group_name_idx ON model_catalog(logical_model_id, source_label);
CREATE TABLE user_wallets (
user_id uuid PRIMARY KEY REFERENCES users(id),
balance numeric(20,8) NOT NULL DEFAULT 0 CHECK (balance >= 0),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE wallet_entries (
id uuid PRIMARY KEY,
user_id uuid NOT NULL REFERENCES users(id),
actor_user_id uuid NOT NULL REFERENCES users(id),
request_id uuid NOT NULL UNIQUE,
amount numeric(20,8) NOT NULL CHECK (amount > 0),
balance_after numeric(20,8) NOT NULL,
currency varchar(3) NOT NULL DEFAULT 'CNY' CHECK (currency = 'CNY'),
reason varchar(500) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX wallet_entries_user_idx ON wallet_entries(user_id, created_at DESC);
CREATE TABLE registration_codes (
account varchar(254) PRIMARY KEY,
code_hash char(64) NOT NULL,
expires_at timestamptz NOT NULL,
attempts integer NOT NULL DEFAULT 0,
consumed boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE verification_send_events (
id uuid PRIMARY KEY,
account varchar(254) NOT NULL,
ip_address varchar(128) NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX verification_send_account_idx ON verification_send_events(account, created_at);
CREATE INDEX verification_send_ip_idx ON verification_send_events(ip_address, created_at);
@@ -0,0 +1,202 @@
package com.moyi.controlplane;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.auth.*;
import com.moyi.controlplane.catalog.CatalogService;
import com.moyi.controlplane.common.ApiException;
import com.moyi.controlplane.common.ApiExceptionHandler;
import com.moyi.controlplane.security.SecretCipher;
import com.moyi.controlplane.wallet.WalletService;
import jakarta.servlet.http.Cookie;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.*;
import javax.sql.DataSource;
import org.flywaydb.core.Flyway;
import org.junit.jupiter.api.*;
import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable;
import org.springframework.context.annotation.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.*;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import static org.junit.jupiter.api.Assertions.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
@EnabledIfEnvironmentVariable(named="MOYI_AUTH_TEST_JDBC_URL", matches="jdbc:postgresql://127\\.0\\.0\\.1:[0-9]+/.+")
class PlatformAdminPostgresTest {
@Configuration @EnableTransactionManagement(proxyTargetClass=true)
static class Transactions {}
static class TestSender implements VerificationSender {
final Map<String,String> codes = new ConcurrentHashMap<>();
boolean enabled = true;
boolean fail = false;
public boolean available(String channel) { return enabled; }
public void send(String channel, String account, String code) {
if (fail) throw new ApiException("VERIFICATION_SEND_FAILED", "Test sender unavailable", 502);
codes.put(account, code);
}
}
private final ObjectMapper json = new ObjectMapper().findAndRegisterModules();
private final AuthService.RequestMeta meta = new AuthService.RequestMeta("127.0.0.1", "isolated-test");
private DriverManagerDataSource base;
private AnnotationConfigApplicationContext context;
private JdbcTemplate jdbc;
private String schema, ownerToken, memberToken;
private UUID memberId;
private AuthService auth;
private CatalogService catalog;
private WalletService wallet;
private VerificationService verification;
private TestSender sender;
@BeforeEach void setup() throws Exception {
String url = System.getenv("MOYI_AUTH_TEST_JDBC_URL");
schema = "platform_test_" + UUID.randomUUID().toString().replace("-", "");
base = new DriverManagerDataSource(url, "moyi_role_test", "");
var source = new DriverManagerDataSource(url + "?currentSchema=" + schema, "moyi_role_test", "");
jdbc = new JdbcTemplate(source);
Flyway.configure().dataSource(base).schemas(schema).defaultSchema(schema).target("9").load().migrate();
var legacyIds = jdbc.queryForList("SELECT id FROM model_catalog ORDER BY id", String.class);
UUID legacyUser = UUID.randomUUID(), legacyKey = UUID.randomUUID();
String legacyGrants = json.writeValueAsString(List.of(legacyIds.getFirst()));
jdbc.update("INSERT INTO users(id,account,account_kind,password_hash,display_name) VALUES (?,'legacy_member','username','not-a-login-hash','Legacy Member')", legacyUser);
jdbc.update("INSERT INTO platform_api_keys(id,user_id,name,key_prefix,key_hash,model_ids) VALUES (?,?,'Legacy Key','test-prefix',?,?::jsonb)", legacyKey, legacyUser, "a".repeat(64), legacyGrants);
Flyway.configure().dataSource(base).schemas(schema).defaultSchema(schema).load().migrate();
assertEquals(legacyIds, jdbc.queryForList("SELECT id FROM model_catalog ORDER BY id", String.class));
assertEquals(legacyIds, jdbc.queryForList("SELECT logical_model_id FROM model_catalog ORDER BY id", String.class));
assertEquals(json.readTree(legacyGrants), json.readTree(jdbc.queryForObject("SELECT model_ids::text FROM platform_api_keys WHERE id=?", String.class, legacyKey)));
context = new AnnotationConfigApplicationContext();
sender = new TestSender();
context.register(Transactions.class);
context.registerBean(DataSource.class, () -> source);
context.registerBean(DataSourceTransactionManager.class, () -> new DataSourceTransactionManager(source));
context.registerBean(AuthService.class, () -> new AuthService(jdbc, new PasswordHasher("test-pepper"), json, 168));
context.registerBean(CatalogService.class, () -> new CatalogService(jdbc, json, new SecretCipher("test-encryption")));
context.registerBean(WalletService.class, () -> new WalletService(jdbc, context.getBean(AuthService.class)));
context.registerBean(VerificationService.class, () -> new VerificationService(jdbc, sender, "test-pepper"));
context.refresh();
auth = context.getBean(AuthService.class);
catalog = context.getBean(CatalogService.class);
wallet = context.getBean(WalletService.class);
verification = context.getBean(VerificationService.class);
auth.ensureAdmin("test_owner", "local-password", "Test Owner");
ownerToken = auth.login("test_owner", "local-password", meta).token();
memberId = auth.createUser(ownerToken, "test_member", "local-password", "Test Member", meta).id();
memberToken = auth.login("test_member", "local-password", meta).token();
}
@AfterEach void cleanup() {
if (context != null) context.close();
// Only the random schema created by this isolated test is removed.
if (base != null && schema != null) new JdbcTemplate(base).execute("DROP SCHEMA IF EXISTS " + schema + " CASCADE");
}
@Test void modelGroupsKeepExactKeyGrantsAndEditableChannels() {
var channel = catalog.createProvider(Map.of("code","test-relay","name","Relay","protocol","openai-compatible","sourceType","relay","baseUrl","https://example.test/v1","credentialType","api-key","credentialSecret","only-a-test-secret"), ownerToken, auth);
String channelId = channel.get("id").toString();
String cipher = jdbc.queryForObject("SELECT credential_ciphertext FROM model_providers WHERE id=?", String.class, channelId);
var model = catalog.saveDefinition(null,Map.of("publicName","Test Model","type","text","mode","sync"),ownerToken,auth);
String modelId = model.get("id").toString();
var first = catalog.createModel(Map.of("logicalModelId",modelId,"providerId",channelId,"sourceLabel","Primary","upstreamModel","upstream-a"),ownerToken,auth);
String firstId = first.get("id").toString();
var second = catalog.createModel(Map.of("logicalModelId",modelId,"providerId",channelId,"sourceLabel","Backup","upstreamModel","upstream-b"),ownerToken,auth);
String secondId = second.get("id").toString();
var keyResult = catalog.createKey(memberToken,Map.of("modelIds",List.of(firstId)),auth);
String plaintext = keyResult.get("key").toString();
var key = catalog.authenticateKey(plaintext);
String keyId = key.get("id").toString();
assertTrue(catalog.keyCanInvoke(key,firstId));
assertFalse(catalog.keyCanInvoke(key,secondId));
assertFalse(catalog.keyCanInvoke(key,modelId));
assertThrows(ApiException.class, () -> catalog.updateKeyModels(ownerToken,keyId,List.of(secondId),auth));
var edited = catalog.updateProvider(channelId,Map.of("name","Relay Updated","baseUrl","https://example.test/v2","credentialSecret",""),ownerToken,auth);
assertEquals("Relay Updated",edited.get("name"));
assertFalse(edited.containsKey("credentialSecret"));
assertEquals(cipher,jdbc.queryForObject("SELECT credential_ciphertext FROM model_providers WHERE id=?",String.class,channelId));
catalog.saveDefinition(modelId,Map.of("publicName","Renamed"),ownerToken,auth);
assertEquals("Renamed",catalog.activeModel(firstId).get("publicName"));
catalog.updateModel(firstId,Map.of("sourceLabel","Edited Group","upstreamModel","upstream-c","maxConcurrency",2),ownerToken,auth);
assertEquals("upstream-c",catalog.activeModel(firstId).get("upstreamModel"));
assertTrue(catalog.keyCanInvoke(catalog.authenticateKey(plaintext),firstId));
catalog.updateProvider(channelId,Map.of("status","disabled"),ownerToken,auth);
assertNull(catalog.activeModel(firstId));
assertTrue(catalog.listModels(false).stream().noneMatch(row -> row.get("id").equals(firstId)));
catalog.updateKeyModels(memberToken,keyId,List.of(firstId),auth);
assertThrows(ApiException.class, () -> catalog.updateKeyModels(memberToken,keyId,List.of(firstId,secondId),auth));
catalog.updateProvider(channelId,Map.of("status","active"),ownerToken,auth);
catalog.saveDefinition(modelId,Map.of("status","disabled"),ownerToken,auth);
assertNull(catalog.activeModel(firstId));
catalog.saveDefinition(modelId,Map.of("status","active"),ownerToken,auth);
catalog.updateModel(firstId,Map.of("status","disabled"),ownerToken,auth);
assertNull(catalog.activeModel(firstId));
catalog.updateKeyModels(memberToken,keyId,List.of(),auth);
assertFalse(catalog.keyCanInvoke(catalog.authenticateKey(plaintext),firstId));
jdbc.update("UPDATE users SET status='disabled' WHERE id=?",memberId);
assertNull(catalog.authenticateKey(plaintext));
assertThrows(ApiException.class, () -> catalog.updateProvider(channelId,Map.of("name","bad"),memberToken,auth));
}
@Test void grantsAreExactAuditedIdempotentAndConcurrent() throws Exception {
assertThrows(ApiException.class, () -> wallet.grant(memberToken,memberId,UUID.randomUUID(),"1","unauthorized",meta));
for (String invalid : List.of("0","-1","1.001","NaN","1000000.01")) assertThrows(ApiException.class, () -> wallet.grant(ownerToken,memberId,UUID.randomUUID(),invalid,"invalid",meta));
UUID request = UUID.randomUUID();
try (var pool = Executors.newFixedThreadPool(4)) {
var one = pool.submit(() -> wallet.grant(ownerToken,memberId,request,"12.30","test grant",meta));
var retry = pool.submit(() -> wallet.grant(ownerToken,memberId,request,"12.30","test grant",meta));
assertEquals(one.get(10,TimeUnit.SECONDS).get("id"),retry.get(10,TimeUnit.SECONDS).get("id"));
var two = pool.submit(() -> wallet.grant(ownerToken,memberId,UUID.randomUUID(),"0.10","second",meta));
var three = pool.submit(() -> wallet.grant(ownerToken,memberId,UUID.randomUUID(),"0.20","third",meta));
two.get(10,TimeUnit.SECONDS); three.get(10,TimeUnit.SECONDS);
}
assertThrows(ApiException.class, () -> wallet.grant(ownerToken,memberId,request,"99","test grant",meta));
assertEquals(0,new BigDecimal("12.60").compareTo(jdbc.queryForObject("SELECT balance FROM user_wallets WHERE user_id=?",BigDecimal.class,memberId)));
assertEquals(3,wallet.entries(ownerToken,memberId).size());
assertEquals(3,jdbc.queryForObject("SELECT count(*) FROM auth_audit_log WHERE event_type='wallet.credit_granted'",Integer.class));
assertEquals(0,new BigDecimal("12.60").compareTo((BigDecimal)catalog.overview(memberToken,auth).get("availableCredit")));
}
@Test void directCreationCannotEscalateAndOtpIsRequiredOnBothChannels() throws Exception {
MockMvc http = MockMvcBuilders.standaloneSetup(new AuthController(auth,verification,168,false)).setControllerAdvice(new ApiExceptionHandler()).build();
http.perform(post("/api/admin/users").cookie(new Cookie("moyi_session",ownerToken)).contentType("application/json").content("{\"account\":\"created_user\",\"password\":\"test-password\",\"role\":\"super_admin\"}"))
.andExpect(status().isCreated()).andExpect(jsonPath("$.user.role").value("user")).andExpect(jsonPath("$.user.password").doesNotExist());
http.perform(post("/api/admin/users").cookie(new Cookie("moyi_session",memberToken)).contentType("application/json").content("{\"account\":\"bad_user\",\"password\":\"test-password\"}"))
.andExpect(status().isForbidden());
String invite = auth.createInvitation(ownerToken,"otp test",10,null,meta).get("code").toString();
for (String account : List.of("otp@example.test","13800000000")) {
var input = new LinkedHashMap<String,String>(Map.of("account",account,"password","test-password","invitationCode",invite));
http.perform(post("/api/auth/register").contentType("application/json").content(json.writeValueAsBytes(input))).andExpect(status().isBadRequest());
http.perform(post("/api/auth/verification").contentType("application/json").content(json.writeValueAsBytes(input)))
.andExpect(status().isOk()).andExpect(jsonPath("$.code").doesNotExist()).andExpect(jsonPath("$.sent").value(true));
String code = sender.codes.get(account);
assertNotEquals(code,jdbc.queryForObject("SELECT code_hash FROM registration_codes WHERE account=?",String.class,account));
input.put("verificationCode",code);
http.perform(post("/api/auth/register").contentType("application/json").content(json.writeValueAsBytes(input)))
.andExpect(status().isCreated()).andExpect(jsonPath("$.user.role").value("user"));
assertThrows(ApiException.class, () -> verification.consume(account,code));
}
}
@Test void otpLimitsExpiryAndFailedSendsPersistAcrossTransactions() {
String invite = auth.createInvitation(ownerToken,"otp limits",20,null,meta).get("code").toString();
String account="limits@example.test";
assertThrows(ApiException.class, () -> verification.send(account,"bad-invite","127.0.0.1"));
verification.send(account,invite,"127.0.0.1");
assertThrows(ApiException.class, () -> verification.send(account,invite,"127.0.0.1"));
String correct=sender.codes.get(account);
String wrong=correct.equals("000000")?"111111":"000000";
for(int i=0;i<5;i++) assertThrows(ApiException.class, () -> verification.consume(account,wrong));
assertEquals(5,jdbc.queryForObject("SELECT attempts FROM registration_codes WHERE account=?",Integer.class,account));
assertThrows(ApiException.class, () -> verification.consume(account,correct));
verification.send("expired@example.test",invite,"127.0.0.1");
jdbc.update("UPDATE registration_codes SET expires_at=now()-interval '1 second' WHERE account='expired@example.test'");
assertThrows(ApiException.class, () -> verification.consume("expired@example.test",sender.codes.get("expired@example.test")));
sender.fail=true;
assertThrows(ApiException.class, () -> verification.send("failed@example.test",invite,"127.0.0.1"));
assertTrue(jdbc.queryForObject("SELECT consumed FROM registration_codes WHERE account='failed@example.test'",Boolean.class));
assertEquals(1,jdbc.queryForObject("SELECT count(*) FROM verification_send_events WHERE account='failed@example.test'",Integer.class));
sender.enabled=false;
assertFalse(verification.capabilities().containsValue(true));
assertThrows(ApiException.class, () -> verification.send("unavailable@example.test",invite,"127.0.0.1"));
}
}
@@ -64,7 +64,7 @@ class AuthPostgresTest {
assertThrows(DataIntegrityViolationException.class, () -> jdbc.update("UPDATE users SET role = 'super_admin' WHERE id = ?", operatorId)); assertThrows(DataIntegrityViolationException.class, () -> jdbc.update("UPDATE users SET role = 'super_admin' WHERE id = ?", operatorId));
assertThrows(IllegalStateException.class, () -> auth.ensureAdmin("operator", "test-password", "Other")); assertThrows(IllegalStateException.class, () -> auth.ensureAdmin("operator", "test-password", "Other"));
MockMvc http = MockMvcBuilders.standaloneSetup(new AuthController(auth, 168, true)) MockMvc http = MockMvcBuilders.standaloneSetup(new AuthController(auth, org.mockito.Mockito.mock(VerificationService.class), 168, true))
.setControllerAdvice(new ApiExceptionHandler()).build(); .setControllerAdvice(new ApiExceptionHandler()).build();
var ownerCookie = login(http, "adimin", "super_admin"); var ownerCookie = login(http, "adimin", "super_admin");
var operatorCookie = login(http, "operator", "admin"); var operatorCookie = login(http, "operator", "admin");
@@ -0,0 +1,18 @@
package com.moyi.controlplane.auth;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class PasswordHasherInteropTest {
@Test
void acceptsMaintenanceScriptPbkdf2HashesIncludingUnicode() {
PasswordHasher hasher = new PasswordHasher("local-test-pepper");
// Python hashlib fixtures with salt bytes 0..15; no real credentials.
String ascii = "pbkdf2$210000$AAECAwQFBgcICQoLDA0ODw$_ZW4zVJDiheXQ51WuP_SSr_f8xjYJXBHvjkzLlPtFHo";
String unicode = "pbkdf2$210000$AAECAwQFBgcICQoLDA0ODw$qZ4RLM7vU3k0rCJtetdh8uSbnAkWbxFYR7sD4GYRmb8";
assertTrue(hasher.matches("Qa-Test42!", ascii));
assertTrue(hasher.matches("\u6d4b\u8bd5A1!", unicode));
assertFalse(hasher.matches("wrong-password", ascii));
assertFalse(new PasswordHasher("wrong-pepper").matches("Qa-Test42!", ascii));
}
}
+23
View File
@@ -275,6 +275,29 @@ sudo python3 deploy.py reload-tls --mode https
V9 迁移扩展角色约束、增加超级管理员唯一索引,应用启动时升级指定账号。旧程序只识别 `admin`,**V9 启用后不能直接切回旧版 JAR**;需要兼容新版角色的修复版本,或由维护人员将升级前备份恢复到独立测试库后验证回退。不要手工修改 Flyway 历史或删除唯一索引。 V9 迁移扩展角色约束、增加超级管理员唯一索引,应用启动时升级指定账号。旧程序只识别 `admin`,**V9 启用后不能直接切回旧版 JAR**;需要兼容新版角色的修复版本,或由维护人员将升级前备份恢复到独立测试库后验证回退。不要手工修改 Flyway 历史或删除唯一索引。
### 修改已存在的超级管理员账号和密码
`ADMIN_ACCOUNT` / `ADMIN_PASSWORD` 只用于初始化和启动校验,修改环境变量本身不会更新已有密码。不要先修改账号环境变量再重启,避免触发唯一超级管理员保护。
单机 Docker Compose 部署可使用 `infra/moyi/admin_credentials.py`。它依赖服务器 Python 3.11+、Docker Compose 和 PostgreSQL 客户端;通过运行版本的 `deploy.py` 解析配置,不在命令行或日志中输出密码。将该脚本放在发布目录外,例如 `/opt/moyi/tools/admin_credentials.py`,避免改动已有发布包的校验文件。
```bash
sudo python3 /opt/moyi/tools/admin_credentials.py --deployment-dir /opt/moyi/releases/<当前版本>/infra/moyi --account MLKJAdmin --database moyi_control --mode https
sudo python3 /opt/moyi/tools/admin_credentials.py --deployment-dir /opt/moyi/releases/<当前版本>/infra/moyi --account MLKJAdmin --database moyi_control --mode https --apply
```
第一条只检查;第二条须在交互式 SSH 中单独执行,隐藏输入两次新密码。没有密码最低长度要求,拒绝空白、控制字符、开发默认密码和部署配置占位符。脚本会:
1. 核对唯一活跃超级管理员、目标库、账号占用、运行容器的发布目录与数据库/加密配置。
2. 保存修改前后的环境配置,调用 Compose 验证只有管理员账号和密码发生变化。
3. 短暂停止后端,将当前专用数据库导出到 `/opt/moyi/backups/owner-reset-*`,保留环境密钥;备份和配置仅 root 可读。
4. 在同一数据库事务中修改原账号及 PBKDF2 哈希、撤销该账号旧会话、记录审计,不新建用户、不改变用户 ID、角色、显示名称或业务关联。
5. 原子替换环境文件,使用现有镜像重建后端,重载容器 Nginx 并验证新超级管理员登录。账号匹配不区分大小写,数据库内使用小写规范形式。
执行前应暂停平台测试,维护期间不要并行修改 `.env.cloud`、发布或启动其他后端实例。密码只在服务器输入,不写进源码、发布包、Shell 历史。工具不会重新构建镜像或修改数据库迁移文件。
若数据库修改前失败,工具尝试启动原后端;若数据库事务已尝试提交后失败,不自动还原数据库或旧配置,以免状态不一致。保留工具输出的私有恢复目录,使用相同账号和密码重跑工具完成配置同步及验收。不要盲目恢复整个共享 RDS 实例、切回旧版程序或旧环境配置。成功后将恢复目录保存在受控位置,不提交 Git。
## 8. 还需提供的信息 ## 8. 还需提供的信息
- RDS 内网地址、端口、新库和账号名、所属 VPC;Tair 内网地址、端口、账号、TLS 状态及 VPC。 - RDS 内网地址、端口、新库和账号名、所属 VPC;Tair 内网地址、端口、账号、TLS 状态及 VPC。
@@ -0,0 +1,76 @@
# 模型分组、注册验证与人民币额度
## 本次变更
- 渠道:独立维护名称、Code、来源类型、协议、Base URL、凭据和启停状态。编辑时凭据留空保留原值;选择“不使用凭据”才清除。
- 模型:独立维护名称、标识、能力类型和调用模式。
- 分组:在模型下添加,自定义名称、选择渠道、填写上游模型 ID、报价、并发上限;均可再次编辑。
- Key:先选模型,再勾选该模型的分组,可继续切换模型配置其他分组。授权只包含已保存的分组,不自动扩展到未来新增分组。清空授权后 Key 不能调用模型。
- 在线调试:模型和分组直接下拉选择;无需返回模型广场。
- 用户与额度:管理员可直接开通普通账号、创建邀请、发放人民币金额并查看流水;只有超级管理员能升降管理员角色。
`/api/models` 保留 `models`(分组/调用路由列表),新增 `logicalModels`(模型定义)。调用仍使用分组的 `id` 作为 `/v1/chat/completions` 的 `model` 值;`modelKey` 是可编辑的展示标识,不是自动路由或授权通配符。
## 旧数据升级
Flyway V10 自动将每条旧目录项转换为一个模型和一个既有分组;保留旧调用 ID、Key 权限及凭据。为避免错误合并,不按名称自动合并旧模型。需要合并时,在“编辑分组”中更改所属模型,再停用已无分组的旧模型即可。
停用渠道、模型或分组后,对应调用立即不可用;旧 Key 的既有授权仍保留,重新启用后恢复。不能给 Key 新增已停用分组的权限。同一模型内分组名称不能重复。
升级前备份 RDS 的专用数据库、`.env.cloud`、认证 pepper、凭据加密密钥及证书。不要连接或修改其他业务库。V10 上线后不要直接回滚到会写入旧目录结构的旧程序;需要回滚时使用升级前备份和对应旧版本。
旧版 `20260917-202503-f5ba6cb2` 尚无验证码实现和 SMTP/SMS 环境变量映射;只改 `.env.cloud` 或重启旧容器不会启用验证码。必须升级后端、前端及 Compose。复制旧配置到新发布目录,保留所有密钥和新填的 SMTP/SMS 参数,只更新镜像版本与运行时 Dockerfile 设置。
新包提供 `infra/moyi/backup_database.py`,在运行新版本 `up` 之前执行:
```bash
# 在新发布目录的 infra/moyi 下运行;指向当前仍在运行的旧版本。
python3 backup_database.py --deployment-dir /opt/moyi/releases/20260917-202503-f5ba6cb2/infra/moyi --mode https
```
工具核对运行容器、数据库及加密配置,只导出 `moyi_control`;同时保存旧 `.env.cloud`(含 SMTP/SMS)和证书,在 `/opt/moyi/backups/pre-upgrade-*` 创建私有备份。导出后读取整个归档并生成校验清单,成功才输出 `BACKUP_OK`。此检查不等同于向独立数据库实际恢复的演练。备份期间停止人工测试并保持配置不变;命令失败时不要继续升级。备份是一个一致性快照,备份后的新写入不包含在其中。
升级后运行 `python3 deploy.py smoke --mode https --login` 和 `curl --fail --silent --show-error https://moyi.soulofmodel.com/api/auth/verification`。后者只检查发送通道是否配置,不发送验证码;`email: true` 不是投递成功的证明。再通过注册页面用有效邀请码和自己控制的邮箱/手机号完成真实收发与注册验收。
## 邮箱和短信配置
注册现在同时要求有效邀请码和 6 位验证码。邮箱、手机号二选一注册,不要求每个人同时验证两种联系方式。手机目前支持中国大陆号码(可带 `+86`)。登录仍使用账号和密码。管理员直接开户不需要验证码,不会自动取得管理员权限。
未配置的发送通道显示“暂不可用”,不会生成假成功;管理员仍能直接开户。密码找回不在本次实现范围内。
在服务器当前发布目录的 `infra/moyi/.env.cloud` 中填写以下变量,不提交到 Git,不将完整凭据发到聊天中。包含 `$`、`#` 等字符的值用单引号。
| 邮箱变量 | 内容 |
| --- | --- |
| `MOYI_SMTP_HOST` | 邮箱服务商的 SMTP 主机 |
| `MOYI_SMTP_PORT` | 通常为 `465`(SSL)或 `587`(STARTTLS),以服务商为准 |
| `MOYI_SMTP_FROM` | 已验证的发件邮箱 |
| `MOYI_SMTP_USERNAME` | SMTP 登录账号 |
| `MOYI_SMTP_PASSWORD` | SMTP 密码或邮箱授权码 |
| `MOYI_SMTP_SSL` | 465 通常设为 `true`;587 通常为 `false` |
| `MOYI_SMTP_STARTTLS` | 587 通常设为 `true`;465 通常为 `false` |
阿里云短信操作:
1. 打开短信服务控制台,完成资质并申请中国大陆短信签名。
2. 申请验证码模板,模板变量使用 `${code}`,有效期文案为 5 分钟;等待签名和模板审核通过。
3. 建立专用于本项目短信发送的 RAM 凭据,按官方文档授予 `dysms:SendSms` 所需最小权限,不复用其他业务或主账号 AccessKey。
4. 填入 `MOYI_SMS_ACCESS_KEY_ID`、`MOYI_SMS_ACCESS_KEY_SECRET`、`MOYI_SMS_SIGN_NAME`、`MOYI_SMS_TEMPLATE_CODE`。
5. 在阿里云设置发送频率及费用预警,确认短信余额与服务器到短信服务的 HTTPS 出站连接。
6. 使用部署脚本重建/重启新版本容器,让环境变量生效;不要只在页面刷新。用自己控制的邮箱和手机号各做一次真实验证码收发验收。
官方资料:[短信 API 接入](https://help.aliyun.com/zh/sms/getting-started/use-sms-api)。本地测试不调用真实发送服务,配置完成后仍需上述真实发送验收。
验证码 5 分钟有效,错误 5 次后失效,一次性使用。发送限制为同一账号 60 秒间隔、每账号每日 10 次、每来源 IP 每小时 30 次、全平台每日 1000 次;失败的发送请求也占用频率额度。哈希存储验证码,不写入日志或返回前端。发送记录保留最近 2 天。公司共享出口 IP 也共享来源 IP 额度。
云端 Nginx 覆盖客户端转发 IP,并清除外部 `Forwarded`,Java 后端不直接发布公网端口。自行新增代理时需维护这一信任边界,否则来源 IP 限制可能失效或合并。
## 人民币额度边界
发放金额以人民币元输入,最多两位小数、必须大于 0,单笔上限 100 万元。发放必须填写原因,记录操作者、时间、金额和发放后余额;使用事务、钱包行锁和请求编号去重。发放请求遇到网络不确定状态时,原弹窗重试沿用同一个编号,不会重复发放。
本次完成的是余额、发放、查询、流水与审计;不是充值支付或自动扣费。分组价格目前是报价元数据,不能把美元报价或每千/百万 token 单位直接用于人民币扣费。网关尚不根据余额拦截或结算;对外收费前仍必须实现明确币种和计费单位、预占额度、成功结算、失败退回及对账。优先级也尚未用于自动故障切换。
## 本地验证
`PlatformAdminPostgresTest` 仅接受 `127.0.0.1` 的 `MOYI_AUTH_TEST_JDBC_URL`,使用 `moyi_role_test` 测试角色与随机 schema;覆盖迁移、精确分组授权、编辑/停用、直接开户权限、额度并发去重,以及邮箱/手机验证码、锁定、过期、重复提交与发送失败。测试发送器不接入外部服务。
+17
View File
@@ -46,6 +46,23 @@ GATEWAY_DEFAULT_MODEL_CONCURRENCY=4
TASK_MAX_QUEUED_PER_MODEL=100 TASK_MAX_QUEUED_PER_MODEL=100
MOYI_TASK_WORKER_INTERVAL_MS=1000 MOYI_TASK_WORKER_INTERVAL_MS=1000
# Registration requires a valid invitation AND an email/SMS verification code.
# Unconfigured channels fail closed; admins can still create user accounts.
# SMTP authorization password, not your mailbox login password where applicable.
MOYI_SMTP_HOST=
MOYI_SMTP_PORT=465
MOYI_SMTP_FROM=
MOYI_SMTP_USERNAME=
MOYI_SMTP_PASSWORD=
MOYI_SMTP_SSL=true
MOYI_SMTP_STARTTLS=false
# Aliyun domestic SMS: approved signature + template with a ${code} variable.
# Use a dedicated least-privilege RAM credential for SendSms only.
MOYI_SMS_ACCESS_KEY_ID=
MOYI_SMS_ACCESS_KEY_SECRET=
MOYI_SMS_SIGN_NAME=
MOYI_SMS_TEMPLATE_CODE=
# OPTIONAL: use admin UI OR environment for one synchronous provider. # OPTIONAL: use admin UI OR environment for one synchronous provider.
# Environment credentials take precedence over admin UI credentials. # Environment credentials take precedence over admin UI credentials.
DEEPSEEK_API_KEY= DEEPSEEK_API_KEY=
+278
View File
@@ -0,0 +1,278 @@
#!/usr/bin/env python3
"""Reset the existing owner of a single-instance MOYI cloud deployment."""
import argparse
import base64
import copy
import getpass
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import re
import secrets
import shutil
import subprocess
import sys
import tempfile
import urllib.parse
class MaintenanceError(Exception):
pass
def require(condition, message):
if not condition:
raise MaintenanceError(message)
def run(command, *, cwd=None, env=None, sql=None, timeout=240):
options = {"input": sql} if sql is not None else {"stdin": subprocess.DEVNULL}
result = subprocess.run(command, cwd=cwd, env=env, capture_output=True,
text=True, encoding="utf-8", timeout=timeout, **options)
# Database/Compose error messages can contain secrets or SQL; never echo them.
require(result.returncode == 0, Path(command[0]).name + " failed; output withheld to protect credentials.")
return result.stdout.strip()
def password_hash(password, pepper):
salt = secrets.token_bytes(16)
key = hashlib.pbkdf2_hmac("sha256", (password + pepper).encode("utf-8"), salt, 210000, 32)
encode = lambda value: base64.urlsafe_b64encode(value).decode("ascii").rstrip("=")
return "pbkdf2$210000$" + encode(salt) + "$" + encode(key)
def sql_literal(value):
# Hex also prevents dollar-quote delimiters from appearing inside a DO body.
return "convert_from(decode('" + str(value).encode("utf-8").hex() + "', 'hex'), 'UTF8')"
def updated_environment(original, account, password):
require(password.strip() and not any(ord(char) < 32 or ord(char) == 127 for char in password),
"Password must be nonblank and cannot contain control characters.")
require(password != "admin123", "The development default password is not allowed.")
# Append effective overrides, then ask Compose to validate them. Do not parse
# or rewrite arbitrary existing dotenv values, which may be multiline/quoted.
values = {"ADMIN_ACCOUNT": account, "ADMIN_PASSWORD": password}
return original.rstrip("\r\n") + "\n\n# Owner credentials set by admin_credentials.py\n" + "".join(
key + "=" + json.dumps(value, ensure_ascii=False).replace("$", "$$") + "\n"
for key, value in values.items())
def validate_staged_config(before, after, account, password):
expected = copy.deepcopy(before)
expected["services"]["moyi-api"]["environment"].update(
ADMIN_ACCOUNT=account, ADMIN_PASSWORD=password)
require(after == expected, "Staged configuration differs unexpectedly. Check shell environment overrides; nothing was changed.")
def postgres_environment(api, expected_database):
url = str(api["SPRING_DATASOURCE_URL"])
require(url.startswith("jdbc:postgresql://"), "PostgreSQL JDBC URL required.")
target = urllib.parse.urlsplit(url[5:])
require(urllib.parse.unquote(target.path) == "/" + expected_database and target.hostname
and not target.username and not target.password, "Database target does not match --database.")
query = urllib.parse.parse_qs(target.query, keep_blank_values=True)
supported = {"sslmode": "PGSSLMODE", "sslrootcert": "PGSSLROOTCERT", "sslcert": "PGSSLCERT", "sslkey": "PGSSLKEY"}
require(all(key in supported and len(value) == 1 for key, value in query.items()),
"Unsupported JDBC parameters; review TLS settings before maintenance.")
env = {key: value for key, value in os.environ.items() if not key.startswith("PG")}
env.update(PGHOST=target.hostname, PGPORT=str(target.port or 5432), PGDATABASE=expected_database,
PGUSER=str(api["SPRING_DATASOURCE_USERNAME"]), PGPASSWORD=str(api["SPRING_DATASOURCE_PASSWORD"]),
PGCONNECT_TIMEOUT="10", PGAPPNAME="moyi-admin-maintenance", PGCLIENTENCODING="UTF8")
for key, value in query.items():
env[supported[key]] = value[0]
return env
def query_database(psql, env, sql):
return run([psql, "-X", "--no-password", "-qAt", "-v", "ON_ERROR_STOP=1", "-f", "-"], env=env, sql=sql)
def read_owner(psql, env, configured_account, new_account):
rows = json.loads(query_database(psql, env, """
SELECT COALESCE(json_agg(json_build_object('id', id, 'account', account, 'status', status)), '[]'::json)
FROM public.users WHERE role = 'super_admin';
"""))
require(len(rows) == 1 and rows[0]["status"] == "active", "Expected exactly one active super administrator.")
normalized = re.sub(r"[\s-]", "", configured_account.strip().lower())
# The second case permits retry after DB commit but before env installation.
require(rows[0]["account"] in (normalized, new_account.lower()),
"Existing owner differs from both configured and requested accounts; refusing to change it.")
occupied = query_database(psql, env, "SELECT count(*) FROM public.users WHERE account = "
+ sql_literal(new_account.lower()) + " AND id <> " + sql_literal(rows[0]["id"]) + "::uuid;")
require(occupied == "0", "Requested account is already used by another user; nothing changed.")
return rows[0]
def reset_sql(database, owner, account, encoded):
database, user_id, previous, account, encoded = map(sql_literal, (
database, owner["id"], owner["account"], account.lower(), encoded))
return f"""
BEGIN;
SET LOCAL standard_conforming_strings = on;
SET LOCAL lock_timeout = '10s';
SET LOCAL statement_timeout = '30s';
LOCK TABLE public.users IN SHARE ROW EXCLUSIVE MODE;
DO $moyi_reset$
BEGIN
IF current_database() <> {database} THEN
RAISE EXCEPTION 'Wrong database';
END IF;
IF (SELECT count(*) FROM public.users WHERE role = 'super_admin') <> 1
OR NOT EXISTS (SELECT 1 FROM public.users WHERE id = {user_id}::uuid
AND account = {previous} AND role = 'super_admin' AND status = 'active') THEN
RAISE EXCEPTION 'Owner changed; refusing reset';
END IF;
IF EXISTS (SELECT 1 FROM public.users WHERE account = {account} AND id <> {user_id}::uuid) THEN
RAISE EXCEPTION 'Account already exists';
END IF;
UPDATE public.users SET account = {account}, account_kind = 'username',
password_hash = {encoded}, updated_at = now() WHERE id = {user_id}::uuid;
UPDATE public.auth_sessions SET revoked_at = now()
WHERE user_id = {user_id}::uuid AND revoked_at IS NULL;
INSERT INTO public.auth_audit_log (actor_user_id, event_type, target_type, target_id, details)
VALUES ({user_id}::uuid, 'user.credentials_reset', 'user', {user_id},
json_build_object('fromAccount', {previous}, 'account', {account}, 'method', 'server_cli')::jsonb);
END;
$moyi_reset$;
COMMIT;
SELECT 'OWNER_RESET_COMMITTED';
"""
def write_private(path, data):
descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
with os.fdopen(descriptor, "wb") as stream:
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
def install_environment(env_file, content):
temporary = env_file.with_name(".env.owner-" + secrets.token_hex(8))
write_private(temporary, content)
os.replace(temporary, env_file)
if os.name != "nt":
descriptor = os.open(env_file.parent, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(descriptor)
finally:
os.close(descriptor)
def check_container(deploy, config, env_file, mode):
compose = deploy.compose_command(env_file, mode)
ids = run(compose + ["ps", "-a", "-q", "moyi-api"], cwd=deploy.HERE).splitlines()
require(len(ids) == 1, "Expected one existing API container in this Compose project.")
item = json.loads(run(["docker", "inspect", ids[0]]))[0]
labels = item["Config"]["Labels"]
require(Path(labels["com.docker.compose.project.working_dir"]).resolve() == deploy.HERE.resolve(),
"Container belongs to another release directory.")
require(item["Config"]["Image"] == config["services"]["moyi-api"]["image"],
"Running image differs from deployment configuration.")
actual = dict(value.split("=", 1) for value in item["Config"]["Env"] if "=" in value)
expected = config["services"]["moyi-api"]["environment"]
for key in ("SPRING_DATASOURCE_URL", "SPRING_DATASOURCE_USERNAME", "SPRING_DATASOURCE_PASSWORD",
"AUTH_PASSWORD_PEPPER", "CREDENTIAL_ENCRYPTION_KEY"):
require(actual.get(key) == expected.get(key), "Container/database or encryption settings differ; refusing reset.")
return ids[0], compose
def apply_change(deploy, config, env_file, mode, account, password, database, psql, pg_dump, backup_root):
api = config["services"]["moyi-api"]["environment"]
pg_env = postgres_environment(api, database)
owner = read_owner(psql, pg_env, api["ADMIN_ACCOUNT"], account)
container, compose = check_container(deploy, config, env_file, mode)
original = env_file.read_bytes()
content = updated_environment(original.decode("utf-8-sig"), account, password).encode("utf-8")
backup_root.mkdir(mode=0o700, parents=True, exist_ok=True)
backup = Path(tempfile.mkdtemp(prefix="owner-reset-", dir=backup_root))
write_private(backup / "env.cloud.before", original)
write_private(backup / "env.cloud.after", content)
staged = deploy.load_config(backup / "env.cloud.after", mode)
deploy.validate_config(staged, mode)
validate_staged_config(config, staged, account, password)
print("Private recovery directory: " + str(backup), flush=True)
print("Stopping API for backup and session revocation...", flush=True)
mutation_started = False
try:
run(["docker", "stop", "--time", "40", container])
require(env_file.read_bytes() == original, "Environment file changed concurrently; refusing reset.")
dump = backup / "moyi_control.dump"
run([pg_dump, "--no-password", "--format=custom", "--quote-all-identifiers", "--lock-wait-timeout=10000",
"--file=" + str(dump)], env=pg_env)
require(dump.stat().st_size > 0, "Database backup is empty.")
with dump.open("rb") as stream:
digest = hashlib.file_digest(stream, "sha256").hexdigest()
write_private(backup / "moyi_control.dump.sha256", (digest + " moyi_control.dump\n").encode("ascii"))
encoded = password_hash(password, api["AUTH_PASSWORD_PEPPER"])
mutation_started = True
result = query_database(psql, pg_env, reset_sql(database, owner, account, encoded))
require(result == "OWNER_RESET_COMMITTED", "Database outcome uncertain; keep API stopped and rerun this tool.")
install_environment(env_file, content)
run(compose + ["up", "-d", "--no-deps", "--no-build", "--pull", "never", "--force-recreate",
"--wait", "--wait-timeout", "180", "moyi-api"], cwd=deploy.HERE)
run(compose + ["exec", "-T", "frontend", "nginx", "-t"], cwd=deploy.HERE)
run(compose + ["exec", "-T", "frontend", "nginx", "-s", "reload"], cwd=deploy.HERE)
deploy.smoke(staged, mode, login=True)
except BaseException:
if not mutation_started:
run(["docker", "start", container])
print("Reset was not attempted; original API container restarted.", flush=True)
else:
print("Maintenance did not finish. Do not restore the old env or database blindly. "
"Rerun this tool with the same account/password to reconcile and verify. Recovery: " + str(backup), flush=True)
raise
print("SUPER_ADMIN_RESET_OK: " + account + "; existing user ID preserved; previous sessions revoked.")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--deployment-dir", type=Path, required=True)
parser.add_argument("--account", required=True)
parser.add_argument("--database", default="moyi_control")
parser.add_argument("--mode", choices=("https", "tunnel"), default="https")
parser.add_argument("--backup-root", type=Path, default=Path("/opt/moyi/backups"))
parser.add_argument("--apply", action="store_true", help="Stop API, back up, reset owner and restart; password is prompted twice")
args = parser.parse_args()
require(re.fullmatch(r"[A-Za-z][A-Za-z0-9_]{0,79}", args.account), "Use an ASCII username starting with a letter.")
require(re.fullmatch(r"[a-z][a-z0-9_]+", args.database) and args.database not in ("postgres", "template0", "template1"),
"Use a dedicated application database.")
require(not args.apply or (os.name == "posix" and os.geteuid() == 0), "Apply must run as root on the Linux server.")
directory = args.deployment_dir.resolve()
spec = importlib.util.spec_from_file_location("moyi_deploy", directory / "deploy.py")
deploy = importlib.util.module_from_spec(spec)
spec.loader.exec_module(deploy)
env_file = directory / ".env.cloud"
psql, pg_dump = shutil.which("psql"), shutil.which("pg_dump")
require(psql and pg_dump, "Install postgresql-client first.")
if args.apply:
import fcntl
os.umask(0o077)
lock = open(directory / ".owner-maintenance.lock", "a")
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
config = deploy.preflight(env_file, args.mode)
api = config["services"]["moyi-api"]["environment"]
env = postgres_environment(api, args.database)
owner = read_owner(psql, env, api["ADMIN_ACCOUNT"], args.account)
check_container(deploy, config, env_file, args.mode)
print("Database: " + args.database + "; existing super administrator: " + owner["account"])
if not args.apply:
print("Read-only check passed. Add --apply to change credentials.")
return
require(sys.stdin.isatty(), "Run interactively in SSH, not through a heredoc or pipe.")
password = getpass.getpass("New super administrator password (hidden): ")
require(password == getpass.getpass("Repeat new password (hidden): "), "Passwords do not match; nothing changed.")
apply_change(deploy, config, env_file, args.mode, args.account, password, args.database,
psql, pg_dump, args.backup_root.resolve())
if __name__ == "__main__":
try:
main()
except (MaintenanceError, ValueError, OSError, subprocess.SubprocessError, KeyboardInterrupt) as error:
message = str(error) if isinstance(error, MaintenanceError) else type(error).__name__ + ": maintenance stopped; no secret output shown."
print("ERROR: " + message, file=sys.stderr)
sys.exit(1)
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env python3
"""Back up the running MOYI database and its configuration before an upgrade."""
import argparse
import hashlib
import importlib.util
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
from datetime import datetime, timezone
from admin_credentials import MaintenanceError, check_container, postgres_environment, require, run, write_private
def backup(deploy, mode, output_root, database="moyi_control"):
require(database == "moyi_control", "This upgrade backup is restricted to moyi_control.")
programs = {name: shutil.which(name) for name in ("psql", "pg_dump", "pg_restore")}
require(all(programs.values()), "Install postgresql-client before backing up.")
env_file = deploy.HERE / ".env.cloud"
config = deploy.preflight(env_file, mode)
check_container(deploy, config, env_file, mode)
pg_env = postgres_environment(config["services"]["moyi-api"]["environment"], database)
actual = run([programs["psql"], "-X", "--no-password", "-qAt", "-v", "ON_ERROR_STOP=1",
"-c", "SELECT current_database()"], env=pg_env)
require(actual == database, "Connected database does not match moyi_control.")
original = env_file.read_bytes()
output_root.mkdir(mode=0o700, parents=True, exist_ok=True)
destination = Path(tempfile.mkdtemp(prefix="pre-upgrade-", dir=output_root))
print("Private backup directory: " + str(destination), flush=True)
write_private(destination / "env.cloud", original)
if mode == "https":
for name in ("fullchain.pem", "privkey.pem"):
write_private(destination / name, (deploy.HERE / "certs" / name).read_bytes())
dump = destination / "moyi_control.dump"
run([programs["pg_dump"], "--no-password", "--format=custom", "--quote-all-identifiers",
"--lock-wait-timeout=10000", "--file=" + str(dump)], env=pg_env)
require(dump.is_file() and dump.stat().st_size > 0, "Database backup is empty.")
# Read/decompress the whole archive without connecting to any database.
run([programs["pg_restore"], "--file=" + os.devnull, str(dump)])
require(env_file.read_bytes() == original, "Configuration changed during backup; repeat the backup.")
digests = {}
for item in destination.iterdir():
with item.open("rb") as stream:
digests[item.name] = hashlib.file_digest(stream, "sha256").hexdigest()
write_private(destination / "SHA256SUMS", "".join(
value + " " + name + "\n" for name, value in sorted(digests.items())).encode("ascii"))
# This marker is written only after export and full archive validation succeed.
write_private(destination / "backup-complete.json", json.dumps({
"database": database, "deployment": str(deploy.HERE),
"completedAt": datetime.now(timezone.utc).isoformat(), "sha256": digests,
}, indent=2).encode("utf-8"))
print("BACKUP_OK: moyi_control exported; archive read successfully; credentials not printed.")
return destination
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--deployment-dir", type=Path, required=True)
parser.add_argument("--mode", choices=("https", "tunnel"), default="https")
parser.add_argument("--output-root", type=Path, default=Path("/opt/moyi/backups"))
args = parser.parse_args()
os.umask(0o077)
directory = args.deployment_dir.resolve()
spec = importlib.util.spec_from_file_location("running_moyi_deploy", directory / "deploy.py")
deploy = importlib.util.module_from_spec(spec)
spec.loader.exec_module(deploy)
backup(deploy, args.mode, args.output_root.resolve())
if __name__ == "__main__":
try:
main()
except (MaintenanceError, ValueError, OSError, subprocess.SubprocessError) as error:
message = str(error) if isinstance(error, MaintenanceError) else type(error).__name__ + ": backup failed; no secret output shown."
print("ERROR: " + message, file=sys.stderr)
sys.exit(1)
+11
View File
@@ -32,6 +32,17 @@ services:
ADMIN_PASSWORD: ${ADMIN_PASSWORD:?Set a strong initial admin password} ADMIN_PASSWORD: ${ADMIN_PASSWORD:?Set a strong initial admin password}
ADMIN_DISPLAY_NAME: ${ADMIN_DISPLAY_NAME:-MOYI Admin} ADMIN_DISPLAY_NAME: ${ADMIN_DISPLAY_NAME:-MOYI Admin}
SESSION_TTL_HOURS: ${SESSION_TTL_HOURS:-168} SESSION_TTL_HOURS: ${SESSION_TTL_HOURS:-168}
MOYI_SMTP_HOST: ${MOYI_SMTP_HOST:-}
MOYI_SMTP_PORT: ${MOYI_SMTP_PORT:-465}
MOYI_SMTP_FROM: ${MOYI_SMTP_FROM:-}
MOYI_SMTP_USERNAME: ${MOYI_SMTP_USERNAME:-}
MOYI_SMTP_PASSWORD: ${MOYI_SMTP_PASSWORD:-}
MOYI_SMTP_SSL: ${MOYI_SMTP_SSL:-true}
MOYI_SMTP_STARTTLS: ${MOYI_SMTP_STARTTLS:-false}
MOYI_SMS_ACCESS_KEY_ID: ${MOYI_SMS_ACCESS_KEY_ID:-}
MOYI_SMS_ACCESS_KEY_SECRET: ${MOYI_SMS_ACCESS_KEY_SECRET:-}
MOYI_SMS_SIGN_NAME: ${MOYI_SMS_SIGN_NAME:-}
MOYI_SMS_TEMPLATE_CODE: ${MOYI_SMS_TEMPLATE_CODE:-}
GATEWAY_REQUESTS_PER_MINUTE: ${GATEWAY_REQUESTS_PER_MINUTE:-60} GATEWAY_REQUESTS_PER_MINUTE: ${GATEWAY_REQUESTS_PER_MINUTE:-60}
GATEWAY_READS_PER_MINUTE: ${GATEWAY_READS_PER_MINUTE:-300} GATEWAY_READS_PER_MINUTE: ${GATEWAY_READS_PER_MINUTE:-300}
GATEWAY_DEFAULT_MODEL_CONCURRENCY: ${GATEWAY_DEFAULT_MODEL_CONCURRENCY:-4} GATEWAY_DEFAULT_MODEL_CONCURRENCY: ${GATEWAY_DEFAULT_MODEL_CONCURRENCY:-4}
+2
View File
@@ -17,6 +17,7 @@ location /api/ {
proxy_set_header Host $http_host; proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Forwarded "";
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
proxy_connect_timeout 5s; proxy_connect_timeout 5s;
proxy_read_timeout 120s; proxy_read_timeout 120s;
@@ -28,6 +29,7 @@ location /v1/ {
proxy_set_header Host $http_host; proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Forwarded "";
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Connection ""; proxy_set_header Connection "";
proxy_buffering off; proxy_buffering off;
+246
View File
@@ -0,0 +1,246 @@
import base64
import contextlib
import hashlib
import importlib.util
import io
import json
import os
from pathlib import Path
import shutil
import subprocess
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import patch
import uuid
from test_deploy import configuration, deploy, DIRECTORY
SPEC = importlib.util.spec_from_file_location("admin_credentials", DIRECTORY / "admin_credentials.py")
maintenance = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(maintenance)
class CredentialMaintenanceTests(unittest.TestCase):
def test_password_format_matches_java_parameters(self):
for password in ("x", "Test42!", "a'b\\c$#\"", "\u6d4b\u8bd5A1!"):
with self.subTest(password=password):
encoded = maintenance.password_hash(password, "local-test-pepper")
name, iterations, salt, key = encoded.split("$")
self.assertEqual((name, iterations), ("pbkdf2", "210000"))
salt = base64.urlsafe_b64decode(salt + "==")
self.assertEqual(len(salt), 16)
actual = base64.urlsafe_b64decode(key + "=")
self.assertEqual(len(actual), 32)
expected = hashlib.pbkdf2_hmac("sha256", (password + "local-test-pepper").encode(), salt, 210000, 32)
self.assertEqual(expected, actual)
self.assertNotEqual(encoded, maintenance.password_hash(password, "local-test-pepper"))
def test_no_password_minimum_but_rejects_blank_and_control_characters(self):
self.assertIn('ADMIN_PASSWORD="x"', maintenance.updated_environment("OTHER=value\n", "Owner", "x"))
for password in ("", " ", "bad\nline", "bad\x00null", "admin123"):
with self.subTest(password=password), self.assertRaises(maintenance.MaintenanceError):
maintenance.updated_environment("OTHER=value\n", "Owner", password)
def test_database_target_guard_and_no_password_in_argv(self):
api = configuration()["services"]["moyi-api"]["environment"]
env = maintenance.postgres_environment(api, "moyi_control")
self.assertEqual(env["PGDATABASE"], "moyi_control")
with patch.object(maintenance, "run", return_value="ok") as runner:
maintenance.query_database("psql", env, "SELECT 1;")
args, kwargs = runner.call_args
self.assertNotIn(api["SPRING_DATASOURCE_PASSWORD"], " ".join(args[0]))
self.assertEqual(kwargs["env"]["PGPASSWORD"], api["SPRING_DATASOURCE_PASSWORD"])
with self.assertRaisesRegex(maintenance.MaintenanceError, "target"):
maintenance.postgres_environment(api, "other_app")
api["SPRING_DATASOURCE_URL"] += "?sslmode=verify-full&sslrootcert=%2Fopt%2Fmoyi%2Fca.pem"
env = maintenance.postgres_environment(api, "moyi_control")
self.assertEqual(env["PGSSLMODE"], "verify-full")
self.assertEqual(env["PGSSLROOTCERT"], "/opt/moyi/ca.pem")
api["SPRING_DATASOURCE_URL"] += "&unknown=unsafe"
with self.assertRaisesRegex(maintenance.MaintenanceError, "Unsupported"):
maintenance.postgres_environment(api, "moyi_control")
def test_secret_tool_errors_are_not_echoed_and_stdin_is_not_inherited(self):
with patch.object(maintenance.subprocess, "run", return_value=SimpleNamespace(returncode=1, stdout="secret", stderr="secret")) as runner:
with self.assertRaises(maintenance.MaintenanceError) as error:
maintenance.run(["docker", "compose"])
self.assertNotIn("secret", str(error.exception))
self.assertEqual(runner.call_args.kwargs["stdin"], subprocess.DEVNULL)
def test_owner_check_and_recovery_after_commit(self):
owner = {"id": str(uuid.uuid4()), "account": "adimin", "status": "active"}
for rows in ([], [owner, owner], [{**owner, "status": "disabled"}], [{**owner, "account": "other"}]):
with patch.object(maintenance, "query_database", return_value=json.dumps(rows)):
with self.assertRaises(maintenance.MaintenanceError):
maintenance.read_owner("psql", {}, "adimin", "NewOwner")
for account in ("adimin", "newowner"):
with patch.object(maintenance, "query_database", side_effect=[json.dumps([{**owner, "account": account}]), "0"]):
self.assertEqual(maintenance.read_owner("psql", {}, "adimin", "NewOwner")["id"], owner["id"])
with patch.object(maintenance, "query_database", side_effect=[json.dumps([owner]), "1"]):
with self.assertRaisesRegex(maintenance.MaintenanceError, "already used"):
maintenance.read_owner("psql", {}, "adimin", "NewOwner")
def test_config_change_guard_preserves_other_settings(self):
before = configuration()
after = json.loads(json.dumps(before))
after["services"]["moyi-api"]["environment"].update(ADMIN_ACCOUNT="Owner", ADMIN_PASSWORD="x")
maintenance.validate_staged_config(before, after, "Owner", "x")
after["services"]["moyi-api"]["environment"]["AUTH_PASSWORD_PEPPER"] = "changed"
with self.assertRaises(maintenance.MaintenanceError):
maintenance.validate_staged_config(before, after, "Owner", "x")
def test_environment_install_is_atomic(self):
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / ".env.cloud"
path.write_bytes(b"before")
with patch.object(maintenance.os, "replace", side_effect=OSError("test")):
with self.assertRaises(OSError):
maintenance.install_environment(path, b"after")
self.assertEqual(path.read_bytes(), b"before")
maintenance.install_environment(path, b"after")
self.assertEqual(path.read_bytes(), b"after")
@unittest.skipUnless(shutil.which("docker"), "Docker CLI required")
def test_real_compose_password_quoting_preserves_every_other_setting(self):
text = (DIRECTORY / ".env.cloud.example").read_text(encoding="utf-8")
for old, new in {"CHANGE_ME_RDS_HOST": "rds.internal", "CHANGE_ME_RDS_PASSWORD": "test-db",
"CHANGE_ME_TAIR_HOST": "redis.internal", "CHANGE_ME_TAIR_PASSWORD": "test-cache",
"GENERATE_AUTH_PEPPER": "p" * 64, "GENERATE_CREDENTIAL_KEY": "k" * 64,
"GENERATE_ADMIN_PASSWORD": "test-admin"}.items():
text = text.replace(old, new)
with tempfile.TemporaryDirectory() as directory:
path = Path(directory) / ".env.cloud"
maintenance.write_private(path, text.encode())
before = deploy.load_config(path, "https")
for password in ("x", "Test42!", "a'b\\c$#\"", "end\\", "$$literal${HOME}", "\u6d4b\u8bd5A1!", " spaced "):
with self.subTest(password=password):
path.write_text(maintenance.updated_environment(text, "TestOwner", password), encoding="utf-8")
after = deploy.load_config(path, "https")
maintenance.validate_staged_config(before, after, "TestOwner", password)
@unittest.skipUnless(os.environ.get("MOYI_CREDENTIAL_TEST_PG_BIN"), "Isolated local PostgreSQL required")
class CredentialDatabaseTests(unittest.TestCase):
def setUp(self):
self.psql = str(Path(os.environ["MOYI_CREDENTIAL_TEST_PG_BIN"]) / "psql.exe")
self.name = "moyi_credentials_test_" + uuid.uuid4().hex
self.env = {key: value for key, value in os.environ.items() if not key.startswith("PG")}
self.env.update(PGHOST="127.0.0.1", PGPORT="55439", PGUSER="moyi_role_test", PGDATABASE="moyi_role_test")
maintenance.query_database(self.psql, self.env, 'CREATE DATABASE "' + self.name + '";')
self.env["PGDATABASE"] = self.name
repo = DIRECTORY.parents[1]
migrations = repo / "control-plane-java/src/main/resources/db/migration"
maintenance.query_database(self.psql, self.env, (migrations / "V1__auth.sql").read_text() + (migrations / "V9__admin_roles.sql").read_text())
self.owner = {"id": str(uuid.uuid4()), "account": "oldowner", "status": "active"}
self.other = str(uuid.uuid4())
self.session = str(uuid.uuid4())
self.other_session = str(uuid.uuid4())
maintenance.query_database(self.psql, self.env, f"""
INSERT INTO public.users (id, account, account_kind, password_hash, display_name, role) VALUES
('{self.owner['id']}', 'oldowner', 'username', 'old-hash', 'Original name', 'super_admin'),
('{self.other}', 'ordinary', 'username', 'other-hash', 'Other name', 'user');
INSERT INTO public.auth_sessions (id, token_hash, user_id, expires_at) VALUES
('{self.session}', 'owner-token', '{self.owner['id']}', now() + interval '1 day'),
('{self.other_session}', 'other-token', '{self.other}', now() + interval '1 day');
INSERT INTO public.invitation_codes (id, code_hash, code_prefix, label, created_by) VALUES
('{uuid.uuid4()}', 'invite-hash', 'invite', 'Owner relation', '{self.owner['id']}');
""")
def tearDown(self):
self.env["PGDATABASE"] = "moyi_role_test"
maintenance.query_database(self.psql, self.env, 'DROP DATABASE "' + self.name + '";')
def query(self, sql):
return maintenance.query_database(self.psql, self.env, sql)
def test_reset_preserves_identity_relations_other_users_and_revokes_owner_sessions(self):
encoded = maintenance.password_hash("Test42!", "local-test-pepper")
self.assertEqual(self.query(maintenance.reset_sql(self.name, self.owner, "NewOwner", encoded)), "OWNER_RESET_COMMITTED")
data = json.loads(self.query("SELECT row_to_json(u) FROM public.users u WHERE role = 'super_admin'"))
self.assertEqual(data["id"], self.owner["id"])
self.assertEqual(data["account"], "newowner")
self.assertEqual(data["password_hash"], encoded)
self.assertEqual(data["display_name"], "Original name")
self.assertEqual(self.query("SELECT count(*) FROM public.users"), "2")
self.assertEqual(self.query("SELECT created_by FROM public.invitation_codes"), self.owner["id"])
self.assertEqual(self.query(f"SELECT revoked_at IS NOT NULL FROM public.auth_sessions WHERE id = '{self.session}'"), "t")
self.assertEqual(self.query(f"SELECT revoked_at IS NULL FROM public.auth_sessions WHERE id = '{self.other_session}'"), "t")
self.assertEqual(self.query(f"SELECT password_hash FROM public.users WHERE id = '{self.other}'"), "other-hash")
details = self.query("SELECT details FROM public.auth_audit_log WHERE event_type = 'user.credentials_reset'")
self.assertNotIn("password", details)
self.assertNotIn(encoded, details)
self.assertIn("newowner", details)
current = maintenance.read_owner(self.psql, self.env, "oldowner", "NewOwner")
self.assertEqual(self.query(maintenance.reset_sql(self.name, current, "NewOwner", encoded)), "OWNER_RESET_COMMITTED")
def test_conflict_wrong_database_and_owner_drift_leave_everything_unchanged(self):
for database, owner, account in ((self.name, self.owner, "ordinary"), ("wrong_database", self.owner, "NewOwner"),
(self.name, {**self.owner, "account": "changed"}, "NewOwner")):
with self.subTest(database=database, account=account):
with self.assertRaises(maintenance.MaintenanceError):
self.query(maintenance.reset_sql(database, owner, account, "new-hash"))
self.assertEqual(self.query("SELECT account FROM public.users WHERE role = 'super_admin'"), "oldowner")
self.assertEqual(self.query("SELECT count(*) FROM public.auth_audit_log"), "0")
self.assertEqual(self.query("SELECT count(*) FROM public.auth_sessions WHERE revoked_at IS NOT NULL"), "0")
def test_audit_failure_rolls_back_password_and_session_changes(self):
self.query("ALTER TABLE public.auth_audit_log ADD CONSTRAINT test_reject_audit CHECK (event_type <> 'user.credentials_reset')")
with self.assertRaises(maintenance.MaintenanceError):
self.query(maintenance.reset_sql(self.name, self.owner, "NewOwner", "new-hash"))
self.assertEqual(self.query("SELECT password_hash FROM public.users WHERE role = 'super_admin'"), "old-hash")
self.assertEqual(self.query("SELECT count(*) FROM public.auth_sessions WHERE revoked_at IS NOT NULL"), "0")
@unittest.skipUnless(shutil.which("docker"), "Docker CLI required for config parsing only")
def test_real_backup_and_recovery_when_env_install_fails_after_commit(self):
text = (DIRECTORY / ".env.cloud.example").read_text(encoding="utf-8")
for old, new in {"jdbc:postgresql://CHANGE_ME_RDS_HOST:5432/moyi_control": "jdbc:postgresql://127.0.0.1:55439/" + self.name,
"MOYI_DB_USERNAME=moyi_app": "MOYI_DB_USERNAME=moyi_role_test", "CHANGE_ME_RDS_PASSWORD": "test-only",
"CHANGE_ME_TAIR_HOST": "redis.internal", "CHANGE_ME_TAIR_PASSWORD": "test-cache",
"GENERATE_AUTH_PEPPER": "p" * 64, "GENERATE_CREDENTIAL_KEY": "k" * 64,
"GENERATE_ADMIN_PASSWORD": "test-admin", "ADMIN_ACCOUNT=adimin": "ADMIN_ACCOUNT=oldowner"}.items():
text = text.replace(old, new)
pg_dump = str(Path(self.psql).with_name("pg_dump.exe"))
real_run = maintenance.run
docker_calls = []
def run_command(command, **kwargs):
if command[0] == "docker":
docker_calls.append(command)
return ""
return real_run(command, **kwargs)
with tempfile.TemporaryDirectory() as temporary:
path = Path(temporary) / ".env.cloud"
backups = Path(temporary) / "backups"
maintenance.write_private(path, text.encode())
cfg = deploy.load_config(path, "https")
with patch.object(maintenance, "check_container", return_value=("test-container", ["docker", "compose"])), \
patch.object(maintenance, "run", side_effect=run_command), patch.object(deploy, "smoke") as smoke, \
contextlib.redirect_stdout(io.StringIO()):
with patch.object(maintenance, "install_environment", side_effect=OSError("injected failure")):
with self.assertRaises(OSError):
maintenance.apply_change(deploy, cfg, path, "https", "NewOwner", "x", self.name,
self.psql, pg_dump, backups)
self.assertEqual(path.read_bytes(), text.encode())
self.assertEqual(self.query("SELECT account FROM public.users WHERE role = 'super_admin'"), "newowner")
self.assertFalse(any(call[1] == "start" or "up" in call for call in docker_calls))
smoke.assert_not_called()
backup = next(backups.glob("owner-reset-*"))
pg_restore = str(Path(self.psql).with_name("pg_restore.exe"))
listing = real_run([pg_restore, "--list", str(backup / "moyi_control.dump")])
self.assertIn("TABLE DATA public users", listing)
real_run([pg_restore, "--file=" + os.devnull, str(backup / "moyi_control.dump")])
maintenance.apply_change(deploy, cfg, path, "https", "NewOwner", "x", self.name,
self.psql, pg_dump, backups)
smoke.assert_called_once()
self.assertTrue(smoke.call_args.kwargs["login"])
final = deploy.load_config(path, "https")
maintenance.validate_staged_config(cfg, final, "NewOwner", "x")
self.assertEqual(self.query("SELECT count(*) FROM public.users WHERE role = 'super_admin'"), "1")
self.assertEqual(self.query("SELECT id FROM public.users WHERE role = 'super_admin'"), self.owner["id"])
self.assertTrue(any("--force-recreate" in call and "--no-build" in call for call in docker_calls))
if __name__ == "__main__":
unittest.main()
+66
View File
@@ -0,0 +1,66 @@
import importlib.util
import json
from pathlib import Path
import sys
import tempfile
from types import SimpleNamespace
import unittest
from unittest.mock import patch
from test_deploy import configuration, DIRECTORY
sys.path.insert(0, str(DIRECTORY))
SPEC = importlib.util.spec_from_file_location("backup_database", DIRECTORY / "backup_database.py")
backup_database = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(backup_database)
class BackupTests(unittest.TestCase):
def test_wrong_database_is_rejected_before_export(self):
with tempfile.TemporaryDirectory() as root:
config = configuration()
config["services"]["moyi-api"]["environment"]["SPRING_DATASOURCE_URL"] = "jdbc:postgresql://rds.internal:5432/another_app"
deploy = SimpleNamespace(HERE=Path(root), preflight=lambda *args: config)
with patch.object(backup_database.shutil, "which", side_effect=lambda name: name), \
patch.object(backup_database, "check_container"), \
patch.object(backup_database, "run") as command:
with self.assertRaisesRegex(backup_database.MaintenanceError, "target"):
backup_database.backup(deploy, "tunnel", Path(root) / "backups")
command.assert_not_called()
def test_complete_marker_requires_successful_archive_validation(self):
for corrupt in (False, True):
with self.subTest(corrupt=corrupt), tempfile.TemporaryDirectory() as root:
directory = Path(root)
(directory / ".env.cloud").write_text("MOYI_SMTP_PASSWORD='test-only-secret'\n")
deploy = SimpleNamespace(HERE=directory, preflight=lambda *args: configuration())
seen = []
def command(argv, **kwargs):
seen.append(argv)
self.assertNotIn("test-only-rds-password", " ".join(argv))
if argv[0] == "psql":
return "moyi_control"
if argv[0] == "pg_dump":
Path(next(item[7:] for item in argv if item.startswith("--file="))).write_bytes(b"test archive")
if argv[0] == "pg_restore" and corrupt:
raise backup_database.MaintenanceError("Invalid archive")
return ""
with patch.object(backup_database.shutil, "which", side_effect=lambda name: name), \
patch.object(backup_database, "check_container"), patch.object(backup_database, "run", side_effect=command):
if corrupt:
with self.assertRaisesRegex(backup_database.MaintenanceError, "Invalid archive"):
backup_database.backup(deploy, "tunnel", directory / "backups")
self.assertEqual([], list((directory / "backups").rglob("backup-complete.json")))
else:
destination = backup_database.backup(deploy, "tunnel", directory / "backups")
report = json.loads((destination / "backup-complete.json").read_text())
self.assertEqual(report["database"], "moyi_control")
self.assertEqual((destination / "env.cloud").read_bytes(), (directory / ".env.cloud").read_bytes())
self.assertEqual(set(report["sha256"]), {"env.cloud", "moyi_control.dump"})
self.assertEqual([argv[0] for argv in seen], ["psql", "pg_dump", "pg_restore"])
if __name__ == "__main__":
unittest.main()
+6
View File
@@ -37,6 +37,12 @@ def configuration():
class DeploymentTests(unittest.TestCase): class DeploymentTests(unittest.TestCase):
def test_proxy_replaces_forwarding_headers_for_verification_limits(self):
routes = (DIRECTORY / "nginx" / "routes.conf").read_text(encoding="utf-8")
self.assertEqual(routes.count('proxy_set_header Forwarded "";'), 2)
self.assertEqual(routes.count('proxy_set_header X-Forwarded-For $remote_addr;'), 2)
self.assertNotIn('$proxy_add_x_forwarded_for', routes)
def test_login_smoke_requires_super_admin_and_checks_management(self): def test_login_smoke_requires_super_admin_and_checks_management(self):
cfg = configuration() cfg = configuration()
cfg["services"]["moyi-api"]["environment"]["ADMIN_ACCOUNT"] = "adimin" cfg["services"]["moyi-api"]["environment"]["ADMIN_ACCOUNT"] = "adimin"
+4 -2
View File
@@ -10,7 +10,8 @@ server {
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Forwarded "";
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Cookie $http_cookie; proxy_set_header Cookie $http_cookie;
} }
@@ -20,7 +21,8 @@ server {
proxy_http_version 1.1; proxy_http_version 1.1;
proxy_set_header Host $host; proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header Forwarded "";
proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Authorization $http_authorization; proxy_set_header Authorization $http_authorization;
proxy_set_header Content-Type $http_content_type; proxy_set_header Content-Type $http_content_type;
+6 -4
View File
@@ -29,6 +29,7 @@ const authenticated = ref(false)
const authUser = ref<AuthUser>() const authUser = ref<AuthUser>()
const accountMenuOpen = ref(false) const accountMenuOpen = ref(false)
const userName = ref('') const userName = ref('')
const availableCredit = ref<number>()
onMounted(async () => { onMounted(async () => {
try { try {
@@ -80,6 +81,7 @@ function signIn(user: AuthUser) {
} }
function logout() { function logout() {
availableCredit.value = undefined
accountMenuOpen.value = false accountMenuOpen.value = false
portal.value = 'user' portal.value = 'user'
activeView.value = 'overview' activeView.value = 'overview'
@@ -130,9 +132,9 @@ function openAccountSettings() {
<div class="sidebar-footer"> <div class="sidebar-footer">
<div v-if="portal === 'user'" class="balance-card"> <div v-if="portal === 'user'" class="balance-card">
<span>额度账本</span> <span>可用额度</span>
<strong>尚未接入</strong> <strong>{{ availableCredit === undefined ? '--' : `¥ ${availableCredit.toFixed(2)}` }}</strong>
<small>额度由管理员配置后显示</small> <small>人民币 CNY</small>
</div> </div>
<div v-else class="security-card"><ShieldCheck :size="17" /><span>管理操作均写入审计日志</span></div> <div v-else class="security-card"><ShieldCheck :size="17" /><span>管理操作均写入审计日志</span></div>
<button class="nav-link" @click="notify('帮助中心将在后续阶段开放')"><CircleHelp :size="18" /><span>帮助中心</span></button> <button class="nav-link" @click="notify('帮助中心将在后续阶段开放')"><CircleHelp :size="18" /><span>帮助中心</span></button>
@@ -164,7 +166,7 @@ function openAccountSettings() {
</header> </header>
<main class="content"> <main class="content">
<UserConsole v-if="portal === 'user'" :view="activeView" :display-name="userName" @navigate="navigate" @notify="notify" /> <UserConsole v-if="portal === 'user'" :view="activeView" :display-name="userName" @navigate="navigate" @notify="notify" @balance="availableCredit = $event" />
<AdminConsole v-else :view="activeView" :current-user="authUser" @navigate="navigate" @notify="notify" /> <AdminConsole v-else :view="activeView" :current-user="authUser" @navigate="navigate" @notify="notify" />
</main> </main>
</div> </div>
+106
View File
@@ -0,0 +1,106 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { Plus, KeyRound, CircleDollarSign, RefreshCcw, Search, ShieldCheck, List } from 'lucide-vue-next'
import { catalogClient, type AdminCatalogUser, type WalletEntry } from '../services/catalog'
import type { AuthUser } from '../services/auth'
import UiModal from './UiModal.vue'
import SlidePanel from './SlidePanel.vue'
const props = defineProps<{ currentUser?: AuthUser }>()
const emit = defineEmits<{ notify: [message: string] }>()
const users = ref<AdminCatalogUser[]>([])
const balances = ref<Record<string, number>>({})
const query = ref('')
const loading = ref(false)
const saving = ref(false)
const error = ref('')
const editor = ref<'account' | 'invite' | 'credit' | 'role' | ''>('')
const target = ref<AdminCatalogUser>()
const account = reactive({ account: '', displayName: '', password: '' })
const role = ref<'user' | 'admin'>('user')
const inviteLabel = ref('')
const inviteCode = ref('')
const amount = ref('')
const reason = ref('')
const requestId = ref('')
const submittedGrant = ref<{ requestId: string; amount: string; reason: string }>()
const ledgerUser = ref<AdminCatalogUser>()
const entries = ref<WalletEntry[]>([])
const ledgerLoading = ref(false)
const filteredUsers = computed(() => users.value.filter(user => `${user.account} ${user.displayName}`.toLowerCase().includes(query.value.toLowerCase())))
const totalBalance = computed(() => Object.values(balances.value).reduce((sum, balance) => sum + Number(balance), 0))
const money = (value: number | undefined) => `¥ ${Number(value || 0).toFixed(2)}`
const roleName = (value: string) => ({ user: '普通用户', admin: '管理员', super_admin: '超级管理员' })[value] || value
async function refresh() {
loading.value = true
error.value = ''
try {
const [userResult, walletResult] = await Promise.all([catalogClient.listAdminUsers(), catalogClient.listWallets()])
users.value = userResult.users
balances.value = Object.fromEntries(walletResult.wallets.map(item => [item.userId, Number(item.balance)]))
} catch (e) { error.value = e instanceof Error ? e.message : '加载失败' }
finally { loading.value = false }
}
onMounted(refresh)
function createAccount() { Object.assign(account, { account: '', displayName: '', password: '' }); editor.value = 'account' }
function createInvite() { inviteCode.value = ''; inviteLabel.value = ''; editor.value = 'invite' }
function credit(user: AdminCatalogUser) {
target.value = user; amount.value = ''; reason.value = ''; requestId.value = crypto.randomUUID(); submittedGrant.value = undefined; editor.value = 'credit'
}
function editRole(user: AdminCatalogUser) { target.value = user; role.value = user.role === 'admin' ? 'admin' : 'user'; editor.value = 'role' }
async function ledger(user: AdminCatalogUser) {
ledgerUser.value = user; entries.value = []; ledgerLoading.value = true
try { entries.value = (await catalogClient.walletEntries(user.id)).entries }
catch (e) { emit('notify', e instanceof Error ? e.message : '加载流水失败') }
finally { ledgerLoading.value = false }
}
async function save() {
if (saving.value) return
saving.value = true
try {
if (editor.value === 'account') {
await catalogClient.createAdminUser(account)
account.password = ''
} else if (editor.value === 'invite') {
inviteCode.value = (await catalogClient.createAdminInvitation({ label: inviteLabel.value, maxUses: 1 })).code
emit('notify', '邀请码已创建')
return
} else if (editor.value === 'role' && target.value) {
await catalogClient.changeUserRole(target.value.id, role.value)
} else if (editor.value === 'credit' && target.value) {
if (!reason.value.trim()) throw new Error('请填写发放原因')
if (!submittedGrant.value) submittedGrant.value = { requestId: requestId.value, amount: amount.value, reason: reason.value.trim() }
await catalogClient.grantCredit(target.value.id, submittedGrant.value)
}
editor.value = ''
await refresh()
emit('notify', '操作已完成')
} catch (e) { emit('notify', e instanceof Error ? e.message : '操作失败') }
finally { saving.value = false }
}
</script>
<template>
<section class="page-heading"><h1>用户与额度</h1><div class="heading-actions"><button class="icon-button" title="刷新用户" :disabled="loading" @click="refresh"><RefreshCcw :size="18" /></button><button class="button secondary" @click="createInvite"><KeyRound :size="16" />创建邀请</button><button class="button primary" @click="createAccount"><Plus :size="16" />开通账号</button></div></section>
<div class="account-summary"><span>用户 <strong>{{ users.length }}</strong></span><span>人民币余额合计 <strong>{{ money(totalBalance) }}</strong></span></div>
<label class="search-input account-search"><Search :size="16" /><input v-model="query" placeholder="搜索账号或姓名" /></label>
<p v-if="error" role="alert">{{ error }}</p><p v-if="loading">加载中…</p>
<div class="responsive-table"><table><thead><tr><th>用户</th><th>角色</th><th>人民币余额</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="user in filteredUsers" :key="user.id"><td><strong>{{ user.displayName }}</strong><small class="account-secondary">{{ user.account }}</small></td><td>{{ roleName(user.role) }}</td><td>{{ money(balances[user.id]) }}</td><td>{{ user.status === 'active' ? '正常' : '已停用' }}</td><td><div class="heading-actions"><button class="button secondary small" :disabled="user.status !== 'active'" @click="credit(user)"><CircleDollarSign :size="15" />发放额度</button><button class="icon-button" :title="`${user.account} 额度流水`" @click="ledger(user)"><List :size="16" /></button><button v-if="props.currentUser?.role === 'super_admin' && user.role !== 'super_admin'" class="icon-button" :title="`${user.account} 修改角色`" @click="editRole(user)"><ShieldCheck :size="16" /></button></div></td></tr><tr v-if="!filteredUsers.length && !loading"><td colspan="5">暂无用户</td></tr></tbody></table></div>
<UiModal v-if="editor" :title="editor === 'account' ? '开通账号' : editor === 'invite' ? '创建邀请' : editor === 'credit' ? '发放人民币额度' : '修改角色'" @close="!saving && (editor = '')">
<form id="account-editor" @submit.prevent="save">
<template v-if="editor === 'account'"><label class="form-label" for="new-account">账号</label><input id="new-account" v-model="account.account" class="text-input" required maxlength="254" autocomplete="off" placeholder="用户名、邮箱或手机号" /><label class="form-label" for="new-display">显示名称</label><input id="new-display" v-model="account.displayName" class="text-input" maxlength="80" /><label class="form-label" for="new-password">初始密码</label><input id="new-password" v-model="account.password" type="password" class="text-input" required minlength="8" maxlength="256" autocomplete="new-password" /></template>
<template v-else-if="editor === 'invite'"><label class="form-label" for="invite-label">邀请备注</label><input id="invite-label" v-model="inviteLabel" class="text-input" :disabled="!!inviteCode" /><label v-if="inviteCode" class="form-label" for="invite-code">邀请码(仅显示一次)</label><input v-if="inviteCode" id="invite-code" :value="inviteCode" class="text-input" readonly /></template>
<template v-else-if="editor === 'credit'"><p>{{ target?.displayName }} · {{ target?.account }}</p><p>当前余额:{{ money(balances[target?.id || '']) }}</p><label class="form-label" for="grant-amount">发放金额(人民币元)</label><input id="grant-amount" v-model="amount" class="text-input" required type="number" min="0.01" max="1000000" step="0.01" :disabled="!!submittedGrant" /><label class="form-label" for="grant-reason">发放原因</label><textarea id="grant-reason" v-model="reason" class="text-input" required maxlength="500" :disabled="!!submittedGrant" /><p>本次增加:{{ money(Number(amount)) }}</p></template>
<template v-else><p>{{ target?.displayName }} · {{ target?.account }}</p><label class="form-label" for="account-role">角色</label><select id="account-role" v-model="role" class="text-input"><option value="user">普通用户</option><option value="admin">管理员</option></select></template>
</form>
<template #footer><button class="button secondary" :disabled="saving" @click="editor = ''">关闭</button><button v-if="!inviteCode || editor !== 'invite'" class="button primary" type="submit" form="account-editor" :disabled="saving">{{ saving ? '提交中…' : editor === 'credit' ? '确认发放' : '确认' }}</button></template>
</UiModal>
<SlidePanel v-if="ledgerUser" :title="`${ledgerUser.displayName} · 额度流水`" @close="ledgerUser = undefined"><p>币种:人民币 CNY</p><p v-if="ledgerLoading">加载中…</p><div v-for="entry in entries" :key="entry.id" class="wallet-entry"><strong>+ {{ money(entry.amount) }}</strong><p>{{ entry.reason }}</p><small>{{ entry.actor }} · {{ new Date(entry.createdAt).toLocaleString('zh-CN') }}</small><p>余额 {{ money(entry.balanceAfter) }}</p></div><p v-if="!entries.length && !ledgerLoading">暂无流水</p></SlidePanel>
</template>
<style scoped>
.account-summary { display: flex; flex-wrap: wrap; gap: 28px; padding: 16px 0; border-bottom: 1px solid #dce3e5; }
.account-search { max-width: 420px; }
.account-secondary { display: block; margin-top: 5px; color: #687378; }
.wallet-entry { border-bottom: 1px solid #dce3e5; padding: 16px 0; overflow-wrap: anywhere; }
@media(max-width: 700px) { .heading-actions { flex-wrap: wrap; } }
</style>
+151
View File
@@ -0,0 +1,151 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { Plus, Pencil, RefreshCcw, Search } from 'lucide-vue-next'
import { catalogClient, type CatalogProvider, type CatalogModel, type LogicalModel } from '../services/catalog'
import UiModal from './UiModal.vue'
const props = defineProps<{ section: 'models' | 'channels' }>()
const emit = defineEmits<{ notify: [message: string] }>()
const channels = ref<CatalogProvider[]>([])
const models = ref<LogicalModel[]>([])
const groups = ref<CatalogModel[]>([])
const query = ref('')
const loading = ref(false)
const saving = ref(false)
const error = ref('')
const editor = ref<'channel' | 'model' | 'group' | ''>('')
const editingId = ref<string>()
const channel = reactive({ code: '', name: '', protocol: 'openai-compatible' as CatalogProvider['protocol'], sourceType: 'relay' as CatalogProvider['sourceType'], baseUrl: '', credentialType: 'api-key' as NonNullable<CatalogProvider['credentialType']>, credentialSecret: '', description: '', status: 'active' as CatalogProvider['status'] })
const model = reactive({ publicName: '', modelKey: '', type: 'text' as LogicalModel['type'], mode: 'sync' as LogicalModel['mode'], description: '', inputTypes: 'text', outputTypes: 'text', status: 'active' as LogicalModel['status'] })
const group = reactive({ logicalModelId: '', providerId: '', sourceLabel: '', upstreamModel: '', input: '', output: '', unit: 'CNY / 1M tokens', priority: '100', maxConcurrency: '1', status: 'active' as CatalogModel['status'] })
const shownModels = computed(() => models.value.filter(item => `${item.publicName} ${item.modelKey || ''}`.toLowerCase().includes(query.value.toLowerCase())))
const shownChannels = computed(() => channels.value.filter(item => `${item.name} ${item.code}`.toLowerCase().includes(query.value.toLowerCase())))
const channelName = (id: string) => channels.value.find(item => item.id === id)?.name || id
const modelGroups = (id: string) => groups.value.filter(item => item.logicalModelId === id)
async function refresh() {
loading.value = true
error.value = ''
try {
const [providers, catalog] = await Promise.all([catalogClient.listAdminProviders(), catalogClient.listAdminModels()])
channels.value = providers.providers
models.value = catalog.logicalModels
groups.value = catalog.models
} catch (e) { error.value = e instanceof Error ? e.message : '加载失败' }
finally { loading.value = false }
}
onMounted(refresh)
watch(() => props.section, () => { query.value = '' })
function editChannel(item?: CatalogProvider) {
editingId.value = item?.id
Object.assign(channel, { code: '', name: '', protocol: 'openai-compatible', sourceType: 'relay', baseUrl: '', credentialType: 'api-key', description: '', status: 'active' }, item || {}, { credentialSecret: '' })
editor.value = 'channel'
}
function editModel(item?: LogicalModel) {
editingId.value = item?.id
Object.assign(model, { publicName: '', modelKey: '', type: 'text', mode: 'sync', description: '', status: 'active' }, item || {}, { inputTypes: item?.inputTypes.join(', ') || 'text', outputTypes: item?.outputTypes.join(', ') || 'text' })
editor.value = 'model'
}
function editGroup(parent: LogicalModel, item?: CatalogModel) {
editingId.value = item?.id
Object.assign(group, { logicalModelId: parent.id, providerId: item?.providerId || '', sourceLabel: item?.sourceLabel || '', upstreamModel: item?.upstreamModel || '', input: item?.pricing?.input?.toString() || '', output: item?.pricing?.output?.toString() || '', unit: item?.pricing?.unit || 'CNY / 1M tokens', priority: String(item?.priority ?? 100), maxConcurrency: String(item?.maxConcurrency ?? 1), status: item?.status || 'active' })
editor.value = 'group'
}
async function save() {
if (saving.value) return
saving.value = true
try {
if (editor.value === 'channel') {
if (!channel.code.trim() || !channel.name.trim()) throw new Error('请填写渠道 Code 和名称')
if (editingId.value) await catalogClient.updateAdminProvider(editingId.value, { code: channel.code, name: channel.name, protocol: channel.protocol, sourceType: channel.sourceType, baseUrl: channel.baseUrl, credentialType: channel.credentialType, credentialSecret: channel.credentialSecret || undefined, description: channel.description, status: channel.status })
else await catalogClient.createAdminProvider({ ...channel })
channel.credentialSecret = ''
} else if (editor.value === 'model') {
if (!model.publicName.trim()) throw new Error('请填写模型名称')
await catalogClient.saveDefinition(editingId.value, { ...model, inputTypes: model.inputTypes.split(',').map(s => s.trim()).filter(Boolean), outputTypes: model.outputTypes.split(',').map(s => s.trim()).filter(Boolean) })
} else {
if (!group.providerId || !group.sourceLabel.trim() || !group.upstreamModel.trim()) throw new Error('请选择渠道并填写分组名称、上游模型标识')
await catalogClient.saveGroup(editingId.value, { logicalModelId: group.logicalModelId, providerId: group.providerId, sourceLabel: group.sourceLabel, upstreamModel: group.upstreamModel, status: group.status, priority: Number(group.priority), maxConcurrency: Number(group.maxConcurrency), pricing: { input: group.input === '' ? undefined : Number(group.input), output: group.output === '' ? undefined : Number(group.output), unit: group.unit } })
}
editor.value = ''
await refresh()
emit('notify', '已保存')
} catch (e) { emit('notify', e instanceof Error ? e.message : '保存失败') }
finally { saving.value = false }
}
async function toggle(kind: 'channel' | 'model' | 'group', item: CatalogProvider | LogicalModel | CatalogModel) {
if (saving.value) return
saving.value = true
try {
const status = item.status === 'active' ? 'disabled' : 'active'
if (kind === 'channel') await catalogClient.updateAdminProvider(item.id, { status })
else if (kind === 'model') await catalogClient.saveDefinition(item.id, { status })
else await catalogClient.saveGroup(item.id, { status })
await refresh()
emit('notify', status === 'active' ? '已启用' : '已停用')
} catch (e) { emit('notify', e instanceof Error ? e.message : '状态更新失败') }
finally { saving.value = false }
}
</script>
<template>
<section class="page-heading"><h1>{{ props.section === 'channels' ? '渠道管理' : '模型与分组' }}</h1><div class="heading-actions"><button class="icon-button" title="刷新" :disabled="loading" @click="refresh"><RefreshCcw :size="18" /></button><button class="button primary" @click="props.section === 'channels' ? editChannel() : editModel()"><Plus :size="16" />{{ props.section === 'channels' ? '添加渠道' : '添加模型' }}</button></div></section>
<label class="search-input catalog-search"><Search :size="16" /><input v-model="query" :placeholder="props.section === 'channels' ? '搜索渠道名称或 Code' : '搜索模型名称或标识'" /></label>
<p v-if="error" role="alert">{{ error }}</p>
<p v-if="loading">加载中…</p>
<div v-if="props.section === 'channels'" class="responsive-table"><table><thead><tr><th>渠道</th><th>来源 / 协议</th><th>Base URL</th><th>凭据</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="item in shownChannels" :key="item.id"><td><strong>{{ item.name }}</strong><small class="catalog-secondary">{{ item.code }}</small></td><td>{{ item.sourceType }}<small class="catalog-secondary">{{ item.protocol }}</small></td><td class="catalog-url">{{ item.baseUrl || '未配置' }}</td><td>{{ item.credentialMasked || '未配置' }}</td><td><label class="catalog-toggle"><input type="checkbox" :checked="item.status === 'active'" :disabled="saving" :aria-label="`${item.name} 启用`" @change="toggle('channel', item)" />{{ item.status === 'active' ? '已启用' : '已停用' }}</label></td><td><button class="icon-button" :title="`编辑渠道 ${item.name}`" @click="editChannel(item)"><Pencil :size="16" /></button></td></tr><tr v-if="!shownChannels.length && !loading"><td colspan="6">暂无渠道</td></tr></tbody></table></div>
<template v-else>
<section v-for="item in shownModels" :key="item.id" class="model-definition-section">
<header class="panel-header"><div><h3>{{ item.publicName }}</h3><small>{{ item.modelKey || item.id }} · {{ item.type }} · {{ item.mode }}</small></div><div class="heading-actions"><label class="catalog-toggle"><input type="checkbox" :checked="item.status === 'active'" :disabled="saving" :aria-label="`${item.publicName} 启用`" @change="toggle('model', item)" />启用</label><button class="icon-button" :title="`编辑模型 ${item.publicName}`" @click="editModel(item)"><Pencil :size="16" /></button><button class="button secondary small" @click="editGroup(item)"><Plus :size="15" />添加分组</button></div></header>
<p v-if="item.description" class="catalog-secondary">{{ item.description }}</p>
<div class="responsive-table"><table><thead><tr><th>分组名称</th><th>渠道</th><th>上游模型</th><th>输入 / 输出价格</th><th>并发</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="route in modelGroups(item.id)" :key="route.id"><td>{{ route.sourceLabel }}</td><td>{{ channelName(route.providerId) }}</td><td><code>{{ route.upstreamModel }}</code></td><td>{{ route.pricing?.input ?? '—' }} / {{ route.pricing?.output ?? '—' }}<small class="catalog-secondary">{{ route.pricing?.unit }}</small></td><td>{{ route.maxConcurrency ?? '默认' }}</td><td><label class="catalog-toggle"><input type="checkbox" :checked="route.status === 'active'" :disabled="saving" :aria-label="`${route.sourceLabel} 启用`" @change="toggle('group', route)" />{{ route.status === 'active' ? '已启用' : '已停用' }}</label></td><td><button class="icon-button" :title="`编辑分组 ${route.sourceLabel}`" @click="editGroup(item, route)"><Pencil :size="16" /></button></td></tr><tr v-if="!modelGroups(item.id).length"><td colspan="7">暂无分组</td></tr></tbody></table></div>
</section>
<p v-if="!shownModels.length && !loading">暂无模型</p>
</template>
<UiModal v-if="editor" :title="`${editingId ? '编辑' : '添加'}${editor === 'channel' ? '渠道' : editor === 'model' ? '模型' : '分组'}`" @close="!saving && (editor = '')">
<form id="catalog-editor" @submit.prevent="save">
<template v-if="editor === 'channel'">
<label class="form-label" for="channel-code">渠道 Code</label><input id="channel-code" v-model="channel.code" class="text-input" required maxlength="64" pattern="[a-z0-9][a-z0-9._\-]{1,63}" />
<label class="form-label" for="channel-name">渠道名称</label><input id="channel-name" v-model="channel.name" class="text-input" required maxlength="120" />
<label class="form-label" for="channel-source">来源类型</label><select id="channel-source" v-model="channel.sourceType" class="text-input"><option value="relay">中转站</option><option value="official">官方供应商</option><option value="self-hosted">自托管</option><option value="custom">其他</option></select>
<label class="form-label" for="channel-protocol">接入协议</label><select id="channel-protocol" v-model="channel.protocol" class="text-input"><option value="openai-compatible">OpenAI 兼容</option><option value="http">HTTP</option><option value="sdk">SDK</option></select>
<label class="form-label" for="channel-url">Base URL</label><input id="channel-url" v-model="channel.baseUrl" class="text-input" type="url" placeholder="https://api.example.com/v1" />
<label class="form-label" for="channel-credential">凭据类型</label><select id="channel-credential" v-model="channel.credentialType" class="text-input"><option value="api-key">API Key</option><option value="bearer">Bearer Token</option><option value="access-token">Access Token</option><option value="none">不使用凭据</option></select>
<label class="form-label" for="channel-secret">{{ editingId ? '新凭据(留空保留原值)' : '凭据' }}</label><input id="channel-secret" v-model="channel.credentialSecret" class="text-input" type="password" autocomplete="new-password" :disabled="channel.credentialType === 'none'" />
<label class="form-label" for="channel-note">备注</label><textarea id="channel-note" v-model="channel.description" class="text-input" />
</template>
<template v-else-if="editor === 'model'">
<label class="form-label" for="logical-name">模型名称</label><input id="logical-name" v-model="model.publicName" class="text-input" required maxlength="160" />
<label class="form-label" for="logical-key">统一模型标识</label><input id="logical-key" v-model="model.modelKey" class="text-input" maxlength="160" />
<label class="form-label" for="logical-type">模型类型</label><select id="logical-type" v-model="model.type" class="text-input"><option value="text">文本</option><option value="code">代码</option><option value="multimodal">多模态</option><option value="image">图像</option><option value="audio">音频</option><option value="video">视频</option><option value="embedding">向量</option><option value="3d">3D</option></select>
<label class="form-label" for="logical-mode">调用模式</label><select id="logical-mode" v-model="model.mode" class="text-input"><option value="sync">同步</option><option value="stream">流式</option><option value="async">异步</option></select>
<label class="form-label" for="logical-input">输入类型</label><input id="logical-input" v-model="model.inputTypes" class="text-input" />
<label class="form-label" for="logical-output">输出类型</label><input id="logical-output" v-model="model.outputTypes" class="text-input" />
<label class="form-label" for="logical-description">模型说明</label><textarea id="logical-description" v-model="model.description" class="text-input" />
</template>
<template v-else>
<label class="form-label" for="group-model">所属模型</label><select id="group-model" v-model="group.logicalModelId" class="text-input" required><option v-for="item in models" :key="item.id" :value="item.id">{{ item.publicName }}</option></select>
<label class="form-label" for="group-name">分组名称</label><input id="group-name" v-model="group.sourceLabel" class="text-input" required maxlength="160" />
<label class="form-label" for="group-channel">渠道</label><select id="group-channel" v-model="group.providerId" class="text-input" required><option value="" disabled>请选择渠道</option><option v-for="item in channels" :key="item.id" :value="item.id">{{ item.name }}{{ item.status === 'disabled' ? '(已停用)' : '' }}</option></select>
<label class="form-label" for="group-upstream">上游模型标识</label><input id="group-upstream" v-model="group.upstreamModel" class="text-input" required maxlength="160" />
<div class="modal-form-grid"><label><span class="form-label">输入价格</span><input v-model="group.input" class="text-input" type="number" min="0" step="any" /></label><label><span class="form-label">输出价格</span><input v-model="group.output" class="text-input" type="number" min="0" step="any" /></label></div>
<label class="form-label" for="group-unit">价格单位</label><input id="group-unit" v-model="group.unit" class="text-input" required />
<div class="modal-form-grid"><label><span class="form-label">优先级</span><input v-model="group.priority" class="text-input" type="number" min="0" step="1" required /></label><label><span class="form-label">并发上限</span><input v-model="group.maxConcurrency" class="text-input" type="number" min="1" step="1" required /></label></div>
</template>
</form>
<template #footer><button class="button secondary" :disabled="saving" @click="editor = ''">取消</button><button class="button primary" form="catalog-editor" type="submit" :disabled="saving">{{ saving ? '保存中…' : '保存' }}</button></template>
</UiModal>
</template>
<style scoped>
.catalog-secondary { display: block; color: #687378; font-size: 12px; margin-top: 5px; overflow-wrap: anywhere; }
.catalog-search { max-width: 420px; }
.catalog-url { max-width: 320px; overflow-wrap: anywhere; }
.catalog-toggle { display: inline-flex; align-items: center; gap: 7px; white-space: nowrap; }
.model-definition-section { padding: 20px 0; border-bottom: 1px solid #dce3e5; }
.model-definition-section h3 { margin: 0; font-size: 18px; }
.model-definition-section .panel-header { padding: 0 0 16px; flex-wrap: wrap; gap: 12px; }
.responsive-table code { overflow-wrap: anywhere; }
@media(max-width: 700px) { .heading-actions { flex-wrap: wrap; } }
</style>
@@ -0,0 +1,48 @@
<script setup lang="ts">
import { computed, ref } from 'vue'
import type { ModelItem } from '../types'
const props = defineProps<{ groups: ModelItem[]; modelValue: string[]; disabled?: boolean }>()
const emit = defineEmits<{ 'update:modelValue': [ids: string[]] }>()
const selectedModel = ref('')
const models = computed(() => [...new Map(props.groups.map(group => [group.logicalModelId || group.id, group])).values()])
const visibleGroups = computed(() => props.groups.filter(group => (group.logicalModelId || group.id) === selectedModel.value))
const unavailable = computed(() => props.modelValue.filter(id => !props.groups.some(group => group.id === id)))
function toggle(id: string, checked: boolean) {
emit('update:modelValue', checked ? [...new Set([...props.modelValue, id])] : props.modelValue.filter(value => value !== id))
}
function count(id: string) { return props.groups.filter(group => (group.logicalModelId || group.id) === id && props.modelValue.includes(group.id)).length }
</script>
<template>
<div class="group-permissions">
<label for="permission-model">模型</label>
<select id="permission-model" v-model="selectedModel" class="text-input" :disabled="disabled">
<option value="" disabled>请选择模型</option>
<option v-for="model in models" :key="model.logicalModelId || model.id" :value="model.logicalModelId || model.id">{{ model.name }} (已选 {{ count(model.logicalModelId || model.id) }} 组)</option>
</select>
<fieldset :disabled="disabled"><legend>可调用分组</legend>
<label v-for="group in visibleGroups" :key="group.id" class="group-option">
<input type="checkbox" :checked="modelValue.includes(group.id)" @change="toggle(group.id, ($event.target as HTMLInputElement).checked)" />
<span><strong>{{ group.sourceLabel || '默认分组' }}</strong><small>{{ group.provider }} · {{ group.mode }}</small><code>{{ group.id }}</code></span>
</label>
<p v-if="!selectedModel">尚未选择模型</p>
<p v-else-if="!visibleGroups.length">该模型暂无可用分组</p>
</fieldset>
<fieldset v-if="unavailable.length" :disabled="disabled"><legend>暂不可用的既有授权</legend>
<label v-for="id in unavailable" :key="id" class="group-option"><input type="checkbox" checked @change="toggle(id, false)" /><code>{{ id }}</code></label>
</fieldset>
<footer><span>已选 {{ modelValue.length }} 个分组</span><button class="text-link" :disabled="disabled || !modelValue.length" @click="emit('update:modelValue', [])">清空授权</button></footer>
</div>
</template>
<style scoped>
.group-permissions { display: grid; gap: 12px; min-width: 0; }
fieldset { border: 0; padding: 0; margin: 0; display: grid; gap: 8px; }
legend { margin-bottom: 8px; font-weight: 600; font-size: 13px; }
.group-option { display: flex; align-items: center; gap: 12px; border-bottom: 1px solid #e5e7eb; padding: 12px 0; cursor: pointer; }
.group-option span { display: grid; gap: 5px; min-width: 0; }
.group-option small, p { color: #6b7280; font-size: 12px; }
code { font-size: 11px; overflow-wrap: anywhere; }
footer { display: flex; justify-content: space-between; align-items: center; font-size: 13px; }
</style>
+1 -1
View File
@@ -8,7 +8,7 @@ defineEmits<{ close: [] }>()
<template> <template>
<div class="slide-overlay" @click="$emit('close')"></div> <div class="slide-overlay" @click="$emit('close')"></div>
<aside class="slide-panel"> <aside class="slide-panel">
<header><div><span>{{ eyebrow ?? 'DETAILS' }}</span><h2>{{ title }}</h2></div><button class="icon-button" @click="$emit('close')"><X :size="18" /></button></header> <header><div><span>{{ eyebrow ?? 'DETAILS' }}</span><h2>{{ title }}</h2></div><button class="icon-button" aria-label="关闭详情" title="关闭" @click="$emit('close')"><X :size="18" /></button></header>
<div class="slide-content"><slot /></div> <div class="slide-content"><slot /></div>
<footer><slot name="footer" /></footer> <footer><slot name="footer" /></footer>
</aside> </aside>
+2 -2
View File
@@ -7,8 +7,8 @@ defineEmits<{ close: [] }>()
<template> <template>
<div class="modal-overlay" @click.self="$emit('close')"> <div class="modal-overlay" @click.self="$emit('close')">
<section class="modal"> <section class="modal" role="dialog" aria-modal="true" :aria-label="title">
<header><div><span>{{ eyebrow ?? 'MOYI CONSOLE' }}</span><h2>{{ title }}</h2></div><button class="icon-button" @click="$emit('close')"><X :size="18" /></button></header> <header><div><span>{{ eyebrow ?? 'MOYI CONSOLE' }}</span><h2>{{ title }}</h2></div><button class="icon-button" aria-label="关闭弹窗" title="关闭" @click="$emit('close')"><X :size="18" /></button></header>
<div class="modal-body"><slot /></div> <div class="modal-body"><slot /></div>
<footer><slot name="footer" /></footer> <footer><slot name="footer" /></footer>
</section> </section>
+2 -2
View File
@@ -46,8 +46,8 @@ export const adminNavigation: NavGroup[] = [
label: '资源运营', label: '资源运营',
items: [ items: [
{ id: 'admin-users', label: '用户与额度', icon: Users }, { id: 'admin-users', label: '用户与额度', icon: Users },
{ id: 'admin-models', label: '模型与供应商', icon: Boxes }, { id: 'admin-models', label: '模型与分组', icon: Boxes },
{ id: 'admin-routing', label: '渠道与路由', icon: Network }, { id: 'admin-routing', label: '渠道管理', icon: Network },
{ id: 'admin-capacity', label: '并发与队列', icon: Gauge }, { id: 'admin-capacity', label: '并发与队列', icon: Gauge },
{ id: 'admin-billing', label: '计费配置', icon: CircleDollarSign }, { id: 'admin-billing', label: '计费配置', icon: CircleDollarSign },
{ id: 'admin-usage', label: '模型调用记录', icon: ScrollText }, { id: 'admin-usage', label: '模型调用记录', icon: ScrollText },
+13
View File
@@ -13,6 +13,7 @@ export interface AuthUser {
export interface RegisterInput { export interface RegisterInput {
invitationCode: string invitationCode: string
verificationCode: string
account: string account: string
password: string password: string
displayName?: string displayName?: string
@@ -24,6 +25,8 @@ export interface LoginInput {
} }
export interface AuthClient { export interface AuthClient {
verificationChannels(): Promise<{ email: boolean; phone: boolean }>
sendVerificationCode(account: string, invitationCode: string): Promise<{ retryAfterSeconds: number }>
health(): Promise<{ status: 'ok'; service: string; capabilities: { verificationCode: boolean; passwordReset: boolean } }> health(): Promise<{ status: 'ok'; service: string; capabilities: { verificationCode: boolean; passwordReset: boolean } }>
login(input: LoginInput): Promise<AuthUser> login(input: LoginInput): Promise<AuthUser>
register(input: RegisterInput): Promise<AuthUser> register(input: RegisterInput): Promise<AuthUser>
@@ -34,6 +37,16 @@ export interface AuthClient {
class HttpAuthClient implements AuthClient { class HttpAuthClient implements AuthClient {
constructor(private readonly baseUrl: string) {} constructor(private readonly baseUrl: string) {}
verificationChannels() {
return this.request<{ email: boolean; phone: boolean }>('/api/auth/verification')
}
sendVerificationCode(account: string, invitationCode: string) {
return this.request<{ retryAfterSeconds: number }>('/api/auth/verification', {
method: 'POST', body: JSON.stringify({ account, invitationCode }),
})
}
async health() { async health() {
return this.request<{ status: 'ok'; service: string; capabilities: { verificationCode: boolean; passwordReset: boolean } }>('/health') return this.request<{ status: 'ok'; service: string; capabilities: { verificationCode: boolean; passwordReset: boolean } }>('/health')
} }
+53 -2
View File
@@ -16,6 +16,7 @@ export interface CatalogProvider {
export interface CatalogModel { export interface CatalogModel {
id: string id: string
logicalModelId: string
providerId: string providerId: string
modelKey?: string modelKey?: string
sourceLabel?: string sourceLabel?: string
@@ -33,6 +34,28 @@ export interface CatalogModel {
status: 'active' | 'disabled' status: 'active' | 'disabled'
} }
export interface LogicalModel {
id: string
publicName: string
modelKey?: string
type: CatalogModelType
mode: CatalogCallMode
description: string
inputTypes: string[]
outputTypes: string[]
status: 'active' | 'disabled'
}
export interface WalletEntry {
id: string
amount: number
balanceAfter: number
currency: 'CNY'
reason: string
createdAt: string
actor: string
}
export interface CatalogProject { export interface CatalogProject {
id: string id: string
ownerUserId: string ownerUserId: string
@@ -180,7 +203,7 @@ class HttpCatalogClient {
constructor(private readonly baseUrl: string) {} constructor(private readonly baseUrl: string) {}
async listModels() { async listModels() {
return this.request<{ providers: CatalogProvider[]; models: CatalogModel[] }>('/api/models') return this.request<{ providers: CatalogProvider[]; models: CatalogModel[]; logicalModels: LogicalModel[] }>('/api/models')
} }
async listProjects() { async listProjects() {
@@ -251,7 +274,7 @@ class HttpCatalogClient {
} }
async listAdminModels() { async listAdminModels() {
return this.request<{ models: CatalogModel[] }>('/api/admin/models') return this.request<{ models: CatalogModel[]; logicalModels: LogicalModel[] }>('/api/admin/models')
} }
async listAdminUsage(filters: { q?: string; keyId?: string; modelId?: string; status?: string; eventKind?: string; page?: number; size?: number } = {}) { async listAdminUsage(filters: { q?: string; keyId?: string; modelId?: string; status?: string; eventKind?: string; page?: number; size?: number } = {}) {
@@ -286,6 +309,22 @@ class HttpCatalogClient {
return this.request<{ users: AdminCatalogUser[] }>('/api/admin/users') return this.request<{ users: AdminCatalogUser[] }>('/api/admin/users')
} }
async createAdminUser(input: { account: string; displayName: string; password: string }) {
return this.request<{ user: AdminCatalogUser }>('/api/admin/users', { method: 'POST', body: JSON.stringify(input) })
}
async listWallets() {
return this.request<{ wallets: Array<{ userId: string; balance: number }> }>('/api/admin/wallets')
}
async walletEntries(userId: string) {
return this.request<{ entries: WalletEntry[] }>(`/api/admin/users/${encodeURIComponent(userId)}/wallet`)
}
async grantCredit(userId: string, input: { requestId: string; amount: string; reason: string }) {
return this.request<{ id: string; balance: number; currency: 'CNY' }>(`/api/admin/users/${encodeURIComponent(userId)}/wallet/grants`, { method: 'POST', body: JSON.stringify(input) })
}
async changeUserRole(id: string, role: 'user' | 'admin') { async changeUserRole(id: string, role: 'user' | 'admin') {
return this.request<{ user: AdminCatalogUser }>(`/api/admin/users/${encodeURIComponent(id)}/role`, { return this.request<{ user: AdminCatalogUser }>(`/api/admin/users/${encodeURIComponent(id)}/role`, {
method: 'POST', body: JSON.stringify({ role }), method: 'POST', body: JSON.stringify({ role }),
@@ -312,6 +351,18 @@ class HttpCatalogClient {
return this.request<{ provider: CatalogProvider }>('/api/admin/providers', { method: 'POST', body: JSON.stringify(input) }) return this.request<{ provider: CatalogProvider }>('/api/admin/providers', { method: 'POST', body: JSON.stringify(input) })
} }
async updateAdminProvider(id: string, input: Partial<CatalogProvider> & { credentialSecret?: string }) {
return this.request<{ provider: CatalogProvider }>(`/api/admin/providers/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(input) })
}
async saveDefinition(id: string | undefined, input: Partial<LogicalModel>) {
return this.request<{ model: LogicalModel }>(`/api/admin/model-definitions${id ? `/${encodeURIComponent(id)}` : ''}`, { method: id ? 'PATCH' : 'POST', body: JSON.stringify(input) })
}
async saveGroup(id: string | undefined, input: Partial<CatalogModel>) {
return this.request<{ model: CatalogModel }>(`/api/admin/models${id ? `/${encodeURIComponent(id)}` : ''}`, { method: id ? 'PATCH' : 'POST', body: JSON.stringify(input) })
}
async createAdminModel(input: { providerId: string; publicName: string; upstreamModel: string; modelKey?: string; sourceLabel?: string; type: CatalogModelType; mode: CatalogCallMode; description?: string; inputTypes?: string[]; outputTypes?: string[]; pricing?: { input?: number; output?: number; unit?: string }; priority?: number; maxConcurrency?: number }) { async createAdminModel(input: { providerId: string; publicName: string; upstreamModel: string; modelKey?: string; sourceLabel?: string; type: CatalogModelType; mode: CatalogCallMode; description?: string; inputTypes?: string[]; outputTypes?: string[]; pricing?: { input?: number; output?: number; unit?: string }; priority?: number; maxConcurrency?: number }) {
return this.request<{ model: CatalogModel }>('/api/admin/models', { method: 'POST', body: JSON.stringify(input) }) return this.request<{ model: CatalogModel }>('/api/admin/models', { method: 'POST', body: JSON.stringify(input) })
} }
+1
View File
@@ -19,6 +19,7 @@ export interface NavGroup {
} }
export interface ModelItem { export interface ModelItem {
logicalModelId?: string
id: string id: string
name: string name: string
provider: string provider: string
+9 -205
View File
@@ -31,12 +31,13 @@ import {
Users, Users,
WalletCards, WalletCards,
} from 'lucide-vue-next' } from 'lucide-vue-next'
import type { AdminUser, ModelItem, ProviderItem, RouteItem } from '../types' import type { AdminUser, ModelItem, ProviderItem } from '../types'
import { catalogClient, type AdminAuditEvent, type CatalogModel, type CatalogProvider, type UsageAuditRecord } from '../services/catalog' import { catalogClient, type AdminAuditEvent, type CatalogModel, type CatalogProvider, type UsageAuditRecord } from '../services/catalog'
import { copyText } from '../services/clipboard'
import type { AuthUser } from '../services/auth' import type { AuthUser } from '../services/auth'
import SlidePanel from '../components/SlidePanel.vue' import SlidePanel from '../components/SlidePanel.vue'
import UiModal from '../components/UiModal.vue' import UiModal from '../components/UiModal.vue'
import CatalogAdmin from '../components/CatalogAdmin.vue'
import AccountAdmin from '../components/AccountAdmin.vue'
const props = defineProps<{ view: string; currentUser?: AuthUser }>() const props = defineProps<{ view: string; currentUser?: AuthUser }>()
const emit = defineEmits<{ navigate: [view: string]; notify: [message: string] }>() const emit = defineEmits<{ navigate: [view: string]; notify: [message: string] }>()
@@ -44,43 +45,7 @@ const emit = defineEmits<{ navigate: [view: string]; notify: [message: string] }
const users = ref<AdminUser[]>([]) const users = ref<AdminUser[]>([])
const providers = ref<ProviderItem[]>([]) const providers = ref<ProviderItem[]>([])
const models = ref<ModelItem[]>([]) const models = ref<ModelItem[]>([])
const routes = ref<RouteItem[]>([])
const catalogConnected = ref(false) const catalogConnected = ref(false)
const userQuery = ref('')
const userStatus = ref('全部')
const selectedUser = ref<AdminUser | null>(null)
const roleTarget = ref<AdminUser | null>(null)
const roleChoice = ref<'user' | 'admin'>('user')
const savingRole = ref(false)
const canEditRole = computed(() => props.currentUser?.role === 'super_admin' && selectedUser.value?.roleCode !== 'super_admin' && selectedUser.value?.id !== props.currentUser.id)
const invitationOpen = ref(false)
const inviteLabel = ref('')
const createdInviteCode = ref('')
const providerOpen = ref(false)
const providerCode = ref('')
const providerName = ref('')
const providerProtocol = ref<CatalogProvider['protocol']>('http')
const providerSourceType = ref<CatalogProvider['sourceType']>('official')
const providerBaseUrl = ref('')
const providerCredentialType = ref<NonNullable<CatalogProvider['credentialType']>>('none')
const providerCredentialSecret = ref('')
const providerDescription = ref('')
const modelOpen = ref(false)
const modelProviderId = ref('')
const modelPublicName = ref('')
const modelUpstreamModel = ref('')
const modelKey = ref('')
const modelSourceLabel = ref('')
const modelType = ref<CatalogModel['type']>('multimodal')
const modelMode = ref<CatalogModel['mode']>('sync')
const modelDescription = ref('')
const modelInputTypes = ref('text')
const modelOutputTypes = ref('text')
const modelInputPrice = ref('')
const modelOutputPrice = ref('')
const modelPriceUnit = ref('1K tokens')
const modelPriority = ref('100')
const modelMaxConcurrency = ref('')
const auditQuery = ref('') const auditQuery = ref('')
const usageRecords = ref<UsageAuditRecord[]>([]) const usageRecords = ref<UsageAuditRecord[]>([])
const usageQuery = ref('') const usageQuery = ref('')
@@ -181,11 +146,6 @@ function formatUsagePayload(value: unknown) {
try { return JSON.stringify(value, null, 2) } catch { return String(value) } try { return JSON.stringify(value, null, 2) } catch { return String(value) }
} }
const filteredUsers = computed(() => {
const query = userQuery.value.trim().toLowerCase()
return users.value.filter((user) => (userStatus.value === '全部' || user.status === userStatus.value) && (!query || `${user.name} ${user.email} ${user.id}`.toLowerCase().includes(query)))
})
const queueGroups: Array<{ name: string; type: string; running: number; limit: number; queued: number; wait: string; status: string }> = [] const queueGroups: Array<{ name: string; type: string; running: number; limit: number; queued: number; wait: string; status: string }> = []
const pricing: Array<{ model: string; unit: string; base: string; output: string; rule: string; status: string }> = [] const pricing: Array<{ model: string; unit: string; base: string; output: string; rule: string; status: string }> = []
const auditEvents = ref<Array<{ time: string; actor: string; action: string; target: string; source: string; level: string }>>([]) const auditEvents = ref<Array<{ time: string; actor: string; action: string; target: string; source: string; level: string }>>([])
@@ -194,134 +154,14 @@ const filteredAudits = computed(() => {
return query ? auditEvents.value.filter((event) => `${event.actor} ${event.action} ${event.target}`.toLowerCase().includes(query)) : auditEvents.value return query ? auditEvents.value.filter((event) => `${event.actor} ${event.action} ${event.target}`.toLowerCase().includes(query)) : auditEvents.value
}) })
async function createInvitation() {
if (!catalogConnected.value) return emit('notify', 'Control Plane 未连接,无法创建真实邀请码')
try {
const result = await catalogClient.createAdminInvitation({ label: inviteLabel.value.trim() || undefined, maxUses: 1 })
createdInviteCode.value = result.code
inviteLabel.value = ''
invitationOpen.value = false
emit('notify', '邀请码已创建,请在弹窗中安全保存完整代码')
} catch (error) {
emit('notify', error instanceof Error ? error.message : '创建邀请码失败')
}
}
function openCredit(user?: AdminUser) {
if (user) selectedUser.value = user
emit('notify', '额度账本接口尚未接入,当前不会伪造发放结果')
}
async function copyUserId(id: string) {
const result = await copyText(id)
emit('notify', result === 'failed' ? '用户 ID 复制失败,请手动复制' : result === 'verified' ? '用户 ID 已复制并校验' : '用户 ID 已写入剪贴板')
}
function mapUser(user: { id: string; account: string; displayName: string; role: 'user' | 'admin' | 'super_admin'; status: 'active' | 'disabled'; lastLoginAt?: string }): AdminUser { function mapUser(user: { id: string; account: string; displayName: string; role: 'user' | 'admin' | 'super_admin'; status: 'active' | 'disabled'; lastLoginAt?: string }): AdminUser {
return { id: user.id, name: user.displayName, email: user.account, role: user.role === 'super_admin' ? '超级管理员' : user.role === 'admin' ? '平台管理员' : '普通用户', roleCode: user.role, status: user.status === 'active' ? '正常' : '已停用' } return { id: user.id, name: user.displayName, email: user.account, role: user.role === 'super_admin' ? '超级管理员' : user.role === 'admin' ? '平台管理员' : '普通用户', roleCode: user.role, status: user.status === 'active' ? '正常' : '已停用' }
} }
function openRoleEditor() {
if (!selectedUser.value || !canEditRole.value) return
roleTarget.value = selectedUser.value
roleChoice.value = selectedUser.value.roleCode === 'admin' ? 'admin' : 'user'
selectedUser.value = null
}
async function saveRole() {
if (!roleTarget.value || savingRole.value) return
savingRole.value = true
try {
const result = await catalogClient.changeUserRole(roleTarget.value.id, roleChoice.value)
const updated = mapUser(result.user)
users.value = users.value.map((user) => user.id === updated.id ? updated : user)
roleTarget.value = null
selectedUser.value = updated
emit('notify', '用户角色已更新')
} catch (error) {
emit('notify', error instanceof Error ? error.message : '角色更新失败')
} finally {
savingRole.value = false
}
}
function mapAudit(event: AdminAuditEvent) { function mapAudit(event: AdminAuditEvent) {
return { time: new Date(event.createdAt).toLocaleString('zh-CN'), actor: event.actorUserId || '系统', action: event.eventType, target: event.targetId || event.targetType || '--', source: event.ipAddress || '--', level: event.eventType.includes('failed') ? '风险' : '普通' } return { time: new Date(event.createdAt).toLocaleString('zh-CN'), actor: event.actorUserId || '系统', action: event.eventType, target: event.targetId || event.targetType || '--', source: event.ipAddress || '--', level: event.eventType.includes('failed') ? '风险' : '普通' }
} }
async function addProvider() {
providerCode.value = ''
providerName.value = ''
providerProtocol.value = 'http'
providerSourceType.value = 'official'
providerBaseUrl.value = ''
providerCredentialType.value = 'none'
providerCredentialSecret.value = ''
providerDescription.value = ''
providerOpen.value = true
}
async function createProvider() {
const code = providerCode.value.trim()
const name = providerName.value.trim()
if (!code || !name) return emit('notify', '请填写供应商 code 和名称')
if (!catalogConnected.value) return emit('notify', 'Control Plane 未连接,无法保存供应商')
try {
await catalogClient.createAdminProvider({ code, name, protocol: providerProtocol.value, sourceType: providerSourceType.value, baseUrl: providerBaseUrl.value.trim() || undefined, credentialType: providerCredentialType.value, credentialSecret: providerCredentialSecret.value.trim() || undefined, description: providerDescription.value.trim() || undefined })
const result = await catalogClient.listAdminProviders()
const modelsResult = await catalogClient.listAdminModels()
providers.value = mapProviders(result.providers, modelsResult.models)
providerOpen.value = false
emit('notify', '供应商已登记')
} catch (error) {
emit('notify', error instanceof Error ? error.message : '登记供应商失败')
}
}
async function addModel() {
if (!catalogConnected.value) return emit('notify', 'Control Plane 未连接,无法保存模型')
const provider = providers.value[0]
if (!provider) return emit('notify', '请先登记供应商')
modelProviderId.value = provider.id
modelPublicName.value = ''
modelUpstreamModel.value = ''
modelKey.value = ''
modelSourceLabel.value = ''
modelType.value = 'multimodal'
modelMode.value = 'sync'
modelDescription.value = ''
modelInputTypes.value = 'text'
modelOutputTypes.value = 'text'
modelInputPrice.value = ''
modelOutputPrice.value = ''
modelPriceUnit.value = '1K tokens'
modelPriority.value = '100'
modelMaxConcurrency.value = ''
modelOpen.value = true
}
async function createModel() {
const publicName = modelPublicName.value.trim()
const upstreamModel = modelUpstreamModel.value.trim()
if (!publicName || !upstreamModel) return emit('notify', '请填写统一模型名称和上游模型标识')
if (!catalogConnected.value) return emit('notify', 'Control Plane 未连接,无法保存模型')
try {
const inputPrice = modelInputPrice.value.trim() ? Number(modelInputPrice.value) : undefined
const outputPrice = modelOutputPrice.value.trim() ? Number(modelOutputPrice.value) : undefined
const priority = Number(modelPriority.value)
const maxConcurrency = modelMaxConcurrency.value.trim() ? Number(modelMaxConcurrency.value) : undefined
if ([inputPrice, outputPrice, priority, maxConcurrency].some((value) => value !== undefined && !Number.isFinite(value))) return emit('notify', '价格、优先级和并发数必须是有效数字')
await catalogClient.createAdminModel({ providerId: modelProviderId.value, publicName, upstreamModel, modelKey: modelKey.value.trim() || undefined, sourceLabel: modelSourceLabel.value.trim() || undefined, type: modelType.value, mode: modelMode.value, inputTypes: modelInputTypes.value.split(',').map((value) => value.trim()).filter(Boolean), outputTypes: modelOutputTypes.value.split(',').map((value) => value.trim()).filter(Boolean), description: modelDescription.value.trim() || undefined, pricing: inputPrice !== undefined || outputPrice !== undefined ? { ...(inputPrice !== undefined ? { input: inputPrice } : {}), ...(outputPrice !== undefined ? { output: outputPrice } : {}), unit: modelPriceUnit.value } : undefined, priority, maxConcurrency })
const [providerResult, modelResult] = await Promise.all([catalogClient.listAdminProviders(), catalogClient.listAdminModels()])
providers.value = mapProviders(providerResult.providers, modelResult.models)
models.value = mapModels(modelResult.models, providerResult.providers)
modelOpen.value = false
emit('notify', '模型已加入统一目录')
} catch (error) {
emit('notify', error instanceof Error ? error.message : '登记模型失败')
}
}
function mapProviders(items: CatalogProvider[], modelItems: CatalogModel[]): ProviderItem[] { function mapProviders(items: CatalogProvider[], modelItems: CatalogModel[]): ProviderItem[] {
return items.map((provider) => ({ return items.map((provider) => ({
id: provider.id, id: provider.id,
@@ -372,29 +212,12 @@ function mapModels(items: CatalogModel[], providersList: CatalogProvider[]): Mod
<template v-if="view === 'admin-overview'"> <template v-if="view === 'admin-overview'">
<section class="page-heading compact"><div><span>ADMIN OVERVIEW</span><h1>管理总览</h1><p>掌握平台供给、用户、容量和风险状态。</p></div><div class="heading-actions"><span class="health-badge"><i></i>核心服务正常</span><button class="button secondary" @click="emit('notify', '数据已刷新')"><Activity :size="16" />刷新数据</button></div></section> <section class="page-heading compact"><div><span>ADMIN OVERVIEW</span><h1>管理总览</h1><p>掌握平台供给、用户、容量和风险状态。</p></div><div class="heading-actions"><span class="health-badge"><i></i>核心服务正常</span><button class="button secondary" @click="emit('notify', '数据已刷新')"><Activity :size="16" />刷新数据</button></div></section>
<section class="metric-grid"><article class="metric-card"><span class="icon-tile violet"><Users :size="18" /></span><div><small>用户总数</small><strong>{{ users.length }}</strong><em>来自认证服务</em></div></article><article class="metric-card"><span class="icon-tile cyan"><Cloud :size="18" /></span><div><small>在线模型</small><strong>{{ models.length }}</strong><em>{{ providers.length }} 个供应商</em></div></article><article class="metric-card"><span class="icon-tile orange"><Gauge :size="18" /></span><div><small>等待任务</small><strong>--</strong><em>容量监控尚未接入</em></div></article><article class="metric-card"><span class="icon-tile green"><CircleDollarSign :size="18" /></span><div><small>今日额度消耗</small><strong>--</strong><em>计费账本尚未接入</em></div></article></section> <section class="metric-grid"><article class="metric-card"><span class="icon-tile violet"><Users :size="18" /></span><div><small>用户总数</small><strong>{{ users.length }}</strong><em>来自认证服务</em></div></article><article class="metric-card"><span class="icon-tile cyan"><Cloud :size="18" /></span><div><small>在线模型</small><strong>{{ models.length }}</strong><em>{{ providers.length }} 个供应商</em></div></article><article class="metric-card"><span class="icon-tile orange"><Gauge :size="18" /></span><div><small>等待任务</small><strong>--</strong><em>容量监控尚未接入</em></div></article><article class="metric-card"><span class="icon-tile green"><CircleDollarSign :size="18" /></span><div><small>今日额度消耗</small><strong>--</strong><em>计费账本尚未接入</em></div></article></section>
<section class="two-column equal"><article class="panel chart-panel"><header class="panel-header"><div><span>PLATFORM TRAFFIC</span><h3>平台请求趋势</h3></div><span class="select-button static">最近 7 天</span></header><div class="empty-state compact"><BarChart3 :size="22" /><strong>暂无平台流量数据</strong><span>接入调用记录后会在这里形成趋势</span></div></article><article class="panel health-panel"><header class="panel-header"><div><span>GATEWAY HEALTH</span><h3>模型供给状态</h3></div><button class="text-link" @click="emit('navigate', 'admin-models')">管理供应商<ArrowRight :size="14" /></button></header><div v-if="providers.length" class="health-list"><div v-for="provider in providers.slice(0, 3)" :key="provider.id"><span class="provider-mark">{{ provider.name.slice(0, 1) }}</span><p><strong>{{ provider.name }}</strong><small>{{ provider.capability }} · {{ provider.latency }}</small></p><b>{{ provider.successRate }}</b><span class="status-chip" :class="provider.status === '健康' ? 'success' : 'warning'"><i></i>{{ provider.status }}</span></div></div><div v-else class="empty-state compact"><Cloud :size="22" /><strong>暂无供应商</strong><span>由管理员登记上游渠道后显示</span></div></article></section> <section class="two-column equal"><article class="panel chart-panel"><header class="panel-header"><div><span>PLATFORM TRAFFIC</span><h3>平台请求趋势</h3></div><span class="select-button static">最近 7 天</span></header><div class="empty-state compact"><BarChart3 :size="22" /><strong>暂无平台流量数据</strong><span>接入调用记录后会在这里形成趋势</span></div></article><article class="panel health-panel"><header class="panel-header"><div><span>GATEWAY HEALTH</span><h3>模型供给状态</h3></div><button class="text-link" @click="emit('navigate', 'admin-routing')">管理渠道<ArrowRight :size="14" /></button></header><div v-if="providers.length" class="health-list"><div v-for="provider in providers.slice(0, 3)" :key="provider.id"><span class="provider-mark">{{ provider.name.slice(0, 1) }}</span><p><strong>{{ provider.name }}</strong><small>{{ provider.capability }} · {{ provider.latency }}</small></p><b>{{ provider.successRate }}</b><span class="status-chip" :class="provider.status === '健康' ? 'success' : 'warning'"><i></i>{{ provider.status }}</span></div></div><div v-else class="empty-state compact"><Cloud :size="22" /><strong>暂无供应商</strong><span>由管理员登记上游渠道后显示</span></div></article></section>
<section class="two-column narrow-left"><article class="panel quick-credit"><header class="panel-header"><div><span>CREDIT OPERATIONS</span><h3>额度分配</h3></div><ShieldCheck :size="18" /></header><p>额度账本接口尚未接入,当前仅保留操作入口和审计位置。</p><button class="button primary full" @click="emit('navigate', 'admin-users')"><Users :size="16" />查看用户</button></article><article class="panel activity-panel"><header class="panel-header"><div><span>RECENT EVENTS</span><h3>最近运营事件</h3></div><button class="text-link" @click="emit('navigate', 'admin-audit')">审计日志<ArrowRight :size="14" /></button></header><div v-if="auditEvents.length" class="activity-list"><div v-for="event in auditEvents.slice(0, 3)" :key="`${event.time}-${event.action}`"><span class="activity-dot cyan"><ShieldCheck :size="14" /></span><p><strong>{{ event.action }}</strong><small>{{ event.actor }} · {{ event.target }}</small></p><time>{{ event.time }}</time></div></div><div v-else class="empty-state compact"><ShieldCheck :size="22" /><strong>暂无运营事件</strong><span>真实管理操作发生后会显示审计记录</span></div></article></section> <section class="two-column narrow-left"><article class="panel quick-credit"><header class="panel-header"><div><span>CREDIT OPERATIONS</span><h3>额度分配</h3></div><ShieldCheck :size="18" /></header><p>人民币额度余额与发放流水</p><button class="button primary full" @click="emit('navigate', 'admin-users')"><Users :size="16" />查看用户</button></article><article class="panel activity-panel"><header class="panel-header"><div><span>RECENT EVENTS</span><h3>最近运营事件</h3></div><button class="text-link" @click="emit('navigate', 'admin-audit')">审计日志<ArrowRight :size="14" /></button></header><div v-if="auditEvents.length" class="activity-list"><div v-for="event in auditEvents.slice(0, 3)" :key="`${event.time}-${event.action}`"><span class="activity-dot cyan"><ShieldCheck :size="14" /></span><p><strong>{{ event.action }}</strong><small>{{ event.actor }} · {{ event.target }}</small></p><time>{{ event.time }}</time></div></div><div v-else class="empty-state compact"><ShieldCheck :size="22" /><strong>暂无运营事件</strong><span>真实管理操作发生后会显示审计记录</span></div></article></section>
</template> </template>
<template v-else-if="view === 'admin-users'"> <AccountAdmin v-else-if="view === 'admin-users'" :current-user="props.currentUser" @notify="emit('notify', $event)" />
<section class="page-heading"><div><span>USERS & CREDITS</span><h1>用户与额度</h1><p>管理邀请、账号状态、角色和内测额度。</p></div><button class="button primary" @click="invitationOpen = true"><Plus :size="16" />创建邀请</button></section> <CatalogAdmin v-else-if="view === 'admin-models' || view === 'admin-routing'" :section="view === 'admin-routing' ? 'channels' : 'models'" @notify="emit('notify', $event)" />
<section class="metric-grid"><article class="metric-card"><span class="icon-tile violet"><Users :size="18" /></span><div><small>用户总数</small><strong>{{ users.length }}</strong><em>来自认证服务</em></div></article><article class="metric-card"><span class="icon-tile cyan"><CheckCircle2 :size="18" /></span><div><small>正常用户</small><strong>{{ users.filter((user) => user.status === '正常').length }}</strong><em>按账号状态统计</em></div></article><article class="metric-card"><span class="icon-tile orange"><CircleDollarSign :size="18" /></span><div><small>已发放额度</small><strong>--</strong><em>额度账本尚未接入</em></div></article><article class="metric-card"><span class="icon-tile green"><Activity :size="18" /></span><div><small>今日活跃</small><strong>--</strong><em>活跃统计尚未接入</em></div></article></section>
<section class="panel table-card"><header class="panel-header table-toolbar"><div><span>USER DIRECTORY</span><h3>用户列表</h3></div><div class="toolbar-controls"><label class="search-input"><Search :size="16" /><input v-model="userQuery" placeholder="搜索姓名、邮箱或 ID" /></label><div class="tabs compact"><button v-for="status in ['全部','正常','待激活','已停用']" :key="status" :class="{ active: userStatus === status }" @click="userStatus = status">{{ status }}</button></div></div></header><div class="responsive-table"><table class="user-table"><thead><tr><th>用户</th><th>角色</th><th>额度余额</th><th>累计用量</th><th>最近活跃</th><th>状态</th></tr></thead><tbody><tr v-for="user in filteredUsers" :key="user.id" class="clickable" @click="selectedUser = user"><td><div class="entity-cell"><span class="avatar-small">{{ user.name.slice(0, 1) }}</span><div><strong>{{ user.name }}</strong><small>{{ user.email }} · {{ user.id }}</small></div></div></td><td><span class="role-tag">{{ user.role }}</span></td><td><strong class="mono">{{ user.balance === undefined ? '--' : `¥ ${user.balance.toFixed(2)}` }}</strong></td><td>{{ user.usage || '--' }}</td><td>{{ user.lastActive || '--' }}</td><td><span class="status-chip" :class="user.status === '正常' ? 'success' : user.status === '待激活' ? 'queued' : 'muted'"><i></i>{{ user.status }}</span></td></tr><tr v-if="!filteredUsers.length"><td colspan="6"><div class="empty-state compact"><Users :size="22" /><strong>暂无用户</strong><span>注册或邀请用户后会显示在这里</span></div></td></tr></tbody></table></div></section>
</template>
<template v-else-if="view === 'admin-models'">
<section class="page-heading"><div><span>MODELS & PROVIDERS</span><h1>模型与供应商</h1><p>配置统一模型目录、能力信息和上游渠道。</p></div><div class="heading-actions"><span class="admin-badge">{{ catalogConnected ? 'Control Plane 已连接' : 'Control Plane 未连接' }}</span><button class="button secondary" @click="addProvider"><Plus :size="16" />登记供应商</button><button class="button primary" @click="addModel"><Plus :size="16" />添加模型</button></div></section>
<section class="notice"><Cloud :size="19" /><div><strong>模型目录与上游渠道解耦</strong><p>用户只看到统一模型名称,供应商密钥、实际渠道和故障转移策略仅在管理端可见。</p></div></section>
<section class="panel table-card"><header class="panel-header"><div><span>PROVIDERS & CHANNELS</span><h3>供应商与渠道来源</h3></div><small>{{ providers.length }} 个来源 · 供应商密钥仅服务端保存</small></header><div class="responsive-table"><table><thead><tr><th>供应商 / 来源</th><th>类型</th><th>接入方式</th><th>服务地址</th><th>模型数</th><th>凭据</th><th>状态</th><th>启用</th></tr></thead><tbody><tr v-for="provider in providers" :key="provider.id"><td><div class="entity-cell"><span class="provider-mark">{{ provider.name.slice(0, 1) }}</span><div><strong>{{ provider.name }}</strong><div class="provider-meta"><span>{{ provider.code || provider.id }}</span><span v-if="provider.description">{{ provider.description }}</span></div></div></div></td><td><span class="provider-source-tag" :class="provider.sourceType">{{ provider.sourceType === 'official' ? '官方供应商' : provider.sourceType === 'relay' ? '中转站 / 渠道' : provider.sourceType === 'self-hosted' ? '自托管' : '自定义来源' }}</span></td><td>{{ provider.protocol === 'openai-compatible' ? 'OpenAI 兼容' : provider.protocol === 'sdk' ? 'SDK' : 'HTTP' }}</td><td><code class="provider-endpoint">{{ provider.baseUrl || '待配置' }}</code></td><td>{{ provider.models }}</td><td><span class="provider-credential">{{ provider.credentialType && provider.credentialType !== 'none' ? (provider.credentialMasked || '已配置') : '未配置' }}</span></td><td><span class="status-chip" :class="provider.status === '健康' ? 'success' : provider.status === '波动' ? 'warning' : 'muted'"><i></i>{{ provider.status }}</span></td><td><button class="switch" :class="{ active: provider.enabled }" @click="provider.enabled = !provider.enabled; emit('notify', `${provider.name} 已${provider.enabled ? '启用' : '停用'}`)"><span></span></button></td></tr></tbody></table></div></section>
<section class="section-title"><div><span>MODEL DIRECTORY</span><h2>统一模型目录</h2></div><button class="text-link" @click="emit('notify', '能力 Schema 文档将在详细设计阶段开放')">能力 Schema<ArrowRight :size="14" /></button></section>
<section class="admin-model-grid"><article v-for="model in models" :key="model.id"><div><span class="model-icon" :class="model.accent"><component :is="model.icon" :size="20" /></span><span class="status-chip success"><i></i>{{ model.availability }}</span></div><h3>{{ model.name }}</h3><p>{{ model.description || '暂无描述,建议补充能力与输入输出说明。' }}</p><div class="model-source-line"><span>来源:{{ model.provider }}</span><span v-if="model.sourceLabel">· {{ model.sourceLabel }}</span></div><div class="model-route-meta"><span>统一标识 <strong>{{ model.modelKey || model.id }}</strong></span><span>优先级 <strong>{{ model.priority ?? '—' }}</strong></span><span>并发 <strong>{{ model.maxConcurrency ?? '不限' }}</strong></span><span v-if="model.pricing">价格 <strong>{{ model.pricing.input ?? '—' }} / {{ model.pricing.output ?? '—' }}</strong> {{ model.pricing.unit || '' }}</span></div><footer><span>{{ model.type }}</span><span>{{ model.mode }}</span><span>{{ model.availability }}</span></footer></article><div v-if="!models.length" class="empty-state"><Boxes :size="24" /><strong>暂无模型</strong><span>添加模型目录项后会显示在这里</span></div></section>
</template>
<template v-else-if="view === 'admin-routing'">
<section class="page-heading"><div><span>CHANNEL ROUTING</span><h1>渠道与路由</h1><p>管理渠道优先级、故障转移和模型映射。</p></div><div class="heading-actions"><span class="health-badge offline"><i></i>路由监控未接入</span><button class="button secondary" @click="emit('notify', '路由模拟器将在真实策略接入后开放')"><SlidersHorizontal :size="16" />模拟路由</button></div></section>
<section class="routing-hero"><span class="icon-tile light"><Network :size="22" /></span><div><small>SMART ROUTING</small><h2>按质量、速度、价格和可用性分配请求</h2><p>路由策略将在配置真实供应商后启用。</p></div><div><strong>--</strong><span>路由成功率</span></div></section>
<section class="panel table-card"><header class="panel-header"><div><span>ROUTING POLICIES</span><h3>模型到渠道映射</h3></div><button class="text-link" @click="emit('notify', '批量编辑将在真实策略接入后开放')">批量编辑<ArrowRight :size="14" /></button></header><div class="responsive-table"><table class="routing-table"><thead><tr><th>模型</th><th>能力</th><th>主渠道</th><th>备用渠道</th><th>策略</th><th>健康</th><th>状态</th></tr></thead><tbody><tr v-for="route in routes" :key="route.id"><td><div class="stacked-cell"><strong>{{ route.model }}</strong><small>{{ route.id }}</small></div></td><td>{{ route.capability }}</td><td><strong>{{ route.primary }}</strong></td><td>{{ route.fallback }}</td><td><span class="role-tag">{{ route.policy }}</span></td><td><strong class="positive">{{ route.health }}</strong></td><td><button class="switch" disabled :class="{ active: route.enabled }" title="路由启停接口尚未接入"><span></span></button></td></tr><tr v-if="!routes.length"><td colspan="7"><div class="empty-state compact"><Network :size="22" /><strong>暂无路由策略</strong><span>配置模型与供应商后会显示映射关系</span></div></td></tr></tbody></table></div></section>
</template>
<template v-else-if="view === 'admin-capacity'"> <template v-else-if="view === 'admin-capacity'">
<section class="page-heading"><div><span>CAPACITY CONTROL</span><h1>并发与队列</h1><p>查看实时并发、排队状态和容量保护。</p></div><div class="heading-actions"><span class="admin-badge"><ShieldCheck :size="15" />保护策略未配置</span><button class="button secondary" @click="emit('notify', '队列保护接口尚未接入')">配置保护策略</button></div></section> <section class="page-heading"><div><span>CAPACITY CONTROL</span><h1>并发与队列</h1><p>查看实时并发、排队状态和容量保护。</p></div><div class="heading-actions"><span class="admin-badge"><ShieldCheck :size="15" />保护策略未配置</span><button class="button secondary" @click="emit('notify', '队列保护接口尚未接入')">配置保护策略</button></div></section>
@@ -405,7 +228,7 @@ function mapModels(items: CatalogModel[], providersList: CatalogProvider[]): Mod
<template v-else-if="view === 'admin-billing'"> <template v-else-if="view === 'admin-billing'">
<section class="page-heading"><div><span>BILLING OPERATIONS</span><h1>计费配置</h1><p>维护模型计费单位、价格和扣费规则。</p></div><button class="button secondary" @click="emit('notify', '真实充值和订单流程将在商业规则确认后开放')"><WalletCards :size="16" />支付能力预留</button></section> <section class="page-heading"><div><span>BILLING OPERATIONS</span><h1>计费配置</h1><p>维护模型计费单位、价格和扣费规则。</p></div><button class="button secondary" @click="emit('notify', '真实充值和订单流程将在商业规则确认后开放')"><WalletCards :size="16" />支付能力预留</button></section>
<section class="notice warning-notice"><AlertTriangle :size="19" /><div><strong>当前仍采用管理员发放额度</strong><p>充值、订单和退款尚未启用。下面的价格目录只用于验证计费结构,不会产生真实支付。</p></div></section> <section class="notice warning-notice"><AlertTriangle :size="19" /><div><strong>当前仍采用管理员发放额度</strong><p>充值、订单和退款尚未启用。下面的价格目录只用于验证计费结构,不会产生真实支付。</p></div></section>
<section class="metric-grid three"><article class="metric-card"><span class="icon-tile violet"><CircleDollarSign :size="18" /></span><div><small>本期额度发放</small><strong>--</strong><em>额度账本尚未接入</em></div></article><article class="metric-card"><span class="icon-tile cyan"><BarChart3 :size="18" /></span><div><small>本期实际消耗</small><strong>--</strong><em>计费规则尚未接入</em></div></article><article class="metric-card"><span class="icon-tile orange"><WalletCards :size="18" /></span><div><small>待对账流水</small><strong>--</strong><em>支付尚未开放</em></div></article></section> <section class="metric-grid three"><article class="metric-card"><span class="icon-tile violet"><CircleDollarSign :size="18" /></span><div><small>本期额度发放</small><strong>--</strong><em>见用户额度流水</em></div></article><article class="metric-card"><span class="icon-tile cyan"><BarChart3 :size="18" /></span><div><small>本期实际消耗</small><strong>--</strong><em>计费规则尚未接入</em></div></article><article class="metric-card"><span class="icon-tile orange"><WalletCards :size="18" /></span><div><small>待对账流水</small><strong>--</strong><em>支付尚未开放</em></div></article></section>
<section class="panel table-card"><header class="panel-header"><div><span>PRICE CATALOG</span><h3>模型计费规则</h3></div><button class="button secondary small" @click="emit('notify', '计费规则接口尚未接入')"><Plus :size="15" />添加规则</button></header><div class="responsive-table"><table><thead><tr><th>模型</th><th>计费单位</th><th>输入 / 基础</th><th>输出 / 结果</th><th>扣费规则</th><th>状态</th></tr></thead><tbody><tr v-if="!pricing.length"><td colspan="6"><div class="empty-state compact"><CircleDollarSign :size="22" /><strong>暂无计费规则</strong><span>商业规则确认后由管理员配置</span></div></td></tr></tbody></table></div></section> <section class="panel table-card"><header class="panel-header"><div><span>PRICE CATALOG</span><h3>模型计费规则</h3></div><button class="button secondary small" @click="emit('notify', '计费规则接口尚未接入')"><Plus :size="15" />添加规则</button></header><div class="responsive-table"><table><thead><tr><th>模型</th><th>计费单位</th><th>输入 / 基础</th><th>输出 / 结果</th><th>扣费规则</th><th>状态</th></tr></thead><tbody><tr v-if="!pricing.length"><td colspan="6"><div class="empty-state compact"><CircleDollarSign :size="22" /><strong>暂无计费规则</strong><span>商业规则确认后由管理员配置</span></div></td></tr></tbody></table></div></section>
</template> </template>
@@ -423,30 +246,11 @@ function mapModels(items: CatalogModel[], providersList: CatalogProvider[]): Mod
<template v-else> <template v-else>
<section class="page-heading"><div><span>PLATFORM SETTINGS</span><h1>平台设置</h1><p>管理注册策略、内测规则和平台级配置。</p></div><button class="button primary" @click="emit('notify', '平台设置接口尚未接入,当前仅展示规划项')"><Check :size="16" />保存设置</button></section> <section class="page-heading"><div><span>PLATFORM SETTINGS</span><h1>平台设置</h1><p>管理注册策略、内测规则和平台级配置。</p></div><button class="button primary" @click="emit('notify', '平台设置接口尚未接入,当前仅展示规划项')"><Check :size="16" />保存设置</button></section>
<section class="settings-grid"><article class="panel settings-card"><header class="panel-header"><div><span>ACCESS CONTROL</span><h3>用户注册策略</h3></div><KeyRound :size="18" /></header><p>第一版通过邀请码控制用户规模,手机号和邮箱公开注册保留开关。</p><div class="setting-list"><div><span><strong>邀请码注册</strong><small>策略接口尚未接入</small></span><button class="switch" disabled :class="{ active: settings.inviteOnly }"><span></span></button></div><div><span><strong>邮箱公开注册</strong><small>验证码服务尚未接入</small></span><button class="switch" disabled :class="{ active: settings.emailSignup }"><span></span></button></div><div><span><strong>手机号公开注册</strong><small>短信服务尚未接入</small></span><button class="switch" disabled :class="{ active: settings.phoneSignup }"><span></span></button></div></div></article><article class="panel settings-card"><header class="panel-header"><div><span>OPERATIONS</span><h3>内测运营策略</h3></div><Settings2 :size="18" /></header><p>配置新用户额度、维护公告和操作审计。</p><div class="setting-list"><div><span><strong>新用户自动发放额度</strong><small>额度账本接口尚未接入</small></span><button class="switch" disabled :class="{ active: settings.automaticCredit }"><span></span></button></div><div><span><strong>显示维护公告</strong><small>公告配置接口尚未接入</small></span><button class="switch" disabled :class="{ active: settings.maintenanceNotice }"><span></span></button></div><div><span><strong>保留操作审计</strong><small>当前仅展示认证服务审计</small></span><button class="switch" disabled :class="{ active: settings.auditRetention }"><span></span></button></div></div></article></section> <section class="settings-grid"><article class="panel settings-card"><header class="panel-header"><div><span>ACCESS CONTROL</span><h3>用户注册策略</h3></div><KeyRound :size="18" /></header><p>第一版通过邀请码控制用户规模,手机号和邮箱公开注册保留开关。</p><div class="setting-list"><div><span><strong>邀请码注册</strong><small>策略接口尚未接入</small></span><button class="switch" disabled :class="{ active: settings.inviteOnly }"><span></span></button></div><div><span><strong>邮箱公开注册</strong><small>邮箱验证码已支持,公开注册暂未开放</small></span><button class="switch" disabled :class="{ active: settings.emailSignup }"><span></span></button></div><div><span><strong>手机号公开注册</strong><small>短信验证码已支持,公开注册暂未开放</small></span><button class="switch" disabled :class="{ active: settings.phoneSignup }"><span></span></button></div></div></article><article class="panel settings-card"><header class="panel-header"><div><span>OPERATIONS</span><h3>内测运营策略</h3></div><Settings2 :size="18" /></header><p>配置新用户额度、维护公告和操作审计。</p><div class="setting-list"><div><span><strong>新用户自动发放额度</strong><small>自动赠送暂未开启,可在用户与额度手动发放</small></span><button class="switch" disabled :class="{ active: settings.automaticCredit }"><span></span></button></div><div><span><strong>显示维护公告</strong><small>公告配置接口尚未接入</small></span><button class="switch" disabled :class="{ active: settings.maintenanceNotice }"><span></span></button></div><div><span><strong>保留操作审计</strong><small>记录认证、渠道、账号及额度操作</small></span><button class="switch" disabled :class="{ active: settings.auditRetention }"><span></span></button></div></div></article></section>
</template> </template>
<SlidePanel v-if="selectedUser" :title="selectedUser.name" eyebrow="USER DETAILS" @close="selectedUser = null">
<div class="user-profile"><span class="avatar-large">{{ selectedUser.name.slice(0, 1) }}</span><div><strong>{{ selectedUser.email }}</strong><small>{{ selectedUser.role }} · {{ selectedUser.status }}</small></div></div>
<dl class="detail-list"><div><dt>用户 ID</dt><dd><code>{{ selectedUser.id }}</code><button class="icon-button" title="复制用户 ID" @click="copyUserId(selectedUser.id)"><Copy :size="14" /></button></dd></div><div><dt>额度余额</dt><dd>{{ selectedUser.balance === undefined ? '--(账本未接入)' : `¥ ${selectedUser.balance.toFixed(2)}` }}</dd></div><div><dt>累计用量</dt><dd>{{ selectedUser.usage || '--(用量统计未接入)' }}</dd></div><div><dt>最近活跃</dt><dd>{{ selectedUser.lastActive || '--' }}</dd></div></dl>
<template #footer>
<button v-if="canEditRole" class="button secondary full" @click="openRoleEditor"><ShieldCheck :size="16" />调整角色</button>
<button v-if="selectedUser.roleCode !== 'super_admin'" class="button primary full" @click="openCredit(selectedUser)"><CircleDollarSign :size="16" />发放额度</button>
<button v-if="selectedUser.roleCode === 'user'" class="button secondary full" @click="emit('notify', '用户状态接口尚未接入,当前不会修改状态')"><ShieldCheck :size="16" />{{ selectedUser.status === '已停用' ? '重新启用' : '停用用户' }}</button>
</template>
</SlidePanel>
<UiModal v-if="roleTarget" title="调整用户角色" @close="!savingRole && (roleTarget = null)">
<p>{{ roleTarget.email }}</p>
<label class="form-label" for="user-role">角色</label>
<select id="user-role" v-model="roleChoice" class="text-input" :disabled="savingRole"><option value="user">普通用户</option><option value="admin">平台管理员</option></select>
<template #footer><button class="button secondary" :disabled="savingRole" @click="roleTarget = null">取消</button><button class="button primary" :disabled="savingRole || roleChoice === roleTarget.roleCode" @click="saveRole"><Check :size="16" />{{ savingRole ? '保存中…' : '保存角色' }}</button></template>
</UiModal>
<SlidePanel v-if="selectedUsage" :title="selectedUsage.modelName || selectedUsage.modelId || '调用记录详情'" eyebrow="REQUEST TRACE" @close="selectedUsage = null"><dl class="detail-list usage-detail-list"><div><dt>记录 ID</dt><dd><code>{{ selectedUsage.id }}</code></dd></div><div><dt>请求时间</dt><dd>{{ new Date(selectedUsage.createdAt).toLocaleString('zh-CN') }}</dd></div><div><dt>用户 / Key</dt><dd>{{ selectedUsage.userName || selectedUsage.userAccount || '--' }} / {{ selectedUsage.keyName || selectedUsage.keyPrefix || '--' }}</dd></div><div><dt>模型 / 供应商</dt><dd>{{ selectedUsage.modelName || selectedUsage.modelId }} / {{ selectedUsage.providerName || selectedUsage.providerId || '--' }}</dd></div><div><dt>状态与耗时</dt><dd>{{ selectedUsage.status }} · {{ selectedUsage.latencyMs ?? '--' }} ms</dd></div><div><dt>输入 / 输出单位</dt><dd>{{ selectedUsage.inputUnits ?? 0 }} / {{ selectedUsage.outputUnits ?? 0 }}</dd></div></dl><label class="form-label">输入数据(已脱敏)</label><pre class="usage-payload">{{ formatUsagePayload(selectedUsage.input) }}</pre><label class="form-label">输出数据(已脱敏)</label><pre class="usage-payload">{{ formatUsagePayload(selectedUsage.output) }}</pre><div v-if="selectedUsage.errorMessage" class="notice warning-notice"><AlertTriangle :size="16" /><span>{{ selectedUsage.errorCode }} · {{ selectedUsage.errorMessage }}</span></div><label class="form-label">管理员备注</label><textarea v-model="usageNote" class="text-input modal-textarea" placeholder="记录排查结论或运营备注"></textarea><template #footer><button class="button secondary" @click="saveUsageNote"><Check :size="16" />保存备注</button><button class="button danger" @click="deleteUsage(selectedUsage.id)"><Trash2 :size="16" />删除记录</button><button class="button primary" @click="selectedUsage = null">关闭</button></template></SlidePanel> <SlidePanel v-if="selectedUsage" :title="selectedUsage.modelName || selectedUsage.modelId || '调用记录详情'" eyebrow="REQUEST TRACE" @close="selectedUsage = null"><dl class="detail-list usage-detail-list"><div><dt>记录 ID</dt><dd><code>{{ selectedUsage.id }}</code></dd></div><div><dt>请求时间</dt><dd>{{ new Date(selectedUsage.createdAt).toLocaleString('zh-CN') }}</dd></div><div><dt>用户 / Key</dt><dd>{{ selectedUsage.userName || selectedUsage.userAccount || '--' }} / {{ selectedUsage.keyName || selectedUsage.keyPrefix || '--' }}</dd></div><div><dt>模型 / 供应商</dt><dd>{{ selectedUsage.modelName || selectedUsage.modelId }} / {{ selectedUsage.providerName || selectedUsage.providerId || '--' }}</dd></div><div><dt>状态与耗时</dt><dd>{{ selectedUsage.status }} · {{ selectedUsage.latencyMs ?? '--' }} ms</dd></div><div><dt>输入 / 输出单位</dt><dd>{{ selectedUsage.inputUnits ?? 0 }} / {{ selectedUsage.outputUnits ?? 0 }}</dd></div></dl><label class="form-label">输入数据(已脱敏)</label><pre class="usage-payload">{{ formatUsagePayload(selectedUsage.input) }}</pre><label class="form-label">输出数据(已脱敏)</label><pre class="usage-payload">{{ formatUsagePayload(selectedUsage.output) }}</pre><div v-if="selectedUsage.errorMessage" class="notice warning-notice"><AlertTriangle :size="16" /><span>{{ selectedUsage.errorCode }} · {{ selectedUsage.errorMessage }}</span></div><label class="form-label">管理员备注</label><textarea v-model="usageNote" class="text-input modal-textarea" placeholder="记录排查结论或运营备注"></textarea><template #footer><button class="button secondary" @click="saveUsageNote"><Check :size="16" />保存备注</button><button class="button danger" @click="deleteUsage(selectedUsage.id)"><Trash2 :size="16" />删除记录</button><button class="button primary" @click="selectedUsage = null">关闭</button></template></SlidePanel>
<UiModal v-if="usageDeleteTarget" title="删除调用记录" eyebrow="DELETE REQUEST TRACE" @close="usageDeleteTarget = null"><p class="modal-description">删除后该记录不会再出现在查询和导出结果中,原始数据库记录会保留删除标记。</p><template #footer><button class="button secondary" @click="usageDeleteTarget = null">取消</button><button class="button danger" @click="deleteUsage(usageDeleteTarget); usageDeleteTarget = null">确认删除</button></template></UiModal> <UiModal v-if="usageDeleteTarget" title="删除调用记录" eyebrow="DELETE REQUEST TRACE" @close="usageDeleteTarget = null"><p class="modal-description">删除后该记录不会再出现在查询和导出结果中,原始数据库记录会保留删除标记。</p><template #footer><button class="button secondary" @click="usageDeleteTarget = null">取消</button><button class="button danger" @click="deleteUsage(usageDeleteTarget); usageDeleteTarget = null">确认删除</button></template></UiModal>
<UiModal v-if="usageBulkDeleteOpen" title="批量删除调用记录" eyebrow="BULK DELETE REQUESTS" @close="usageBulkDeleteOpen = false"><p class="modal-description">确认删除选中的 {{ usageSelectedIds.length }} 条记录?删除后不会再出现在查询和导出结果中。</p><template #footer><button class="button secondary" @click="usageBulkDeleteOpen = false">取消</button><button class="button danger" @click="usageBulkDeleteOpen = false; deleteSelectedUsage()">确认删除</button></template></UiModal> <UiModal v-if="usageBulkDeleteOpen" title="批量删除调用记录" eyebrow="BULK DELETE REQUESTS" @close="usageBulkDeleteOpen = false"><p class="modal-description">确认删除选中的 {{ usageSelectedIds.length }} 条记录?删除后不会再出现在查询和导出结果中。</p><template #footer><button class="button secondary" @click="usageBulkDeleteOpen = false">取消</button><button class="button danger" @click="usageBulkDeleteOpen = false; deleteSelectedUsage()">确认删除</button></template></UiModal>
<UiModal v-if="invitationOpen" title="创建用户邀请" eyebrow="NEW INVITATION" @close="invitationOpen = false"><p class="modal-description">创建后生成一次性邀请码;账号和额度由用户激活后分别处理。</p><label class="form-label">邀请备注(可选)</label><input v-model="inviteLabel" class="text-input" placeholder="例如:内部测试成员" /><template #footer><button class="button secondary" @click="invitationOpen = false">取消</button><button class="button primary" @click="createInvitation"><Plus :size="16" />创建邀请码</button></template></UiModal>
<UiModal v-if="createdInviteCode" title="请立即保存邀请码" eyebrow="INVITATION CREATED" @close="createdInviteCode = ''"><p class="modal-description centered">完整邀请码只展示一次,关闭后只能重新创建。</p><div class="secret-box"><code>{{ createdInviteCode }}</code><button title="复制邀请码" @click="copyUserId(createdInviteCode)"><Copy :size="16" /></button></div><template #footer><button class="button primary full" @click="createdInviteCode = ''">我已安全保存</button></template></UiModal>
<UiModal v-if="providerOpen" title="登记供应商 / 渠道来源" eyebrow="NEW PROVIDER CHANNEL" @close="providerOpen = false"><p class="modal-description">供应商是渠道的身份,官方接口、中转站 Key、自托管服务都可以作为独立来源登记。保存后再关联该来源可提供的模型。</p><div class="modal-form-grid"><div><label class="form-label">供应商 Code</label><input v-model="providerCode" class="text-input" placeholder="例如:zhipu" @keyup.enter="createProvider" /></div><div><label class="form-label">显示名称</label><input v-model="providerName" class="text-input" placeholder="例如:智谱 AI / 内测中转 A" @keyup.enter="createProvider" /></div></div><div class="modal-form-grid"><div><label class="form-label">来源类型</label><select v-model="providerSourceType" class="text-input"><option value="official">官方供应商</option><option value="relay">中转站 / 渠道</option><option value="self-hosted">自托管模型</option><option value="custom">自定义来源</option></select></div><div><label class="form-label">接入协议</label><select v-model="providerProtocol" class="text-input"><option value="openai-compatible">OpenAI 兼容</option><option value="http">HTTP</option><option value="sdk">SDK</option></select></div></div><label class="form-label">服务 Base URL(可选)</label><input v-model="providerBaseUrl" class="text-input" placeholder="例如:https://api.example.com/v1" /><div class="modal-form-grid"><div><label class="form-label">凭据类型</label><select v-model="providerCredentialType" class="text-input"><option value="none">暂不配置</option><option value="api-key">API Key</option><option value="bearer">Bearer Token</option><option value="access-token">Access Token</option></select></div><div><label class="form-label">凭据值(可选)</label><input v-model="providerCredentialSecret" class="text-input" type="password" placeholder="仅保存服务端,不在用户端展示" /></div></div><label class="form-label">备注(可选)</label><textarea v-model="providerDescription" class="text-input modal-textarea" placeholder="记录区域、额度池、供应商文档或适配说明"></textarea><template #footer><button class="button secondary" @click="providerOpen = false">取消</button><button class="button primary" @click="createProvider"><Plus :size="16" />登记来源</button></template></UiModal>
<UiModal v-if="modelOpen" title="添加模型目录项" eyebrow="NEW MODEL ROUTE" @close="modelOpen = false"><p class="modal-description">同一个用户可见模型可以通过多个来源提供。当前目录项代表“一个模型 + 一个渠道”,用于后续优先级、价格和并发路由。</p><div class="modal-form-grid"><div><label class="form-label">所属供应商 / 渠道</label><select v-model="modelProviderId" class="text-input"><option v-for="provider in providers" :key="provider.id" :value="provider.id">{{ provider.name }}{{ provider.sourceType === 'relay' ? ' · 中转' : '' }}</option></select></div><div><label class="form-label">渠道显示名(可选)</label><input v-model="modelSourceLabel" class="text-input" placeholder="例如:低价池 / 高质量池" /></div></div><div class="modal-form-grid"><div><label class="form-label">统一模型名称</label><input v-model="modelPublicName" class="text-input" placeholder="例如:GLM-4.5 Air" @keyup.enter="createModel" /></div><div><label class="form-label">统一模型标识(可选)</label><input v-model="modelKey" class="text-input" placeholder="留空则使用系统生成 ID" /></div></div><label class="form-label">上游模型标识</label><input v-model="modelUpstreamModel" class="text-input" placeholder="例如:glm-4.5-air" @keyup.enter="createModel" /><div class="modal-form-grid"><div><label class="form-label">模型类型</label><select v-model="modelType" class="text-input"><option value="text">文本</option><option value="code">代码</option><option value="multimodal">多模态</option><option value="image">图像</option><option value="audio">音频</option><option value="video">视频</option><option value="embedding">向量</option><option value="3d">3D</option></select></div><div><label class="form-label">调用模式</label><select v-model="modelMode" class="text-input"><option value="sync">同步</option><option value="stream">流式</option><option value="async">异步</option></select></div></div><div class="modal-form-grid"><div><label class="form-label">输入类型</label><input v-model="modelInputTypes" class="text-input" placeholder="text, image(逗号分隔)" /></div><div><label class="form-label">输出类型</label><input v-model="modelOutputTypes" class="text-input" placeholder="text / video / model" /></div></div><div class="modal-form-grid"><div><label class="form-label">输入价格(可选)</label><input v-model="modelInputPrice" class="text-input" type="number" min="0" step="0.000001" placeholder="例如:0.002" /></div><div><label class="form-label">输出价格(可选)</label><input v-model="modelOutputPrice" class="text-input" type="number" min="0" step="0.000001" placeholder="例如:0.008" /></div></div><div class="modal-form-grid"><div><label class="form-label">价格单位</label><input v-model="modelPriceUnit" class="text-input" placeholder="例如:1K tokens / 次 / 秒" /></div><div><label class="form-label">路由优先级</label><input v-model="modelPriority" class="text-input" type="number" min="0" step="1" placeholder="数字越小越优先" /></div></div><label class="form-label">单渠道并发上限(可选)</label><input v-model="modelMaxConcurrency" class="text-input" type="number" min="0" step="1" placeholder="留空表示由全局策略控制" /><label class="form-label">模型说明(可选)</label><textarea v-model="modelDescription" class="text-input modal-textarea" placeholder="描述能力、输入输出、限制或适用场景"></textarea><template #footer><button class="button secondary" @click="modelOpen = false">取消</button><button class="button primary" @click="createModel"><Plus :size="16" />添加模型来源</button></template></UiModal>
</div> </div>
</template> </template>
+26 -4
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, ref } from 'vue' import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { import {
ArrowLeft, ArrowLeft,
ArrowRight, ArrowRight,
@@ -30,6 +30,13 @@ const account = ref('')
const password = ref('') const password = ref('')
const confirmPassword = ref('') const confirmPassword = ref('')
const invitationCode = ref('') const invitationCode = ref('')
const verificationCode = ref('')
const channels = ref({ email: false, phone: false })
const sendingCode = ref(false)
const cooldown = ref(0)
let cooldownTimer: ReturnType<typeof setInterval> | undefined
watch([account, registerChannel], () => { verificationCode.value = '' })
onUnmounted(() => { clearInterval(cooldownTimer) })
const agreeTerms = ref(false) const agreeTerms = ref(false)
const showPassword = ref(false) const showPassword = ref(false)
const showConfirmPassword = ref(false) const showConfirmPassword = ref(false)
@@ -43,8 +50,20 @@ function switchMode(nextMode: AuthMode) {
mode.value = nextMode mode.value = nextMode
} }
function sendCode() { async function sendCode() {
emit('notify', '验证码服务尚未接入,当前请使用管理员邀请码注册') if (sendingCode.value || cooldown.value) return
if (!invitationCode.value.trim()) return emit('notify', '请先填写邀请码')
if (registerChannel.value === 'email' ? !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(account.value.trim()) : !/^(?:\+86)?1[3-9]\d{9}$/.test(account.value.trim())) return emit('notify', `请输入有效的${accountLabel.value}`)
sendingCode.value = true
try {
const result = await authClient.sendVerificationCode(account.value, invitationCode.value)
cooldown.value = result.retryAfterSeconds
clearInterval(cooldownTimer)
cooldownTimer = setInterval(() => { if (cooldown.value > 0) cooldown.value--; else clearInterval(cooldownTimer) }, 1000)
emit('notify', '验证码已发送,5 分钟内有效')
} catch (error) {
emit('notify', error instanceof Error ? error.message : '验证码发送失败')
} finally { sendingCode.value = false }
} }
async function submitLogin() { async function submitLogin() {
@@ -63,6 +82,7 @@ async function submitLogin() {
async function submitRegister() { async function submitRegister() {
if (!invitationCode.value.trim()) return emit('notify', '第一版内测需要填写邀请码') if (!invitationCode.value.trim()) return emit('notify', '第一版内测需要填写邀请码')
if (!account.value.trim()) return emit('notify', `请输入${accountLabel.value}`) if (!account.value.trim()) return emit('notify', `请输入${accountLabel.value}`)
if (!/^\d{6}$/.test(verificationCode.value)) return emit('notify', '请输入 6 位验证码')
if (password.value.length < 8) return emit('notify', '密码至少需要 8 位') if (password.value.length < 8) return emit('notify', '密码至少需要 8 位')
if (password.value !== confirmPassword.value) return emit('notify', '两次输入的密码不一致') if (password.value !== confirmPassword.value) return emit('notify', '两次输入的密码不一致')
if (!agreeTerms.value) return emit('notify', '请先同意服务协议与隐私政策') if (!agreeTerms.value) return emit('notify', '请先同意服务协议与隐私政策')
@@ -70,6 +90,7 @@ async function submitRegister() {
try { try {
const user = await authClient.register({ const user = await authClient.register({
invitationCode: invitationCode.value, invitationCode: invitationCode.value,
verificationCode: verificationCode.value,
account: account.value, account: account.value,
password: password.value, password: password.value,
}) })
@@ -86,6 +107,7 @@ function submitReset() {
} }
onMounted(async () => { onMounted(async () => {
authClient.verificationChannels().then(value => { channels.value = value }).catch(() => {})
try { try {
await authClient.health() await authClient.health()
serviceStatus.value = 'online' serviceStatus.value = 'online'
@@ -152,7 +174,7 @@ onMounted(async () => {
<label><span>邀请码</span><div class="auth-input"><KeyRound :size="17" /><input v-model="invitationCode" placeholder="请输入管理员提供的邀请码" /></div></label> <label><span>邀请码</span><div class="auth-input"><KeyRound :size="17" /><input v-model="invitationCode" placeholder="请输入管理员提供的邀请码" /></div></label>
<div class="register-channel"><button type="button" :class="{ active: registerChannel === 'email' }" @click="registerChannel = 'email'"><Mail :size="15" />邮箱注册</button><button type="button" :class="{ active: registerChannel === 'phone' }" @click="registerChannel = 'phone'"><Phone :size="15" />手机号注册</button></div> <div class="register-channel"><button type="button" :class="{ active: registerChannel === 'email' }" @click="registerChannel = 'email'"><Mail :size="15" />邮箱注册</button><button type="button" :class="{ active: registerChannel === 'phone' }" @click="registerChannel = 'phone'"><Phone :size="15" />手机号注册</button></div>
<label><span>{{ accountLabel }}</span><div class="auth-input"><component :is="registerChannel === 'email' ? Mail : Phone" :size="17" /><input v-model="account" :placeholder="accountPlaceholder" /></div></label> <label><span>{{ accountLabel }}</span><div class="auth-input"><component :is="registerChannel === 'email' ? Mail : Phone" :size="17" /><input v-model="account" :placeholder="accountPlaceholder" /></div></label>
<label><span>验证码(公开注册开放后启用)</span><div class="auth-code-row"><div class="auth-input disabled"><ShieldCheck :size="17" /><input disabled placeholder="当前无需填写" /></div><button type="button" disabled @click="sendCode">暂未开放</button></div></label> <label><span>{{ registerChannel === 'email' ? '邮箱验证码' : '短信验证码' }}</span><div class="auth-code-row"><div class="auth-input"><ShieldCheck :size="17" /><input v-model="verificationCode" inputmode="numeric" autocomplete="one-time-code" maxlength="6" pattern="[0-9]{6}" required placeholder="6 位验证码" /></div><button type="button" :disabled="sendingCode || cooldown > 0 || !channels[registerChannel]" @click="sendCode">{{ sendingCode ? '发送中' : cooldown ? `${cooldown} 秒后重发` : '获取验证码' }}</button></div><small v-if="!channels[registerChannel]">{{ registerChannel === 'email' ? '邮箱' : '短信' }}发送服务暂不可用,请联系管理员。</small></label>
<label><span>设置密码</span><div class="auth-input"><LockKeyhole :size="17" /><input v-model="password" :type="showPassword ? 'text' : 'password'" autocomplete="new-password" placeholder="至少 8 位字符" /><button type="button" @click="showPassword = !showPassword"><EyeOff v-if="showPassword" :size="17" /><Eye v-else :size="17" /></button></div></label> <label><span>设置密码</span><div class="auth-input"><LockKeyhole :size="17" /><input v-model="password" :type="showPassword ? 'text' : 'password'" autocomplete="new-password" placeholder="至少 8 位字符" /><button type="button" @click="showPassword = !showPassword"><EyeOff v-if="showPassword" :size="17" /><Eye v-else :size="17" /></button></div></label>
<label><span>确认密码</span><div class="auth-input"><LockKeyhole :size="17" /><input v-model="confirmPassword" :type="showConfirmPassword ? 'text' : 'password'" autocomplete="new-password" placeholder="再次输入密码" /><button type="button" @click="showConfirmPassword = !showConfirmPassword"><EyeOff v-if="showConfirmPassword" :size="17" /><Eye v-else :size="17" /></button></div></label> <label><span>确认密码</span><div class="auth-input"><LockKeyhole :size="17" /><input v-model="confirmPassword" :type="showConfirmPassword ? 'text' : 'password'" autocomplete="new-password" placeholder="再次输入密码" /><button type="button" @click="showConfirmPassword = !showConfirmPassword"><EyeOff v-if="showConfirmPassword" :size="17" /><Eye v-else :size="17" /></button></div></label>
<label class="check-row terms-row"><input v-model="agreeTerms" type="checkbox" /><em>我已阅读并同意<a href="#" @click.prevent="emit('notify', '服务协议将在正式上线前补充')">《服务协议》</a>与<a href="#" @click.prevent="emit('notify', '隐私政策将在正式上线前补充')">《隐私政策》</a></em></label> <label class="check-row terms-row"><input v-model="agreeTerms" type="checkbox" /><em>我已阅读并同意<a href="#" @click.prevent="emit('notify', '服务协议将在正式上线前补充')">《服务协议》</a>与<a href="#" @click.prevent="emit('notify', '隐私政策将在正式上线前补充')">《隐私政策》</a></em></label>
+37 -20
View File
@@ -41,9 +41,10 @@ import { catalogClient, platformApiBaseUrl, type AsyncTaskResult, type CatalogAp
import { copyText, type CopyResult } from '../services/clipboard' import { copyText, type CopyResult } from '../services/clipboard'
import SlidePanel from '../components/SlidePanel.vue' import SlidePanel from '../components/SlidePanel.vue'
import UiModal from '../components/UiModal.vue' import UiModal from '../components/UiModal.vue'
import ModelGroupPermissions from '../components/ModelGroupPermissions.vue'
defineProps<{ view: string; displayName?: string }>() defineProps<{ view: string; displayName?: string }>()
const emit = defineEmits<{ navigate: [view: string]; notify: [message: string] }>() const emit = defineEmits<{ navigate: [view: string]; notify: [message: string]; balance: [value: number | undefined] }>()
const modelQuery = ref('') const modelQuery = ref('')
const modelType = ref<'全部' | ModelType>('全部') const modelType = ref<'全部' | ModelType>('全部')
@@ -54,7 +55,17 @@ const selectedModel = ref<ModelItem | null>(null)
const emptyModel: ModelItem = { id: '', name: '尚未选择模型', provider: '等待目录加载', type: '文本', mode: '同步', description: '', latency: '--', specification: '--', availability: '--', accent: 'violet', icon: MessageSquareText } const emptyModel: ModelItem = { id: '', name: '尚未选择模型', provider: '等待目录加载', type: '文本', mode: '同步', description: '', latency: '--', specification: '--', availability: '--', accent: 'violet', icon: MessageSquareText }
const catalogModels = ref<ModelItem[]>([]) const catalogModels = ref<ModelItem[]>([])
const activeModel = ref<ModelItem>(emptyModel) const activeModel = ref<ModelItem>(emptyModel)
const callMode = ref<CallMode>('流式') const callMode = ref<CallMode>('同步')
const playgroundModels = computed(() => [...new Map(catalogModels.value.map(group => [group.logicalModelId || group.id, group])).values()])
const playgroundGroups = computed(() => catalogModels.value.filter(group => (group.logicalModelId || group.id) === (activeModel.value.logicalModelId || activeModel.value.id)))
function selectPlaygroundGroup(id: string) {
const group = catalogModels.value.find(item => item.id === id)
if (group) { activeModel.value = group; callMode.value = group.mode; response.value = ''; activeTaskId.value = '' }
}
function selectPlaygroundModel(id: string) {
const group = catalogModels.value.find(item => (item.logicalModelId || item.id) === id)
if (group) selectPlaygroundGroup(group.id)
}
const prompt = ref('') const prompt = ref('')
const running = ref(false) const running = ref(false)
const response = ref('') const response = ref('')
@@ -91,10 +102,11 @@ onMounted(async () => {
try { try {
const [catalog, keyResult, projectResult, overviewResult] = await Promise.all([catalogClient.listModels(), catalogClient.listKeys(), catalogClient.listProjects(), catalogClient.getOverview()]) const [catalog, keyResult, projectResult, overviewResult] = await Promise.all([catalogClient.listModels(), catalogClient.listKeys(), catalogClient.listProjects(), catalogClient.getOverview()])
catalogModels.value = mapCatalogModels(catalog.models, catalog.providers) catalogModels.value = mapCatalogModels(catalog.models, catalog.providers)
if (catalogModels.value[0]) activeModel.value = catalogModels.value[0] if (catalogModels.value[0]) selectPlaygroundGroup(catalogModels.value[0].id)
keys.value = keyResult.keys.map((key) => mapCatalogKey(key)) keys.value = keyResult.keys.map((key) => mapCatalogKey(key))
projects.value = projectResult.projects projects.value = projectResult.projects
overview.value = overviewResult overview.value = overviewResult
emit('balance', overviewResult.availableCredit)
overviewLoaded.value = true overviewLoaded.value = true
catalogConnected.value = true catalogConnected.value = true
try { try {
@@ -153,7 +165,6 @@ const usageSeries = computed(() => {
const recentTasks = computed(() => tasks.value.slice(0, 3)) const recentTasks = computed(() => tasks.value.slice(0, 3))
const modelTypes: Array<'全部' | ModelType> = ['全部', '文本', '多模态', '图像', '3D', '视频', '音频'] const modelTypes: Array<'全部' | ModelType> = ['全部', '文本', '多模态', '图像', '3D', '视频', '音频']
const callModes: Array<'全部' | CallMode> = ['全部', '同步', '流式', '异步'] const callModes: Array<'全部' | CallMode> = ['全部', '同步', '流式', '异步']
const allModelsSelected = computed(() => catalogModels.value.length > 0 && catalogModels.value.every((model) => selectedModelIds.value.includes(model.id)))
async function copy(value: string, label: string, target: string) { async function copy(value: string, label: string, target: string) {
const result = await copyText(value) const result = await copyText(value)
@@ -184,6 +195,7 @@ function resetModelFilters() {
async function refreshOverview() { async function refreshOverview() {
try { try {
overview.value = await catalogClient.getOverview() overview.value = await catalogClient.getOverview()
emit('balance', overview.value.availableCredit)
overviewLoaded.value = true overviewLoaded.value = true
} catch {} } catch {}
} }
@@ -326,6 +338,7 @@ function mapCatalogModels(items: CatalogModel[], providers: Array<{ id: string;
const modeLabels: Record<string, CallMode> = { sync: '同步', stream: '流式', async: '异步' } const modeLabels: Record<string, CallMode> = { sync: '同步', stream: '流式', async: '异步' }
return items.map((item) => ({ return items.map((item) => ({
id: item.id, id: item.id,
logicalModelId: item.logicalModelId,
name: item.publicName, name: item.publicName,
provider: providerNames.get(item.providerId) || item.providerId, provider: providerNames.get(item.providerId) || item.providerId,
type: typeLabels[item.type] || '文本', type: typeLabels[item.type] || '文本',
@@ -379,20 +392,9 @@ function openCreatedKeyPermissions() {
if (key) openModelPermissions(key) if (key) openModelPermissions(key)
} }
function toggleModelPermission(modelId: string) {
selectedModelIds.value = selectedModelIds.value.includes(modelId)
? selectedModelIds.value.filter((id) => id !== modelId)
: [...selectedModelIds.value, modelId]
}
function toggleAllModels() {
selectedModelIds.value = allModelsSelected.value ? [] : catalogModels.value.map((model) => model.id)
}
async function saveModelPermissions() { async function saveModelPermissions() {
const key = permissionKey.value const key = permissionKey.value
if (!key) return if (!key) return
if (!selectedModelIds.value.length) return emit('notify', '请至少选择一个可调用模型')
if (!catalogConnected.value) return emit('notify', 'Control Plane 未连接,无法保存模型权限') if (!catalogConnected.value) return emit('notify', 'Control Plane 未连接,无法保存模型权限')
savingPermissions.value = true savingPermissions.value = true
try { try {
@@ -488,10 +490,12 @@ async function createProject() {
<section class="playground-grid"> <section class="playground-grid">
<article class="panel request-panel"> <article class="panel request-panel">
<header class="panel-header"><div><span>REQUEST</span><h3>请求配置</h3></div><button class="icon-button" @click="prompt = ''; response = ''; activeTaskId = ''"><RefreshCcw :size="16" /></button></header> <header class="panel-header"><div><span>REQUEST</span><h3>请求配置</h3></div><button class="icon-button" @click="prompt = ''; response = ''; activeTaskId = ''"><RefreshCcw :size="16" /></button></header>
<label class="form-label">模型</label> <div class="playground-selectors">
<button class="model-picker" @click="emit('navigate', 'models')"><span class="model-icon" :class="activeModel.accent"><component :is="activeModel.icon" :size="18" /></span><div><strong>{{ activeModel.name }}</strong><small>{{ activeModel.type }} · {{ activeModel.provider }}</small></div><ChevronDown :size="16" /></button> <label>模型<select class="text-input" aria-label="调试模型" :value="activeModel.logicalModelId || activeModel.id" :disabled="running || !playgroundModels.length" @change="selectPlaygroundModel(($event.target as HTMLSelectElement).value)"><option v-for="model in playgroundModels" :key="model.logicalModelId || model.id" :value="model.logicalModelId || model.id">{{ model.name }}</option></select></label>
<label>分组<select class="text-input" aria-label="调试分组" :value="activeModel.id" :disabled="running || !playgroundGroups.length" @change="selectPlaygroundGroup(($event.target as HTMLSelectElement).value)"><option v-for="group in playgroundGroups" :key="group.id" :value="group.id">{{ group.sourceLabel || '默认分组' }} · {{ group.provider }}</option></select></label>
</div>
<label class="form-label">调用模式</label> <label class="form-label">调用模式</label>
<div class="segment"><button v-for="mode in ['同步','流式','异步']" :key="mode" :class="{ active: callMode === mode }" @click="callMode = mode as CallMode">{{ mode }}</button></div> <div class="segment"><button v-for="mode in ['同步','流式','异步']" :key="mode" :disabled="running || mode !== activeModel.mode || mode === '流式'" :class="{ active: callMode === mode }" @click="callMode = mode as CallMode">{{ mode }}</button></div>
<label class="form-label prompt-label"><span>输入内容</span><small>{{ prompt.length }}/4000</small></label> <label class="form-label prompt-label"><span>输入内容</span><small>{{ prompt.length }}/4000</small></label>
<textarea v-model="prompt" maxlength="4000" :placeholder="callMode === '异步' ? activeModel.type === '视频' ? '例如:电影感产品展示视频,柔和运镜与自然光影' : '例如:一个低面数的木质机械鸟,游戏资产风格' : '描述你希望模型完成的任务'"></textarea> <textarea v-model="prompt" maxlength="4000" :placeholder="callMode === '异步' ? activeModel.type === '视频' ? '例如:电影感产品展示视频,柔和运镜与自然光影' : '例如:一个低面数的木质机械鸟,游戏资产风格' : '描述你希望模型完成的任务'"></textarea>
<div class="request-footer"><span><ShieldCheck :size="14" />{{ catalogConnected ? '通过 MOYI Key 调用真实网关' : '连接服务后才能调用' }}</span><button class="button primary" :disabled="running || !catalogConnected || !activeModel.id" @click="runModel"><Play v-if="!running" :size="16" /><span v-else class="spinner"></span>{{ running ? '提交中…' : callMode === '异步' ? activeModel.type === '视频' ? '生成视频' : '生成 3D' : '开始调用' }}</button></div> <div class="request-footer"><span><ShieldCheck :size="14" />{{ catalogConnected ? '通过 MOYI Key 调用真实网关' : '连接服务后才能调用' }}</span><button class="button primary" :disabled="running || !catalogConnected || !activeModel.id" @click="runModel"><Play v-if="!running" :size="16" /><span v-else class="spinner"></span>{{ running ? '提交中…' : callMode === '异步' ? activeModel.type === '视频' ? '生成视频' : '生成 3D' : '开始调用' }}</button></div>
@@ -516,7 +520,7 @@ async function createProject() {
<template v-else-if="view === 'keys'"> <template v-else-if="view === 'keys'">
<section class="page-heading"><div><span>DEVELOPER ACCESS</span><h1>API Keys</h1><p>为不同应用和环境创建独立访问凭证。</p></div><button class="button primary" @click="createKeyOpen = true"><Plus :size="16" />创建 API Key</button></section> <section class="page-heading"><div><span>DEVELOPER ACCESS</span><h1>API Keys</h1><p>为不同应用和环境创建独立访问凭证。</p></div><button class="button primary" @click="createKeyOpen = true"><Plus :size="16" />创建 API Key</button></section>
<section class="notice"><ShieldCheck :size="19" /><div><strong>妥善保管访问凭证</strong><p>完整 Key 只在创建时展示一次,请存放在安全的环境变量或密钥管理服务中。</p></div></section> <section class="notice"><ShieldCheck :size="19" /><div><strong>妥善保管访问凭证</strong><p>完整 Key 只在创建时展示一次,请存放在安全的环境变量或密钥管理服务中。</p></div></section>
<section class="panel table-card"><header class="panel-header"><div><span>CREDENTIALS</span><h3>个人与项目 Keys</h3></div><small>{{ keys.length }} 个凭证{{ catalogConnected ? ' · 已连接 Control Plane' : ' · 服务未连接' }}</small></header><div class="responsive-table"><table><thead><tr><th>名称</th><th>Key</th><th>归属范围</th><th>模型权限</th><th>最近使用</th><th>状态</th><th></th></tr></thead><tbody><tr v-for="key in keys" :key="key.id"><td><div class="entity-cell"><span class="icon-tile violet"><KeyRound :size="16" /></span><div><strong>{{ key.name }}</strong><small>创建于 {{ key.createdAt }}</small></div></div></td><td><span class="code-value readonly" title="完整 Key 仅在创建时展示"><code>{{ key.value }}</code><ShieldCheck :size="14" /></span></td><td>{{ key.scope }}</td><td><button class="model-permission-summary" :disabled="key.status !== '正常'" @click="openModelPermissions(key)"><span>{{ key.modelIds.length === catalogModels.length && catalogModels.length ? `全部 ${catalogModels.length} 个模型` : key.modelIds.length ? `${key.modelIds.length} 个模型` : '未配置' }}</span><SlidersHorizontal :size="14" /></button></td><td>{{ key.lastUsed }}</td><td><span class="status-chip" :class="key.status === '正常' ? 'success' : 'muted'"><i></i>{{ key.status }}</span></td><td><button class="icon-button" :title="key.status === '正常' ? '停用 Key' : '已停用'" @click="toggleKey(key)"><EyeOff v-if="key.status === '正常'" :size="16" /><Eye v-else :size="16" /></button></td></tr><tr v-if="!keys.length"><td colspan="7"><div class="empty-state compact"><KeyRound :size="22" /><strong>暂无 API Key</strong><span>创建后完整 Key 只会展示一次</span></div></td></tr></tbody></table></div></section> <section class="panel table-card"><header class="panel-header"><div><span>CREDENTIALS</span><h3>个人与项目 Keys</h3></div><small>{{ keys.length }} 个凭证{{ catalogConnected ? ' · 已连接 Control Plane' : ' · 服务未连接' }}</small></header><div class="responsive-table"><table><thead><tr><th>名称</th><th>Key</th><th>归属范围</th><th>模型权限</th><th>最近使用</th><th>状态</th><th></th></tr></thead><tbody><tr v-for="key in keys" :key="key.id"><td><div class="entity-cell"><span class="icon-tile violet"><KeyRound :size="16" /></span><div><strong>{{ key.name }}</strong><small>创建于 {{ key.createdAt }}</small></div></div></td><td><span class="code-value readonly" title="完整 Key 仅在创建时展示"><code>{{ key.value }}</code><ShieldCheck :size="14" /></span></td><td>{{ key.scope }}</td><td><button class="model-permission-summary" :disabled="key.status !== '正常'" @click="openModelPermissions(key)"><span>{{ key.modelIds.length ? `${key.modelIds.length} 个分组` : '未配置' }}</span><SlidersHorizontal :size="14" /></button></td><td>{{ key.lastUsed }}</td><td><span class="status-chip" :class="key.status === '正常' ? 'success' : 'muted'"><i></i>{{ key.status }}</span></td><td><button class="icon-button" :title="key.status === '正常' ? '停用 Key' : '已停用'" @click="toggleKey(key)"><EyeOff v-if="key.status === '正常'" :size="16" /><Eye v-else :size="16" /></button></td></tr><tr v-if="!keys.length"><td colspan="7"><div class="empty-state compact"><KeyRound :size="22" /><strong>暂无 API Key</strong><span>创建后完整 Key 只会展示一次</span></div></td></tr></tbody></table></div></section>
</template> </template>
<template v-else-if="view === 'tasks'"> <template v-else-if="view === 'tasks'">
@@ -548,6 +552,19 @@ MOYI_MODEL=&lt;model-id&gt;</code></pre></div></section><section><b>02</b><div><
<UiModal v-if="createKeyOpen" title="创建 API Key" eyebrow="NEW CREDENTIAL" @close="createKeyOpen = false"><p class="modal-description">个人 Key 适合个人开发调试,项目 Key 适合服务端应用和团队协作。创建后再配置该 Key 可调用的具体模型。</p><label class="form-label">Key 名称</label><input v-model="keyName" class="text-input" placeholder="例如:生产环境" /><label class="form-label">Key 归属</label><div class="option-list"><button :class="{ active: keyScopeType === 'personal' }" @click="keyScopeType = 'personal'"><span><i></i><strong>个人 Key</strong><small>归属当前账号</small></span><Check v-if="keyScopeType === 'personal'" :size="16" /></button><button :class="{ active: keyScopeType === 'project' }" @click="keyScopeType = 'project'"><span><i></i><strong>项目 Key</strong><small>归属工作区/项目</small></span><Check v-if="keyScopeType === 'project'" :size="16" /></button></div><div v-if="keyScopeType === 'project'"><label class="form-label"><span>选择项目</span><button class="text-link" type="button" @click="openProjectModal">新建项目</button></label><select v-model="selectedProjectId" class="text-input"><option value="" disabled>请选择项目</option><option v-for="project in projects" :key="project.id" :value="project.id">{{ project.name }}</option></select></div><div class="permission-hint"><ShieldCheck :size="16" /><span>Key 创建后默认不开放模型权限,请在下一步选择具体可调用模型。</span></div><template #footer><button class="button secondary" @click="createKeyOpen = false">取消</button><button class="button primary" @click="createKey"><KeyRound :size="16" />生成 Key</button></template></UiModal> <UiModal v-if="createKeyOpen" title="创建 API Key" eyebrow="NEW CREDENTIAL" @close="createKeyOpen = false"><p class="modal-description">个人 Key 适合个人开发调试,项目 Key 适合服务端应用和团队协作。创建后再配置该 Key 可调用的具体模型。</p><label class="form-label">Key 名称</label><input v-model="keyName" class="text-input" placeholder="例如:生产环境" /><label class="form-label">Key 归属</label><div class="option-list"><button :class="{ active: keyScopeType === 'personal' }" @click="keyScopeType = 'personal'"><span><i></i><strong>个人 Key</strong><small>归属当前账号</small></span><Check v-if="keyScopeType === 'personal'" :size="16" /></button><button :class="{ active: keyScopeType === 'project' }" @click="keyScopeType = 'project'"><span><i></i><strong>项目 Key</strong><small>归属工作区/项目</small></span><Check v-if="keyScopeType === 'project'" :size="16" /></button></div><div v-if="keyScopeType === 'project'"><label class="form-label"><span>选择项目</span><button class="text-link" type="button" @click="openProjectModal">新建项目</button></label><select v-model="selectedProjectId" class="text-input"><option value="" disabled>请选择项目</option><option v-for="project in projects" :key="project.id" :value="project.id">{{ project.name }}</option></select></div><div class="permission-hint"><ShieldCheck :size="16" /><span>Key 创建后默认不开放模型权限,请在下一步选择具体可调用模型。</span></div><template #footer><button class="button secondary" @click="createKeyOpen = false">取消</button><button class="button primary" @click="createKey"><KeyRound :size="16" />生成 Key</button></template></UiModal>
<UiModal v-if="secretOpen" title="请立即保存你的 Key" eyebrow="CREDENTIAL CREATED" @close="secretOpen = false"><div class="secret-success"><CheckCircle2 :size="25" /><strong>API Key 创建成功</strong></div><p class="modal-description centered">完整 Key 只展示一次,关闭后无法再次查看。保存后继续配置模型权限。</p><div class="secret-box"><code>{{ revealSecret ? createdSecret : `${createdSecret.slice(0, 10)}••••••••••••` }}</code><button title="显示或隐藏 Key" @click="revealSecret = !revealSecret"><EyeOff v-if="revealSecret" :size="16" /><Eye v-else :size="16" /></button><button title="复制完整 Key" @click="copy(createdSecret, 'API Key', 'secret-key')"><Check v-if="copySucceeded('secret-key')" :size="16" /><Copy v-else :size="16" /></button></div><template #footer><button class="button secondary" @click="secretOpen = false; revealSecret = false">稍后配置</button><button class="button primary" @click="openCreatedKeyPermissions"><SlidersHorizontal :size="16" />配置可调用模型</button></template></UiModal> <UiModal v-if="secretOpen" title="请立即保存你的 Key" eyebrow="CREDENTIAL CREATED" @close="secretOpen = false"><div class="secret-success"><CheckCircle2 :size="25" /><strong>API Key 创建成功</strong></div><p class="modal-description centered">完整 Key 只展示一次,关闭后无法再次查看。保存后继续配置模型权限。</p><div class="secret-box"><code>{{ revealSecret ? createdSecret : `${createdSecret.slice(0, 10)}••••••••••••` }}</code><button title="显示或隐藏 Key" @click="revealSecret = !revealSecret"><EyeOff v-if="revealSecret" :size="16" /><Eye v-else :size="16" /></button><button title="复制完整 Key" @click="copy(createdSecret, 'API Key', 'secret-key')"><Check v-if="copySucceeded('secret-key')" :size="16" /><Copy v-else :size="16" /></button></div><template #footer><button class="button secondary" @click="secretOpen = false; revealSecret = false">稍后配置</button><button class="button primary" @click="openCreatedKeyPermissions"><SlidersHorizontal :size="16" />配置可调用模型</button></template></UiModal>
<UiModal v-if="projectOpen" title="新建工作区 / 项目" eyebrow="NEW PROJECT" @close="projectOpen = false"><p class="modal-description">项目用于归属团队 Key,并为后续用量、额度和权限隔离预留空间。</p><label class="form-label">项目名称</label><input v-model="projectName" class="text-input" placeholder="例如:AI SoulMate 研发项目" @keyup.enter="createProject" /><label class="form-label">项目描述(可选)</label><textarea v-model="projectDescription" class="text-input modal-textarea" placeholder="描述项目用途或成员范围"></textarea><template #footer><button class="button secondary" @click="projectOpen = false">取消</button><button class="button primary" @click="createProject"><Plus :size="16" />创建项目</button></template></UiModal> <UiModal v-if="projectOpen" title="新建工作区 / 项目" eyebrow="NEW PROJECT" @close="projectOpen = false"><p class="modal-description">项目用于归属团队 Key,并为后续用量、额度和权限隔离预留空间。</p><label class="form-label">项目名称</label><input v-model="projectName" class="text-input" placeholder="例如:AI SoulMate 研发项目" @keyup.enter="createProject" /><label class="form-label">项目描述(可选)</label><textarea v-model="projectDescription" class="text-input modal-textarea" placeholder="描述项目用途或成员范围"></textarea><template #footer><button class="button secondary" @click="projectOpen = false">取消</button><button class="button primary" @click="createProject"><Plus :size="16" />创建项目</button></template></UiModal>
<UiModal v-if="modelPermissionsOpen && permissionKey" title="配置模型权限" eyebrow="MODEL ACCESS" @close="modelPermissionsOpen = false; permissionKey = null"><p class="modal-description">为 <strong>{{ permissionKey.name }}</strong> 选择允许调用的模型。权限变更会立即应用到该 Key。</p><button class="permission-all-toggle" :class="{ active: allModelsSelected }" @click="toggleAllModels"><span><i></i><strong>全部模型</strong><small>{{ allModelsSelected ? '已选中当前目录全部模型' : '一键选择当前目录全部模型' }}</small></span><Check v-if="allModelsSelected" :size="17" /></button><div class="permission-model-list"><button v-for="model in catalogModels" :key="model.id" class="permission-model-button" :class="{ active: selectedModelIds.includes(model.id) }" @click="toggleModelPermission(model.id)"><span class="model-icon" :class="model.accent"><component :is="model.icon" :size="17" /></span><span><strong>{{ model.name }}</strong><small>{{ model.provider }} · {{ model.type }} · {{ model.mode }}</small></span><Check v-if="selectedModelIds.includes(model.id)" :size="17" /></button><div v-if="!catalogModels.length" class="empty-state compact"><Box :size="20" /><strong>暂无可选模型</strong><span>请先由管理员配置模型目录</span></div></div><template #footer><button class="button secondary" @click="modelPermissionsOpen = false; permissionKey = null">取消</button><button class="button primary" :disabled="savingPermissions || !selectedModelIds.length" @click="saveModelPermissions"><span v-if="savingPermissions" class="spinner"></span><Check v-else :size="16" />{{ savingPermissions ? '保存中…' : '保存模型权限' }}</button></template></UiModal> <UiModal v-if="modelPermissionsOpen && permissionKey" title="配置模型与分组权限" eyebrow="MODEL ACCESS" @close="modelPermissionsOpen = false; permissionKey = null">
<p class="modal-description">{{ permissionKey.name }}</p>
<ModelGroupPermissions v-model="selectedModelIds" :groups="catalogModels" :disabled="savingPermissions" />
<template #footer><button class="button secondary" :disabled="savingPermissions" @click="modelPermissionsOpen = false; permissionKey = null">取消</button><button class="button primary" :disabled="savingPermissions" @click="saveModelPermissions"><span v-if="savingPermissions" class="spinner"></span><Check v-else :size="16" />{{ savingPermissions ? '保存中…' : '保存权限' }}</button></template>
</UiModal>
</div> </div>
</template> </template>
<style scoped>
.request-panel, .response-panel { min-width: 0; }
.playground-selectors { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; margin-bottom: 16px; }
.playground-selectors label { display: grid; gap: 8px; font-size: 13px; min-width: 0; }
.playground-selectors select { width: 100%; min-width: 0; }
@media(max-width: 1180px) { .playground-grid { grid-template-columns: minmax(0, 1fr); } }
@media(max-width: 700px) { .playground-selectors { grid-template-columns: minmax(0, 1fr); } }
</style>
+1 -1
View File
@@ -28,7 +28,7 @@ New-Item -ItemType Directory -Force -Path $artifactRoot | Out-Null
$staging = Join-Path $artifactRoot ('moyi-test-' + $releaseId) $staging = Join-Path $artifactRoot ('moyi-test-' + $releaseId)
New-Item -ItemType Directory -Path $staging | Out-Null New-Item -ItemType Directory -Path $staging | Out-Null
# Copy tracked deployment files only, never .env, certificates or .git. # Copy tracked deployment files only, never .env, certificates or .git.
$tracked = @(git ls-files infra/moyi docs/11-server-test-deployment.md) $tracked = @(git ls-files infra/moyi docs/11-server-test-deployment.md docs/13-model-groups-registration-credit.md)
foreach ($relative in $tracked) { foreach ($relative in $tracked) {
if ($relative -match '(^|/)(\.env\.cloud|\.deploy-mode|certs)(/|$)') { throw 'Sensitive path in release allowlist.' } if ($relative -match '(^|/)(\.env\.cloud|\.deploy-mode|certs)(/|$)') { throw 'Sensitive path in release allowlist.' }
$destination = Join-Path $staging $relative $destination = Join-Path $staging $relative