From 2dcba633ba01a1a7dfaa558bfcbf1d5146a4f55e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Thu, 5 Mar 2026 15:38:36 +0800 Subject: [PATCH] Add configurable automatic time sync Add autoTimeSync (default: true) to the Napcat config and honor NAPCAT_DISABLE_TIME_SYNC=1 or autoTimeSync=false to disable automatic time synchronization. When enabled, time sync is attempted via getServerTime with errors logged; warning threshold for significant drift increased from 1s to 5s. Adds informational log when auto time sync is disabled. --- packages/napcat-core/helper/config.ts | 1 + packages/napcat-core/index.ts | 21 +++++++++++++-------- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/napcat-core/helper/config.ts b/packages/napcat-core/helper/config.ts index b1b323c9..e41c1684 100644 --- a/packages/napcat-core/helper/config.ts +++ b/packages/napcat-core/helper/config.ts @@ -23,6 +23,7 @@ export const NapcatConfigSchema = Type.Object({ packetBackend: Type.String({ default: 'auto' }), packetServer: Type.String({ default: '' }), o3HookMode: Type.Number({ default: 0 }), + autoTimeSync: Type.Boolean({ default: true }), bypass: Type.Optional(BypassOptionsSchema), }); diff --git a/packages/napcat-core/index.ts b/packages/napcat-core/index.ts index 7777e1ec..d7df1f45 100644 --- a/packages/napcat-core/index.ts +++ b/packages/napcat-core/index.ts @@ -176,15 +176,20 @@ export class NapCatCore { fs.mkdirSync(this.NapCatTempPath, { recursive: true }); } // 通过 getServerTime 全局 hook Date.now() 矫正本地时间偏差 - try { - const offsetMs = hookGlobalDateNow(() => this.context.session.getMSFService().getServerTime()); - if (Math.abs(offsetMs) > 1000) { - this.context.logger.logWarn(`[ServerTime] 本地时间与服务器时间偏差 ${(offsetMs / 1000).toFixed(1)}s,已自动矫正`); - } else { - this.context.logger.log(`[ServerTime] 时间同步完成,偏差 ${offsetMs}ms`); + // 可通过环境变量 NAPCAT_DISABLE_TIME_SYNC=1 或配置 autoTimeSync: false 禁用 + if (process.env['NAPCAT_DISABLE_TIME_SYNC'] === '1' || !this.configLoader.configData.autoTimeSync) { + this.context.logger.log('[ServerTime] 自动对时已禁用'); + } else { + try { + const offsetMs = hookGlobalDateNow(() => this.context.session.getMSFService().getServerTime()); + if (Math.abs(offsetMs) > 5000) { + this.context.logger.logWarn(`[ServerTime] 本地时间与服务器时间偏差 ${(offsetMs / 1000).toFixed(1)}s,已自动矫正`); + } else { + this.context.logger.log(`[ServerTime] 时间同步完成,偏差 ${offsetMs}ms`); + } + } catch (e) { + this.context.logger.logError('[ServerTime] 时间矫正失败', e); } - } catch (e) { - this.context.logger.logError('[ServerTime] 时间矫正失败', e); } // 遍历this.apis[i].initApi 如果存在该函数进行async 调用 for (const apiKey in this.apis) {