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

@@ -6,6 +6,11 @@ import org.springframework.web.bind.annotation.RestController;
@RestController
public class HealthController {
private final com.moyi.controlplane.auth.VerificationService verification;
public HealthController(com.moyi.controlplane.auth.VerificationService verification) {
this.verification = verification;
}
@GetMapping("/health")
public Map<String, Object> health() {
return Map.of(
@@ -13,7 +18,7 @@ public class HealthController {
"service", "moyi-control-plane-java",
"migration", "catalog",
"capabilities", Map.of(
"verificationCode", false,
"verificationCode", verification.capabilities().containsValue(true),
"passwordReset", false
)
);
@@ -26,26 +26,44 @@ import org.springframework.web.bind.annotation.RestController;
public class AuthController {
private static final String SESSION_COOKIE = "moyi_session";
private final AuthService authService;
private final VerificationService verification;
private final int sessionTtlHours;
private final boolean secureCookie;
public AuthController(
AuthService authService,
VerificationService verification,
@Value("${moyi.auth.session-ttl-hours}") int sessionTtlHours,
@Value("${moyi.auth.secure-cookie}") boolean secureCookie
) {
this.authService = authService;
this.verification = verification;
this.sessionTtlHours = sessionTtlHours;
this.secureCookie = secureCookie;
}
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 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")
public Map<String, Object> login(
@@ -64,6 +82,7 @@ public class AuthController {
HttpServletRequest request,
HttpServletResponse response
) {
verification.consume(input.account(),input.verificationCode());
AuthService.AuthResult result = authService.register(
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();
}
@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
public Map<String, Object> createInvitation(
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.web.bind.annotation.GetMapping;
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.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
@@ -28,7 +29,7 @@ public class CatalogController {
@GetMapping("/models")
public Map<String, Object> models(jakarta.servlet.http.HttpServletRequest 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")
@@ -103,7 +104,27 @@ public class CatalogController {
@GetMapping("/admin/models")
public Map<String, Object> adminModels(jakarta.servlet.http.HttpServletRequest 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")
@@ -48,8 +48,56 @@ public class CatalogService {
}
public List<Map<String, Object>> listModels(boolean includeDisabled) {
String statusClause = includeDisabled ? "" : " WHERE status = 'active'";
return jdbc.query("SELECT * FROM model_catalog" + statusClause + " ORDER BY public_name", this::mapModel);
String statusClause = includeDisabled ? "" : " WHERE m.status = 'active' AND p.status = 'active' AND d.status = 'active'";
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
@@ -59,54 +107,123 @@ public class CatalogService {
String name = required(input, "name");
String protocol = optional(input, "protocol", "http");
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", "供应商标识、协议或来源类型无效");
}
String id = UUID.randomUUID().toString();
String baseUrl = optional(input, "baseUrl", null);
validateBaseUrl(baseUrl);
String description = optional(input, "description", "");
String credentialType = optional(input, "credentialType", null);
String secret = optional(input, "credentialSecret", null);
String credentialType = optional(input, "credentialType", "none");
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);
jdbc.update(
"INSERT INTO model_providers (id, code, name, protocol, source_type, base_url, description, credential_type, credential_ciphertext, credential_masked, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'active')",
id, code, name, protocol, sourceType, baseUrl, description, credentialType, secret == null ? null : secretCipher.encrypt(secret), masked
"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, status(input)
);
auth.audit("provider.created", admin.id(), new AuthService.RequestMeta(null, null), Map.of("providerId", 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
public Map<String, Object> createModel(Map<String, Object> input, String token, AuthService auth) {
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");
if (findProvider(providerId) == null) throw new ApiException("PROVIDER_NOT_FOUND", "供应商不存在", 404);
String publicName = required(input, "publicName");
String upstreamModel = required(input, "upstreamModel");
if (upstreamModel.length() > 160) throw new ApiException("INVALID_MODEL", "上游模型标识不能超过 160 字符");
String type = required(input, "type");
String mode = required(input, "mode");
if (!MODEL_TYPES.contains(type) || !CALL_MODES.contains(mode)) throw new ApiException("INVALID_MODEL", "模型类型或调用模式无效");
String id = UUID.randomUUID().toString();
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 inputTypes = jsonArray(input.get("inputTypes"));
String outputTypes = jsonArray(input.get("outputTypes"));
String capabilities = jsonObject(input.get("capabilities"));
String pricing = jsonObjectOrNull(input.get("pricing"));
validatePricing(input.get("pricing"));
Integer priority = integerOrNull(input.get("priority"));
Integer maxConcurrency = integerOrNull(input.get("maxConcurrency"));
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(
"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,
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));
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) {
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());
@@ -158,8 +275,11 @@ public class CatalogService {
@Transactional
public Map<String, Object> updateKeyModels(String token, String keyId, List<String> modelIds, AuthService auth) {
UserView user = auth.requireUser(token);
List<String> uniqueIds = modelIds == null ? List.of() : modelIds.stream().map(String::trim).filter(value -> !value.isBlank()).distinct().toList();
for (String modelId : uniqueIds) if (findActiveModel(modelId) == null) throw new ApiException("MODEL_NOT_FOUND", "模型不存在或已下线", 404);
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());
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());
if (changed == 0) throw new ApiException("KEY_NOT_FOUND", "Key 不存在、已停用或无权修改", 404);
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("series", 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;
}
public Map<String, Object> authenticateKey(String plaintext) {
if (plaintext == null || plaintext.isBlank()) return null;
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) {
return null;
}
@@ -237,7 +360,7 @@ public class CatalogService {
}
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; }
}
@@ -274,6 +397,7 @@ public class CatalogService {
private Map<String, Object> mapModel(ResultSet resultSet, int rowNumber) throws SQLException {
Map<String, Object> model = new LinkedHashMap<>();
model.put("id", resultSet.getString("id"));
model.put("logicalModelId", resultSet.getString("logical_model_id"));
model.put("providerId", resultSet.getString("provider_id"));
putIfNotNull(model, "modelKey", resultSet.getString("model_key"));
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);
}
}