feat(token): 一作用域一Token(签发N个作用域生成N把); 新增Open API /api/open/token/ensure(get-or-create, X-Open-Key鉴权, 明文不可回吐)

This commit is contained in:
xiaoqu
2026-09-04 16:53:18 +08:00
parent b1ad0f727a
commit 965b314751
14 changed files with 503 additions and 39 deletions
@@ -130,8 +130,8 @@ public class AdminConsoleController {
}
@PostMapping("/users/{id}/tokens")
public AdminTokenService.IssuedToken issue(@PathVariable Long id, @RequestBody TokenRequest body,
HttpSession session) {
public List<AdminTokenService.IssuedToken> issue(@PathVariable Long id, @RequestBody TokenRequest body,
HttpSession session) {
if (body == null) bad("请求内容不能为空");
return tokenService.issue(id, body.memo(), body.scopeIds(), body.expireTime(), adminId(session));
}
@@ -34,12 +34,23 @@ public class AdminTokenService {
this.scopeMapper = scopeMapper;
}
/**
* 签发 Token:一作用域一 Token。选 N 个作用域生成 N 把,每把独立绑定单个作用域,
* 便于独立吊销、独立审计,明文逐把返回(仅本次可见)。
*/
@Transactional(transactionManager = "svcTransactionManager")
public IssuedToken issue(Long userId, String memo, List<Long> scopeIds, Date expireTime, Long adminId) {
public List<IssuedToken> issue(Long userId, String memo, List<Long> scopeIds, Date expireTime, Long adminId) {
User user = userMapper.selectById(userId);
if (user == null || Integer.valueOf(1).equals(user.getSoftDelete())) bad("人员不存在");
validateMemo(memo);
validateScopes(scopeIds);
return scopeIds.stream().distinct()
.map(scopeId -> issueSingle(userId, memo, scopeId, expireTime, adminId))
.toList();
}
/** 签发一把绑定单个作用域的 Token;人员/作用域合法性由调用方保证。 */
public IssuedToken issueSingle(Long userId, String memo, Long scopeId, Date expireTime, Long creatorId) {
String plaintext = "xqak_" + AdminAuthController.randomHex(24);
AgentApiKey token = new AgentApiKey();
token.setUserId(userId);
@@ -48,14 +59,32 @@ public class AdminTokenService {
token.setMemo(trim(memo, 255));
token.setStatus((byte) 1);
token.setExpireTime(expireTime);
token.setCreateId(adminId);
token.setModifyId(adminId);
token.setCreateId(creatorId);
token.setModifyId(creatorId);
token.setSoftDelete((byte) 0);
tokenMapper.insert(token);
replaceScopes(token.getId(), scopeIds, adminId);
replaceScopes(token.getId(), List.of(scopeId), creatorId);
return new IssuedToken(plaintext, view(token));
}
/** 查找某人员在某作用域下的有效 Token(正常状态且未过期),取最新一把;无则 null。 */
public AgentApiKey findActiveToken(Long userId, Long scopeId) {
List<Long> tokenIds = relationMapper.selectList(new LambdaQueryWrapper<TokenScope>()
.eq(TokenScope::getScopeId, scopeId).eq(TokenScope::getSoftDelete, 0))
.stream().map(TokenScope::getTokenId).toList();
if (tokenIds.isEmpty()) return null;
return tokenMapper.selectList(new LambdaQueryWrapper<AgentApiKey>()
.in(AgentApiKey::getId, tokenIds)
.eq(AgentApiKey::getUserId, userId)
.eq(AgentApiKey::getStatus, 1)
.eq(AgentApiKey::getSoftDelete, 0)
.and(w -> w.isNull(AgentApiKey::getExpireTime)
.or().gt(AgentApiKey::getExpireTime, new Date()))
.orderByDesc(AgentApiKey::getCreateTime)
.last("LIMIT 1"))
.stream().findFirst().orElse(null);
}
@Transactional(transactionManager = "svcTransactionManager")
public void update(Long tokenId, String memo, List<Long> scopeIds, Date expireTime, Long adminId) {
AgentApiKey current = activeToken(tokenId);
@@ -66,7 +66,7 @@ public class AuditService {
}
/**
* client_type:X-Client-Type 头优先;否则 User-Agent 含 kimi→mcp-kimi,
* client_type:/api/open/** → open-api;X-Client-Type 头其次;否则 User-Agent 含 kimi→mcp-kimi,
* 含 claude→mcp-claude,含 curl→cli,其余 unknown。
*/
private static String clientType() {
@@ -74,6 +74,9 @@ public class AuditService {
if (request == null) {
return "unknown";
}
if (request.getRequestURI() != null && request.getRequestURI().startsWith("/api/open/")) {
return "open-api";
}
String explicit = request.getHeader("X-Client-Type");
if (explicit != null && !explicit.isBlank()) {
return explicit;
@@ -0,0 +1,55 @@
package me.iiv.agent.open;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
/**
* /api/open 通道服务间鉴权:X-Open-Key 静态密钥(配置 app.open.api-key)。
* 与 ak 体系、后台 session 体系完全分离;配置为空 = 接口关闭。
*/
@Component
public class OpenKeyFilter extends OncePerRequestFilter {
static final String OPEN_KEY_HEADER = "X-Open-Key";
@Value("${app.open.api-key:}")
private String apiKey;
@Override
protected boolean shouldNotFilter(HttpServletRequest request) {
return !request.getRequestURI().startsWith("/api/open/");
}
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
response.setHeader("Cache-Control", "no-store");
if (apiKey == null || apiKey.isBlank()) {
error(response, 403, "Open API 未启用");
return;
}
String provided = request.getHeader(OPEN_KEY_HEADER);
if (provided == null || !MessageDigest.isEqual(
apiKey.getBytes(StandardCharsets.UTF_8), provided.getBytes(StandardCharsets.UTF_8))) {
error(response, 401, "服务间密钥无效");
return;
}
chain.doFilter(request, response);
}
private static void error(HttpServletResponse response, int status, String message) throws IOException {
response.setStatus(status);
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setContentType("application/json");
response.getWriter().write("{\"message\":\"" + message + "\"}");
}
}
@@ -0,0 +1,35 @@
package me.iiv.agent.open;
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.RestController;
import java.util.Date;
/**
* 对外服务间接口(/api/open/**),X-Open-Key 鉴权,见 OpenKeyFilter。
*/
@RestController
@RequestMapping("/api/open")
public class OpenTokenController {
private final OpenTokenService openTokenService;
public OpenTokenController(OpenTokenService openTokenService) {
this.openTokenService = openTokenService;
}
/**
* 确保某人员在某作用域下有有效 Token:存在则返回元信息(created=false,无明文),
* 不存在则自动创建永久 Token 并返回明文(created=true,仅此一次可见)。
*/
@PostMapping("/token/ensure")
public EnsureResult ensure(@RequestBody EnsureRequest body) {
return openTokenService.ensure(body);
}
public record EnsureRequest(String mobile, String email, String scopeCode) {}
public record EnsureResult(boolean created, String token, String keyPrefix, Date expireTime,
Long userId, String userName, String scopeCode) {}
}
@@ -0,0 +1,120 @@
package me.iiv.agent.open;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import me.iiv.agent.admin.AdminTokenService;
import me.iiv.agent.common.AuditService;
import me.iiv.agent.entity.m0.User;
import me.iiv.agent.entity.svc.AgentApiKey;
import me.iiv.agent.entity.svc.AgentScope;
import me.iiv.agent.mapper.m0.UserMapper;
import me.iiv.agent.mapper.svc.AgentScopeMapper;
import me.iiv.agent.security.AuthContext;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ResponseStatusException;
import java.util.Date;
/**
* Open API:按 手机号/邮箱 + 作用域编码 确保 Token 存在(get-or-create)。
* 存在有效 Token 只回元信息(服务端只存哈希,明文不可回吐);
* 不存在则自动创建永久 Token,明文仅本次返回。
*/
@Service
public class OpenTokenService {
/** 系统签发(Open API 自动创建)的 createId 约定值 */
static final long SYSTEM_CREATOR_ID = 0L;
static final String AUDIT_TOOL = "open.token.ensure";
private final UserMapper userMapper;
private final AgentScopeMapper scopeMapper;
private final AdminTokenService tokenService;
private final AuditService auditService;
public OpenTokenService(UserMapper userMapper, AgentScopeMapper scopeMapper,
AdminTokenService tokenService, AuditService auditService) {
this.userMapper = userMapper;
this.scopeMapper = scopeMapper;
this.tokenService = tokenService;
this.auditService = auditService;
}
@Transactional(transactionManager = "svcTransactionManager")
public OpenTokenController.EnsureResult ensure(OpenTokenController.EnsureRequest body) {
long start = System.currentTimeMillis();
if (body == null) bad(HttpStatus.BAD_REQUEST, "请求内容不能为空");
if (!StringUtils.hasText(body.mobile()) && !StringUtils.hasText(body.email())) {
bad(HttpStatus.BAD_REQUEST, "手机号和邮箱至少传一个");
}
if (!StringUtils.hasText(body.scopeCode())) bad(HttpStatus.BAD_REQUEST, "作用域编码不能为空");
AgentScope scope = scopeMapper.selectOne(new LambdaQueryWrapper<AgentScope>()
.eq(AgentScope::getCode, body.scopeCode().trim()).eq(AgentScope::getSoftDelete, 0));
if (scope == null || !Byte.valueOf((byte) 1).equals(scope.getStatus())) {
bad(HttpStatus.BAD_REQUEST, "作用域不存在或已停用");
}
User user = findUser(body.mobile(), body.email());
if (user == null) {
audit(null, null, body, "error", "人员不存在或非企业账号", start);
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "人员不存在或非企业账号");
}
AgentApiKey existing = tokenService.findActiveToken(user.getId(), scope.getId());
if (existing != null) {
audit(user, existing, body, "success", "已存在有效 Token,返回元信息", start);
return new OpenTokenController.EnsureResult(false, null, existing.getKeyPrefix(),
existing.getExpireTime(), user.getId(), user.getName(), scope.getCode());
}
AdminTokenService.IssuedToken issued = tokenService.issueSingle(user.getId(),
"open-api 自动签发(" + scope.getCode() + ")", scope.getId(), null, SYSTEM_CREATOR_ID);
AgentApiKey created = new AgentApiKey();
created.setId(issued.token().id());
audit(user, created, body, "success", "自动创建永久 Token", start);
return new OpenTokenController.EnsureResult(true, issued.plaintext(), issued.token().keyPrefix(),
null, user.getId(), user.getName(), scope.getCode());
}
/** 手机号优先、邮箱兜底;只认企业账号(enterprise_type 0/1,历史 NULL 保留),与后台用户列表同口径。 */
private User findUser(String mobile, String email) {
LambdaQueryWrapper<User> query = new LambdaQueryWrapper<User>()
.eq(User::getSoftDelete, 0)
.and(w -> w.ne(User::getEnterpriseType, 2).or().isNull(User::getEnterpriseType));
if (StringUtils.hasText(mobile)) {
query.eq(User::getMobile, mobile.trim());
} else {
query.eq(User::getEmail, email.trim());
}
return userMapper.selectList(query.orderByDesc(User::getId).last("LIMIT 1"))
.stream().findFirst().orElse(null);
}
private void audit(User user, AgentApiKey token, OpenTokenController.EnsureRequest body,
String status, String message, long start) {
String digest = "mobile=" + maskMobile(body.mobile()) + " email=" + maskEmail(body.email())
+ " scopeCode=" + body.scopeCode();
auditService.record(new AuthContext(token, user), AUDIT_TOOL, digest,
status, message, System.currentTimeMillis() - start);
}
private static String maskMobile(String mobile) {
if (!StringUtils.hasText(mobile)) return "-";
String value = mobile.trim();
return value.length() < 7 ? "***" : value.substring(0, 3) + "****" + value.substring(value.length() - 4);
}
private static String maskEmail(String email) {
if (!StringUtils.hasText(email)) return "-";
String value = email.trim();
int at = value.indexOf('@');
return at <= 1 ? "***" + value.substring(at) : value.charAt(0) + "***" + value.substring(at);
}
private static void bad(HttpStatus status, String message) {
throw new ResponseStatusException(status, message);
}
}