fix: callbacks cleanup and credential timestamp validation (#1669)

* fix(rpc): clean callbacks when sending failed

* chore: format

* fix(pty): handle ws message properly

* fix(webui-backend): unify credential timestamp validation

Store credential CreatedTime in seconds and validate expiry using the same unit. Keep backward compatibility for legacy millisecond timestamps.

* chore: format

* Revert "chore: format"

This reverts commit 6f2e9f1b53b55e8f4bf4a747ed7b05a0d6e4dbb4.

* fix: naming

Rename ONE_HOUR_SECONDS to MAX_CREDENTIAL_VALID_SECONDS for clearer intent. Simplify CreatedTime parsing by using Math.floor(Number(...)) and remove the legacy millisecond-to-second conversion branch. Update the time-difference check to use the new constant name.
This commit is contained in:
水化 authored and GitHub committed 2026-03-04 19:03:21 +08:00
1 parent 7b58681b2b
commit 79ac1052c6
4 files changed
+39 -10

No files matched your search

+14 -3
View File
@@ -67,6 +67,7 @@ export class MessageTransport implements RpcTransport {
resolve: (response: RpcResponse) => void; resolve: (response: RpcResponse) => void;
reject: (error: Error) => void; reject: (error: Error) => void;
}>(); }>();
private callbackHandler?: (callbackId: string, args: SerializedValue[]) => Promise<SerializedValue>; private callbackHandler?: (callbackId: string, args: SerializedValue[]) => Promise<SerializedValue>;
private sendMessage: (message: string) => void | Promise<void>; private sendMessage: (message: string) => void | Promise<void>;
@@ -113,15 +114,25 @@ export class MessageTransport implements RpcTransport {
} }
async send (request: RpcRequest): Promise<RpcResponse> { async send (request: RpcRequest): Promise<RpcResponse> {
return new Promise((resolve, reject) => { // eslint-disable-next-line no-async-promise-executor
this.pendingRequests.set(request.id, { resolve, reject }); return new Promise(async (resolve, _reject) => {
const id = request.id;
const reject = (error: any) => {
this.pendingRequests.delete(id);
_reject(error);
};
this.pendingRequests.set(id, { resolve, reject });
const message = JSON.stringify({ const message = JSON.stringify({
type: 'request', type: 'request',
request, request,
}); });
Promise.resolve(this.sendMessage(message)).catch(reject); try {
await this.sendMessage(message);
} catch (error) {
reject(error);
}
}); });
} }
@@ -3,6 +3,7 @@ import store from 'napcat-common/src/store';
import type { WebUiCredentialJson, WebUiCredentialInnerJson } from '@/napcat-webui-backend/src/types'; import type { WebUiCredentialJson, WebUiCredentialInnerJson } from '@/napcat-webui-backend/src/types';
export class AuthHelper { export class AuthHelper {
private static readonly secretKey = process.env['NAPCAT_WEBUI_JWT_SECRET_KEY'] || Math.random().toString(36).slice(2); private static readonly secretKey = process.env['NAPCAT_WEBUI_JWT_SECRET_KEY'] || Math.random().toString(36).slice(2);
private static readonly MAX_CREDENTIAL_VALID_SECONDS = 3600;
public static getSecretKey (): string { public static getSecretKey (): string {
return AuthHelper.secretKey; return AuthHelper.secretKey;
@@ -15,7 +16,8 @@ export class AuthHelper {
*/ */
public static signCredential (hash: string): WebUiCredentialJson { public static signCredential (hash: string): WebUiCredentialJson {
const innerJson: WebUiCredentialInnerJson = { const innerJson: WebUiCredentialInnerJson = {
CreatedTime: Date.now(), // 统一使用秒级时间戳,避免与校验逻辑出现单位不一致
CreatedTime: Math.floor(Date.now() / 1000),
HashEncoded: hash, HashEncoded: hash,
}; };
const jsonString = JSON.stringify(innerJson); const jsonString = JSON.stringify(innerJson);
@@ -59,10 +61,11 @@ export class AuthHelper {
return false; return false;
} }
const currentTime = Date.now() / 1000; const currentTimeSeconds = Math.floor(Date.now() / 1000);
const createdTime = credentialJson.Data.CreatedTime; const createdTimeSeconds = Math.floor(Number(credentialJson.Data.CreatedTime));
const timeDifference = currentTime - createdTime; const timeDifferenceSeconds = currentTimeSeconds - createdTimeSeconds;
return timeDifference <= 3600 && credentialJson.Data.HashEncoded === AuthHelper.generatePasswordHash(token); const isWithinOneHour = timeDifferenceSeconds >= 0 && timeDifferenceSeconds <= AuthHelper.MAX_CREDENTIAL_VALID_SECONDS;
return isWithinOneHour && credentialJson.Data.HashEncoded === AuthHelper.generatePasswordHash(token);
} }
/** /**
@@ -84,7 +84,13 @@ class TerminalManager {
ws.on('message', (data) => { ws.on('message', (data) => {
if (instance) { if (instance) {
const result = JSON.parse(data.toString()); let text: string;
if (Array.isArray(data)) {
text = Buffer.concat(data).toString();
} else {
text = data.toString();
}
const result = JSON.parse(text);
if (result.type === 'input') { if (result.type === 'input') {
instance.pty.write(result.data); instance.pty.write(result.data);
} }
+10 -1
View File
@@ -1,2 +1,11 @@
packages: packages:
- 'packages/*' - packages/*
onlyBuiltDependencies:
- '@heroui/shared-utils'
- '@homebridge/node-pty-prebuilt-multiarch'
- '@swc/core'
- esbuild
- sharp
- ttf2woff2
- unrs-resolver