feat: 交付本地可运行 V1 候选版

实现初始化、单管理员认证、NapCat 被动接收、消息查询、媒体与发送闭环,补齐前端、自动化测试及同步文档。
This commit is contained in:
2026-11-04 11:34:34 +08:00
parent 46010f9fd2
commit 5432d61571
90 changed files with 10665 additions and 130 deletions
@@ -0,0 +1,85 @@
package com.qlinker.audit;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qlinker.common.RequestContext;
import com.qlinker.security.CryptoService;
import com.qlinker.security.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Map;
/**
* 审计写入(AGENTS.md 11.4、数据库设计 14.1)。只追加,不提供更新与删除入口。
*
* <p>审计失败不得吞掉:业务动作已经产生外部副作用时,审计写入失败必须让调用方感知,
* 否则事后无法追溯发送依据。同时审计内容不得包含密码、密钥与完整访问令牌。</p>
*/
public class AuditService {
public static final String RESULT_SUCCEEDED = "SUCCEEDED";
public static final String RESULT_FAILED = "FAILED";
public static final String RESULT_DENIED = "DENIED";
private static final Logger log = LoggerFactory.getLogger(AuditService.class);
private final JdbcTemplate jdbc;
private final CryptoService crypto;
private final ObjectMapper mapper = new ObjectMapper();
public AuditService(JdbcTemplate jdbc, CryptoService crypto) {
this.jdbc = jdbc;
this.crypto = crypto;
}
public void record(CurrentUser actor,
String action,
String resourceType,
String resourceId,
String result,
String reason,
Map<String, Object> details,
String sourceIp) {
String auditUid = "aud_" + crypto.randomToken(12);
String json;
try {
json = details == null || details.isEmpty() ? null : mapper.writeValueAsString(redact(details));
} catch (Exception e) {
json = null;
log.warn("审计详情序列化失败已降级为无详情 action={} error={}", action, e.toString());
}
jdbc.update("INSERT INTO audit_log (audit_uid, actor_type, actor_id, actor_name, action, resource_type, "
+ "resource_id, result, reason, request_id, trace_id, source_ip, details, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
auditUid,
actor == null ? "SYSTEM" : "USER",
actor == null ? null : actor.userId(),
actor == null ? "system" : actor.username(),
action, resourceType, resourceId, result, reason,
RequestContext.get(), RequestContext.get(), sourceIp, json,
Timestamp.from(Instant.now()));
}
/** 递归剔除敏感键,避免令牌与口令进入审计正文。 */
private Map<String, Object> redact(Map<String, Object> details) {
return details.entrySet().stream()
.filter(e -> !isSensitive(e.getKey()))
.collect(java.util.HashMap::new,
(m, e) -> m.put(e.getKey(), e.getValue() instanceof Map<?, ?> sub ? new java.util.HashMap<>(cast(sub)) : e.getValue()),
java.util.HashMap::putAll);
}
@SuppressWarnings("unchecked")
private Map<String, Object> cast(Map<?, ?> sub) {
return (Map<String, Object>) sub;
}
private boolean isSensitive(String key) {
String k = key.toLowerCase();
return k.contains("token") || k.contains("password") || k.contains("secret")
|| k.contains("credential") || k.contains("access_key") || k.contains("key");
}
}
@@ -0,0 +1,7 @@
package com.qlinker.binding;
public class BindingConflictException extends RuntimeException {
public BindingConflictException(String message) {
super(message);
}
}
@@ -0,0 +1,208 @@
package com.qlinker.binding;
import com.qlinker.security.CryptoService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* NapCat 绑定读写(数据库设计 7.1)。
*
* <p>访问令牌不放在本表:写入 secret_reference 并以 credential_ref_id 关联,
* 读取时只返回脱敏值,绝不通过管理接口回显明文(AGENTS.md 11.2)。</p>
*/
public class BindingRepository {
private final JdbcTemplate jdbc;
private final CryptoService crypto;
public BindingRepository(JdbcTemplate jdbc, CryptoService crypto) {
this.jdbc = jdbc;
this.crypto = crypto;
}
public record Binding(long id, String bindingUid, String instanceUid, String displayName, String connectionType,
String endpoint, Long credentialRefId, String bindingStatus, String connectionStatus,
String napcatVersion, String qqAccountId, Instant lastConnectedAt, Instant lastEventAt,
String lastErrorCode, Instant lastErrorAt) {
public boolean active() {
return BindingStatus.ACTIVE.equals(bindingStatus);
}
}
public List<Binding> findAll() {
return jdbc.query("SELECT * FROM napcat_binding ORDER BY id", this::mapBinding);
}
public List<Binding> findActive() {
return jdbc.query("SELECT * FROM napcat_binding WHERE binding_status = ? ORDER BY id",
this::mapBinding, BindingStatus.ACTIVE);
}
public Optional<Binding> findById(long id) {
List<Binding> rows = jdbc.query("SELECT * FROM napcat_binding WHERE id = ?", this::mapBinding, id);
return rows.stream().findFirst();
}
public Optional<Binding> findByUid(String bindingUid) {
List<Binding> rows = jdbc.query("SELECT * FROM napcat_binding WHERE binding_uid = ?", this::mapBinding,
bindingUid);
return rows.stream().findFirst();
}
/**
* 创建绑定。同一 instance_uid 只允许一条 ACTIVE 绑定,由数据库生成列唯一约束强制;
* 冲突时返回明确的资源冲突语义,不静默覆盖已有绑定。
*/
public Binding create(String instanceUid, String displayName, String connectionType, String endpoint,
String accessToken) {
Instant now = Instant.now();
Long credentialRefId = null;
if (accessToken != null && !accessToken.isBlank()) {
credentialRefId = saveCredential(accessToken, "napcat_access_token", "napcat_binding", instanceUid, now);
}
String bindingUid = "bnd_" + crypto.randomToken(12);
try {
jdbc.update("INSERT INTO napcat_binding (binding_uid, instance_uid, display_name, connection_type, "
+ "endpoint, credential_ref_id, binding_status, connection_status, created_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
bindingUid, instanceUid, displayName, connectionType, endpoint, credentialRefId,
BindingStatus.ACTIVE, ConnectionStatus.DISCONNECTED, Timestamp.from(now), Timestamp.from(now));
} catch (DuplicateKeyException e) {
throw new BindingConflictException("该 NapCat 实例已存在有效绑定:" + instanceUid);
}
return findByUid(bindingUid).orElseThrow(() -> new IllegalStateException("绑定创建后无法读回"));
}
public void updateStatus(long bindingId, String bindingStatus) {
jdbc.update("UPDATE napcat_binding SET binding_status = ?, updated_at = ? WHERE id = ?",
bindingStatus, Timestamp.from(Instant.now()), bindingId);
}
public void updateConnectionStatus(long bindingId, String connectionStatus, String errorCode, String errorMessage) {
Instant now = Instant.now();
if (ConnectionStatus.ONLINE.equals(connectionStatus)) {
jdbc.update("UPDATE napcat_binding SET connection_status = ?, last_connected_at = ?, last_error_code = NULL, "
+ "updated_at = ? WHERE id = ?",
connectionStatus, Timestamp.from(now), Timestamp.from(now), bindingId);
return;
}
jdbc.update("UPDATE napcat_binding SET connection_status = ?, last_error_code = ?, last_error_at = ?, "
+ "updated_at = ? WHERE id = ?",
connectionStatus, errorCode, Timestamp.from(now), Timestamp.from(now), bindingId);
}
public void touchEvent(long bindingId, Instant at) {
jdbc.update("UPDATE napcat_binding SET last_event_at = ?, updated_at = ? WHERE id = ?",
Timestamp.from(at), Timestamp.from(at), bindingId);
}
/** 轮换访问令牌:更新既有 secret_reference 行,不新增重复记录,不回显新值。 */
public void rotateCredential(long bindingId, String accessToken) {
Binding binding = findById(bindingId).orElseThrow(() -> new IllegalArgumentException("绑定不存在"));
Instant now = Instant.now();
if (binding.credentialRefId() == null) {
Long refId = saveCredential(accessToken, "napcat_access_token", "napcat_binding",
binding.bindingUid(), now);
jdbc.update("UPDATE napcat_binding SET credential_ref_id = ?, updated_at = ? WHERE id = ?",
refId, Timestamp.from(now), bindingId);
return;
}
jdbc.update("UPDATE secret_reference SET encrypted_value = ?, cipher_algorithm = ?, key_id = ?, "
+ "masked_value = ?, updated_at = ? WHERE id = ?",
crypto.encrypt(accessToken), CryptoService.ALGORITHM, crypto.keyId(),
CryptoService.mask(accessToken), Timestamp.from(now), binding.credentialRefId());
}
/** 读取访问令牌明文,仅供连接与发送内部使用;不得写入日志或返回给前端。 */
public Optional<String> accessTokenOf(Binding binding) {
if (binding.credentialRefId() == null) {
return Optional.empty();
}
List<String> rows = jdbc.queryForList(
"SELECT encrypted_value FROM secret_reference WHERE id = ?", String.class, binding.credentialRefId());
return rows.stream().findFirst().map(crypto::decrypt);
}
/**
* 保存凭据密文。secret_reference 以 secret_key 唯一,这里用「类型:归属」拼出稳定键,
* 保证同一归属重复轮换不会产生多行密文。
*/
private Long saveCredential(String plaintext, String secretType, String ownerType, String ownerUid, Instant now) {
String secretKey = secretType + ":" + ownerType + ":" + ownerUid;
jdbc.update("INSERT INTO secret_reference (secret_key, secret_type, storage_backend, masked_value, "
+ "encrypted_value, cipher_algorithm, key_id, status, created_at, updated_at) "
+ "VALUES (?, ?, 'DB_ENCRYPTED', ?, ?, ?, ?, 'ACTIVE', ?, ?)",
secretKey, secretType, CryptoService.mask(plaintext),
crypto.encrypt(plaintext), CryptoService.ALGORITHM, crypto.keyId(),
Timestamp.from(now), Timestamp.from(now));
return jdbc.queryForObject("SELECT id FROM secret_reference WHERE secret_key = ?", Long.class, secretKey);
}
/** 面向管理接口的展示视图:只含脱敏信息。 */
public Map<String, Object> toView(Binding binding) {
Map<String, Object> view = new LinkedHashMap<>();
view.put("bindingUid", binding.bindingUid());
view.put("instanceUid", binding.instanceUid());
view.put("displayName", binding.displayName());
view.put("connectionType", binding.connectionType());
view.put("endpoint", binding.endpoint());
view.put("bindingStatus", binding.bindingStatus());
view.put("connectionStatus", binding.connectionStatus());
view.put("napcatVersion", binding.napcatVersion());
view.put("qqAccountId", binding.qqAccountId());
view.put("hasCredential", binding.credentialRefId() != null);
view.put("lastConnectedAt", binding.lastConnectedAt());
view.put("lastEventAt", binding.lastEventAt());
view.put("lastErrorCode", binding.lastErrorCode());
view.put("lastErrorAt", binding.lastErrorAt());
return view;
}
public List<Map<String, Object>> connectionSnapshot() {
List<Map<String, Object>> out = new ArrayList<>();
for (Binding binding : findAll()) {
out.add(toView(binding));
}
return out;
}
private Binding mapBinding(ResultSet rs, int rowNum) throws SQLException {
return new Binding(
rs.getLong("id"),
rs.getString("binding_uid"),
rs.getString("instance_uid"),
rs.getString("display_name"),
rs.getString("connection_type"),
rs.getString("endpoint"),
longOrNull(rs, "credential_ref_id"),
rs.getString("binding_status"),
rs.getString("connection_status"),
rs.getString("napcat_version"),
rs.getString("qq_account_id"),
instant(rs, "last_connected_at"),
instant(rs, "last_event_at"),
rs.getString("last_error_code"),
instant(rs, "last_error_at"));
}
private static Long longOrNull(ResultSet rs, String column) throws SQLException {
long value = rs.getLong(column);
return rs.wasNull() ? null : value;
}
private static Instant instant(ResultSet rs, String column) throws SQLException {
Timestamp value = rs.getTimestamp(column);
return value == null ? null : value.toInstant();
}
}
@@ -0,0 +1,18 @@
package com.qlinker.binding;
/**
* 绑定状态与连接状态。取值在本任务内定稿并写入 DDL 生成列条件,
* 任何新增取值都必须同步新增迁移,不得只改代码(数据库设计 20.2)。
*/
public final class BindingStatus {
/** 有效绑定。同一 NapCat 实例身份下只允许一条,由 napcat_binding.active_instance_uid 唯一约束保证。 */
public static final String ACTIVE = "ACTIVE";
/** 已停用:保留配置与历史,不再建立连接。 */
public static final String DISABLED = "DISABLED";
/** 已解绑:保留记录用于历史事件溯源,不物理删除。 */
public static final String UNBOUND = "UNBOUND";
private BindingStatus() {
}
}
@@ -0,0 +1,21 @@
package com.qlinker.binding;
/**
* 连接状态。语义与接口设计 6.3 对齐,且明确区分「TCP/WS 已连接」与「已确认可用」:
* NapCat 正向 WebSocket 握手不校验 access_token,握手成功不代表凭据正确,
* 因此 ONLINE 只有在收到 lifecycle 或任一有效事件后才允许设置(能力基线实测结论)。
*/
public final class ConnectionStatus {
/** 尚未建立连接。 */
public static final String DISCONNECTED = "DISCONNECTED";
/** WebSocket 已连接,但尚未收到任何可信事件,凭据有效性未确认。 */
public static final String CONNECTING = "CONNECTING";
/** 已收到 lifecycle 或有效事件,确认连接与凭据可用。 */
public static final String ONLINE = "ONLINE";
/** 已确认凭据或配置错误,需人工处理;退避重试仍会继续。 */
public static final String ERROR = "ERROR";
private ConnectionStatus() {
}
}
@@ -0,0 +1,36 @@
package com.qlinker.common;
/**
* 稳定业务错误码。取值与 docs/接口设计.md 18 章错误码规范保持一致,
* HTTP 状态码映射同样集中在此处,避免各模块自行拼装。
*/
public enum ApiCode {
OK(200),
VALIDATION_ERROR(400),
UNAUTHENTICATED(401),
PERMISSION_DENIED(403),
RESOURCE_NOT_FOUND(404),
RESOURCE_CONFLICT(409),
DUPLICATE_REQUEST(409),
IDEMPOTENCY_CONFLICT(409),
RATE_LIMITED(429),
SAFETY_REJECTED(403),
APPROVAL_REQUIRED(409),
NAPCAT_NOT_CONNECTED(503),
NAPCAT_UNSUPPORTED(422),
NAPCAT_CALL_FAILED(502),
EXTERNAL_RESULT_UNKNOWN(504),
INSTANCE_NOT_INITIALIZED(503),
INTERNAL_ERROR(500);
private final int httpStatus;
ApiCode(int httpStatus) {
this.httpStatus = httpStatus;
}
public int httpStatus() {
return httpStatus;
}
}
@@ -0,0 +1,28 @@
package com.qlinker.common;
/**
* 业务异常。携带稳定错误码与可选的结构化字段错误,由 GlobalExceptionHandler 统一转换。
*/
public class ApiException extends RuntimeException {
private final ApiCode code;
private final Object data;
public ApiException(ApiCode code, String message) {
this(code, message, null);
}
public ApiException(ApiCode code, String message, Object data) {
super(message);
this.code = code;
this.data = data;
}
public ApiCode code() {
return code;
}
public Object data() {
return data;
}
}
@@ -0,0 +1,29 @@
package com.qlinker.common;
import java.time.Instant;
/**
* 统一响应结构(接口设计 3.3)。所有管理 API 复用该结构,文件下载与流式接口除外。
*/
public record ApiResponse<T>(
boolean success,
String code,
String message,
T data,
String requestId,
String timestamp) {
public static <T> ApiResponse<T> ok(T data) {
return new ApiResponse<>(true, ApiCode.OK.name(), "操作成功", data, currentRequestId(), Instant.now().toString());
}
@SuppressWarnings("unchecked")
public static <T> ApiResponse<T> error(ApiCode code, String message, Object data) {
return new ApiResponse<>(false, code.name(), message, (T) data, currentRequestId(), Instant.now().toString());
}
private static String currentRequestId() {
String requestId = RequestContext.get();
return requestId == null ? "req_unknown" : requestId;
}
}
@@ -0,0 +1,52 @@
package com.qlinker.common;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import java.util.List;
import java.util.Map;
/**
* 全局异常处理(接口设计 18 章)。错误响应不得包含堆栈、SQL、凭据或内部配置。
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(ApiException.class)
public ResponseEntity<ApiResponse<Object>> handleApi(ApiException e) {
Object data = e.data();
return ResponseEntity.status(e.code().httpStatus())
.body(ApiResponse.error(e.code(), e.getMessage(), data));
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ApiResponse<Object>> handleValidation(MethodArgumentNotValidException e) {
List<Map<String, String>> fieldErrors = e.getBindingResult().getFieldErrors().stream()
.map(f -> Map.of("field", f.getField(), "reason", f.getDefaultMessage() == null ? "不合法" : f.getDefaultMessage()))
.toList();
return ResponseEntity.status(ApiCode.VALIDATION_ERROR.httpStatus())
.body(ApiResponse.error(ApiCode.VALIDATION_ERROR, "请求参数不合法", Map.of("fieldErrors", fieldErrors)));
}
@ExceptionHandler({MissingServletRequestParameterException.class, HttpMessageNotReadableException.class, IllegalArgumentException.class})
public ResponseEntity<ApiResponse<Object>> handleBadRequest(Exception e) {
return ResponseEntity.status(ApiCode.VALIDATION_ERROR.httpStatus())
.body(ApiResponse.error(ApiCode.VALIDATION_ERROR, "请求参数不合法", null));
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ApiResponse<Object>> handleUnexpected(Exception e) {
String requestId = RequestContext.get();
log.error("未处理异常 requestId={} type={}", requestId, e.getClass().getName(), e);
return ResponseEntity.status(ApiCode.INTERNAL_ERROR.httpStatus())
.body(ApiResponse.error(ApiCode.INTERNAL_ERROR, "内部错误,请依据 requestId 排查", null));
}
}
@@ -0,0 +1,9 @@
package com.qlinker.common;
import java.util.List;
/**
* 分页载荷(接口设计 3.4)。page 从 1 开始,pageSize 上限由接口层强制。
*/
public record PageData<T>(List<T> items, int page, int pageSize, long total) {
}
@@ -0,0 +1,25 @@
package com.qlinker.common;
/**
* 请求追踪标识的线程上下文。由 RequestIdFilter 写入,响应包装与审计记录复用同一个值。
* 追踪标识不得充当认证凭证(接口设计 3.6)。
*/
public final class RequestContext {
private static final ThreadLocal<String> REQUEST_ID = new ThreadLocal<>();
private RequestContext() {
}
public static void set(String requestId) {
REQUEST_ID.set(requestId);
}
public static String get() {
return REQUEST_ID.get();
}
public static void clear() {
REQUEST_ID.remove();
}
}
@@ -0,0 +1,36 @@
package com.qlinker.common;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import java.io.IOException;
import java.util.UUID;
/**
* 为每个请求生成或复用追踪标识,供统一响应与审计记录关联(接口设计 3.6)。
*/
@Component
public class RequestIdFilter extends OncePerRequestFilter {
public static final String HEADER = "X-Request-Id";
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
String incoming = request.getHeader(HEADER);
String requestId = incoming != null && incoming.matches("^[A-Za-z0-9_-]{8,64}$")
? incoming
: "req_" + UUID.randomUUID().toString().replace("-", "").substring(0, 16);
RequestContext.set(requestId);
response.setHeader(HEADER, requestId);
try {
chain.doFilter(request, response);
} finally {
RequestContext.clear();
}
}
}
@@ -0,0 +1,59 @@
package com.qlinker.common;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.util.Date;
/**
* JDBC 时间值归一化工具。
*
* <p>MySQL Connector/J 在 {@code queryForList} 等通用映射路径下会把 DATETIME 返回为
* {@link LocalDateTime},而不是 {@link Timestamp};直接强转会抛 ClassCastException。
* 本工具统一把常见 JDBC 时间类型转换为 {@link Instant}(数据库时间按 UTC 存储,
* 见数据库设计总则)。</p>
*/
public final class TimeValues {
private TimeValues() {
}
/** 无法识别或空值返回 null;调用方必须显式处理 null。 */
public static Instant toInstant(Object value) {
if (value == null) {
return null;
}
if (value instanceof Instant instant) {
return instant;
}
if (value instanceof Timestamp timestamp) {
return timestamp.toInstant();
}
if (value instanceof LocalDateTime localDateTime) {
return localDateTime.toInstant(ZoneOffset.UTC);
}
if (value instanceof OffsetDateTime offsetDateTime) {
return offsetDateTime.toInstant();
}
if (value instanceof LocalDate localDate) {
return localDate.atStartOfDay(ZoneOffset.UTC).toInstant();
}
if (value instanceof java.sql.Date date) {
return date.toLocalDate().atStartOfDay(ZoneOffset.UTC).toInstant();
}
if (value instanceof Date date) {
return date.toInstant();
}
if (value instanceof CharSequence text) {
String trimmed = text.toString().trim();
if (trimmed.isEmpty()) {
return null;
}
return com.qlinker.message.MessageQueryService.parseInstant(trimmed);
}
throw new IllegalArgumentException("不支持的时间类型: " + value.getClass().getName());
}
}
@@ -0,0 +1,375 @@
package com.qlinker.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.time.Duration;
/**
* 运行配置(AGENTS.md 18.3)。所有外部地址、凭据、超时与容量上限集中在此,
* 缺失关键配置时在启动阶段即给出明确错误,而不是运行期产生难以定位的行为。
*/
@ConfigurationProperties(prefix = "qlinker")
public class QLinkerProperties {
/** 管理 API 会话令牌有效期。 */
private Duration sessionTtl = Duration.ofHours(8);
/** 实例初始化相关配置。 */
private Instance instance = new Instance();
/** 对象存储配置。 */
private Storage storage = new Storage();
/** 媒体下载配置。 */
private Media media = new Media();
/** 消息发送配置。 */
private Send send = new Send();
/** NapCat 连接配置。 */
private Napcat napcat = new Napcat();
public static class Instance {
/** 加密主密钥(Base64,32 字节)。用于 secret_reference 信封加密;必须由部署环境提供。 */
private String masterKey;
/** 实例身份状态文件所在目录;文件记录随机数据库名与 bucket 名,是重启复用身份的唯一依据。 */
private String stateDir = "./data";
/** MySQL 服务地址(不含库名),用于首次创建隔离数据库。 */
private String mysqlHost = "127.0.0.1";
private int mysqlPort = 3306;
private String mysqlUser;
private String mysqlPassword;
/** 业务库连接池上限;共享 MySQL 实例下需保守(AGENTS.md 13.3)。 */
private int maxPoolSize = 8;
/** 数据库名后缀随机标识长度。 */
private int randomIdLength = 8;
/** 名称冲突时最大重试次数。 */
private int maxCreateAttempts = 5;
/** 是否允许本实例执行首次初始化(创建数据库与 bucket)。 */
private boolean bootstrapEnabled = true;
public String getMasterKey() {
return masterKey;
}
public void setMasterKey(String masterKey) {
this.masterKey = masterKey;
}
public String getStateDir() {
return stateDir;
}
public void setStateDir(String stateDir) {
this.stateDir = stateDir;
}
public String getMysqlHost() {
return mysqlHost;
}
public void setMysqlHost(String mysqlHost) {
this.mysqlHost = mysqlHost;
}
public int getMysqlPort() {
return mysqlPort;
}
public void setMysqlPort(int mysqlPort) {
this.mysqlPort = mysqlPort;
}
public String getMysqlUser() {
return mysqlUser;
}
public void setMysqlUser(String mysqlUser) {
this.mysqlUser = mysqlUser;
}
public String getMysqlPassword() {
return mysqlPassword;
}
public void setMysqlPassword(String mysqlPassword) {
this.mysqlPassword = mysqlPassword;
}
public int getMaxPoolSize() {
return maxPoolSize;
}
public void setMaxPoolSize(int maxPoolSize) {
this.maxPoolSize = maxPoolSize;
}
public int getRandomIdLength() {
return randomIdLength;
}
public void setRandomIdLength(int randomIdLength) {
this.randomIdLength = randomIdLength;
}
public int getMaxCreateAttempts() {
return maxCreateAttempts;
}
public void setMaxCreateAttempts(int maxCreateAttempts) {
this.maxCreateAttempts = maxCreateAttempts;
}
public boolean isBootstrapEnabled() {
return bootstrapEnabled;
}
public void setBootstrapEnabled(boolean bootstrapEnabled) {
this.bootstrapEnabled = bootstrapEnabled;
}
}
public static class Storage {
/** MinIO S3 API 端点,例如 http://127.0.0.1:9000。 */
private String endpoint;
private String accessKey;
private String secretKey;
/** 区域签名值;MinIO 允许任意非空值。 */
private String region = "us-east-1";
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public String getAccessKey() {
return accessKey;
}
public void setAccessKey(String accessKey) {
this.accessKey = accessKey;
}
public String getSecretKey() {
return secretKey;
}
public void setSecretKey(String secretKey) {
this.secretKey = secretKey;
}
public String getRegion() {
return region;
}
public void setRegion(String region) {
this.region = region;
}
}
public static class Media {
/** 单个媒体对象上限,字节。默认 100 MB(决策基线 DEC-402)。 */
private long maxBytes = 100L * 1024 * 1024;
/** 下载超时。 */
private Duration downloadTimeout = Duration.ofSeconds(60);
/** 保留天数(决策基线 DEC-401)。 */
private long retentionDays = 365;
/** 预签名访问 URL 有效期。 */
private Duration presignTtl = Duration.ofMinutes(5);
/**
* 是否允许访问私有与内网地址。默认 false:媒体下载必须通过 SSRF 防护
* (功能设计 6.4、AGENTS.md 11.3)。仅在明确的本地开发环境显式开启。
*/
private boolean allowPrivateNetwork = false;
public long getMaxBytes() {
return maxBytes;
}
public void setMaxBytes(long maxBytes) {
this.maxBytes = maxBytes;
}
public Duration getDownloadTimeout() {
return downloadTimeout;
}
public void setDownloadTimeout(Duration downloadTimeout) {
this.downloadTimeout = downloadTimeout;
}
public long getRetentionDays() {
return retentionDays;
}
public void setRetentionDays(long retentionDays) {
this.retentionDays = retentionDays;
}
public Duration getPresignTtl() {
return presignTtl;
}
public void setPresignTtl(Duration presignTtl) {
this.presignTtl = presignTtl;
}
public boolean isAllowPrivateNetwork() {
return allowPrivateNetwork;
}
public void setAllowPrivateNetwork(boolean allowPrivateNetwork) {
this.allowPrivateNetwork = allowPrivateNetwork;
}
}
public static class Send {
/** 单绑定每分钟允许的发送操作数。 */
private int rateLimitPerMinute = 10;
/** 二次确认令牌有效期。 */
private Duration confirmTokenTtl = Duration.ofMinutes(5);
/** NapCat API 调用超时。 */
private Duration apiTimeout = Duration.ofSeconds(30);
public int getRateLimitPerMinute() {
return rateLimitPerMinute;
}
public void setRateLimitPerMinute(int rateLimitPerMinute) {
this.rateLimitPerMinute = rateLimitPerMinute;
}
public Duration getConfirmTokenTtl() {
return confirmTokenTtl;
}
public void setConfirmTokenTtl(Duration confirmTokenTtl) {
this.confirmTokenTtl = confirmTokenTtl;
}
public Duration getApiTimeout() {
return apiTimeout;
}
public void setApiTimeout(Duration apiTimeout) {
this.apiTimeout = apiTimeout;
}
}
public static class Napcat {
/** WebSocket 连接与握手超时。 */
private Duration connectTimeout = Duration.ofSeconds(15);
/** 断线后的最小重连退避。 */
private Duration reconnectMinBackoff = Duration.ofSeconds(2);
/** 断线后的最大重连退避。 */
private Duration reconnectMaxBackoff = Duration.ofSeconds(60);
/**
* 在线判定窗口。 NapCat 正向 WS 握手不校验 access_token,必须在收到 lifecycle
* 或任一有效事件后才判定为 ONLINE;超过该窗口仍无任何事件时降级为 CONNECTING 并告警。
*/
private Duration onlineConfirmTimeout = Duration.ofSeconds(30);
/** 单条事件报文上限,字节。超限事件保留状态标记而不是静默丢弃(AGENTS.md 5.2)。 */
private long maxEventBytes = 8L * 1024 * 1024;
/** 是否启用事件接收。关闭后不再建立 NapCat 连接。 */
private boolean receiverEnabled = true;
public Duration getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Duration getReconnectMinBackoff() {
return reconnectMinBackoff;
}
public void setReconnectMinBackoff(Duration reconnectMinBackoff) {
this.reconnectMinBackoff = reconnectMinBackoff;
}
public Duration getReconnectMaxBackoff() {
return reconnectMaxBackoff;
}
public void setReconnectMaxBackoff(Duration reconnectMaxBackoff) {
this.reconnectMaxBackoff = reconnectMaxBackoff;
}
public Duration getOnlineConfirmTimeout() {
return onlineConfirmTimeout;
}
public void setOnlineConfirmTimeout(Duration onlineConfirmTimeout) {
this.onlineConfirmTimeout = onlineConfirmTimeout;
}
public long getMaxEventBytes() {
return maxEventBytes;
}
public void setMaxEventBytes(long maxEventBytes) {
this.maxEventBytes = maxEventBytes;
}
public boolean isReceiverEnabled() {
return receiverEnabled;
}
public void setReceiverEnabled(boolean receiverEnabled) {
this.receiverEnabled = receiverEnabled;
}
}
public Duration getSessionTtl() {
return sessionTtl;
}
public void setSessionTtl(Duration sessionTtl) {
this.sessionTtl = sessionTtl;
}
public Instance getInstance() {
return instance;
}
public void setInstance(Instance instance) {
this.instance = instance;
}
public Storage getStorage() {
return storage;
}
public void setStorage(Storage storage) {
this.storage = storage;
}
public Media getMedia() {
return media;
}
public void setMedia(Media media) {
this.media = media;
}
public Send getSend() {
return send;
}
public void setSend(Send send) {
this.send = send;
}
public Napcat getNapcat() {
return napcat;
}
public void setNapcat(Napcat napcat) {
this.napcat = napcat;
}
}
@@ -0,0 +1,215 @@
package com.qlinker.config;
import com.qlinker.audit.AuditService;
import com.qlinker.binding.BindingRepository;
import com.qlinker.event.EventIngestService;
import com.qlinker.init.BootstrapCoordinator;
import com.qlinker.init.BucketProvisioner;
import com.qlinker.init.DatabaseProvisioner;
import com.qlinker.init.InstanceStateStore;
import com.qlinker.init.SchemaMigrator;
import com.qlinker.media.MediaService;
import com.qlinker.media.SecureDownloadClient;
import com.qlinker.message.MessageNormalizer;
import com.qlinker.message.MessageQueryService;
import com.qlinker.napcat.NapCatApiClient;
import com.qlinker.napcat.NapCatConnectionManager;
import com.qlinker.napcat.NapCatSessionFactory;
import com.qlinker.napcat.WebSocketNapCatSessionFactory;
import com.qlinker.security.AuthInterceptor;
import com.qlinker.security.AuthService;
import com.qlinker.security.CryptoService;
import com.qlinker.send.SendService;
import com.qlinker.storage.StorageService;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.minio.MinioClient;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* 运行期装配。
*
* <p>业务数据源在应用启动阶段由 BootstrapCoordinator 确定资源身份后构建,
* 因此这里使用懒加载的 {@link RuntimeDataSource} 持有连接池,避免「身份未确定就建表」。</p>
*/
@Configuration
@EnableConfigurationProperties(QLinkerProperties.class)
@EnableScheduling
public class RuntimeConfiguration implements WebMvcConfigurer {
private final org.springframework.beans.factory.ObjectProvider<AuthInterceptor> authInterceptor;
public RuntimeConfiguration(org.springframework.beans.factory.ObjectProvider<AuthInterceptor> authInterceptor) {
this.authInterceptor = authInterceptor;
}
@Bean
public MinioClient minioClient(QLinkerProperties properties) {
String endpoint = properties.getStorage().getEndpoint();
if (endpoint == null || endpoint.isBlank()) {
// 端点缺失不阻断启动:对象存储不可用属于可降级依赖,媒体与初始化会给出明确错误。
endpoint = "http://127.0.0.1:9000";
}
return MinioClient.builder()
.endpoint(endpoint)
.credentials(nullToEmpty(properties.getStorage().getAccessKey()),
nullToEmpty(properties.getStorage().getSecretKey()))
.region(properties.getStorage().getRegion())
.build();
}
@Bean
public InstanceStateStore instanceStateStore(QLinkerProperties properties) {
return new InstanceStateStore(properties.getInstance().getStateDir());
}
@Bean
public DatabaseProvisioner databaseProvisioner(QLinkerProperties properties) {
return new DatabaseProvisioner(properties);
}
@Bean
public BucketProvisioner bucketProvisioner(QLinkerProperties properties, MinioClient minioClient) {
return new BucketProvisioner(properties, minioClient);
}
@Bean
public SchemaMigrator schemaMigrator() {
return new SchemaMigrator();
}
@Bean
public BootstrapCoordinator bootstrapCoordinator(QLinkerProperties properties,
InstanceStateStore stateStore,
DatabaseProvisioner databaseProvisioner,
BucketProvisioner bucketProvisioner,
SchemaMigrator schemaMigrator) {
return new BootstrapCoordinator(properties, stateStore, databaseProvisioner, bucketProvisioner, schemaMigrator);
}
@Bean
public RuntimeDataSource runtimeDataSource(BootstrapCoordinator coordinator,
DatabaseProvisioner provisioner,
QLinkerProperties properties) {
return new RuntimeDataSource(coordinator, provisioner, properties);
}
@Bean
public JdbcTemplate jdbcTemplate(RuntimeDataSource dataSource) {
return new JdbcTemplate(dataSource);
}
@Bean
public CryptoService cryptoService(QLinkerProperties properties) {
return new CryptoService(properties.getInstance().getMasterKey());
}
@Bean
public AuditService auditService(JdbcTemplate jdbc, CryptoService crypto) {
return new AuditService(jdbc, crypto);
}
@Bean
public AuthService authService(JdbcTemplate jdbc, CryptoService crypto,
QLinkerProperties properties, AuditService audit) {
return new AuthService(jdbc, crypto, properties, audit);
}
@Bean
public BindingRepository bindingRepository(JdbcTemplate jdbc, CryptoService crypto) {
return new BindingRepository(jdbc, crypto);
}
@Bean
public EventIngestService eventIngestService(JdbcTemplate jdbc, ObjectMapper mapper,
QLinkerProperties properties) {
return new EventIngestService(jdbc, mapper, properties.getNapcat().getMaxEventBytes());
}
@Bean
public MessageNormalizer messageNormalizer(JdbcTemplate jdbc, ObjectMapper mapper) {
return new MessageNormalizer(jdbc, mapper);
}
@Bean
public StorageService storageService(MinioClient minioClient, BootstrapCoordinator coordinator,
QLinkerProperties properties) {
return new StorageService(minioClient, coordinator, properties);
}
@Bean
public SecureDownloadClient secureDownloadClient(QLinkerProperties properties) {
return new SecureDownloadClient(properties.getMedia());
}
@Bean
public MediaService mediaService(JdbcTemplate jdbc, ObjectMapper mapper, StorageService storage,
SecureDownloadClient downloader, QLinkerProperties properties) {
return new MediaService(jdbc, mapper, downloader, storage, properties.getMedia());
}
@Bean
public MessageQueryService messageQueryService(JdbcTemplate jdbc) {
return new MessageQueryService(jdbc);
}
@Bean
public NapCatApiClient napCatApiClient(ObjectMapper mapper, QLinkerProperties properties) {
return new NapCatApiClient(mapper, properties.getSend().getApiTimeout());
}
@Bean
public NapCatSessionFactory napCatSessionFactory() {
return new WebSocketNapCatSessionFactory();
}
@Bean
public NapCatConnectionManager napCatConnectionManager(BindingRepository bindings,
NapCatSessionFactory sessionFactory,
EventIngestService ingest,
MessageNormalizer normalizer,
MediaService media,
QLinkerProperties properties) {
return new NapCatConnectionManager(bindings, ingest, normalizer, media, sessionFactory,
properties.getNapcat());
}
@Bean
public SendService sendService(JdbcTemplate jdbc, BindingRepository bindings, NapCatApiClient apiClient,
ObjectMapper mapper, CryptoService crypto, AuditService audit,
QLinkerProperties properties) {
return new SendService(jdbc, bindings, apiClient, mapper, crypto, audit, properties.getSend());
}
@Bean
public com.qlinker.init.BootstrapRunner bootstrapRunner(BootstrapCoordinator coordinator,
AuthService auth, CryptoService crypto,
NapCatConnectionManager connections,
QLinkerProperties properties) {
return new com.qlinker.init.BootstrapRunner(coordinator, auth, crypto, connections,
properties.getNapcat().isReceiverEnabled());
}
@Bean
public AuthInterceptor authInterceptor(AuthService auth) {
return new AuthInterceptor(auth);
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 初始化与登录接口本身不带令牌,其余 /api/v1 接口一律要求服务端校验(AGENTS.md 11.1)。
registry.addInterceptor(authInterceptor.getObject())
.addPathPatterns("/api/v1/**")
.excludePathPatterns("/api/v1/auth/login", "/api/v1/auth/bootstrap",
"/api/v1/system/initialization");
}
private static String nullToEmpty(String value) {
return value == null ? "" : value;
}
}
@@ -0,0 +1,75 @@
package com.qlinker.config;
import com.qlinker.init.BootstrapCoordinator;
import com.qlinker.init.DatabaseProvisioner;
import com.zaxxer.hikari.HikariDataSource;
import org.springframework.jdbc.datasource.AbstractDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* 延迟解析的业务库数据源。
*
* <p>业务数据库名在进程启动后才由初始化流程确定,因此不能在配置文件中写死 URL。
* 首次取连接时触发初始化核验,之后复用同一连接池;资源身份异常时直接抛出,
* 使所有依赖数据库的接口以明确的 503 失败,而不是连到一个错误的库。</p>
*/
public class RuntimeDataSource extends AbstractDataSource {
private final BootstrapCoordinator coordinator;
private final DatabaseProvisioner provisioner;
private final QLinkerProperties properties;
private volatile HikariDataSource delegate;
public RuntimeDataSource(BootstrapCoordinator coordinator,
DatabaseProvisioner provisioner,
QLinkerProperties properties) {
this.coordinator = coordinator;
this.provisioner = provisioner;
this.properties = properties;
}
private DataSource delegate() {
HikariDataSource current = delegate;
if (current != null) {
return current;
}
synchronized (this) {
if (delegate == null) {
var identity = coordinator.ensureReady();
HikariDataSource ds = new HikariDataSource();
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.setJdbcUrl(provisioner.businessJdbcUrl(identity.databaseName()));
ds.setUsername(properties.getInstance().getMysqlUser());
ds.setPassword(properties.getInstance().getMysqlPassword());
ds.setMaximumPoolSize(properties.getInstance().getMaxPoolSize());
ds.setMinimumIdle(1);
ds.setPoolName("qlinker-business");
ds.setAutoCommit(true);
delegate = ds;
}
return delegate;
}
}
@Override
public Connection getConnection() throws SQLException {
return delegate().getConnection();
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return delegate().getConnection(username, password);
}
/** Spring 容器关闭时自动调用(Bean destroyMethod 默认推断 close)。 */
public void close() {
HikariDataSource current = delegate;
if (current != null) {
current.close();
}
}
}
@@ -0,0 +1,24 @@
package com.qlinker.event;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HexFormat;
public final class ContentHash {
public static byte[] sha256(String text) {
try {
return MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("运行环境缺少 SHA-256 实现", e);
}
}
public static String hex(String text) {
return HexFormat.of().formatHex(sha256(text));
}
private ContentHash() {
}
}
@@ -0,0 +1,201 @@
package com.qlinker.event;
import com.fasterxml.jackson.databind.JsonNode;
import java.time.Duration;
import java.time.Instant;
/**
* 事件去重键推导(数据库设计 8.2、决策基线 GC-010 / GC-022)。
*
* <p>关键约束:群 ID 与私聊 QQ 号同为无符号 64 位整数,只用会话 ID 或只用 real_seq 都会跨会话
* 误判重复并静默丢数据,因此键必须显式包含「会话类型判别 + 会话 ID + 会话内标识」三段;
* real_seq 在事件通道是字符串、在 history 通道是数字,必须在此统一为规范十进制文本,
* 禁止依赖隐式转换或字符串比较。</p>
*/
public final class DedupKeyFactory {
public static final String STRATEGY_SEQ = "CONVERSATION_SEQ";
public static final String STRATEGY_MESSAGE_ID = "CONVERSATION_MESSAGE_ID";
public static final String STRATEGY_FORWARD_HASH = "CONVERSATION_FORWARD_HASH";
/** 无稳定来源标识时的降级策略:正文哈希 + 有效期限,存在误判风险,必须限制窗口。 */
public static final String STRATEGY_CONTENT_HASH_TTL = "CONTENT_HASH_TTL";
/** 无法安全去重:原样入库,不声称去重成功。 */
public static final String STRATEGY_NONE = "NO_DEDUP";
/** 降级策略的固定有效期限;超出窗口后由清理任务回收。 */
static final Duration CONTENT_HASH_TTL = Duration.ofHours(6);
public record DedupKey(String key, String strategy, Instant expiresAt) {
public boolean deduplicable() {
return !STRATEGY_NONE.equals(strategy);
}
}
public static DedupKey derive(JsonNode event) {
String postType = text(event, "post_type");
String detailType = detailTypeOf(event);
Conversation conv = conversationOf(event);
if ("message".equals(postType) || "message_sent".equals(postType)) {
String seq = canonicalSequence(text(event, "real_seq"));
if (conv != null && seq != null) {
return new DedupKey(STRATEGY_SEQ + ":" + conv.scope() + ":" + seq, STRATEGY_SEQ, null);
}
String messageId = text(event, "message_id");
if (conv != null && messageId != null) {
// message_id 不是序号且不可跨会话比较,因此必须带会话范围(能力基线实测)。
return new DedupKey(STRATEGY_MESSAGE_ID + ":" + conv.scope() + ":" + messageId,
STRATEGY_MESSAGE_ID, null);
}
String forwardHash = text(event, "hash");
if (conv != null && forwardHash != null) {
return new DedupKey(STRATEGY_FORWARD_HASH + ":" + conv.scope() + ":" + forwardHash,
STRATEGY_FORWARD_HASH, null);
}
return contentHashKey(event);
}
if ("meta_event".equals(postType)) {
// lifecycle / heartbeat 每轮都会重复,按类型+心跳周期去重,不参与消息去重语义。
String heartbeatInterval = text(event, "interval");
String key = "evt:meta:" + nullToEmpty(detailType) + ":" + nullToEmpty(heartbeatInterval);
if ("heartbeat".equals(detailType) && heartbeatInterval != null) {
return new DedupKey(key, STRATEGY_CONTENT_HASH_TTL, Instant.now().plus(CONTENT_HASH_TTL));
}
if ("lifecycle".equals(detailType)) {
return new DedupKey(key + ":" + nullToEmpty(text(event, "self_id")), STRATEGY_SEQ, null);
}
return new DedupKey(null, STRATEGY_NONE, null);
}
if ("notice".equals(postType) || "request".equals(postType)) {
String messageId = text(event, "message_id");
String seq = canonicalSequence(text(event, "real_seq"));
if (conv != null && seq != null) {
return new DedupKey(STRATEGY_SEQ + ":" + conv.scope() + ":" + seq, STRATEGY_SEQ, null);
}
if (conv != null && messageId != null) {
return new DedupKey(STRATEGY_MESSAGE_ID + ":" + conv.scope() + ":" + messageId,
STRATEGY_MESSAGE_ID, null);
}
// 通知类事件常无稳定标识,用正文哈希 + 有效期限降级,误判风险已在策略名中标明。
return contentHashKey(event);
}
return new DedupKey(null, STRATEGY_NONE, null);
}
private static DedupKey contentHashKey(JsonNode event) {
return new DedupKey(STRATEGY_CONTENT_HASH_TTL + ":" + ContentHash.hex(event.toString()),
STRATEGY_CONTENT_HASH_TTL, Instant.now().plus(CONTENT_HASH_TTL));
}
/** 会话范围判别。群与私聊使用不同前缀,避免同为数字 ID 时互相冲突。 */
/**
* 子类型字段。NapCat 的 meta 事件用 meta_event_type、notice 用 notice_type、request 用 request_type,
* detail_type 并非这些事件的字段(能力基线实测);只读 detail_type 会让全部心跳与生命周期事件
* 退化为不去重,心跳每 3 秒一条会持续膨胀 raw_event。
*/
public static String detailTypeOf(JsonNode event) {
return firstText(event, "detail_type", "meta_event_type", "notice_type", "request_type");
}
public record Conversation(String type, String id) {
public String scope() {
return type + ":" + id;
}
}
public static Conversation conversationOf(JsonNode event) {
String messageType = text(event, "message_type");
if ("group".equals(messageType)) {
String groupId = firstText(event, "group_id", "chat_id");
return groupId == null ? null : new Conversation("group", groupId);
}
if ("private".equals(messageType)) {
String userId = firstText(event, "user_id", "sender_id", "target_id");
return userId == null ? null : new Conversation("private", userId);
}
Long guildId = longOf(event, "guild_id");
if (guildId != null && guildId != 0L) {
String channelId = firstText(event, "channel_id");
return channelId == null ? null : new Conversation("guild", channelId);
}
return null;
}
/** 统一 real_seq 的字符串/数字表示,去掉前导零;非数字输入直接拒绝。 */
static String canonicalSequence(String raw) {
if (raw == null) {
return null;
}
String trimmed = raw.trim();
if (trimmed.isEmpty()) {
return null;
}
for (int i = 0; i < trimmed.length(); i++) {
char c = trimmed.charAt(i);
if (c < '0' || c > '9') {
return null;
}
}
String stripped = trimmed.replaceFirst("^0+(?=.)", "");
return stripped;
}
static String canonicalSequence(JsonNode node) {
if (node == null || node.isNull() || node.isMissingNode()) {
return null;
}
if (node.isNumber()) {
return node.bigIntegerValue().toString();
}
return canonicalSequence(node.asText());
}
private static String firstText(JsonNode node, String... fields) {
for (String field : fields) {
String value = text(node, field);
if (value != null) {
return value;
}
}
return null;
}
public static String text(JsonNode node, String field) {
if (node == null) {
return null;
}
JsonNode value = node.get(field);
if (value == null || value.isNull() || value.isMissingNode()) {
return null;
}
if (value.isNumber()) {
return value.bigIntegerValue().toString();
}
String text = value.asText().trim();
return text.isEmpty() ? null : text;
}
private static Long longOf(JsonNode node, String field) {
String value = text(node, field);
if (value == null) {
return null;
}
try {
return Long.parseUnsignedLong(value);
} catch (NumberFormatException e) {
return null;
}
}
private static String nullToEmpty(String value) {
return value == null ? "" : value;
}
private DedupKeyFactory() {
}
}
@@ -0,0 +1,242 @@
package com.qlinker.event;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Optional;
/**
* 事件接收落库(AGENTS.md 6.1、6.3、16.1)。
*
* <p>接收成功以「raw_event 已可靠持久化」为准;落库与去重记录在同一事务内写入,
* 保证重复事件不会绕过唯一约束。解析、媒体下载与规则执行一律在落库之后异步进行,
* 不在接收路径上执行耗时操作。</p>
*/
public class EventIngestService {
private static final Logger log = LoggerFactory.getLogger(EventIngestService.class);
public static final String PARSE_PENDING = "PENDING";
public static final String PARSE_PARSED = "PARSED";
public static final String PARSE_PARTIAL = "PARTIAL";
public static final String PARSE_UNKNOWN_TYPE = "UNKNOWN_TYPE";
public static final String PARSE_INVALID_JSON = "INVALID_JSON";
public static final String PARSE_TOO_LARGE = "TOO_LARGE";
public static final String PROCESS_PENDING = "PENDING";
public static final String PROCESS_PROCESSING = "PROCESSING";
public static final String PROCESS_PROCESSED = "PROCESSED";
public static final String PROCESS_FAILED = "FAILED";
public static final String PROCESS_SKIPPED = "SKIPPED";
private final JdbcTemplate jdbc;
private final ObjectMapper mapper;
private final long maxEventBytes;
public EventIngestService(JdbcTemplate jdbc, ObjectMapper mapper, long maxEventBytes) {
this.jdbc = jdbc;
this.mapper = mapper;
this.maxEventBytes = maxEventBytes;
}
/** 落库结果。duplicated=true 表示该事件此前已接收,未重复产生副作用。 */
public record IngestResult(Long eventId, String eventUid, boolean duplicated, String parseStatus) {
}
/**
* 持久化一条原始事件。
*
* @param bindingId 来源绑定
* @param rawPayload 原始报文,逐字保留
* @param receivedAt 系统接收时间
* @param instanceUid 来源实例身份,仅用于日志关联
*/
@Transactional(propagation = Propagation.REQUIRED)
public IngestResult ingest(long bindingId, String rawPayload, Instant receivedAt, String instanceUid) {
Instant now = receivedAt == null ? Instant.now() : receivedAt;
String eventUid = "evt_" + ContentHash.hex(bindingId + "|" + now.toEpochMilli() + "|"
+ System.nanoTime()).substring(0, 32);
if (rawPayload == null) {
throw new IllegalArgumentException("原始事件不得为空");
}
if (rawPayload.getBytes(java.nio.charset.StandardCharsets.UTF_8).length > maxEventBytes) {
// 超限事件不入库正文,只记录超限状态,避免超大负载耗尽存储与内存(AGENTS.md 5.2)。
log.warn("事件超过上限已拒绝 binding={} instance={} maxBytes={}", bindingId, instanceUid, maxEventBytes);
throw new EventTooLargeException("事件超过 " + maxEventBytes + " 字节上限");
}
JsonNode parsed = tryParse(rawPayload);
String eventType = parsed == null ? "unparseable" : DedupKeyFactory.text(parsed, "post_type");
if (eventType == null || eventType.isBlank()) {
eventType = "unknown";
}
String detailType = parsed == null ? null : DedupKeyFactory.detailTypeOf(parsed);
String fullType = detailType == null ? eventType : eventType + "/" + detailType;
String sourceEventId = parsed == null ? null : DedupKeyFactory.text(parsed, "message_id");
Timestamp sourceTime = parsed == null ? null : timestampOf(parsed);
String parseStatus = parseStatusOf(parsed, fullType);
Long eventId = insertRawEvent(bindingId, eventUid, sourceEventId, fullType, sourceTime, now,
rawPayload, parseStatus);
DedupKeyFactory.DedupKey dedup = parsed == null
? new DedupKeyFactory.DedupKey(DedupKeyFactory.STRATEGY_NONE + ":" + eventUid,
DedupKeyFactory.STRATEGY_NONE, null)
: DedupKeyFactory.derive(parsed);
boolean duplicated = recordDedup(bindingId, eventId, eventUid, dedup);
return new IngestResult(eventId, eventUid, duplicated, parseStatus);
}
private String parseStatusOf(JsonNode parsed, String fullType) {
if (parsed == null) {
return PARSE_INVALID_JSON;
}
return switch (fullType) {
case "message", "message/message", "message_sent", "message_sent/message",
"meta_event/lifecycle", "meta_event/heartbeat", "notice", "request" -> PARSE_PARSED;
case "unknown", "unparseable" -> PARSE_UNKNOWN_TYPE;
default -> KnownEventTypes.isKnown(fullType) ? PARSE_PARSED : PARSE_UNKNOWN_TYPE;
};
}
private Long insertRawEvent(long bindingId, String eventUid, String sourceEventId, String eventType,
Timestamp sourceTime, Instant receivedAt, String rawPayload, String parseStatus) {
KeyHolder keyHolder = new GeneratedKeyHolder();
byte[] hash = ContentHash.sha256(rawPayload);
jdbc.update(connection -> {
PreparedStatement ps = connection.prepareStatement(
"INSERT INTO raw_event (event_uid, binding_id, source_event_id, event_type, event_time, "
+ "received_at, raw_payload, payload_hash, parse_status, processing_status, retry_count, "
+ "created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0, ?)",
Statement.RETURN_GENERATED_KEYS);
ps.setString(1, eventUid);
ps.setLong(2, bindingId);
ps.setString(3, sourceEventId);
ps.setString(4, truncate(eventType, 128));
ps.setTimestamp(5, sourceTime);
ps.setTimestamp(6, Timestamp.from(receivedAt));
ps.setString(7, rawPayload);
ps.setBytes(8, hash);
ps.setString(9, parseStatus);
ps.setString(10, PROCESS_PENDING);
ps.setTimestamp(11, Timestamp.from(Instant.now()));
return ps;
}, keyHolder);
Number key = keyHolder.getKey();
if (key == null) {
throw new IllegalStateException("raw_event 插入未返回主键");
}
return key.longValue();
}
/**
* 写入去重记录。唯一约束 UNIQUE(binding_id, dedup_key) 冲突即代表重复事件:
* 原始事件仍保留(数据库设计要求保留原始数据),但立即标记为 SKIPPED,
* 使其不会进入解析与后续副作用(重复发送、重复规则执行)。
*/
private boolean recordDedup(long bindingId, Long eventId, String eventUid, DedupKeyFactory.DedupKey dedup) {
if (!dedup.deduplicable()) {
// 无稳定标识时不去重:宁可保留重复记录,也不冒误判丢数据的风险。
return false;
}
try {
jdbc.update("INSERT INTO event_dedup (binding_id, dedup_key, event_uid, dedup_strategy, first_seen_at, "
+ "expires_at) VALUES (?, ?, ?, ?, ?, ?)",
bindingId, dedup.key(), eventUid, dedup.strategy(), Timestamp.from(Instant.now()),
dedup.expiresAt() == null ? null : Timestamp.from(dedup.expiresAt()));
return false;
} catch (DuplicateKeyException e) {
log.info("重复事件已忽略 binding={} dedupKey={} eventUid={}", bindingId, dedup.key(), eventUid);
markProcessed(eventId, PROCESS_SKIPPED, "DUPLICATE_EVENT", "去重键命中已有事件:" + dedup.key());
return true;
}
}
/** 标记事件处理状态,供积压监控与失败排查使用。 */
public void markProcessed(long eventId, String processingStatus, String errorCode, String errorMessage) {
jdbc.update("UPDATE raw_event SET processing_status = ?, last_error_code = ?, last_error_message = ?, "
+ "processed_at = ? WHERE id = ?",
processingStatus, errorCode, sanitize(errorMessage),
PROCESS_PROCESSED.equals(processingStatus) || PROCESS_SKIPPED.equals(processingStatus)
? Timestamp.from(Instant.now()) : null,
eventId);
}
public void bumpRetry(long eventId, String errorCode, String errorMessage) {
jdbc.update("UPDATE raw_event SET processing_status = ?, retry_count = retry_count + 1, "
+ "last_error_code = ?, last_error_message = ? WHERE id = ?",
PROCESS_FAILED, errorCode, sanitize(errorMessage), eventId);
}
/** 错误摘要脱敏:截断长度并去除可能出现的令牌片段。 */
public static String sanitize(String message) {
if (message == null) {
return null;
}
String cleaned = message.replaceAll("(?i)(access_token|authorization|token|password|secret)[=:][^&\\s\"]+",
"$1=***");
return truncate(cleaned, 1000);
}
public static String truncate(String value, int max) {
if (value == null) {
return null;
}
return value.length() <= max ? value : value.substring(0, max);
}
private JsonNode tryParse(String rawPayload) {
try {
JsonNode node = mapper.readTree(rawPayload);
return node != null && node.isObject() ? node : null;
} catch (Exception e) {
return null;
}
}
/** 解析 time 字段(秒级);缺失或非法时返回空,由调用方回退到接收时间。 */
public static Optional<Instant> eventTimeOf(JsonNode event) {
String raw = DedupKeyFactory.text(event, "time");
if (raw == null) {
return Optional.empty();
}
try {
long seconds = Long.parseLong(raw);
// NapCat 时间戳为秒;大于 1e12 视为毫秒。
return Optional.of(seconds > 1_000_000_000_000L
? Instant.ofEpochMilli(seconds)
: Instant.ofEpochSecond(seconds));
} catch (NumberFormatException e) {
return Optional.empty();
}
}
private Timestamp timestampOf(JsonNode event) {
return eventTimeOf(event).map(Timestamp::from).orElse(null);
}
/** 事件解析后的 JSON 访问入口,避免其他模块重复注入 ObjectMapper。 */
public ObjectMapper mapper() {
return mapper;
}
public static class EventTooLargeException extends RuntimeException {
public EventTooLargeException(String message) {
super(message);
}
}
}
@@ -0,0 +1,35 @@
package com.qlinker.event;
import java.util.Set;
/**
* 已适配的事件类型目录。仅用于标记 parse_status 是否为未知类型,
* 不用于丢弃事件:未知类型必须原样入库(AGENTS.md 5.2)。
* 完整能力目录与逐项验证状态属后续任务,本任务不声称全部适配。
*/
public final class KnownEventTypes {
private static final Set<String> KNOWN = Set.of(
"message", "message/message", "message_sent", "message_sent/message",
"meta_event", "meta_event/lifecycle", "meta_event/heartbeat",
"notice", "notice/group_increase", "notice/group_decrease", "notice/notify",
"notice/group_recall", "notice/friend_notify", "notice/tip",
"notice/poke", "notice/essence", "notice/notify/group_msg_reject",
"request", "request/friend", "request/add_group");
public static boolean isKnown(String fullType) {
if (fullType == null) {
return false;
}
if (KNOWN.contains(fullType)) {
return true;
}
// notice/request 的子类型在 NapCat 版本间有差异,主类型已知即视为可解析,
// 子类型差异通过 raw_payload 与 parse_status=PARSED 保留,不丢弃。
String main = fullType.split("/", 2)[0];
return "notice".equals(main) || "request".equals(main);
}
private KnownEventTypes() {
}
}
@@ -0,0 +1,250 @@
package com.qlinker.init;
import com.qlinker.config.QLinkerProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
/**
* 实例初始化编排(架构设计 13.3、AGENTS.md 12 章)。
*
* <p>职责:确定并持久化资源身份、按需创建隔离数据库与 bucket、执行 Flyway 迁移、
* 双向校验身份与真实资源是否一致。任何不一致都进入 RECOVERY_REQUIRED 并阻断业务,
* 绝不自动新建一套空资源继续运行,以免历史数据被遗弃或产生数据分裂。</p>
*
* <p>每一步完成后立即落盘阶段状态,使进程中断后的重启能够判断已完成到哪一步,
* 而不是重复执行可能产生破坏性结果的操作(AGENTS.md 12.3)。</p>
*/
public class BootstrapCoordinator {
private static final Logger log = LoggerFactory.getLogger(BootstrapCoordinator.class);
private final QLinkerProperties properties;
private final InstanceStateStore stateStore;
private final DatabaseProvisioner databaseProvisioner;
private final BucketProvisioner bucketProvisioner;
private final SchemaMigrator schemaMigrator;
private final java.security.SecureRandom random = new java.security.SecureRandom();
private final AtomicReference<InstanceIdentity> identity = new AtomicReference<>();
private final AtomicReference<String> blockedReason = new AtomicReference<>();
public BootstrapCoordinator(QLinkerProperties properties,
InstanceStateStore stateStore,
DatabaseProvisioner databaseProvisioner,
BucketProvisioner bucketProvisioner,
SchemaMigrator schemaMigrator) {
this.properties = properties;
this.stateStore = stateStore;
this.databaseProvisioner = databaseProvisioner;
this.bucketProvisioner = bucketProvisioner;
this.schemaMigrator = schemaMigrator;
}
/**
* 保证实例处于可服务状态。返回已确认的资源身份;无法确认时抛出异常并保留阻断原因。
*/
public synchronized InstanceIdentity ensureReady() {
InstanceIdentity current = identity.get();
if (current != null && current.stage() == InstanceIdentity.Stage.READY) {
return current;
}
try {
InstanceIdentity resolved = doEnsureReady();
identity.set(resolved);
blockedReason.set(null);
return resolved;
} catch (InstanceBlocked e) {
blockedReason.set(e.getMessage());
identity.set(new InstanceIdentity(null, null, null, InstanceIdentity.Stage.RECOVERY_REQUIRED, null));
throw e;
}
}
private InstanceIdentity doEnsureReady() {
Optional<InstanceStateStore.InstanceState> stored = stateStore.read();
if (stored.isEmpty()) {
return firstRun();
}
return resume(stored.get());
}
private InstanceIdentity firstRun() {
if (!properties.getInstance().isBootstrapEnabled()) {
throw new InstanceBlocked("实例尚未初始化,且 qlinker.instance.bootstrap-enabled=false 禁止自动初始化。"
+ "请在部署环境准备隔离数据库与 bucket 后写入状态文件 " + stateStore.stateFile());
}
int maxAttempts = Math.max(1, properties.getInstance().getMaxCreateAttempts());
for (int attempt = 1; attempt <= maxAttempts; attempt++) {
String randomId = ResourceNames.randomId(random, properties.getInstance().getRandomIdLength());
String databaseName = ResourceNames.databaseName(randomId);
String bucketName = ResourceNames.bucketName(randomId);
if (databaseProvisioner.databaseExists(databaseName) || bucketProvisioner.bucketExists(bucketName)) {
log.warn("随机资源名称冲突,重新生成 attempt={} database={}", attempt, databaseName);
continue;
}
String instanceUid = "inst_" + randomId;
// 先落盘名称再创建资源:即使创建过程中进程被中断,重启时也能核实是否已经创建,而不是换一套新名字。
persist(instanceUid, databaseName, bucketName, InstanceIdentity.Stage.PLANNED, null);
if (!databaseProvisioner.databaseExists(databaseName)) {
databaseProvisioner.createDatabase(databaseName);
}
persist(instanceUid, databaseName, bucketName, InstanceIdentity.Stage.DATABASE_CREATED, null);
if (!bucketProvisioner.bucketExists(bucketName)) {
bucketProvisioner.createBucket(bucketName);
}
persist(instanceUid, databaseName, bucketName, InstanceIdentity.Stage.BUCKET_CREATED, null);
String version = schemaMigrator.migrate(databaseBusinessDataSource(databaseName));
persist(instanceUid, databaseName, bucketName, InstanceIdentity.Stage.SCHEMA_MIGRATED, version);
recordInstanceRow(instanceUid, databaseName, bucketName, version);
InstanceIdentity ready = persist(instanceUid, databaseName, bucketName, InstanceIdentity.Stage.READY, version);
log.info("实例初始化完成 instanceUid={} database={} bucket={} schema={}",
instanceUid, databaseName, bucketName, version);
return ready;
}
throw new InstanceBlocked("连续 " + maxAttempts + " 次生成的随机资源名称均与已有资源冲突,请检查命名冲突或加大随机长度");
}
private InstanceIdentity resume(InstanceStateStore.InstanceState state) {
InstanceIdentity current = state.toIdentity();
if (current.stage().isBlocked()) {
throw new InstanceBlocked("实例状态文件处于 RECOVERY_REQUIRED,需要人工确认资源身份后修复状态文件");
}
if (!ResourceNames.isValidDatabaseName(current.databaseName()) || !ResourceNames.isValidBucketName(current.bucketName())) {
throw new InstanceBlocked("实例状态文件中的资源名称不满足命名规则,疑似被篡改或损坏");
}
InstanceIdentity verified = current;
boolean dbExists = safe(() -> databaseProvisioner.databaseExists(verified.databaseName()), "数据库可达性");
if (!dbExists) {
throw new InstanceBlocked("状态文件记录的业务数据库不存在或不可访问 database=" + current.databaseName()
+ ";已拒绝自动创建新资源,请确认数据库是否被删除或连接配置是否变更");
}
boolean bucketExists = safe(() -> bucketProvisioner.bucketExists(verified.bucketName()), "bucket 可达性");
if (!bucketExists) {
throw new InstanceBlocked("状态文件记录的 bucket 不存在或不可访问 bucket=" + current.bucketName()
+ ";已拒绝自动创建新资源,请确认 bucket 是否被删除或凭据是否变更");
}
DataSource ds = databaseBusinessDataSource(current.databaseName());
if (!current.stage().atLeast(InstanceIdentity.Stage.SCHEMA_MIGRATED)) {
String version = schemaMigrator.migrate(ds);
current = persist(current.instanceUid(), current.databaseName(), current.bucketName(),
InstanceIdentity.Stage.SCHEMA_MIGRATED, version);
}
String version = current.stage().atLeast(InstanceIdentity.Stage.SCHEMA_MIGRATED)
? current.schemaVersion()
: schemaMigrator.currentVersion(ds);
verifyInstanceRow(ds, current, version);
if (current.stage() != InstanceIdentity.Stage.READY) {
current = persist(current.instanceUid(), current.databaseName(), current.bucketName(),
InstanceIdentity.Stage.READY, version);
}
log.info("实例身份复用成功 instanceUid={} database={} bucket={}",
current.instanceUid(), current.databaseName(), current.bucketName());
return current;
}
/** system_instance 记录与状态文件必须互相印证,任一侧缺失或不同即视为身份异常。 */
private void verifyInstanceRow(DataSource ds, InstanceIdentity current, String version) {
String sql = "SELECT instance_uid, database_name, bucket_name FROM system_instance WHERE instance_uid = ?";
try (Connection c = ds.getConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, current.instanceUid());
try (ResultSet rs = ps.executeQuery()) {
if (!rs.next()) {
recordInstanceRow(current.instanceUid(), current.databaseName(), current.bucketName(), version);
return;
}
String db = rs.getString("database_name");
String bucket = rs.getString("bucket_name");
if (!current.databaseName().equals(db) || !current.bucketName().equals(bucket)) {
throw new InstanceBlocked("system_instance 记录与状态文件不一致:数据库记录 database=" + db + ", bucket=" + bucket
+ ";状态文件 database=" + current.databaseName() + ", bucket=" + current.bucketName()
+ "。已拒绝自动改写,请人工确认哪一侧为真实资源");
}
}
} catch (InstanceBlocked e) {
throw e;
} catch (Exception e) {
throw new InstanceBlocked("无法读取 system_instance 记录以确认资源身份:" + e.getMessage());
}
}
private void recordInstanceRow(String instanceUid, String databaseName, String bucketName, String version) {
String sql = "INSERT INTO system_instance (instance_uid, instance_name, database_name, bucket_name, "
+ "init_status, schema_version, created_at, updated_at) VALUES (?, ?, ?, ?, 'READY', ?, ?, ?)";
Timestamp now = Timestamp.from(Instant.now());
try (Connection c = databaseBusinessDataSource(databaseName).getConnection();
PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, instanceUid);
ps.setString(2, "QLinker " + instanceUid);
ps.setString(3, databaseName);
ps.setString(4, bucketName);
ps.setString(5, version);
ps.setTimestamp(6, now);
ps.setTimestamp(7, now);
ps.executeUpdate();
} catch (Exception e) {
throw new InstanceBlocked("无法写入 system_instance 资源身份记录:" + e.getMessage());
}
}
private DataSource databaseBusinessDataSource(String databaseName) {
DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
ds.setUrl(databaseProvisioner.businessJdbcUrl(databaseName));
ds.setUsername(properties.getInstance().getMysqlUser());
ds.setPassword(properties.getInstance().getMysqlPassword());
return ds;
}
private InstanceIdentity persist(String instanceUid, String databaseName, String bucketName,
InstanceIdentity.Stage stage, String version) {
stateStore.write(new InstanceStateStore.InstanceState(instanceUid, databaseName, bucketName, stage, version));
return new InstanceIdentity(instanceUid, databaseName, bucketName, stage, version);
}
private boolean safe(java.util.function.BooleanSupplier check, String what) {
try {
return check.getAsBoolean();
} catch (Exception e) {
throw new InstanceBlocked("无法确认" + what + ":" + e.getMessage());
}
}
/** 供状态接口读取的只读快照,不触发初始化。 */
public Optional<InstanceIdentity> peek() {
return Optional.ofNullable(identity.get());
}
public Optional<String> blockedReason() {
return Optional.ofNullable(blockedReason.get());
}
/** 测试与本地开发使用:清空内存快照,强制下一次访问重新核验。 */
public void resetForTest() {
identity.set(null);
blockedReason.set(null);
}
/** 资源身份异常:需要人工介入,禁止自动新建资源。 */
public static class InstanceBlocked extends RuntimeException {
public InstanceBlocked(String message) {
super(message);
}
}
}
@@ -0,0 +1,80 @@
package com.qlinker.init;
import com.qlinker.security.AuthService;
import com.qlinker.security.CryptoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import java.time.Duration;
import java.time.Instant;
/**
* 启动后的初始化收尾(AGENTS.md 12.1、12.3)。
*
* <p>引导令牌只在「尚无管理员且从未签发过令牌」时生成一次,明文只在本进程日志输出一次,
* 数据库仅保存哈希。已初始化的实例重启不会重新签发,也不会重新创建任何资源。</p>
*/
public class BootstrapRunner implements ApplicationRunner {
private static final Logger log = LoggerFactory.getLogger(BootstrapRunner.class);
private static final Duration BOOTSTRAP_TTL = Duration.ofHours(24);
private final BootstrapCoordinator coordinator;
private final AuthService auth;
private final CryptoService crypto;
private final com.qlinker.napcat.NapCatConnectionManager connections;
private final boolean receiverEnabled;
public BootstrapRunner(BootstrapCoordinator coordinator, AuthService auth, CryptoService crypto,
com.qlinker.napcat.NapCatConnectionManager connections, boolean receiverEnabled) {
this.coordinator = coordinator;
this.auth = auth;
this.crypto = crypto;
this.connections = connections;
this.receiverEnabled = receiverEnabled;
}
@Override
public void run(ApplicationArguments args) {
InstanceIdentity identity;
try {
identity = coordinator.ensureReady();
} catch (RuntimeException e) {
log.error("实例资源身份无法确认,管理接口将返回 503 直到人工修复:{}", e.getMessage());
return;
}
log.info("实例就绪 instanceUid={} database={} bucket={} schema={}",
identity.instanceUid(), identity.databaseName(), identity.bucketName(), identity.schemaVersion());
if (receiverEnabled) {
// 事件接收必须在初始化成功后才启动:断线期间事件不补推,落库晚一秒就少一秒数据(能力基线)。
connections.start();
} else {
log.warn("NapCat 事件接收已关闭(qlinker.napcat.receiver-enabled=false),不会接收任何消息");
}
if (auth.hasAdministrator()) {
return;
}
if (auth.hasBootstrapToken()) {
log.warn("实例尚无管理员但已存在引导令牌记录,未重复签发。请使用首次启动时输出的令牌完成初始化");
return;
}
String token = crypto.randomToken(24);
Instant expiresAt = Instant.now().plus(BOOTSTRAP_TTL);
try {
auth.registerBootstrapToken(token, expiresAt);
} catch (RuntimeException e) {
log.error("引导令牌写入失败,无法完成首次初始化:{}", e.toString());
return;
}
// 令牌明文只在此处输出一次,用于本机首次初始化;数据库只保存哈希(AGENTS.md 11.2)。
log.warn("===== 首次初始化引导令牌(仅输出一次,有效期 24 小时)=====");
log.warn("引导令牌: {}", token);
log.warn("请在管理页面或 POST /api/v1/auth/bootstrap 使用该令牌创建唯一管理员账号");
log.warn("==============================================================");
}
}
@@ -0,0 +1,64 @@
package com.qlinker.init;
import com.qlinker.config.QLinkerProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
/**
* 独立 bucket 的创建与核验(AGENTS.md 12.1)。bucket 名由系统生成,不接受用户输入。
*/
public class BucketProvisioner {
private final QLinkerProperties properties;
private final MinioClient client;
public BucketProvisioner(QLinkerProperties properties, MinioClient client) {
this.properties = properties;
this.client = client;
}
public BucketProvisioner(QLinkerProperties properties) {
this(properties, buildClient(properties));
}
public static MinioClient buildClient(QLinkerProperties properties) {
QLinkerProperties.Storage storage = properties.getStorage();
if (storage.getEndpoint() == null || storage.getEndpoint().isBlank()
|| storage.getAccessKey() == null || storage.getAccessKey().isBlank()
|| storage.getSecretKey() == null || storage.getSecretKey().isBlank()) {
throw new IllegalStateException("缺少对象存储配置:qlinker.storage.endpoint / access-key / secret-key");
}
return MinioClient.builder()
.endpoint(storage.getEndpoint())
.credentials(storage.getAccessKey(), storage.getSecretKey())
.region(storage.getRegion())
.build();
}
public MinioClient client() {
return client;
}
public boolean bucketExists(String bucket) {
try {
return client.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
} catch (Exception e) {
throw new IllegalStateException("无法确认 bucket 是否存在:" + e.getMessage(), e);
}
}
/** 幂等创建 bucket;已存在时不改动其策略与内容。 */
public void createBucket(String bucket) {
if (!ResourceNames.isValidBucketName(bucket)) {
throw new IllegalArgumentException("非法 bucket 名");
}
try {
if (!client.bucketExists(BucketExistsArgs.builder().bucket(bucket).build())) {
client.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
}
} catch (Exception e) {
throw new IllegalStateException("bucket 创建失败:" + e.getMessage(), e);
}
}
}
@@ -0,0 +1,78 @@
package com.qlinker.init;
import com.qlinker.config.QLinkerProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* 隔离业务数据库的创建与存在性核验(AGENTS.md 12.1、12.3)。
*
* <p>只执行 {@code CREATE DATABASE IF NOT EXISTS} 与 {@code SELECT SCHEMA_NAME FROM information_schema},
* 不对任何已存在的库执行 ALTER / DROP;库名由 {@link ResourceNames} 生成并做白名单校验后再拼接,
* 不接受任何外部输入。</p>
*/
public class DatabaseProvisioner {
private static final Logger log = LoggerFactory.getLogger(DatabaseProvisioner.class);
private final QLinkerProperties properties;
public DatabaseProvisioner(QLinkerProperties properties) {
this.properties = properties;
}
/** 连接到 MySQL 服务本身(不指定数据库),用于创建与核验业务库。 */
Connection openServerConnection() throws Exception {
QLinkerProperties.Instance cfg = properties.getInstance();
String url = "jdbc:mysql://" + cfg.getMysqlHost() + ":" + cfg.getMysqlPort()
+ "/?useSSL=false&allowPublicKeyRetrieval=true&connectionTimeZone=UTC&forceConnectionTimeZoneToSession=true";
return DriverManager.getConnection(url, cfg.getMysqlUser(), cfg.getMysqlPassword());
}
/** 业务库 JDBC 地址。 */
public String businessJdbcUrl(String databaseName) {
QLinkerProperties.Instance cfg = properties.getInstance();
return "jdbc:mysql://" + cfg.getMysqlHost() + ":" + cfg.getMysqlPort() + "/" + databaseName
+ "?useSSL=false&allowPublicKeyRetrieval=true&characterEncoding=utf8"
+ "&connectionTimeZone=UTC&forceConnectionTimeZoneToSession=true"
+ "&rewriteBatchedStatements=true&serverTimezone=UTC";
}
public boolean databaseExists(String databaseName) {
if (!ResourceNames.isValidDatabaseName(databaseName)) {
throw new IllegalArgumentException("非法数据库名");
}
String sql = "SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = ?";
try (Connection c = openServerConnection(); PreparedStatement ps = c.prepareStatement(sql)) {
ps.setString(1, databaseName);
try (ResultSet rs = ps.executeQuery()) {
return rs.next();
}
} catch (Exception e) {
throw new IllegalStateException("无法确认数据库是否存在:" + e.getMessage(), e);
}
}
/**
* 创建业务库。使用 IF NOT EXISTS 以满足初始化幂等(进程中断后重跑不报错)。
* 排序规则显式指定 utf8mb4_0900_ai_ci,与迁移脚本保持一致,避免依赖服务端默认值。
*/
public void createDatabase(String databaseName) {
if (!ResourceNames.isValidDatabaseName(databaseName)) {
throw new IllegalArgumentException("非法数据库名");
}
String ddl = "CREATE DATABASE IF NOT EXISTS `" + databaseName + "` "
+ "CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci";
try (Connection c = openServerConnection(); PreparedStatement ps = c.prepareStatement(ddl)) {
ps.execute();
log.info("业务数据库已就绪 database={}", databaseName);
} catch (Exception e) {
throw new IllegalStateException("业务数据库创建失败:" + e.getMessage(), e);
}
}
}
@@ -0,0 +1,52 @@
package com.qlinker.init;
/**
* 实例身份与已创建资源的绑定关系。一旦持久化,后续启动只能复用,不得随机替换
* (AGENTS.md 12.2、架构设计 13.3)。
*
* @param instanceUid QLinker 稳定身份
* @param databaseName 实际业务数据库名
* @param bucketName 实际对象存储 bucket 名
* @param stage 初始化阶段,用于中断后判断已完成到哪一步
* @param schemaVersion 已应用的数据库结构版本
*/
public record InstanceIdentity(String instanceUid,
String databaseName,
String bucketName,
Stage stage,
String schemaVersion) {
/**
* 初始化阶段(架构设计 13.3)。顺序即恢复顺序,只允许向前推进。
*/
public enum Stage {
/** 已确定资源名称但尚未创建任何资源。 */
PLANNED,
/** 业务数据库已创建。 */
DATABASE_CREATED,
/** bucket 已创建。 */
BUCKET_CREATED,
/** 数据库结构迁移已完成。 */
SCHEMA_MIGRATED,
/** 初始化完成,可对外提供服务。 */
READY,
/** 身份与真实资源不一致或资源缺失,需要人工介入;此状态下禁止自动新建资源。 */
RECOVERY_REQUIRED;
public boolean isBlocked() {
return this == RECOVERY_REQUIRED;
}
boolean atLeast(Stage other) {
return this.ordinal() >= other.ordinal();
}
}
public InstanceIdentity withStage(Stage newStage) {
return new InstanceIdentity(instanceUid, databaseName, bucketName, newStage, schemaVersion);
}
public InstanceIdentity withSchemaVersion(String version) {
return new InstanceIdentity(instanceUid, databaseName, bucketName, stage, version);
}
}
@@ -0,0 +1,95 @@
package com.qlinker.init;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.util.Optional;
/**
* 实例身份状态文件:资源身份的持久化载体,也是重启后复用资源的唯一依据。
*
* <p>选择本地文件而非业务库,是因为业务库本身要等身份确定后才能连接;
* 状态文件与业务库/bucket 中的 {@code system_instance} 记录构成双向校验,
* 任一侧缺失或不一致时进入 RECOVERY_REQUIRED,禁止自动新建资源(AGENTS.md 12.2)。</p>
*/
public class InstanceStateStore {
private static final Logger log = LoggerFactory.getLogger(InstanceStateStore.class);
public static final String FILE_NAME = "instance-state.json";
private final Path file;
private final ObjectMapper mapper = new ObjectMapper();
public InstanceStateStore(String stateDir) {
this.file = Path.of(stateDir).resolve(FILE_NAME);
}
public Path stateFile() {
return file;
}
public Optional<InstanceState> read() {
if (!Files.exists(file)) {
return Optional.empty();
}
try {
ObjectNode node = (ObjectNode) mapper.readTree(Files.readString(file, StandardCharsets.UTF_8));
return Optional.of(new InstanceState(
text(node, "instanceUid"),
text(node, "databaseName"),
text(node, "bucketName"),
InstanceIdentity.Stage.valueOf(node.path("stage").asText(InstanceIdentity.Stage.PLANNED.name())),
node.path("schemaVersion").asText(null)));
} catch (Exception e) {
// 状态文件损坏不能被视为「未初始化」,否则会绕过保护重新创建一套空资源。
log.error("实例状态文件无法解析 path={} error={}", file, e.toString());
return Optional.of(new InstanceState(null, null, null, InstanceIdentity.Stage.RECOVERY_REQUIRED, null));
}
}
public void write(InstanceState state) {
try {
Files.createDirectories(file.getParent());
ObjectNode node = mapper.createObjectNode();
node.put("instanceUid", state.instanceUid());
node.put("databaseName", state.databaseName());
node.put("bucketName", state.bucketName());
node.put("stage", state.stage().name());
node.put("schemaVersion", state.schemaVersion());
Path tmp = file.resolveSibling(FILE_NAME + ".tmp");
Files.writeString(tmp, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(node),
StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
try {
Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} catch (IOException e) {
Files.move(tmp, file, StandardCopyOption.REPLACE_EXISTING);
}
} catch (IOException e) {
throw new IllegalStateException("实例状态文件写入失败 path=" + file, e);
}
}
private static String text(ObjectNode node, String field) {
String value = node.path(field).asText(null);
return value == null || value.isBlank() ? null : value;
}
public record InstanceState(String instanceUid,
String databaseName,
String bucketName,
InstanceIdentity.Stage stage,
String schemaVersion) {
public InstanceIdentity toIdentity() {
return new InstanceIdentity(instanceUid, databaseName, bucketName, stage, schemaVersion);
}
}
}
@@ -0,0 +1,65 @@
package com.qlinker.init;
import java.security.SecureRandom;
import java.util.Locale;
import java.util.regex.Pattern;
/**
* 隔离资源命名(AGENTS.md 12.1)。
*
* <p>随机标识使用 {@link SecureRandom},字符集为小写字母与数字:对象存储 bucket 名
* 只允许小写字母、数字与连字符;MySQL 的 {@code lower_case_table_names=1} 会把库名
* 折叠为小写,而 Linux 上更常见的 {@code lower_case_table_names=0} 区分大小写。</p>
*
* <p>本项目始终只生成、持久化并使用同一个小写库名,因此两种设置下身份名与实际资源名
* 都保持一致;与 AGENTS.md 12.1 写作 {@code Qlinker_} 的差异仅是命名书写大小写,
* 不改变隔离边界,也不影响 Flyway 迁移。不得为对齐书写而重命名已初始化实例的库或 bucket。</p>
*/
public final class ResourceNames {
/** 数据库名前缀。与 AGENTS.md 12.1 的书写大小写差异及 Linux 影响见任务 004 交付文档。 */
public static final String DATABASE_PREFIX = "qlinker_";
public static final String BUCKET_PREFIX = "qlinker-";
private static final char[] ALPHABET = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
private static final Pattern DATABASE_NAME = Pattern.compile("^qlinker_[a-z0-9]{8}$");
private static final Pattern BUCKET_NAME = Pattern.compile("^qlinker-[a-z0-9]{8}$");
private ResourceNames() {
}
public static String randomId(SecureRandom random, int length) {
if (length < 6 || length > 32) {
throw new IllegalArgumentException("随机标识长度必须在 6 到 32 之间");
}
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
sb.append(ALPHABET[random.nextInt(ALPHABET.length)]);
}
return sb.toString();
}
public static String databaseName(String randomId) {
String name = (DATABASE_PREFIX + randomId).toLowerCase(Locale.ROOT);
if (!DATABASE_NAME.matcher(name).matches()) {
throw new IllegalArgumentException("数据库名不满足命名规则: " + name);
}
return name;
}
public static String bucketName(String randomId) {
String name = (BUCKET_PREFIX + randomId).toLowerCase(Locale.ROOT);
if (!BUCKET_NAME.matcher(name).matches() || name.length() > 63) {
throw new IllegalArgumentException("bucket 名不满足命名规则: " + name);
}
return name;
}
public static boolean isValidDatabaseName(String name) {
return name != null && DATABASE_NAME.matcher(name).matches();
}
public static boolean isValidBucketName(String name) {
return name != null && BUCKET_NAME.matcher(name).matches();
}
}
@@ -0,0 +1,41 @@
package com.qlinker.init;
import org.flywaydb.core.Flyway;
import org.flywaydb.core.api.MigrationInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.sql.DataSource;
/**
* 显式执行 Flyway 迁移。迁移只在初始化编排内触发,不依赖 Spring Boot 的自动迁移,
* 保证「先确定资源身份、再建表」的顺序可控(数据库设计 20.1、20.2)。
*/
public class SchemaMigrator {
private static final Logger log = LoggerFactory.getLogger(SchemaMigrator.class);
public String migrate(DataSource dataSource) {
Flyway flyway = Flyway.configure()
.dataSource(dataSource)
.locations("classpath:db/migration")
.baselineOnMigrate(false)
.cleanDisabled(true)
.table("flyway_schema_history")
.load();
var result = flyway.migrate();
String version = currentVersion(dataSource);
log.info("数据库迁移完成 applied={} version={}", result.migrationsExecuted, version);
return version;
}
public String currentVersion(DataSource dataSource) {
Flyway flyway = Flyway.configure()
.dataSource(dataSource)
.locations("classpath:db/migration")
.table("flyway_schema_history")
.load();
MigrationInfo current = flyway.info().current();
return current == null || current.getVersion() == null ? null : current.getVersion().getVersion();
}
}
@@ -0,0 +1,377 @@
package com.qlinker.media;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qlinker.config.QLinkerProperties;
import com.qlinker.event.ContentHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import java.io.ByteArrayInputStream;
import java.security.MessageDigest;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HexFormat;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* 媒体落库与状态跟踪(AGENTS.md 7.3、数据库设计 9.1/9.2)。
*
* <p>设计取舍:NapCat 媒体 CDN URL 含时效性 rkey,history 又不可翻页,因此必须在事件到达后
* 立即尝试下载。下载失败不阻塞消息落库,只把 media_object 标记为可诊断的失败状态,
* 由管理页面展示真实状态而不是假装已存储。</p>
*/
public class MediaService {
private static final Logger log = LoggerFactory.getLogger(MediaService.class);
public static final String STATUS_PENDING = "PENDING";
public static final String STATUS_DOWNLOADING = "DOWNLOADING";
public static final String STATUS_STORED = "STORED";
public static final String STATUS_FAILED = "FAILED";
public static final String STATUS_SOURCE_EXPIRED = "SOURCE_EXPIRED";
public static final String STATUS_OBJECT_MISSING = "OBJECT_MISSING";
private static final List<String> MEDIA_SEGMENT_TYPES = List.of("image", "record", "video", "file");
private final JdbcTemplate jdbc;
private final ObjectMapper mapper;
private final SecureDownloadClient downloader;
private final com.qlinker.storage.StorageService storage;
private final QLinkerProperties.Media config;
public MediaService(JdbcTemplate jdbc,
ObjectMapper mapper,
SecureDownloadClient downloader,
com.qlinker.storage.StorageService storage,
QLinkerProperties.Media config) {
this.jdbc = jdbc;
this.mapper = mapper;
this.downloader = downloader;
this.storage = storage;
this.config = config;
}
public record MediaView(String mediaUid, String mediaType, String storageStatus, String fileName,
String mimeType, Long fileSize, String errorCode, String errorMessage,
Instant createdAt, Instant updatedAt) {
}
/**
* 为消息中的媒体段登记媒体对象。消息已落库后调用;登记失败只记录日志,
* 不得回滚消息本身(消息完整性优先于媒体可用性)。
*/
public int registerForMessage(long messageId) {
List<Long> bindingIds = jdbc.queryForList("SELECT binding_id FROM message WHERE id = ?",
Long.class, messageId);
if (bindingIds.isEmpty()) {
return 0;
}
long bindingId = bindingIds.get(0);
List<Map<String, Object>> segments = jdbc.queryForList(
"SELECT id, segment_type, raw_segment FROM message_segment WHERE message_id = ? ORDER BY segment_index",
messageId);
int created = 0;
for (Map<String, Object> segment : segments) {
String type = (String) segment.get("segment_type");
if (!MEDIA_SEGMENT_TYPES.contains(type)) {
continue;
}
try {
JsonNode raw = mapper.readTree(String.valueOf(segment.get("raw_segment")));
JsonNode data = raw.path("data");
String sourceUrl = firstText(data, "url", "file", "path");
String sourceMediaId = firstText(data, "file_id", "fileId", "id");
String fileName = firstText(data, "file_name", "name", "file");
Long mediaId = create(bindingId, type, sourceMediaId, sourceUrl, fileName);
if (mediaId != null) {
jdbc.update("UPDATE message_segment SET media_object_id = ? WHERE id = ?",
mediaId, segment.get("id"));
created++;
}
} catch (Exception e) {
log.warn("媒体段登记失败已跳过 segmentId={} type={} error={}",
segment.get("id"), type, e.toString());
}
}
return created;
}
/** 创建媒体记录并立即尝试下载;返回 media_object.id,参数不足以下载时返回 null。 */
private Long create(long bindingId, String mediaType, String sourceMediaId, String sourceUrl, String fileName) {
boolean hasUrl = sourceUrl != null && (sourceUrl.startsWith("http://") || sourceUrl.startsWith("https://"));
if (!hasUrl && sourceMediaId == null) {
return null;
}
Instant now = Instant.now();
String mediaUid = "med_" + ContentHash.hex(String.valueOf(now.toEpochMilli()) + "|" + mediaType + "|"
+ (sourceMediaId == null ? sourceUrl : sourceMediaId)).substring(0, 24);
String initialStatus = hasUrl ? STATUS_PENDING : STATUS_FAILED;
String errorCode = hasUrl ? null : "NO_DOWNLOADABLE_URL";
String errorMessage = hasUrl ? null : "上游未提供可下载的 http(s) 地址";
try {
jdbc.update("INSERT INTO media_object (media_uid, source_binding_id, source_media_id, file_name, "
+ "media_type, storage_status, security_status, source_url_hash, last_error_code, "
+ "last_error_message, retention_until, created_at, updated_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, 'PENDING', ?, ?, ?, ?, ?, ?)",
mediaUid, bindingId, sourceMediaId, sanitizeName(fileName), mediaType, initialStatus,
sourceUrl == null ? null : ContentHash.hex(sourceUrl),
errorCode, errorMessage,
Timestamp.from(now.plus(Duration.ofDays(config.getRetentionDays()))),
Timestamp.from(now), Timestamp.from(now));
} catch (DuplicateKeyException e) {
List<Long> ids = jdbc.queryForList("SELECT id FROM media_object WHERE media_uid = ?", Long.class, mediaUid);
return ids.isEmpty() ? null : ids.get(0);
}
Long id = jdbc.queryForObject("SELECT id FROM media_object WHERE media_uid = ?", Long.class, mediaUid);
if (hasUrl) {
attemptDownload(id, sourceUrl);
}
return id;
}
/** 同步执行一次下载与上传。调用方已在异步线程中,不得在事件接收线程直接调用。 */
public void attemptDownload(long mediaId, String sourceUrl) {
Instant startedAt = Instant.now();
jdbc.update("UPDATE media_object SET storage_status = ?, updated_at = ? WHERE id = ? AND storage_status = ?",
STATUS_DOWNLOADING, Timestamp.from(startedAt), mediaId, STATUS_PENDING);
Long operationId = startOperation(mediaId, "download", startedAt);
try {
SecureDownloadClient.Downloaded downloaded = downloader.download(sourceUrl);
String sniffedType = sniffMimeType(downloaded.bytes(), downloaded.declaredContentType());
String objectKey = objectKeyOf(mediaId, sniffedType);
storage.put(objectKey, new ByteArrayInputStream(downloaded.bytes()), downloaded.size(), sniffedType);
Instant finishedAt = Instant.now();
jdbc.update("UPDATE media_object SET storage_status = ?, storage_bucket = ?, object_key = ?, "
+ "mime_type = ?, file_size = ?, content_hash = ?, last_error_code = NULL, "
+ "last_error_message = NULL, updated_at = ? WHERE id = ?",
STATUS_STORED, storage.bucket(), objectKey, sniffedType, downloaded.size(),
sha256Bytes(downloaded.bytes()), Timestamp.from(finishedAt), mediaId);
finishOperation(operationId, "SUCCEEDED", null, null, finishedAt);
log.info("媒体已存储 mediaId={} size={} type={}", mediaId, downloaded.size(), sniffedType);
} catch (SecureDownloadClient.DownloadRejectedException e) {
Instant finishedAt = Instant.now();
String status = mapStatus(e.reasonCode());
jdbc.update("UPDATE media_object SET storage_status = ?, last_error_code = ?, last_error_message = ?, "
+ "updated_at = ? WHERE id = ?", status, e.reasonCode(),
com.qlinker.event.EventIngestService.sanitize(e.getMessage()), Timestamp.from(finishedAt), mediaId);
finishOperation(operationId, "FAILED", e.reasonCode(), e.getMessage(), finishedAt);
log.warn("媒体下载失败 mediaId={} reason={} message={}", mediaId, e.reasonCode(), e.getMessage());
} catch (Exception e) {
Instant finishedAt = Instant.now();
jdbc.update("UPDATE media_object SET storage_status = ?, last_error_code = ?, last_error_message = ?, "
+ "updated_at = ? WHERE id = ?", STATUS_FAILED, "STORAGE_FAILED",
com.qlinker.event.EventIngestService.sanitize(e.toString()), Timestamp.from(finishedAt), mediaId);
finishOperation(operationId, "FAILED", "STORAGE_FAILED", e.toString(), finishedAt);
log.error("媒体写入对象存储失败 mediaId={} error={}", mediaId, e.toString());
}
}
static String mapStatus(String reasonCode) {
if (reasonCode == null) {
return STATUS_FAILED;
}
if (reasonCode.startsWith("SOURCE_HTTP_") || SecureDownloadClient.ERROR_TIMEOUT.equals(reasonCode)) {
// NapCat 媒体 URL 带时效 rkey,超时/4xx 多数是链接已过期。
return STATUS_SOURCE_EXPIRED;
}
return STATUS_FAILED;
}
public Optional<MediaView> find(String mediaUid) {
List<MediaView> rows = jdbc.query("SELECT * FROM media_object WHERE media_uid = ?", this::mapView, mediaUid);
return rows.stream().findFirst();
}
public List<MediaView> ofMessage(long messageId) {
return jdbc.query("SELECT m.* FROM media_object m JOIN message_segment s ON s.media_object_id = m.id "
+ "WHERE s.message_id = ? ORDER BY s.segment_index", this::mapView, messageId);
}
/** 读取可访问 URL。对象缺失时把状态修正为 OBJECT_MISSING,而不是返回一个坏链接。 */
public Optional<String> accessUrl(String mediaUid) {
List<Map<String, Object>> rows = jdbc.queryForList(
"SELECT storage_status, object_key FROM media_object WHERE media_uid = ?", mediaUid);
if (rows.isEmpty()) {
return Optional.empty();
}
String objectKey = (String) rows.get(0).get("object_key");
if (!STATUS_STORED.equals(rows.get(0).get("storage_status")) || objectKey == null) {
return Optional.empty();
}
if (!storage.exists(objectKey)) {
jdbc.update("UPDATE media_object SET storage_status = ?, last_error_code = ?, updated_at = ? WHERE media_uid = ?",
STATUS_OBJECT_MISSING, "OBJECT_MISSING", Timestamp.from(Instant.now()), mediaUid);
return Optional.empty();
}
try {
return Optional.of(storage.presignedGetUrl(objectKey));
} catch (Exception e) {
log.warn("生成媒体访问地址失败 media={} error={}", mediaUid, e.toString());
return Optional.empty();
}
}
public Map<String, Long> statusCounts() {
Map<String, Long> out = new java.util.LinkedHashMap<>();
for (String status : List.of(STATUS_PENDING, STATUS_DOWNLOADING, STATUS_STORED, STATUS_FAILED,
STATUS_SOURCE_EXPIRED, STATUS_OBJECT_MISSING)) {
Integer count = jdbc.queryForObject("SELECT COUNT(*) FROM media_object WHERE storage_status = ?",
Integer.class, status);
out.put(status, count == null ? 0L : count.longValue());
}
return out;
}
private MediaView mapView(java.sql.ResultSet rs, int rowNum) throws java.sql.SQLException {
return new MediaView(
rs.getString("media_uid"),
rs.getString("media_type"),
rs.getString("storage_status"),
rs.getString("file_name"),
rs.getString("mime_type"),
rs.getObject("file_size") == null ? null : rs.getLong("file_size"),
rs.getString("last_error_code"),
rs.getString("last_error_message"),
instant(rs, "created_at"),
instant(rs, "updated_at"));
}
private static Instant instant(java.sql.ResultSet rs, String column) throws java.sql.SQLException {
Timestamp value = rs.getTimestamp(column);
return value == null ? null : value.toInstant();
}
private Long startOperation(long mediaId, String type, Instant startedAt) {
jdbc.update("INSERT INTO media_operation (media_object_id, operation_type, operation_status, retry_count, "
+ "started_at, created_at, updated_at) VALUES (?, ?, 'RUNNING', 0, ?, ?, ?)",
mediaId, type, Timestamp.from(startedAt), Timestamp.from(startedAt), Timestamp.from(startedAt));
return jdbc.queryForObject("SELECT LAST_INSERT_ID()", Long.class);
}
private void finishOperation(Long operationId, String status, String code, String message, Instant finishedAt) {
if (operationId == null) {
return;
}
jdbc.update("UPDATE media_operation SET operation_status = ?, finished_at = ?, last_error_code = ?, "
+ "last_error_message = ?, updated_at = ? WHERE id = ?",
status, Timestamp.from(finishedAt), code,
com.qlinker.event.EventIngestService.sanitize(message), Timestamp.from(finishedAt), operationId);
}
/** 对象 key 完全由系统生成,不接受上游文件名或用户输入拼接(AGENTS.md 7.3)。 */
static String objectKeyOf(long mediaId, String mimeType) {
String extension = extensionOf(mimeType);
return "media/" + mediaId + "/" + System.currentTimeMillis() + extension;
}
/** 只按真实字节特征判定类型,不信任上游 Content-Type 或文件名扩展名。 */
static String sniffMimeType(byte[] bytes, String declared) {
if (bytes == null || bytes.length == 0) {
return "application/octet-stream";
}
if (starts(bytes, 0xFF, 0xD8, 0xFF)) {
return "image/jpeg";
}
if (starts(bytes, 0x89, 'P', 'N', 'G', 0x0D, 0x0A, 0x1A, 0x0A)) {
return "image/png";
}
if (starts(bytes, 'G', 'I', 'F', '8')) {
return "image/gif";
}
if (starts(bytes, 'R', 'I', 'F', 'F') && bytes.length > 11
&& bytes[8] == 'W' && bytes[9] == 'E' && bytes[10] == 'B' && bytes[11] == 'P') {
return "image/webp";
}
if (starts(bytes, 'R', 'I', 'F', 'F')) {
return "audio/wav";
}
if (starts(bytes, 'A', 'M', 'R')) {
return "audio/amr";
}
if (bytes.length > 11 && bytes[4] == 'f' && bytes[5] == 't' && bytes[6] == 'y' && bytes[7] == 'p') {
return "video/mp4";
}
if (starts(bytes, 'O', 'g', 'g', 'S')) {
return "audio/ogg";
}
if (starts(bytes, 0x25, 'P', 'D', 'F')) {
return "application/pdf";
}
if (starts(bytes, '<', '?', 'x', 'm', 'l') || starts(bytes, '<', 'h', 't', 'm', 'l')) {
return "text/plain";
}
return declared == null || declared.isBlank() ? "application/octet-stream" : declared.split(";")[0].trim();
}
private static boolean starts(byte[] bytes, int... prefix) {
if (bytes.length < prefix.length) {
return false;
}
for (int i = 0; i < prefix.length; i++) {
if ((bytes[i] & 0xFF) != (prefix[i] & 0xFF)) {
return false;
}
}
return true;
}
private static String extensionOf(String mimeType) {
return switch (mimeType == null ? "" : mimeType) {
case "image/jpeg" -> ".jpg";
case "image/png" -> ".png";
case "image/gif" -> ".gif";
case "image/webp" -> ".webp";
case "audio/amr" -> ".amr";
case "audio/ogg" -> ".ogg";
case "audio/wav" -> ".wav";
case "video/mp4" -> ".mp4";
case "application/pdf" -> ".pdf";
case "text/plain" -> ".txt";
default -> ".bin";
};
}
private static byte[] sha256Bytes(byte[] bytes) {
try {
return MessageDigest.getInstance("SHA-256").digest(bytes);
} catch (Exception e) {
return null;
}
}
/** 展示用文件名清理:去掉路径分隔符与控制字符,防止污染日志与前端渲染。 */
static String sanitizeName(String name) {
if (name == null || name.isBlank()) {
return null;
}
String base = name.replace('\\', '/');
base = base.substring(base.lastIndexOf('/') + 1);
base = base.replaceAll("[\\p{Cntrl}]", "").trim();
if (base.length() > 180) {
base = base.substring(base.length() - 180);
}
return base.isEmpty() ? null : base;
}
private static String firstText(JsonNode node, String... fields) {
List<String> values = new ArrayList<>();
for (String field : fields) {
JsonNode value = node == null ? null : node.get(field);
if (value != null && value.isTextual() && !value.asText().isBlank()) {
values.add(value.asText().trim());
}
}
return values.isEmpty() ? null : values.get(0);
}
static String hexOf(byte[] bytes) {
return bytes == null ? null : HexFormat.of().formatHex(bytes);
}
}
@@ -0,0 +1,200 @@
package com.qlinker.media;
import com.qlinker.config.QLinkerProperties;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ProxySelector;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
/**
* 受限的媒体下载客户端(AGENTS.md 7.3、11.3)。
*
* <p>SSRF 防护要点:只允许 http/https;关闭自动重定向(重定向可绕过首次地址校验);
* 解析全部 A/AAAA 记录后逐个校验,默认拒绝回环、私网、链路本地与组播地址;
* 强制超时与字节上限,超限立即中断而不是先读满内存。</p>
*/
public class SecureDownloadClient {
public static final String REJECT_SCHEME = "URL_SCHEME_NOT_ALLOWED";
public static final String REJECT_HOST = "URL_HOST_NOT_ALLOWED";
public static final String REJECT_PRIVATE_NETWORK = "URL_PRIVATE_NETWORK_BLOCKED";
public static final String ERROR_TOO_LARGE = "MEDIA_TOO_LARGE";
public static final String ERROR_TIMEOUT = "DOWNLOAD_TIMEOUT";
private final HttpClient http;
private final long maxBytes;
private final Duration timeout;
private final boolean allowPrivateNetwork;
public SecureDownloadClient(QLinkerProperties.Media config) {
this.maxBytes = config.getMaxBytes();
this.timeout = config.getDownloadTimeout();
this.allowPrivateNetwork = config.isAllowPrivateNetwork();
this.http = HttpClient.newBuilder()
.connectTimeout(timeout)
.followRedirects(HttpClient.Redirect.NEVER)
.proxy(ProxySelector.getDefault())
.build();
}
/** 下载被拒绝时抛出,携带可对外展示的稳定原因码。 */
public static class DownloadRejectedException extends RuntimeException {
private final String reasonCode;
public DownloadRejectedException(String reasonCode, String message) {
super(message);
this.reasonCode = reasonCode;
}
public String reasonCode() {
return reasonCode;
}
}
public record Downloaded(byte[] bytes, String declaredContentType, long size) {
}
public Downloaded download(String rawUrl) {
URI uri = validateUri(rawUrl);
HttpRequest request = HttpRequest.newBuilder(uri)
.timeout(timeout)
.GET()
.build();
try {
HttpResponse<InputStream> response = http.send(request, HttpResponse.BodyHandlers.ofInputStream());
int status = response.statusCode();
if (status >= 300 && status < 400) {
// 不跟随重定向:目标地址未经校验,可能指向内网(AGENTS.md 11.3)。
throw new DownloadRejectedException(REJECT_HOST, "下载目标发生重定向,已按安全策略中止");
}
if (status < 200 || status >= 300) {
closeQuietly(response.body());
throw new DownloadRejectedException("SOURCE_HTTP_" + status, "来源返回 HTTP " + status);
}
long declared = response.headers().firstValueAsLong("Content-Length").orElse(-1);
if (declared > maxBytes) {
closeQuietly(response.body());
throw new DownloadRejectedException(ERROR_TOO_LARGE,
"媒体大小 " + declared + " 超过上限 " + maxBytes);
}
try (InputStream in = response.body()) {
byte[] bytes = readCapped(in);
String contentType = response.headers().firstValue("Content-Type").orElse(null);
return new Downloaded(bytes, contentType, bytes.length);
}
} catch (DownloadRejectedException e) {
throw e;
} catch (java.net.http.HttpTimeoutException e) {
throw new DownloadRejectedException(ERROR_TIMEOUT, "下载超时");
} catch (IOException e) {
throw new DownloadRejectedException("DOWNLOAD_FAILED", "下载失败:" + e.getMessage());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new DownloadRejectedException(ERROR_TIMEOUT, "下载被中断");
}
}
private byte[] readCapped(InputStream in) throws IOException {
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream(Math.min(1 << 20, (int) Math.min(maxBytes, 1 << 20)));
byte[] buffer = new byte[64 * 1024];
long total = 0;
int read;
while ((read = in.read(buffer)) > 0) {
total += read;
if (total > maxBytes) {
throw new DownloadRejectedException(ERROR_TOO_LARGE, "媒体超过大小上限 " + maxBytes);
}
out.write(buffer, 0, read);
}
return out.toByteArray();
}
/** 校验协议、主机名与解析后的地址范围。 */
URI validateUri(String rawUrl) {
URI uri;
try {
uri = URI.create(rawUrl.trim());
} catch (IllegalArgumentException e) {
throw new DownloadRejectedException(REJECT_HOST, "下载地址不合法");
}
String scheme = uri.getScheme();
if (scheme == null || !(scheme.equalsIgnoreCase("http") || scheme.equalsIgnoreCase("https"))) {
throw new DownloadRejectedException(REJECT_SCHEME, "只允许 http/https 下载地址");
}
String host = uri.getHost();
if (host == null || host.isBlank()) {
throw new DownloadRejectedException(REJECT_HOST, "下载地址缺少主机名");
}
if (uri.getUserInfo() != null) {
throw new DownloadRejectedException(REJECT_HOST, "下载地址不得携带用户信息");
}
if (allowPrivateNetwork) {
return uri;
}
List<InetAddress> addresses;
try {
addresses = new ArrayList<>(List.of(InetAddress.getAllByName(host)));
} catch (IOException e) {
throw new DownloadRejectedException("DNS_FAILED", "下载地址解析失败");
}
for (InetAddress address : addresses) {
if (isForbidden(address)) {
throw new DownloadRejectedException(REJECT_PRIVATE_NETWORK,
"下载地址指向内网或保留地址,已按安全策略拒绝");
}
}
return uri;
}
static boolean isForbidden(InetAddress address) {
return address.isLoopbackAddress()
|| address.isAnyLocalAddress()
|| address.isLinkLocalAddress()
|| address.isSiteLocalAddress()
|| address.isMulticastAddress()
|| isCarrierGradeNat(address)
|| isUniqueLocalIpv6(address);
}
/** 100.64.0.0/10(运营商级 NAT)不被 Java 归类为私网,但同样属于不可公开访问范围。 */
private static boolean isCarrierGradeNat(InetAddress address) {
byte[] bytes = address.getAddress();
return bytes.length == 4 && (bytes[0] & 0xFF) == 100 && (bytes[1] & 0xFF) >= 64 && (bytes[1] & 0xFF) <= 127;
}
/** fc00::/7 唯一本地地址。 */
private static boolean isUniqueLocalIpv6(InetAddress address) {
byte[] bytes = address.getAddress();
return bytes.length == 16 && (bytes[0] & 0xFE) == 0xFC;
}
private static void closeQuietly(java.io.Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (IOException ignored) {
// 关闭失败不影响错误上报。
}
}
/** 供测试与本地开发判断当前是否放行内网地址。 */
public boolean allowPrivateNetwork() {
return allowPrivateNetwork;
}
public InetSocketAddress probeTarget(String rawUrl) {
URI uri = validateUri(rawUrl);
return new InetSocketAddress(uri.getHost(), uri.getPort() > 0 ? uri.getPort()
: (uri.getScheme().equalsIgnoreCase("https") ? 443 : 80));
}
}
@@ -0,0 +1,237 @@
package com.qlinker.message;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qlinker.event.ContentHash;
import com.qlinker.event.DedupKeyFactory;
import com.qlinker.event.EventIngestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.JdbcTemplate;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* 事件到归一化消息的转换(AGENTS.md 7.1、7.2)。
*
* <p>归一化结果与原始数据并存:message / message_segment 只用于查询与展示,
* raw_event.raw_payload 始终是唯一的原始副本,重新解析以它为准。
* 段顺序必须保留,未知段类型不得丢弃也不得强行转换。</p>
*/
public class MessageNormalizer {
private static final Logger log = LoggerFactory.getLogger(MessageNormalizer.class);
public static final String DIRECTION_INBOUND = "INBOUND";
public static final String DIRECTION_OUTBOUND = "OUTBOUND";
public static final String STATUS_PARSED = "PARSED";
public static final String STATUS_PARTIAL = "PARTIAL";
public static final String STATUS_UNKNOWN = "UNKNOWN";
/** 已识别的消息段类型。其余一律标记 UNKNOWN 并保留原样。 */
private static final Set<String> KNOWN_SEGMENTS = Set.of(
"text", "face", "at", "reply", "image", "record", "video", "file", "json", "xml",
"poke", "location", "music", "contact", "share", "shakker", "gift", "animisedemoji",
"node", "forward", "news", "item", "miniapp", "dialog", "question");
/**
* 不可作为用户正文的渲染占位类型。news 等段在 NapCat 中会渲染成占位串,
* 直接入库会把渲染文本当作用户正文(能力基线实测结论)。
*/
private static final Set<String> PLACEHOLDER_SEGMENTS = Set.of("news", "node", "forward", "item");
private final JdbcTemplate jdbc;
private final ObjectMapper mapper;
public MessageNormalizer(JdbcTemplate jdbc, ObjectMapper mapper) {
this.jdbc = jdbc;
this.mapper = mapper;
}
/** 归一化结果,含是否包含未知段。 */
public record Result(Long messageId, String messageUid, boolean hasUnknownSegment) {
}
/**
* 把一条已落库的事件归一化为消息。非消息事件返回空结果并标记 SKIPPED,
* 不产生消息记录,但事件本身保留可查。
*/
public Result normalize(long bindingId, long eventId, String rawPayload) {
JsonNode event;
try {
event = mapper.readTree(rawPayload);
} catch (Exception e) {
return new Result(null, null, false);
}
String postType = DedupKeyFactory.text(event, "post_type");
if (!"message".equals(postType) && !"message_sent".equals(postType)) {
return new Result(null, null, false);
}
DedupKeyFactory.Conversation conversation = DedupKeyFactory.conversationOf(event);
if (conversation == null) {
// 无法确定会话范围时不建消息记录:缺少会话二元组会破坏查询与去重语义(GC-022)。
log.warn("消息事件缺少会话标识已跳过归一化 binding={} eventId={}", bindingId, eventId);
return new Result(null, null, true);
}
// 自发消息回推使用 post_type=message_sent,不能只匹配 post_type=message(能力基线实测)。
String direction = "message_sent".equals(postType) ? DIRECTION_OUTBOUND : DIRECTION_INBOUND;
String sourceMessageId = DedupKeyFactory.text(event, "message_id");
String senderId = firstText(event, "sender_id", "user_id", "target_id");
String senderName = null;
JsonNode sender = event.get("sender");
if (sender != null && sender.isObject()) {
senderName = firstText(sender, "card", "nickname", "name");
}
if (DIRECTION_OUTBOUND.equals(direction)) {
senderName = senderName == null ? "本人" : senderName;
}
List<Segment> segments = segmentsOf(event.get("message"));
boolean hasUnknown = segments.stream().anyMatch(s -> !s.known());
Instant messageTime = EventIngestService.eventTimeOf(event).orElseGet(Instant::now);
String messageUid = "msg_" + ContentHash.hex(bindingId + "|" + conversation.scope() + "|"
+ (sourceMessageId == null ? rawPayload : sourceMessageId)).substring(0, 32);
String summary = summaryOf(segments);
Long messageId = insertMessage(bindingId, eventId, messageUid, sourceMessageId, postType, direction,
conversation, senderId, senderName, messageTime,
hasUnknown ? STATUS_PARTIAL : STATUS_PARSED, summary);
Timestamp created = Timestamp.from(Instant.now());
for (Segment segment : segments) {
jdbc.update("INSERT INTO message_segment (message_id, segment_index, segment_type, segment_status, "
+ "normalized_content, raw_segment, media_object_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
messageId, segment.index(), segment.type(),
segment.known() ? STATUS_PARSED : STATUS_UNKNOWN,
segment.normalized(), segment.rawJson(), segment.mediaObjectId(), created);
}
return new Result(messageId, messageUid, hasUnknown);
}
record Segment(int index, String type, boolean known, String normalized, String rawJson, Long mediaObjectId) {
}
/**
* 解析消息段数组。 NapCat 的 message 字段是段数组,禁止用正则切 raw_message:
* raw_message 含 HTML 实体转义,正则切分会破坏正文(能力基线实测)。
*/
List<Segment> segmentsOf(JsonNode messageNode) {
List<Segment> out = new ArrayList<>();
if (messageNode == null || messageNode.isNull()) {
return out;
}
if (messageNode.isTextual()) {
out.add(new Segment(0, "text", true, messageNode.asText(), rawJsonOf(messageNode), null));
return out;
}
if (!messageNode.isArray()) {
out.add(new Segment(0, "unknown", false, null, rawJsonOf(messageNode), null));
return out;
}
int index = 0;
for (JsonNode segment : messageNode) {
String type = DedupKeyFactory.text(segment, "type");
if (type == null) {
type = "unknown";
}
boolean known = KNOWN_SEGMENTS.contains(type);
JsonNode data = segment.get("data");
String normalized = normalizeSegment(type, data);
out.add(new Segment(index++, type, known, known ? normalized : null, rawJsonOf(segment), null));
}
return out;
}
private String normalizeSegment(String type, JsonNode data) {
if (data == null || data.isNull()) {
return null;
}
if (PLACEHOLDER_SEGMENTS.contains(type)) {
// 合并转发内层节点不可还原、news 只是渲染占位,均不得当作用户正文入库。
return "[不支持展示的 " + type + " 内容]";
}
return switch (type) {
case "text" -> text(data, "text");
case "at" -> "[有人被@:" + orPlaceholder(text(data, "qq")) + "]";
case "face" -> "[表情 " + orPlaceholder(text(data, "id")) + "]";
case "reply" -> "[回复消息 " + orPlaceholder(text(data, "id")) + "]";
case "image" -> "[图片]";
case "record" -> "[语音]";
case "video" -> "[视频]";
case "file" -> "[文件:" + orPlaceholder(firstText(data, "file_name", "name", "file")) + "]";
case "poke" -> "[戳一戳]";
case "location" -> "[位置]";
case "music" -> "[音乐]";
case "share" -> "[分享链接]";
case "json", "xml", "miniapp" -> "[卡片消息]";
default -> null;
};
}
private String summaryOf(List<Segment> segments) {
StringBuilder sb = new StringBuilder();
for (Segment segment : segments) {
if (segment.normalized() == null) {
continue;
}
if (!sb.isEmpty() && !segment.normalized().startsWith("[")) {
sb.append(' ');
}
sb.append(segment.normalized());
}
return EventIngestService.truncate(sb.toString(), 4000);
}
private Long insertMessage(long bindingId, long eventId, String messageUid, String sourceMessageId,
String messageType, String direction,
DedupKeyFactory.Conversation conversation, String senderId, String senderName,
Instant messageTime, String normalizedStatus, String summary) {
Timestamp now = Timestamp.from(Instant.now());
jdbc.update("INSERT INTO message (message_uid, raw_event_id, binding_id, source_message_id, message_type, "
+ "message_direction, conversation_type, conversation_id, sender_id, sender_name, target_id, "
+ "message_time, normalized_status, raw_summary, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
messageUid, eventId, bindingId, sourceMessageId, messageType, direction,
conversation.type(), conversation.id(), senderId, senderName,
DIRECTION_OUTBOUND.equals(direction) ? conversation.id() : null,
Timestamp.from(messageTime), normalizedStatus, summary, now);
return jdbc.queryForObject("SELECT id FROM message WHERE message_uid = ?", Long.class, messageUid);
}
private String rawJsonOf(JsonNode node) {
try {
return mapper.writeValueAsString(node);
} catch (Exception e) {
return node.toString();
}
}
private static String firstText(JsonNode node, String... fields) {
for (String field : fields) {
String value = text(node, field);
if (value != null) {
return value;
}
}
return null;
}
private static String text(JsonNode node, String field) {
JsonNode value = node == null ? null : node.get(field);
if (value == null || value.isNull() || value.isMissingNode()) {
return null;
}
String text = value.isNumber() ? value.asText() : value.asText().trim();
return text.isEmpty() ? null : text;
}
private static String orPlaceholder(String value) {
return value == null ? "未知" : value;
}
}
@@ -0,0 +1,255 @@
package com.qlinker.message;
import com.qlinker.common.ApiCode;
import com.qlinker.common.ApiException;
import com.qlinker.common.PageData;
import com.qlinker.common.TimeValues;
import org.springframework.jdbc.core.JdbcTemplate;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* 消息查询(数据库设计 17.2、接口设计 9 章)。
*
* <p>列表只返回归一化摘要,不返回原始事件与原始消息段:raw_event.raw_payload 与
* message_segment.raw_segment 是 LONGTEXT,列表批量返回会直接拖垮接口(AGENTS.md 13.2)。
* 原始结构只在单条详情接口按需读取。</p>
*/
public class MessageQueryService {
private static final int MAX_PAGE_SIZE = 100;
private static final int SUMMARY_LENGTH = 200;
private final JdbcTemplate jdbc;
public MessageQueryService(JdbcTemplate jdbc) {
this.jdbc = jdbc;
}
public record Query(Integer page, Integer pageSize, String conversationType, String conversationId,
String senderId, String bindingUid, String direction, Instant from, Instant to, String keyword) {
}
public record MessageRow(long id, String messageUid, String bindingUid, String messageType, String direction,
String conversationType, String conversationId, String senderId, String senderName,
String summary, Instant messageTime, String normalizedStatus, int segmentCount,
int mediaCount, String sourceMessageId) {
}
public record MessageDetail(MessageRow message, List<SegmentRow> segments, String rawEventUid,
String rawEventType, String rawPayload) {
}
public record SegmentRow(int index, String type, String status, String content, String mediaUid,
String rawSegment) {
}
public PageData<MessageRow> search(Query query) {
int page = query.page() == null || query.page() < 1 ? 1 : query.page();
int pageSize = query.pageSize() == null || query.pageSize() < 1 ? 20
: Math.min(query.pageSize(), MAX_PAGE_SIZE);
List<String> where = new ArrayList<>();
List<Object> args = new ArrayList<>();
if (notBlank(query.conversationType())) {
where.add("m.conversation_type = ?");
args.add(query.conversationType().trim());
}
if (notBlank(query.conversationId())) {
where.add("m.conversation_id = ?");
args.add(query.conversationId().trim());
}
if (notBlank(query.senderId())) {
where.add("m.sender_id = ?");
args.add(query.senderId().trim());
}
if (notBlank(query.bindingUid())) {
where.add("b.binding_uid = ?");
args.add(query.bindingUid().trim());
}
if (notBlank(query.direction())) {
where.add("m.message_direction = ?");
args.add(query.direction().trim().toUpperCase());
}
if (query.from() != null) {
where.add("m.message_time >= ?");
args.add(Timestamp.from(query.from()));
}
if (query.to() != null) {
where.add("m.message_time <= ?");
args.add(Timestamp.from(query.to()));
}
if (notBlank(query.keyword())) {
// 仅做前缀匹配:与注释及 AGENTS.md 13.2 的「避免对大字段做无界 LIKE 扫描」一致。
// 当前 raw_summary 尚无专用索引,V1 本地量级可接受;正式版需补检索索引或全文方案。
where.add("m.raw_summary LIKE ?");
args.add(escapeLike(query.keyword().trim()) + "%");
}
String filter = where.isEmpty() ? "" : " WHERE " + String.join(" AND ", where);
Long total = jdbc.queryForObject("SELECT COUNT(*) FROM message m JOIN napcat_binding b ON b.id = m.binding_id"
+ filter, Long.class, args.toArray());
List<Object> pageArgs = new ArrayList<>(args);
pageArgs.add(pageSize);
pageArgs.add((page - 1) * pageSize);
List<MessageRow> rows = jdbc.query("SELECT m.*, b.binding_uid, "
+ "(SELECT COUNT(*) FROM message_segment s WHERE s.message_id = m.id) AS segment_count, "
+ "(SELECT COUNT(*) FROM message_segment s WHERE s.message_id = m.id AND s.media_object_id IS NOT NULL) AS media_count "
+ "FROM message m JOIN napcat_binding b ON b.id = m.binding_id" + filter
+ " ORDER BY m.message_time DESC, m.id DESC LIMIT ? OFFSET ?",
this::mapRow, pageArgs.toArray());
return new PageData<>(rows, page, pageSize, total == null ? 0L : total);
}
public MessageDetail detail(String messageUid) {
List<MessageRow> rows = jdbc.query("SELECT m.*, b.binding_uid, "
+ "(SELECT COUNT(*) FROM message_segment s WHERE s.message_id = m.id) AS segment_count, "
+ "(SELECT COUNT(*) FROM message_segment s WHERE s.message_id = m.id AND s.media_object_id IS NOT NULL) AS media_count "
+ "FROM message m JOIN napcat_binding b ON b.id = m.binding_id WHERE m.message_uid = ?",
this::mapRow, messageUid);
if (rows.isEmpty()) {
throw new ApiException(ApiCode.RESOURCE_NOT_FOUND, "消息不存在:" + messageUid);
}
MessageRow message = rows.get(0);
List<SegmentRow> segments = jdbc.query("SELECT s.segment_index, s.segment_type, s.segment_status, "
+ "s.normalized_content, m.media_uid, s.raw_segment FROM message_segment s "
+ "LEFT JOIN media_object m ON m.id = s.media_object_id WHERE s.message_id = ? "
+ "ORDER BY s.segment_index",
(rs, i) -> new SegmentRow(rs.getInt("segment_index"), rs.getString("segment_type"),
rs.getString("segment_status"), rs.getString("normalized_content"),
rs.getString("media_uid"), rs.getString("raw_segment")),
message.id());
String rawEventUid = null;
String rawEventType = null;
String rawPayload = null;
if (message.id() > 0) {
List<Map<String, Object>> events = jdbc.queryForList(
"SELECT e.event_uid, e.event_type, e.raw_payload FROM message m JOIN raw_event e ON e.id = m.raw_event_id "
+ "WHERE m.message_uid = ?", messageUid);
if (!events.isEmpty()) {
rawEventUid = (String) events.get(0).get("event_uid");
rawEventType = (String) events.get(0).get("event_type");
rawPayload = (String) events.get(0).get("raw_payload");
}
}
return new MessageDetail(message, segments, rawEventUid, rawEventType, rawPayload);
}
/** 会话列表:按会话二元组聚合,供前端侧栏使用(GC-022 要求类型与 ID 联合判别)。 */
public PageData<Map<String, Object>> conversations(int page, int pageSize) {
int safePage = Math.max(1, page);
int safeSize = pageSize < 1 ? 20 : Math.min(pageSize, MAX_PAGE_SIZE);
Long total = jdbc.queryForObject("SELECT COUNT(*) FROM (SELECT m.conversation_type, m.conversation_id "
+ "FROM message m GROUP BY m.conversation_type, m.conversation_id) t", Long.class);
List<Map<String, Object>> items = jdbc.queryForList(
"SELECT m.conversation_type, m.conversation_id, COUNT(*) AS message_count, "
+ "MAX(m.message_time) AS last_message_time, MAX(b.binding_uid) AS binding_uid "
+ "FROM message m JOIN napcat_binding b ON b.id = m.binding_id "
+ "GROUP BY m.conversation_type, m.conversation_id "
+ "ORDER BY MAX(m.message_time) DESC LIMIT ? OFFSET ?",
safeSize, (safePage - 1) * safeSize);
List<Map<String, Object>> out = new ArrayList<>();
for (Map<String, Object> row : items) {
Map<String, Object> item = new LinkedHashMap<>();
item.put("conversationType", row.get("conversation_type"));
item.put("conversationId", row.get("conversation_id"));
item.put("messageCount", row.get("message_count"));
item.put("lastMessageTime", toInstant(row.get("last_message_time")));
item.put("bindingUid", row.get("binding_uid"));
out.add(item);
}
return new PageData<>(out, safePage, safeSize, total == null ? 0L : total);
}
public Map<String, Object> stats() {
Map<String, Object> out = new LinkedHashMap<>();
out.put("totalMessages", count("SELECT COUNT(*) FROM message"));
out.put("inboundMessages", count("SELECT COUNT(*) FROM message WHERE message_direction = 'INBOUND'"));
out.put("outboundMessages", count("SELECT COUNT(*) FROM message WHERE message_direction = 'OUTBOUND'"));
out.put("partialMessages", count("SELECT COUNT(*) FROM message WHERE normalized_status <> 'PARSED'"));
out.put("totalEvents", count("SELECT COUNT(*) FROM raw_event"));
out.put("unprocessedEvents", count("SELECT COUNT(*) FROM raw_event WHERE processing_status = 'PENDING'"));
out.put("failedEvents", count("SELECT COUNT(*) FROM raw_event WHERE processing_status = 'FAILED'"));
out.put("unknownTypeEvents", count("SELECT COUNT(*) FROM raw_event WHERE parse_status = 'UNKNOWN_TYPE'"));
return out;
}
public Optional<Map<String, Object>> recentOfConversation(String conversationType, String conversationId, int limit) {
if (!notBlank(conversationType) || !notBlank(conversationId)) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "conversationType 与 conversationId 不能为空");
}
int safeLimit = limit < 1 ? 20 : Math.min(limit, MAX_PAGE_SIZE);
List<Map<String, Object>> rows = jdbc.queryForList(
"SELECT message_uid, message_direction, raw_summary, message_time, normalized_status "
+ "FROM message WHERE conversation_type = ? AND conversation_id = ? "
+ "ORDER BY message_time DESC, id DESC LIMIT ?",
conversationType.trim(), conversationId.trim(), safeLimit);
return Optional.of(Map.of("items", rows.reversed().stream().map(row -> {
Map<String, Object> item = new java.util.LinkedHashMap<>(row);
item.put("messageTime", toInstant(row.get("message_time")));
item.remove("message_time");
return item;
}).toList()));
}
private long count(String sql) {
Long value = jdbc.queryForObject(sql, Long.class);
return value == null ? 0L : value;
}
private MessageRow mapRow(ResultSet rs, int rowNum) throws SQLException {
String summary = rs.getString("raw_summary");
return new MessageRow(
rs.getLong("id"),
rs.getString("message_uid"),
rs.getString("binding_uid"),
rs.getString("message_type"),
rs.getString("message_direction"),
rs.getString("conversation_type"),
rs.getString("conversation_id"),
rs.getString("sender_id"),
rs.getString("sender_name"),
summary == null || summary.length() <= SUMMARY_LENGTH ? summary : summary.substring(0, SUMMARY_LENGTH),
rs.getTimestamp("message_time").toInstant(),
rs.getString("normalized_status"),
rs.getInt("segment_count"),
rs.getInt("media_count"),
rs.getString("source_message_id"));
}
public static Instant parseInstant(String value) {
if (value == null || value.isBlank()) {
return null;
}
try {
return Instant.parse(value.trim());
} catch (DateTimeParseException e) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "时间格式必须为 ISO-8601 UTC,例如 2026-01-01T00:00:00Z");
}
}
private static Object toInstant(Object value) {
Instant instant = TimeValues.toInstant(value);
return instant == null ? null : instant.toString();
}
private static boolean notBlank(String value) {
return value != null && !value.isBlank();
}
private static String escapeLike(String value) {
return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_");
}
}
@@ -0,0 +1,115 @@
package com.qlinker.napcat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
/**
* NapCat HTTP 客户端调用(OneBot 11 兼容接口)。
*
* <p>注意:retcode=0 只表示上游受理,不等于送达,也不等于语义完整;写操作对不存在的目标
* 同样可能返回 retcode=0(能力基线实测)。因此本客户端把「有 data.message_id」作为成功证据,
* 其余情况一律不得对外声称发送成功。</p>
*/
public class NapCatApiClient {
private final HttpClient http;
private final ObjectMapper mapper;
private final Duration timeout;
public NapCatApiClient(ObjectMapper mapper, Duration timeout) {
this.mapper = mapper;
this.timeout = timeout;
this.http = HttpClient.newBuilder()
.connectTimeout(timeout)
.followRedirects(HttpClient.Redirect.NEVER)
.build();
}
/** 调用结果。transportFailed=true 表示请求结果未知,不得自动重试。 */
public record Call(int retcode, JsonNode data, String message, boolean transportFailed, String rawResponse) {
public boolean accepted() {
return !transportFailed && retcode == 0;
}
}
public Call call(String httpBase, String accessToken, String action, JsonNode payload) {
String url = buildUrl(httpBase, action, accessToken);
String body;
try {
body = mapper.writeValueAsString(payload == null ? mapper.createObjectNode() : payload);
} catch (Exception e) {
throw new IllegalArgumentException("请求体序列化失败", e);
}
HttpRequest request = HttpRequest.newBuilder(URI.create(url))
.timeout(timeout)
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(body, StandardCharsets.UTF_8))
.build();
try {
HttpResponse<String> response = http.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
return parse(response.statusCode(), response.body());
} catch (Exception e) {
// 连接超时、读超时、对端中断等:上游可能已执行,必须按结果未知处理(AGENTS.md 6.4)。
return new Call(-1, null, sanitize(e.toString()), true, null);
}
}
private Call parse(int httpStatus, String body) {
if (httpStatus < 200 || httpStatus >= 300) {
return new Call(-1, null, "HTTP " + httpStatus + " " + sanitize(body), false, truncate(body));
}
try {
JsonNode node = mapper.readTree(body == null ? "{}" : body);
int retcode = node.path("retcode").asInt(-1);
JsonNode data = node.get("data");
String message = node.hasNonNull("msg") ? node.get("msg").asText()
: (node.hasNonNull("wording") ? node.get("wording").asText() : null);
return new Call(retcode, data, message, false, truncate(body));
} catch (Exception e) {
return new Call(-1, null, "上游响应不是合法 JSON", false, truncate(body));
}
}
/**
* 由正向 WS 端点推导 NapCat HTTP 服务基址。NapCat 的 HTTP Server 与正向 WebSocket
* 默认共用同一监听端口,因此沿用 host 与 port,只替换协议。
*/
public static String deriveHttpBase(String wsEndpoint) {
URI uri = URI.create(wsEndpoint.trim());
String scheme = "wss".equalsIgnoreCase(uri.getScheme()) || "https".equalsIgnoreCase(uri.getScheme())
? "https" : "http";
if (uri.getHost() == null) {
throw new IllegalArgumentException("绑定地址缺少主机名");
}
int port = uri.getPort() > 0 ? uri.getPort() : ("https".equals(scheme) ? 443 : 80);
return scheme + "://" + uri.getHost() + ":" + port;
}
private static String buildUrl(String httpBase, String action, String accessToken) {
String separator = httpBase.contains("?") ? "&" : "?";
String token = accessToken == null || accessToken.isBlank() ? "" : separator + "access_token=" + accessToken;
return httpBase.replaceAll("/+$", "") + "/" + action + token;
}
private static String truncate(String value) {
if (value == null) {
return null;
}
return value.length() <= 1000 ? value : value.substring(0, 1000);
}
private static String sanitize(String value) {
if (value == null) {
return null;
}
return truncate(value.replaceAll("(?i)(access_token|authorization|token|password|secret)[=:][^&\\s\"]+",
"$1=***"));
}
}
@@ -0,0 +1,317 @@
package com.qlinker.napcat;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qlinker.binding.BindingRepository;
import com.qlinker.binding.ConnectionStatus;
import com.qlinker.config.QLinkerProperties;
import com.qlinker.event.EventIngestService;
import com.qlinker.message.MessageNormalizer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
* NapCat 正向 WebSocket 连接管理器。
*
* <p>关键约束(能力基线实测,NapCat 4.18.4):</p>
* <ul>
* <li>握手不校验 access_token,因此连接建立后只能标记 CONNECTING,
* 收到 lifecycle 或任一有效事件后才升级为 ONLINE。</li>
* <li>断线期间事件不补推,因此必须持续重连,且事件一到就落库,不做内存攒批。</li>
* <li>NapCat 不主动心跳推送,静默超过阈值时由本端主动断开重连,避免长时间假在线。</li>
* </ul>
*/
public class NapCatConnectionManager implements AutoCloseable {
private static final Logger log = LoggerFactory.getLogger(NapCatConnectionManager.class);
private final BindingRepository bindings;
private final EventIngestService ingest;
private final MessageNormalizer normalizer;
private final com.qlinker.media.MediaService media;
private final NapCatSessionFactory sessionFactory;
private final QLinkerProperties.Napcat config;
private final ScheduledExecutorService scheduler;
private final Map<Long, ManagedConnection> connections = new ConcurrentHashMap<>();
private final AtomicBoolean running = new AtomicBoolean(false);
public NapCatConnectionManager(BindingRepository bindings,
EventIngestService ingest,
MessageNormalizer normalizer,
com.qlinker.media.MediaService media,
NapCatSessionFactory sessionFactory,
QLinkerProperties.Napcat config) {
this.bindings = bindings;
this.ingest = ingest;
this.normalizer = normalizer;
this.media = media;
this.sessionFactory = sessionFactory;
this.config = config;
ThreadFactory factory = runnable -> {
Thread thread = new Thread(runnable, "napcat-conn");
thread.setDaemon(true);
return thread;
};
this.scheduler = Executors.newScheduledThreadPool(4, factory);
}
public void start() {
if (!running.compareAndSet(false, true)) {
return;
}
scheduler.execute(this::reconcile);
scheduler.scheduleWithFixedDelay(this::safeReconcile, 15, 15, TimeUnit.SECONDS);
scheduler.scheduleWithFixedDelay(this::safeStalenessCheck, 10, 10, TimeUnit.SECONDS);
}
private void safeReconcile() {
try {
reconcile();
} catch (Exception e) {
log.error("NapCat 绑定巡检失败 error={}", e.toString());
}
}
/** 为每个 ACTIVE 绑定确保存在一条连接;绑定被停用或解绑时关闭对应连接。 */
void reconcile() {
if (!running.get()) {
return;
}
for (BindingRepository.Binding binding : bindings.findActive()) {
connections.computeIfAbsent(binding.id(), id -> {
ManagedConnection connection = new ManagedConnection(binding);
connection.schedule(0);
return connection;
});
}
connections.entrySet().removeIf(entry -> {
var binding = bindings.findById(entry.getKey());
if (binding.isPresent() && binding.get().active()) {
return false;
}
entry.getValue().shutdown();
return true;
});
}
/**
* 静默检测:连接长时间没有任何报文时主动断开重连。
* NapCat 未配置心跳推送时不会有任何周期性报文,仅靠 TCP 无法发现半开连接。
*/
void safeStalenessCheck() {
if (!running.get()) {
return;
}
Duration limit = config.getOnlineConfirmTimeout().multipliedBy(3);
Instant cutoff = Instant.now().minus(limit);
for (ManagedConnection connection : connections.values()) {
connection.closeIfSilentBefore(cutoff);
}
}
/** 单个绑定的连接状态机。 */
private final class ManagedConnection {
private final long bindingId;
private final String bindingUid;
private final String instanceUid;
private final AtomicInteger attempts = new AtomicInteger();
private volatile NapCatSessionFactory.NapCatSession session;
private volatile ScheduledFuture<?> pending;
private volatile Instant lastActivityAt = Instant.now();
private volatile boolean confirmed;
private final AtomicBoolean closed = new AtomicBoolean(false);
private ManagedConnection(BindingRepository.Binding binding) {
this.bindingId = binding.id();
this.bindingUid = binding.bindingUid();
this.instanceUid = binding.instanceUid();
}
void schedule(long delayMs) {
if (closed.get() || !running.get()) {
return;
}
pending = scheduler.schedule(this::connect, delayMs, TimeUnit.MILLISECONDS);
}
private void connect() {
if (closed.get() || !running.get()) {
return;
}
try {
BindingRepository.Binding binding = bindings.findById(bindingId).orElse(null);
if (binding == null || !binding.active()) {
shutdown();
return;
}
String token = bindings.accessTokenOf(binding).orElse(null);
session = sessionFactory.open(binding.endpoint(), token, new NapCatSessionFactory.NapCatSession.Listener() {
@Override
public void onOpen() {
// 握手成功不代表凭据正确:NapCat 正向 WS 不校验 access_token。
lastActivityAt = Instant.now();
bindings.updateConnectionStatus(bindingId, ConnectionStatus.CONNECTING, null, null);
log.info("NapCat WebSocket 已握手,等待事件确认在线 binding={} instance={}", bindingUid, instanceUid);
}
@Override
public void onMessage(String text) {
handleInbound(text);
}
@Override
public void onClose(int code, String reason) {
bindings.updateConnectionStatus(bindingId, ConnectionStatus.DISCONNECTED,
"WS_CLOSED_" + code, EventIngestService.sanitize(reason));
scheduleBackoff();
}
@Override
public void onError(Throwable error) {
log.warn("NapCat 连接异常 binding={} error={}", bindingUid, error.toString());
bindings.updateConnectionStatus(bindingId, ConnectionStatus.ERROR,
"WS_ERROR", EventIngestService.sanitize(error.toString()));
scheduleBackoff();
}
});
attempts.set(0);
} catch (Exception e) {
log.warn("NapCat 连接失败,退避重试 binding={} instance={} error={}",
bindingUid, instanceUid, e.toString());
bindings.updateConnectionStatus(bindingId, ConnectionStatus.ERROR,
"CONNECT_FAILED", EventIngestService.sanitize(e.toString()));
scheduleBackoff();
}
}
private void handleInbound(String text) {
lastActivityAt = Instant.now();
Instant receivedAt = Instant.now();
try {
EventIngestService.IngestResult result = ingest.ingest(bindingId, text, receivedAt, instanceUid);
bindings.touchEvent(bindingId, receivedAt);
if (!confirmed && !result.duplicated()) {
confirmed = true;
attempts.set(0);
bindings.updateConnectionStatus(bindingId, ConnectionStatus.ONLINE, null, null);
log.info("NapCat 已确认可用 binding={} instance={} firstEvent={}", bindingUid, instanceUid,
result.eventUid());
}
if (result.duplicated() || result.eventId() == null) {
return;
}
// 接收路径只做可靠落库;归一化与后续处理异步执行,避免拖慢事件接收(AGENTS.md 6.2)。
long eventId = result.eventId();
scheduler.execute(() -> processAfterPersist(eventId, text));
} catch (EventIngestService.EventTooLargeException e) {
bindings.updateConnectionStatus(bindingId, ConnectionStatus.ERROR,
"EVENT_TOO_LARGE", EventIngestService.sanitize(e.getMessage()));
} catch (Exception e) {
// 单个事件处理失败不得影响连接:事件已落库,可后续重放解析。
log.error("事件接收失败 binding={} error={}", bindingUid, e.toString());
}
}
private void processAfterPersist(long eventId, String text) {
try {
MessageNormalizer.Result normalized = normalizer.normalize(bindingId, eventId, text);
if (normalized.messageId() != null) {
try {
media.registerForMessage(normalized.messageId());
} catch (Exception e) {
// 媒体失败不得影响消息状态:消息完整性优先,媒体状态由 media_object 表达。
log.warn("媒体登记失败 messageId={} error={}", normalized.messageId(), e.toString());
}
ingest.markProcessed(eventId, EventIngestService.PROCESS_PROCESSED, null, null);
} else if (normalized.hasUnknownSegment()) {
ingest.markProcessed(eventId, EventIngestService.PROCESS_SKIPPED, "NO_CONVERSATION",
"事件缺少可用会话标识,未生成消息记录");
} else {
ingest.markProcessed(eventId, EventIngestService.PROCESS_SKIPPED, "NOT_MESSAGE_EVENT", null);
}
} catch (Exception e) {
log.error("事件归一化失败已标记 binding={} eventId={} error={}",
bindingUid, eventId, e.toString());
ingest.bumpRetry(eventId, "NORMALIZE_FAILED", e.toString());
}
}
private void scheduleBackoff() {
confirmed = false;
if (closed.get() || !running.get()) {
return;
}
int attempt = attempts.incrementAndGet();
Duration min = config.getReconnectMinBackoff();
Duration max = config.getReconnectMaxBackoff();
long base = Math.max(1L, min.toMillis());
long cap = Math.max(base, max.toMillis());
long delay = Math.min(cap, base * (1L << Math.min(6, Math.max(0, attempt - 1))));
log.info("NapCat 将在 {} ms 后重连 binding={} attempt={}", delay, bindingUid, attempt);
schedule(delay);
}
void closeIfSilentBefore(Instant cutoff) {
NapCatSessionFactory.NapCatSession current = session;
if (current == null || !current.isOpen()) {
return;
}
if (lastActivityAt.isBefore(cutoff)) {
log.warn("NapCat 连接长时间无报文,主动断开重连 binding={} lastActivity={}", bindingUid, lastActivityAt);
bindings.updateConnectionStatus(bindingId, ConnectionStatus.DISCONNECTED,
"SILENT_TIMEOUT", "连接在窗口内无任何报文,判定为半开连接");
try {
current.close();
} catch (Exception e) {
log.debug("关闭半开连接失败 binding={} error={}", bindingUid, e.toString());
}
}
}
void shutdown() {
if (!closed.compareAndSet(false, true)) {
return;
}
ScheduledFuture<?> task = pending;
if (task != null) {
task.cancel(false);
}
NapCatSessionFactory.NapCatSession current = session;
if (current != null) {
try {
current.close();
} catch (Exception e) {
log.debug("关闭 NapCat 连接失败 binding={} error={}", bindingUid, e.toString());
}
}
}
}
@Override
public void close() {
running.set(false);
connections.values().forEach(ManagedConnection::shutdown);
connections.clear();
scheduler.shutdownNow();
}
/** 供健康检查与前端展示使用。 */
public Map<String, Object> status() {
return Map.of(
"receiverEnabled", config.isReceiverEnabled(),
"managedConnections", connections.size());
}
}
@@ -0,0 +1,39 @@
package com.qlinker.napcat;
import java.net.URI;
/**
* NapCat 传输层抽象。抽出接口使连接管理、去重、消息归一化与发送服务在没有真实 NapCat
* 时也能完成自动化测试;真实环境验证结果单独记录,不得由测试通过推断(AGENTS.md 17.3)。
*/
public interface NapCatSessionFactory {
/**
* 建立到 NapCat 正向 WebSocket 的连接。
*
* @param endpoint 连接地址;access_token 由实现按 NapCat 约定附加
* @param listener 事件与关闭回调
*/
NapCatSession open(String endpoint, String accessToken, NapCatSession.Listener listener) throws Exception;
/** 一次已建立的连接。 */
interface NapCatSession extends AutoCloseable {
void sendText(String text) throws Exception;
boolean isOpen();
@Override
void close();
interface Listener {
void onOpen();
void onMessage(String text);
void onClose(int code, String reason);
void onError(Throwable error);
}
}
}
@@ -0,0 +1,126 @@
package com.qlinker.napcat;
import jakarta.websocket.ClientEndpoint;
import jakarta.websocket.CloseReason;
import jakarta.websocket.ContainerProvider;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnError;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.WebSocketContainer;
import java.net.URI;
/**
* 基于 Jakarta WebSocket 客户端的 NapCat 正向连接实现。
*
* <p>NapCat 正向 WebSocket 握手不校验 access_token(能力基线实测),因此 token 只作为查询参数
* 附带,真正的可用性由上层在收到 lifecycle 或有效事件后判定。</p>
*/
public class WebSocketNapCatSessionFactory implements NapCatSessionFactory {
/** 单条事件报文上限。合并转发与大消息可能较大,超限由上层标记为超限而非静默丢弃。 */
static final int MAX_MESSAGE_BYTES = 8 * 1024 * 1024;
@Override
public NapCatSession open(String endpoint, String accessToken, NapCatSession.Listener listener) throws Exception {
URI uri = withAccessToken(URI.create(endpoint), accessToken);
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.setDefaultMaxTextMessageBufferSize(MAX_MESSAGE_BYTES);
container.setDefaultMaxBinaryMessageBufferSize(MAX_MESSAGE_BYTES);
ListenerEndpoint endpointObject = new ListenerEndpoint(listener);
container.connectToServer(endpointObject, uri);
return endpointObject;
}
static URI withAccessToken(URI base, String accessToken) {
if (accessToken == null || accessToken.isBlank()) {
return base;
}
String tokenParam = "access_token=" + accessToken;
String existing = base.getRawQuery();
String finalQuery = existing == null || existing.isBlank() ? tokenParam : existing + "&" + tokenParam;
StringBuilder sb = new StringBuilder();
if (base.getScheme() != null) {
sb.append(base.getScheme()).append("://");
}
if (base.getRawAuthority() != null) {
sb.append(base.getRawAuthority());
}
if (base.getRawPath() != null) {
sb.append(base.getRawPath());
}
sb.append('?').append(finalQuery);
if (base.getRawFragment() != null) {
sb.append('#').append(base.getRawFragment());
}
return URI.create(sb.toString());
}
@ClientEndpoint
public static final class ListenerEndpoint implements NapCatSession {
private final Listener listener;
private volatile Session session;
public ListenerEndpoint(Listener listener) {
this.listener = listener;
}
@OnOpen
public void onOpen(Session session) {
this.session = session;
listener.onOpen();
}
@OnMessage
public void onMessage(String text) {
listener.onMessage(text);
}
@OnClose
public void onClose(Session session, CloseReason reason) {
listener.onClose(reason.getCloseCode().getCode(), reason.getReasonPhrase());
}
@OnError
public void onError(Session session, Throwable error) {
listener.onError(error);
}
@Override
public void sendText(String text) throws Exception {
Session current = session;
if (current == null || !current.isOpen()) {
throw new IllegalStateException("NapCat 连接不可用");
}
synchronized (this) {
current.getBasicRemote().sendText(text);
}
}
@Override
public boolean isOpen() {
Session current = session;
return current != null && current.isOpen();
}
@Override
public void close() {
Session current = session;
if (current == null) {
return;
}
try {
current.close(new CloseReason(CloseReason.CloseCodes.NORMAL_CLOSURE, "qlinker shutdown"));
} catch (Exception e) {
try {
current.close();
} catch (Exception ignored) {
// 已尽力关闭;残留连接由容器超时回收,不影响重连。
}
}
}
}
}
@@ -0,0 +1,35 @@
package com.qlinker.security;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.annotation.AnnotationUtils;
public final class AuthAttributes {
public static final String CURRENT_USER = "qlinker.currentUser";
private AuthAttributes() {
}
/** 供拦截器读取处理器上声明的所需权限。 */
public static String requiredPermission(Object handler) {
if (handler == null) {
return null;
}
var method = handler instanceof org.springframework.web.method.HandlerMethod hm ? hm.getMethod() : null;
if (method != null) {
RequiresPermission ann = AnnotationUtils.findAnnotation(method, RequiresPermission.class);
if (ann != null) {
return ann.value();
}
}
Class<?> type = method != null ? method.getDeclaringClass() : handler.getClass();
RequiresPermission ann = AnnotationUtils.findAnnotation(type, RequiresPermission.class);
return ann == null ? null : ann.value();
}
/** 从请求属性中取出当前操作者(由 AuthInterceptor 写入)。 */
public static CurrentUser currentUser(HttpServletRequest request) {
Object value = request.getAttribute(CURRENT_USER);
return value instanceof CurrentUser user ? user : null;
}
}
@@ -0,0 +1,61 @@
package com.qlinker.security;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qlinker.common.ApiCode;
import com.qlinker.common.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import java.nio.charset.StandardCharsets;
/**
* Bearer Token 鉴权与权限校验(DEC-201、接口设计 4.1/4.2)。
* 所有 /api/v1 接口必须在此通过服务端校验,未通过不得进入业务层。
*/
public class AuthInterceptor implements HandlerInterceptor {
private final AuthService auth;
private final ObjectMapper mapper = new ObjectMapper();
public AuthInterceptor(AuthService auth) {
this.auth = auth;
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!(handler instanceof HandlerMethod)) {
return true;
}
CurrentUser user = auth.resolve(bearerToken(request));
if (user == null) {
reject(response, ApiCode.UNAUTHENTICATED, "未认证或会话已失效", null);
return false;
}
request.setAttribute(AuthAttributes.CURRENT_USER, user);
String required = AuthAttributes.requiredPermission(handler);
if (required != null && !user.has(required)) {
reject(response, ApiCode.PERMISSION_DENIED, "当前账号缺少权限 " + required, required);
return false;
}
return true;
}
private String bearerToken(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header == null || !header.regionMatches(true, 0, "Bearer ", 0, 7)) {
return null;
}
return header.substring(7).trim();
}
private void reject(HttpServletResponse response, ApiCode code, String message, String permission) throws Exception {
response.setStatus(code.httpStatus());
response.setContentType("application/json");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
Object data = permission == null ? null : java.util.Map.of("requiredPermission", permission);
response.getWriter().write(mapper.writeValueAsString(ApiResponse.error(code, message, data)));
}
}
@@ -0,0 +1,297 @@
package com.qlinker.security;
import com.qlinker.audit.AuditService;
import com.qlinker.common.ApiCode;
import com.qlinker.common.ApiException;
import com.qlinker.common.TimeValues;
import com.qlinker.config.QLinkerProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 单管理员认证(任务 004 范围)。
*
* <p>首次初始化使用一次性引导令牌:令牌由启动时生成并只输出一次,库内只保存 SHA-256 哈希,
* 成功创建管理员后立即置为 USED 并永久失效,避免留下默认口令。密码只保存 BCrypt 哈希,
* 会话令牌只保存哈希并带过期时间,支持主动撤销(接口设计 4.1)。</p>
*/
public class AuthService {
private static final Logger log = LoggerFactory.getLogger(AuthService.class);
private static final int MAX_FAILED_LOGINS = 8;
private static final Duration LOGIN_LOCK_WINDOW = Duration.ofMinutes(5);
private final JdbcTemplate jdbc;
private final CryptoService crypto;
private final QLinkerProperties properties;
private final AuditService audit;
private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
/** 登录失败计数为进程内状态,仅用于抬高暴力猜测成本,不作为跨实例的硬性防护。 */
private final Map<String, FailureWindow> loginFailures = new ConcurrentHashMap<>();
public AuthService(JdbcTemplate jdbc, CryptoService crypto, QLinkerProperties properties, AuditService audit) {
this.jdbc = jdbc;
this.crypto = crypto;
this.properties = properties;
this.audit = audit;
}
/** 是否已存在可用管理员账号。 */
public boolean hasAdministrator() {
Integer count = jdbc.queryForObject(
"SELECT COUNT(*) FROM user_account ua JOIN user_role ur ON ur.user_id = ua.id "
+ "JOIN role r ON r.id = ur.role_id WHERE r.role_code = ? AND ua.status = 'ACTIVE'",
Integer.class, PermissionCatalog.ADMIN_ROLE_CODE);
return count != null && count > 0;
}
/**
* 使用一次性引导令牌创建首个管理员。令牌无效、已用或已存在管理员时拒绝,
* 已存在管理员后不再接受任何引导请求,防止被再次提权。
*/
public void bootstrapAdministrator(String bootstrapToken, String username, String rawPassword, String sourceIp) {
if (hasAdministrator()) {
throw new ApiException(ApiCode.RESOURCE_CONFLICT, "实例已完成初始化管理员,不能重复创建");
}
if (bootstrapToken == null || bootstrapToken.isBlank()) {
throw new ApiException(ApiCode.UNAUTHENTICATED, "引导令牌不正确");
}
if (username == null || !username.matches("^[A-Za-z0-9_.-]{3,64}$")) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "登录名必须为 3-64 位字母、数字、下划线、点或短横线");
}
if (rawPassword == null || rawPassword.length() < 12) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "初始口令至少 12 位");
}
String tokenHash = CryptoService.sha256Hex(bootstrapToken);
List<Map<String, Object>> rows = jdbc.queryForList(
"SELECT id, token_status, expires_at FROM bootstrap_token WHERE token_hash = ?", tokenHash);
if (rows.isEmpty()) {
throw new ApiException(ApiCode.UNAUTHENTICATED, "引导令牌不正确");
}
Map<String, Object> row = rows.get(0);
long tokenId = ((Number) row.get("id")).longValue();
if (!"ACTIVE".equals(row.get("token_status"))) {
throw new ApiException(ApiCode.UNAUTHENTICATED, "引导令牌已失效");
}
Instant expiresAt = TimeValues.toInstant(row.get("expires_at"));
if (expiresAt != null && expiresAt.isBefore(Instant.now())) {
jdbc.update("UPDATE bootstrap_token SET token_status = 'REVOKED', updated_at = ? WHERE id = ?",
Timestamp.from(Instant.now()), tokenId);
throw new ApiException(ApiCode.UNAUTHENTICATED, "引导令牌已过期");
}
Instant now = Instant.now();
Long userId;
try {
userId = createUser(username, rawPassword, now);
} catch (DuplicateKeyException e) {
throw new ApiException(ApiCode.RESOURCE_CONFLICT, "该登录名已存在");
}
// 令牌消费使用条件更新:并发下只有一个请求能把 ACTIVE 改成 USED,避免创建出两个管理员。
int consumed = jdbc.update("UPDATE bootstrap_token SET token_status = 'USED', used_at = ?, used_by = ?, "
+ "updated_at = ? WHERE id = ? AND token_status = 'ACTIVE'",
Timestamp.from(now), userId, Timestamp.from(now), tokenId);
if (consumed == 0) {
jdbc.update("DELETE FROM user_role WHERE user_id = ?", userId);
jdbc.update("DELETE FROM user_account WHERE id = ?", userId);
throw new ApiException(ApiCode.RESOURCE_CONFLICT, "引导令牌已被使用");
}
audit.record(new CurrentUser(userId, username, username, java.util.Set.of()),
"auth.bootstrap", "user_account", String.valueOf(userId),
AuditService.RESULT_SUCCEEDED, "首次初始化管理员", Map.of("username", username), sourceIp);
log.info("管理员初始化完成 username={}", username);
}
private Long createUser(String username, String rawPassword, Instant now) {
Timestamp ts = Timestamp.from(now);
jdbc.update("INSERT INTO user_account (username, password_hash, display_name, status, "
+ "password_changed_at, created_at, updated_at) VALUES (?, ?, ?, 'ACTIVE', ?, ?, ?)",
username, encoder.encode(rawPassword), username, ts, ts, ts);
Long userId = jdbc.queryForObject("SELECT id FROM user_account WHERE username = ?", Long.class, username);
ensureAdminRole(now);
Long roleId = jdbc.queryForObject("SELECT id FROM role WHERE role_code = ?", Long.class,
PermissionCatalog.ADMIN_ROLE_CODE);
jdbc.update("INSERT INTO user_role (user_id, role_id, created_at) VALUES (?, ?, ?)", userId, roleId, ts);
return userId;
}
/** 幂等补齐 admin 角色与权限目录,保证权限编码与 permission 表一致。 */
private void ensureAdminRole(Instant now) {
Timestamp ts = Timestamp.from(now);
jdbc.update("INSERT IGNORE INTO role (role_code, role_name, description, status, created_at, updated_at) "
+ "VALUES (?, ?, ?, 'ACTIVE', ?, ?)",
PermissionCatalog.ADMIN_ROLE_CODE, PermissionCatalog.ADMIN_ROLE_NAME,
"任务 004 单管理员角色", ts, ts);
Long roleId = jdbc.queryForObject("SELECT id FROM role WHERE role_code = ?", Long.class,
PermissionCatalog.ADMIN_ROLE_CODE);
for (String code : PermissionCatalog.ADMIN_PERMISSIONS) {
String[] parts = code.split("\\.", 2);
jdbc.update("INSERT IGNORE INTO permission (permission_code, permission_name, resource_type, action, "
+ "created_at) VALUES (?, ?, ?, ?, ?)",
code, code, parts[0], parts[1], ts);
Long permissionId = jdbc.queryForObject("SELECT id FROM permission WHERE permission_code = ?",
Long.class, code);
jdbc.update("INSERT IGNORE INTO role_permission (role_id, permission_id, created_at) VALUES (?, ?, ?)",
roleId, permissionId, ts);
}
}
public record LoginResult(String token, Instant expiresAt, CurrentUser user) {
}
public LoginResult login(String username, String rawPassword, String clientInfo, String sourceIp) {
String throttleKey = (username == null ? "?" : username.toLowerCase()) + "@" + sourceIp;
FailureWindow window = loginFailures.get(throttleKey);
if (window != null && window.isLocked()) {
audit.record(null, "auth.login.throttled", "user_account", username,
AuditService.RESULT_DENIED, "登录失败次数过多,临时拒绝", Map.of(), sourceIp);
throw new ApiException(ApiCode.RATE_LIMITED, "登录失败次数过多,请稍后重试");
}
List<Map<String, Object>> rows = username == null ? List.of() : jdbc.queryForList(
"SELECT id, username, password_hash, display_name, status FROM user_account WHERE username = ?",
username);
boolean ok = rows.stream().findFirst()
.filter(r -> "ACTIVE".equals(r.get("status")))
.map(r -> encoder.matches(rawPassword == null ? "" : rawPassword, (String) r.get("password_hash")))
.orElse(false);
if (!ok) {
// 不区分「用户不存在」与「口令错误」,避免泄露账号是否存在(接口设计 4.1)。
recordFailure(throttleKey);
audit.record(null, "auth.login", "user_account", username,
AuditService.RESULT_FAILED, "用户名或口令不正确", Map.of(), sourceIp);
throw new ApiException(ApiCode.UNAUTHENTICATED, "用户名或口令不正确");
}
loginFailures.remove(throttleKey);
Map<String, Object> row = rows.get(0);
long userId = ((Number) row.get("id")).longValue();
Instant now = Instant.now();
Instant expiresAt = now.plus(properties.getSessionTtl());
String token = crypto.randomToken(32);
jdbc.update("INSERT INTO user_session (user_id, session_token_hash, issued_at, expires_at, last_seen_at, "
+ "client_info) VALUES (?, ?, ?, ?, ?, ?)",
userId, CryptoService.sha256Hex(token), Timestamp.from(now), Timestamp.from(expiresAt),
Timestamp.from(now), clientInfo);
jdbc.update("UPDATE user_account SET last_login_at = ?, updated_at = ? WHERE id = ?",
Timestamp.from(now), Timestamp.from(now), userId);
CurrentUser user = new CurrentUser(userId, (String) row.get("username"),
(String) row.get("display_name"), permissionsOf(userId));
audit.record(user, "auth.login", "user_account", String.valueOf(userId),
AuditService.RESULT_SUCCEEDED, null, Map.of(), sourceIp);
return new LoginResult(token, expiresAt, user);
}
/** 校验 Bearer 会话令牌;令牌无效、已撤销或已过期时返回空。 */
public CurrentUser resolve(String bearerToken) {
if (bearerToken == null || bearerToken.isBlank()) {
return null;
}
List<Map<String, Object>> rows = jdbc.queryForList(
"SELECT s.user_id, s.expires_at, s.revoked_at, ua.username, ua.display_name, ua.status "
+ "FROM user_session s JOIN user_account ua ON ua.id = s.user_id "
+ "WHERE s.session_token_hash = ?",
CryptoService.sha256Hex(bearerToken));
if (rows.isEmpty()) {
return null;
}
Map<String, Object> row = rows.get(0);
if (row.get("revoked_at") != null || !"ACTIVE".equals(row.get("status"))) {
return null;
}
Instant expiresAt = TimeValues.toInstant(row.get("expires_at"));
if (expiresAt == null || expiresAt.isBefore(Instant.now())) {
return null;
}
long userId = ((Number) row.get("user_id")).longValue();
jdbc.update("UPDATE user_session SET last_seen_at = ? WHERE session_token_hash = ?",
Timestamp.from(Instant.now()), CryptoService.sha256Hex(bearerToken));
return new CurrentUser(userId, (String) row.get("username"), (String) row.get("display_name"),
permissionsOf(userId));
}
public void logout(String bearerToken, CurrentUser actor, String sourceIp) {
if (bearerToken == null || bearerToken.isBlank()) {
return;
}
jdbc.update("UPDATE user_session SET revoked_at = ? WHERE session_token_hash = ? AND revoked_at IS NULL",
Timestamp.from(Instant.now()), CryptoService.sha256Hex(bearerToken));
audit.record(actor, "auth.logout", "user_session", null,
AuditService.RESULT_SUCCEEDED, null, Map.of(), sourceIp);
}
public java.util.Set<String> permissionsOf(long userId) {
return new java.util.HashSet<>(jdbc.queryForList(
"SELECT DISTINCT p.permission_code FROM permission p "
+ "JOIN role_permission rp ON rp.permission_id = p.id "
+ "JOIN user_role ur ON ur.role_id = rp.role_id "
+ "WHERE ur.user_id = ? AND p.permission_code IS NOT NULL",
String.class, userId));
}
private void recordFailure(String key) {
loginFailures.compute(key, (k, existing) -> {
FailureWindow window = existing == null || existing.isExpired()
? new FailureWindow()
: existing;
window.count.incrementAndGet();
return window;
});
}
private static final class FailureWindow {
final AtomicInteger count = new AtomicInteger();
final Instant start = Instant.now();
boolean isLocked() {
return count.get() >= MAX_FAILED_LOGINS && !isExpired();
}
boolean isExpired() {
return start.plus(LOGIN_LOCK_WINDOW).isBefore(Instant.now());
}
}
/** 供启动流程写入引导令牌记录;只保存哈希。 */
public void registerBootstrapToken(String plainToken, Instant expiresAt) {
Map<String, Object> record = new HashMap<>();
record.put("hash", CryptoService.sha256Hex(plainToken));
jdbc.update("INSERT INTO bootstrap_token (token_uid, token_hash, token_status, issued_at, expires_at, "
+ "created_at, updated_at) VALUES (?, ?, 'ACTIVE', ?, ?, ?, ?)",
"bts_" + crypto.randomToken(12), record.get("hash"), Timestamp.from(Instant.now()),
expiresAt == null ? null : Timestamp.from(expiresAt),
Timestamp.from(Instant.now()), Timestamp.from(Instant.now()));
}
/** 是否已经签发过引导令牌(避免重启后重复签发)。 */
public boolean hasBootstrapToken() {
Integer count = jdbc.queryForObject("SELECT COUNT(*) FROM bootstrap_token", Integer.class);
return count != null && count > 0;
}
/** 引导令牌是否仍然可用(未使用、未撤销、未过期)。 */
public boolean bootstrapTokenActive() {
Integer count = jdbc.queryForObject("SELECT COUNT(*) FROM bootstrap_token WHERE token_status = 'ACTIVE' "
+ "AND (expires_at IS NULL OR expires_at > ?)", Integer.class, Timestamp.from(Instant.now()));
return count != null && count > 0;
}
}
@@ -0,0 +1,118 @@
package com.qlinker.security;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.HexFormat;
/**
* 凭据保护工具:AES-256-GCM 信封加密与 SHA-256 摘要。
*
* <p>设计约束(AGENTS.md 11.2、数据库设计 21.1):明文密钥不得入库、不得写日志;
* 需要长期保存的敏感值只以密文形式落库,仅用于比对的值(令牌、会话)只保存哈希。</p>
*/
public final class CryptoService {
public static final String ALGORITHM = "AES-256-GCM";
public static final String DEFAULT_KEY_ID = "master-v1";
private static final int GCM_IV_LENGTH = 12;
private static final int GCM_TAG_BITS = 128;
private final SecretKey masterKey;
private final String keyId;
private final SecureRandom random = new SecureRandom();
public CryptoService(String base64MasterKey) {
if (base64MasterKey == null || base64MasterKey.isBlank()) {
throw new IllegalStateException("缺少 qlinker.instance.master-key:用于加密存储 NapCat 访问令牌等敏感配置");
}
byte[] keyBytes;
try {
keyBytes = Base64.getDecoder().decode(base64MasterKey.trim());
} catch (IllegalArgumentException e) {
throw new IllegalStateException("qlinker.instance.master-key 必须是 Base64 编码的 32 字节密钥");
}
if (keyBytes.length != 32) {
throw new IllegalStateException("qlinker.instance.master-key 解码后必须是 32 字节(AES-256)");
}
this.masterKey = new SecretKeySpec(keyBytes, "AES");
this.keyId = DEFAULT_KEY_ID;
}
public String keyId() {
return keyId;
}
/** 返回 Base64(IV || 密文+认证标签)。 */
public String encrypt(String plaintext) {
try {
byte[] iv = new byte[GCM_IV_LENGTH];
random.nextBytes(iv);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, masterKey, new GCMParameterSpec(GCM_TAG_BITS, iv));
byte[] cipherText = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
byte[] out = new byte[iv.length + cipherText.length];
System.arraycopy(iv, 0, out, 0, iv.length);
System.arraycopy(cipherText, 0, out, iv.length, cipherText.length);
return Base64.getEncoder().encodeToString(out);
} catch (Exception e) {
throw new IllegalStateException("加密失败", e);
}
}
public String decrypt(String encoded) {
try {
byte[] all = Base64.getDecoder().decode(encoded);
if (all.length <= GCM_IV_LENGTH) {
throw new IllegalArgumentException("密文长度不合法");
}
byte[] iv = new byte[GCM_IV_LENGTH];
System.arraycopy(all, 0, iv, 0, GCM_IV_LENGTH);
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, masterKey, new GCMParameterSpec(GCM_TAG_BITS, iv));
byte[] plain = cipher.doFinal(all, GCM_IV_LENGTH, all.length - GCM_IV_LENGTH);
return new String(plain, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new IllegalStateException("解密失败:主密钥与密文不匹配或数据已损坏", e);
}
}
public static String sha256Hex(String value) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
return HexFormat.of().formatHex(digest.digest(value.getBytes(StandardCharsets.UTF_8)));
} catch (Exception e) {
throw new IllegalStateException("SHA-256 不可用", e);
}
}
public static byte[] sha256(byte[] value) {
try {
return MessageDigest.getInstance("SHA-256").digest(value);
} catch (Exception e) {
throw new IllegalStateException("SHA-256 不可用", e);
}
}
/** 生成 URL 安全的随机字符串,用于令牌与幂等标识。 */
public String randomToken(int byteLength) {
byte[] buf = new byte[byteLength];
random.nextBytes(buf);
return Base64.getUrlEncoder().withoutPadding().encodeToString(buf);
}
/** 管理页面展示用的脱敏值,不可用于还原明文。 */
public static String mask(String value) {
if (value == null || value.isBlank()) {
return "***";
}
int keep = value.length() >= 4 ? 2 : 1;
return value.substring(0, keep) + "***" + value.substring(value.length() - keep);
}
}
@@ -0,0 +1,13 @@
package com.qlinker.security;
import java.util.Set;
/**
* 通过会话校验后的当前操作者。仅承载本次请求所需的身份与权限集合。
*/
public record CurrentUser(long userId, String username, String displayName, Set<String> permissions) {
public boolean has(String permission) {
return permissions.contains(permission);
}
}
@@ -0,0 +1,36 @@
package com.qlinker.security;
import java.util.List;
/**
* 权限编码目录(接口设计 4.2)。取值与 permission 表一致,前后端共用同一字符串。
* 任务 004 只开放单管理员模型,但权限编码按域拆分,避免后续引入角色时改动接口契约。
*/
public final class PermissionCatalog {
public static final String SYSTEM_READ = "system.read";
public static final String SYSTEM_UPDATE = "system.update";
public static final String NAPCAT_READ = "napcat.read";
public static final String NAPCAT_MANAGE = "napcat.manage";
public static final String MESSAGE_READ = "message.read";
public static final String MEDIA_READ = "media.read";
public static final String MEDIA_MANAGE = "media.manage";
public static final String SEND_READ = "send.read";
public static final String SEND_EXECUTE = "send.execute";
public static final String AUDIT_READ = "audit.read";
/** 单管理员角色拥有的全部权限。 */
public static final List<String> ADMIN_PERMISSIONS = List.of(
SYSTEM_READ, SYSTEM_UPDATE,
NAPCAT_READ, NAPCAT_MANAGE,
MESSAGE_READ,
MEDIA_READ, MEDIA_MANAGE,
SEND_READ, SEND_EXECUTE,
AUDIT_READ);
public static final String ADMIN_ROLE_CODE = "admin";
public static final String ADMIN_ROLE_NAME = "管理员";
private PermissionCatalog() {
}
}
@@ -0,0 +1,16 @@
package com.qlinker.security;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 声明接口所需权限。校验在拦截器中统一执行,前端隐藏按钮不构成权限控制(AGENTS.md 11.1)。
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequiresPermission {
String value();
}
@@ -0,0 +1,439 @@
package com.qlinker.send;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qlinker.audit.AuditService;
import com.qlinker.binding.BindingRepository;
import com.qlinker.binding.ConnectionStatus;
import com.qlinker.common.ApiCode;
import com.qlinker.common.ApiException;
import com.qlinker.common.TimeValues;
import com.qlinker.config.QLinkerProperties;
import com.qlinker.event.ContentHash;
import com.qlinker.napcat.NapCatApiClient;
import com.qlinker.security.CryptoService;
import com.qlinker.security.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.jdbc.core.JdbcTemplate;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Duration;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
/**
* 统一发送服务(AGENTS.md 8.1、8.2、8.3)。
*
* <p>所有发送必须经过本服务,禁止业务代码直接调用 NapCat 发送接口。本服务负责:
* 权限与绑定校验、二次确认、幂等、限流、发送记录、结果分类与审计。</p>
*
* <p>结果语义(不得对外夸大):只有上游返回 data.message_id 才记为 SUCCEEDED,
* 且仍只代表「上游确认受理」,不代表接收方已看到;请求已发出但无响应时记为 UNKNOWN,
* 不自动重试,避免重复的真实副作用。</p>
*/
public class SendService {
private static final Logger log = LoggerFactory.getLogger(SendService.class);
public static final String STATUS_PENDING = "PENDING";
public static final String STATUS_RUNNING = "RUNNING";
public static final String STATUS_SUCCEEDED = "SUCCEEDED";
public static final String STATUS_FAILED = "FAILED";
public static final String STATUS_UNKNOWN = "UNKNOWN";
public static final String STATUS_REJECTED = "REJECTED";
private static final int MAX_TEXT_LENGTH = 4500;
private final JdbcTemplate jdbc;
private final BindingRepository bindings;
private final NapCatApiClient api;
private final ObjectMapper mapper;
private final CryptoService crypto;
private final AuditService audit;
private final QLinkerProperties.Send config;
public SendService(JdbcTemplate jdbc,
BindingRepository bindings,
NapCatApiClient api,
ObjectMapper mapper,
CryptoService crypto,
AuditService audit,
QLinkerProperties.Send config) {
this.jdbc = jdbc;
this.bindings = bindings;
this.api = api;
this.mapper = mapper;
this.crypto = crypto;
this.audit = audit;
this.config = config;
}
/** 准备阶段结果:返回待确认的操作标识与确认令牌。 */
public record Prepared(String operationUid, String confirmToken, Instant confirmExpiresAt, String targetSummary) {
}
public record SendView(String operationUid, String status, String targetType, String targetId,
String text, Integer attemptCount, String errorCode, String errorMessage,
Instant createdAt, Instant finishedAt, String idempotencyKey) {
}
/**
* 第一步:创建发送操作并签发二次确认令牌。此步骤不产生任何外部副作用。
* 幂等键在库内唯一,重复提交返回既有操作而不是新建。
*/
public Prepared prepare(String bindingUid, String targetType, String targetId, String text,
String reason, String idempotencyKey, CurrentUser actor, String sourceIp) {
validateTarget(targetType, targetId);
validateText(text);
BindingRepository.Binding binding = requireBinding(bindingUid);
if (!ConnectionStatus.ONLINE.equals(binding.connectionStatus())) {
throw new ApiException(ApiCode.NAPCAT_NOT_CONNECTED,
"绑定当前未确认可用(状态:" + binding.connectionStatus() + "),不能发送");
}
String normalizedTargetType = targetType.toLowerCase();
String payloadJson = textPayload(text);
String payloadHash = ContentHash.hex(payloadJson);
String effectiveKey = idempotencyKey == null || idempotencyKey.isBlank()
? "auto_" + ContentHash.hex(actor.userId() + "|" + bindingUid + "|" + normalizedTargetType + "|"
+ targetId + "|" + payloadHash + "|" + Instant.now().getEpochSecond() / 30)
: idempotencyKey;
Optional<SendView> existing = findByIdempotencyKey(effectiveKey);
if (existing.isPresent()) {
SendView view = existing.get();
if (!payloadHash.equals(hashOfStored(view.operationUid()))) {
// 同一幂等键携带不同正文:属于客户端错误,必须显式拒绝而不是静默执行其一。
throw new ApiException(ApiCode.IDEMPOTENCY_CONFLICT,
"相同幂等键已用于另一条发送内容,操作 " + view.operationUid());
}
throw new ApiException(ApiCode.DUPLICATE_REQUEST,
"相同幂等键的发送操作已存在:" + view.operationUid(), Map.of("operationUid", view.operationUid()));
}
Instant now = Instant.now();
String operationUid = "snd_" + crypto.randomToken(12);
String confirmToken = crypto.randomToken(24);
Instant confirmExpiry = now.plus(config.getConfirmTokenTtl());
try {
jdbc.update("INSERT INTO send_operation (operation_uid, binding_id, source_type, source_id, target_type, "
+ "target_id, message_payload, payload_hash, operation_status, risk_level, "
+ "approval_required, idempotency_key, confirm_token_hash, attempt_count, created_by, "
+ "reason, created_at) VALUES (?, ?, 'MANUAL', ?, ?, ?, ?, ?, ?, 'HIGH', 1, ?, ?, 0, ?, ?, ?)",
operationUid, binding.id(), String.valueOf(actor.userId()), normalizedTargetType, targetId,
payloadJson, ContentHash.sha256(payloadJson), STATUS_PENDING, effectiveKey,
CryptoService.sha256Hex(confirmToken), actor.userId(), reason, Timestamp.from(now));
} catch (DuplicateKeyException e) {
throw new ApiException(ApiCode.DUPLICATE_REQUEST, "相同幂等键的发送操作已存在,未重复创建");
}
audit.record(actor, "send.prepare", "send_operation", operationUid, AuditService.RESULT_SUCCEEDED,
reason, Map.of("targetType", normalizedTargetType, "targetId", targetId,
"textLength", text.length()), sourceIp);
return new Prepared(operationUid, confirmToken, confirmExpiry,
"group".equals(normalizedTargetType) ? "群 " + targetId : "私聊 " + targetId);
}
/**
* 第二步:校验确认令牌并真正调用 NapCat。令牌必须与目标、正文哈希绑定的操作一致,
* 防止前端确认与实际发送内容不一致。
*/
public SendView execute(String operationUid, String confirmToken, CurrentUser actor, String sourceIp) {
Map<String, Object> row = loadOperation(operationUid);
if (!STATUS_PENDING.equals(row.get("operation_status"))) {
throw new ApiException(ApiCode.RESOURCE_CONFLICT,
"该发送操作已执行过,当前状态:" + row.get("operation_status"));
}
if (confirmToken == null || confirmToken.isBlank()) {
throw new ApiException(ApiCode.APPROVAL_REQUIRED, "缺少二次确认令牌,未执行发送");
}
String storedHash = (String) row.get("confirm_token_hash");
if (storedHash == null || !storedHash.equals(CryptoService.sha256Hex(confirmToken))) {
audit.record(actor, "send.execute", "send_operation", operationUid, AuditService.RESULT_DENIED,
"二次确认令牌不匹配", Map.of(), sourceIp);
throw new ApiException(ApiCode.APPROVAL_REQUIRED, "二次确认令牌无效或已失效,未执行发送");
}
Instant createdAt = TimeValues.toInstant(row.get("created_at"));
if (createdAt == null || createdAt.plus(config.getConfirmTokenTtl()).isBefore(Instant.now())) {
jdbc.update("UPDATE send_operation SET operation_status = ?, last_error_code = ?, finished_at = ? "
+ "WHERE operation_uid = ?", STATUS_REJECTED, "CONFIRM_EXPIRED", Timestamp.from(Instant.now()),
operationUid);
throw new ApiException(ApiCode.APPROVAL_REQUIRED, "确认已超时,请重新发起发送");
}
long bindingId = ((Number) row.get("binding_id")).longValue();
BindingRepository.Binding binding = bindings.findById(bindingId)
.orElseThrow(() -> new ApiException(ApiCode.RESOURCE_NOT_FOUND, "绑定不存在"));
String token = bindings.accessTokenOf(binding).orElse(null);
String httpBase = NapCatApiClient.deriveHttpBase(binding.endpoint());
int attempt = ((Number) row.get("attempt_count")).longValue() == 0L ? 1
: ((Number) row.get("attempt_count")).intValue() + 1;
checkRateLimit(bindingId);
// 先落库为 RUNNING:进程中断或响应丢失时,可据此判断该操作已被投递过。
jdbc.update("UPDATE send_operation SET operation_status = ?, attempt_count = ?, started_at = ? "
+ "WHERE operation_uid = ? AND operation_status = ?",
STATUS_RUNNING, attempt, Timestamp.from(Instant.now()), operationUid, STATUS_PENDING);
String action = "group".equals(row.get("target_type")) ? "send_group_msg" : "send_private_msg";
ObjectNode payload = mapper.createObjectNode();
if ("group".equals(row.get("target_type"))) {
payload.put("group_id", parseTargetId((String) row.get("target_id")));
} else {
payload.put("user_id", parseTargetId((String) row.get("target_id")));
}
try {
payload.set("message", mapper.readTree((String) row.get("message_payload")));
} catch (Exception e) {
throw new ApiException(ApiCode.INTERNAL_ERROR, "发送内容解析失败");
}
Instant startedAt = Instant.now();
NapCatApiClient.Call call = api.call(httpBase, token, action, payload);
Instant finishedAt = Instant.now();
long duration = Duration.between(startedAt, finishedAt).toMillis();
String status;
String errorCode = null;
String errorMessage = null;
if (call.transportFailed()) {
status = STATUS_UNKNOWN;
errorCode = "UPSTREAM_RESULT_UNKNOWN";
errorMessage = "请求已发出但未取得可判定响应:" + call.message();
} else if (call.accepted() && hasMessageId(call.data())) {
// message_id 只作为「上游已受理」的证据,原始响应保存在 send_attempt.response_summary。
status = STATUS_SUCCEEDED;
} else if (call.accepted()) {
// retcode=0 但无 message_id:上游受理不等于送达,保守记为结果未知(能力基线实测)。
status = STATUS_UNKNOWN;
errorCode = "UPSTREAM_ACCEPTED_WITHOUT_EVIDENCE";
errorMessage = "上游返回受理但未提供 message_id,无法确认消息已产生";
} else {
status = STATUS_FAILED;
errorCode = "UPSTREAM_RETCODE_" + call.retcode();
errorMessage = call.message();
}
jdbc.update("UPDATE send_operation SET operation_status = ?, finished_at = ?, last_error_code = ?, "
+ "last_error_message = ?, confirm_token_hash = NULL WHERE operation_uid = ?",
status, Timestamp.from(finishedAt), errorCode,
com.qlinker.event.EventIngestService.sanitize(errorMessage), operationUid);
jdbc.update("INSERT INTO send_attempt (send_operation_id, attempt_number, request_summary, response_summary, "
+ "attempt_status, started_at, finished_at, duration_ms, error_code, error_message, created_at) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
row.get("id"), attempt,
com.qlinker.event.EventIngestService.sanitize(action + " -> " + row.get("target_type") + ":"
+ row.get("target_id") + " textLength=" + textLengthOf(row.get("message_payload"))),
com.qlinker.event.EventIngestService.sanitize(call.rawResponse()),
status.equals(STATUS_SUCCEEDED) ? "SUCCEEDED" : status.equals(STATUS_UNKNOWN) ? "UNKNOWN" : "FAILED",
Timestamp.from(startedAt), Timestamp.from(finishedAt), duration, errorCode,
com.qlinker.event.EventIngestService.sanitize(errorMessage), Timestamp.from(Instant.now()));
audit.record(actor, "send.execute", "send_operation", operationUid,
status.equals(STATUS_SUCCEEDED) ? AuditService.RESULT_SUCCEEDED : AuditService.RESULT_FAILED,
status, Map.of("bindingUid", binding.bindingUid(), "attempt", attempt,
"upstreamRetcode", call.retcode()), sourceIp);
log.info("发送操作完成 operation={} status={} retcode={} transportFailed={}",
operationUid, status, call.retcode(), call.transportFailed());
if (STATUS_UNKNOWN.equals(status)) {
throw new ApiException(ApiCode.EXTERNAL_RESULT_UNKNOWN,
"发送结果未知:上游可能已投递,系统不会自动重试。请在消息记录中核对后再决定是否重发。",
Map.of("operationUid", operationUid, "status", STATUS_UNKNOWN));
}
return view(operationUid).orElseThrow(() -> new ApiException(ApiCode.INTERNAL_ERROR, "发送记录读回失败"));
}
public Optional<SendView> findByIdempotencyKey(String idempotencyKey) {
return queryOne("SELECT * FROM send_operation WHERE idempotency_key = ?", idempotencyKey);
}
public Optional<SendView> find(String operationUid) {
return queryOne("SELECT * FROM send_operation WHERE operation_uid = ?", operationUid);
}
/**
* payload_hash 列是 BINARY(32),JDBC 读回为字节数组;这里统一转成十六进制小写,
* 与 ContentHash.hex 生成的摘要保持一致,避免同键重放被误判为不同内容。
*/
private String hashOfStored(String operationUid) {
List<byte[]> rows = jdbc.queryForList("SELECT payload_hash FROM send_operation WHERE operation_uid = ?",
byte[].class, operationUid);
return rows.isEmpty() || rows.get(0) == null ? null : java.util.HexFormat.of().formatHex(rows.get(0));
}
private void checkRateLimit(long bindingId) {
Integer count = jdbc.queryForObject(
"SELECT COUNT(*) FROM send_operation WHERE binding_id = ? AND created_at > ?",
Integer.class, bindingId, Timestamp.from(Instant.now().minus(Duration.ofMinutes(1))));
if (count != null && count >= config.getRateLimitPerMinute()) {
throw new ApiException(ApiCode.RATE_LIMITED,
"该绑定 1 分钟内发送操作已达上限 " + config.getRateLimitPerMinute() + ",请稍后再试");
}
}
private BindingRepository.Binding requireBinding(String bindingUid) {
BindingRepository.Binding binding = bindings.findByUid(bindingUid)
.orElseThrow(() -> new ApiException(ApiCode.RESOURCE_NOT_FOUND, "绑定不存在:" + bindingUid));
if (!binding.active()) {
throw new ApiException(ApiCode.RESOURCE_CONFLICT, "绑定未处于有效状态,不能发送");
}
return binding;
}
private Map<String, Object> loadOperation(String operationUid) {
List<Map<String, Object>> rows = jdbc.queryForList("SELECT * FROM send_operation WHERE operation_uid = ?",
operationUid);
if (rows.isEmpty()) {
throw new ApiException(ApiCode.RESOURCE_NOT_FOUND, "发送操作不存在:" + operationUid);
}
return rows.get(0);
}
private Optional<SendView> view(String operationUid) {
return queryOne("SELECT * FROM send_operation WHERE operation_uid = ?", operationUid);
}
private Optional<SendView> queryOne(String sql, Object arg) {
List<SendView> rows = jdbc.query(sql, this::mapView, arg);
return rows.stream().findFirst();
}
private SendView mapView(ResultSet rs, int rowNum) throws SQLException {
String payload = rs.getString("message_payload");
return new SendView(
rs.getString("operation_uid"),
rs.getString("operation_status"),
rs.getString("target_type"),
rs.getString("target_id"),
textFromPayload(payload),
rs.getInt("attempt_count"),
rs.getString("last_error_code"),
rs.getString("last_error_message"),
instant(rs, "created_at"),
instant(rs, "finished_at"),
rs.getString("idempotency_key"));
}
private static Instant instant(ResultSet rs, String column) throws SQLException {
Timestamp value = rs.getTimestamp(column);
return value == null ? null : value.toInstant();
}
static void validateTarget(String targetType, String targetId) {
if (targetType == null || !List.of("private", "group").contains(targetType.toLowerCase())) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "目标类型只支持 private 或 group");
}
if (targetId == null || !targetId.matches("^[0-9]{4,20}$")) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "目标标识必须是 4-20 位数字");
}
}
static void validateText(String text) {
if (text == null || text.isBlank()) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "发送正文不能为空");
}
if (text.length() > MAX_TEXT_LENGTH) {
throw new ApiException(ApiCode.VALIDATION_ERROR,
"单条文本长度不得超过 " + MAX_TEXT_LENGTH + " 字符,请拆分后分条发送");
}
}
static long parseTargetId(String value) {
try {
return Long.parseUnsignedLong(value);
} catch (NumberFormatException e) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "目标标识超出可表示范围");
}
}
/** 消息段数组:统一由系统生成,避免把用户输入直接拼成任意消息段。 */
static String textPayload(String text) {
ArrayNode segments = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.arrayNode();
ObjectNode segment = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode();
segment.put("type", "text");
segment.putObject("data").put("text", text);
segments.add(segment);
return segments.toString();
}
static String textFromPayload(String payloadJson) {
if (payloadJson == null) {
return null;
}
try {
JsonNode node = new ObjectMapper().readTree(payloadJson);
StringBuilder sb = new StringBuilder();
for (JsonNode segment : node) {
if ("text".equals(segment.path("type").asText())) {
sb.append(segment.path("data").path("text").asText(""));
}
}
return sb.toString();
} catch (Exception e) {
return null;
}
}
private static int textLengthOf(Object payloadJson) {
String text = textFromPayload(payloadJson == null ? null : payloadJson.toString());
return text == null ? 0 : text.length();
}
private static boolean hasMessageId(JsonNode data) {
return messageIdOf(data) != null;
}
private static String messageIdOf(JsonNode data) {
if (data == null || !data.isObject()) {
return null;
}
JsonNode id = data.get("message_id");
if (id == null || id.isNull()) {
return null;
}
return id.isNumber() ? id.bigIntegerValue().toString() : id.asText();
}
public Map<String, Object> summary() {
Map<String, Object> out = new LinkedHashMap<>();
for (String status : List.of(STATUS_PENDING, STATUS_RUNNING, STATUS_SUCCEEDED, STATUS_FAILED, STATUS_UNKNOWN)) {
Integer count = jdbc.queryForObject("SELECT COUNT(*) FROM send_operation WHERE operation_status = ?",
Integer.class, status);
out.put(status, count == null ? 0 : count);
}
return out;
}
/** 最近发送操作列表;正文只返回长度,避免列表接口回传完整消息内容。 */
public List<Map<String, Object>> recent(int limit) {
int safeLimit = limit < 1 ? 50 : Math.min(limit, 200);
return jdbc.query("SELECT operation_uid, target_type, target_id, operation_status, attempt_count, "
+ "last_error_code, created_at, finished_at FROM send_operation "
+ "ORDER BY created_at DESC, id DESC LIMIT ?",
(rs, i) -> {
Map<String, Object> row = new LinkedHashMap<>();
row.put("operationUid", rs.getString("operation_uid"));
row.put("targetType", rs.getString("target_type"));
row.put("targetId", rs.getString("target_id"));
row.put("status", rs.getString("operation_status"));
row.put("attemptCount", rs.getInt("attempt_count"));
row.put("errorCode", rs.getString("last_error_code"));
java.sql.Timestamp created = rs.getTimestamp("created_at");
java.sql.Timestamp finished = rs.getTimestamp("finished_at");
row.put("createdAt", created == null ? null : created.toInstant());
row.put("finishedAt", finished == null ? null : finished.toInstant());
return row;
}, safeLimit);
}
}
@@ -0,0 +1,109 @@
package com.qlinker.storage;
import com.qlinker.config.QLinkerProperties;
import com.qlinker.init.BootstrapCoordinator;
import com.qlinker.init.InstanceIdentity;
import io.minio.BucketExistsArgs;
import io.minio.GetObjectArgs;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import io.minio.StatObjectArgs;
import io.minio.StatObjectResponse;
import io.minio.http.Method;
import java.io.InputStream;
import java.time.Duration;
/**
* 本实例专属 bucket 的对象存储访问。
*
* <p>bucket 名来自持久化的实例身份,不接受外部传入;object key 一律由系统生成,
* 不得由用户输入拼接(AGENTS.md 7.3)。访问 URL 使用短时效预签名,避免长期公开对象。</p>
*
* <p>bucket 名在初始化完成后才确定,因此这里延迟解析:首次使用时才向初始化流程索取身份,
* 未初始化时抛出明确异常,而不是连到一个默认 bucket。</p>
*/
public class StorageService {
private final MinioClient client;
private final BootstrapCoordinator coordinator;
private final Duration presignTtl;
private volatile String bucket;
public StorageService(MinioClient client, BootstrapCoordinator coordinator, QLinkerProperties properties) {
QLinkerProperties.Storage storage = properties.getStorage();
if (storage.getEndpoint() == null || storage.getEndpoint().isBlank()) {
throw new IllegalStateException("缺少 qlinker.storage.endpoint:对象存储地址未配置");
}
this.client = client;
this.coordinator = coordinator;
this.presignTtl = properties.getMedia().getPresignTtl();
}
public String bucket() {
String current = bucket;
if (current != null) {
return current;
}
InstanceIdentity identity = coordinator.ensureReady();
bucket = identity.bucketName();
return bucket;
}
/** 校验 bucket 可访问;不可访问时抛出,由健康检查与初始化流程上报。 */
public void verifyAccessible() throws Exception {
client.bucketExists(BucketExistsArgs.builder().bucket(bucket()).build());
}
/** 初始化时确保 bucket 存在。已存在则跳过,保证初始化幂等。 */
public void ensureBucket() throws Exception {
String name = bucket();
if (!client.bucketExists(BucketExistsArgs.builder().bucket(name).build())) {
client.makeBucket(MakeBucketArgs.builder().bucket(name).build());
}
}
public void put(String objectKey, InputStream data, long size, String contentType) throws Exception {
client.putObject(PutObjectArgs.builder()
.bucket(bucket())
.object(objectKey)
.stream(data, size < 0 ? -1 : size, size < 0 ? 16L * 1024 * 1024 : -1)
.contentType(contentType == null ? "application/octet-stream" : contentType)
.build());
}
public InputStream get(String objectKey) throws Exception {
return client.getObject(GetObjectArgs.builder().bucket(bucket()).object(objectKey).build());
}
public boolean exists(String objectKey) {
try {
client.statObject(StatObjectArgs.builder().bucket(bucket()).object(objectKey).build());
return true;
} catch (Exception e) {
return false;
}
}
public StatObjectResponse stat(String objectKey) throws Exception {
return client.statObject(StatObjectArgs.builder().bucket(bucket()).object(objectKey).build());
}
public void remove(String objectKey) throws Exception {
client.removeObject(RemoveObjectArgs.builder().bucket(bucket()).object(objectKey).build());
}
/** 生成短时效只读 URL。对象 key 由系统控制,不接受外部拼接。 */
public String presignedGetUrl(String objectKey) throws Exception {
return client.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
.method(Method.GET)
.bucket(bucket())
.object(objectKey)
.expiry((int) Math.max(60, presignTtl.toSeconds()))
.build());
}
}
@@ -0,0 +1,104 @@
package com.qlinker.web;
import com.qlinker.common.ApiResponse;
import com.qlinker.security.AuthAttributes;
import com.qlinker.security.AuthService;
import com.qlinker.security.CurrentUser;
import jakarta.servlet.http.HttpServletRequest;
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.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.Instant;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* 认证接口(接口设计 4.1)。
*
* <p>/auth/bootstrap 与 /auth/bootstrap-status 是仅有的两个免鉴权管理接口,
* 且一旦存在管理员即永久关闭,避免留下可重复提权的入口。</p>
*/
@RestController
@RequestMapping("/api/v1/auth")
public class AuthController {
private final AuthService auth;
public AuthController(AuthService auth) {
this.auth = auth;
}
public record BootstrapRequest(String bootstrapToken, String username, String password) {
}
public record LoginRequest(String username, String password) {
}
@PostMapping("/bootstrap")
public ApiResponse<Map<String, Object>> bootstrap(@RequestBody BootstrapRequest request,
HttpServletRequest servletRequest) {
auth.bootstrapAdministrator(request.bootstrapToken(), request.username(), request.password(),
sourceIp(servletRequest));
return ApiResponse.ok(Map.of("initialized", true,
"message", "管理员已创建,引导令牌已永久失效,请使用用户名口令登录"));
}
@PostMapping("/login")
public ApiResponse<Map<String, Object>> login(@RequestBody LoginRequest request,
HttpServletRequest servletRequest) {
AuthService.LoginResult result = auth.login(request.username(), request.password(),
servletRequest.getHeader("User-Agent"), sourceIp(servletRequest));
Map<String, Object> data = new LinkedHashMap<>();
data.put("token", result.token());
data.put("tokenType", "Bearer");
data.put("expiresAt", result.expiresAt());
data.put("user", view(result.user()));
return ApiResponse.ok(data);
}
@PostMapping("/logout")
public ApiResponse<Map<String, Object>> logout(HttpServletRequest servletRequest) {
CurrentUser actor = (CurrentUser) servletRequest.getAttribute(AuthAttributes.CURRENT_USER);
auth.logout(bearer(servletRequest), actor, sourceIp(servletRequest));
return ApiResponse.ok(Map.of("loggedOut", true));
}
@GetMapping("/me")
public ApiResponse<Map<String, Object>> me(HttpServletRequest servletRequest) {
CurrentUser actor = (CurrentUser) servletRequest.getAttribute(AuthAttributes.CURRENT_USER);
Map<String, Object> data = new LinkedHashMap<>(view(actor));
data.put("hasAdministrator", auth.hasAdministrator());
return ApiResponse.ok(data);
}
static Map<String, Object> view(CurrentUser user) {
Map<String, Object> view = new LinkedHashMap<>();
view.put("userId", user.userId());
view.put("username", user.username());
view.put("displayName", user.displayName());
view.put("permissions", user.permissions() == null ? Set.of() : user.permissions());
return view;
}
static String bearer(HttpServletRequest request) {
String header = request.getHeader("Authorization");
if (header == null || !header.regionMatches(true, 0, "Bearer ", 0, 7)) {
return null;
}
return header.substring(7).trim();
}
/** 只用于审计展示与登录限流键,取自直连地址,不信任可伪造的 X-Forwarded-For。 */
static String sourceIp(HttpServletRequest request) {
String remote = request.getRemoteAddr();
return remote == null ? "unknown" : (remote.length() > 60 ? remote.substring(0, 60) : remote);
}
static Instant now() {
return Instant.now();
}
}
@@ -0,0 +1,172 @@
package com.qlinker.web;
import com.qlinker.binding.BindingRepository;
import com.qlinker.common.ApiCode;
import com.qlinker.common.ApiException;
import com.qlinker.common.ApiResponse;
import com.qlinker.init.BootstrapCoordinator;
import com.qlinker.security.AuthAttributes;
import com.qlinker.security.CurrentUser;
import com.qlinker.security.PermissionCatalog;
import com.qlinker.security.RequiresPermission;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.net.URI;
import java.util.List;
import java.util.Map;
/**
* NapCat 绑定管理(接口设计 6 章)。
*
* <p>一个 QLinker 对同一 NapCat 实例最多一条有效绑定,由数据库唯一约束强制;
* 访问令牌只写不读,任何接口都不回显明文(AGENTS.md 11.2)。</p>
*/
@RestController
@RequestMapping("/api/v1/napcat-bindings")
public class BindingController {
private final BindingRepository bindings;
private final BootstrapCoordinator coordinator;
private final com.qlinker.audit.AuditService audit;
public BindingController(BindingRepository bindings, BootstrapCoordinator coordinator,
com.qlinker.audit.AuditService audit) {
this.bindings = bindings;
this.coordinator = coordinator;
this.audit = audit;
}
public record CreateRequest(String displayName, String endpoint, String accessToken) {
}
public record RotateRequest(String accessToken) {
}
@GetMapping
@RequiresPermission(PermissionCatalog.NAPCAT_READ)
public ApiResponse<List<Map<String, Object>>> list() {
return ApiResponse.ok(bindings.findAll().stream().map(bindings::toView).toList());
}
@GetMapping("/{bindingUid}")
@RequiresPermission(PermissionCatalog.NAPCAT_READ)
public ApiResponse<Map<String, Object>> get(@PathVariable String bindingUid) {
return ApiResponse.ok(bindings.toView(require(bindingUid)));
}
@PostMapping
@RequiresPermission(PermissionCatalog.NAPCAT_MANAGE)
public ApiResponse<Map<String, Object>> create(@RequestBody CreateRequest request,
HttpServletRequest servletRequest) {
String endpoint = normalizeEndpoint(request.endpoint());
String instanceUid = resolveInstanceUid(endpoint, request.accessToken());
BindingRepository.Binding binding = bindings.create(instanceUid,
displayName(request.displayName(), endpoint), "forward_websocket", endpoint,
blankToNull(request.accessToken()));
audit.record(AuthAttributes.currentUser(servletRequest), "napcat.binding.create", "napcat_binding",
binding.bindingUid(), com.qlinker.audit.AuditService.RESULT_SUCCEEDED, null,
Map.of("endpoint", endpoint), AuthController.sourceIp(servletRequest));
return ApiResponse.ok(bindings.toView(binding));
}
/**
* 解绑:只做状态标记(UNBOUND),不删除任何历史消息与事件(数据库设计 15.2)。
*/
@DeleteMapping("/{bindingUid}")
@RequiresPermission(PermissionCatalog.NAPCAT_MANAGE)
public ApiResponse<Map<String, Object>> deactivate(@PathVariable String bindingUid,
HttpServletRequest servletRequest) {
BindingRepository.Binding binding = require(bindingUid);
bindings.updateStatus(binding.id(), com.qlinker.binding.BindingStatus.UNBOUND);
bindings.updateConnectionStatus(binding.id(), com.qlinker.binding.ConnectionStatus.DISCONNECTED, null, null);
audit.record(AuthAttributes.currentUser(servletRequest), "napcat.binding.deactivate", "napcat_binding",
bindingUid, com.qlinker.audit.AuditService.RESULT_SUCCEEDED, "解绑仅停用,历史消息与事件保留",
Map.of(), AuthController.sourceIp(servletRequest));
return ApiResponse.ok(Map.of("bindingUid", bindingUid, "bindingStatus",
com.qlinker.binding.BindingStatus.UNBOUND));
}
@PutMapping("/{bindingUid}/access-token")
@RequiresPermission(PermissionCatalog.NAPCAT_MANAGE)
public ApiResponse<Map<String, Object>> rotate(@PathVariable String bindingUid,
@RequestBody RotateRequest request,
HttpServletRequest servletRequest) {
BindingRepository.Binding binding = require(bindingUid);
if (request.accessToken() == null || request.accessToken().isBlank()) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "访问令牌不能为空");
}
bindings.rotateCredential(binding.id(), request.accessToken());
CurrentUser actor = AuthAttributes.currentUser(servletRequest);
audit.record(actor, "napcat.binding.rotate_token", "napcat_binding", bindingUid,
com.qlinker.audit.AuditService.RESULT_SUCCEEDED, null, Map.of(),
AuthController.sourceIp(servletRequest));
return ApiResponse.ok(Map.of("bindingUid", bindingUid, "rotated", true,
"note", "令牌已更新,不回显明文;NapCat 正向 WS 握手不校验令牌,凭据错误只能靠事件到达确认"));
}
private BindingRepository.Binding require(String bindingUid) {
return bindings.findByUid(bindingUid)
.orElseThrow(() -> new ApiException(ApiCode.RESOURCE_NOT_FOUND, "绑定不存在:" + bindingUid));
}
/**
* 只接受 ws/wss 正向 WebSocket 端点。禁止 http/https 与本地文件协议,
* 避免把绑定接口变成访问内网服务的入口(AGENTS.md 11.3)。
*/
static String normalizeEndpoint(String raw) {
if (raw == null || raw.isBlank()) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "连接地址不能为空");
}
URI uri;
try {
uri = URI.create(raw.trim());
} catch (IllegalArgumentException e) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "连接地址格式不合法");
}
String scheme = uri.getScheme();
if (scheme == null || !(scheme.equalsIgnoreCase("ws") || scheme.equalsIgnoreCase("wss"))) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "连接地址必须是 ws:// 或 wss:// 正向 WebSocket 端点");
}
if (uri.getHost() == null || uri.getHost().isBlank()) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "连接地址缺少主机名");
}
if (uri.getUserInfo() != null) {
throw new ApiException(ApiCode.VALIDATION_ERROR, "连接地址不得携带用户信息");
}
return uri.toString();
}
/**
* 解析 NapCat 实例稳定标识。正向 WS 端点本身不含实例身份,且 NapCat 未提供
* 无需凭据即可稳定区分的标识,因此退化为「端点哈希 + 可选令牌哈希」。
* 该标识只用于本实例内的唯一绑定约束,不作为跨 QLinker 的全局身份。
*/
static String resolveInstanceUidFrom(String endpoint, String accessToken) {
return "nci_" + com.qlinker.event.ContentHash.hex(
endpoint + "|" + (accessToken == null ? "" : accessToken)).substring(0, 24);
}
private String resolveInstanceUid(String endpoint, String accessToken) {
return resolveInstanceUidFrom(endpoint, accessToken);
}
private static String displayName(String provided, String endpoint) {
if (provided != null && !provided.isBlank()) {
return provided.length() > 100 ? provided.substring(0, 100) : provided.trim();
}
URI uri = URI.create(endpoint);
return (uri.getHost() == null ? "napcat" : uri.getHost()) + (uri.getPort() > 0 ? ":" + uri.getPort() : "");
}
private static String blankToNull(String value) {
return value == null || value.isBlank() ? null : value;
}
}
@@ -0,0 +1,80 @@
package com.qlinker.web;
import com.qlinker.common.ApiCode;
import com.qlinker.common.ApiException;
import com.qlinker.common.ApiResponse;
import com.qlinker.media.MediaService;
import com.qlinker.security.PermissionCatalog;
import com.qlinker.security.RequiresPermission;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 媒体状态与访问接口(接口设计 10 章)。
*
* <p>上游媒体 URL 含时效性 rkey,因此本接口只返回系统内状态与短时效预签名地址,
* 不透传上游 URL(能力基线:媒体 URL 必须现发现用)。</p>
*/
@RestController
@RequestMapping("/api/v1/media")
public class MediaController {
private final MediaService media;
public MediaController(MediaService media) {
this.media = media;
}
@GetMapping("/stats")
@RequiresPermission(PermissionCatalog.MEDIA_READ)
public ApiResponse<Map<String, Long>> stats() {
return ApiResponse.ok(media.statusCounts());
}
@GetMapping("/{mediaUid}")
@RequiresPermission(PermissionCatalog.MEDIA_READ)
public ApiResponse<Map<String, Object>> get(@PathVariable String mediaUid) {
return ApiResponse.ok(viewMap(require(mediaUid)));
}
@GetMapping("/{mediaUid}/access-url")
@RequiresPermission(PermissionCatalog.MEDIA_READ)
public ApiResponse<Map<String, Object>> accessUrl(@PathVariable String mediaUid) {
MediaService.MediaView view = require(mediaUid);
if (!MediaService.STATUS_STORED.equals(view.storageStatus())) {
throw new ApiException(ApiCode.RESOURCE_CONFLICT,
"媒体尚未成功入库,当前状态:" + view.storageStatus()
+ (view.errorMessage() == null ? "" : ",原因:" + view.errorMessage()));
}
String url = media.accessUrl(mediaUid)
.orElseThrow(() -> new ApiException(ApiCode.RESOURCE_CONFLICT,
"对象不可读:对象存储不可用或对象已缺失,请检查媒体状态后重试"));
return ApiResponse.ok(Map.of("mediaUid", mediaUid, "url", url,
"note", "地址为短时效预签名地址,过期后需重新获取"));
}
private MediaService.MediaView require(String mediaUid) {
return media.find(mediaUid)
.orElseThrow(() -> new ApiException(ApiCode.RESOURCE_NOT_FOUND, "媒体记录不存在:" + mediaUid));
}
static Map<String, Object> viewMap(MediaService.MediaView view) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("mediaUid", view.mediaUid());
map.put("mediaType", view.mediaType());
map.put("storageStatus", view.storageStatus());
map.put("fileName", view.fileName());
map.put("mimeType", view.mimeType());
map.put("fileSize", view.fileSize());
map.put("lastErrorCode", view.errorCode());
map.put("lastErrorMessage", view.errorMessage());
map.put("createdAt", view.createdAt());
map.put("updatedAt", view.updatedAt());
return map;
}
}
@@ -0,0 +1,66 @@
package com.qlinker.web;
import com.qlinker.common.ApiResponse;
import com.qlinker.common.PageData;
import com.qlinker.message.MessageQueryService;
import com.qlinker.security.PermissionCatalog;
import com.qlinker.security.RequiresPermission;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
* 消息查询接口(接口设计 9 章)。列表不返回原始 JSON,详情才返回(AGENTS.md 13.2)。
*/
@RestController
@RequestMapping("/api/v1/messages")
public class MessageController {
private final MessageQueryService query;
public MessageController(MessageQueryService query) {
this.query = query;
}
@GetMapping
@RequiresPermission(PermissionCatalog.MESSAGE_READ)
public ApiResponse<PageData<MessageQueryService.MessageRow>> list(
@RequestParam(required = false) Integer page,
@RequestParam(required = false) Integer pageSize,
@RequestParam(required = false) String conversationType,
@RequestParam(required = false) String conversationId,
@RequestParam(required = false) String senderId,
@RequestParam(required = false) String bindingUid,
@RequestParam(required = false) String direction,
@RequestParam(required = false) String from,
@RequestParam(required = false) String to,
@RequestParam(required = false) String keyword) {
return ApiResponse.ok(query.search(new MessageQueryService.Query(
page, pageSize, conversationType, conversationId, senderId, bindingUid, direction,
MessageQueryService.parseInstant(from), MessageQueryService.parseInstant(to), keyword)));
}
@GetMapping("/{messageUid}")
@RequiresPermission(PermissionCatalog.MESSAGE_READ)
public ApiResponse<MessageQueryService.MessageDetail> detail(@PathVariable String messageUid) {
return ApiResponse.ok(query.detail(messageUid));
}
@GetMapping("/conversations")
@RequiresPermission(PermissionCatalog.MESSAGE_READ)
public ApiResponse<PageData<Map<String, Object>>> conversations(@RequestParam(required = false) Integer page,
@RequestParam(required = false) Integer pageSize) {
return ApiResponse.ok(query.conversations(page == null ? 1 : page, pageSize == null ? 20 : pageSize));
}
@GetMapping("/stats")
@RequiresPermission(PermissionCatalog.MESSAGE_READ)
public ApiResponse<Map<String, Object>> stats() {
return ApiResponse.ok(query.stats());
}
}
@@ -0,0 +1,114 @@
package com.qlinker.web;
import com.qlinker.common.ApiCode;
import com.qlinker.common.ApiException;
import com.qlinker.common.ApiResponse;
import com.qlinker.security.AuthAttributes;
import com.qlinker.security.CurrentUser;
import com.qlinker.security.PermissionCatalog;
import com.qlinker.security.RequiresPermission;
import com.qlinker.send.SendService;
import jakarta.servlet.http.HttpServletRequest;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 统一发送入口(AGENTS.md 8.1、接口设计 11 章)。
*
* <p>发送分两步:prepare 只落库并签发确认令牌,不产生外部副作用;execute 校验令牌后才真正
* 调用 NapCat。上游超时等无法判定的情况返回 UNKNOWN 与操作标识,由人工核实,不自动重试。</p>
*/
@RestController
@RequestMapping("/api/v1/send")
public class SendController {
private final SendService send;
public SendController(SendService send) {
this.send = send;
}
public record PrepareRequest(String bindingUid, String targetType, String targetId, String text, String reason) {
}
public record ExecuteRequest(String confirmToken) {
}
@PostMapping("/text")
@RequiresPermission(PermissionCatalog.SEND_EXECUTE)
public ApiResponse<Map<String, Object>> prepare(@RequestBody PrepareRequest request,
@RequestHeader(value = "Idempotency-Key", required = false) String idempotencyKey,
HttpServletRequest servletRequest) {
CurrentUser actor = AuthAttributes.currentUser(servletRequest);
SendService.Prepared prepared = send.prepare(request.bindingUid(), request.targetType(),
request.targetId(), request.text(), request.reason(), idempotencyKey, actor,
AuthController.sourceIp(servletRequest));
Map<String, Object> data = new LinkedHashMap<>();
data.put("operationUid", prepared.operationUid());
data.put("confirmToken", prepared.confirmToken());
data.put("confirmExpiresAt", prepared.confirmExpiresAt());
data.put("targetSummary", prepared.targetSummary());
data.put("requiresConfirmation", true);
data.put("message", "已创建发送操作,尚未发送。请携带 confirmToken 调用 execute 完成二次确认");
return ApiResponse.ok(data);
}
@PostMapping("/operations/{operationUid}/execute")
@RequiresPermission(PermissionCatalog.SEND_EXECUTE)
public ApiResponse<Map<String, Object>> execute(@PathVariable String operationUid,
@RequestBody ExecuteRequest request,
HttpServletRequest servletRequest) {
CurrentUser actor = AuthAttributes.currentUser(servletRequest);
SendService.SendView view = send.execute(operationUid, request.confirmToken(), actor,
AuthController.sourceIp(servletRequest));
return ApiResponse.ok(viewMap(view));
}
@GetMapping("/operations/{operationUid}")
@RequiresPermission(PermissionCatalog.SEND_READ)
public ApiResponse<Map<String, Object>> get(@PathVariable String operationUid) {
return ApiResponse.ok(viewMap(send.find(operationUid)
.orElseThrow(() -> new ApiException(ApiCode.RESOURCE_NOT_FOUND, "发送操作不存在:" + operationUid))));
}
@GetMapping("/operations")
@RequiresPermission(PermissionCatalog.SEND_READ)
public ApiResponse<List<Map<String, Object>>> list(@RequestParam(required = false) Integer limit) {
return ApiResponse.ok(send.recent(limit == null ? 50 : limit));
}
@GetMapping("/summary")
@RequiresPermission(PermissionCatalog.SEND_READ)
public ApiResponse<Map<String, Object>> summary() {
return ApiResponse.ok(send.summary());
}
static Map<String, Object> viewMap(SendService.SendView view) {
Map<String, Object> map = new LinkedHashMap<>();
map.put("operationUid", view.operationUid());
map.put("status", view.status());
map.put("targetType", view.targetType());
map.put("targetId", view.targetId());
map.put("text", view.text());
map.put("attemptCount", view.attemptCount());
map.put("errorCode", view.errorCode());
map.put("errorMessage", view.errorMessage());
map.put("createdAt", view.createdAt());
map.put("finishedAt", view.finishedAt());
if (SendService.STATUS_UNKNOWN.equals(view.status())) {
// 上游可能已执行但本地未收到确认,必须显式说明语义,禁止自动重试造成重复发送。
map.put("warning", "上游结果未知:消息可能已送达也可能未送达。请勿重复发送,需人工核实");
}
return map;
}
}
@@ -0,0 +1,84 @@
package com.qlinker.web;
import com.qlinker.common.ApiResponse;
import com.qlinker.security.AuthService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 初始化状态查询(免鉴权,只暴露是否已完成初始化,不暴露令牌与凭据)。
*/
@RestController
@RequestMapping("/api/v1/system")
public class SystemStatusController {
private final AuthService auth;
private final com.qlinker.init.BootstrapCoordinator coordinator;
private final com.qlinker.napcat.NapCatConnectionManager connections;
private final com.qlinker.message.MessageQueryService messages;
private final com.qlinker.media.MediaService media;
private final com.qlinker.send.SendService send;
private final com.qlinker.binding.BindingRepository bindings;
public SystemStatusController(AuthService auth,
com.qlinker.init.BootstrapCoordinator coordinator,
com.qlinker.napcat.NapCatConnectionManager connections,
com.qlinker.message.MessageQueryService messages,
com.qlinker.media.MediaService media,
com.qlinker.send.SendService send,
com.qlinker.binding.BindingRepository bindings) {
this.auth = auth;
this.coordinator = coordinator;
this.connections = connections;
this.messages = messages;
this.media = media;
this.send = send;
this.bindings = bindings;
}
/** 前端启动时判断应进入初始化页还是登录页;不得在此返回令牌明文。 */
@GetMapping("/initialization")
public ApiResponse<Map<String, Object>> initialization() {
Map<String, Object> data = new LinkedHashMap<>();
boolean administrator = auth.hasAdministrator();
data.put("administratorExists", administrator);
data.put("bootstrapRequired", !administrator && auth.bootstrapTokenActive());
data.put("bootstrapTokenIssued", auth.hasBootstrapToken());
data.put("bootstrapTokenActive", auth.bootstrapTokenActive());
coordinator.blockedReason().ifPresent(reason -> data.put("recoveryRequired", reason));
coordinator.peek().ifPresent(identity -> {
data.put("instanceUid", identity.instanceUid());
data.put("databaseName", identity.databaseName());
data.put("bucketName", identity.bucketName());
data.put("initStage", identity.stage().name());
data.put("schemaVersion", identity.schemaVersion());
});
return ApiResponse.ok(data);
}
/**
* 依赖健康分项展示(AGENTS.md 16.2)。单一 HTTP 存活不代表依赖可用,
* 因此数据库、对象存储、NapCat、事件接收、任务积压分别给出真实状态。
*/
@GetMapping("/health-detail")
@com.qlinker.security.RequiresPermission(com.qlinker.security.PermissionCatalog.SYSTEM_READ)
public ApiResponse<Map<String, Object>> healthDetail() {
Map<String, Object> data = new LinkedHashMap<>();
data.put("application", "UP");
data.put("instance", coordinator.peek().map(com.qlinker.init.InstanceIdentity::instanceUid).orElse(null));
Map<String, Object> bindingSummary = new LinkedHashMap<>();
bindingSummary.put("total", bindings.findAll().size());
bindingSummary.put("connections", connections.status());
bindingSummary.put("items", bindings.connectionSnapshot());
data.put("napcat", bindingSummary);
data.put("messages", messages.stats());
data.put("media", media.statusCounts());
data.put("send", send.summary());
return ApiResponse.ok(data);
}
}
+61
View File
@@ -4,6 +4,55 @@ server:
spring:
application:
name: qlinker-server
jackson:
default-property-inclusion: non_null
serialization:
write-dates-as-timestamps: false
# 业务数据源在启动阶段由初始化流程确定资源身份后构建,因此这里不配置 spring.datasource,
# 避免自动配置连到一个与实例身份无关的默认库(AGENTS.md 12.2)。
autoconfigure:
exclude:
- org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
- org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration
qlinker:
session-ttl: 8h
instance:
# 主密钥必须由部署环境注入,禁止把真实值写入仓库(AGENTS.md 11.2)。
# 本地开发示例:设置环境变量 QLINKER_INSTANCE_MASTER_KEY 为 Base64 编码的 32 字节随机值。
master-key: ${QLINKER_INSTANCE_MASTER_KEY:}
state-dir: ${QLINKER_STATE_DIR:./data}
mysql-host: ${QLINKER_MYSQL_HOST:127.0.0.1}
mysql-port: ${QLINKER_MYSQL_PORT:3306}
mysql-user: ${QLINKER_MYSQL_USER:}
mysql-password: ${QLINKER_MYSQL_PASSWORD:}
max-pool-size: 8
random-id-length: 8
max-create-attempts: 5
bootstrap-enabled: ${QLINKER_BOOTSTRAP_ENABLED:true}
storage:
endpoint: ${QLINKER_MINIO_ENDPOINT:http://127.0.0.1:9000}
access-key: ${QLINKER_MINIO_ACCESS_KEY:}
secret-key: ${QLINKER_MINIO_SECRET_KEY:}
region: us-east-1
media:
max-bytes: 104857600
download-timeout: 60s
retention-days: 365
presign-ttl: 5m
# 仅本地开发环境显式开启;生产环境必须为 false(AGENTS.md 11.3)。
allow-private-network: ${QLINKER_MEDIA_ALLOW_PRIVATE:false}
send:
rate-limit-per-minute: 10
confirm-token-ttl: 5m
api-timeout: 30s
napcat:
connect-timeout: 15s
reconnect-min-backoff: 2s
reconnect-max-backoff: 60s
online-confirm-timeout: 30s
max-event-bytes: 8388608
receiver-enabled: ${QLINKER_NAPCAT_RECEIVER_ENABLED:true}
management:
endpoints:
@@ -13,3 +62,15 @@ management:
endpoint:
health:
show-details: never
health:
# 业务库在初始化完成后才可用;进程存活与资源可用性分开判断,
# 数据库/对象存储/NapCat 的分别状态由 /api/v1/system/health-detail 暴露(AGENTS.md 16.2)。
db:
enabled: false
logging:
level:
root: INFO
com.qlinker: INFO
pattern:
console: "%d{yyyy-MM-dd'T'HH:mm:ss.SSSXXX} %-5level [%X{requestId:-}] %logger{36} - %msg%n"
@@ -0,0 +1,59 @@
-- 任务 003 / 数据库设计第 7 章:NapCat 绑定与能力表
-- 依据:docs/数据库设计.md 7.1、7.2、15.2(绑定解绑或停用,保留历史事件来源,故不物理删除)。
-- 业务规则:一个 QLinker 对同一 NapCat 实例最多一条有效绑定;同一 NapCat 可被多个 QLinker 绑定;
-- 不假定 endpoint 唯一;qq_account_id 不能代替 NapCat 实例身份。
-- 本文件不包含任何真实地址、令牌或凭据。
CREATE TABLE `napcat_binding` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '内部绑定 ID',
`binding_uid` VARCHAR(64) NOT NULL COMMENT '稳定绑定标识,本库内唯一',
`instance_uid` VARCHAR(128) NOT NULL COMMENT 'NapCat 实例身份,不等同于 qq_account_id',
`display_name` VARCHAR(128) NOT NULL COMMENT '显示名称',
`connection_type` VARCHAR(32) NOT NULL COMMENT '通信方式,受控状态值',
`endpoint` VARCHAR(512) NOT NULL COMMENT '连接地址;不要求唯一,可被多个 QLinker 绑定',
`credential_ref_id` BIGINT NULL COMMENT '敏感凭证引用,指向 secret_reference.id;不保存凭据本身',
`binding_status` VARCHAR(32) NOT NULL COMMENT '绑定状态,受控状态值',
`connection_status` VARCHAR(32) NOT NULL COMMENT '当前连接状态,受控状态值',
`napcat_version` VARCHAR(64) NULL COMMENT '已知 NapCat 版本',
`qq_account_id` VARCHAR(128) NULL COMMENT 'QQ 账号标识,可能为空;不得代替实例身份',
`last_connected_at` DATETIME(3) NULL COMMENT '最后成功连接时间(UTC)',
`last_event_at` DATETIME(3) NULL COMMENT '最后接收事件时间(UTC)',
`last_error_code` VARCHAR(64) NULL COMMENT '最近错误码',
`last_error_at` DATETIME(3) NULL COMMENT '最近错误时间(UTC)',
`created_at` DATETIME(3) NOT NULL COMMENT '创建时间(UTC)',
`updated_at` DATETIME(3) NOT NULL COMMENT '更新时间(UTC)',
-- 任务 004 落地「同一 instance_uid 最多一条有效绑定」的条件唯一约束(数据库设计 7.1 生成列方案)。
-- 本部署单元的有效绑定状态在代码与接口中固定为 ACTIVE,其余状态(DISABLED / UNBOUND)不计入唯一性;
-- 该字面量与 com.qlinker.binding.BindingStatus 保持一致,改动必须同时新增迁移,不得原地改写本文件。
`active_instance_uid` VARCHAR(128)
GENERATED ALWAYS AS (IF(`binding_status` = 'ACTIVE', `instance_uid`, NULL)) STORED
COMMENT '仅在 binding_status=ACTIVE 时等于 instance_uid,用于条件唯一约束',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_napcat_binding_binding_uid` (`binding_uid`),
UNIQUE KEY `uk_napcat_binding_active_instance` (`active_instance_uid`),
KEY `idx_napcat_binding_instance_status` (`instance_uid`, `binding_status`),
CONSTRAINT `fk_napcat_binding_credential_ref` FOREIGN KEY (`credential_ref_id`) REFERENCES `secret_reference` (`id`) ON DELETE RESTRICT
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci COMMENT 'NapCat 绑定与连接配置(数据库设计 7.1)';
-- 能力目录为全局目录表:多列验证状态必须分开记录,不得用单个布尔值代替(数据库设计 7.2)。
CREATE TABLE `napcat_capability` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '内部主键',
`capability_code` VARCHAR(128) NOT NULL COMMENT '能力标识,唯一',
`capability_name` VARCHAR(128) NOT NULL COMMENT '能力名称',
`capability_type` VARCHAR(32) NOT NULL COMMENT '能力类型,受控状态值',
`official_document_status` VARCHAR(32) NOT NULL COMMENT '官方文档声明状态,受控状态值',
`adapter_implementation_status` VARCHAR(32) NOT NULL COMMENT '适配代码状态,受控状态值',
`automated_test_status` VARCHAR(32) NOT NULL COMMENT '自动化测试状态,受控状态值',
`version_compatibility_status` VARCHAR(32) NOT NULL COMMENT '版本兼容验证状态,受控状态值',
`real_environment_status` VARCHAR(32) NOT NULL COMMENT '真实环境测试状态,受控状态值',
`known_limitations` TEXT NULL COMMENT '已知限制',
`last_verified_at` DATETIME(3) NULL COMMENT '最后验证时间(UTC)',
`created_at` DATETIME(3) NOT NULL COMMENT '创建时间(UTC)',
`updated_at` DATETIME(3) NOT NULL COMMENT '更新时间(UTC)',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_napcat_capability_capability_code` (`capability_code`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci COMMENT 'NapCat 能力及验证状态(数据库设计 7.2)';
@@ -0,0 +1,164 @@
-- 任务 004 / 初始化引导、媒体、发送与审计表
-- 依据:docs/数据库设计.md 9.1、9.2、12.1、12.2、14.1;docs/接口设计.md 12、18 章;
-- docs/系统架构设计.md 13.3(初始化步骤)、10.1(统一发送入口)。
-- bootstrap_token 为任务 004 新增表:正式表清单未覆盖「一次性初始化管理员引导」,
-- 差异已登记在 docs/数据库设计.md 5.4 与 docs/LLMChangeMemory/任务-004-交付文档.md。
-- 本文件不包含任何真实账号、令牌、地址或凭据。
-- 一次性初始化令牌:只保存 SHA-256 哈希,成功使用后写 used_at 并永久失效(不再接受任何请求)。
CREATE TABLE `bootstrap_token` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '内部主键',
`token_uid` VARCHAR(64) NOT NULL COMMENT '令牌记录标识,唯一',
`token_hash` CHAR(64) NOT NULL COMMENT '初始化令牌 SHA-256 哈希;不得保存令牌明文',
`token_status` VARCHAR(32) NOT NULL COMMENT '令牌状态,受控状态值:ACTIVE / USED / REVOKED',
`issued_at` DATETIME(3) NOT NULL COMMENT '签发时间(UTC)',
`expires_at` DATETIME(3) NULL COMMENT '过期时间(UTC);为空表示不设过期',
`used_at` DATETIME(3) NULL COMMENT '成功使用时间(UTC);非空即永久失效',
`used_by` BIGINT NULL COMMENT '使用该令牌创建的管理用户 ID(应用层约束)',
`attempt_count` INT NOT NULL DEFAULT 0 COMMENT '校验失败次数,用于限流与审计',
`created_at` DATETIME(3) NOT NULL COMMENT '记录创建时间(UTC)',
`updated_at` DATETIME(3) NOT NULL COMMENT '更新时间(UTC)',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_bootstrap_token_token_uid` (`token_uid`),
UNIQUE KEY `uk_bootstrap_token_token_hash` (`token_hash`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci COMMENT '一次性初始化管理员引导令牌(任务 004)';
-- 媒体元数据与对象存储引用(数据库设计 9.1)。
-- storage_status 使用任务 004 定稿的受控值:PENDING / DOWNLOADING / STORED / FAILED /
-- SOURCE_EXPIRED / OBJECT_MISSING / UNKNOWN;unsupported 由 media_type 不支持表达(见 media_type 注释)。
CREATE TABLE `media_object` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '内部主键',
`media_uid` VARCHAR(64) NOT NULL COMMENT '稳定媒体标识,唯一',
`source_binding_id` BIGINT NOT NULL COMMENT '来源绑定 ID(应用层约束,指向 napcat_binding.id)',
`source_media_id` VARCHAR(255) NULL COMMENT '来源媒体 ID;唯一性未经验证,不建唯一约束(数据库设计 9.1)',
`storage_bucket` VARCHAR(63) NULL COMMENT '对象所在 bucket;下载成功前为空',
`object_key` VARCHAR(1024) NULL COMMENT '系统生成的对象 key;不得由用户输入拼接',
`file_name` VARCHAR(512) NULL COMMENT '清理后的展示文件名;不直接用于对象路径',
`mime_type` VARCHAR(255) NULL COMMENT '由实际字节嗅探得到的 MIME 类型,不信任上游声明',
`media_type` VARCHAR(32) NOT NULL COMMENT '业务媒体类型:image / video / record / file / unsupported',
`file_size` BIGINT NULL COMMENT '文件大小,字节',
`content_hash` BINARY(32) NULL COMMENT '内容 SHA-256 哈希',
`storage_status` VARCHAR(32) NOT NULL COMMENT '存储状态,受控状态值',
`security_status` VARCHAR(32) NOT NULL COMMENT '安全检查状态,受控状态值',
`source_url_hash` CHAR(64) NULL COMMENT '来源 URL 的 SHA-256,用于排查时效问题;不保存原始 URL 明文',
`last_error_code` VARCHAR(64) NULL COMMENT '最近错误码',
`last_error_message` VARCHAR(1000) NULL COMMENT '脱敏错误摘要,不得含带签名参数的完整 URL',
`retention_until` DATETIME(3) NULL COMMENT '保留期限(UTC)',
`created_at` DATETIME(3) NOT NULL COMMENT '创建时间(UTC)',
`updated_at` DATETIME(3) NOT NULL COMMENT '更新时间(UTC)',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_media_object_media_uid` (`media_uid`),
KEY `idx_media_object_source` (`source_binding_id`, `source_media_id`),
KEY `idx_media_object_status_created` (`storage_status`, `created_at`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci COMMENT '媒体元数据与对象存储引用(数据库设计 9.1)';
-- 内容哈希去重索引按 9.1「仅在需要内容去重时建立」,任务 004 未启用内容去重,故不建。
CREATE TABLE `media_operation` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '内部主键',
`media_object_id` BIGINT NOT NULL COMMENT '关联媒体 ID',
`operation_type` VARCHAR(32) NOT NULL COMMENT '操作类型,受控状态值:download / upload / verify / delete',
`operation_status` VARCHAR(32) NOT NULL COMMENT '操作状态,受控状态值',
`retry_count` INT NOT NULL DEFAULT 0 COMMENT '重试次数',
`started_at` DATETIME(3) NULL COMMENT '开始时间(UTC)',
`finished_at` DATETIME(3) NULL COMMENT '结束时间(UTC)',
`last_error_code` VARCHAR(64) NULL COMMENT '错误码',
`last_error_message` VARCHAR(1000) NULL COMMENT '脱敏错误摘要',
`created_at` DATETIME(3) NOT NULL COMMENT '创建时间(UTC)',
`updated_at` DATETIME(3) NOT NULL COMMENT '更新时间(UTC)',
PRIMARY KEY (`id`),
KEY `idx_media_operation_media_created` (`media_object_id`, `created_at`),
KEY `idx_media_operation_status_created` (`operation_status`, `created_at`),
CONSTRAINT `fk_media_operation_media_object_id` FOREIGN KEY (`media_object_id`) REFERENCES `media_object` (`id`) ON DELETE RESTRICT
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci COMMENT '媒体下载、上传、校验与删除任务(数据库设计 9.2)';
-- 统一发送记录(数据库设计 12.1)。
-- 任务 004 只开放管理员手动单条文本发送,source_type 固定 MANUAL;自动化与 AI 来源为后续任务预留。
-- 内容保存策略:保存完整正文(operation_status 与权限受控访问),审计展示使用摘要,见接口设计 12 章。
CREATE TABLE `send_operation` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '内部主键',
`operation_uid` VARCHAR(64) NOT NULL COMMENT '发送操作标识,唯一',
`binding_id` BIGINT NOT NULL COMMENT '目标绑定 ID(应用层约束,指向 napcat_binding.id)',
`source_type` VARCHAR(32) NOT NULL COMMENT '来源类型,受控状态值:MANUAL / RULE / AI / SCHEDULE',
`source_id` VARCHAR(64) NULL COMMENT '来源对象标识',
`target_type` VARCHAR(32) NOT NULL COMMENT '目标类型,受控状态值:private / group',
`target_id` VARCHAR(128) NOT NULL COMMENT '目标标识,保留原始字符串表示',
`message_payload` TEXT NOT NULL COMMENT '发送给 NapCat 的消息段 JSON',
`payload_hash` BINARY(32) NOT NULL COMMENT '消息段哈希;用于幂等参数一致性校验',
`operation_status` VARCHAR(32) NOT NULL COMMENT '发送状态,受控状态值:PENDING/RUNNING/SUCCEEDED/FAILED/UNKNOWN/RETRY_WAIT/CANCELLED/REJECTED',
`risk_level` VARCHAR(32) NOT NULL COMMENT '风险级别,受控状态值',
`approval_required` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否需要审批;任务 004 使用后端二次确认令牌',
`approval_status` VARCHAR(32) NULL COMMENT '审批状态,受控状态值',
`idempotency_key` VARCHAR(128) NULL COMMENT '幂等键;必须持久化,不得只存进程内缓存',
`confirm_token_hash` CHAR(64) NULL COMMENT '二次确认令牌哈希;后端据此确认操作者已确认目标与完整正文',
`attempt_count` INT NOT NULL DEFAULT 0 COMMENT '已尝试次数',
`created_by` BIGINT NOT NULL COMMENT '创建人 user_account.id(应用层约束)',
`reason` VARCHAR(512) NULL COMMENT '发送理由',
`created_at` DATETIME(3) NOT NULL COMMENT '创建时间(UTC)',
`started_at` DATETIME(3) NULL COMMENT '开始执行时间(UTC)',
`finished_at` DATETIME(3) NULL COMMENT '结束时间(UTC)',
`last_error_code` VARCHAR(64) NULL COMMENT '最近错误码',
`last_error_message` VARCHAR(1000) NULL COMMENT '脱敏错误摘要',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_send_operation_operation_uid` (`operation_uid`),
UNIQUE KEY `uk_send_operation_idempotency_key` (`idempotency_key`),
KEY `idx_send_operation_binding_created` (`binding_id`, `created_at`),
KEY `idx_send_operation_status_created` (`operation_status`, `created_at`),
KEY `idx_send_operation_target_created` (`target_type`, `target_id`, `created_at`),
KEY `idx_send_operation_source` (`source_type`, `source_id`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci COMMENT '统一发送记录(数据库设计 12.1)';
CREATE TABLE `send_attempt` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '内部主键',
`send_operation_id` BIGINT NOT NULL COMMENT '所属发送操作 ID',
`attempt_number` INT NOT NULL COMMENT '第几次尝试,从 1 开始',
`request_summary` VARCHAR(1000) NULL COMMENT '请求摘要;不得含访问令牌',
`response_summary` VARCHAR(1000) NULL COMMENT '响应摘要;不得含完整凭据',
`attempt_status` VARCHAR(32) NOT NULL COMMENT '尝试状态,受控状态值:SUCCEEDED / FAILED / UNKNOWN',
`started_at` DATETIME(3) NOT NULL COMMENT '开始时间(UTC)',
`finished_at` DATETIME(3) NULL COMMENT '结束时间(UTC)',
`duration_ms` BIGINT NULL COMMENT '耗时,毫秒',
`error_code` VARCHAR(64) NULL COMMENT '错误码',
`error_message` VARCHAR(1000) NULL COMMENT '脱敏错误摘要',
`created_at` DATETIME(3) NOT NULL COMMENT '创建时间(UTC)',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_send_attempt_operation_attempt` (`send_operation_id`, `attempt_number`),
CONSTRAINT `fk_send_attempt_send_operation_id` FOREIGN KEY (`send_operation_id`) REFERENCES `send_operation` (`id`) ON DELETE RESTRICT
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci COMMENT '单次发送尝试(数据库设计 12.2)';
-- 审计日志采用追加式设计:不提供 UPDATE / DELETE 路径,普通业务用户不得修改或删除(数据库设计 14.1)。
CREATE TABLE `audit_log` (
`id` BIGINT NOT NULL AUTO_INCREMENT COMMENT '内部主键',
`audit_uid` VARCHAR(64) NOT NULL COMMENT '审计记录标识,唯一',
`actor_type` VARCHAR(32) NOT NULL COMMENT '操作主体类型,受控状态值:USER / SYSTEM / AI',
`actor_id` BIGINT NULL COMMENT '操作主体 ID;系统主体为空',
`actor_name` VARCHAR(128) NULL COMMENT '操作主体展示名',
`action` VARCHAR(128) NOT NULL COMMENT '操作类型,受控状态值',
`resource_type` VARCHAR(64) NULL COMMENT '目标资源类型',
`resource_id` VARCHAR(128) NULL COMMENT '目标资源标识',
`result` VARCHAR(32) NOT NULL COMMENT '操作结果,受控状态值:SUCCEEDED / FAILED / DENIED',
`reason` VARCHAR(512) NULL COMMENT '操作理由或失败原因',
`request_id` VARCHAR(64) NULL COMMENT '请求追踪标识',
`trace_id` VARCHAR(64) NULL COMMENT '链路追踪标识',
`source_ip` VARCHAR(64) NULL COMMENT '来源地址',
`details` JSON NULL COMMENT '结构化详情;不得含密码、密钥或完整访问令牌',
`created_at` DATETIME(3) NOT NULL COMMENT '记录创建时间(UTC)',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_audit_log_audit_uid` (`audit_uid`),
KEY `idx_audit_log_actor_created` (`actor_id`, `created_at`),
KEY `idx_audit_log_action_created` (`action`, `created_at`),
KEY `idx_audit_log_resource_created` (`resource_type`, `resource_id`, `created_at`),
KEY `idx_audit_log_result_created` (`result`, `created_at`)
) ENGINE = InnoDB
DEFAULT CHARSET = utf8mb4
COLLATE = utf8mb4_0900_ai_ci COMMENT '操作审计(数据库设计 14.1)';