diff --git a/electron.vite.config.ts b/electron.vite.config.ts index e6b320a..3e68669 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -39,6 +39,7 @@ const config: ElectronViteConfig = { ...external.map(genCpModule), { src: './manifest.json', dest: 'dist' }, { src: './icon.webp', dest: 'dist' }, + { src: './src/ntqqapi/native/napcat-protocol-packet/Moehoo/*', dest: 'dist/main/Moehoo' }, ], }), ], diff --git a/manifest.json b/manifest.json index 28e50ec..2add6a2 100644 --- a/manifest.json +++ b/manifest.json @@ -4,12 +4,16 @@ "name": "LLOneBot", "slug": "LLOneBot", "description": "实现 OneBot 11 和 Satori 协议,用于 QQ 机器人开发", - "version": "4.1.4", + "version": "4.1.5", "icon": "./icon.webp", "authors": [ { "name": "linyuchen", "link": "https://github.com/linyuchen" + }, + { + "name": "idranme", + "link": "https://github.com/idranme" } ], "repository": { diff --git a/scripts/gen-manifest.ts b/scripts/gen-manifest.ts index f90eb74..01eff1f 100644 --- a/scripts/gen-manifest.ts +++ b/scripts/gen-manifest.ts @@ -13,6 +13,10 @@ const manifest = { { name: 'linyuchen', link: 'https://github.com/linyuchen' + }, + { + "name": "idranme", + "link": "https://github.com/idranme" } ], repository: { diff --git a/src/main/main.ts b/src/main/main.ts index 4a72919..2c2339d 100644 --- a/src/main/main.ts +++ b/src/main/main.ts @@ -36,6 +36,9 @@ import { } from '../ntqqapi/api' import { existsSync, mkdirSync } from 'node:fs' +import { initWrapperSession} from '@/ntqqapi/native/napcat-protocol-packet' +initWrapperSession().then() + declare module 'cordis' { interface Events { 'llob/config-updated': (input: LLOBConfig) => void diff --git a/src/ntqqapi/core.ts b/src/ntqqapi/core.ts index 54b7e15..ce866c8 100644 --- a/src/ntqqapi/core.ts +++ b/src/ntqqapi/core.ts @@ -19,7 +19,8 @@ import { import { selfInfo } from '../common/globalVars' import { version } from '../version' import { invoke } from './ntcall' -import { Native } from './native/index' +import { Native } from './native/crychic' +import { initWrapperSession, NTQQPacketApi } from './native/napcat-protocol-packet' declare module 'cordis' { interface Context { @@ -40,10 +41,12 @@ class Core extends Service { static inject = ['ntMsgApi', 'ntFriendApi', 'ntGroupApi', 'store'] public startTime = 0 public native + public ntqqPacketApi: NTQQPacketApi constructor(protected ctx: Context, public config: Core.Config) { super(ctx, 'app', true) this.native = new Native(ctx) + initWrapperSession().then(session=>{this.ntqqPacketApi = new NTQQPacketApi(session)}) } public start() { diff --git a/src/ntqqapi/native/external/crychic-win32-x64.node b/src/ntqqapi/native/crychic/external/crychic-win32-x64.node similarity index 100% rename from src/ntqqapi/native/external/crychic-win32-x64.node rename to src/ntqqapi/native/crychic/external/crychic-win32-x64.node diff --git a/src/ntqqapi/native/index.ts b/src/ntqqapi/native/crychic/index.ts similarity index 94% rename from src/ntqqapi/native/index.ts rename to src/ntqqapi/native/crychic/index.ts index 843e1ef..aa8670d 100644 --- a/src/ntqqapi/native/index.ts +++ b/src/ntqqapi/native/crychic/index.ts @@ -1,9 +1,9 @@ import { Context } from 'cordis' import { Dict } from 'cosmokit' -import { getBuildVersion } from '@/common/utils/misc' -import { TEMP_DIR } from '@/common/globalVars' +import { getBuildVersion } from '../../../common/utils/misc' +import { TEMP_DIR } from '../../../common/globalVars' import { copyFile } from 'fs/promises' -import { ChatType, Peer } from '../types' +import { ChatType, Peer } from '../../types' import path from 'node:path' import addon from './external/crychic-win32-x64.node?asset' diff --git a/src/ntqqapi/native/napcat-protocol-packet/Moehoo/MoeHoo.linux.arm64.node b/src/ntqqapi/native/napcat-protocol-packet/Moehoo/MoeHoo.linux.arm64.node new file mode 100644 index 0000000..73d9a01 Binary files /dev/null and b/src/ntqqapi/native/napcat-protocol-packet/Moehoo/MoeHoo.linux.arm64.node differ diff --git a/src/ntqqapi/native/napcat-protocol-packet/Moehoo/MoeHoo.linux.x64.node b/src/ntqqapi/native/napcat-protocol-packet/Moehoo/MoeHoo.linux.x64.node new file mode 100644 index 0000000..70ca668 Binary files /dev/null and b/src/ntqqapi/native/napcat-protocol-packet/Moehoo/MoeHoo.linux.x64.node differ diff --git a/src/ntqqapi/native/napcat-protocol-packet/Moehoo/MoeHoo.win32.x64.node b/src/ntqqapi/native/napcat-protocol-packet/Moehoo/MoeHoo.win32.x64.node new file mode 100644 index 0000000..ab1701c Binary files /dev/null and b/src/ntqqapi/native/napcat-protocol-packet/Moehoo/MoeHoo.win32.x64.node differ diff --git a/src/ntqqapi/native/napcat-protocol-packet/index.d.ts b/src/ntqqapi/native/napcat-protocol-packet/index.d.ts new file mode 100644 index 0000000..a9dcd4b --- /dev/null +++ b/src/ntqqapi/native/napcat-protocol-packet/index.d.ts @@ -0,0 +1,16 @@ +import { WrapperSession } from './wrapper-session/types'; +export { initWrapperSession } from './wrapper-session'; +export declare class NTQQPacketApi { + private qqVersion; + private packetSession; + private logger; + private readonly wrapperSession; + constructor(wrapperSession: WrapperSession); + get available(): boolean; + private InitSendPacket; + private sendPacket; + private sendOidbPacket; + sendPokePacket(peer: number, group?: number): Promise; + sendGroupSignPacket(selfUin: string, groupCode: string): Promise; + sendSetSpecialTittlePacket(groupCode: string, uid: string, tittle: string): Promise; +} diff --git a/src/ntqqapi/native/napcat-protocol-packet/index.mjs b/src/ntqqapi/native/napcat-protocol-packet/index.mjs new file mode 100644 index 0000000..54778a5 --- /dev/null +++ b/src/ntqqapi/native/napcat-protocol-packet/index.mjs @@ -0,0 +1 @@ +import e from"os";import t from"stream";import s from"zlib";import r from"buffer";import i,{createHash as n}from"crypto";import o from"events";import a from"https";import c from"http";import h from"net";import l from"tls";import f,{fileURLToPath as u}from"url";import d,{dirname as p}from"path";import m from"fs";import g,{constants as _}from"node:os";import b from"node:fs";import y from"node:path";class w{capacity;cache;constructor(e){this.capacity=e,this.cache=new Map}get(e){const t=this.cache.get(e);return void 0!==t&&(this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.capacity){const e=this.cache.keys().next().value;void 0!==e&&this.cache.delete(e)}this.cache.set(e,t)}}function k(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function v(e){if(e.__esModule)return e;var t=e.default;if("function"==typeof t){var s=function e(){return this instanceof e?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};s.prototype=t.prototype}else s={};return Object.defineProperty(s,"__esModule",{value:!0}),Object.keys(e).forEach((function(t){var r=Object.getOwnPropertyDescriptor(e,t);Object.defineProperty(s,t,r.get?r:{enumerable:!0,get:function(){return e[t]}})})),s}var S={exports:{}};const E=["nodebuffer","arraybuffer","fragments"],N="undefined"!=typeof Blob;N&&E.push("blob");var T={BINARY_TYPES:E,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:N,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}};const I=v(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));const{EMPTY_BUFFER:O}=T,x=Buffer[Symbol.species];function B(e,t,s,r,i){for(let n=0;n{this.pending--,this[U]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[U]()}[U](){if(this.pending!==this.concurrency&&this.jobs.length){const e=this.jobs.shift();this.pending++,e(this[L])}}},{kStatusCode:F}=T,V=Buffer[Symbol.species],j=Buffer.from([0,0,255,255]),M=Symbol("permessage-deflate"),W=Symbol("total-length"),$=Symbol("callback"),G=Symbol("buffers"),Q=Symbol("error");let q;var X=class{constructor(e,t,s){if(this._maxPayload=0|s,this._options=e||{},this._threshold=void 0!==this._options.threshold?this._options.threshold:1024,this._isServer=!!t,this._deflate=null,this._inflate=null,this.params=null,!q){const e=void 0!==this._options.concurrencyLimit?this._options.concurrencyLimit:10;q=new D(e)}}static get extensionName(){return"permessage-deflate"}offer(){const e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:null==this._options.clientMaxWindowBits&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){const e=this._deflate[$];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){const t=this._options,s=e.find((e=>!(!1===t.serverNoContextTakeover&&e.server_no_context_takeover||e.server_max_window_bits&&(!1===t.serverMaxWindowBits||"number"==typeof t.serverMaxWindowBits&&t.serverMaxWindowBits>e.server_max_window_bits)||"number"==typeof t.clientMaxWindowBits&&!e.client_max_window_bits)));if(!s)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),"number"==typeof t.serverMaxWindowBits&&(s.server_max_window_bits=t.serverMaxWindowBits),"number"==typeof t.clientMaxWindowBits?s.client_max_window_bits=t.clientMaxWindowBits:!0!==s.client_max_window_bits&&!1!==t.clientMaxWindowBits||delete s.client_max_window_bits,s}acceptAsClient(e){const t=e[0];if(!1===this._options.clientNoContextTakeover&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(t.client_max_window_bits){if(!1===this._options.clientMaxWindowBits||"number"==typeof this._options.clientMaxWindowBits&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"')}else"number"==typeof this._options.clientMaxWindowBits&&(t.client_max_window_bits=this._options.clientMaxWindowBits);return t}normalizeParams(e){return e.forEach((e=>{Object.keys(e).forEach((t=>{let s=e[t];if(s.length>1)throw new Error(`Parameter "${t}" must have only a single value`);if(s=s[0],"client_max_window_bits"===t){if(!0!==s){const e=+s;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}else if("server_max_window_bits"===t){const e=+s;if(!Number.isInteger(e)||e<8||e>15)throw new TypeError(`Invalid value for parameter "${t}": ${s}`);s=e}else{if("client_no_context_takeover"!==t&&"server_no_context_takeover"!==t)throw new Error(`Unknown parameter "${t}"`);if(!0!==s)throw new TypeError(`Invalid value for parameter "${t}": ${s}`)}e[t]=s}))})),e}decompress(e,t,s){q.add((r=>{this._decompress(e,t,((e,t)=>{r(),s(e,t)}))}))}compress(e,t,s){q.add((r=>{this._compress(e,t,((e,t)=>{r(),s(e,t)}))}))}_decompress(e,t,s){const r=this._isServer?"client":"server";if(!this._inflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?R.Z_DEFAULT_WINDOWBITS:this.params[e];this._inflate=R.createInflateRaw({...this._options.zlibInflateOptions,windowBits:t}),this._inflate[M]=this,this._inflate[W]=0,this._inflate[G]=[],this._inflate.on("error",Z),this._inflate.on("data",Y)}this._inflate[$]=s,this._inflate.write(e),t&&this._inflate.write(j),this._inflate.flush((()=>{const e=this._inflate[Q];if(e)return this._inflate.close(),this._inflate=null,void s(e);const i=A.concat(this._inflate[G],this._inflate[W]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[W]=0,this._inflate[G]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),s(null,i)}))}_compress(e,t,s){const r=this._isServer?"server":"client";if(!this._deflate){const e=`${r}_max_window_bits`,t="number"!=typeof this.params[e]?R.Z_DEFAULT_WINDOWBITS:this.params[e];this._deflate=R.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:t}),this._deflate[W]=0,this._deflate[G]=[],this._deflate.on("data",K)}this._deflate[$]=s,this._deflate.write(e),this._deflate.flush(R.Z_SYNC_FLUSH,(()=>{if(!this._deflate)return;let e=A.concat(this._deflate[G],this._deflate[W]);t&&(e=new V(e.buffer,e.byteOffset,e.length-4)),this._deflate[$]=null,this._deflate[W]=0,this._deflate[G]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),s(null,e)}))}};function K(e){this[G].push(e),this[W]+=e.length}function Y(e){this[W]+=e.length,this[M]._maxPayload<1||this[W]<=this[M]._maxPayload?this[G].push(e):(this[Q]=new RangeError("Max payload size exceeded"),this[Q].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Q][F]=1009,this.removeListener("data",Y),this.reset())}function Z(e){this[M]._inflate=null,e[F]=1007,this[$](e)}var J={exports:{}};const z=v(Object.freeze(Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));const{isUtf8:H}=r,{hasBlob:ee}=T;function te(e){const t=e.length;let s=0;for(;s=t||128!=(192&e[s+1])||128!=(192&e[s+2])||224===e[s]&&128==(224&e[s+1])||237===e[s]&&160==(224&e[s+1]))return!1;s+=3}else{if(240!=(248&e[s]))return!1;if(s+3>=t||128!=(192&e[s+1])||128!=(192&e[s+2])||128!=(192&e[s+3])||240===e[s]&&128==(240&e[s+1])||244===e[s]&&e[s+1]>143||e[s]>244)return!1;s+=4}else s++;return!0}if(J.exports={isBlob:function(e){return ee&&"object"==typeof e&&"function"==typeof e.arrayBuffer&&"string"==typeof e.type&&"function"==typeof e.stream&&("Blob"===e[Symbol.toStringTag]||"File"===e[Symbol.toStringTag])},isValidStatusCode:function(e){return e>=1e3&&e<=1014&&1004!==e&&1005!==e&&1006!==e||e>=3e3&&e<=4999},isValidUTF8:te,tokenChars:[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0]},H)J.exports.isValidUTF8=function(e){return e.length<24?te(e):H(e)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{const e=z;J.exports.isValidUTF8=function(t){return t.length<32?te(t):e(t)}}catch(e){}var se=J.exports;const{Writable:re}=t,ie=X,{BINARY_TYPES:ne,EMPTY_BUFFER:oe,kStatusCode:ae,kWebSocket:ce}=T,{concat:he,toArrayBuffer:le,unmask:fe}=C,{isValidStatusCode:ue,isValidUTF8:de}=se,pe=Buffer[Symbol.species];var me=class extends re{constructor(e={}){super(),this._allowSynchronousEvents=void 0===e.allowSynchronousEvents||e.allowSynchronousEvents,this._binaryType=e.binaryType||ne[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=0|e.maxPayload,this._skipUTF8Validation=!!e.skipUTF8Validation,this[ce]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(e,t,s){if(8===this._opcode&&0==this._state)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e=s.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),r),this._buffers[0]=new pe(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return t}startLoop(e){this._loop=!0;do{switch(this._state){case 0:this.getInfo(e);break;case 1:this.getPayloadLength16(e);break;case 2:this.getPayloadLength64(e);break;case 3:this.getMask();break;case 4:this.getData(e);break;case 5:case 6:return void(this._loop=!1)}}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2)return void(this._loop=!1);const t=this.consume(2);if(48&t[0]){return void e(this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3"))}const s=!(64&~t[0]);if(!s||this._extensions[ie.extensionName]){if(this._fin=!(128&~t[0]),this._opcode=15&t[0],this._payloadLength=127&t[1],0===this._opcode){if(s){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(!this._fragmented){return void e(this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE"))}this._opcode=this._fragmented}else if(1===this._opcode||2===this._opcode){if(this._fragmented){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}this._compressed=s}else{if(!(this._opcode>7&&this._opcode<11)){return void e(this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE"))}if(!this._fin){return void e(this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN"))}if(s){return void e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}if(this._payloadLength>125||8===this._opcode&&1===this._payloadLength){return void e(this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"))}}if(this._fin||this._fragmented||(this._fragmented=this._opcode),this._masked=!(128&~t[1]),this._isServer){if(!this._masked){return void e(this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK"))}}else if(this._masked){return void e(this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK"))}126===this._payloadLength?this._state=1:127===this._payloadLength?this._state=2:this.haveLength(e)}else{e(this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1"))}}getPayloadLength16(e){this._bufferedBytes<2?this._loop=!1:(this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e))}getPayloadLength64(e){if(this._bufferedBytes<8)return void(this._loop=!1);const t=this.consume(8),s=t.readUInt32BE(0);if(s>Math.pow(2,21)-1){e(this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"))}else this._payloadLength=s*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){e(this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"))}else this._masked?this._state=3:this._state=4}getMask(){this._bufferedBytes<4?this._loop=!1:(this._mask=this.consume(4),this._state=4)}getData(e){let t=oe;if(this._payloadLength){if(this._bufferedBytes7)this.controlMessage(t,e);else{if(this._compressed)return this._state=5,void this.decompress(t,e);t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}}decompress(e,t){this._extensions[ie.extensionName].decompress(e,this._fin,((e,s)=>{if(e)return t(e);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){const e=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");return void t(e)}this._fragments.push(s)}this.dataMessage(t),0===this._state&&this.startLoop(t)}))}dataMessage(e){if(!this._fin)return void(this._state=0);const t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],2===this._opcode){let r;r="nodebuffer"===this._binaryType?he(s,t):"arraybuffer"===this._binaryType?le(he(s,t)):"blob"===this._binaryType?new Blob(s):s,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",r,!0),this._state=0,this.startLoop(e)})))}else{const r=he(s,t);if(!this._skipUTF8Validation&&!de(r)){const t=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void e(t)}5===this._state||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=0):(this._state=6,setImmediate((()=>{this.emit("message",r,!1),this._state=0,this.startLoop(e)})))}}controlMessage(e,t){if(8!==this._opcode)this._allowSynchronousEvents?(this.emit(9===this._opcode?"ping":"pong",e),this._state=0):(this._state=6,setImmediate((()=>{this.emit(9===this._opcode?"ping":"pong",e),this._state=0,this.startLoop(t)})));else{if(0===e.length)this._loop=!1,this.emit("conclude",1005,oe),this.end();else{const s=e.readUInt16BE(0);if(!ue(s)){const e=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");return void t(e)}const r=new pe(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!de(r)){const e=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");return void t(e)}this._loop=!1,this.emit("conclude",s,r),this.end()}this._state=0}}createError(e,t,s,r,i){this._loop=!1,this._errored=!0;const n=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(n,this.createError),n.code=i,n[ae]=r,n}};const{randomFillSync:ge}=i,_e=X,{EMPTY_BUFFER:be,kWebSocket:ye,NOOP:we}=T,{isBlob:ke,isValidStatusCode:ve}=se,{mask:Se,toBuffer:Ee}=C,Ne=Symbol("kByteLength"),Te=Buffer.alloc(4),Ie=8192;let Oe,xe=Ie;var Be=class e{constructor(e,t,s){this._extensions=t||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=0,this.onerror=we,this[ye]=void 0}static frame(e,t){let s,r,i=!1,n=2,o=!1;t.mask&&(s=t.maskBuffer||Te,t.generateMask?t.generateMask(s):(xe===Ie&&(void 0===Oe&&(Oe=Buffer.alloc(Ie)),ge(Oe,0,Ie),xe=0),s[0]=Oe[xe++],s[1]=Oe[xe++],s[2]=Oe[xe++],s[3]=Oe[xe++]),o=!(s[0]|s[1]|s[2]|s[3]),n=6),"string"==typeof e?r=t.mask&&!o||void 0===t[Ne]?(e=Buffer.from(e)).length:t[Ne]:(r=e.length,i=t.mask&&t.readOnly&&!o);let a=r;r>=65536?(n+=8,a=127):r>125&&(n+=2,a=126);const c=Buffer.allocUnsafe(i?r+n:n);return c[0]=t.fin?128|t.opcode:t.opcode,t.rsv1&&(c[0]|=64),c[1]=a,126===a?c.writeUInt16BE(r,2):127===a&&(c[2]=c[3]=0,c.writeUIntBE(r,4,6)),t.mask?(c[1]|=128,c[n-4]=s[0],c[n-3]=s[1],c[n-2]=s[2],c[n-1]=s[3],o?[c,e]:i?(Se(e,s,c,n,r),[c]):(Se(e,s,e,0,r),[c,e])):[c,e]}close(t,s,r,i){let n;if(void 0===t)n=be;else{if("number"!=typeof t||!ve(t))throw new TypeError("First argument must be a valid error code number");if(void 0!==s&&s.length){const e=Buffer.byteLength(s);if(e>123)throw new RangeError("The message must not be greater than 123 bytes");n=Buffer.allocUnsafe(2+e),n.writeUInt16BE(t,0),"string"==typeof s?n.write(s,2):n.set(s,2)}else n=Buffer.allocUnsafe(2),n.writeUInt16BE(t,0)}const o={[Ne]:n.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};0!==this._state?this.enqueue([this.dispatch,n,!1,o,i]):this.sendFrame(e.frame(n,o),i)}ping(t,s,r){let i,n;if("string"==typeof t?(i=Buffer.byteLength(t),n=!1):ke(t)?(i=t.size,n=!1):(i=(t=Ee(t)).length,n=Ee.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Ne]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};ke(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}pong(t,s,r){let i,n;if("string"==typeof t?(i=Buffer.byteLength(t),n=!1):ke(t)?(i=t.size,n=!1):(i=(t=Ee(t)).length,n=Ee.readOnly),i>125)throw new RangeError("The data size must not be greater than 125 bytes");const o={[Ne]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};ke(t)?0!==this._state?this.enqueue([this.getBlobData,t,!1,o,r]):this.getBlobData(t,!1,o,r):0!==this._state?this.enqueue([this.dispatch,t,!1,o,r]):this.sendFrame(e.frame(t,o),r)}send(e,t,s){const r=this._extensions[_e.extensionName];let i,n,o=t.binary?2:1,a=t.compress;"string"==typeof e?(i=Buffer.byteLength(e),n=!1):ke(e)?(i=e.size,n=!1):(i=(e=Ee(e)).length,n=Ee.readOnly),this._firstFragment?(this._firstFragment=!1,a&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(a=i>=r._threshold),this._compress=a):(a=!1,o=0),t.fin&&(this._firstFragment=!0);const c={[Ne]:i,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:n,rsv1:a};ke(e)?0!==this._state?this.enqueue([this.getBlobData,e,this._compress,c,s]):this.getBlobData(e,this._compress,c,s):0!==this._state?this.enqueue([this.dispatch,e,this._compress,c,s]):this.dispatch(e,this._compress,c,s)}getBlobData(t,s,r,i){this._bufferedBytes+=r[Ne],this._state=2,t.arrayBuffer().then((t=>{if(this._socket.destroyed){const e=new Error("The socket was closed while the blob was being read");return void process.nextTick(Pe,this,e,i)}this._bufferedBytes-=r[Ne];const n=Ee(t);s?this.dispatch(n,s,r,i):(this._state=0,this.sendFrame(e.frame(n,r),i),this.dequeue())})).catch((e=>{process.nextTick(Ce,this,e,i)}))}dispatch(t,s,r,i){if(!s)return void this.sendFrame(e.frame(t,r),i);const n=this._extensions[_e.extensionName];this._bufferedBytes+=r[Ne],this._state=1,n.compress(t,r.fin,((t,s)=>{if(this._socket.destroyed){Pe(this,new Error("The socket was closed while data was being compressed"),i)}else this._bufferedBytes-=r[Ne],this._state=0,r.readOnly=!1,this.sendFrame(e.frame(s,r),i),this.dequeue()}))}dequeue(){for(;0===this._state&&this._queue.length;){const e=this._queue.shift();this._bufferedBytes-=e[3][Ne],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Ne],this._queue.push(e)}sendFrame(e,t){2===e.length?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};function Pe(e,t,s){"function"==typeof s&&s(t);for(let s=0;s{let s=e[t];return Array.isArray(s)||(s=[s]),s.map((e=>[t].concat(Object.keys(e).map((t=>{let s=e[t];return Array.isArray(s)||(s=[s]),s.map((e=>!0===e?t:`${t}=${e}`)).join("; ")}))).join("; "))).join(", ")})).join(", ")},parse:function(e){const t=Object.create(null);let s,r,i=Object.create(null),n=!1,o=!1,a=!1,c=-1,h=-1,l=-1,f=0;for(;f0&&e.unshift(t),e.on("close",Qt),e.on("data",qt),e.on("end",Xt),e.on("error",Kt),this._readyState=Ot.OPEN,this.emit("open")}emitClose(){if(!this._socket)return this._readyState=Ot.CLOSED,void this.emit("close",this._closeCode,this._closeMessage);this._extensions[at.extensionName]&&this._extensions[at.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=Ot.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==Ot.CLOSED)if(this.readyState!==Ot.CONNECTING)this.readyState!==Ot.CLOSING?(this._readyState=Ot.CLOSING,this._sender.close(e,t,!this._isServer,(e=>{e||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())})),Gt(this)):this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();else{const e="WebSocket was closed before the connection was established";Lt(this,this._req,e)}}pause(){this.readyState!==Ot.CONNECTING&&this.readyState!==Ot.CLOSED&&(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===Ot.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===Ot.OPEN?(void 0===t&&(t=!this._isServer),this._sender.ping(e||ut,t,s)):Ut(this,e,s)}pong(e,t,s){if(this.readyState===Ot.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");"function"==typeof e?(s=e,e=t=void 0):"function"==typeof t&&(s=t,t=void 0),"number"==typeof e&&(e=e.toString()),this.readyState===Ot.OPEN?(void 0===t&&(t=!this._isServer),this._sender.pong(e||ut,t,s)):Ut(this,e,s)}resume(){this.readyState!==Ot.CONNECTING&&this.readyState!==Ot.CLOSED&&(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===Ot.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if("function"==typeof t&&(s=t,t={}),"number"==typeof e&&(e=e.toString()),this.readyState!==Ot.OPEN)return void Ut(this,e,s);const r={binary:"string"!=typeof e,mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[at.extensionName]||(r.compress=!1),this._sender.send(e||ut,r,s)}terminate(){if(this.readyState!==Ot.CLOSED)if(this.readyState!==Ot.CONNECTING)this._socket&&(this._readyState=Ot.CLOSING,this._socket.destroy());else{const e="WebSocket was closed before the connection was established";Lt(this,this._req,e)}}}function xt(e,t,s,r){const i={allowSynchronousEvents:!0,autoPong:!0,protocolVersion:Nt[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...r,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(e._autoPong=i.autoPong,!Nt.includes(i.protocolVersion))throw new RangeError(`Unsupported protocol version: ${i.protocolVersion} (supported versions: ${Nt.join(", ")})`);let n;if(t instanceof ot)n=t;else try{n=new ot(t)}catch(e){throw new SyntaxError(`Invalid URL: ${t}`)}"http:"===n.protocol?n.protocol="ws:":"https:"===n.protocol&&(n.protocol="wss:"),e._url=n.href;const o="wss:"===n.protocol,a="ws+unix:"===n.protocol;let c;if("ws:"===n.protocol||o||a?a&&!n.pathname?c="The URL's pathname is empty":n.hash&&(c="The URL contains a fragment identifier"):c='The URL\'s protocol must be one of "ws:", "wss:", "http:", "https", or "ws+unix:"',c){const t=new SyntaxError(c);if(0===e._redirects)throw t;return void Bt(e,t)}const h=o?443:80,l=it(16).toString("base64"),f=o?et.request:tt.request,u=new Set;let d,p;if(i.createConnection=i.createConnection||(o?Ct:Pt),i.defaultPort=i.defaultPort||h,i.port=n.port||h,i.host=n.hostname.startsWith("[")?n.hostname.slice(1,-1):n.hostname,i.headers={...i.headers,"Sec-WebSocket-Version":i.protocolVersion,"Sec-WebSocket-Key":l,Connection:"Upgrade",Upgrade:"websocket"},i.path=n.pathname+n.search,i.timeout=i.handshakeTimeout,i.perMessageDeflate&&(d=new at(!0!==i.perMessageDeflate?i.perMessageDeflate:{},!1,i.maxPayload),i.headers["Sec-WebSocket-Extensions"]=kt({[at.extensionName]:d.offer()})),s.length){for(const e of s){if("string"!=typeof e||!It.test(e)||u.has(e))throw new SyntaxError("An invalid or duplicated subprotocol was specified");u.add(e)}i.headers["Sec-WebSocket-Protocol"]=s.join(",")}if(i.origin&&(i.protocolVersion<13?i.headers["Sec-WebSocket-Origin"]=i.origin:i.headers.Origin=i.origin),(n.username||n.password)&&(i.auth=`${n.username}:${n.password}`),a){const e=i.path.split(":");i.socketPath=e[0],i.path=e[1]}if(i.followRedirects){if(0===e._redirects){e._originalIpc=a,e._originalSecure=o,e._originalHostOrSocketPath=a?i.socketPath:n.host;const t=r&&r.headers;if(r={...r,headers:{}},t)for(const[e,s]of Object.entries(t))r.headers[e.toLowerCase()]=s}else if(0===e.listenerCount("redirect")){const t=a?!!e._originalIpc&&i.socketPath===e._originalHostOrSocketPath:!e._originalIpc&&n.host===e._originalHostOrSocketPath;(!t||e._originalSecure&&!o)&&(delete i.headers.authorization,delete i.headers.cookie,t||delete i.headers.host,i.auth=void 0)}i.auth&&!r.headers.authorization&&(r.headers.authorization="Basic "+Buffer.from(i.auth).toString("base64")),p=e._req=f(i),e._redirects&&e.emit("redirect",e.url,p)}else p=e._req=f(i);i.timeout&&p.on("timeout",(()=>{Lt(e,p,"Opening handshake has timed out")})),p.on("error",(t=>{null===p||p[Et]||(p=e._req=null,Bt(e,t))})),p.on("response",(n=>{const o=n.headers.location,a=n.statusCode;if(o&&i.followRedirects&&a>=300&&a<400){if(++e._redirects>i.maxRedirects)return void Lt(e,p,"Maximum redirects exceeded");let n;p.abort();try{n=new ot(o,t)}catch(t){const s=new SyntaxError(`Invalid URL: ${o}`);return void Bt(e,s)}xt(e,n,s,r)}else e.emit("unexpected-response",p,n)||Lt(e,p,`Unexpected server response: ${n.statusCode}`)})),p.on("upgrade",((t,s,r)=>{if(e.emit("upgrade",t),e.readyState!==Ot.CONNECTING)return;p=e._req=null;const n=t.headers.upgrade;if(void 0===n||"websocket"!==n.toLowerCase())return void Lt(e,s,"Invalid Upgrade header");const o=nt("sha1").update(l+dt).digest("base64");if(t.headers["sec-websocket-accept"]!==o)return void Lt(e,s,"Invalid Sec-WebSocket-Accept header");const a=t.headers["sec-websocket-protocol"];let c;if(void 0!==a?u.size?u.has(a)||(c="Server sent an invalid subprotocol"):c="Server sent a subprotocol but none was requested":u.size&&(c="Server sent no subprotocol"),c)return void Lt(e,s,c);a&&(e._protocol=a);const h=t.headers["sec-websocket-extensions"];if(void 0!==h){if(!d){return void Lt(e,s,"Server sent a Sec-WebSocket-Extensions header but no extension was requested")}let t;try{t=vt(h)}catch(t){return void Lt(e,s,"Invalid Sec-WebSocket-Extensions header")}const r=Object.keys(t);if(1!==r.length||r[0]!==at.extensionName){return void Lt(e,s,"Server indicated an extension that was not requested")}try{d.accept(t[at.extensionName])}catch(t){return void Lt(e,s,"Invalid Sec-WebSocket-Extensions header")}e._extensions[at.extensionName]=d}e.setSocket(s,r,{allowSynchronousEvents:i.allowSynchronousEvents,generateMask:i.generateMask,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation})})),i.finishRequest?i.finishRequest(p,e):p.end()}function Bt(e,t){e._readyState=Ot.CLOSING,e._errorEmitted=!0,e.emit("error",t),e.emitClose()}function Pt(e){return e.path=e.socketPath,st.connect(e)}function Ct(e){return e.path=void 0,e.servername||""===e.servername||(e.servername=st.isIP(e.host)?"":e.host),rt.connect(e)}function Lt(e,t,s){e._readyState=Ot.CLOSING;const r=new Error(s);Error.captureStackTrace(r,Lt),t.setHeader?(t[Et]=!0,t.abort(),t.socket&&!t.socket.destroyed&&t.socket.destroy(),process.nextTick(Bt,e,r)):(t.destroy(r),t.once("error",e.emit.bind(e,"error")),t.once("close",e.emitClose.bind(e)))}function Ut(e,t,s){if(t){const s=lt(t)?t.size:St(t).length;e._socket?e._sender._bufferedBytes+=s:e._bufferedAmount+=s}if(s){const t=new Error(`WebSocket is not open: readyState ${e.readyState} (${Tt[e.readyState]})`);process.nextTick(s,t)}}function Rt(e,t){const s=this[_t];s._closeFrameReceived=!0,s._closeMessage=t,s._closeCode=e,void 0!==s._socket[_t]&&(s._socket.removeListener("data",qt),process.nextTick(Wt,s._socket),1005===e?s.close():s.close(e,t))}function At(){const e=this[_t];e.isPaused||e._socket.resume()}function Dt(e){const t=this[_t];void 0!==t._socket[_t]&&(t._socket.removeListener("data",qt),process.nextTick(Wt,t._socket),t.close(e[gt])),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e))}function Ft(){this[_t].emitClose()}function Vt(e,t){this[_t].emit("message",e,t)}function jt(e){const t=this[_t];t._autoPong&&t.pong(e,!this._isServer,bt),t.emit("ping",e)}function Mt(e){this[_t].emit("pong",e)}function Wt(e){e.resume()}function $t(e){const t=this[_t];t.readyState!==Ot.CLOSED&&(t.readyState===Ot.OPEN&&(t._readyState=Ot.CLOSING,Gt(t)),this._socket.end(),t._errorEmitted||(t._errorEmitted=!0,t.emit("error",e)))}function Gt(e){e._closeTimer=setTimeout(e._socket.destroy.bind(e._socket),3e4)}function Qt(){const e=this[_t];let t;this.removeListener("close",Qt),this.removeListener("data",qt),this.removeListener("end",Xt),e._readyState=Ot.CLOSING,this._readableState.endEmitted||e._closeFrameReceived||e._receiver._writableState.errorEmitted||null===(t=e._socket.read())||e._receiver.write(t),e._receiver.end(),this[_t]=void 0,clearTimeout(e._closeTimer),e._receiver._writableState.finished||e._receiver._writableState.errorEmitted?e.emitClose():(e._receiver.on("error",Ft),e._receiver.on("finish",Ft))}function qt(e){this[_t]._receiver.write(e)||this.pause()}function Xt(){const e=this[_t];e._readyState=Ot.CLOSING,e._receiver.end(),this.end()}function Kt(){const e=this[_t];this.removeListener("error",Kt),this.on("error",bt),e&&(e._readyState=Ot.CLOSING,this.destroy())}Object.defineProperty(Ot,"CONNECTING",{enumerable:!0,value:Tt.indexOf("CONNECTING")}),Object.defineProperty(Ot.prototype,"CONNECTING",{enumerable:!0,value:Tt.indexOf("CONNECTING")}),Object.defineProperty(Ot,"OPEN",{enumerable:!0,value:Tt.indexOf("OPEN")}),Object.defineProperty(Ot.prototype,"OPEN",{enumerable:!0,value:Tt.indexOf("OPEN")}),Object.defineProperty(Ot,"CLOSING",{enumerable:!0,value:Tt.indexOf("CLOSING")}),Object.defineProperty(Ot.prototype,"CLOSING",{enumerable:!0,value:Tt.indexOf("CLOSING")}),Object.defineProperty(Ot,"CLOSED",{enumerable:!0,value:Tt.indexOf("CLOSED")}),Object.defineProperty(Ot.prototype,"CLOSED",{enumerable:!0,value:Tt.indexOf("CLOSED")}),["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((e=>{Object.defineProperty(Ot.prototype,e,{enumerable:!0})})),["open","error","close","message"].forEach((e=>{Object.defineProperty(Ot.prototype,`on${e}`,{enumerable:!0,get(){for(const t of this.listeners(e))if(t[pt])return t[mt];return null},set(t){for(const t of this.listeners(e))if(t[pt]){this.removeListener(e,t);break}"function"==typeof t&&this.addEventListener(e,t,{[pt]:!0})}})})),Ot.prototype.addEventListener=yt,Ot.prototype.removeEventListener=wt;const Yt=k(Ot);class Zt{cb=new w(500);isAvailable=!1;wrapperSession;constructor(e){this.wrapperSession=e}randText(e){let t="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";for(let r=0;r{}){return new Promise(((o,a)=>{const c=setTimeout((()=>{a(new Error(`sendCommand timed out after ${i} ms for ${e} with trace_id ${s}`))}),i);this.registerCallback(s,"send",(async e=>{n(e),r||(clearTimeout(c),o(e))})),r&&this.registerCallback(s,"recv",(async e=>{clearTimeout(c),o(e)})),this.sendCommandImpl(e,t,s)}))}async sendPacket(e,t,s=!1){return new Promise(((r,n)=>{if(!this.available)return void console.error("NapCat.Packet 未初始化!");const o=i.createHash("md5").update(t).digest("hex"),a=(this.randText(4)+o+t).slice(0,t.length/2);this.sendCommand(e,t,a,s,2e4,(async()=>{await this.wrapperSession.getMsgService().sendSsoCmdReqByContend(e,a)})).then((e=>r(e))).catch((e=>n(e)))}))}async sendOidbPacket(e,t=!1){return this.sendPacket(e.cmd,e.data,t)}}class Jt extends Zt{websocket;isConnected=!1;reconnectAttempts=0;maxReconnectAttempts=60;clientUrl="";logger=console;constructor(e){super(e),this.clientUrl="ws://127.0.0.1:8086/ws"}check(){return!0}sendCommandImpl(e,t,s){throw new Error("Method not implemented.")}connect(e){return new Promise(((t,s)=>{this.websocket=new Yt(this.clientUrl),this.websocket.on("error",(e=>{})),this.websocket.onopen=()=>{this.isConnected=!0,this.reconnectAttempts=0,this.logger.log.bind(this.logger)(`[Core] [Packet Server] 已连接到 ${this.clientUrl}`),e(),t()},this.websocket.onerror=e=>{s(new Error(`${e.message}`))},this.websocket.onmessage=e=>{this.handleMessage(e.data).then().catch()},this.websocket.onclose=()=>{this.isConnected=!1,this.attemptReconnect(e)}}))}attemptReconnect(e){try{this.reconnectAttempts{this.connect(e).catch((e=>{this.logger.error.bind(this.logger)(`[Core] [Packet Server] 尝试重连失败:${e.message}`)}))}),5e3*this.reconnectAttempts)):this.logger.error.bind(this.logger)(`[Core] [Packet Server] ${this.clientUrl} 已达到最大重连次数!`)}catch(e){this.logger.error.bind(this.logger)(`[Core] [Packet Server] 重连时出错: ${e.message}`)}}async init(e,t,s){if(!this.isConnected||!this.websocket)throw new Error("WebSocket is not connected");const r={action:"init",pid:e,recv:t,send:s};this.websocket.send(JSON.stringify(r))}async handleMessage(e){try{const t=JSON.parse(e.toString()),s=t.trace_id_md5,r=t?.type??"init",i=this.cb.get(s+r);i&&await i(t.data)}catch(e){this.logger.error.bind(this.logger)(`Error parsing message: ${e}`)}}}class zt extends Zt{supportedPlatforms=["win32.x64","linux.x64","linux.arm64"];MoeHooExport={exports:{}};sendEvent=new w(500);constructor(e){super(e)}get available(){return this.isAvailable}check(){const e=process.platform+"."+process.arch;if(!this.supportedPlatforms.includes(e))return console.warn(`[Core] [Packet:Native] 不支持的平台: ${e}`),!1;const t=d.join(p(u(import.meta.url)),"./moehoo/MoeHoo."+e+".node");return!!m.existsSync(t)||(console.warn(`[Core] [Packet:Native] 缺失运行时文件: ${t}`),!1)}async init(e,t,s){const r=process.platform+"."+process.arch,i=d.join(p(u(import.meta.url)),"./moehoo/MoeHoo."+r+".node"),o=d.join(p(u(import.meta.url)),"./moehoo/MoeHoo.v1.0.0.node");if(m.existsSync(i)&&!m.existsSync(o))try{m.copyFileSync(i,o)}catch(e){}console.debug("moehoo_path:",o),process.dlopen(this.MoeHooExport,o,_.dlopen.RTLD_LAZY),this.MoeHooExport.exports.InitHook?.(s,t,((e,t,s,r,i)=>{const o=n("md5").update(Buffer.from(i,"hex")).digest("hex");if(0===e&&this.cb.get(o+"recv")&&this.sendEvent.put(r,o),1===e&&this.sendEvent.get(r)){const e=this.sendEvent.get(r),t=this.cb.get(e+"recv");t?.({seq:r,cmd:s,hex_data:i})}})),console.debug("MoeHoo init complete"),this.isAvailable=!0}sendCommandImpl(e,t,s){const r=n("md5").update(s).digest("hex");this.MoeHooExport.exports.SendPacket?.(e,t,r),this.cb.get(r+"send")?.({seq:0,cmd:e,hex_data:""})}connect(e){return e(),Promise.resolve()}}function Ht(e){let t=typeof e;if("object"==t){if(Array.isArray(e))return"array";if(null===e)return"null"}return t}let es="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""),ts=[];for(let e=0;e>4,!(128&s))return this.assertBounds(),[e,t];for(let s=3;s<=31;s+=7){let r=this.buf[this.pos++];if(t|=(127&r)<>>r,n=!(i>>>7==0&&0==t),o=255&(n?128|i:i);if(s.push(o),!n)return}const r=e>>>28&15|(7&t)<<4,i=!!(t>>3);if(s.push(255&(i?128|r:r)),i){for(let e=3;e<31;e+=7){const r=t>>>e,i=!(r>>>7==0),n=255&(i?128|r:r);if(s.push(n),!i)return}s.push(t>>>31&1)}}ts["-".charCodeAt(0)]=es.indexOf("+"),ts["_".charCodeAt(0)]=es.indexOf("/"),function(e){e.symbol=Symbol.for("protobuf-ts/unknown"),e.onRead=(s,r,i,n,o)=>{(t(r)?r[e.symbol]:r[e.symbol]=[]).push({no:i,wireType:n,data:o})},e.onWrite=(t,s,r)=>{for(let{no:t,wireType:i,data:n}of e.list(s))r.tag(t,i).raw(n)},e.list=(s,r)=>{if(t(s)){let t=s[e.symbol];return r?t.filter((e=>e.no==r)):t}return[]},e.last=(t,s)=>e.list(t,s).slice(-1)[0];const t=t=>t&&Array.isArray(t[e.symbol])}(ss||(ss={})),function(e){e[e.Varint=0]="Varint",e[e.Bit64=1]="Bit64",e[e.LengthDelimited=2]="LengthDelimited",e[e.StartGroup=3]="StartGroup",e[e.EndGroup=4]="EndGroup",e[e.Bit32=5]="Bit32"}(rs||(rs={}));const os=4294967296;function as(e){let t="-"==e[0];t&&(e=e.slice(1));const s=1e6;let r=0,i=0;function n(t,n){const o=Number(e.slice(t,n));i*=s,r=r*s+o,r>=os&&(i+=r/os|0,r%=os)}return n(-24,-18),n(-18,-12),n(-12,-6),n(-6),[t,r,i]}function cs(e,t){if(t>>>0<=2097151)return""+(os*t+(e>>>0));let s=(e>>>24|t<<8)>>>0&16777215,r=t>>16&65535,i=(16777215&e)+6777216*s+6710656*r,n=s+8147497*r,o=2*r,a=1e7;function c(e,t){let s=e?String(e):"";return t?"0000000".slice(s.length)+s:s}return i>=a&&(n+=Math.floor(i/a),i%=a),n>=a&&(o+=Math.floor(n/a),n%=a),c(o,0)+c(n,o)+c(i,1)}function hs(e,t){if(e>=0){for(;e>127;)t.push(127&e|128),e>>>=7;t.push(e)}else{for(let s=0;s<9;s++)t.push(127&e|128),e>>=7;t.push(1)}}function ls(){let e=this.buf[this.pos++],t=127&e;if(!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<7,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<14,!(128&e))return this.assertBounds(),t;if(e=this.buf[this.pos++],t|=(127&e)<<21,!(128&e))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(15&e)<<28;for(let t=5;128&e&&t<10;t++)e=this.buf[this.pos++];if(128&e)throw new Error("invalid varint");return this.assertBounds(),t>>>0}let fs;function us(e){if(!e)throw new Error("BigInt unavailable, see https://github.com/timostamm/protobuf-ts/blob/v1.0.8/MANUAL.md#bigint-support")}!function(){const e=new DataView(new ArrayBuffer(8)),t=void 0!==globalThis.BigInt&&"function"==typeof e.getBigInt64&&"function"==typeof e.getBigUint64&&"function"==typeof e.setBigInt64&&"function"==typeof e.setBigUint64;fs=t?{MIN:BigInt("-9223372036854775808"),MAX:BigInt("9223372036854775807"),UMIN:BigInt("0"),UMAX:BigInt("18446744073709551615"),C:BigInt,V:e}:void 0}();const ds=/^-?[0-9]+$/,ps=4294967296,ms=2147483648;class gs{constructor(e,t){this.lo=0|e,this.hi=0|t}isZero(){return 0==this.lo&&0==this.hi}toNumber(){let e=this.hi*ps+(this.lo>>>0);if(!Number.isSafeInteger(e))throw new Error("cannot convert to safe number");return e}}class _s extends gs{static from(e){if(fs)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=fs.C(e);case"number":if(0===e)return this.ZERO;e=fs.C(e);case"bigint":if(!e)return this.ZERO;if(efs.UMAX)throw new Error("ulong too large");return fs.V.setBigUint64(0,e,!0),new _s(fs.V.getInt32(0,!0),fs.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!ds.test(e))throw new Error("string is no integer");let[t,s,r]=as(e);if(t)throw new Error("signed value for ulong");return new _s(s,r);case"number":if(0==e)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");if(e<0)throw new Error("signed value for ulong");return new _s(e,e/ps)}throw new Error("unknown value "+typeof e)}toString(){return fs?this.toBigInt().toString():cs(this.lo,this.hi)}toBigInt(){return us(fs),fs.V.setInt32(0,this.lo,!0),fs.V.setInt32(4,this.hi,!0),fs.V.getBigUint64(0,!0)}}_s.ZERO=new _s(0,0);class bs extends gs{static from(e){if(fs)switch(typeof e){case"string":if("0"==e)return this.ZERO;if(""==e)throw new Error("string is no integer");e=fs.C(e);case"number":if(0===e)return this.ZERO;e=fs.C(e);case"bigint":if(!e)return this.ZERO;if(efs.MAX)throw new Error("signed long too large");return fs.V.setBigInt64(0,e,!0),new bs(fs.V.getInt32(0,!0),fs.V.getInt32(4,!0))}else switch(typeof e){case"string":if("0"==e)return this.ZERO;if(e=e.trim(),!ds.test(e))throw new Error("string is no integer");let[t,s,r]=as(e);if(t){if(r>ms||r==ms&&0!=s)throw new Error("signed long too small")}else if(r>=ms)throw new Error("signed long too large");let i=new bs(s,r);return t?i.negate():i;case"number":if(0==e)return this.ZERO;if(!Number.isSafeInteger(e))throw new Error("number is no integer");return e>0?new bs(e,e/ps):new bs(-e,-e/ps).negate()}throw new Error("unknown value "+typeof e)}isNegative(){return!!(this.hi&ms)}negate(){let e=~this.hi,t=this.lo;return t?t=1+~t:e+=1,new bs(t,e)}toString(){if(fs)return this.toBigInt().toString();if(this.isNegative()){let e=this.negate();return"-"+cs(e.lo,e.hi)}return cs(this.lo,this.hi)}toBigInt(){return us(fs),fs.V.setInt32(0,this.lo,!0),fs.V.setInt32(4,this.hi,!0),fs.V.getBigInt64(0,!0)}}bs.ZERO=new bs(0,0);const ys={readUnknownField:!0,readerFactory:e=>new ws(e)};class ws{constructor(e,t){this.varint64=is,this.uint32=ls,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=null!=t?t:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0})}tag(){let e=this.uint32(),t=e>>>3,s=7&e;if(t<=0||s<0||s>5)throw new Error("illegal tag: field no "+t+" wire type "+s);return[t,s]}skip(e){let t=this.pos;switch(e){case rs.Varint:for(;128&this.buf[this.pos++];);break;case rs.Bit64:this.pos+=4;case rs.Bit32:this.pos+=4;break;case rs.LengthDelimited:let t=this.uint32();this.pos+=t;break;case rs.StartGroup:let s;for(;(s=this.tag()[1])!==rs.EndGroup;)this.skip(s);break;default:throw new Error("cant skip wire type "+e)}return this.assertBounds(),this.buf.subarray(t,this.pos)}assertBounds(){if(this.pos>this.len)throw new RangeError("premature EOF")}int32(){return 0|this.uint32()}sint32(){let e=this.uint32();return e>>>1^-(1&e)}int64(){return new bs(...this.varint64())}uint64(){return new _s(...this.varint64())}sint64(){let[e,t]=this.varint64(),s=-(1&e);return e=(e>>>1|(1&t)<<31)^s,t=t>>>1^s,new bs(e,t)}bool(){let[e,t]=this.varint64();return 0!==e||0!==t}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return new _s(this.sfixed32(),this.sfixed32())}sfixed64(){return new bs(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}}function ks(e,t){if(!e)throw new Error(t)}function vs(e){if("number"!=typeof e)throw new Error("invalid int 32: "+typeof e);if(!Number.isInteger(e)||e>2147483647||e<-2147483648)throw new Error("invalid int 32: "+e)}function Ss(e){if("number"!=typeof e)throw new Error("invalid uint 32: "+typeof e);if(!Number.isInteger(e)||e>4294967295||e<0)throw new Error("invalid uint 32: "+e)}function Es(e){if("number"!=typeof e)throw new Error("invalid float 32: "+typeof e);if(Number.isFinite(e)&&(e>34028234663852886e22||e<-34028234663852886e22))throw new Error("invalid float 32: "+e)}const Ns={writeUnknownFields:!0,writerFactory:()=>new Ts};class Ts{constructor(e){this.stack=[],this.textEncoder=null!=e?e:new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(Ss(e);e>127;)this.buf.push(127&e|128),e>>>=7;return this.buf.push(e),this}int32(e){return vs(e),hs(e,this.buf),this}bool(e){return this.buf.push(e?1:0),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){Es(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){Ss(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){vs(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return vs(e),hs(e=(e<<1^e>>31)>>>0,this.buf),this}sfixed64(e){let t=new Uint8Array(8),s=new DataView(t.buffer),r=bs.from(e);return s.setInt32(0,r.lo,!0),s.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),s=new DataView(t.buffer),r=_s.from(e);return s.setInt32(0,r.lo,!0),s.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=bs.from(e);return ns(t.lo,t.hi,this.buf),this}sint64(e){let t=bs.from(e),s=t.hi>>31;return ns(t.lo<<1^s,(t.hi<<1|t.lo>>>31)^s,this.buf),this}uint64(e){let t=_s.from(e);return ns(t.lo,t.hi,this.buf),this}}const Is={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0},Os={ignoreUnknownFields:!1};const xs=Symbol.for("protobuf-ts/message-type");function Bs(e){let t=!1;const s=[];for(let r=0;r!r.includes(e))))return!1;if(!s&&r.some((e=>!i.known.includes(e))))return!1;if(t<1)return!0;for(const r of i.oneofs){const i=e[r];if(!Rs(i))return!1;if(void 0===i.oneofKind)continue;const n=this.fields.find((e=>e.localName===i.oneofKind));if(!n)return!1;if(!this.field(i[i.oneofKind],n,s,t))return!1}for(const r of this.fields)if(void 0===r.oneof&&!this.field(e[r.localName],r,s,t))return!1;return!0}field(e,t,s,r){let i=t.repeat;switch(t.kind){case"scalar":return void 0===e?t.opt:i?this.scalars(e,t.T,r,t.L):this.scalar(e,t.T,t.L);case"enum":return void 0===e?t.opt:i?this.scalars(e,Ps.INT32,r):this.scalar(e,Ps.INT32);case"message":return void 0===e||(i?this.messages(e,t.T(),s,r):this.message(e,t.T(),s,r));case"map":if("object"!=typeof e||null===e)return!1;if(r<2)return!0;if(!this.mapKeys(e,t.K,r))return!1;switch(t.V.kind){case"scalar":return this.scalars(Object.values(e),t.V.T,r,t.V.L);case"enum":return this.scalars(Object.values(e),Ps.INT32,r);case"message":return this.messages(Object.values(e),t.V.T(),s,r)}}return!0}message(e,t,s,r){return s?t.isAssignable(e,r):t.is(e,r)}messages(e,t,s,r){if(!Array.isArray(e))return!1;if(r<2)return!0;if(s){for(let s=0;sparseInt(e))),t,s);case Ps.BOOL:return this.scalars(r.slice(0,s).map((e=>"true"==e||"false"!=e&&e)),t,s);default:return this.scalars(r,t,s,Cs.STRING)}}}function Ds(e,t){switch(t){case Cs.BIGINT:return e.toBigInt();case Cs.NUMBER:return e.toNumber();default:return e.toString()}}class Fs{constructor(e){this.info=e}prepare(){var e;if(void 0===this.fMap){this.fMap={};const t=null!==(e=this.info.fields)&&void 0!==e?e:[];for(const e of t)this.fMap[e.name]=e,this.fMap[e.jsonName]=e,this.fMap[e.localName]=e}}assert(e,t,s){if(!e){let e=Ht(s);throw"number"!=e&&"boolean"!=e||(e=s.toString()),new Error(`Cannot parse JSON ${e} for ${this.info.typeName}#${t}`)}}read(e,t,s){this.prepare();const r=[];for(const[n,o]of Object.entries(e)){const e=this.fMap[n];if(!e){if(!s.ignoreUnknownFields)throw new Error(`Found unknown field while reading ${this.info.typeName} from JSON format. JSON key: ${n}`);continue}const a=e.localName;let c;if(e.oneof){if(null===o&&("enum"!==e.kind||"google.protobuf.NullValue"!==e.T()[0]))continue;if(r.includes(e.oneof))throw new Error(`Multiple members of the oneof group "${e.oneof}" of ${this.info.typeName} are present in JSON.`);r.push(e.oneof),c=t[e.oneof]={oneofKind:a}}else c=t;if("map"==e.kind){if(null===o)continue;this.assert(null!==(i=o)&&"object"==typeof i&&!Array.isArray(i),e.name,o);const t=c[a];for(const[r,i]of Object.entries(o)){let n;switch(this.assert(null!==i,e.name+" map value",null),e.V.kind){case"message":n=e.V.T().internalJsonRead(i,s);break;case"enum":if(n=this.enum(e.V.T(),i,e.name,s.ignoreUnknownFields),!1===n)continue;break;case"scalar":n=this.scalar(i,e.V.T,e.V.L,e.name)}this.assert(void 0!==n,e.name+" map value",i);let o=r;e.K==Ps.BOOL&&(o="true"==o||"false"!=o&&o),o=this.scalar(o,e.K,Cs.STRING,e.name).toString(),t[o]=n}}else if(e.repeat){if(null===o)continue;this.assert(Array.isArray(o),e.name,o);const t=c[a];for(const r of o){let i;switch(this.assert(null!==r,e.name,null),e.kind){case"message":i=e.T().internalJsonRead(r,s);break;case"enum":if(i=this.enum(e.T(),r,e.name,s.ignoreUnknownFields),!1===i)continue;break;case"scalar":i=this.scalar(r,e.T,e.L,e.name)}this.assert(void 0!==i,e.name,o),t.push(i)}}else switch(e.kind){case"message":if(null===o&&"google.protobuf.Value"!=e.T().typeName){this.assert(void 0===e.oneof,e.name+" (oneof member)",null);continue}c[a]=e.T().internalJsonRead(o,s,c[a]);break;case"enum":let t=this.enum(e.T(),o,e.name,s.ignoreUnknownFields);if(!1===t)continue;c[a]=t;break;case"scalar":c[a]=this.scalar(o,e.T,e.L,e.name)}}var i}enum(e,t,s,r){if("google.protobuf.NullValue"==e[0]&&ks(null===t||"NULL_VALUE"===t,`Unable to parse field ${this.info.typeName}#${s}, enum ${e[0]} only accepts null.`),null===t)return 0;switch(typeof t){case"number":return ks(Number.isInteger(t),`Unable to parse field ${this.info.typeName}#${s}, enum can only be integral number, got ${t}.`),t;case"string":let i=t;e[2]&&t.substring(0,e[2].length)===e[2]&&(i=t.substring(e[2].length));let n=e[1][i];return(void 0!==n||!r)&&(ks("number"==typeof n,`Unable to parse field ${this.info.typeName}#${s}, enum ${e[0]} has no value for "${t}".`),n)}ks(!1,`Unable to parse field ${this.info.typeName}#${s}, cannot parse enum value from ${typeof t}".`)}scalar(e,t,s,r){let i;try{switch(t){case Ps.DOUBLE:case Ps.FLOAT:if(null===e)return 0;if("NaN"===e)return Number.NaN;if("Infinity"===e)return Number.POSITIVE_INFINITY;if("-Infinity"===e)return Number.NEGATIVE_INFINITY;if(""===e){i="empty string";break}if("string"==typeof e&&e.trim().length!==e.length){i="extra whitespace";break}if("string"!=typeof e&&"number"!=typeof e)break;let r=Number(e);if(Number.isNaN(r)){i="not a number";break}if(!Number.isFinite(r)){i="too large or small";break}return t==Ps.FLOAT&&Es(r),r;case Ps.INT32:case Ps.FIXED32:case Ps.SFIXED32:case Ps.SINT32:case Ps.UINT32:if(null===e)return 0;let n;if("number"==typeof e?n=e:""===e?i="empty string":"string"==typeof e&&(e.trim().length!==e.length?i="extra whitespace":n=Number(e)),void 0===n)break;return t==Ps.UINT32?Ss(n):vs(n),n;case Ps.INT64:case Ps.SFIXED64:case Ps.SINT64:if(null===e)return Ds(bs.ZERO,s);if("number"!=typeof e&&"string"!=typeof e)break;return Ds(bs.from(e),s);case Ps.FIXED64:case Ps.UINT64:if(null===e)return Ds(_s.ZERO,s);if("number"!=typeof e&&"string"!=typeof e)break;return Ds(_s.from(e),s);case Ps.BOOL:if(null===e)return!1;if("boolean"!=typeof e)break;return e;case Ps.STRING:if(null===e)return"";if("string"!=typeof e){i="extra whitespace";break}try{encodeURIComponent(e)}catch(i){i="invalid UTF8";break}return e;case Ps.BYTES:if(null===e||""===e)return new Uint8Array(0);if("string"!=typeof e)break;return function(e){let t=3*e.length/4;"="==e[e.length-2]?t-=2:"="==e[e.length-1]&&(t-=1);let s,r=new Uint8Array(t),i=0,n=0,o=0;for(let t=0;t>4,o=s,n=2;break;case 2:r[i++]=(15&o)<<4|(60&s)>>2,o=s,n=3;break;case 3:r[i++]=(3&o)<<6|s,n=0}}if(1==n)throw Error("invalid base64 string.");return r.subarray(0,i)}(e)}}catch(e){i=e.message}this.assert(!1,r+(i?" - "+i:""),e)}}class Vs{constructor(e){var t;this.fields=null!==(t=e.fields)&&void 0!==t?t:[]}write(e,t){const s={},r=e;for(const e of this.fields){if(!e.oneof){let i=this.field(e,r[e.localName],t);void 0!==i&&(s[t.useProtoFieldName?e.name:e.jsonName]=i);continue}const i=r[e.oneof];if(i.oneofKind!==e.localName)continue;const n="scalar"==e.kind||"enum"==e.kind?Object.assign(Object.assign({},t),{emitDefaultValues:!0}):t;let o=this.field(e,i[e.localName],n);ks(void 0!==o),s[t.useProtoFieldName?e.name:e.jsonName]=o}return s}field(e,t,s){let r;if("map"==e.kind){ks("object"==typeof t&&null!==t);const i={};switch(e.V.kind){case"scalar":for(const[s,r]of Object.entries(t)){const t=this.scalar(e.V.T,r,e.name,!1,!0);ks(void 0!==t),i[s.toString()]=t}break;case"message":const r=e.V.T();for(const[n,o]of Object.entries(t)){const t=this.message(r,o,e.name,s);ks(void 0!==t),i[n.toString()]=t}break;case"enum":const n=e.V.T();for(const[r,o]of Object.entries(t)){ks(void 0===o||"number"==typeof o);const t=this.enum(n,o,e.name,!1,!0,s.enumAsInteger);ks(void 0!==t),i[r.toString()]=t}}(s.emitDefaultValues||Object.keys(i).length>0)&&(r=i)}else if(e.repeat){ks(Array.isArray(t));const i=[];switch(e.kind){case"scalar":for(let s=0;s0||s.emitDefaultValues)&&(r=i)}else switch(e.kind){case"scalar":r=this.scalar(e.T,t,e.name,e.opt,s.emitDefaultValues);break;case"enum":r=this.enum(e.T(),t,e.name,e.opt,s.emitDefaultValues,s.enumAsInteger);break;case"message":r=this.message(e.T(),t,e.name,s)}return r}enum(e,t,s,r,i,n){if("google.protobuf.NullValue"==e[0])return i||r?null:void 0;if(void 0!==t){if(0!==t||i||r)return ks("number"==typeof t),ks(Number.isInteger(t)),n||!e[1].hasOwnProperty(t)?t:e[2]?e[2]+e[1][t]:e[1][t]}else ks(r)}message(e,t,s,r){return void 0===t?r.emitDefaultValues?null:void 0:e.internalJsonWrite(t,r)}scalar(e,t,s,r,i){if(void 0===t)return void ks(r);const n=i||r;switch(e){case Ps.INT32:case Ps.SFIXED32:case Ps.SINT32:return 0===t?n?0:void 0:(vs(t),t);case Ps.FIXED32:case Ps.UINT32:return 0===t?n?0:void 0:(Ss(t),t);case Ps.FLOAT:Es(t);case Ps.DOUBLE:return 0===t?n?0:void 0:(ks("number"==typeof t),Number.isNaN(t)?"NaN":t===Number.POSITIVE_INFINITY?"Infinity":t===Number.NEGATIVE_INFINITY?"-Infinity":t);case Ps.STRING:return""===t?n?"":void 0:(ks("string"==typeof t),t);case Ps.BOOL:return!1===t?!n&&void 0:(ks("boolean"==typeof t),t);case Ps.UINT64:case Ps.FIXED64:ks("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let e=_s.from(t);if(e.isZero()&&!n)return;return e.toString();case Ps.INT64:case Ps.SFIXED64:case Ps.SINT64:ks("number"==typeof t||"string"==typeof t||"bigint"==typeof t);let s=bs.from(t);if(s.isZero()&&!n)return;return s.toString();case Ps.BYTES:return ks(t instanceof Uint8Array),t.byteLength?function(e){let t,s="",r=0,i=0;for(let n=0;n>2],i=(3&t)<<4,r=1;break;case 1:s+=es[i|t>>4],i=(15&t)<<2,r=2;break;case 2:s+=es[i|t>>6],s+=es[63&t],r=0}return r&&(s+=es[i],s+="=",1==r&&(s+="=")),s}(t):n?"":void 0}}}function js(e,t=Cs.STRING){switch(e){case Ps.BOOL:return!1;case Ps.UINT64:case Ps.FIXED64:return Ds(_s.ZERO,t);case Ps.INT64:case Ps.SFIXED64:case Ps.SINT64:return Ds(bs.ZERO,t);case Ps.DOUBLE:case Ps.FLOAT:return 0;case Ps.BYTES:return new Uint8Array(0);case Ps.STRING:return"";default:return 0}}class Ms{constructor(e){this.info=e}prepare(){var e;if(!this.fieldNoToField){const t=null!==(e=this.info.fields)&&void 0!==e?e:[];this.fieldNoToField=new Map(t.map((e=>[e.no,e])))}}read(e,t,s,r){this.prepare();const i=void 0===r?e.len:e.pos+r;for(;e.pose.no-t.no))}}write(e,t,s){this.prepare();for(const r of this.fields){let i,n,o=r.repeat,a=r.localName;if(r.oneof){const t=e[r.oneof];if(t.oneofKind!==a)continue;i=t[a],n=!0}else i=e[a],n=!1;switch(r.kind){case"scalar":case"enum":let e="enum"==r.kind?Ps.INT32:r.T;if(o)if(ks(Array.isArray(i)),o==Ls.PACKED)this.packed(t,e,r.no,i);else for(const s of i)this.scalar(t,e,r.no,s,!0);else void 0===i?ks(r.opt):this.scalar(t,e,r.no,i,n||r.opt);break;case"message":if(o){ks(Array.isArray(i));for(const e of i)this.message(t,s,r.T(),r.no,e)}else this.message(t,s,r.T(),r.no,i);break;case"map":ks("object"==typeof i&&null!==i);for(const[e,n]of Object.entries(i))this.mapEntry(t,s,r,e,n)}}let r=s.writeUnknownFields;!1!==r&&(!0===r?ss.onWrite:r)(this.info.typeName,e,t)}mapEntry(e,t,s,r,i){e.tag(s.no,rs.LengthDelimited),e.fork();let n=r;switch(s.K){case Ps.INT32:case Ps.FIXED32:case Ps.UINT32:case Ps.SFIXED32:case Ps.SINT32:n=Number.parseInt(r);break;case Ps.BOOL:ks("true"==r||"false"==r),n="true"==r}switch(this.scalar(e,s.K,1,n,!0),s.V.kind){case"scalar":this.scalar(e,s.V.T,2,i,!0);break;case"enum":this.scalar(e,Ps.INT32,2,i,!0);break;case"message":this.message(e,t,s.V.T(),2,i)}e.join()}message(e,t,s,r,i){void 0!==i&&(s.internalBinaryWrite(i,e.tag(r,rs.LengthDelimited).fork(),t),e.join())}scalar(e,t,s,r,i){let[n,o,a]=this.scalarInfo(t,r);a&&!i||(e.tag(s,n),e[o](r))}packed(e,t,s,r){if(!r.length)return;ks(t!==Ps.BYTES&&t!==Ps.STRING),e.tag(s,rs.LengthDelimited),e.fork();let[,i]=this.scalarInfo(t);for(let t=0;t{const s=e[t];if("scalar"===s.kind){const e=s.repeat?[Ps.STRING,Ps.BYTES].includes(s.type)?Ls.UNPACKED:Ls.PACKED:Ls.NO;return{no:s.no,name:t,kind:"scalar",T:s.type,opt:s.optional,repeat:e}}if("message"===s.kind)return{no:s.no,name:t,kind:"message",repeat:s.repeat?Ls.PACKED:Ls.NO,T:()=>Js.getInstance(s.type())._proto_msg}})),this._proto_msg=new Ys("nya",this._field)}static getInstance(e){let t=this.cache.get(e);return t||(t=new Js(e),this.cache.set(e,t)),t}encode(e){return this._proto_msg.toBinary(this._proto_msg.create(e))}decode(e){return this._proto_msg.fromBinary(e)}}class zs{realMsg;constructor(e){this.realMsg=Js.getInstance(e)}encode(e){return this.realMsg.encode(e)}decode(e){return this.realMsg.decode(e)}}const Hs={command:Zs(1,Ps.UINT32),subCommand:Zs(2,Ps.UINT32),body:Zs(4,Ps.BYTES),errorMsg:Zs(5,Ps.STRING,!0),isReserved:Zs(12,Ps.UINT32)};Zs(4,Ps.BYTES);const er={uin:Zs(1,Ps.UINT32),groupUin:Zs(2,Ps.UINT32),friendUin:Zs(5,Ps.UINT32),ext:Zs(6,Ps.UINT32,!0)},tr={targetUid:Zs(1,Ps.STRING),specialTitle:Zs(5,Ps.STRING),expiredTime:Zs(6,Ps.SINT32),uinName:Zs(7,Ps.STRING),targetName:Zs(8,Ps.STRING)},sr={groupUin:Zs(1,Ps.UINT32),body:Zs(3,Ps.BYTES)},rr={uin:Zs(1,Ps.STRING),groupUin:Zs(2,Ps.STRING),version:Zs(3,Ps.STRING)},ir={body:Zs(2,(()=>rr))};class nr{client;constructor(e){this.client=e}packetPacket(e){return Buffer.from(e).toString("hex")}packOidbPacket(e,t,s,r=!0,i=!1){const n=new zs(Hs).encode({command:e,subCommand:t,body:s,isReserved:r?1:0});return{cmd:`OidbSvcTrpcTcp.0x${e.toString(16).toUpperCase()}_${t}`,data:this.packetPacket(n)}}packPokePacket(e,t){const s=new zs(er).encode({uin:e,groupUin:t,friendUin:t??e,ext:0});return this.packOidbPacket(3795,1,s)}packSetSpecialTittlePacket(e,t,s){const r=new zs(tr).encode({targetUid:t,specialTitle:s,expiredTime:-1,uinName:s}),i=new zs(sr).encode({groupUin:+e,body:r});return this.packOidbPacket(2300,2,i,!1,!1)}packGroupSignReq(e,t){return this.packOidbPacket(3767,1,new zs(ir).encode({body:{uin:e,groupUin:t,version:"9.0.90"}}),!1,!1)}}const or={10:e=>new zt(e),1:e=>new Jt(e)};class ar{client;packer;wrapperSession;constructor(e){this.wrapperSession=e,this.client=this.newClient(),this.packer=new nr(this.client)}newClient(){let e,t="native";switch(t){case"native":console.log("[Core] [Packet] 使用指定的 NativePacketClient 作为后端"),e=new zt(this.wrapperSession);break;case"frida":console.log("[Core] [Packet] 使用指定的 FridaPacketClient 作为后端"),e=new Jt(this.wrapperSession);break;case"auto":case void 0:e=this.judgeClient();break;default:console.error(`[Core] [Packet] 未知的PacketBackend ${t},请检查配置文件!`),e=null}if(!e||!e.check())throw new Error("[Core] [Packet] 无可用的后端,NapCat.Packet将不会加载!");return e}judgeClient(){const e=Object.entries(or).map((([e,t])=>{const s=t(this.wrapperSession),r=+e*+s.check();return{client:s,score:r}})).filter((({score:e})=>e>0)).sort(((e,t)=>t.score-e.score)),t=e[0]?.client;if(!t)throw new Error("[Core] [Packet] 无可用的后端,NapCat.Packet将不会加载!");return console.log(`[Core] [Packet] 自动选择 ${t.constructor.name} 作为后端`),t}}const cr={"6.9.56-28418-arm64":{send:"4471360",recv:"4473BCC"},"3.2.12-28418-x64":{recv:"A0723E0",send:"A06EAE0"},"9.9.15-28418-x64":{recv:"37A9004",send:"37A4BD0"},"9.9.15-28498-x64":{recv:"37A9004",send:"37A4BD0"},"9.9.16-28788-x64":{send:"38076D0",recv:"380BB04"},"3.2.13-28788-x64":{send:"A0CEC20",recv:"A0D2520"},"3.2.13-28788-arm64":{send:"6E91018",recv:"6E94850"},"9.9.16-28971-x64":{send:"38079F0",recv:"380BE24"},"3.2.13-28971-x64":{send:"A0CEF60",recv:"A0D2860"},"3.2.12-28971-arm64":{send:"6E91318",recv:"6E94B50"},"6.9.58-28971-arm64":{send:"449ACA0",recv:"449D50C"},"9.9.16-29271-x64":{send:"3833510",recv:"3837944"},"3.2.13-29271-x64":{send:"A11E680",recv:"A121F80"},"3.2.13-29271-arm64":{send:"6ECA098",recv:"6ECD8D0"},"9.9.16-29456-x64":{send:"3835CD0",recv:"383A104"},"3.2.13-29456-x64":{send:"A11E820",recv:"A122120"},"3.2.13-29456-arm64":{send:"6ECA130",recv:"6ECD968"}};class hr{QQMainPath;QQPackageInfoPath;QQVersionConfigPath;isQuickUpdate;QQVersionConfig;QQPackageInfo;constructor(){this.QQMainPath=process.execPath,this.QQVersionConfigPath=function(e=""){let t;if("win32"===g.platform())t=y.join(y.dirname(e),"versions","config.json");else if("darwin"===g.platform()){const e=g.homedir(),s=y.resolve(e,"./Library/Application Support/QQ");t=y.resolve(s,"./versions/config.json")}else{const e=g.homedir(),s=y.resolve(e,"./.config/QQ");t=y.resolve(s,"./versions/config.json")}if("string"==typeof t&&(b.existsSync(t)||(t=y.join(y.dirname(e),"./resources/app/versions/config.json")),b.existsSync(t)))return t}(this.QQMainPath),this.isQuickUpdate=!!this.QQVersionConfigPath,this.QQVersionConfig=this.isQuickUpdate?JSON.parse(b.readFileSync(this.QQVersionConfigPath).toString()):"linux"===g.platform()?{baseVersion:"3.2.12.28060",curVersion:"3.2.12.28060",prevVersion:"",onErrorVersions:[],buildId:"27254"}:"darwin"===g.platform()?{baseVersion:"6.9.53.28060",curVersion:"6.9.53.28060",prevVersion:"",onErrorVersions:[],buildId:"28060"}:{baseVersion:"9.9.15-28131",curVersion:"9.9.15-28131",prevVersion:"",onErrorVersions:[],buildId:"28131"},this.QQPackageInfoPath=function(e="",t){let s;return s="darwin"===g.platform()?y.join(y.dirname(e),"..","Resources","app","package.json"):"linux"===g.platform()?y.join(y.dirname(e),"./resources/app/package.json"):y.join(y.dirname(e),"./versions/"+t+"/resources/app/package.json"),b.existsSync(s)||(s=y.join(y.dirname(e),"./resources/app/versions/"+t+"/package.json")),s}(this.QQMainPath,this.QQVersionConfig?.curVersion),this.QQPackageInfo=JSON.parse(b.readFileSync(this.QQPackageInfoPath).toString())}getFullQQVersion(){const e=this.isQuickUpdate?this.QQVersionConfig?.curVersion:this.QQPackageInfo?.version;if(!e)throw new Error("QQ版本获取失败");return e}}let lr=require("process"),fr=null;const ur="dlopenOri"+Math.random().toString(36).substring(7);async function dr(){return fr||new Promise(((e,t)=>{let s=setInterval((()=>{fr&&(clearInterval(s),e(fr))}),100)}))}lr[ur]=lr.dlopen,lr.dlopen=function(e,t,s=g.constants.dlopen.RTLD_LAZY){let r=this[ur](e,t,s),i=e.exports;return e.exports=new Proxy({},{get:function(e,t,s){return"NodeIQQNTWrapperSession"===t?new Proxy((()=>{}),{get(e,t,s){if("create"===t)return new Proxy((()=>{}),{apply:(e,t,s)=>(fr=i.NodeIQQNTWrapperSession.create(...s),console.log("NodeIQQNTWrapperSession created:",fr),lr.dlopen=lr[ur],fr)})}}):i[t]}}),r};class pr{qqVersion;packetSession;logger=console;wrapperSession;constructor(e){this.wrapperSession=e,this.packetSession=void 0,this.InitSendPacket((new hr).getFullQQVersion()).then().catch(console.error)}get available(){return this.packetSession?.client.available??!1}async InitSendPacket(t){this.qqVersion=t;const s=cr[t+"-"+e.arch()];if(!s)return this.logger.error("PacketServer Offset table not found for QQVersion: ",t+"-"+e.arch()),!1;this.packetSession=new ar(this.wrapperSession);return await this.packetSession.client.connect((()=>{this.packetSession&&this.packetSession.client&&this.packetSession.client.init(process.pid,s.recv,s.send).then().catch(this.logger.error.bind(this.logger))})),!0}async sendPacket(e,t,s=!1){return this.packetSession.client.sendPacket(e,t,s)}async sendOidbPacket(e,t=!1){return this.sendPacket(e.cmd,e.data,t)}async sendPokePacket(e,t){const s=this.packetSession?.packer.packPokePacket(e,t);await this.sendOidbPacket(s,!1)}async sendGroupSignPacket(e,t){const s=this.packetSession?.packer.packGroupSignReq(e,t);await this.sendOidbPacket(s,!0)}async sendSetSpecialTittlePacket(e,t,s){const r=this.packetSession?.packer.packSetSpecialTittlePacket(e,t,s);await this.sendOidbPacket(r,!0)}}export{pr as NTQQPacketApi,dr as initWrapperSession}; diff --git a/src/ntqqapi/native/napcat-protocol-packet/wrapper-session/index.d.ts b/src/ntqqapi/native/napcat-protocol-packet/wrapper-session/index.d.ts new file mode 100644 index 0000000..7939cf4 --- /dev/null +++ b/src/ntqqapi/native/napcat-protocol-packet/wrapper-session/index.d.ts @@ -0,0 +1 @@ +export declare function initWrapperSession(): Promise; diff --git a/src/ntqqapi/native/napcat-protocol-packet/wrapper-session/types.d.ts b/src/ntqqapi/native/napcat-protocol-packet/wrapper-session/types.d.ts new file mode 100644 index 0000000..a3ecdb0 --- /dev/null +++ b/src/ntqqapi/native/napcat-protocol-packet/wrapper-session/types.d.ts @@ -0,0 +1,6 @@ +export interface MsgService { + sendSsoCmdReqByContend: (cmd: string, trace_id: string) => Promise; +} +export type WrapperSession = { + getMsgService(): MsgService; +}; diff --git a/src/onebot11/action/go-cqhttp/SendGroupSign.ts b/src/onebot11/action/go-cqhttp/SendGroupSign.ts new file mode 100644 index 0000000..c80b693 --- /dev/null +++ b/src/onebot11/action/go-cqhttp/SendGroupSign.ts @@ -0,0 +1,20 @@ +import { BaseAction, Schema } from '../BaseAction' +import { ActionName } from '../types' +import { getBuildVersion } from '@/common/utils/misc' +import { selfInfo } from '@/common/globalVars' + +interface Payload { + group_id: number | string +} + +export class SendGroupSign extends BaseAction { + actionName = ActionName.GoCQHTTP_SendGroupSign + payloadSchema = Schema.object({ + group_id: Schema.union([Number, String]).required(), + }) + + async _handle(payload: Payload) { + await this.ctx.app.ntqqPacketApi.sendGroupSignPacket(selfInfo.uin, payload.group_id.toString()) + return null + } +} diff --git a/src/onebot11/action/go-cqhttp/SetGroupSpecialTitle.ts b/src/onebot11/action/go-cqhttp/SetGroupSpecialTitle.ts new file mode 100644 index 0000000..8aa48e7 --- /dev/null +++ b/src/onebot11/action/go-cqhttp/SetGroupSpecialTitle.ts @@ -0,0 +1,25 @@ +import { BaseAction, Schema } from '../BaseAction' +import { ActionName } from '../types' +import { getBuildVersion } from '@/common/utils/misc' + +interface Payload { + group_id: number | string + user_id: number | string + special_title?: string +} + +export class SetGroupSpecialTitle extends BaseAction { + actionName = ActionName.GoCQHTTP_SetGroupSpecialTitle + payloadSchema = Schema.object({ + group_id: Schema.union([Number, String]).required(), + user_id: Schema.union([Number, String]).required(), + special_title: Schema.string() + }) + + async _handle(payload: Payload) { + const uid = await this.ctx.ntUserApi.getUidByUin(payload.user_id.toString(), payload.group_id.toString()) + if (!uid) throw new Error(`用户${payload.user_id}的uid获取失败`) + await this.ctx.app.ntqqPacketApi.sendSetSpecialTittlePacket(payload.group_id.toString(), uid, payload.special_title || "") + return null + } +} diff --git a/src/onebot11/action/index.ts b/src/onebot11/action/index.ts index 744d74a..665698e 100644 --- a/src/onebot11/action/index.ts +++ b/src/onebot11/action/index.ts @@ -78,6 +78,8 @@ import { GroupPoke } from './llonebot/GroupPoke' import { FriendPoke } from './llonebot/FriendPoke' import { GetGroupFileSystemInfo } from './go-cqhttp/GetGroupFileSystemInfo' import { GetCredentials } from './system/GetCredentials' +import { SetGroupSpecialTitle } from '@/onebot11/action/go-cqhttp/SetGroupSpecialTitle' +import { SendGroupSign } from '@/onebot11/action/go-cqhttp/SendGroupSign' export function initActionMap(adapter: Adapter) { const actionHandlers = [ @@ -161,6 +163,8 @@ export function initActionMap(adapter: Adapter) { new DeleteFriend(adapter), new OCRImage(adapter), new GetGroupFileSystemInfo(adapter), + new SetGroupSpecialTitle(adapter), + new SendGroupSign(adapter), ] const actionMap = new Map() for (const action of actionHandlers) { diff --git a/src/onebot11/action/llonebot/FriendPoke.ts b/src/onebot11/action/llonebot/FriendPoke.ts index 80a4ae5..3b2f7b2 100644 --- a/src/onebot11/action/llonebot/FriendPoke.ts +++ b/src/onebot11/action/llonebot/FriendPoke.ts @@ -13,13 +13,15 @@ export class FriendPoke extends BaseAction { }) async _handle(payload: Payload) { - if (!this.ctx.app.native.checkPlatform()) { - throw new Error('当前系统平台或架构不支持') - } - if (!this.ctx.app.native.checkVersion()) { - throw new Error(`当前 QQ 版本 ${getBuildVersion()} 不支持,可尝试其他版本 27333—27597`) - } - await this.ctx.app.native.sendFriendPoke(+payload.user_id) + // if (!this.ctx.app.native.checkPlatform()) { + // throw new Error('当前系统平台或架构不支持') + // } + // if (!this.ctx.app.native.checkVersion()) { + // throw new Error(`当前 QQ 版本 ${getBuildVersion()} 不支持,可尝试其他版本 27333—27597`) + // } + // await this.ctx.app.native.sendFriendPoke(+payload.user_id) + + await this.ctx.app.ntqqPacketApi.sendPokePacket(+payload.user_id) return null } } diff --git a/src/onebot11/action/llonebot/GroupPoke.ts b/src/onebot11/action/llonebot/GroupPoke.ts index 89f8787..1025378 100644 --- a/src/onebot11/action/llonebot/GroupPoke.ts +++ b/src/onebot11/action/llonebot/GroupPoke.ts @@ -1,6 +1,7 @@ import { BaseAction, Schema } from '../BaseAction' import { ActionName } from '../types' import { getBuildVersion } from '@/common/utils/misc' +import {NTQQPacketApi} from '@/ntqqapi/native/napcat-protocol-packet' interface Payload { group_id: number | string @@ -15,13 +16,14 @@ export class GroupPoke extends BaseAction { }) async _handle(payload: Payload) { - if (!this.ctx.app.native.checkPlatform()) { - throw new Error('当前系统平台或架构不支持') - } - if (!this.ctx.app.native.checkVersion()) { - throw new Error(`当前 QQ 版本 ${getBuildVersion()} 不支持,可尝试其他版本 27333—27597`) - } - await this.ctx.app.native.sendGroupPoke(+payload.group_id, +payload.user_id) + // if (!this.ctx.app.native.checkPlatform()) { + // throw new Error('当前系统平台或架构不支持') + // } + // if (!this.ctx.app.native.checkVersion()) { + // throw new Error(`当前 QQ 版本 ${getBuildVersion()} 不支持,可尝试其他版本 27333—27597`) + // } + // await this.ctx.app.native.sendGroupPoke(+payload.group_id, +payload.user_id) + await this.ctx.app.ntqqPacketApi.sendPokePacket(+payload.user_id, +payload.group_id) return null } } diff --git a/src/onebot11/action/types.ts b/src/onebot11/action/types.ts index 74c8048..126db44 100644 --- a/src/onebot11/action/types.ts +++ b/src/onebot11/action/types.ts @@ -91,4 +91,6 @@ export enum ActionName { GoCQHTTP_DeleteFriend = 'delete_friend', GoCQHTTP_OCRImage = 'ocr_image', GoCQHTTP_GetGroupFileSystemInfo = 'get_group_file_system_info', + GoCQHTTP_SetGroupSpecialTitle = 'set_group_special_title', + GoCQHTTP_SendGroupSign = 'send_group_sign', } diff --git a/src/version.ts b/src/version.ts index 94bbc74..355f74a 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1 +1 @@ -export const version = '4.1.4' +export const version = '4.1.5'