From 692eb3d2a3164d23b5c88db7bf586b65d4693331 Mon Sep 17 00:00:00 2001 From: CrescentLeaf Date: Thu, 25 Sep 2025 14:18:50 +0800 Subject: [PATCH] =?UTF-8?q?chore:=20=E5=B0=87=E4=BB=A4=E7=89=8C=E6=AA=A2?= =?UTF-8?q?=E6=B8=AC=E5=87=BD=E6=95=B8=E7=A7=BB=E5=8B=95=E5=88=B0=20TokenM?= =?UTF-8?q?anager=20*=20=E9=80=99=E6=A8=A3=E6=89=8D=E5=8F=AB=20TokenManage?= =?UTF-8?q?r=20=E5=98=9BX?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- server/api/BaseApi.ts | 8 ++------ server/api/TokenManager.ts | 12 +++++++++++- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/server/api/BaseApi.ts b/server/api/BaseApi.ts index 06237de..412310f 100644 --- a/server/api/BaseApi.ts +++ b/server/api/BaseApi.ts @@ -3,6 +3,7 @@ import ApiManager from "./ApiManager.ts" import { CallMethod, ClientEvent } from './ApiDeclare.ts' import User from "../data/User.ts" import Token from "./Token.ts" +import TokenManager from './TokenManager.ts' import * as SocketIo from "socket.io" export default abstract class BaseApi { @@ -24,12 +25,7 @@ export default abstract class BaseApi { return false } checkToken(token: Token, deviceId: string) { - if (token.expired_time < Date.now()) return false - if (!token.author || !User.findById(token.author)) return false - if (deviceId != null) - if (token.device_id != deviceId) - return false - return true + return TokenManager.checkToken(token, deviceId) } registerEvent(name: CallMethod, func: EventCallbackFunction) { if (!name.startsWith(this.getName() + ".")) throw Error("注冊的事件應該與接口集合命名空間相匹配: " + name) diff --git a/server/api/TokenManager.ts b/server/api/TokenManager.ts index e80da3e..4785022 100644 --- a/server/api/TokenManager.ts +++ b/server/api/TokenManager.ts @@ -22,7 +22,6 @@ export default class TokenManager { ).toString('hex') } static decode(token: string) { - if (token == null) throw new Error('令牌為空!') try { return JSON.parse(crypto.createDecipheriv("aes-256-gcm", normalizeKey(config.aes_key), '01234567890123456').update( Buffer.from(token, 'hex') @@ -55,4 +54,15 @@ export default class TokenManager { return this.makeAuth(user) == tk.auth } + /** + * 嚴格檢驗令牌: 時間, 用戶, (設備 ID) + */ + static checkToken(token: Token, deviceId?: string) { + if (token.expired_time < Date.now()) return false + if (!token.author || !User.findById(token.author)) return false + if (deviceId != null) + if (token.device_id != deviceId) + return false + return true + } }