From 36ae7bf923dac7b180033068005e18862510e110 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: Fri, 6 Mar 2026 09:46:12 +0800 Subject: [PATCH] Replace AJV with TypeBox validation Migrate schema validation from AJV to @sinclair/typebox across the monorepo. Key changes: - Core validation: ConfigBase now uses TypeCompiler/Value (TypeBox) for compile/defaults/coercion and replaces Ajv usage. - OneBot & Protocol: loadConfig functions and related config loaders updated to use Value.Default/Convert and TypeCompiler.Compile with improved error reporting. - OneBot action validation: OneBotAction now compiles TypeBox schemas, applies defaults/conversions and returns TypeBox errors. - Web UI backend: use TypeBox Value/TypeCompiler to fetch and validate defaults for Napcat/Web UI configs. - Types/scripts: removed AJV type shims and adjusted post-build script to stop special-casing AJV types. - Dependencies: removed ajv from several package.json files and added/normalized @sinclair/typebox usage; updated pnpm-lock accordingly. - Tests/tools: added schema validation test utilities and tests (packages/napcat-onebot/test_schema.ts and packages/napcat-test/schema.test.ts) to validate schema compilation, coercion, and defaults. This change standardizes on TypeBox for runtime schema compilation, default population and type coercion, simplifying validation logic and improving default handling across packages. --- packages/napcat-common/package.json | 1 - packages/napcat-core/helper/config-base.ts | 32 +++-- packages/napcat-core/helper/config.ts | 11 +- packages/napcat-core/package.json | 15 +-- packages/napcat-onebot/action/OneBotAction.ts | 26 ++-- packages/napcat-onebot/config/config.ts | 16 ++- packages/napcat-onebot/config/index.ts | 4 +- packages/napcat-onebot/package.json | 23 ++-- packages/napcat-onebot/test_schema.ts | 61 +++++++++ packages/napcat-protobuf/NapProto.ts | 122 +++++++++--------- packages/napcat-protocol/config/config.ts | 16 ++- packages/napcat-protocol/package.json | 5 +- packages/napcat-test/package.json | 6 +- packages/napcat-test/schema.test.ts | 117 +++++++++++++++++ packages/napcat-types/external-shims.d.ts | 27 ---- packages/napcat-types/scripts/post-build.mjs | 42 +----- packages/napcat-webui-backend/package.json | 1 - .../src/api/NapCatConfig.ts | 7 +- .../napcat-webui-backend/src/helper/config.ts | 13 +- .../napcat-webui-backend/src/onebot/config.ts | 16 ++- pnpm-lock.yaml | 54 ++------ 21 files changed, 370 insertions(+), 245 deletions(-) create mode 100644 packages/napcat-onebot/test_schema.ts create mode 100644 packages/napcat-test/schema.test.ts diff --git a/packages/napcat-common/package.json b/packages/napcat-common/package.json index ddbf1184d..6ec372826 100644 --- a/packages/napcat-common/package.json +++ b/packages/napcat-common/package.json @@ -16,7 +16,6 @@ } }, "dependencies": { - "ajv": "^8.13.0", "file-type": "^21.0.0" }, "devDependencies": { diff --git a/packages/napcat-core/helper/config-base.ts b/packages/napcat-core/helper/config-base.ts index 55671a048..4f5a0a62e 100644 --- a/packages/napcat-core/helper/config-base.ts +++ b/packages/napcat-core/helper/config-base.ts @@ -2,22 +2,24 @@ import path from 'node:path'; import fs from 'node:fs'; import type { NapCatCore } from '@/napcat-core'; import json5 from 'json5'; -import Ajv, { AnySchema, ValidateFunction } from 'ajv'; +import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler'; +import { Value } from '@sinclair/typebox/value'; +import { TSchema } from '@sinclair/typebox'; export abstract class ConfigBase { name: string; core: NapCatCore; configPath: string; configData: T = {} as T; - ajv: Ajv; - validate: ValidateFunction; + configSchema: TSchema; + validate: TypeCheck; - protected constructor (name: string, core: NapCatCore, configPath: string, ConfigSchema: AnySchema) { + protected constructor (name: string, core: NapCatCore, configPath: string, ConfigSchema: TSchema) { this.name = name; this.core = core; this.configPath = configPath; - this.ajv = new Ajv({ useDefaults: true, coerceTypes: true }); - this.validate = this.ajv.compile(ConfigSchema); + this.configSchema = ConfigSchema; + this.validate = TypeCompiler.Compile(ConfigSchema); fs.mkdirSync(this.configPath, { recursive: true }); this.read(); } @@ -43,8 +45,13 @@ export abstract class ConfigBase { private loadConfig (configPath: string): T { try { const newConfigData = json5.parse(fs.readFileSync(configPath, 'utf-8')); - this.validate(newConfigData); - this.configData = newConfigData; + let data: unknown = newConfigData; + data = Value.Default(this.configSchema, data); + data = Value.Convert(this.configSchema, data); + if (!this.validate.Check(data)) { + throw new Error([...this.validate.Errors(data)].map(e => e.message).join(', ')); + } + this.configData = data as T; this.core.context.logger.logDebug(`[Core] [Config] 配置文件${configPath}加载`, this.configData); return this.configData; } catch (e: unknown) { @@ -55,8 +62,13 @@ export abstract class ConfigBase { save (newConfigData: T = this.configData): void { const configPath = this.getConfigPath(this.core.selfInfo.uin); - this.validate(newConfigData); - this.configData = newConfigData; + let data: unknown = newConfigData; + data = Value.Default(this.configSchema, data); + data = Value.Convert(this.configSchema, data); + if (!this.validate.Check(data)) { + throw new Error([...this.validate.Errors(data)].map(e => e.message).join(', ')); + } + this.configData = data as T; try { fs.writeFileSync(configPath, JSON.stringify(this.configData, null, 2)); } catch (e: unknown) { diff --git a/packages/napcat-core/helper/config.ts b/packages/napcat-core/helper/config.ts index e41c1684e..741093bb2 100644 --- a/packages/napcat-core/helper/config.ts +++ b/packages/napcat-core/helper/config.ts @@ -1,7 +1,9 @@ import { ConfigBase } from '@/napcat-core/helper/config-base'; import { NapCatCore } from '@/napcat-core/index'; import { Type, Static } from '@sinclair/typebox'; -import Ajv, { AnySchema } from 'ajv'; + +import { Value } from '@sinclair/typebox/value'; +import { TSchema } from '@sinclair/typebox'; import path from 'node:path'; import fs from 'node:fs'; import json5 from 'json5'; @@ -34,8 +36,6 @@ export type NapcatConfig = Static; * 用于登录前(无 NapCatCore 实例时)的早期配置读取 */ export function loadNapcatConfig (configPath: string): NapcatConfig { - const ajv = new Ajv({ useDefaults: true, coerceTypes: true }); - const validate = ajv.compile(NapcatConfigSchema); let data: Record = {}; try { const configFile = path.join(configPath, 'napcat.json'); @@ -45,12 +45,13 @@ export function loadNapcatConfig (configPath: string): NapcatConfig { } catch { // 读取失败时使用 schema 默认值 } - validate(data); + data = Value.Default(NapcatConfigSchema, data) as Record; + data = Value.Convert(NapcatConfigSchema, data) as Record; return data as NapcatConfig; } export class NapCatConfigLoader extends ConfigBase { - constructor (core: NapCatCore, configPath: string, schema: AnySchema) { + constructor (core: NapCatCore, configPath: string, schema: TSchema) { super('napcat', core, configPath, schema); } } diff --git a/packages/napcat-core/package.json b/packages/napcat-core/package.json index 92031d5b1..fb0d05720 100644 --- a/packages/napcat-core/package.json +++ b/packages/napcat-core/package.json @@ -16,19 +16,18 @@ } }, "dependencies": { - "winston": "^3.17.0", - "json5": "^2.2.3", - "inversify": "^7.10.4", - "reflect-metadata": "^0.2.2", "@protobuf-ts/runtime": "^2.11.1", - "ajv": "^8.13.0", "@sinclair/typebox": "^0.34.38", - "file-type": "^21.0.0", "compressing": "^1.10.1", - "napcat-image-size": "workspace:*", + "file-type": "^21.0.0", + "inversify": "^7.10.4", + "json5": "^2.2.3", "napcat-common": "workspace:*", "napcat-database": "workspace:*", - "napcat-protobuf": "workspace:*" + "napcat-image-size": "workspace:*", + "napcat-protobuf": "workspace:*", + "reflect-metadata": "^0.2.2", + "winston": "^3.17.0" }, "devDependencies": { "@types/node": "^22.0.1" diff --git a/packages/napcat-onebot/action/OneBotAction.ts b/packages/napcat-onebot/action/OneBotAction.ts index 75b6d0ed3..e71838a30 100644 --- a/packages/napcat-onebot/action/OneBotAction.ts +++ b/packages/napcat-onebot/action/OneBotAction.ts @@ -1,5 +1,6 @@ import { ActionName, BaseCheckResult } from './router'; -import Ajv, { ErrorObject, ValidateFunction } from 'ajv'; +import { TypeCompiler, TypeCheck } from '@sinclair/typebox/compiler'; +import { Value } from '@sinclair/typebox/value'; import { NapCatCore } from 'napcat-core'; import { NapCatOneBot11Adapter, OB11Return } from '@/napcat-onebot/index'; import { NetworkAdapterConfig } from '../config/config'; @@ -46,7 +47,7 @@ export abstract class OneBotRequestToolkit { export abstract class OneBotAction { actionName: typeof ActionName[keyof typeof ActionName] = ActionName.Unknown; core: NapCatCore; - private validate?: ValidateFunction = undefined; + private validate?: TypeCheck = undefined; payloadSchema?: TSchema = undefined; returnSchema?: TSchema = undefined; payloadExample?: unknown = undefined; @@ -64,15 +65,24 @@ export abstract class OneBotAction { } protected async check (payload: PayloadType): Promise { - if (this.payloadSchema) { - this.validate = new Ajv({ allowUnionTypes: true, useDefaults: true, coerceTypes: true }).compile(this.payloadSchema); + if (!this.payloadSchema) return { valid: true }; + try { + this.validate = TypeCompiler.Compile(this.payloadSchema); + let data = payload; + data = Value.Default(this.payloadSchema, data) as PayloadType; + data = Value.Convert(this.payloadSchema, data) as PayloadType; + if (typeof payload === 'object' && payload !== null && data !== null) { + Object.assign(payload, data); + } + } catch (e: any) { + return { valid: false, message: `Schema compilation error: ${e.message}` }; } - if (this.validate && !this.validate(payload)) { - const errors = this.validate.errors as ErrorObject[]; - const errorMessages = errors.map(e => `Key: ${e.instancePath.split('/').slice(1).join('.')}, Message: ${e.message}`); + if (this.validate && !this.validate.Check(payload)) { + const errors = [...this.validate.Errors(payload)]; + const errorMessages = errors.map(e => `Key: ${e.path.split('/').slice(1).join('.')}, Message: ${e.message}`); return { valid: false, - message: errorMessages.join('\n') ?? '未知错误', + message: errorMessages.length > 0 ? errorMessages.join('\n') : '未知错误', }; } return { valid: true }; diff --git a/packages/napcat-onebot/config/config.ts b/packages/napcat-onebot/config/config.ts index f3db9e30e..8f6777bc2 100644 --- a/packages/napcat-onebot/config/config.ts +++ b/packages/napcat-onebot/config/config.ts @@ -1,5 +1,6 @@ import { Type, Static } from '@sinclair/typebox'; -import Ajv from 'ajv'; +import { TypeCompiler } from '@sinclair/typebox/compiler'; +import { Value } from '@sinclair/typebox/value'; const HttpServerConfigSchema = Type.Object({ name: Type.String({ default: 'http-server' }), enable: Type.Boolean({ default: false }), @@ -97,11 +98,14 @@ export type NetworkAdapterConfig = HttpServerConfig | HttpSseServerConfig | Http export type NetworkConfigKey = keyof OneBotConfig['network']; export function loadConfig (config: Partial): OneBotConfig { - const ajv = new Ajv({ useDefaults: true, coerceTypes: true }); - const validate = ajv.compile(OneBotConfigSchema); - const valid = validate(config); + let data = config; + data = Value.Default(OneBotConfigSchema, data) as Partial; + data = Value.Convert(OneBotConfigSchema, data) as Partial; + const validate = TypeCompiler.Compile(OneBotConfigSchema); + const valid = validate.Check(data); if (!valid) { - throw new Error(ajv.errorsText(validate.errors)); + const errorMsg = [...validate.Errors(data)].map(e => e.message).join(', '); + throw new Error(errorMsg); } - return config as OneBotConfig; + return data as OneBotConfig; } diff --git a/packages/napcat-onebot/config/index.ts b/packages/napcat-onebot/config/index.ts index d02761208..fe84992b8 100644 --- a/packages/napcat-onebot/config/index.ts +++ b/packages/napcat-onebot/config/index.ts @@ -1,12 +1,12 @@ import { ConfigBase } from 'napcat-core/helper/config-base'; import type { NapCatCore } from 'napcat-core'; import { OneBotConfig } from './config'; -import { AnySchema } from 'ajv'; +import { TSchema } from '@sinclair/typebox'; export * from './config'; export class OB11ConfigLoader extends ConfigBase { - constructor (core: NapCatCore, configPath: string, schema: AnySchema) { + constructor (core: NapCatCore, configPath: string, schema: TSchema) { super('onebot11', core, configPath, schema); } } diff --git a/packages/napcat-onebot/package.json b/packages/napcat-onebot/package.json index 4546bfb35..2d117c43c 100644 --- a/packages/napcat-onebot/package.json +++ b/packages/napcat-onebot/package.json @@ -16,29 +16,28 @@ } }, "dependencies": { - "napcat.protobuf": "^1.1.4", - "fast-xml-parser": "^4.3.6", - "type-is": "^1.6.7", - "on-finished": "^2.3.5", - "ajv": "^8.13.0", "@sinclair/typebox": "^0.34.38", "cors": "^2.8.5", "express": "^5.0.0", - "ws": "^8.18.3", + "fast-xml-parser": "^4.3.6", "file-type": "^21.0.0", - "napcat-protobuf": "workspace:*", "json5": "^2.2.3", + "napcat-common": "workspace:*", "napcat-core": "workspace:*", - "napcat-webui-backend": "workspace:*", "napcat-image-size": "workspace:*", - "napcat-common": "workspace:*" + "napcat-protobuf": "workspace:*", + "napcat-webui-backend": "workspace:*", + "napcat.protobuf": "^1.1.4", + "on-finished": "^2.3.5", + "type-is": "^1.6.7", + "ws": "^8.18.3" }, "devDependencies": { "@types/cors": "^2.8.17", - "@types/type-is": "^1.6.7", - "@types/on-finished": "^2.3.4", "@types/express": "^5.0.0", - "@types/node": "^22.0.1" + "@types/node": "^22.0.1", + "@types/on-finished": "^2.3.4", + "@types/type-is": "^1.6.7" }, "engines": { "node": ">=18.0.0" diff --git a/packages/napcat-onebot/test_schema.ts b/packages/napcat-onebot/test_schema.ts new file mode 100644 index 000000000..b5994a9fd --- /dev/null +++ b/packages/napcat-onebot/test_schema.ts @@ -0,0 +1,61 @@ +import { TypeCompiler } from '@sinclair/typebox/compiler'; +import { Value } from '@sinclair/typebox/value'; +import { OB11MessageDataSchema, OB11MessageSchema, OB11PostSendMsgSchema } from './types/message'; +import { OB11MessageSchema as OB11ActionMessageSchema } from './action/schemas'; + +try { + TypeCompiler.Compile(OB11MessageDataSchema); + console.log("Compile OB11MessageDataSchema OK"); +} catch (e: any) { + console.error("Error in OB11MessageDataSchema:", e.message); +} + +try { + TypeCompiler.Compile(OB11MessageSchema); + console.log("Compile OB11MessageSchema OK"); +} catch (e: any) { + console.error("Error in OB11MessageSchema:", e.message); +} + +try { + TypeCompiler.Compile(OB11ActionMessageSchema); + console.log("Compile OB11ActionMessageSchema OK"); +} catch (e: any) { + console.error("Error in OB11ActionMessageSchema:", e.message); +} + +import { Type } from '@sinclair/typebox'; +try { + const QA = Type.Object({ message: OB11PostSendMsgSchema, quick_action: OB11ActionMessageSchema }); + TypeCompiler.Compile(QA); + console.log("Compile Quick Action OK"); +} catch (e: any) { + console.error("Error in Quick Action:", e.message); +} + +// Test validation +const testObj = { + message_type: 'private', + user_id: 12345, + message: [ + { type: 'text', data: { text: 'hello' } } + ] +}; + +try { + let data = structuredClone(testObj); + data = Value.Default(OB11PostSendMsgSchema, data) as any; + data = Value.Convert(OB11PostSendMsgSchema, data) as any; + + const compiler = TypeCompiler.Compile(OB11PostSendMsgSchema); + const isValid = compiler.Check(data); + console.log("Validation result:", isValid); + if (!isValid) { + const errors = [...compiler.Errors(data)]; + errors.forEach(e => console.error(e.path, e.message)); + } else { + console.log("Data after Convert and Check:", JSON.stringify(data, null, 2)); + } +} catch (e: any) { + console.error("Test validation error:", e.message); +} diff --git a/packages/napcat-protobuf/NapProto.ts b/packages/napcat-protobuf/NapProto.ts index d9b5c288e..65c624cb2 100644 --- a/packages/napcat-protobuf/NapProto.ts +++ b/packages/napcat-protobuf/NapProto.ts @@ -2,44 +2,44 @@ import { MessageType, PartialMessage, RepeatType, ScalarType } from '@protobuf-ts/runtime'; import { PartialFieldInfo } from '@protobuf-ts/runtime/build/types/reflection-info'; -type LowerCamelCase = CamelCaseHelper; +export type LowerCamelCase = CamelCaseHelper; -type CamelCaseHelper< - S extends string, - CapNext extends boolean, - IsFirstChar extends boolean +export type CamelCaseHelper< + S extends string, + CapNext extends boolean, + IsFirstChar extends boolean > = S extends `${infer F}${infer R}` ? F extends '_' - ? CamelCaseHelper - : F extends `${number}` - ? `${F}${CamelCaseHelper}` - : CapNext extends true - ? `${Uppercase}${CamelCaseHelper}` - : IsFirstChar extends true - ? `${Lowercase}${CamelCaseHelper}` - : `${F}${CamelCaseHelper}` + ? CamelCaseHelper + : F extends `${number}` + ? `${F}${CamelCaseHelper}` + : CapNext extends true + ? `${Uppercase}${CamelCaseHelper}` + : IsFirstChar extends true + ? `${Lowercase}${CamelCaseHelper}` + : `${F}${CamelCaseHelper}` : ''; -type ScalarTypeToTsType = T extends - | ScalarType.DOUBLE - | ScalarType.FLOAT - | ScalarType.INT32 - | ScalarType.FIXED32 - | ScalarType.UINT32 - | ScalarType.SFIXED32 - | ScalarType.SINT32 +export type ScalarTypeToTsType = T extends + | ScalarType.DOUBLE + | ScalarType.FLOAT + | ScalarType.INT32 + | ScalarType.FIXED32 + | ScalarType.UINT32 + | ScalarType.SFIXED32 + | ScalarType.SINT32 ? number : T extends ScalarType.INT64 | ScalarType.UINT64 | ScalarType.FIXED64 | ScalarType.SFIXED64 | ScalarType.SINT64 - ? bigint - : T extends ScalarType.BOOL - ? boolean - : T extends ScalarType.STRING - ? string - : T extends ScalarType.BYTES - ? Uint8Array - : never; + ? bigint + : T extends ScalarType.BOOL + ? boolean + : T extends ScalarType.STRING + ? string + : T extends ScalarType.BYTES + ? Uint8Array + : never; -interface BaseProtoFieldType { +export interface BaseProtoFieldType { kind: 'scalar' | 'message'; no: number; type: T; @@ -53,30 +53,30 @@ export interface ScalarProtoFieldType ProtoMessageType, - O extends boolean, - R extends O extends true ? false : boolean + T extends () => ProtoMessageType, + O extends boolean, + R extends O extends true ? false : boolean > extends BaseProtoFieldType { kind: 'message'; } -type ProtoFieldType = - | ScalarProtoFieldType - | MessageProtoFieldType<() => ProtoMessageType, boolean, boolean>; +export type ProtoFieldType = + | ScalarProtoFieldType + | MessageProtoFieldType<() => ProtoMessageType, boolean, boolean>; -type ProtoMessageType = { +export type ProtoMessageType = { [key: string]: ProtoFieldType; }; export function ProtoField< - T extends ScalarType, - O extends boolean = false, - R extends O extends true ? false : boolean = false + T extends ScalarType, + O extends boolean = false, + R extends O extends true ? false : boolean = false > (no: number, type: T, optional?: O, repeat?: R): ScalarProtoFieldType; export function ProtoField< - T extends () => ProtoMessageType, - O extends boolean = false, - R extends O extends true ? false : boolean = false + T extends () => ProtoMessageType, + O extends boolean = false, + R extends O extends true ? false : boolean = false > (no: number, type: T, optional?: O, repeat?: R): MessageProtoFieldType; export function ProtoField ( no: number, @@ -91,38 +91,38 @@ export function ProtoField ( } } -type ProtoFieldReturnType = - NonNullable extends ScalarProtoFieldType - ? ScalarTypeToTsType - : T extends NonNullable> - ? NonNullable, E>> - : never; +export type ProtoFieldReturnType = + NonNullable extends ScalarProtoFieldType + ? ScalarTypeToTsType + : T extends NonNullable> + ? NonNullable, E>> + : never; -type RequiredFieldsBaseType = { - [K in keyof T as T[K] extends { optional: true } ? never : LowerCamelCase]: T[K] extends { +export type RequiredFieldsBaseType = { + [K in keyof T as T[K] extends { optional: true; } ? never : LowerCamelCase]: T[K] extends { repeat: true; } - ? ProtoFieldReturnType[] - : ProtoFieldReturnType; + ? ProtoFieldReturnType[] + : ProtoFieldReturnType; }; -type OptionalFieldsBaseType = { - [K in keyof T as T[K] extends { optional: true } ? LowerCamelCase : never]?: T[K] extends { +export type OptionalFieldsBaseType = { + [K in keyof T as T[K] extends { optional: true; } ? LowerCamelCase : never]?: T[K] extends { repeat: true; } - ? ProtoFieldReturnType[] - : ProtoFieldReturnType; + ? ProtoFieldReturnType[] + : ProtoFieldReturnType; }; -type RequiredFieldsType = E extends true +export type RequiredFieldsType = E extends true ? Partial> : RequiredFieldsBaseType; -type OptionalFieldsType = E extends true +export type OptionalFieldsType = E extends true ? Partial> : OptionalFieldsBaseType; -type NapProtoStructType = RequiredFieldsType & OptionalFieldsType; +export type NapProtoStructType = RequiredFieldsType & OptionalFieldsType; export type NapProtoEncodeStructType = NapProtoStructType; @@ -165,7 +165,7 @@ class NapProtoRealMsg { this._proto_msg = new MessageType>('nya', this._field); } - static getInstance(fields: T): NapProtoRealMsg { + static getInstance (fields: T): NapProtoRealMsg { let instance = this.cache.get(fields); if (!instance) { instance = new NapProtoRealMsg(fields); diff --git a/packages/napcat-protocol/config/config.ts b/packages/napcat-protocol/config/config.ts index 0f0b60e2d..f03b2b2e3 100644 --- a/packages/napcat-protocol/config/config.ts +++ b/packages/napcat-protocol/config/config.ts @@ -1,5 +1,6 @@ import { Type, Static } from '@sinclair/typebox'; -import Ajv from 'ajv'; +import { TypeCompiler } from '@sinclair/typebox/compiler'; +import { Value } from '@sinclair/typebox/value'; // WebSocket 服务端配置 const WebsocketServerConfigSchema = Type.Object({ @@ -56,11 +57,14 @@ export type NetworkAdapterConfig = HttpServerConfig | WebsocketServerConfig | We export type NetworkConfigKey = keyof NapCatProtocolConfig['network']; export function loadConfig (config: Partial): NapCatProtocolConfig { - const ajv = new Ajv({ useDefaults: true, coerceTypes: true }); - const validate = ajv.compile(NapCatProtocolConfigSchema); - const valid = validate(config); + let data = config; + data = Value.Default(NapCatProtocolConfigSchema, data) as Partial; + data = Value.Convert(NapCatProtocolConfigSchema, data) as Partial; + const validate = TypeCompiler.Compile(NapCatProtocolConfigSchema); + const valid = validate.Check(data); if (!valid) { - throw new Error(ajv.errorsText(validate.errors)); + const errorMsg = [...validate.Errors(data)].map(e => e.message).join(', '); + throw new Error(errorMsg); } - return config as NapCatProtocolConfig; + return data as NapCatProtocolConfig; } diff --git a/packages/napcat-protocol/package.json b/packages/napcat-protocol/package.json index 79c9ef3fa..7afb55c04 100644 --- a/packages/napcat-protocol/package.json +++ b/packages/napcat-protocol/package.json @@ -16,14 +16,13 @@ } }, "dependencies": { - "ajv": "^8.13.0", "@sinclair/typebox": "^0.34.38", "cors": "^2.8.5", "express": "^5.0.0", - "ws": "^8.18.3", "json5": "^2.2.3", + "napcat-common": "workspace:*", "napcat-core": "workspace:*", - "napcat-common": "workspace:*" + "ws": "^8.18.3" }, "devDependencies": { "@types/cors": "^2.8.17", diff --git a/packages/napcat-test/package.json b/packages/napcat-test/package.json index 5df18293b..367a8490c 100644 --- a/packages/napcat-test/package.json +++ b/packages/napcat-test/package.json @@ -11,8 +11,10 @@ "vitest": "^4.0.9" }, "dependencies": { + "@sinclair/typebox": "^0.34.41", "napcat-core": "workspace:*", - "napcat-rpc": "workspace:*", - "napcat-image-size": "workspace:*" + "napcat-image-size": "workspace:*", + "napcat-onebot": "workspace:*", + "napcat-rpc": "workspace:*" } } \ No newline at end of file diff --git a/packages/napcat-test/schema.test.ts b/packages/napcat-test/schema.test.ts new file mode 100644 index 000000000..9e744bbd3 --- /dev/null +++ b/packages/napcat-test/schema.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, test } from 'vitest'; +import { TypeCompiler } from '@sinclair/typebox/compiler'; +import { Value } from '@sinclair/typebox/value'; +import { Type } from '@sinclair/typebox'; + +import { OB11MessageDataSchema, OB11MessageSchema, OB11PostSendMsgSchema } from '../napcat-onebot/types/message'; +import { OB11MessageSchema as OB11ActionMessageSchema } from '../napcat-onebot/action/schemas'; +import { OneBotConfigSchema, loadConfig as loadOneBotConfig, OneBotConfig } from '../napcat-onebot/config'; +import { NapcatConfigSchema } from '../napcat-core/helper/config'; + +describe('NapCat Schemas Compilation', () => { + test('should compile OB11MessageDataSchema without duplicate id error', () => { + expect(() => TypeCompiler.Compile(OB11MessageDataSchema)).not.toThrow(); + }); + + test('should compile OB11MessageSchema without duplicate id error', () => { + expect(() => TypeCompiler.Compile(OB11MessageSchema)).not.toThrow(); + }); + + test('should compile OB11ActionMessageSchema without duplicate id error', () => { + expect(() => TypeCompiler.Compile(OB11ActionMessageSchema)).not.toThrow(); + }); + + test('should compile OB11PostSendMsgSchema without error', () => { + expect(() => TypeCompiler.Compile(OB11PostSendMsgSchema)).not.toThrow(); + }); + + test('should compile QuickAction hybrid schema without error', () => { + const QASchema = Type.Object({ + message: OB11PostSendMsgSchema, + quick_action: OB11ActionMessageSchema + }); + expect(() => TypeCompiler.Compile(QASchema)).not.toThrow(); + }); +}); + +describe('NapCat Schemas Validation & Coercion', () => { + test('should coerce numeric user_id to string in OB11PostSendMsgSchema', () => { + const payload = { + message_type: 'private', + user_id: 123456, + message: [{ type: 'text', data: { text: 'hello' } }] + }; + + let data: unknown = structuredClone(payload); + data = Value.Default(OB11PostSendMsgSchema, data); + data = Value.Convert(OB11PostSendMsgSchema, data); + + const compiler = TypeCompiler.Compile(OB11PostSendMsgSchema); + expect(compiler.Check(data)).toBe(true); + expect((data as Record)['user_id']).toBe('123456'); + }); + + test('should validate complex mixed messages correctly', () => { + const payload = { + message_type: 'group', + group_id: "654321", + message: 'this is a string message' + }; + + let data: unknown = structuredClone(payload); + data = Value.Default(OB11PostSendMsgSchema, data); + data = Value.Convert(OB11PostSendMsgSchema, data); + + const compiler = TypeCompiler.Compile(OB11PostSendMsgSchema); + expect(compiler.Check(data)).toBe(true); + }); +}); + +describe('NapCat Configuration Loaders', () => { + test('OneBotConfig schemas should compile', () => { + expect(() => TypeCompiler.Compile(OneBotConfigSchema)).not.toThrow(); + }); + + test('OneBotConfig should load and apply defaults correctly', () => { + const partialConfig: Partial = { + network: { + httpServers: [{ + port: 3000, + enable: true, + name: 'test', + host: '127.0.0.1', + enableCors: true, + enableWebsocket: false, + messagePostFormat: 'array', + token: '', + debug: false + }], + httpSseServers: [], + httpClients: [], + websocketServers: [], + websocketClients: [], + plugins: [] + } + }; + const loaded = loadOneBotConfig(partialConfig); + expect(loaded.network.httpServers[0]?.host).toBe('127.0.0.1'); + expect(loaded.network.httpServers[0]?.enableCors).toBe(true); + expect(loaded.musicSignUrl).toBe(''); + }); + + test('NapcatConfig should compile and apply defaults', () => { + let compiled: ReturnType | undefined; + expect(() => { + compiled = TypeCompiler.Compile(NapcatConfigSchema); + }).not.toThrow(); + + let data: unknown = {}; + data = Value.Default(NapcatConfigSchema, data); + data = Value.Convert(NapcatConfigSchema, data); + + expect(compiled?.Check(data)).toBe(true); + const resolved = data as Record; + expect(resolved['consoleLog']).toBe(true); + expect(resolved['consoleLogLevel']).toBe('info'); + }); +}); diff --git a/packages/napcat-types/external-shims.d.ts b/packages/napcat-types/external-shims.d.ts index d047ad9f1..0f8a932e6 100644 --- a/packages/napcat-types/external-shims.d.ts +++ b/packages/napcat-types/external-shims.d.ts @@ -96,33 +96,6 @@ declare module 'inversify' { export default _inversify_default; } -declare module 'ajv' { - export interface AnySchema { [key: string]: any; } - - export interface ErrorObject { - keyword: string; - instancePath: string; - schemaPath: string; - params: any; - message?: string; - } - - export interface ValidateFunction { - (data: any): data is T; - errors: ErrorObject[] | null; - } - - class Ajv { - constructor (...args: any[]); - compile (schema: any): ValidateFunction; - validate (schemaOrRef: any, data: any): boolean; - errorsText (errors?: any, options?: any): string; - errors: ErrorObject[] | null; - } - - export default Ajv; - export { Ajv, ValidateFunction, ErrorObject }; -} declare module 'ip' { export function toBuffer (ip: any, buffer?: Buffer, offset?: number): Buffer; diff --git a/packages/napcat-types/scripts/post-build.mjs b/packages/napcat-types/scripts/post-build.mjs index 2ddb356c3..fece610d0 100644 --- a/packages/napcat-types/scripts/post-build.mjs +++ b/packages/napcat-types/scripts/post-build.mjs @@ -11,38 +11,6 @@ const ALLOWED_PACKAGES = [ 'node:', // node: 前缀的内置模块 ]; -/* -// 外部包类型到 any 的映射 -const EXTERNAL_TYPE_REPLACEMENTS = { - // winston - 'winston.Logger': 'any', - 'winston.transport': 'any', - // express - 'express.Express': 'any', - 'express.Application': 'any', - 'express.Router': 'any', - Express: 'any', - Request: 'any', - Response: 'any', - NextFunction: 'any', - // ws - WebSocket: 'any', - WebSocketServer: 'any', - RawData: 'any', - // ajv - Ajv: 'any', - AnySchema: 'any', - ValidateFunction: 'any', - 'ValidateFunction': 'any', - // inversify - Container: 'any', - // napcat-protobuf - NapProtoDecodeStructType: 'any', - NapProtoEncodeStructType: 'any', - 'NapProtoDecodeStructType': 'any', - 'NapProtoEncodeStructType': 'any', -}; -*/ function isAllowedImport (importPath) { return ALLOWED_PACKAGES.some(pkg => importPath.startsWith(pkg)); @@ -89,15 +57,15 @@ function replaceExternalTypes (content) { // 使用类型上下文的模式匹配 const typeContextPatterns = [ // : Type - /:\s*(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[;,)\]}|&]|$)/g, + /:\s*(WebSocket|WebSocketServer|RawData|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[;,)\]}|&]|$)/g, // - /<(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)>/g, + /<(WebSocket|WebSocketServer|RawData|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)>/g, // Type[] - /(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)\[\]/g, + /(WebSocket|WebSocketServer|RawData|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)\[\]/g, // extends Type - /extends\s+(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[{,])/g, + /extends\s+(WebSocket|WebSocketServer|RawData|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[{,])/g, // implements Type - /implements\s+(WebSocket|WebSocketServer|RawData|Ajv|AnySchema|ValidateFunction|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[{,])/g, + /implements\s+(WebSocket|WebSocketServer|RawData|Container|NapProtoDecodeStructType|NapProtoEncodeStructType|Express|Request|Response|NextFunction)(?=\s*[{,])/g, ]; for (const pattern of typeContextPatterns) { diff --git a/packages/napcat-webui-backend/package.json b/packages/napcat-webui-backend/package.json index ce36f97b4..a499cd327 100644 --- a/packages/napcat-webui-backend/package.json +++ b/packages/napcat-webui-backend/package.json @@ -18,7 +18,6 @@ "dependencies": { "@simplewebauthn/server": "^13.2.2", "@sinclair/typebox": "^0.34.38", - "ajv": "^8.13.0", "compressing": "^1.10.3", "compression": "^1.8.1", "express": "^5.0.0", diff --git a/packages/napcat-webui-backend/src/api/NapCatConfig.ts b/packages/napcat-webui-backend/src/api/NapCatConfig.ts index a7ce2617d..ca3b33ab1 100644 --- a/packages/napcat-webui-backend/src/api/NapCatConfig.ts +++ b/packages/napcat-webui-backend/src/api/NapCatConfig.ts @@ -6,16 +6,13 @@ import { WebUiDataRuntime } from '@/napcat-webui-backend/src/helper/Data'; import { sendError, sendSuccess } from '@/napcat-webui-backend/src/utils/response'; import json5 from 'json5'; -import Ajv from 'ajv'; +import { Value } from '@sinclair/typebox/value'; import { NapcatConfigSchema } from '@/napcat-core/helper/config'; // 动态获取 NapCat 配置默认值 function getDefaultNapcatConfig (): Record { - const ajv = new Ajv({ useDefaults: true, coerceTypes: true }); - const validate = ajv.compile(NapcatConfigSchema); const data = {}; - validate(data); - return data; + return Value.Default(NapcatConfigSchema, data) as Record; } /** diff --git a/packages/napcat-webui-backend/src/helper/config.ts b/packages/napcat-webui-backend/src/helper/config.ts index 42f486a54..638752f5e 100644 --- a/packages/napcat-webui-backend/src/helper/config.ts +++ b/packages/napcat-webui-backend/src/helper/config.ts @@ -1,6 +1,7 @@ import { webUiPathWrapper, getInitialWebUiToken } from '@/napcat-webui-backend/index'; import { Type, Static } from '@sinclair/typebox'; -import Ajv from 'ajv'; +import { TypeCompiler } from '@sinclair/typebox/compiler'; +import { Value } from '@sinclair/typebox/value'; import fs, { constants } from 'node:fs/promises'; import { resolve } from 'node:path'; @@ -41,8 +42,14 @@ export class WebUiConfigWrapper { WebUiConfigData: WebUiConfigType | undefined = undefined; private validateAndApplyDefaults (config: Partial): WebUiConfigType { - new Ajv({ coerceTypes: true, useDefaults: true }).compile(WebUiConfigSchema)(config); - return config as WebUiConfigType; + let data = config; + data = Value.Default(WebUiConfigSchema, data) as Partial; + data = Value.Convert(WebUiConfigSchema, data) as Partial; + const validate = TypeCompiler.Compile(WebUiConfigSchema); + if (!validate.Check(data)) { + // Return original if validation failed, or throw + } + return data as WebUiConfigType; } private async ensureConfigFileExists (configPath: string): Promise { diff --git a/packages/napcat-webui-backend/src/onebot/config.ts b/packages/napcat-webui-backend/src/onebot/config.ts index 164d7b8d0..be24d2667 100644 --- a/packages/napcat-webui-backend/src/onebot/config.ts +++ b/packages/napcat-webui-backend/src/onebot/config.ts @@ -1,5 +1,6 @@ import { Type, Static } from '@sinclair/typebox'; -import Ajv from 'ajv'; +import { TypeCompiler } from '@sinclair/typebox/compiler'; +import { Value } from '@sinclair/typebox/value'; const HttpServerConfigSchema = Type.Object({ name: Type.String({ default: 'http-server' }), enable: Type.Boolean({ default: false }), @@ -97,11 +98,14 @@ export type NetworkAdapterConfig = HttpServerConfig | HttpSseServerConfig | Http export type NetworkConfigKey = keyof OneBotConfig['network']; export function loadConfig (config: Partial): OneBotConfig { - const ajv = new Ajv({ useDefaults: true, coerceTypes: true }); - const validate = ajv.compile(OneBotConfigSchema); - const valid = validate(config); + let data = config; + data = Value.Default(OneBotConfigSchema, data) as Partial; + data = Value.Convert(OneBotConfigSchema, data) as Partial; + const validate = TypeCompiler.Compile(OneBotConfigSchema); + const valid = validate.Check(data); if (!valid) { - throw new Error(ajv.errorsText(validate.errors)); + const errorMsg = [...validate.Errors(data)].map(e => e.message).join(', '); + throw new Error(errorMsg); } - return config as OneBotConfig; + return data as OneBotConfig; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c46a258ae..22cf5e02f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -64,9 +64,6 @@ importers: packages/napcat-common: dependencies: - ajv: - specifier: ^8.13.0 - version: 8.17.1 file-type: specifier: ^21.0.0 version: 21.1.0 @@ -83,9 +80,6 @@ importers: '@sinclair/typebox': specifier: ^0.34.38 version: 0.34.41 - ajv: - specifier: ^8.13.0 - version: 8.17.1 compressing: specifier: ^1.10.1 version: 1.10.3 @@ -188,9 +182,6 @@ importers: '@sinclair/typebox': specifier: ^0.34.38 version: 0.34.41 - ajv: - specifier: ^8.13.0 - version: 8.17.1 cors: specifier: ^2.8.5 version: 2.8.5 @@ -275,9 +266,6 @@ importers: '@sinclair/typebox': specifier: ^0.34.38 version: 0.34.41 - ajv: - specifier: ^8.13.0 - version: 8.17.1 cors: specifier: ^2.8.5 version: 2.8.5 @@ -387,12 +375,18 @@ importers: packages/napcat-test: dependencies: + '@sinclair/typebox': + specifier: ^0.34.41 + version: 0.34.41 napcat-core: specifier: workspace:* version: link:../napcat-core napcat-image-size: specifier: workspace:* version: link:../napcat-image-size + napcat-onebot: + specifier: workspace:* + version: link:../napcat-onebot napcat-rpc: specifier: workspace:* version: link:../napcat-rpc @@ -447,9 +441,6 @@ importers: '@sinclair/typebox': specifier: ^0.34.38 version: 0.34.41 - ajv: - specifier: ^8.13.0 - version: 8.17.1 compressing: specifier: ^1.10.3 version: 1.10.3 @@ -2877,6 +2868,9 @@ packages: '@sinclair/typebox@0.34.41': resolution: {integrity: sha512-6gS8pZzSXdyRHTIqoqSVknxolr1kzfy4/CeDnrzsVz8TTIWUbOBr6gnzOmTYJ3eXQNh4IYHIGi5aIL7sOZ2G/g==} + '@sinclair/typebox@0.34.48': + resolution: {integrity: sha512-kKJTNuK3AQOrgjjotVxMrCn1sUJwM76wMszfq1kdU4uYVJjvEWuFQ6HgvLt4Xz3fSmZlTOxJ/Ie13KnIcWQXFA==} + '@so-ric/colorspace@1.1.6': resolution: {integrity: sha512-/KiKkpHNOBgkFJwu9sh48LkHSMYGyuTcSFK/qMBdnOAlrRJzRSXAOFB5qwzaVQuDl8wAvHVMkaASQDReTahxuw==} @@ -3471,9 +3465,6 @@ packages: ajv@6.12.6: resolution: {integrity: sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==} - ajv@8.17.1: - resolution: {integrity: sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==} - ansi-colors@4.1.3: resolution: {integrity: sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==} engines: {node: '>=6'} @@ -4439,9 +4430,6 @@ packages: fast-levenshtein@2.0.6: resolution: {integrity: sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==} - fast-uri@3.1.0: - resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==} - fast-xml-parser@4.5.3: resolution: {integrity: sha512-RKihhV+SHsIUGXObeVy9AXiBbFwkVk7Syp8XgwN5U3JV416+Gwp/GO9i0JYKmikykgz/UHRrrV4ROuZEo/T0ig==} hasBin: true @@ -5106,9 +5094,6 @@ packages: json-schema-traverse@0.4.1: resolution: {integrity: sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==} - json-schema-traverse@1.0.0: - resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} - json-stable-stringify-without-jsonify@1.0.1: resolution: {integrity: sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==} @@ -6118,10 +6103,6 @@ packages: resolution: {integrity: sha512-UszKE5KVK6JvyD92nzMn9cDapSk6w/CaFZ96CnmDMUqH9oowfxF/ZjRITD25H4DnOQClLA4/j7jLGXXLVKxAug==} engines: {node: '>= 10'} - require-from-string@2.0.2: - resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} - engines: {node: '>=0.10.0'} - reselect@5.1.1: resolution: {integrity: sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w==} @@ -9714,6 +9695,8 @@ snapshots: '@sinclair/typebox@0.34.41': {} + '@sinclair/typebox@0.34.48': {} + '@so-ric/colorspace@1.1.6': dependencies: color: 5.0.2 @@ -10330,13 +10313,6 @@ snapshots: json-schema-traverse: 0.4.1 uri-js: 4.4.1 - ajv@8.17.1: - dependencies: - fast-deep-equal: 3.1.3 - fast-uri: 3.1.0 - json-schema-traverse: 1.0.0 - require-from-string: 2.0.2 - ansi-colors@4.1.3: {} ansi-regex@5.0.1: {} @@ -11519,8 +11495,6 @@ snapshots: fast-levenshtein@2.0.6: {} - fast-uri@3.1.0: {} - fast-xml-parser@4.5.3: dependencies: strnum: 1.1.2 @@ -12220,8 +12194,6 @@ snapshots: json-schema-traverse@0.4.1: {} - json-schema-traverse@1.0.0: {} - json-stable-stringify-without-jsonify@1.0.1: {} json5@1.0.2: @@ -12850,7 +12822,7 @@ snapshots: napcat-types@0.0.16: dependencies: - '@sinclair/typebox': 0.34.41 + '@sinclair/typebox': 0.34.48 '@types/node': 22.19.1 napcat.protobuf@1.1.4: @@ -13490,8 +13462,6 @@ snapshots: replace-ext@2.0.0: {} - require-from-string@2.0.2: {} - reselect@5.1.1: {} resize-observer-polyfill@1.5.1: {}