feat(device): 设备签名升级为 ECDSA 并新增壁纸/图片/闹钟与策略扩展

签名与安全
- 设备验签由 HMAC 重构为 ECDSA P-256(SHA256withECDSA),抽出
  DeviceSignatureVerifier,canonical 串为 METHOD|path|bodyHash|ts|nonce
- 新增 CachedBodyRequestWrapper 支持请求体读取,multipart 不参与 bodyHash
- Redis 一次性 nonce 防重放,验签前校验设备存在且 status != 0(封禁即吊销)
- bind_phone 接口豁免过滤器,改由 Controller 用请求内公钥做 PoP 验签并自动注册
- 新增封禁/解封设备接口(sys:device:update),SQL 增加 sys_sn.public_key

家属端(client)
- 壁纸:上传单个 / 轮换(最多 7 张)/ 调整顺序,静态资源映射 /static/wallpaper/**
- 图片:发送到设备(contentType=24)、发送记录列表、收藏状态标记
- 闹钟:查询 / 新增 / 修改 / 删除,变更后推送设备同步(contentType=25)
- 新增请求绑定设备(contentType=20)、绑定成功通知(21)、反向拨号(22)

设备端(mobile)
- 新增 get_alarms / sync_alarms,按设备本地 id 整表覆盖重建
- 策略接口同步新增 20 项管控开关(安全模式、ADB、APN、飞行模式、定位等)

其他
- MQTT 首次连接失败不再阻塞启动,新增每分钟定时兜底重连
- 文件服务补充 md5/sha1/sha256 校验值,AppIcon 增加 iconSha1/iconSha256
- 新增 SQL:sn_device_key / sn_device_alarm / sn_device_picture / sn_device_wallpaper
This commit is contained in:
TongTongStudio committed 2026-10-19 10:41:17 +08:00
1 parent af2b9846f1
commit adb9b96cb7
51 files changed
+2965 -173

No files matched your search

@@ -1,12 +1,12 @@
package com.youlai.boot.device.controller;
import cn.hutool.core.util.IdUtil;
import com.youlai.boot.common.annotation.Log;
import com.youlai.boot.common.config.FilePath;
import com.youlai.boot.common.enums.ActionTypeEnum;
import com.youlai.boot.common.enums.LogModuleEnum;
import com.youlai.boot.common.exception.BusinessException;
import com.youlai.boot.common.result.Result;
import com.youlai.boot.common.result.ResultCode;
import com.youlai.boot.common.util.HashUtils;
import com.youlai.boot.device.model.entity.SnDeviceSystemInfo;
import com.youlai.boot.device.model.entity.SnDeviceHardwareInfo;
@@ -27,9 +27,12 @@ import com.youlai.boot.device.model.entity.SnScreenshot;
import com.youlai.boot.device.model.req.DevicePolicyReq;
import com.youlai.boot.device.model.req.DevicePolicyToggleReq;
import com.youlai.boot.device.model.vo.DeveloperOptionsVO;
import com.youlai.boot.device.model.vo.DeviceAlarmVO;
import com.youlai.boot.device.model.vo.DevicePolicyVO;
import com.youlai.boot.device.model.vo.DeviceWallpaperVO;
import com.youlai.boot.device.converter.DevicePolicyConverter;
import com.youlai.boot.device.service.*;
import com.youlai.boot.framework.security.signature.DeviceSignatureVerifier;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
@@ -37,7 +40,6 @@ import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
@@ -47,7 +49,6 @@ import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
/**
* 设备控制层
@@ -59,9 +60,6 @@ import java.util.concurrent.TimeUnit;
@RequestMapping("/api/v1/sn")
@RequiredArgsConstructor
public class MobileController {
private static final String DEVICE_SECRET_PREFIX = "device:secret:";
private final RedisTemplate<String, Object> redisTemplate;
private final DeviceService deviceService;
private final ScreenshotService screenshotService;
private final LocationService locationService;
@@ -75,27 +73,123 @@ public class MobileController {
private final OtherInfoService otherInfoService;
private final DevicePolicyService devicePolicyService;
private final DevicePolicyConverter devicePolicyConverter;
private final DeviceSignatureVerifier deviceSignatureVerifier;
private final DeviceWallpaperService deviceWallpaperService;
private final DeviceAlarmService deviceAlarmService;
private final Logger logger = LoggerFactory.getLogger(MobileController.class);
@Operation(summary = "注册设备")
@PostMapping("/register")
@Log(module = LogModuleEnum.MOBILE, value = ActionTypeEnum.REGISTER)
public Map<String, Object> registerDevice(@RequestParam() String sn) {
@Operation(summary = "设备确认绑定手机号(绑定即注册)",
description = "设备端同意家属绑定请求后调用。接口豁免标准签名过滤,改用 PoP 验签:\n" +
"1) 用请求内公钥验证设备对 challenge(sn:ts:nonce) 的 ECDSA 签名;\n" +
"2) 自动注册设备(SN ↔ 公钥,不存在则新建,已存在则更新公钥);\n" +
"3) 写入 sys_sn.snMobile 完成绑定,并向设备回推绑定成功。\n" +
"设备首次绑定前可能尚未注册(无公钥),故不能走标准 ECDSA 验签,而是与注册接口相同的 PoP 方式。")
@PostMapping("/bind_phone")
@Log(module = LogModuleEnum.MOBILE, value = ActionTypeEnum.UPDATE)
public Result<?> bindPhone(
@RequestParam() String sn,
@RequestParam(value = "model", required = false) String model,
@RequestParam(value = "publicKey", required = false) String publicKey,
@RequestParam(value = "challenge", required = false) String challenge,
@RequestParam(value = "signature", required = false) String signature,
@RequestParam() String phone) {
// 生成设备密钥
String deviceSecret = IdUtil.fastSimpleUUID();
if (sn == null || sn.trim().isEmpty()) {
return Result.failed("设备序列号不能为空");
}
if (phone == null || phone.trim().isEmpty()) {
return Result.failed("绑定手机号不能为空");
}
// 存储到Redis(可根据需要设置过期时间)
redisTemplate.opsForValue().set(DEVICE_SECRET_PREFIX + sn, deviceSecret, 365, TimeUnit.DAYS);
try {
// 1. PoP 验签:设备可能尚未注册(无公钥),用请求内公钥验证 challenge 签名
if (publicKey == null || publicKey.trim().isEmpty()
|| challenge == null || challenge.trim().isEmpty()
|| signature == null || signature.trim().isEmpty()) {
return Result.failed("设备公钥/挑战值/签名不能为空");
}
if (!verifyRegisterChallenge(publicKey, challenge, signature)) {
return Result.failed(ResultCode.MOBILE_SIGN_INVALID, "设备签名验证失败");
}
Map<String, Object> result = new HashMap<>();
result.put("deviceId", sn);
result.put("deviceSecret", deviceSecret);
result.put("message", "请妥善保管设备密钥,用于生成API签名");
// 2. 注册设备(绑定即注册):SN ↔ 公钥,不存在则新建,已存在则更新公钥
SnDeviceInfo device = deviceService.lambdaQuery()
.eq(SnDeviceInfo::getSerialno, sn)
.one();
if (device == null) {
device = new SnDeviceInfo();
device.setSerialno(sn);
device.setStatus(1);
device.setSnModel(model);
device.setPublicKey(publicKey);
boolean saved = deviceService.save(device);
if (!saved) {
return Result.failed("设备注册失败");
}
} else {
device.setPublicKey(publicKey);
if (model != null && !model.trim().isEmpty()) {
device.setSnModel(model);
}
deviceService.updateById(device);
}
return result;
// 3. 已绑定给其他手机号则拒绝(同一设备仅允许一个家属手机号)
if (StringUtils.hasText(device.getSnMobile())
&& !device.getSnMobile().equals(phone.trim())) {
return Result.failed("该设备已绑定其他手机号");
}
// 4. 写入绑定关系
device.setSnMobile(phone.trim());
deviceService.updateById(device);
logger.info("设备确认绑定成功(绑定即注册), sn: {}, phone: {}", sn, phone.trim());
// 5. 回推绑定成功通知到设备端(contentType=21)
deviceService.pushBindSuccess(sn, phone.trim());
Map<String, Object> result = new HashMap<>();
result.put("sn", sn);
result.put("phone", phone.trim());
result.put("message", "设备绑定成功");
return Result.success(result);
} catch (BusinessException be) {
return Result.failed(be.getMessage());
} catch (Exception e) {
logger.error("bindPhone error, sn: {}, phone: {}", sn, phone, e);
return Result.failed("绑定手机号失败: " + e.getMessage());
}
}
/**
* 校验绑定请求的 PoP 签名:用请求内上传的公钥验证设备对 challenge(sn:ts:nonce)的 ECDSA 签名。
*
* <p><b>不校验 challenge 内时间戳的时效</b>,原因:</p>
* <ul>
* <li>设备(老人机/定制 ROM)系统时间可能长期未校准,强制 2 分钟窗口会导致绑定失败
* (实测设备时间与服务器偏差可达数天);</li>
* <li>{@code bind_phone} 的绑定语义天然防重放:一台设备只能绑定一个手机号,
* 重复绑定同一手机号是幂等操作,攻击者重放也无法篡改为其他手机号
* (必须持有私钥重新签名)。</li>
* </ul>
* PoP 验签本身已证明「请求者持有该公钥对应的私钥」。
*/
private boolean verifyRegisterChallenge(String publicKey, String challenge, String signature) {
try {
// 解析 challenge:sn:ts:nonce(格式校验,时间戳仅作为签名原文的一部分,不校验时效)
String[] parts = challenge.split(":", 3);
if (parts.length != 3) {
return false;
}
Long.parseLong(parts[1]);
// 用公钥验签
return deviceSignatureVerifier.verify(publicKey, challenge, signature);
} catch (Exception e) {
logger.error("verifyRegisterChallenge error, sn: {}, challenge: {}", challenge, e.getMessage());
return false;
}
}
@Operation(summary = "上传设备硬件信息")
@@ -573,6 +667,63 @@ public class MobileController {
}
}
@Operation(summary = "获取设备壁纸配置", description = "返回设备的壁纸配置(mode:0-单个 1-轮换;images:图片URL列表),未配置时返回 null")
@GetMapping("/get_wallpaper")
public Result<DeviceWallpaperVO> getWallpaper(
@RequestHeader(value = "X-Device-SN") String sn
) {
try {
if (sn == null || sn.trim().isEmpty()) {
return Result.failed("设备序列号不能为空");
}
DeviceWallpaperVO vo = deviceWallpaperService.getBySn(sn.trim());
// 未配置壁纸时返回 success(null),设备端按默认壁纸处理
return Result.success(vo);
} catch (Exception e) {
logger.error("getWallpaper error, sn: {}", sn, e);
return Result.failed("获取壁纸配置失败: " + e.getMessage());
}
}
// ===================== 设备闹钟(设备端同步) =====================
@Operation(summary = "获取设备闹钟列表", description = "返回该设备全部闹钟(按时间升序),设备收到推送或启动时拉取并覆盖本地 Room")
@GetMapping("/get_alarms")
public Result<List<DeviceAlarmVO>> getAlarms(
@RequestHeader(value = "X-Device-SN") String sn
) {
try {
if (sn == null || sn.trim().isEmpty()) {
return Result.failed("设备序列号不能为空");
}
return Result.success(deviceAlarmService.listAlarms(sn.trim()));
} catch (Exception e) {
logger.error("getAlarms error, sn: {}", sn, e);
return Result.failed("获取闹钟列表失败: " + e.getMessage());
}
}
@Operation(summary = "整表同步设备闹钟", description = "设备端本地增删改闹钟后整表上传,服务端逻辑删除旧数据后按设备本地 id 重建")
@PostMapping("/sync_alarms")
public Result<?> syncAlarms(
@RequestHeader(value = "X-Device-SN") String sn,
@RequestBody(required = false) List<DeviceAlarmVO> alarms
) {
try {
if (sn == null || sn.trim().isEmpty()) {
return Result.failed("设备序列号不能为空");
}
boolean ok = deviceAlarmService.replaceAlarms(sn.trim(), alarms);
if (!ok) {
return Result.failed("闹钟同步失败");
}
return Result.success();
} catch (Exception e) {
logger.error("syncAlarms error, sn: {}", sn, e);
return Result.failed("闹钟同步失败: " + e.getMessage());
}
}
// ===================== 设备策略信息(设备端) =====================
@Operation(summary = "获取设备策略信息", description = "SN 合法且无记录时自动新建默认策略(默认全开)")
@@ -653,19 +804,36 @@ public class MobileController {
target.setStorageCard(src.getStorageCard());
target.setFactoryReset(src.getFactoryReset());
target.setWifiHotspot(src.getWifiHotspot());
target.setBluetoothSwitch(src.getBluetoothSwitch());
target.setBluetooth(src.getBluetooth());
target.setWallpaper(src.getWallpaper());
target.setNotificationBar(src.getNotificationBar());
target.setStatusBarPullDown(src.getStatusBarPullDown());
target.setSystemNavBarShow(src.getSystemNavBarShow());
target.setSystemNavBarSetting(src.getSystemNavBarSetting());
target.setNavBarOptions(src.getNavBarOptions());
target.setBluetoothFunction(src.getBluetoothFunction());
target.setConfigBluetooth(src.getConfigBluetooth());
target.setOtaUpgrade(src.getOtaUpgrade());
target.setAppInstall(src.getAppInstall());
target.setInstallApps(src.getInstallApps());
target.setAutoRotate(src.getAutoRotate());
target.setAutoBrightness(src.getAutoBrightness());
target.setEyeProtection(src.getEyeProtection());
target.setDarkMode(src.getDarkMode());
target.setSafeBoot(src.getSafeBoot());
target.setAdbUsbDebug(src.getAdbUsbDebug());
target.setMountPhysicalStorage(src.getMountPhysicalStorage());
target.setModifySystemTimeZone(src.getModifySystemTimeZone());
target.setToggleAirplaneMode(src.getToggleAirplaneMode());
target.setModifyMobileApn(src.getModifyMobileApn());
target.setUninstallApps(src.getUninstallApps());
target.setCamera(src.getCamera());
target.setUsbFileTransfer(src.getUsbFileTransfer());
target.setModifyLocationSwitch(src.getModifyLocationSwitch());
target.setBluetoothSharing(src.getBluetoothSharing());
target.setResetNetworkSettings(src.getResetNetworkSettings());
target.setAdjustGlobalVolume(src.getAdjustGlobalVolume());
target.setModifyScreenTimeout(src.getModifyScreenTimeout());
target.setManualAdjustTimeZone(src.getManualAdjustTimeZone());
target.setModifySystemLanguage(src.getModifySystemLanguage());
target.setManualAdjustBrightness(src.getManualAdjustBrightness());
}
}