feat: migrate java control plane foundation

This commit is contained in:
wlx committed 2026-09-07 16:54:43 +08:00
1 parent 1615401185
commit 9da175c040
24 files changed
+1555 -12

No files matched your search

@@ -11,7 +11,11 @@ public class HealthController {
return Map.of(
"status", "ok",
"service", "moyi-control-plane-java",
"migration", "bootstrap"
"migration", "catalog",
"capabilities", Map.of(
"verificationCode", false,
"passwordReset", false
)
);
}
}
@@ -0,0 +1,40 @@
package com.moyi.controlplane.auth;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public class AdminBootstrap implements ApplicationRunner {
private final AuthService authService;
private final Environment environment;
private final String account;
private final String password;
private final String displayName;
public AdminBootstrap(
AuthService authService,
Environment environment,
@Value("${moyi.bootstrap.admin-account}") String account,
@Value("${moyi.bootstrap.admin-password}") String password,
@Value("${moyi.bootstrap.admin-display-name}") String displayName
) {
this.authService = authService;
this.environment = environment;
this.account = account;
this.password = password;
this.displayName = displayName;
}
@Override
public void run(ApplicationArguments arguments) {
for (String profile : environment.getActiveProfiles()) {
if ("production".equals(profile) && "admin123".equals(password)) {
throw new IllegalStateException("ADMIN_PASSWORD must be changed in production");
}
}
authService.ensureAdmin(account, password, displayName);
}
}
@@ -0,0 +1,140 @@
package com.moyi.controlplane.auth;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseCookie;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class AuthController {
private static final String SESSION_COOKIE = "moyi_session";
private final AuthService authService;
private final int sessionTtlHours;
private final boolean secureCookie;
public AuthController(
AuthService authService,
@Value("${moyi.auth.session-ttl-hours}") int sessionTtlHours,
@Value("${moyi.auth.secure-cookie}") boolean secureCookie
) {
this.authService = authService;
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 InvitationRequest(String label, Integer maxUses, OffsetDateTime expiresAt) {}
@PostMapping("/auth/login")
public Map<String, Object> login(
@RequestBody LoginRequest input,
HttpServletRequest request,
HttpServletResponse response
) {
AuthService.AuthResult result = authService.login(input.account(), input.password(), meta(request));
response.addHeader(HttpHeaders.SET_COOKIE, sessionCookie(result.token(), Duration.ofHours(sessionTtlHours)).toString());
return Map.of("user", result.user());
}
@PostMapping("/auth/register")
public ResponseEntity<Map<String, Object>> register(
@RequestBody RegisterRequest input,
HttpServletRequest request,
HttpServletResponse response
) {
AuthService.AuthResult result = authService.register(
input.invitationCode(), input.account(), input.password(), input.displayName(), meta(request)
);
response.addHeader(HttpHeaders.SET_COOKIE, sessionCookie(result.token(), Duration.ofHours(sessionTtlHours)).toString());
return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("user", result.user()));
}
@PostMapping("/auth/logout")
public ResponseEntity<Void> logout(HttpServletRequest request, HttpServletResponse response) {
authService.logout(sessionToken(request), meta(request));
response.addHeader(HttpHeaders.SET_COOKIE, sessionCookie("", Duration.ZERO).toString());
return ResponseEntity.noContent().build();
}
@GetMapping("/auth/me")
public Map<String, Object> currentUser(HttpServletRequest request) {
return Map.of("user", authService.requireUser(sessionToken(request)));
}
@GetMapping("/admin/users")
public Map<String, Object> users(HttpServletRequest request) {
return Map.of("users", authService.listUsers(sessionToken(request)));
}
@GetMapping("/admin/invitations")
public Map<String, Object> invitations(HttpServletRequest request) {
return Map.of("invitations", authService.listInvitations(sessionToken(request)));
}
@PostMapping("/admin/invitations")
public ResponseEntity<Map<String, Object>> createInvitation(
@RequestBody InvitationRequest input,
HttpServletRequest request
) {
return ResponseEntity.status(HttpStatus.CREATED).body(authService.createInvitation(
sessionToken(request), input.label(), input.maxUses(), input.expiresAt(), meta(request)
));
}
@PostMapping("/admin/invitations/{id}/revoke")
public ResponseEntity<Void> revokeInvitation(@PathVariable UUID id, HttpServletRequest request) {
authService.revokeInvitation(sessionToken(request), id, meta(request));
return ResponseEntity.noContent().build();
}
@GetMapping("/admin/audit")
public Map<String, Object> audit(
@RequestParam(defaultValue = "100") int limit,
HttpServletRequest request
) {
return Map.of("events", authService.listAudit(sessionToken(request), limit));
}
private ResponseCookie sessionCookie(String value, Duration maxAge) {
return ResponseCookie.from(SESSION_COOKIE, value)
.httpOnly(true)
.secure(secureCookie)
.sameSite("Lax")
.path("/")
.maxAge(maxAge)
.build();
}
public static String sessionToken(HttpServletRequest request) {
Cookie[] cookies = request.getCookies();
if (cookies == null) return null;
for (Cookie cookie : cookies) {
if (SESSION_COOKIE.equals(cookie.getName())) return cookie.getValue();
}
return null;
}
public static AuthService.RequestMeta meta(HttpServletRequest request) {
return new AuthService.RequestMeta(request.getRemoteAddr(), request.getHeader(HttpHeaders.USER_AGENT));
}
}
@@ -0,0 +1,407 @@
package com.moyi.controlplane.auth;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.common.ApiException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Base64;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class AuthService {
private static final Pattern EMAIL = Pattern.compile("^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$");
private static final Pattern PHONE = Pattern.compile("^\\+?[0-9][0-9\\s-]{6,19}$");
private final JdbcTemplate jdbc;
private final PasswordHasher passwordHasher;
private final ObjectMapper objectMapper;
private final int sessionTtlHours;
public AuthService(
JdbcTemplate jdbc,
PasswordHasher passwordHasher,
ObjectMapper objectMapper,
@Value("${moyi.auth.session-ttl-hours}") int sessionTtlHours
) {
this.jdbc = jdbc;
this.passwordHasher = passwordHasher;
this.objectMapper = objectMapper;
this.sessionTtlHours = sessionTtlHours;
}
public record UserView(
UUID id,
String account,
String accountKind,
String displayName,
String role,
String status,
OffsetDateTime createdAt,
OffsetDateTime lastLoginAt
) {}
public record AuthResult(String token, UserView user) {}
public record RequestMeta(String ipAddress, String userAgent) {}
private record UserRow(
UUID id,
String account,
String accountKind,
String passwordHash,
String displayName,
String role,
String status,
OffsetDateTime createdAt,
OffsetDateTime lastLoginAt
) {}
@Transactional
public void ensureAdmin(String accountInput, String password, String displayName) {
String account = normalizeAccount(accountInput);
if (account.isBlank() || password.isBlank()) {
throw new ApiException("INVALID_ADMIN_CONFIG", "管理员初始配置无效", 500);
}
if (findUserByAccount(account) != null) {
return;
}
OffsetDateTime now = now();
jdbc.update(
"INSERT INTO users (id, account, account_kind, password_hash, display_name, role, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'admin', 'active', ?, ?)",
UUID.randomUUID(), account, accountKind(account), passwordHasher.hash(password),
displayName == null || displayName.isBlank() ? "平台管理员" : displayName.trim(), now, now
);
}
public AuthResult login(String accountInput, String password, RequestMeta meta) {
UserRow user = findUserByAccount(normalizeAccount(accountInput));
if (user == null || !passwordHasher.matches(password, user.passwordHash())) {
throw new ApiException("INVALID_CREDENTIALS", "账号或密码错误", 401);
}
if (!"active".equals(user.status())) {
throw new ApiException("ACCOUNT_DISABLED", "账号已停用", 403);
}
OffsetDateTime loginAt = now();
jdbc.update("UPDATE users SET last_login_at = ?, updated_at = ? WHERE id = ?", loginAt, loginAt, user.id());
audit("user.logged_in", user.id(), meta, Map.of());
return new AuthResult(createSession(user.id(), meta), toView(user, loginAt));
}
@Transactional
public AuthResult register(
String invitationCode,
String accountInput,
String password,
String displayName,
RequestMeta meta
) {
String account = normalizeAccount(accountInput);
validatePublicAccount(account);
if (password == null || password.length() < 8) {
throw new ApiException("WEAK_PASSWORD", "密码至少需要 8 位");
}
if (invitationCode == null || invitationCode.isBlank()) {
throw new ApiException("INVITATION_REQUIRED", "第一版注册需要邀请码");
}
if (findUserByAccount(account) != null) {
throw new ApiException("ACCOUNT_EXISTS", "账号已注册", 409);
}
List<Map<String, Object>> invitations = jdbc.queryForList(
"SELECT id, max_uses, used_count, expires_at, disabled_at FROM invitation_codes WHERE code_hash = ? FOR UPDATE",
hashSecret(invitationCode.trim())
);
if (invitations.isEmpty()) {
throw new ApiException("INVITATION_INVALID", "邀请码无效或已失效", 403);
}
Map<String, Object> invitation = invitations.getFirst();
OffsetDateTime now = now();
OffsetDateTime expiresAt = toOffsetDateTime(invitation.get("expires_at"));
if (invitation.get("disabled_at") != null
|| (expiresAt != null && !expiresAt.isAfter(now))
|| ((Number) invitation.get("used_count")).intValue() >= ((Number) invitation.get("max_uses")).intValue()) {
throw new ApiException("INVITATION_EXHAUSTED", "邀请码无效、已用尽或账号已注册", 403);
}
UUID userId = UUID.randomUUID();
String name = displayName == null || displayName.isBlank() ? defaultDisplayName(account) : displayName.trim();
jdbc.update(
"INSERT INTO users (id, account, account_kind, password_hash, display_name, role, status, created_at, updated_at) VALUES (?, ?, ?, ?, ?, 'user', 'active', ?, ?)",
userId, account, accountKind(account), passwordHasher.hash(password), name, now, now
);
UUID invitationId = (UUID) invitation.get("id");
jdbc.update("UPDATE invitation_codes SET used_count = used_count + 1 WHERE id = ?", invitationId);
jdbc.update("INSERT INTO invitation_redemptions (invitation_id, user_id, redeemed_at) VALUES (?, ?, ?)", invitationId, userId, now);
UserRow user = findUserById(userId);
audit("user.registered", userId, meta, Map.of("invitationId", invitationId));
return new AuthResult(createSession(userId, meta), toView(user, null));
}
public UserView requireUser(String token) {
return toView(requireUserRow(token), null);
}
public UserView requireAdmin(String token) {
UserRow user = requireUserRow(token);
if (!"admin".equals(user.role())) {
throw new ApiException("FORBIDDEN", "需要管理员权限", 403);
}
return toView(user, null);
}
public void logout(String token, RequestMeta meta) {
if (token == null || token.isBlank()) {
return;
}
List<Map<String, Object>> sessions = jdbc.queryForList(
"SELECT id, user_id FROM auth_sessions WHERE token_hash = ? AND revoked_at IS NULL",
hashSecret(token)
);
if (sessions.isEmpty()) {
return;
}
Map<String, Object> session = sessions.getFirst();
jdbc.update("UPDATE auth_sessions SET revoked_at = ? WHERE id = ?", now(), session.get("id"));
audit("user.logged_out", (UUID) session.get("user_id"), meta, Map.of());
}
public List<UserView> listUsers(String token) {
requireAdmin(token);
return jdbc.query("SELECT * FROM users ORDER BY created_at DESC", this::mapUser).stream().map(user -> toView(user, null)).toList();
}
@Transactional
public Map<String, Object> createInvitation(
String token,
String label,
Integer maxUses,
OffsetDateTime expiresAt,
RequestMeta meta
) {
UserView admin = requireAdmin(token);
String code = "moyi_" + randomToken(12);
UUID id = UUID.randomUUID();
OffsetDateTime createdAt = now();
int allowedUses = maxUses == null ? 1 : Math.max(1, maxUses);
jdbc.update(
"INSERT INTO invitation_codes (id, code_hash, code_prefix, label, max_uses, used_count, expires_at, created_by, created_at) VALUES (?, ?, ?, ?, ?, 0, ?, ?, ?)",
id, hashSecret(code), code.substring(0, Math.min(code.length(), 10)),
label == null || label.isBlank() ? "内测邀请码" : label.trim(), allowedUses, expiresAt, admin.id(), createdAt
);
audit("invitation.created", admin.id(), meta, Map.of("invitationId", id));
return Map.of(
"code", code,
"invitation", invitationView(id, code.substring(0, Math.min(code.length(), 10)),
label == null || label.isBlank() ? "内测邀请码" : label.trim(), allowedUses, 0,
expiresAt, null, admin.id(), createdAt)
);
}
public List<Map<String, Object>> listInvitations(String token) {
requireAdmin(token);
return jdbc.query(
"SELECT id, code_prefix, label, max_uses, used_count, expires_at, disabled_at, created_by, created_at FROM invitation_codes ORDER BY created_at DESC",
(resultSet, rowNumber) -> invitationView(
resultSet.getObject("id", UUID.class), resultSet.getString("code_prefix"), resultSet.getString("label"),
resultSet.getInt("max_uses"), resultSet.getInt("used_count"),
resultSet.getObject("expires_at", OffsetDateTime.class), resultSet.getObject("disabled_at", OffsetDateTime.class),
resultSet.getObject("created_by", UUID.class), resultSet.getObject("created_at", OffsetDateTime.class)
)
);
}
public void revokeInvitation(String token, UUID invitationId, RequestMeta meta) {
UserView admin = requireAdmin(token);
int changed = jdbc.update(
"UPDATE invitation_codes SET disabled_at = ? WHERE id = ? AND disabled_at IS NULL",
now(), invitationId
);
if (changed == 0) {
throw new ApiException("INVITATION_NOT_FOUND", "邀请码不存在或已停用", 404);
}
audit("invitation.revoked", admin.id(), meta, Map.of("invitationId", invitationId));
}
public List<Map<String, Object>> listAudit(String token, int requestedLimit) {
requireAdmin(token);
int limit = Math.min(Math.max(requestedLimit, 1), 200);
return jdbc.query(
"SELECT id, actor_user_id, event_type, target_type, target_id, ip_address, user_agent, details, created_at FROM auth_audit_log ORDER BY created_at DESC LIMIT ?",
(resultSet, rowNumber) -> {
Map<String, Object> event = new java.util.LinkedHashMap<>();
event.put("id", String.valueOf(resultSet.getLong("id")));
UUID actorUserId = resultSet.getObject("actor_user_id", UUID.class);
if (actorUserId != null) event.put("actorUserId", actorUserId);
event.put("eventType", resultSet.getString("event_type"));
String targetType = resultSet.getString("target_type");
String targetId = resultSet.getString("target_id");
String ipAddress = resultSet.getString("ip_address");
if (targetType != null) event.put("targetType", targetType);
if (targetId != null) event.put("targetId", targetId);
if (ipAddress != null) event.put("ipAddress", ipAddress);
event.put("details", readJson(resultSet.getString("details")));
event.put("createdAt", resultSet.getObject("created_at", OffsetDateTime.class));
return event;
},
limit
);
}
public void audit(String eventType, UUID actorUserId, RequestMeta meta, Map<String, Object> details) {
jdbc.update(
"INSERT INTO auth_audit_log (actor_user_id, event_type, ip_address, user_agent, details) VALUES (?, ?, CAST(? AS inet), ?, CAST(? AS jsonb))",
actorUserId, eventType, blankToNull(meta.ipAddress()), blankToNull(meta.userAgent()), writeJson(details)
);
}
private UserRow requireUserRow(String token) {
if (token == null || token.isBlank()) {
throw new ApiException("UNAUTHENTICATED", "请先登录", 401);
}
List<UserRow> users = jdbc.query(
"SELECT u.* FROM auth_sessions s JOIN users u ON u.id = s.user_id WHERE s.token_hash = ? AND s.revoked_at IS NULL AND s.expires_at > now() AND u.status = 'active'",
this::mapUser,
hashSecret(token)
);
if (users.isEmpty()) {
throw new ApiException("UNAUTHENTICATED", "请先登录", 401);
}
return users.getFirst();
}
private String createSession(UUID userId, RequestMeta meta) {
String token = randomToken(32);
OffsetDateTime createdAt = now();
jdbc.update(
"INSERT INTO auth_sessions (id, token_hash, user_id, expires_at, created_at, last_seen_at, user_agent, ip_address) VALUES (?, ?, ?, ?, ?, ?, ?, CAST(? AS inet))",
UUID.randomUUID(), hashSecret(token), userId, createdAt.plusHours(sessionTtlHours), createdAt, createdAt,
blankToNull(meta.userAgent()), blankToNull(meta.ipAddress())
);
return token;
}
private UserRow findUserByAccount(String account) {
try {
return jdbc.queryForObject("SELECT * FROM users WHERE account = ?", this::mapUser, account);
} catch (EmptyResultDataAccessException exception) {
return null;
}
}
private UserRow findUserById(UUID id) {
return jdbc.queryForObject("SELECT * FROM users WHERE id = ?", this::mapUser, id);
}
private UserRow mapUser(ResultSet resultSet, int rowNumber) throws SQLException {
return new UserRow(
resultSet.getObject("id", UUID.class),
resultSet.getString("account"),
resultSet.getString("account_kind"),
resultSet.getString("password_hash"),
resultSet.getString("display_name"),
resultSet.getString("role"),
resultSet.getString("status"),
resultSet.getObject("created_at", OffsetDateTime.class),
resultSet.getObject("last_login_at", OffsetDateTime.class)
);
}
private UserView toView(UserRow user, OffsetDateTime lastLoginOverride) {
return new UserView(
user.id(), user.account(), user.accountKind(), user.displayName(), user.role(), user.status(),
user.createdAt(), lastLoginOverride == null ? user.lastLoginAt() : lastLoginOverride
);
}
private Map<String, Object> invitationView(
UUID id, String prefix, String label, int maxUses, int usedCount, OffsetDateTime expiresAt,
OffsetDateTime disabledAt, UUID createdBy, OffsetDateTime createdAt
) {
Map<String, Object> result = new java.util.LinkedHashMap<>();
result.put("id", id);
result.put("codePrefix", prefix);
result.put("label", label);
result.put("maxUses", maxUses);
result.put("usedCount", usedCount);
if (expiresAt != null) result.put("expiresAt", expiresAt);
if (disabledAt != null) result.put("disabledAt", disabledAt);
result.put("createdBy", createdBy);
result.put("createdAt", createdAt);
return result;
}
private Map<String, Object> readJson(String value) {
try {
return objectMapper.readValue(value, new TypeReference<>() {});
} catch (JsonProcessingException exception) {
return Map.of();
}
}
private String writeJson(Map<String, Object> value) {
try {
return objectMapper.writeValueAsString(value);
} catch (JsonProcessingException exception) {
throw new ApiException("JSON_ENCODING_FAILED", "无法记录审计信息", 500);
}
}
private void validatePublicAccount(String account) {
if (!EMAIL.matcher(account).matches() && !PHONE.matcher(account).matches()) {
throw new ApiException("INVALID_ACCOUNT", "请输入有效的邮箱或手机号");
}
}
private String normalizeAccount(String account) {
String normalized = account == null ? "" : account.trim().toLowerCase();
return normalized.contains("@") ? normalized : normalized.replaceAll("[\\s-]", "");
}
private String accountKind(String account) {
if (account.contains("@")) return "email";
return PHONE.matcher(account).matches() ? "phone" : "username";
}
private String defaultDisplayName(String account) {
int separator = account.indexOf('@');
return separator > 0 ? account.substring(0, separator) : "MOYI 用户";
}
private String randomToken(int byteCount) {
byte[] bytes = new byte[byteCount];
new java.security.SecureRandom().nextBytes(bytes);
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
public static String hashSecret(String value) {
try {
return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (NoSuchAlgorithmException exception) {
throw new IllegalStateException(exception);
}
}
private OffsetDateTime now() {
return OffsetDateTime.now(ZoneOffset.UTC);
}
private OffsetDateTime toOffsetDateTime(Object value) {
return value instanceof OffsetDateTime dateTime ? dateTime : null;
}
private String blankToNull(String value) {
return value == null || value.isBlank() ? null : value;
}
}
@@ -0,0 +1,68 @@
package com.moyi.controlplane.auth;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class PasswordHasher {
private static final int ITERATIONS = 210_000;
private static final int KEY_LENGTH = 256;
private final SecureRandom secureRandom = new SecureRandom();
private final String pepper;
public PasswordHasher(@Value("${moyi.auth.password-pepper}") String pepper) {
this.pepper = pepper;
}
public String hash(String password) {
byte[] salt = new byte[16];
secureRandom.nextBytes(salt);
byte[] result = derive(password, salt, ITERATIONS, KEY_LENGTH);
return "pbkdf2$" + ITERATIONS + "$" + Base64.getUrlEncoder().withoutPadding().encodeToString(salt)
+ "$" + Base64.getUrlEncoder().withoutPadding().encodeToString(result);
}
public boolean matches(String password, String encoded) {
try {
String[] parts = encoded.split("\\$");
if (parts.length != 4 || !"pbkdf2".equals(parts[0])) {
return false;
}
int iterations = Integer.parseInt(parts[1]);
byte[] salt = Base64.getUrlDecoder().decode(parts[2]);
byte[] expected = Base64.getUrlDecoder().decode(parts[3]);
byte[] actual = derive(password, salt, iterations, expected.length * 8);
return MessageDigest.isEqual(expected, actual);
} catch (RuntimeException exception) {
return false;
}
}
private byte[] derive(String password, byte[] salt, int iterations, int keyLength) {
char[] value = (password + pepper).toCharArray();
PBEKeySpec specification = new PBEKeySpec(value, salt, iterations, keyLength);
try {
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(specification).getEncoded();
} catch (Exception exception) {
throw new IllegalStateException("Password hashing is unavailable", exception);
} finally {
specification.clearPassword();
ArraysSupport.clear(value);
}
}
private static final class ArraysSupport {
private ArraysSupport() {
}
static void clear(char[] value) {
java.util.Arrays.fill(value, '\0');
}
}
}
@@ -0,0 +1,118 @@
package com.moyi.controlplane.catalog;
import com.moyi.controlplane.auth.AuthController;
import com.moyi.controlplane.auth.AuthService;
import java.util.List;
import java.util.Map;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class CatalogController {
private final CatalogService catalogService;
private final AuthService authService;
public CatalogController(CatalogService catalogService, AuthService authService) {
this.catalogService = catalogService;
this.authService = authService;
}
@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));
}
@GetMapping("/overview")
public Map<String, Object> overview(@jakarta.servlet.http.HttpServletRequest request) {
return catalogService.overview(AuthController.sessionToken(request), authService);
}
@GetMapping("/projects")
public Map<String, Object> projects(@jakarta.servlet.http.HttpServletRequest request) {
return Map.of("projects", catalogService.listProjects(AuthController.sessionToken(request), authService));
}
@PostMapping("/projects")
public ResponseEntity<Map<String, Object>> createProject(
@RequestBody Map<String, Object> input,
jakarta.servlet.http.HttpServletRequest request
) {
return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("project", catalogService.createProject(
AuthController.sessionToken(request), input, authService
)));
}
@GetMapping("/keys")
public Map<String, Object> keys(jakarta.servlet.http.HttpServletRequest request) {
return Map.of("keys", catalogService.listKeys(AuthController.sessionToken(request), authService));
}
@PostMapping("/keys")
public ResponseEntity<Map<String, Object>> createKey(
@RequestBody Map<String, Object> input,
jakarta.servlet.http.HttpServletRequest request
) {
return ResponseEntity.status(HttpStatus.CREATED).body(catalogService.createKey(
AuthController.sessionToken(request), input, authService
));
}
@PostMapping("/keys/{id}/models")
public Map<String, Object> updateKeyModels(
@PathVariable String id,
@RequestBody Map<String, Object> input,
jakarta.servlet.http.HttpServletRequest request
) {
return catalogService.updateKeyModels(
AuthController.sessionToken(request), id, input.get("modelIds") instanceof List<?> values
? values.stream().map(String::valueOf).toList() : List.of(), authService
);
}
@PostMapping("/keys/{id}/revoke")
public ResponseEntity<Void> revokeKey(@PathVariable String id, jakarta.servlet.http.HttpServletRequest request) {
catalogService.revokeKey(AuthController.sessionToken(request), id, authService);
return ResponseEntity.noContent().build();
}
@GetMapping("/admin/providers")
public Map<String, Object> adminProviders(jakarta.servlet.http.HttpServletRequest request) {
authService.requireAdmin(AuthController.sessionToken(request));
return Map.of("providers", catalogService.listProviders(true));
}
@PostMapping("/admin/providers")
public ResponseEntity<Map<String, Object>> createProvider(
@RequestBody Map<String, Object> input,
jakarta.servlet.http.HttpServletRequest request
) {
return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("provider", catalogService.createProvider(
input, AuthController.sessionToken(request), authService
)));
}
@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));
}
@PostMapping("/admin/models")
public ResponseEntity<Map<String, Object>> createModel(
@RequestBody Map<String, Object> input,
jakarta.servlet.http.HttpServletRequest request
) {
return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("model", catalogService.createModel(
input, AuthController.sessionToken(request), authService
)));
}
}
@@ -0,0 +1,372 @@
package com.moyi.controlplane.catalog;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.moyi.controlplane.auth.AuthService;
import com.moyi.controlplane.auth.AuthService.UserView;
import com.moyi.controlplane.common.ApiException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class CatalogService {
private static final List<String> MODEL_TYPES = List.of("text", "code", "multimodal", "image", "audio", "video", "embedding", "3d");
private static final List<String> CALL_MODES = List.of("sync", "stream", "async");
private static final List<String> PROTOCOLS = List.of("openai-compatible", "http", "sdk");
private static final List<String> SOURCE_TYPES = List.of("official", "relay", "self-hosted", "custom");
private final JdbcTemplate jdbc;
private final ObjectMapper objectMapper;
private final SecureRandom secureRandom = new SecureRandom();
public CatalogService(JdbcTemplate jdbc, ObjectMapper objectMapper) {
this.jdbc = jdbc;
this.objectMapper = objectMapper;
}
public List<Map<String, Object>> listProviders(boolean includeDisabled) {
String statusClause = includeDisabled ? "" : " WHERE status = 'active'";
return jdbc.query("SELECT * FROM model_providers" + statusClause + " ORDER BY name", this::mapProvider);
}
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);
}
@Transactional
public Map<String, Object> createProvider(Map<String, Object> input, String token, AuthService auth) {
UserView admin = auth.requireAdmin(token);
String code = required(input, "code").toLowerCase();
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)) {
throw new ApiException("INVALID_PROVIDER", "供应商标识、协议或来源类型无效");
}
String id = UUID.randomUUID().toString();
String baseUrl = optional(input, "baseUrl", null);
String description = optional(input, "description", "");
String credentialType = optional(input, "credentialType", null);
String secret = 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, null, masked
);
auth.audit("provider.created", admin.id(), new AuthService.RequestMeta(null, null), Map.of("providerId", id));
return findProvider(id);
}
@Transactional
public Map<String, Object> createModel(Map<String, Object> input, String token, AuthService auth) {
UserView admin = auth.requireAdmin(token);
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");
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 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"));
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");
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')",
id, providerId, modelKey, sourceLabel, publicName, upstreamModel, type, mode, description,
inputTypes, outputTypes, capabilities, pricing, priority, maxConcurrency
);
auth.audit("model.created", admin.id(), new AuthService.RequestMeta(null, null), Map.of("modelId", id));
return findModel(id);
}
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());
}
@Transactional
public Map<String, Object> createProject(String token, Map<String, Object> input, AuthService auth) {
UserView user = auth.requireUser(token);
String name = required(input, "name");
if (name.length() > 80) throw new ApiException("INVALID_PROJECT_NAME", "项目名称不能超过 80 个字符");
String id = "project_" + UUID.randomUUID().toString().replace("-", "").substring(0, 20);
OffsetDateTime now = now();
jdbc.update(
"INSERT INTO model_projects (id, owner_user_id, name, description, status, created_at, updated_at) VALUES (?, ?, ?, ?, 'active', ?, ?)",
id, user.id(), name, optional(input, "description", ""), now, now
);
return findProject(id);
}
public List<Map<String, Object>> listKeys(String token, AuthService auth) {
UserView user = auth.requireUser(token);
return jdbc.query("SELECT * FROM platform_api_keys WHERE user_id = ? ORDER BY created_at DESC", this::mapApiKey, user.id());
}
@Transactional
public Map<String, Object> createKey(String token, Map<String, Object> input, AuthService auth) {
UserView user = auth.requireUser(token);
String name = optional(input, "name", "默认开发 Key");
if (name.length() > 80) throw new ApiException("INVALID_KEY_NAME", "Key 名称不能超过 80 个字符");
String projectId = optional(input, "projectId", null);
if (projectId != null && !ownsProject(projectId, user.id())) throw new ApiException("PROJECT_NOT_FOUND", "项目不存在或无权访问", 404);
List<String> scopes = stringList(input.get("scopes"));
if (scopes.isEmpty()) scopes = List.of("invoke");
List<String> modelIds = stringList(input.get("modelIds"));
for (String modelId : modelIds) if (findActiveModel(modelId) == null) throw new ApiException("MODEL_NOT_FOUND", "模型不存在或已下线", 404);
String plaintext = "sk-moyi-" + randomToken(24);
String id = UUID.randomUUID().toString();
OffsetDateTime now = now();
jdbc.update(
"INSERT INTO platform_api_keys (id, user_id, project_id, name, key_prefix, key_hash, scopes, model_ids, status, created_at) VALUES (?, ?, ?, ?, ?, ?, CAST(? AS jsonb), CAST(? AS jsonb), 'active', ?)",
id, user.id(), projectId, name, plaintext.substring(0, 16), sha256(plaintext), writeJson(scopes), writeJson(modelIds), now
);
Map<String, Object> result = new LinkedHashMap<>();
result.put("key", plaintext);
result.put("apiKey", findKey(id));
return result;
}
@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);
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));
}
@Transactional
public void revokeKey(String token, String keyId, AuthService auth) {
UserView user = auth.requireUser(token);
int changed = jdbc.update("UPDATE platform_api_keys SET status = 'disabled', revoked_at = ? WHERE id = ? AND user_id = ? AND status = 'active'", now(), UUID.fromString(keyId), user.id());
if (changed == 0) throw new ApiException("KEY_NOT_FOUND", "Key 不存在或已停用", 404);
}
public Map<String, Object> overview(String token, AuthService auth) {
UserView user = auth.requireUser(token);
Integer callsToday = jdbc.queryForObject("SELECT COUNT(*) FROM usage_events WHERE user_id = ? AND event_kind = 'call' AND created_at >= CURRENT_DATE", Integer.class, user.id());
Integer callsMonth = jdbc.queryForObject("SELECT COUNT(*) FROM usage_events WHERE user_id = ? AND event_kind = 'call' AND created_at >= date_trunc('month', now())", Integer.class, user.id());
Integer tasks = jdbc.queryForObject("SELECT COUNT(*) FROM usage_events WHERE user_id = ? AND event_kind = 'task'", Integer.class, user.id());
Map<String, Object> result = new LinkedHashMap<>();
result.put("generatedAt", now());
result.put("callsToday", callsToday == null ? 0 : callsToday);
result.put("callsThisMonth", callsMonth == null ? 0 : callsMonth);
result.put("asyncTasks", tasks == null ? 0 : tasks);
result.put("tasks", Map.of("queued", 0, "running", 0, "succeeded", 0, "failed", 0));
result.put("series", List.of());
result.put("ledger", List.of());
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()));
} catch (EmptyResultDataAccessException exception) {
return null;
}
}
public Map<String, Object> activeModel(String id) {
return findActiveModel(id);
}
public boolean keyCanInvoke(Map<String, Object> key, String modelId) {
if (key == null || !"active".equals(key.get("status"))) return false;
Object scopes = key.get("scopes");
Object modelIds = key.get("modelIds");
return scopes instanceof List<?> scopeList && scopeList.contains("invoke")
&& modelIds instanceof List<?> modelList && modelList.contains(modelId);
}
public void touchKey(Map<String, Object> key) {
if (key != null && key.get("id") != null) jdbc.update("UPDATE platform_api_keys SET last_used_at = ? WHERE id = ?", now(), UUID.fromString(String.valueOf(key.get("id"))));
}
public String providerIdForModel(String modelId) {
try {
return jdbc.queryForObject("SELECT provider_id FROM model_catalog WHERE id = ? AND status = 'active'", String.class, modelId);
} catch (EmptyResultDataAccessException exception) {
return null;
}
}
private Map<String, Object> findProvider(String id) {
try { return jdbc.queryForObject("SELECT * FROM model_providers WHERE id = ?", this::mapProvider, id); }
catch (EmptyResultDataAccessException exception) { return null; }
}
private Map<String, Object> findModel(String id) {
try { return jdbc.queryForObject("SELECT * FROM model_catalog WHERE id = ?", this::mapModel, id); }
catch (EmptyResultDataAccessException exception) { return null; }
}
private Map<String, Object> findActiveModel(String id) {
try { return jdbc.queryForObject("SELECT * FROM model_catalog WHERE id = ? AND status = 'active'", this::mapModel, id); }
catch (EmptyResultDataAccessException exception) { return null; }
}
private Map<String, Object> findProject(String id) {
try { return jdbc.queryForObject("SELECT * FROM model_projects WHERE id = ?", this::mapProject, id); }
catch (EmptyResultDataAccessException exception) { return null; }
}
private Map<String, Object> findKey(String id) {
return jdbc.queryForObject("SELECT * FROM platform_api_keys WHERE id = ?", this::mapApiKey, UUID.fromString(id));
}
private boolean ownsProject(String projectId, UUID userId) {
Integer count = jdbc.queryForObject("SELECT COUNT(*) FROM model_projects WHERE id = ? AND owner_user_id = ? AND status = 'active'", Integer.class, projectId, userId);
return count != null && count > 0;
}
private Map<String, Object> mapProvider(ResultSet resultSet, int rowNumber) throws SQLException {
Map<String, Object> provider = new LinkedHashMap<>();
provider.put("id", resultSet.getString("id"));
provider.put("code", resultSet.getString("code"));
provider.put("name", resultSet.getString("name"));
provider.put("protocol", resultSet.getString("protocol"));
provider.put("sourceType", resultSet.getString("source_type"));
putIfNotNull(provider, "baseUrl", resultSet.getString("base_url"));
putIfNotNull(provider, "description", resultSet.getString("description"));
putIfNotNull(provider, "credentialType", resultSet.getString("credential_type"));
putIfNotNull(provider, "credentialMasked", resultSet.getString("credential_masked"));
provider.put("status", resultSet.getString("status"));
provider.put("createdAt", resultSet.getObject("created_at", OffsetDateTime.class));
return provider;
}
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("providerId", resultSet.getString("provider_id"));
putIfNotNull(model, "modelKey", resultSet.getString("model_key"));
putIfNotNull(model, "sourceLabel", resultSet.getString("source_label"));
model.put("publicName", resultSet.getString("public_name"));
model.put("upstreamModel", resultSet.getString("upstream_model"));
model.put("type", resultSet.getString("model_type"));
model.put("mode", resultSet.getString("call_mode"));
model.put("description", resultSet.getString("description"));
model.put("inputTypes", readList(resultSet.getString("input_types")));
model.put("outputTypes", readList(resultSet.getString("output_types")));
model.put("capabilities", readMap(resultSet.getString("capabilities")));
putIfNotNull(model, "pricing", readOptionalMap(resultSet.getString("pricing")));
putIfNotNull(model, "priority", resultSet.getObject("priority"));
putIfNotNull(model, "maxConcurrency", resultSet.getObject("max_concurrency"));
model.put("status", resultSet.getString("status"));
model.put("createdAt", resultSet.getObject("created_at", OffsetDateTime.class));
return model;
}
private Map<String, Object> mapProject(ResultSet resultSet, int rowNumber) throws SQLException {
Map<String, Object> project = new LinkedHashMap<>();
project.put("id", resultSet.getString("id"));
project.put("ownerUserId", resultSet.getObject("owner_user_id", UUID.class));
project.put("name", resultSet.getString("name"));
project.put("description", resultSet.getString("description"));
project.put("status", resultSet.getString("status"));
project.put("createdAt", resultSet.getObject("created_at", OffsetDateTime.class));
return project;
}
private Map<String, Object> mapApiKey(ResultSet resultSet, int rowNumber) throws SQLException {
Map<String, Object> key = new LinkedHashMap<>();
UUID id = resultSet.getObject("id", UUID.class);
String projectId = resultSet.getString("project_id");
key.put("id", id);
key.put("scopeType", projectId == null ? "personal" : "project");
putIfNotNull(key, "projectId", projectId);
key.put("name", resultSet.getString("name"));
key.put("keyPrefix", resultSet.getString("key_prefix"));
key.put("scopes", readList(resultSet.getString("scopes")));
key.put("modelIds", readList(resultSet.getString("model_ids")));
key.put("status", resultSet.getString("status"));
key.put("createdAt", resultSet.getObject("created_at", OffsetDateTime.class));
putIfNotNull(key, "lastUsedAt", resultSet.getObject("last_used_at", OffsetDateTime.class));
putIfNotNull(key, "revokedAt", resultSet.getObject("revoked_at", OffsetDateTime.class));
return key;
}
private String required(Map<String, Object> input, String key) {
String value = optional(input, key, "");
if (value.isBlank()) throw new ApiException("INVALID_INPUT", key + " 不能为空");
return value;
}
private String optional(Map<String, Object> input, String key, String fallback) {
Object value = input == null ? null : input.get(key);
return value == null ? fallback : String.valueOf(value).trim();
}
private Integer integerOrNull(Object value) {
if (value == null || String.valueOf(value).isBlank()) return null;
try { return Integer.valueOf(String.valueOf(value)); }
catch (NumberFormatException exception) { throw new ApiException("INVALID_NUMBER", "数值格式无效"); }
}
private List<String> stringList(Object value) {
if (value == null) return new ArrayList<>();
if (value instanceof List<?> list) return list.stream().map(String::valueOf).map(String::trim).filter(item -> !item.isBlank()).distinct().toList();
return List.of(String.valueOf(value));
}
private String jsonArray(Object value) { return writeJson(stringList(value)); }
private String jsonObject(Object value) { return value instanceof Map<?, ?> ? writeJson(value) : "{}"; }
private String jsonObjectOrNull(Object value) { return value instanceof Map<?, ?> ? writeJson(value) : null; }
private String writeJson(Object value) {
try { return objectMapper.writeValueAsString(value); }
catch (JsonProcessingException exception) { throw new ApiException("INVALID_JSON", "JSON字段格式无效"); }
}
private List<String> readList(String value) {
try { return value == null ? List.of() : objectMapper.readValue(value, new TypeReference<>() {}); }
catch (JsonProcessingException exception) { return List.of(); }
}
private Map<String, Object> readMap(String value) {
try { return value == null ? Map.of() : objectMapper.readValue(value, new TypeReference<>() {}); }
catch (JsonProcessingException exception) { return Map.of(); }
}
private Map<String, Object> readOptionalMap(String value) { return value == null ? null : readMap(value); }
private void putIfNotNull(Map<String, Object> target, String key, Object value) { if (value != null) target.put(key, value); }
private String mask(String value) { return value.length() <= 8 ? "••••••••" : value.substring(0, 4) + "••••••••" + value.substring(value.length() - 4); }
private String randomToken(int byteCount) { byte[] bytes = new byte[byteCount]; secureRandom.nextBytes(bytes); return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes); }
private String sha256(String value) { try { return java.util.HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8))); } catch (Exception exception) { throw new IllegalStateException(exception); } }
private OffsetDateTime now() { return OffsetDateTime.now(ZoneOffset.UTC); }
}
@@ -0,0 +1,24 @@
package com.moyi.controlplane.common;
public class ApiException extends RuntimeException {
private final String code;
private final int status;
public ApiException(String code, String message, int status) {
super(message);
this.code = code;
this.status = status;
}
public ApiException(String code, String message) {
this(code, message, 400);
}
public String getCode() {
return code;
}
public int getStatus() {
return status;
}
}
@@ -0,0 +1,34 @@
package com.moyi.controlplane.common;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class ApiExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);
@ExceptionHandler(ApiException.class)
public ResponseEntity<Map<String, Object>> handleApiException(ApiException exception) {
return ResponseEntity.status(exception.getStatus()).body(error(exception.getCode(), exception.getMessage()));
}
@ExceptionHandler(DataIntegrityViolationException.class)
public ResponseEntity<Map<String, Object>> handleConflict(DataIntegrityViolationException exception) {
return ResponseEntity.status(409).body(error("DATA_CONFLICT", "数据已存在或关联关系无效"));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Map<String, Object>> handleUnexpected(Exception exception) {
log.error("Unhandled API error", exception);
return ResponseEntity.internalServerError().body(error("INTERNAL_ERROR", "服务暂时不可用"));
}
private Map<String, Object> error(String code, String message) {
return Map.of("error", Map.of("code", code, "message", message));
}
}
@@ -0,0 +1,29 @@
package com.moyi.controlplane.config;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
private final String[] allowedOrigins;
public WebConfig(@Value("${moyi.web.cors-origins}") String allowedOrigins) {
this.allowedOrigins = Arrays.stream(allowedOrigins.split(","))
.map(String::trim)
.filter(origin -> !origin.isBlank())
.toArray(String[]::new);
}
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins(allowedOrigins)
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
.allowedHeaders("Content-Type", "Authorization")
.allowCredentials(true)
.maxAge(3600);
}
}
@@ -0,0 +1,84 @@
package com.moyi.controlplane.gateway;
import com.moyi.controlplane.catalog.CatalogService;
import com.moyi.controlplane.common.ApiException;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/v1")
public class GatewayController {
private final CatalogService catalogService;
public GatewayController(CatalogService catalogService) {
this.catalogService = catalogService;
}
@GetMapping("/models")
public Map<String, Object> models(@RequestHeader(value = "Authorization", required = false) String authorization) {
Map<String, Object> key = requireKey(authorization);
List<Map<String, Object>> data = catalogService.listModels(false).stream()
.filter(model -> catalogService.keyCanInvoke(key, String.valueOf(model.get("id"))))
.map(model -> {
Map<String, Object> item = new LinkedHashMap<>();
item.put("id", model.get("id"));
item.put("object", "model");
item.put("owned_by", model.get("providerId"));
item.put("type", model.get("type"));
item.put("mode", model.get("mode"));
return item;
}).toList();
catalogService.touchKey(key);
return Map.of("object", "list", "data", data);
}
@PostMapping("/chat/completions")
public ResponseEntity<Map<String, Object>> chatCompletions(
@RequestHeader(value = "Authorization", required = false) String authorization,
@RequestBody Map<String, Object> input
) {
Map<String, Object> key = requireKey(authorization);
String modelId = String.valueOf(input.getOrDefault("model", ""));
Map<String, Object> model = catalogService.activeModel(modelId);
if (model == null) throw new ApiException("MODEL_NOT_FOUND", "模型不存在或已下线", 404);
if (!catalogService.keyCanInvoke(key, modelId)) throw new ApiException("MODEL_FORBIDDEN", "当前 Key 无权调用该模型", 403);
if ("async".equals(model.get("mode"))) throw new ApiException("ASYNC_MODEL", "该模型需要使用异步任务接口", 400);
String prompt = extractPrompt(input.get("messages"));
String content = "MOYI Java Mock 已收到:" + (prompt.isBlank() ? "(空消息)" : prompt);
catalogService.touchKey(key);
Map<String, Object> response = new LinkedHashMap<>();
response.put("id", "chatcmpl-" + UUID.randomUUID().toString().replace("-", "").substring(0, 12));
response.put("object", "chat.completion");
response.put("created", Instant.now().getEpochSecond());
response.put("model", modelId);
response.put("choices", List.of(Map.of("index", 0, "message", Map.of("role", "assistant", "content", content), "finish_reason", "stop")));
response.put("usage", Map.of("prompt_tokens", prompt.length(), "completion_tokens", content.length(), "total_tokens", prompt.length() + content.length()));
return ResponseEntity.status(HttpStatus.OK).body(response);
}
private Map<String, Object> requireKey(String authorization) {
if (authorization == null || !authorization.startsWith("Bearer ")) throw new ApiException("UNAUTHENTICATED", "请提供有效的 API Key", 401);
Map<String, Object> key = catalogService.authenticateKey(authorization.substring(7));
if (key == null) throw new ApiException("INVALID_API_KEY", "API Key 无效或已停用", 401);
return key;
}
private String extractPrompt(Object messages) {
if (!(messages instanceof List<?> list)) return "";
return list.stream().filter(item -> item instanceof Map<?, ?>).map(item -> {
Object content = ((Map<?, ?>) item).get("content");
return content == null ? "" : String.valueOf(content);
}).reduce((left, right) -> left + "\n" + right).orElse("");
}
}