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

@@ -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');
}
}
}