add auth check
This commit is contained in:
+39
-5
@@ -17,10 +17,38 @@
|
||||
| 方法 | 路径 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `POST` | `/` | 主业务 API |
|
||||
| `POST` | `/device` | ReinLoop 设备侧 API(license -> deviceToken) |
|
||||
| `POST` | `/upload/:token` | 根据上传凭证接收 multipart 文件 |
|
||||
| `GET` | `/files/:fileID` | 下载已存储文件 |
|
||||
| `GET` | `/downloads/:ticket` | 使用一次性临时下载票据获取文件 |
|
||||
| `GET` | `/files/:fileID` | 旧直链下载入口(已停用,固定返回 403) |
|
||||
| `GET` | `/health` | 服务存活检查 |
|
||||
|
||||
## 设备侧鉴权与分路由
|
||||
|
||||
`/device` 仅用于 ReinLoop 客户端,禁止使用 `adminToken`。
|
||||
|
||||
调用方式:
|
||||
|
||||
1. 先 `POST /device`,`type=deviceAuth`,字段 `licenseId`、`deviceId`。
|
||||
2. 服务端校验许可证状态(存在、未过期、未撤销、deviceId 匹配)后签发 `deviceToken`。
|
||||
3. ReinLoop 后续调用 `/device` 白名单接口时携带 `deviceToken`。
|
||||
|
||||
`deviceToken` 默认有效期由 `DEVICE_TOKEN_TTL_MS` 控制(默认 15 分钟)。
|
||||
|
||||
离线宽限由 ReinLoop 客户端控制,当前默认 `REINLOOP_LICENSE_OFFLINE_HOURS=100`(100 小时)。
|
||||
|
||||
## 下载安全调用链
|
||||
|
||||
统一链路为:业务 `POST /`(鉴权) -> 返回临时 URL -> `GET /downloads/:ticket`(一次性消费)。
|
||||
|
||||
安全校验点:
|
||||
|
||||
- `POST /`:按业务类型执行权限校验。
|
||||
- `GET /downloads/:ticket`:
|
||||
- 票据存在且未过期(`DOWNLOAD_URL_TTL_MS`,兼容旧环境变量 `DOWNLOAD_TOKEN_TTL_MS`)。
|
||||
- 票据仅可消费一次,成功下载或校验失败后均失效。
|
||||
- 下载请求来源 IP 必须与签发票据的 `POST` 请求来源 IP 一致。
|
||||
|
||||
## 设备心跳与组织
|
||||
|
||||
| type | 鉴权 | 请求字段 | 功能与响应要点 |
|
||||
@@ -51,13 +79,19 @@ Panel 应每 10 秒调用 `listOrganizations` 刷新在线状态,不应自行
|
||||
| `uploadDataFile` | 视目录而定 | `fileName`、`folder` | 签发通用两步上传凭证。目录为 `*/model_config` 时必须 Admin;其他既有 ReinLoop 数据上传保持兼容。 |
|
||||
| `issueModelUpload` | Admin | `deviceId`、`fileName`、可选 `modelName`、`overwrite` | `fileName` 是本地原始文件名;传入 `modelName` 时以该名称存储和识别模型,并保留 `originalFileName`。同名模型已存在时返回 `conflict: true`;仅 `overwrite: true` 可签发覆盖凭证。 |
|
||||
| `listModels` | 无 | `folder` | 返回 `files` 当前模型名数组和 `fileList` 元数据数组,最多 100 条;每条同时包含 `fileName` 和 `originalFileName`。 |
|
||||
| `downloadModel` | 视文件而定 | `fileID` | 模型保持兼容;非模型文件要求 Admin 并返回短期签名下载 URL。 |
|
||||
| `downloadModel` | Admin | `fileID` | 返回一次性临时下载 URL(`/downloads/:ticket`)。 |
|
||||
| `deleteFile` | Admin | `fileID`,或 `folder` 与 `fileName` | 删除文件及元数据;同名文件不唯一时必须使用 `fileID`。 |
|
||||
| `deleteModel` | Admin | 同 `deleteFile` | 模型删除的明确管理端别名。 |
|
||||
|
||||
上传分两步:先调用 `uploadDataFile` 或 `issueModelUpload`,再将文件作为 `multipart/form-data` 的 `file` 字段提交到响应中的 `uploadMetadata.url`。上传成功返回 HTTP `204`;响应中的 `fileID` 可用于下载和删除。
|
||||
模型重命名不会修改文件格式,因此 `modelName` 与原始 `fileName` 的扩展名必须一致。未传 `modelName` 时两者相同,旧客户端行为不变。
|
||||
|
||||
设备侧(`/device`)模型访问约束:
|
||||
|
||||
- `listModels` 固定返回当前 `deviceId/model_config` 目录。
|
||||
- `downloadModel` 仅允许下载当前 `deviceId/model_config` 下文件。
|
||||
- 设备侧不允许模型上传与删除。
|
||||
|
||||
上传到 `<deviceId>/ind_data` 的 `.csv`、`.json` 会自动进入 Panel inbox。
|
||||
|
||||
## 配置发布与读取
|
||||
@@ -67,7 +101,7 @@ Panel 应每 10 秒调用 `listOrganizations` 刷新在线状态,不应自行
|
||||
| `publishIdentificationConfig` | Admin | `deviceId`、`parameters` | 校验辨识参数并为 `<deviceId>/identification_config/identification_config.csv` 签发上传凭证。 |
|
||||
| `getIdentificationConfig` | 无 | `deviceId` | 返回该设备辨识 CSV 的 `fileID` 和 `url`。 |
|
||||
| `publishVolumeConfig` | Admin | `parameters` | 校验容积参数并签发 `volume_config.json` 上传凭证。上传完成后更新功能参数记录。 |
|
||||
| `getVolumeConfigFile` | 无 | 无 | 返回已发布容积 JSON 的 `fileID`、`cloudPath`、`url`。 |
|
||||
| `getVolumeConfigFile` | Admin | `deviceId` | 返回指定设备已发布容积 JSON 的 `fileID`、`cloudPath`、`url`。 |
|
||||
| `getFunctionConfig` | 无 | `configType: "volume"` | 返回已发布容积参数的 `parameters`、`version`、`updateTime`。 |
|
||||
|
||||
发布接口仅签发上传凭证;客户端完成二步上传后,读取接口才会返回新文件或参数。
|
||||
@@ -83,7 +117,7 @@ Panel 应每 10 秒调用 `listOrganizations` 刷新在线状态,不应自行
|
||||
| `getPendingPanelFile` | Admin | `deviceId` | 获取指定设备下一条待处理 CSV/JSON;无数据时 `pending: false`,有数据时返回文件信息和 `url`。 |
|
||||
| `ackPanelFile` | Admin | `deviceId`、`fileID` | Panel 处理完成后确认,移除 inbox 项并标记历史记录为 `processed`,不立即删除文件。 |
|
||||
| `listIdentificationFiles` | Admin | `deviceId`、可选 `mediaType`、`status`、`page`、`pageSize` | 分页返回设备的辨识 CSV/JSON 暂存历史。 |
|
||||
| `getIdentificationFileDownload` | Admin | `fileID` | 返回原始辨识文件的短期签名下载 URL。 |
|
||||
| `getIdentificationFileDownload` | Admin | `fileID` | 返回原始辨识文件的一次性临时下载 URL。 |
|
||||
| `deleteIdentificationFile` | Admin | `fileID` | 显式删除辨识文件、历史记录及待处理消息。 |
|
||||
|
||||
CSV 辨识文件须先以同名 `runId` 调用 `registerIdentificationResult`,才会出现在 `getPendingPanelFile`;初始行程 JSON 可直接获取。
|
||||
@@ -97,7 +131,7 @@ CSV 辨识文件须先以同名 `runId` 调用 `registerIdentificationResult`,
|
||||
| `createVolumeConfigRequest` | 无 | `deviceId` | ReinLoop 创建一次性上传请求,返回 `requestId`、`createdAtMs`、`expiresAtMs`。同设备旧请求会被替换。 |
|
||||
| `getPendingVolumeConfigRequest` | 无 | `deviceId` | 查询是否存在待上传请求,返回 `pending` 和请求时间信息。 |
|
||||
| `submitVolumeConfigFile` | 无 | `deviceId`、`requestId`、`fileID`、可选 `fileName` | 将已上传到 `<deviceId>/volume_config_requests/<requestId>/` 的文件绑定至请求。 |
|
||||
| `getVolumeConfigRequest` | 无 | `deviceId`、`requestId` | 轮询配置是否就绪,返回 `ready`、`expired`;就绪时包含下载 `url`。 |
|
||||
| `getVolumeConfigRequest` | 无 | `deviceId`、`requestId` | 轮询配置是否就绪,返回 `ready`、`expired`;就绪时包含一次性临时下载 `url`。 |
|
||||
| `ackVolumeConfigRequest` | 无 | `deviceId`、`requestId` | ReinLoop 下载完成后确认,清理请求及关联文件。 |
|
||||
|
||||
请求有效期由 `VOLUME_REQUEST_TTL_MS` 控制,默认 300000 毫秒(5 分钟)。
|
||||
|
||||
+175
-42
@@ -1,12 +1,13 @@
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const { randomUUID, constants, createHmac, timingSafeEqual, verify } = require("node:crypto");
|
||||
const { randomUUID, constants, verify } = require("node:crypto");
|
||||
const express = require("express");
|
||||
const multer = require("multer");
|
||||
|
||||
const BASE_FOLDER = "ReinLoop_GUI";
|
||||
const VOLUME_REQUEST_TTL_MS = Number(process.env.VOLUME_REQUEST_TTL_MS || 300000);
|
||||
const DOWNLOAD_TOKEN_TTL_MS = Number(process.env.DOWNLOAD_TOKEN_TTL_MS || 300000);
|
||||
const DOWNLOAD_URL_TTL_MS = Number(process.env.DOWNLOAD_URL_TTL_MS || process.env.DOWNLOAD_TOKEN_TTL_MS || 300000);
|
||||
const DEVICE_TOKEN_TTL_MS = Number(process.env.DEVICE_TOKEN_TTL_MS || 15 * 60 * 1000);
|
||||
const IDENTIFICATION_RETENTION_MS = Number(process.env.IDENTIFICATION_RETENTION_MS || 30 * 24 * 60 * 60 * 1000);
|
||||
const DEVICE_HEARTBEAT_TTL_MS = 30_000;
|
||||
const CONFIG_SCHEMAS = {
|
||||
@@ -161,6 +162,8 @@ function createApp({
|
||||
const app = express();
|
||||
const upload = multer({ storage: multer.memoryStorage(), limits: { fileSize: 100 * 1024 * 1024 } });
|
||||
const pendingUploads = new Map();
|
||||
const pendingDownloads = new Map();
|
||||
const pendingDeviceTokens = new Map();
|
||||
|
||||
app.disable("x-powered-by");
|
||||
app.use(express.json({ limit: "2mb" }));
|
||||
@@ -200,23 +203,68 @@ function createApp({
|
||||
};
|
||||
}
|
||||
|
||||
function signDownload(fileID, expiresAtMs) {
|
||||
return createHmac("sha256", adminToken).update(`${fileID}\n${expiresAtMs}`).digest("hex");
|
||||
function requestIp(req) {
|
||||
return String(req.ip || req.socket?.remoteAddress || "").trim();
|
||||
}
|
||||
|
||||
function downloadUrl(req, fileID) {
|
||||
const baseUrl = `${publicBaseUrl(req)}/files/${encodeURIComponent(fileID)}`;
|
||||
if (fileID.startsWith("model://")) return baseUrl;
|
||||
const expires = Date.now() + DOWNLOAD_TOKEN_TTL_MS;
|
||||
return `${baseUrl}?expires=${expires}&token=${signDownload(fileID, expires)}`;
|
||||
function issueDownloadUrl(req, fileID) {
|
||||
const ticket = randomUUID().replace(/-/g, "");
|
||||
pendingDownloads.set(ticket, {
|
||||
fileID,
|
||||
requestIp: requestIp(req),
|
||||
expiresAtMs: Date.now() + DOWNLOAD_URL_TTL_MS
|
||||
});
|
||||
return `${publicBaseUrl(req)}/downloads/${ticket}`;
|
||||
}
|
||||
|
||||
function hasValidDownloadToken(req, fileID) {
|
||||
const expires = Number(req.query.expires);
|
||||
const token = String(req.query.token || "");
|
||||
if (!Number.isSafeInteger(expires) || expires < Date.now() || !/^[0-9a-f]{64}$/.test(token)) return false;
|
||||
const expected = signDownload(fileID, expires);
|
||||
return timingSafeEqual(Buffer.from(token, "hex"), Buffer.from(expected, "hex"));
|
||||
function consumeDownloadTicket(req, ticket) {
|
||||
const request = pendingDownloads.get(ticket);
|
||||
if (!request) return { ok: false, errMsg: "下载链接无效或已失效" };
|
||||
pendingDownloads.delete(ticket);
|
||||
if (request.expiresAtMs < Date.now()) return { ok: false, errMsg: "下载链接已过期" };
|
||||
if (!request.requestIp || request.requestIp !== requestIp(req)) {
|
||||
return { ok: false, errMsg: "下载请求来源IP不匹配" };
|
||||
}
|
||||
return { ok: true, fileID: request.fileID };
|
||||
}
|
||||
|
||||
function verifyLicenseRecord(record, deviceId) {
|
||||
if (!record) return { success: false, valid: false, status: "not_found" };
|
||||
if (deviceId && deviceId !== record.deviceId) {
|
||||
return { success: true, valid: false, status: "device_mismatch", licenseId: record.licenseId };
|
||||
}
|
||||
if (new Date(record.expiryAt || parseLicenseTimestamp(record.expiry, "expiry")) <= new Date()) {
|
||||
return { success: true, valid: false, status: "expired", licenseId: record.licenseId };
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
valid: record.status === "active",
|
||||
status: record.status,
|
||||
licenseId: record.licenseId
|
||||
};
|
||||
}
|
||||
|
||||
function issueDeviceToken({ deviceId, licenseId }) {
|
||||
const token = randomUUID().replace(/-/g, "");
|
||||
const expiresAtMs = Date.now() + DEVICE_TOKEN_TTL_MS;
|
||||
pendingDeviceTokens.set(token, { deviceId, licenseId, expiresAtMs });
|
||||
return { token, expiresAtMs };
|
||||
}
|
||||
|
||||
function consumeDeviceContext(event) {
|
||||
const deviceToken = String(event.deviceToken || "").trim();
|
||||
if (!deviceToken) {
|
||||
return { ok: false, errCode: "DEVICE_TOKEN_REQUIRED", errMsg: "缺少 deviceToken" };
|
||||
}
|
||||
const session = pendingDeviceTokens.get(deviceToken);
|
||||
if (!session) {
|
||||
return { ok: false, errCode: "DEVICE_TOKEN_INVALID", errMsg: "deviceToken 无效" };
|
||||
}
|
||||
if (session.expiresAtMs <= Date.now()) {
|
||||
pendingDeviceTokens.delete(deviceToken);
|
||||
return { ok: false, errCode: "DEVICE_TOKEN_EXPIRED", errMsg: "deviceToken 已过期" };
|
||||
}
|
||||
return { ok: true, ...session };
|
||||
}
|
||||
|
||||
//config test-----------------------------------
|
||||
@@ -540,17 +588,8 @@ function createApp({
|
||||
case "validateLicense": {
|
||||
const database = await store.read();
|
||||
const record = database.licenses.find((item) => item.licenseId === event.licenseId);
|
||||
if (!record) return { success: true, valid: false, status: "not_found" };
|
||||
if (event.deviceId && normalizeDeviceId(event.deviceId) !== record.deviceId) {
|
||||
return { success: true, valid: false, status: "device_mismatch", licenseId: record.licenseId };
|
||||
}
|
||||
if (new Date(record.expiryAt || parseLicenseTimestamp(record.expiry, "expiry")) <= new Date()) {
|
||||
return { success: true, valid: false, status: "expired", licenseId: record.licenseId };
|
||||
}
|
||||
return {
|
||||
success: true, valid: record.status === "active",
|
||||
status: record.status, licenseId: record.licenseId
|
||||
};
|
||||
const deviceId = event.deviceId ? normalizeDeviceId(event.deviceId) : null;
|
||||
return verifyLicenseRecord(record, deviceId);
|
||||
}
|
||||
case "uploadDataFile":
|
||||
if (normalizeRelativePath(event.folder, "data_record").endsWith("/model_config")) {
|
||||
@@ -584,13 +623,11 @@ function createApp({
|
||||
const database = await store.read();
|
||||
const record = database.fileRecords.find((item) => item.fileID === event.fileID);
|
||||
if (!record || !store.resolveStoredFile(record.fileID)) return { success: false, errMsg: "文件不存在" };
|
||||
if (!record.fileID.startsWith("model://")) {
|
||||
const authError = requireAdmin(event);
|
||||
if (authError) return { success: false, errMsg: authError };
|
||||
}
|
||||
const authError = requireAdmin(event);
|
||||
if (authError) return { success: false, errMsg: authError };
|
||||
return {
|
||||
success: true,
|
||||
url: downloadUrl(req, record.fileID),
|
||||
url: issueDownloadUrl(req, record.fileID),
|
||||
fileName: record.fileName,
|
||||
originalFileName: record.originalFileName || record.fileName
|
||||
};
|
||||
@@ -651,7 +688,7 @@ function createApp({
|
||||
if (!record) return { success: true, found: false, deviceId };
|
||||
return {
|
||||
success: true, found: true, deviceId, fileID: record.fileID,
|
||||
fileName: record.fileName, url: downloadUrl(req, record.fileID),
|
||||
fileName: record.fileName, url: issueDownloadUrl(req, record.fileID),
|
||||
updatedAtMs: config.updatedAtMs, requestId: config.requestId
|
||||
};
|
||||
}
|
||||
@@ -667,7 +704,7 @@ function createApp({
|
||||
const record = database.fileRecords.find((item) => item.folder === `${deviceId}/identification_config` && item.fileName === "identification_config.csv");
|
||||
if (!record) return { success: false, errMsg: "服务器尚未配置辨识参数" };
|
||||
logConfigRead({ configType: "identification", deviceId, record });
|
||||
return { success: true, fileName: record.fileName, fileID: record.fileID, cloudPath: record.cloudPath, url: downloadUrl(req, record.fileID) };
|
||||
return { success: true, fileName: record.fileName, fileID: record.fileID, cloudPath: record.cloudPath, url: issueDownloadUrl(req, record.fileID) };
|
||||
}
|
||||
case "getPendingPanelFile": {
|
||||
const authError = requireAdmin(event);
|
||||
@@ -689,7 +726,7 @@ function createApp({
|
||||
fileName: message.fileName,
|
||||
mediaType: message.mediaType,
|
||||
uploadTime: message.uploadTime,
|
||||
url: downloadUrl(req, message.fileID)
|
||||
url: issueDownloadUrl(req, message.fileID)
|
||||
};
|
||||
}
|
||||
case "getPendingPanelNotification": {
|
||||
@@ -812,7 +849,7 @@ function createApp({
|
||||
fileName: record.fileName,
|
||||
uploadTime: record.uploadTime,
|
||||
size: record.size,
|
||||
url: downloadUrl(req, record.fileID)
|
||||
url: issueDownloadUrl(req, record.fileID)
|
||||
};
|
||||
}
|
||||
case "deleteControlFile": {
|
||||
@@ -844,7 +881,7 @@ function createApp({
|
||||
fileID: fileRecord.fileID,
|
||||
fileName: fileRecord.fileName,
|
||||
mediaType: historyRecord.mediaType,
|
||||
url: downloadUrl(req, fileRecord.fileID)
|
||||
url: issueDownloadUrl(req, fileRecord.fileID)
|
||||
};
|
||||
}
|
||||
case "deleteIdentificationFile": {
|
||||
@@ -969,7 +1006,7 @@ function createApp({
|
||||
const fileRecord = database.fileRecords.find((item) => item.fileID === record.configFileID);
|
||||
if (!fileRecord) return { success: false, errMsg: "容积配置文件记录不存在" };
|
||||
logConfigRead({ configType: "volume", deviceId, requestId: record.requestId, record: fileRecord });
|
||||
return { success: true, ready: true, expired: false, requestId: record.requestId, fileName: record.configFileName, fileID: fileRecord.fileID, cloudPath: fileRecord.cloudPath, uploadedAtMs: record.uploadedAtMs, url: downloadUrl(req, record.configFileID) };
|
||||
return { success: true, ready: true, expired: false, requestId: record.requestId, fileName: record.configFileName, fileID: fileRecord.fileID, cloudPath: fileRecord.cloudPath, uploadedAtMs: record.uploadedAtMs, url: issueDownloadUrl(req, record.configFileID) };
|
||||
}
|
||||
case "ackVolumeConfigRequest": {
|
||||
const deviceId = normalizeDeviceId(event.deviceId);
|
||||
@@ -989,6 +1026,88 @@ function createApp({
|
||||
}
|
||||
}
|
||||
|
||||
async function dispatchDevice(event, req) {
|
||||
if (event.type === "deviceAuth") {
|
||||
const licenseId = String(event.licenseId || "").trim();
|
||||
if (!licenseId) return { success: false, errCode: "LICENSE_ID_REQUIRED", errMsg: "缺少 licenseId" };
|
||||
const deviceId = normalizeDeviceId(event.deviceId);
|
||||
const database = await store.read();
|
||||
const record = database.licenses.find((item) => item.licenseId === licenseId);
|
||||
const validation = verifyLicenseRecord(record, deviceId);
|
||||
if (!validation.valid) {
|
||||
const errCodeMap = {
|
||||
not_found: "LICENSE_NOT_FOUND",
|
||||
device_mismatch: "DEVICE_ID_MISMATCH",
|
||||
expired: "LICENSE_EXPIRED",
|
||||
revoked: "LICENSE_REVOKED"
|
||||
};
|
||||
return {
|
||||
success: false,
|
||||
errCode: errCodeMap[validation.status] || "LICENSE_INVALID",
|
||||
errMsg: `许可证不可用: ${validation.status}`
|
||||
};
|
||||
}
|
||||
const issued = issueDeviceToken({ deviceId, licenseId });
|
||||
return {
|
||||
success: true,
|
||||
deviceId,
|
||||
licenseId,
|
||||
deviceToken: issued.token,
|
||||
expiresAtMs: issued.expiresAtMs
|
||||
};
|
||||
}
|
||||
|
||||
const context = consumeDeviceContext(event);
|
||||
if (!context.ok) return { success: false, errCode: context.errCode, errMsg: context.errMsg };
|
||||
const deviceId = context.deviceId;
|
||||
|
||||
switch (event.type) {
|
||||
case "deviceHeartbeat":
|
||||
case "registerIdentificationResult":
|
||||
case "getIdentificationFeedback":
|
||||
case "ackIdentificationFeedback":
|
||||
case "createVolumeConfigRequest":
|
||||
case "getPendingVolumeConfigRequest":
|
||||
case "submitVolumeConfigFile":
|
||||
case "getVolumeConfigRequest":
|
||||
case "ackVolumeConfigRequest":
|
||||
case "getIdentificationConfig":
|
||||
return dispatch({ ...event, deviceId }, req);
|
||||
case "uploadDataFile": {
|
||||
const folder = normalizeRelativePath(event.folder, "data_record");
|
||||
const devicePrefix = `${deviceId}/`;
|
||||
if (!folder.startsWith(devicePrefix)) {
|
||||
return { success: false, errMsg: "设备接口仅允许访问当前 deviceId 目录" };
|
||||
}
|
||||
if (folder.endsWith("/model_config")) {
|
||||
return { success: false, errMsg: "设备接口不允许上传模型" };
|
||||
}
|
||||
return dispatch({ ...event, folder }, req);
|
||||
}
|
||||
case "listModels": {
|
||||
const folder = `${deviceId}/model_config`;
|
||||
return dispatch({ ...event, folder }, req);
|
||||
}
|
||||
case "downloadModel": {
|
||||
if (!event.fileID) return { success: false, errMsg: "缺少 fileID" };
|
||||
const database = await store.read();
|
||||
const record = database.fileRecords.find((item) => item.fileID === event.fileID);
|
||||
if (!record || !store.resolveStoredFile(record.fileID)) return { success: false, errMsg: "文件不存在" };
|
||||
if (record.folder !== `${deviceId}/model_config`) {
|
||||
return { success: false, errMsg: "设备接口无权下载该模型" };
|
||||
}
|
||||
return {
|
||||
success: true,
|
||||
url: issueDownloadUrl(req, record.fileID),
|
||||
fileName: record.fileName,
|
||||
originalFileName: record.originalFileName || record.fileName
|
||||
};
|
||||
}
|
||||
default:
|
||||
return { success: false, errMsg: "无效的 type 字段" };
|
||||
}
|
||||
}
|
||||
|
||||
app.get("/health", (req, res) => res.json({ success: true, service: "reinloop-server" }));
|
||||
|
||||
app.post("/upload/:token", upload.single("file"), async (req, res, next) => {
|
||||
@@ -1085,12 +1204,13 @@ function createApp({
|
||||
}
|
||||
});
|
||||
|
||||
app.get("/files/:fileID", async (req, res, next) => {
|
||||
app.get("/downloads/:ticket", async (req, res, next) => {
|
||||
try {
|
||||
const fileID = decodeURIComponent(req.params.fileID);
|
||||
if (!fileID.startsWith("model://") && !hasValidDownloadToken(req, fileID)) {
|
||||
return res.status(403).json({ success: false, errMsg: "下载凭证无效或已过期" });
|
||||
}
|
||||
const ticket = String(req.params.ticket || "").trim();
|
||||
if (!ticket) return res.status(403).json({ success: false, errMsg: "下载链接无效或已失效" });
|
||||
const consumed = consumeDownloadTicket(req, ticket);
|
||||
if (!consumed.ok) return res.status(403).json({ success: false, errMsg: consumed.errMsg });
|
||||
const fileID = consumed.fileID;
|
||||
const database = await store.read();
|
||||
const record = database.fileRecords.find((item) => item.fileID === fileID);
|
||||
const filePath = record && store.resolveStoredFile(fileID);
|
||||
@@ -1103,6 +1223,10 @@ function createApp({
|
||||
}
|
||||
});
|
||||
|
||||
app.get("/files/:fileID", (req, res) => {
|
||||
res.status(403).json({ success: false, errMsg: "旧下载链接已停用,请先通过 API 获取临时下载链接" });
|
||||
});
|
||||
|
||||
const apiHandler = async (req, res) => {
|
||||
try {
|
||||
res.json(await dispatch(normalizeEventCompat(req.body || {}), req));
|
||||
@@ -1112,6 +1236,15 @@ function createApp({
|
||||
};
|
||||
app.post("/", apiHandler);
|
||||
|
||||
const deviceApiHandler = async (req, res) => {
|
||||
try {
|
||||
res.json(await dispatchDevice(normalizeEventCompat(req.body || {}), req));
|
||||
} catch (error) {
|
||||
res.status(400).json({ success: false, errMsg: error.message });
|
||||
}
|
||||
};
|
||||
app.post("/device", deviceApiHandler);
|
||||
|
||||
app.use((error, req, res, next) => {
|
||||
console.error(error);
|
||||
res.status(500).json({ success: false, errMsg: "服务器内部错误" });
|
||||
|
||||
@@ -121,6 +121,7 @@ test("existing two-step client flow uploads, lists, and downloads a file", async
|
||||
});
|
||||
const downloaded = await fetch(download.url);
|
||||
assert.equal(await downloaded.text(), "time,pressure\n0,10\n");
|
||||
assert.equal((await fetch(download.url)).status, 403);
|
||||
});
|
||||
|
||||
test("admin lists, downloads, and deletes only the selected device control data", async () => {
|
||||
@@ -159,8 +160,9 @@ test("admin lists, downloads, and deletes only the selected device control data"
|
||||
});
|
||||
assert.equal(download.success, true);
|
||||
assert.equal(download.size, Buffer.byteLength('{"parts":1}'));
|
||||
assert.match(download.url, /expires=.*token=/);
|
||||
assert.match(download.url, /\/downloads\//);
|
||||
assert.equal(await (await fetch(download.url)).text(), '{"parts":1}');
|
||||
assert.equal((await fetch(download.url)).status, 403);
|
||||
|
||||
const forbiddenDelete = await post({
|
||||
type: "deleteControlFile", fileID: "model://control-co/line-1/controller.bin", adminToken: "test-token"
|
||||
|
||||
Reference in New Issue
Block a user