refactor(boundary): 跨模块循环依赖清零(8 对 → 0),task→业务 依赖归零

共享内核下沉(跨模块共享的"身份/组织/安全"类型进 common)
- AdminUserEntity/AdminUserMapper、ShopManageGroupEntity/ShopManageGroupMapper → common
- AdminAuthSupport(33 文件 17 模块引用)、JwtService、AuthProperties、DeviceSessionPolicy
  → common/security(原先放在 admin/auth 里,任何模块用一次就多一条跨模块边)

端口化(消费方声明接口、数据方实现)
- task/spi:ResultFileJobHandler 新增 resolveResultFileUrl 钩子(BRAND 特例从 Worker 收回);
  Worker 改为调用 handler.onSuccess(该钩子历史上从未被调用,withdraw 的收尾靠 Worker 里的
  WITHDRAW 特判硬编码——现两者都归位,task 侧不再 import withdraw/brand)
- admin/spi/UserSecretCleanupPort(删除用户级联清理密钥)、notification/spi/ProxyBalancePort
  (代理余额探测)、shopdatacrawl/spi/ManagedShopNamesPort(可管店铺名)
- shopkey/spi/GroupDeletionGuardPort:分组删除守卫改由各业务模块实现(invalidasin/dedupe 两个实现),
  shopkey 不再直连它们的 Mapper

棘轮与量化(2026-09-14 实测)
- ArchitectureBoundaryTest:task→业务 119 → **0**(基线钉死为 0,新增跨模块动作必须走 task/spi)
- 跨模块 import 行数 650 → 605;双向依赖对 8 → **0**(usersecret/permission/shopkey 三向环、
  task↔withdraw、task↔brand、admin↔permission、admin↔usersecret、dedup↔shopkey、
  invalidasin↔shopkey、notification↔usersecret、shopdatacrawl↔shopduplicatecheck 全部拆解)

测试同步:接口契约 8→9、品牌 Handler 钩子契约、worker 的 10 个测试构造实参、通知/管理测试端口化。
mvn test 2881 全绿。
This commit is contained in:
2026-09-14 10:05:04 +08:00
parent f0c677e4c9
commit 96800a2c88
99 changed files with 417 additions and 228 deletions
@@ -1,19 +0,0 @@
package com.nanri.aiimage.modules.auth.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@Component
@ConfigurationProperties(prefix = "aiimage.auth")
public class AuthProperties {
private String jwtSecret = "please-change-this-secret-please-rotate-at-least-32-bytes";
private long jwtTtlHours = 168L;
private String cookieName = "aiimage_token";
private boolean cookieSecure = false;
private String cookieSameSite = "Lax";
/** 单设备登录(互踢)总开关:关闭后恢复为多设备同时在线(回滚用)。 */
private boolean singleDeviceEnabled = true;
}
@@ -3,12 +3,12 @@ package com.nanri.aiimage.modules.auth.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.auth.config.AuthProperties;
import com.nanri.aiimage.common.security.AuthProperties;
import com.nanri.aiimage.modules.auth.mapper.LoginUserMapper;
import com.nanri.aiimage.modules.auth.model.dto.LoginRequest;
import com.nanri.aiimage.modules.auth.model.entity.LoginUserEntity;
import com.nanri.aiimage.modules.auth.model.vo.LoginResultVo;
import com.nanri.aiimage.modules.auth.support.DeviceSessionPolicy;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.modules.auth.util.WerkzeugPasswordEncoder;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import io.jsonwebtoken.Claims;
@@ -21,6 +21,7 @@ import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import com.nanri.aiimage.common.security.JwtService;
@Service
@RequiredArgsConstructor
@@ -1,109 +0,0 @@
package com.nanri.aiimage.modules.auth.service;
import com.nanri.aiimage.modules.auth.config.AuthProperties;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.Instant;
import java.util.Date;
@Service
@RequiredArgsConstructor
@Slf4j
public class JwtService {
private static final String INSECURE_DEFAULT_SECRET = "please-change-this-secret-please-rotate-at-least-32-bytes";
private final AuthProperties props;
private volatile SecretKey cachedKey;
@org.springframework.beans.factory.annotation.Value("${spring.profiles.active:}")
private String activeProfiles;
/**
* 生产 profile 下密钥缺失即拒绝启动(2026-09 全维度审查)。
*
* <p>此前未配置时静默回退到内置默认密钥——那是公开值,任何人可据此伪造 token;
* 一次 env 丢失就会让全站鉴权形同虚设,只留一行 warn 日志不足以拦住发布。
* 本地/测试 profile 保持宽松(否则开发无法启动)。
*/
@jakarta.annotation.PostConstruct
void requireSecretInServerProfile() {
boolean serverProfile = activeProfiles != null && activeProfiles.contains("server");
if (serverProfile && (props.getJwtSecret() == null || props.getJwtSecret().isBlank())) {
throw new IllegalStateException(
"server profile 下必须配置 aiimage.auth.jwt-secret(环境变量 AIIMAGE_JWT_SECRET)——"
+ "缺失时会回退到公开的默认密钥,token 可被任意伪造");
}
}
private SecretKey signingKey() {
SecretKey key = cachedKey;
if (key == null) {
synchronized (this) {
key = cachedKey;
if (key == null) {
String configured = props.getJwtSecret();
byte[] keyBytes;
if (configured == null || configured.isBlank()) {
// 兜底:未配置时使用内置默认密钥(公开值,等同无防护,任何人可伪造 token)。
// 桌面客户端本地 Flask 已退役,服务端可独立轮换密钥;若恢复客户端侧验签,
// 需与客户端同步下发密钥后才能轮换。
keyBytes = INSECURE_DEFAULT_SECRET.getBytes(StandardCharsets.UTF_8);
log.warn("[auth] AIIMAGE_JWT_SECRET 未配置,使用内置默认密钥;"
+ "生产环境请在 application-server.yml 配置 aiimage.auth.jwt-secret");
} else {
keyBytes = configured.getBytes(StandardCharsets.UTF_8);
}
if (keyBytes.length < 32) {
byte[] padded = new byte[32];
System.arraycopy(keyBytes, 0, padded, 0, keyBytes.length);
keyBytes = padded;
}
key = Keys.hmacShaKeyFor(keyBytes);
cachedKey = key;
}
}
}
return key;
}
public String issue(Long userId, String username, String deviceId) {
Instant now = Instant.now();
Instant exp = now.plus(Duration.ofHours(props.getJwtTtlHours()));
return Jwts.builder()
.subject(String.valueOf(userId))
.claim("username", username)
.claim("deviceId", deviceId)
.issuedAt(Date.from(now))
.expiration(Date.from(exp))
.signWith(signingKey())
.compact();
}
public Claims parse(String token) {
try {
return Jwts.parser()
.verifyWith(signingKey())
.build()
.parseSignedClaims(token)
.getPayload();
} catch (JwtException | IllegalArgumentException e) {
log.debug("[auth] jwt parse failed: {}", e.getMessage());
return null;
}
}
public long ttlSeconds() {
return Duration.ofHours(props.getJwtTtlHours()).toSeconds();
}
}
@@ -1,90 +0,0 @@
package com.nanri.aiimage.modules.auth.support;
import com.nanri.aiimage.common.exception.BusinessException;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
/**
* 单设备登录(互踢)策略。
*
* <p>账号当前绑定的设备存放在 users.machine(登录成功即覆盖,last-login-wins);
* 非超管账号仅允许「token 内签名的 deviceId」与绑定设备一致的请求通过,
* 被新设备顶下线的旧 token 在下一次受保护请求时抛 4011。</p>
*
* <p>校验只认 token 内签名的 deviceId,绝不使用 X-Device-Id 请求头(头是客户端可控的)。</p>
*/
@Slf4j
public final class DeviceSessionPolicy {
/** 账号已在其他设备登录(前端据此提示并下线本设备)。 */
public static final int CODE_KICKED = 4011;
private DeviceSessionPolicy() {
}
/** 计算用户管理角色:super_admin / admin / null(含老数据 role 为空时按 created_by_id 推断)。 */
public static String resolveRole(String role, Integer isAdmin, Long createdById) {
String storedRole = role == null ? "" : role.trim().toLowerCase();
if ("super_admin".equals(storedRole)) {
return "super_admin";
}
if ("admin".equals(storedRole)) {
return "admin";
}
boolean isAdminFlag = isAdmin != null && isAdmin == 1;
if (storedRole.isEmpty() && isAdminFlag) {
return createdById == null ? "super_admin" : "admin";
}
return null;
}
/** 是否超级管理员(互踢的唯一豁免角色)。 */
public static boolean isSuperAdmin(String role, Integer isAdmin, Long createdById) {
return "super_admin".equals(resolveRole(role, isAdmin, createdById));
}
/** 从 JWT claims 中提取签名的设备号;缺失返回空串。 */
public static String claimDeviceId(Claims claims) {
Object raw = claims == null ? null : claims.get("deviceId");
return raw == null ? "" : raw.toString().trim();
}
/**
* 校验请求携带的 token 是否仍属于账号当前绑定的设备。
* 超管豁免;machine 为空(尚未绑定)放行;不匹配抛 4011。
*/
public static void assertSameDevice(String storedMachine, String claimDeviceId, boolean exempt,
Long userId, String username) {
if (exempt) {
return;
}
String bound = storedMachine == null ? "" : storedMachine.trim();
if (bound.isEmpty()) {
// 尚未绑定(首次登录前 / V118 清空后首个登录前),不做限制
return;
}
String claimed = claimDeviceId == null ? "" : claimDeviceId.trim();
if (claimed.isEmpty()) {
log.warn("[auth] 单设备登录校验:token 缺少设备标识,拒绝 userId={} username={}", userId, username);
throw new BusinessException(401, "登录态无效");
}
if (!bound.equals(claimed)) {
log.warn("[auth] 单设备登录拦截:用户 {} 已被其他设备顶下线,token设备={} 当前绑定设备={}",
userId, claimed, bound);
throw new BusinessException(CODE_KICKED, "该账号已在其他设备登录,本设备已下线");
}
}
/** 登录绑定时的中文日志:首次绑定 / 换设备(顶下线)/ 同设备重登,便于线上排查互踢来源。 */
public static void logBindOnLogin(String previousMachine, String deviceId, Long userId, String username) {
String previous = previousMachine == null ? "" : previousMachine.trim();
if (previous.isEmpty()) {
log.info("[auth] 单设备登录:用户 {}({})首次绑定设备 {}", userId, username, deviceId);
} else if (!previous.equals(deviceId)) {
log.warn("[auth] 单设备登录:用户 {}({})在设备 {} 登录,原设备 {} 已被顶下线",
userId, username, deviceId, previous);
} else {
log.info("[auth] 单设备登录:用户 {}({})同设备重新登录 device={}", userId, username, deviceId);
}
}
}