iosignal 6.1.2 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ko.md +54 -0
- package/README.md +57 -0
- package/dist/browser/esm/io.js +1 -1
- package/dist/browser/iife/io.js +1 -1
- package/dist/node/iosignal.cjs +122 -19
- package/dist/node/iosignal.js +122 -19
- package/package.json +1 -1
package/README.ko.md
CHANGED
|
@@ -88,6 +88,28 @@ process.once('SIGINT', () => io.stop());
|
|
|
88
88
|
`signal(tag, ...args)`는 문자열, 바이너리, 객체 및 여러 인자를 지원합니다.
|
|
89
89
|
`unsubscribe(tag)`로 구독을 해제할 수 있습니다.
|
|
90
90
|
|
|
91
|
+
### 시그널 태그 요약
|
|
92
|
+
|
|
93
|
+
| 통신 방식 | 송신 | 구독 | 수신 tag |
|
|
94
|
+
| --- | --- | --- | --- |
|
|
95
|
+
| 채널 | `room#topic` | `room#topic` | `room#topic` |
|
|
96
|
+
| 홈채널 | `#topic` | `#topic` | `#topic` |
|
|
97
|
+
| B에게 직접 송신 | `B@topic` | 불필요 | `@topic` |
|
|
98
|
+
| A의 CID 발행 | A가 `@topic` 송신 | `A@topic` | `A@topic` |
|
|
99
|
+
|
|
100
|
+
직접 시그널은 `on('message', ...)`가 아닌 `on('@', ...)`로 받습니다.
|
|
101
|
+
|
|
102
|
+
```js
|
|
103
|
+
io.on('@', (tag, ...args) => {
|
|
104
|
+
if (tag === '@topic') console.log(...args);
|
|
105
|
+
});
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
리테인 발행은 `room#$state`나 `@$state`처럼 `$`를 포함한 태그를 사용합니다.
|
|
109
|
+
보관 정책과 제한은 서버·서비스 설정 및 인증 유형에 따라 달라집니다.
|
|
110
|
+
자세한 내용은 [시그널 태그](https://iosignal.net/docs/core/signal_tags)와
|
|
111
|
+
[시그널 유형](https://iosignal.net/docs/core/signal_types)을 참고하세요.
|
|
112
|
+
|
|
91
113
|
## 브라우저
|
|
92
114
|
|
|
93
115
|
번들러를 사용하는 브라우저 프로젝트에서는 브라우저 전용 진입점을 가져옵니다.
|
|
@@ -220,6 +242,38 @@ Arduino 장치 ←→ IOSignal 서버 ←→ 브라우저 웹앱
|
|
|
220
242
|
웹앱 코드 제공자에 대한 신뢰가 필요합니다. boho는 브라우저의 mixed content
|
|
221
243
|
정책을 우회하지 않습니다.
|
|
222
244
|
|
|
245
|
+
### 7.0.0 세션 시간·재사용 검증
|
|
246
|
+
|
|
247
|
+
서버는 허용 시간 차이를 벗어나거나 이미 허용한 시간·카운터 조합을 다시
|
|
248
|
+
사용한 암호 패킷을 거부하고, 명령 실행·중계 전에 연결을 종료합니다.
|
|
249
|
+
`ENC_488`과 `ENC_E2E` 라우팅 암호 헤더에 같은 정책을 적용하며 패킷 형식은 유지합니다.
|
|
250
|
+
|
|
251
|
+
```js
|
|
252
|
+
const server = new Server({
|
|
253
|
+
port: 8080,
|
|
254
|
+
security: {
|
|
255
|
+
maxClockSkewMs: 60000,
|
|
256
|
+
authChallengeMaxAgeMs: 60000,
|
|
257
|
+
maxReplayEntries: 65536
|
|
258
|
+
}
|
|
259
|
+
}, authManager);
|
|
260
|
+
```
|
|
261
|
+
|
|
262
|
+
기본값은 절대 시간 차이 60초, 인증 challenge 유효기간 60초, 연결별 저장 한도
|
|
263
|
+
65,536개입니다. 설정은 양의 안전 정수여야 합니다. 저장 한도 초과도 연결을
|
|
264
|
+
종료하며 아직 유효한 재사용 기록을 임의로 지우지 않습니다.
|
|
265
|
+
`security:mismatch(remote, reason)` 이벤트와 `remote.securityFailure`로 사유를 확인합니다.
|
|
266
|
+
|
|
267
|
+
정상 검증된 인증 증명은 challenge를 소진합니다. 재인증 또는 challenge 만료 후
|
|
268
|
+
수동 로그인은 재연결해야 합니다. 인증된 연결에서 다시 `login()`하면 연결이
|
|
269
|
+
종료됩니다. AUTH_REQ에는 현재 장치 시각이 없으므로 초기에는 challenge 경과시간을,
|
|
270
|
+
이후 암호 패킷에서는 장치 시각과 서버 시각의 차이를 검사합니다.
|
|
271
|
+
평문·TLS 전송 정책은 변경하지 않습니다.
|
|
272
|
+
|
|
273
|
+
JS 클라이언트 시계는 허용 범위 안에 있어야 합니다. Boho Arduino 1.0.0은 검증된
|
|
274
|
+
서버 암호 헤더로 시계를 점진 보정하며 평문 PING/PONG은 시간 보정에 사용하지 않습니다.
|
|
275
|
+
내부 E2E 본문의 재사용 방지는 연결 암호 헤더 검증과 별도로 응용 계층에서 처리합니다.
|
|
276
|
+
|
|
223
277
|
### 현재 구현의 적용 조건
|
|
224
278
|
|
|
225
279
|
- 충분히 무작위인 키를 사용하세요. `set_key`의 SHA-256 한 번은 비밀번호용 느린 KDF가 아닙니다.
|
package/README.md
CHANGED
|
@@ -89,6 +89,28 @@ process.once('SIGINT', () => io.stop());
|
|
|
89
89
|
`signal(tag, ...args)` supports strings, binary data, objects and multiple
|
|
90
90
|
arguments. Use `unsubscribe(tag)` to unsubscribe.
|
|
91
91
|
|
|
92
|
+
### Signal tags at a glance
|
|
93
|
+
|
|
94
|
+
| Communication | Send | Subscribe | Received tag |
|
|
95
|
+
| --- | --- | --- | --- |
|
|
96
|
+
| Channel | `room#topic` | `room#topic` | `room#topic` |
|
|
97
|
+
| Home channel | `#topic` | `#topic` | `#topic` |
|
|
98
|
+
| Direct to B | `B@topic` | Not required | `@topic` |
|
|
99
|
+
| Publication by A | A sends `@topic` | `A@topic` | `A@topic` |
|
|
100
|
+
|
|
101
|
+
Direct signals arrive on `on('@', ...)`, rather than `on('message', ...)`.
|
|
102
|
+
|
|
103
|
+
```js
|
|
104
|
+
io.on('@', (tag, ...args) => {
|
|
105
|
+
if (tag === '@topic') console.log(...args);
|
|
106
|
+
});
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
For retained publications, use a tag containing `$`, such as `room#$state` or
|
|
110
|
+
`@$state`. Retention policies and limits depend on server/service configuration
|
|
111
|
+
and authentication type. See [signal tags](https://iosignal.net/docs/core/signal_tags)
|
|
112
|
+
and [signal types](https://iosignal.net/docs/core/signal_types) for details.
|
|
113
|
+
|
|
92
114
|
## Browsers
|
|
93
115
|
|
|
94
116
|
For browser projects using a bundler, import the browser-specific entry point.
|
|
@@ -230,6 +252,41 @@ also applying E2E to message bodies. Modified app code can expose keys and
|
|
|
230
252
|
plaintext, so E2E still requires trust in the app code provider. Boho does not
|
|
231
253
|
bypass browser mixed content rules.
|
|
232
254
|
|
|
255
|
+
### Session freshness in 7.0.0
|
|
256
|
+
|
|
257
|
+
The server now rejects encrypted session packets outside the configured clock
|
|
258
|
+
window or with an already accepted time/counter pair. Both `ENC_488` and the
|
|
259
|
+
`ENC_E2E` routing envelope share this policy. Rejection terminates the connection
|
|
260
|
+
before executing or routing the message. Wire formats remain unchanged.
|
|
261
|
+
|
|
262
|
+
```js
|
|
263
|
+
const server = new Server({
|
|
264
|
+
port: 8080,
|
|
265
|
+
security: {
|
|
266
|
+
maxClockSkewMs: 60000,
|
|
267
|
+
authChallengeMaxAgeMs: 60000,
|
|
268
|
+
maxReplayEntries: 65536
|
|
269
|
+
}
|
|
270
|
+
}, authManager);
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
Defaults are a 60-second absolute clock window, a 60-second authentication
|
|
274
|
+
challenge lifetime and at most 65,536 remembered packet tuples per connection.
|
|
275
|
+
The limits must be positive safe integers. Cache exhaustion also terminates the
|
|
276
|
+
connection; still-valid replay evidence is never evicted. The server emits
|
|
277
|
+
`security:mismatch(remote, reason)` and records `remote.securityFailure`.
|
|
278
|
+
|
|
279
|
+
A successfully verified authentication proof consumes its challenge. Reconnect
|
|
280
|
+
for reauthentication or if manual login occurs after challenge expiry; calling
|
|
281
|
+
`login()` again on an authenticated connection now closes it. AUTH_REQ has no
|
|
282
|
+
current device timestamp, so this stage checks challenge age. Device clock skew
|
|
283
|
+
is checked on encrypted packets. Plaintext/TLS transport policy is unchanged.
|
|
284
|
+
|
|
285
|
+
JS clients must have a clock within the configured window. Boho Arduino 1.0.0
|
|
286
|
+
adds gradual clock correction from authenticated server envelopes; plain
|
|
287
|
+
PING/PONG provides no time sample. Inner E2E payload freshness remains an
|
|
288
|
+
application concern, separate from the connection envelope.
|
|
289
|
+
|
|
233
290
|
### Conditions in the current implementation
|
|
234
291
|
|
|
235
292
|
- Use sufficiently random keys. A single SHA-256 in `set_key` is not a slow password KDF.
|
package/dist/browser/esm/io.js
CHANGED
|
@@ -19,5 +19,5 @@ var s=(r||(r=1,function(r){const n=function(){if(t)return i;t=1,i.byteLength=fun
|
|
|
19
19
|
*
|
|
20
20
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
21
21
|
* @license MIT
|
|
22
|
-
*/var Yt=(zt||(zt=1,function(t){const e=function(){if(Dt)return Ht;Dt=1,Ht.byteLength=function(t){var e=o(t),r=e[0],n=e[1];return 3*(r+n)/4-n},Ht.toByteArray=function(t){var n,i,s=o(t),f=s[0],u=s[1],h=new r(function(t,e,r){return 3*(e+r)/4-r}(0,f,u)),a=0,c=u>0?f-4:f;for(i=0;i<c;i+=4)n=e[t.charCodeAt(i)]<<18|e[t.charCodeAt(i+1)]<<12|e[t.charCodeAt(i+2)]<<6|e[t.charCodeAt(i+3)],h[a++]=n>>16&255,h[a++]=n>>8&255,h[a++]=255&n;return 2===u&&(n=e[t.charCodeAt(i)]<<2|e[t.charCodeAt(i+1)]>>4,h[a++]=255&n),1===u&&(n=e[t.charCodeAt(i)]<<10|e[t.charCodeAt(i+1)]<<4|e[t.charCodeAt(i+2)]>>2,h[a++]=n>>8&255,h[a++]=255&n),h},Ht.fromByteArray=function(e){for(var r,n=e.length,i=n%3,o=[],s=16383,u=0,h=n-i;u<h;u+=s)o.push(f(e,u,u+s>h?h:u+s));return 1===i?(r=e[n-1],o.push(t[r>>2]+t[r<<4&63]+"==")):2===i&&(r=(e[n-2]<<8)+e[n-1],o.push(t[r>>10]+t[r>>4&63]+t[r<<2&63]+"=")),o.join("")};for(var t=[],e=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)t[i]=n[i],e[n.charCodeAt(i)]=i;function o(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function s(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[63&e]}function f(t,e,r){for(var n,i=[],o=e;o<r;o+=3)n=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(255&t[o+2]),i.push(s(n));return i.join("")}return e["-".charCodeAt(0)]=62,e["_".charCodeAt(0)]=63,Ht}(),r=Gt(),n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=s,t.SlowBuffer=function(t){return+t!=t&&(t=0),s.alloc(+t)},t.INSPECT_MAX_BYTES=50;const i=2147483647;function o(t){if(t>i)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,s.prototype),e}function s(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return h(t)}return f(t,e,r)}function f(t,e,r){if("string"==typeof t)return function(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!s.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|p(t,e);let n=o(r);const i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(q(t,Uint8Array)){const e=new Uint8Array(t);return c(e.buffer,e.byteOffset,e.byteLength)}return a(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(q(t,ArrayBuffer)||t&&q(t.buffer,ArrayBuffer))return c(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(q(t,SharedArrayBuffer)||t&&q(t.buffer,SharedArrayBuffer)))return c(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return s.from(n,e,r);const i=function(t){if(s.isBuffer(t)){const e=0|l(t.length),r=o(e);return 0===r.length||t.copy(r,0,0,e),r}return void 0!==t.length?"number"!=typeof t.length||K(t.length)?o(0):a(t):"Buffer"===t.type&&Array.isArray(t.data)?a(t.data):void 0}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return s.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function u(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function h(t){return u(t),o(t<0?0:0|l(t))}function a(t){const e=t.length<0?0:0|l(t.length),r=o(e);for(let n=0;n<e;n+=1)r[n]=255&t[n];return r}function c(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===e&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,e):new Uint8Array(t,e,r),Object.setPrototypeOf(n,s.prototype),n}function l(t){if(t>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|t}function p(t,e){if(s.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||q(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return V(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(t).length;default:if(i)return n?-1:V(t).length;e=(""+e).toLowerCase(),i=!0}}function y(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return I(this,e,r);case"ascii":return U(this,e,r);case"latin1":case"binary":return L(this,e,r);case"base64":return A(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function g(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function d(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),K(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=s.from(e,n)),s.isBuffer(e))return 0===e.length?-1:b(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):b(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(t,e,r,n,i){let o,s=1,f=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,f/=2,u/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){let n=-1;for(o=r;o<f;o++)if(h(t,o)===h(e,-1===n?0:o-n)){if(-1===n&&(n=o),o-n+1===u)return n*s}else-1!==n&&(o-=o-n),n=-1}else for(r+u>f&&(r=f-u),o=r;o>=0;o--){let r=!0;for(let n=0;n<u;n++)if(h(t,o+n)!==h(e,n)){r=!1;break}if(r)return o}return-1}function w(t,e,r,n){r=Number(r)||0;const i=t.length-r;n?(n=Number(n))>i&&(n=i):n=i;const o=e.length;let s;for(n>o/2&&(n=o/2),s=0;s<n;++s){const n=parseInt(e.substr(2*s,2),16);if(K(n))return s;t[r+s]=n}return s}function E(t,e,r,n){return Y(V(e,t.length-r),t,r,n)}function B(t,e,r,n){return Y(function(t){const e=[];for(let r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function m(t,e,r,n){return Y(G(e),t,r,n)}function _(t,e,r,n){return Y(function(t,e){let r,n,i;const o=[];for(let s=0;s<t.length&&!((e-=2)<0);++s)r=t.charCodeAt(s),n=r>>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function A(t,r,n){return 0===r&&n===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(r,n))}function I(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i<r;){const e=t[i];let o=null,s=e>239?4:e>223?3:e>191?2:1;if(i+s<=r){let r,n,f,u;switch(s){case 1:e<128&&(o=e);break;case 2:r=t[i+1],128==(192&r)&&(u=(31&e)<<6|63&r,u>127&&(o=u));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(u=(15&e)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(o=u));break;case 4:r=t[i+1],n=t[i+2],f=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&f)&&(u=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&f,u>65535&&u<1114112&&(o=u))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(t){const e=t.length;if(e<=v)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=v));return r}(n)}t.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=function(){try{const t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),42===t.foo()}catch(t){return!1}}(),s.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(t,e,r){return f(t,e,r)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(t,e,r){return function(t,e,r){return u(t),t<=0?o(t):void 0!==e?"string"==typeof r?o(t).fill(e,r):o(t).fill(e):o(t)}(t,e,r)},s.allocUnsafe=function(t){return h(t)},s.allocUnsafeSlow=function(t){return h(t)},s.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==s.prototype},s.compare=function(t,e){if(q(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),q(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(t)||!s.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;let r=t.length,n=e.length;for(let i=0,o=Math.min(r,n);i<o;++i)if(t[i]!==e[i]){r=t[i],n=e[i];break}return r<n?-1:n<r?1:0},s.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(t,e){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return s.alloc(0);let r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;const n=s.allocUnsafe(e);let i=0;for(r=0;r<t.length;++r){let e=t[r];if(q(e,Uint8Array))i+e.length>n.length?(s.isBuffer(e)||(e=s.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!s.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},s.byteLength=p,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;e<t;e+=2)g(this,e,e+1);return this},s.prototype.swap32=function(){const t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let e=0;e<t;e+=4)g(this,e,e+3),g(this,e+1,e+2);return this},s.prototype.swap64=function(){const t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let e=0;e<t;e+=8)g(this,e,e+7),g(this,e+1,e+6),g(this,e+2,e+5),g(this,e+3,e+4);return this},s.prototype.toString=function(){const t=this.length;return 0===t?"":0===arguments.length?I(this,0,t):y.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(t){if(!s.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===s.compare(this,t)},s.prototype.inspect=function(){let e="";const r=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},n&&(s.prototype[n]=s.prototype.inspect),s.prototype.compare=function(t,e,r,n,i){if(q(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let o=(i>>>=0)-(n>>>=0),f=(r>>>=0)-(e>>>=0);const u=Math.min(o,f),h=this.slice(n,i),a=t.slice(e,r);for(let t=0;t<u;++t)if(h[t]!==a[t]){o=h[t],f=a[t];break}return o<f?-1:f<o?1:0},s.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},s.prototype.indexOf=function(t,e,r){return d(this,t,e,r,!0)},s.prototype.lastIndexOf=function(t,e,r){return d(this,t,e,r,!1)},s.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return w(this,t,e,r);case"utf8":case"utf-8":return E(this,t,e,r);case"ascii":case"latin1":case"binary":return B(this,t,e,r);case"base64":return m(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const v=4096;function U(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(127&t[i]);return n}function L(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function T(t,e,r){const n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);let i="";for(let n=e;n<r;++n)i+=J[t[n]];return i}function S(t,e,r){const n=t.slice(e,r);let i="";for(let t=0;t<n.length-1;t+=2)i+=String.fromCharCode(n[t]+256*n[t+1]);return i}function R(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,r,n,i,o){if(!s.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<o)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function M(t,e,r,n,i){j(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,r}function C(t,e,r,n,i){j(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r+7]=o,o>>=8,t[r+6]=o,o>>=8,t[r+5]=o,o>>=8,t[r+4]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=s,s>>=8,t[r+2]=s,s>>=8,t[r+1]=s,s>>=8,t[r]=s,r+8}function N(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function k(t,e,n,i,o){return e=+e,n>>>=0,o||N(t,0,n,4),r.write(t,e,n,i,23,4),n+4}function x(t,e,n,i,o){return e=+e,n>>>=0,o||N(t,0,n,8),r.write(t,e,n,i,52,8),n+8}s.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e<t&&(e=t);const n=this.subarray(t,e);return Object.setPrototypeOf(n,s.prototype),n},s.prototype.readUintLE=s.prototype.readUIntLE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t],i=1,o=0;for(;++o<e&&(i*=256);)n+=this[t+o]*i;return n},s.prototype.readUintBE=s.prototype.readUIntBE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},s.prototype.readUint8=s.prototype.readUInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),this[t]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]|this[t+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]<<8|this[t+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},s.prototype.readBigUInt64LE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))}),s.prototype.readBigUInt64BE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)}),s.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t],i=1,o=0;for(;++o<e&&(i*=256);)n+=this[t+o]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*e)),n},s.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=e,i=1,o=this[t+--n];for(;n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},s.prototype.readInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},s.prototype.readInt16LE=function(t,e){t>>>=0,e||R(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(t,e){t>>>=0,e||R(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},s.prototype.readInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},s.prototype.readBigInt64LE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(e+256*this[++t]+65536*this[++t]+this[++t]*2**24)}),s.prototype.readBigInt64BE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<<BigInt(32))+BigInt(this[++t]*2**24+65536*this[++t]+256*this[++t]+r)}),s.prototype.readFloatLE=function(t,e){return t>>>=0,e||R(t,4,this.length),r.read(this,t,!0,23,4)},s.prototype.readFloatBE=function(t,e){return t>>>=0,e||R(t,4,this.length),r.read(this,t,!1,23,4)},s.prototype.readDoubleLE=function(t,e){return t>>>=0,e||R(t,8,this.length),r.read(this,t,!0,52,8)},s.prototype.readDoubleBE=function(t,e){return t>>>=0,e||R(t,8,this.length),r.read(this,t,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||O(this,t,e,r,Math.pow(2,8*r)-1,0);let i=1,o=0;for(this[e]=255&t;++o<r&&(i*=256);)this[e+o]=t/i&255;return e+r},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||O(this,t,e,r,Math.pow(2,8*r)-1,0);let i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},s.prototype.writeUint8=s.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,1,255,0),this[e]=255&t,e+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeBigUInt64LE=Q(function(t,e=0){return M(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(t,e=0){return C(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);O(this,t,e,r,n-1,-n)}let i=0,o=1,s=0;for(this[e]=255&t;++i<r&&(o*=256);)t<0&&0===s&&0!==this[e+i-1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},s.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);O(this,t,e,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[e+i]=255&t;--i>=0&&(o*=256);)t<0&&0===s&&0!==this[e+i+1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},s.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},s.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},s.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeBigInt64LE=Q(function(t,e=0){return M(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(t,e=0){return C(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(t,e,r){return k(this,t,e,!0,r)},s.prototype.writeFloatBE=function(t,e,r){return k(this,t,e,!1,r)},s.prototype.writeDoubleLE=function(t,e,r){return x(this,t,e,!0,r)},s.prototype.writeDoubleBE=function(t,e,r){return x(this,t,e,!1,r)},s.prototype.copy=function(t,e,r,n){if(!s.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-r&&(n=t.length-e+r);const i=n-r;return this===t&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(e,r,n):Uint8Array.prototype.set.call(t,this.subarray(r,n),e),i},s.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){const e=t.charCodeAt(0);("utf8"===n&&e<128||"latin1"===n)&&(t=e)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;let i;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i<r;++i)this[i]=t;else{const o=s.isBuffer(t)?t:s.from(t,n),f=o.length;if(0===f)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(i=0;i<r-e;++i)this[i+e]=o[i%f]}return this};const P={};function $(t,e,r){P[t]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(t){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:t,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}function D(t){let e="",r=t.length;const n="-"===t[0]?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function j(t,e,r,n,i,o){if(t>r||t<e){const r="bigint"==typeof e?"n":"";let n;throw n=0===e||e===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(o+1)}${r}`:`>= -(2${r} ** ${8*(o+1)-1}${r}) and < 2 ** ${8*(o+1)-1}${r}`,new P.ERR_OUT_OF_RANGE("value",n,t)}!function(t,e,r){z(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||F(e,t.length-(r+1))}(n,i,o)}function z(t,e){if("number"!=typeof t)throw new P.ERR_INVALID_ARG_TYPE(e,"number",t)}function F(t,e,r){if(Math.floor(t)!==t)throw z(t,r),new P.ERR_OUT_OF_RANGE("offset","an integer",t);if(e<0)throw new P.ERR_BUFFER_OUT_OF_BOUNDS;throw new P.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${e}`,t)}$("ERR_BUFFER_OUT_OF_BOUNDS",function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),$("ERR_INVALID_ARG_TYPE",function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`},TypeError),$("ERR_OUT_OF_RANGE",function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=D(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=D(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);const H=/[^+/0-9A-Za-z-_]/g;function V(t,e){let r;e=e||1/0;const n=t.length;let i=null;const o=[];for(let s=0;s<n;++s){if(r=t.charCodeAt(s),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function G(t){return e.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(H,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Y(t,e,r,n){let i;for(i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function q(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function K(t){return t!=t}const J=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Q(t){return"undefined"==typeof BigInt?W:t}function W(){throw new Error("BigInt not supported")}}(Ft)),Ft);let qt={SERVER_TIME_NONCE:176,AUTH_REQ:177,AUTH_RES:178,AUTH_FAIL:179,ENC_PACK:182,ENC_E2E:183,ENC_488:184};for(let t in qt)qt[qt[t]]=t;const Kt={SERVER_TIME_NONCE:Pt.meta(Pt.MB("header","8",0),Pt.MB("unixTime","32L",0),Pt.MB("milTime","16L",0),Pt.MB("counter","16L",0),Pt.MB("nonce",Yt.Buffer.alloc(4))),AUTH_REQ:Pt.meta(Pt.MB("header","8",0),Pt.MB("id8",Yt.Buffer.alloc(8)),Pt.MB("nonce",Yt.Buffer.alloc(4)),Pt.MB("hmac32",Yt.Buffer.alloc(32))),AUTH_RES:Pt.meta(Pt.MB("header","8",0),Pt.MB("hmac32",Yt.Buffer.alloc(32))),ENC_PACK:Pt.meta(Pt.MB("type","8",0),Pt.MB("len","32L",0),Pt.MB("salt12",Yt.Buffer.alloc(12)),Pt.MB("hmac",8,0)),ENC_488:Pt.meta(Pt.MB("type","8",0),Pt.MB("len","32L",0),Pt.MB("otpSrc8",Yt.Buffer.alloc(8)),Pt.MB("hmac8",Yt.Buffer.alloc(8)))};function Jt(t){let e=t[t.length-1];return e[2]+e[3]}const Qt={SERVER_TIME_NONCE:Jt(Kt.SERVER_TIME_NONCE),AUTH_REQ:Jt(Kt.AUTH_REQ),AUTH_RES:Jt(Kt.AUTH_RES),ENC_PACK:Jt(Kt.ENC_PACK),ENC_488:Jt(Kt.ENC_488)};function Wt(t,e){if(!(t instanceof Uint8Array&&e instanceof Uint8Array&&t.length===e.length))return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return 0===r}function Xt(t,e,r,n,i=!1){if(!(t instanceof Uint8Array))return;const o=Yt.Buffer.from(t);return o.length<r||o[0]!==e||(i?o.readUInt32LE(1)!==o.length-r:o.length!==r)?void 0:Pt.unpack(o,n)}function Zt(t){return globalThis.crypto.getRandomValues(Yt.Buffer.alloc(t))}class te{constructor(){this._id8=Yt.Buffer.alloc(8),this._otpSrc44=Yt.Buffer.alloc(44),this._otp36=Yt.Buffer.alloc(36),this._hmac=Yt.Buffer.alloc(32),this.auth_salt12=Yt.Buffer.alloc(12),this.localNonce=Yt.Buffer.alloc(4),this.remoteNonce=Yt.Buffer.alloc(4),this.isAuthorized=!1,this.counter=0,this._hasKey=!1,this._lastSendTime=0}clearAuth(){this._id8.fill(0),this._otpSrc44.fill(0),this._otp36.fill(0),this._hmac.fill(0),this.auth_salt12.fill(0),this.localNonce.fill(0),this.remoteNonce.fill(0),this.isAuthorized=!1,this.counter=0,this._hasKey=!1,this._lastSendTime=0}set_hash_id8(t){Pt.B8($t.hash(t)).copy(this._id8,0,0,8)}set_id8(t){let e=Pt.B8(t);this._id8.fill(0),e.copy(this._id8,0,0,8)}set_key(t){const e=Pt.B8(t);if(!e||0===e.length)throw new TypeError("Key must not be empty");this.copy_key(Pt.B8($t.hash(e)))}set_id_key(t){let e=t.indexOf(".");if(-1==e)return;let r=t.substring(0,e),n=t.substring(e+1);this.set_id8(r),this.set_key(n)}copy_id8(t){t.copy(this._id8,0,0,8)}copy_key(t){if(!(t instanceof Uint8Array)||32!==t.length)throw new TypeError("copy_key requires exactly 32 bytes");this._otpSrc44.set(t,0),this._hasKey=!0}sha256_n(t,e){let r=$t.hash(t);for(let t=0;t<e;t++)r=$t.hash(r);return r}set_clock_rand(){this.set_clock_nonce(Zt(4))}set_clock_nonce(t){if(!(t instanceof Uint8Array)||4!==t.length)throw new TypeError("Nonce must be 4 bytes");let e=Math.max(Date.now(),this._lastSendTime);if(this.counter=this.counter+1&65535,0===this.counter&&e===this._lastSendTime&&e++,!Number.isSafeInteger(e)||e<0||Math.floor(e/1e3)>4294967295)throw new RangeError("Clock is outside the protocol range");this._lastSendTime=e,Yt.Buffer.concat([Pt.NB("32L",Math.floor(e/1e3)),Pt.NB("16L",e%1e3),Pt.NB("16L",this.counter),Yt.Buffer.from(t)]).copy(this._otpSrc44,32)}_requireKey(){if(!this._hasKey)throw new Error("Set a key before encryption or authentication")}set_salt12(t,e){if(12!=t.byteLength)throw TypeError("set_salt12: Invalid salt12 byteLength.");t.copy(this._otpSrc44,32)}resetOTP(){this._requireKey(),Pt.B8($t.hash(this._otpSrc44)).copy(this._otp36,0,0,32)}getIndexOTP(t){return this._otp36.writeUInt32LE(t,32),$t.hash(this._otp36)}generateHMAC(t){this._requireKey();let e=Yt.Buffer.concat([this._otpSrc44,t]);this._hmac=Pt.B8($t.hash(e))}getHMAC8(t){this._requireKey();let e=Yt.Buffer.concat([this._otpSrc44,t]);return this._hmac=Pt.B8($t.hash(e)),this._hmac.subarray(0,8)}xotp(t,e=0,r=!1){let n=(t=Pt.B8(t,r)).byteLength,i=e,o=0,s=0;for(;n>0;){s=n<32?n:32;let e=this.getIndexOTP(++i);for(let r=0;r<s;r++)t[o++]^=e[r];n-=32}return t}server_time_nonce(){const t=Date.now(),e=Math.floor(t/1e3),r=t%1e3;return this.localNonce=Zt(4),this.auth_salt12=Yt.Buffer.concat([Pt.NB("32L",e),Pt.NB("16L",r),Zt(2),this.localNonce]),Yt.Buffer.concat([Pt.NB("8",qt.SERVER_TIME_NONCE),this.auth_salt12])}auth_req(t){if(!this._hasKey)return!1;let e=Xt(t,qt.SERVER_TIME_NONCE,Qt.SERVER_TIME_NONCE,Kt.SERVER_TIME_NONCE);if(e&&e.milTime>=1e3)return!1;if(e){let t=Yt.Buffer.concat([Pt.NB("32L",e.unixTime),Pt.NB("16L",e.milTime),Pt.NB("16L",e.counter),e.nonce]);return this.set_salt12(t,"auth_req"),this.localNonce=Zt(4),this.generateHMAC(this.localNonce),this.remoteNonce=e.nonce,Pt.pack(Pt.MB("#header","8",qt.AUTH_REQ),Pt.MB("#id8",this._id8),Pt.MB("#nonce",this.localNonce),Pt.MB("#hmac32",this._hmac))}return!1}verify_auth_req(t){if(!this._hasKey)return!1;let e;if(t instanceof Uint8Array?e=Xt(t,qt.AUTH_REQ,Qt.AUTH_REQ,Kt.AUTH_REQ):t&&"object"==typeof t&&(e=t),!e||e.header!==qt.AUTH_REQ||!(e.id8 instanceof Uint8Array)||8!==e.id8.length||!(e.nonce instanceof Uint8Array)||4!==e.nonce.length||!(e.hmac32 instanceof Uint8Array)||32!==e.hmac32.length||e.$OTHERS&&0!==e.$OTHERS.length)return!1;this.set_salt12(this.auth_salt12,"verify_auth_req 1/2"),this.generateHMAC(e.nonce);let r=this._hmac;if(Wt(e.hmac32,r)){this.remoteNonce=Yt.Buffer.from(e.nonce);let t=Yt.Buffer.concat([this.localNonce,this.remoteNonce,this.localNonce]);this.set_salt12(t,"verify_auth_req 2/2"),this.generateHMAC(e.nonce);let r=this._hmac,n=Pt.rawPack(Pt.MB("header","8",qt.AUTH_RES),Pt.MB("hmac32",r));return this.isAuthorized=!0,n}return!1}verify_auth_res(t){if(!this._hasKey)return!1;let e=Xt(t,qt.AUTH_RES,Qt.AUTH_RES,Kt.AUTH_RES);if(e){let t=Yt.Buffer.concat([this.remoteNonce,this.localNonce,this.remoteNonce]);if(this.set_salt12(t,"verify_auth_res"),this.generateHMAC(this.localNonce),Wt(this._hmac,e.hmac32))return this.isAuthorized=!0,!0}}encrypt_488(t){if(!this.isAuthorized||!this._hasKey)return;t=Pt.B8(t),this.set_clock_nonce(this.remoteNonce),this.resetOTP();let e=this.getHMAC8(t),r=this.xotp(t);return Pt.pack(Pt.MB("#type","8",qt.ENC_488),Pt.MB("#len","32L",t.byteLength),Pt.MB("#otpSrc8",this._otpSrc44.subarray(32,40)),Pt.MB("#hmac8",e),Pt.MB("#xdata",r))}decrypt_488(t){if(!this.isAuthorized||!this._hasKey)return;let e=t;if(t instanceof Uint8Array&&t[0]===qt.ENC_E2E){if(t.length<Qt.ENC_488)return;const r=Yt.Buffer.from(t),n=r.readUInt32LE(1);if(n>r.length-Qt.ENC_488)return;e=Yt.Buffer.from(r.subarray(0,Qt.ENC_488+n)),e[0]=qt.ENC_488}const r=Xt(e,qt.ENC_488,Qt.ENC_488,Kt.ENC_488,!0);if(!(r&&(n=r.otpSrc8,n.readUInt16LE(4)<1e3)))return;var n;this.set_salt12(Yt.Buffer.concat([r.otpSrc8,this.localNonce]),"decrypt_488"),this.resetOTP();const i=this.xotp(r.$OTHERS??Yt.Buffer.alloc(0));return Wt(this.getHMAC8(i),r.hmac8)?i:void 0}encryptPack(t){this._requireKey(),t=Pt.B8(t),this.set_clock_rand(),this.resetOTP();let e=this.getHMAC8(t),r=this.xotp(t);return Pt.pack(Pt.MB("#type","8",qt.ENC_PACK),Pt.MB("#len","32L",t.byteLength),Pt.MB("#salt12",this._otpSrc44.subarray(32)),Pt.MB("#hmac8",e),Pt.MB("#xdata",r))}decryptPack(t){if(!this._hasKey)return;const e=Xt(t,qt.ENC_PACK,Qt.ENC_PACK,Kt.ENC_PACK,!0);if(!e)return;this.set_salt12(e.salt12,"decryptPack"),this.resetOTP();const r=this.xotp(e.$OTHERS??Yt.Buffer.alloc(0));return Wt(e.hmac,this.getHMAC8(r))?(e.data=r,e):void 0}encrypt_e2e(t,e){return this._withKey(e,()=>this.encryptPack(t))}decrypt_e2e(t,e){return this._withKey(e,()=>this.decryptPack(t))}_withKey(t,e){const r=Pt.B8(t);if(!r||0===r.length)throw new TypeError("Key must not be empty");const n=[Yt.Buffer.from(this._otpSrc44),Yt.Buffer.from(this._otp36),Yt.Buffer.from(this._hmac)],i=this._hasKey;try{return this._otpSrc44.set($t.hash(r),0),this._hasKey=!0,e()}finally{this._otpSrc44.set(n[0]),this._otp36.set(n[1]),this._hmac.set(n[2]),this._hasKey=i;for(const t of n)t.fill(0)}}}te.RAND=Zt,te.BohoMsg=qt,te.Meta=Kt,te.MetaSize=Qt,te.sha256=$t,te.MBP=Pt,te.Buffer=Yt.Buffer;const ee=k.Buffer,re=new TextEncoder,ne=new TextDecoder;function ie(t,e=!0){if("string"!=typeof t)throw TypeError("tag should be string.");const r=re.encode(t);if(!e&&0===r.byteLength||r.byteLength>H.TAG_LEN1)throw TypeError("tag UTF-8 byte length must be "+(e?"0":"1")+"~255");return r}class oe extends j{constructor(t){super(),this.cid="",this.ip="",this.socket=null,this.url=t,this.state=z.CLOSED,this.stateName=this.getStateName(),this._stateRevision=0,this.txCounter=0,this.rxCounter=0,this.txBytes=0,this.rxBytes=0,this.lastTxRxTime=Date.now(),this.connectionCheckerPeriod=H.CONNECTION_CHECKER_PERIOD,this.connectionCheckerIntervalID=null,this.boho=new te,this.serverTimeNonce=ee.alloc(te.MetaSize.SERVER_TIME_NONCE),this.TLS=!1,this.encMode=F.AUTO,this.useAuth=!1,this.nick="",this.channels=new Set,this.promiseMap=new Map,this.promiseTimeOut=H.PROMISE_TIMEOUT,this.mid=0,this.level=3,this.quota=q[this.level],this.serverSet={},this.linkMap=new Map,this.autoReconnect=!0,this._closed=!1,this.on("open",this.onOpen.bind(this)),this.on("close",this.onClose.bind(this)),this.on("socket_data",this.onData.bind(this))}close(){if(!1===this.autoReconnect&&(clearInterval(this.connectionCheckerIntervalID),this.connectionCheckerIntervalID=null),!this._closed){if(this._closed=!0,this.socket){if(0===this.socket.readyState){const t=this.socket;t.onopen=()=>{t&&t.close()},t.onmessage=null,t.onerror=null,t.onclose=null}else try{this.socket.close?.()}catch{}this.socket=null}this.promiseMap.clear(),this.cid="",this.boho&&(this.boho.isAuthorized=!1),this.state!==z.STOP&&this.stateChange("closed")&&this.emit("closed")}}stop(){this.autoReconnect=!1,this.close(),this.cid="",this.stateChange("stop","stop")}destroy(){this.stop(),this.removeAllListeners(),this.channels.clear(),this.linkMap.clear(),this.boho=null}keepAlive(){this.keepConnection(),Date.now()-this.lastTxRxTime>H.CLIENT_PING_PERIOD&&this.ping()}redirect(t){this.stateChange("redirecting","redirecting"),this.close(),this.createConnection(t)}open(t){this.socket&&this.close(),t&&(this.url=t),this.url?(this.createConnection(this.url),this._closed||this.connectionCheckerIntervalID||(this.connectionCheckerIntervalID=setInterval(this.keepAlive.bind(this),this.connectionCheckerPeriod))):this.emit("error",new Error("URL is not set."))}onOpen(){this._closed=!1,this.url.includes("wss://")?this.TLS=!0:this.TLS=!1,this.stateChange("open")}onClose(){this.close()}login(t,e){if(this.serverTimeNonce){this.auth(t,e),this.useAuth=!0;let r=this.boho.auth_req(this.serverTimeNonce);this.send(r),this.stateChange("auth_req","auth_req")}return this}auth(t,e){return t||e||this.emit("error",new Error("auth failed. no id and key.")),!e&&t.includes(".")?this.boho.set_id_key(t):t&&e?(this.boho.set_id8(t),this.boho.set_key(e)):this.emit("error",new Error("auth failed. no id or key.")),this.useAuth=!0,this}onData(t){let e,r=t[0];if(r===te.BohoMsg.ENC_488)e=this.boho.decrypt_488(t),e&&(r=e[0],t=e);else if(r===te.BohoMsg.ENC_E2E)try{if(e=this.boho.decrypt_488(t),!e)return;r=e[0],t.set(e,te.MetaSize.ENC_488),t=t.subarray(te.MetaSize.ENC_488)}catch(t){return}let n=G[r];switch(n||(n=te.BohoMsg[r]),r){case G.OVER_SIZE:console.log("## server sent: over_size event."),this.emit("over_size","over_size");break;case G.PING:this.pong();break;case G.PONG:break;case G.ECHO:try{let e=ne.decode(t.subarray(1));this.emit("echo",e)}catch(t){this.emit("error",new Error("ECHO data error"))}break;case G.IAM_RES:try{let e=ne.decode(t.subarray(1)),r=JSON.parse(e);r.ip&&(this.ip=r.ip),r.nick&&(this.nick=r.nick),r.did&&(this.did=r.did),r.uid&&(this.uid=r.uid),this.emit("iam_res",e)}catch(t){this.emit("error",new Error("IAM_RES data error"))}break;case G.CID_RES:let r=ne.decode(t.subarray(1));this.cid=r,this.stateChange("ready","cid_ready"),this.subscribe_channels();break;case G.QUOTA_LEVEL:let n=t[1];this.level=n,this.quota=q[n];break;case G.AUTH_CLEAR:this.useAuth=!1,this.boho.clearAuth(),this.stateChange("auth_clear","server request auth_clear."),this.stop();break;case G.SERVER_REDIRECT:let i,o,s;7==t.byteLength?(i=function(t){if(6!=t.byteLength)return;return t[0].toString()+"."+t[1].toString()+"."+t[2].toString()+"."+t[3].toString()+":"+((t[4]<<8)+t[5]).toString()}(t.subarray(1)),s="cong://"):(i=ne.decode(t.subarray(1)),s=""),o=s+i,this.redirect(o);break;case te.BohoMsg.SERVER_TIME_NONCE:if(t.copy(this.serverTimeNonce),!this.stateChange("server_ready","server_ready"))break;this.useAuth?(this.send(this.boho.auth_req(t)),this.stateChange("auth_req","auth_req")):this.send(ee.from([G.CID_REQ]));break;case G.SERVER_SIGNAL:try{let e=ne.decode(t.subarray(1)),r=JSON.parse(e);r.event&&r.data&&(this.serverSet=r.data,this.emit(r.event,r.data))}catch(t){this.emit("error",new Error("SERVER_SIGNAL parsing error"))}break;case G.SET:try{let e=k.unpack(t);e&&this.emit(e.topic,...e.args)}catch(t){this.emit("error",new Error("SET parsing error"))}break;case G.SIGNAL_E2E:case G.SIGNAL:try{let e=t.readUint8(1),r=t.subarray(2,2+e),n=ne.decode(r),i=t.readUint8(2+e),o=t.subarray(3+e);switch(i){case V.EMPTY:0===n.indexOf("@")?this.emit("@",n):(this.emit(n,n),this.emit("message",n));break;case V.TEXT:let t=o;0===o[o.byteLength-1]&&(t=o.subarray(0,o.byteLength-1));let e=ne.decode(t);0===n.indexOf("@")?this.emit("@",n,e):(this.emit(n,n,e),this.emit("message",n,e));break;case V.BINARY:0===n.indexOf("@")?this.emit("@",n,o):(this.emit(n,n,o),this.emit("message",n,o));break;case V.OBJECT:let r=ne.decode(o),i=JSON.parse(r);0===n.indexOf("@")?this.emit("@",n,i):(this.emit(n,n,i),this.emit("message",n,i));break;case V.MJSON:let s=ne.decode(o),f=JSON.parse(s);0===n.indexOf("@")?this.emit("@",n,...f):(this.emit(n,n,...f),this.emit("message",n,...f));break;case V.MBA:let u=k.unpack(o);0===n.indexOf("@")?this.emit("@",n,...u.args):(this.emit(n,n,...u.args),this.emit("message",n,...u.args))}}catch(t){console.log("IOCore IOMsg.SIGNAL parser err",t)}break;case G.RESPONSE_MBP:this.testPromise(t);break;case te.BohoMsg.AUTH_FAIL:this.boho.isAuthorized=!1,this.stateChange("auth_fail","auth_fail from server.");break;case te.BohoMsg.AUTH_RES:if(this.boho.verify_auth_res(t)){if(!this.stateChange("auth_res","server sent auth_res"))break;this.send(ee.from([G.CID_REQ]))}else this.boho.isAuthorized=!1,this.stateChange("auth_fail","verify_auth_res() invalid server_hmac");break;default:try{e=ne.decode(t),this.emit("text_message",e)}catch(t){}}}iam(t){t?this.send_enc_mode(k.pack(k.MB("#MsgType","8",G.IAM),k.MB("#",t))):this.send_enc_mode(k.pack(k.MB("#MsgType","8",G.IAM)))}ping(){this.send(ee.from([G.PING]))}pong(){this.send(ee.from([G.PONG]))}echo(t){t?this.send_enc_mode(k.pack(k.MB("#MsgType","8",G.ECHO),k.MB("#msg",t))):this.send(ee.from([G.ECHO]))}bin(...t){this.send(k.U8pack(...t))}send(t){if(t.byteLength>this.quota.signalSize)return this.emit("over_size"),console.log("## QUOTA LIMIT OVER!! \nsignal message.byteLength: ",t.byteLength),void console.log("## your maximum signalSize(bytes) is:",this.quota.signalSize);this.socket_send(t)}getEncryptionMode(){return!(this.encMode!==F.YES&&(this.encMode!==F.AUTO||this.TLS||!this.boho.isAuthorized))}send_enc_mode(t,e){if(void 0===e&&(e=this.getEncryptionMode()),t[0]==G.SIGNAL_E2E&&e){let e=t[1],r=this.boho.encrypt_488(t.subarray(0,3+e));r[0]=te.BohoMsg.ENC_E2E,this.send(ee.concat([r,t.subarray(3+e)]))}else if(e){let e=this.boho.encrypt_488(t);this.send(e)}else this.send(t)}setMsgPromise(t){return new Promise((e,r)=>{const n=setTimeout(e=>{this.promiseMap.has(t)&&(r("timeout"),this.promiseMap.delete(t))},this.promiseTimeOut);this.promiseMap.set(t,[e,r,n])})}testPromise(t){let e=k.unpack(t);if(e)if(this.promiseMap.has(e.mid)){let[t,r,n]=this.promiseMap.get(e.mid);clearTimeout(n),this.promiseMap.delete(e.mid),e.status<128?(e.ok=!0,t(e)):(e.ok=!1,r(e))}else console.log("no promise id")}publish(t,...e){this.signal(t,...e)}signal(t,...e){if("string"!=typeof t)throw TypeError("tag should be string.");t.startsWith("@")&&this.cid&&ie(this.cid+t);let r=J(t,...e);this.send_enc_mode(r)}decrypt_e2e(t,e){return this.boho.decrypt_e2e(t,e)}signal_e2e(t,e,r){const n=ie(t);if(t.startsWith("@")&&this.cid&&ie(this.cid+t),!this.boho.isAuthorized)return;let i=k.B8(e),o=this.boho.encrypt_e2e(i,r),s=k.pack(k.MB("#MsgType","8",G.SIGNAL_E2E),k.MB("#tagLen","8",n.byteLength),k.MB("#tag",n),k.MB("#payloadType","8",V.BINARY),k.MB("#payload",o));this.send_enc_mode(s)}set(t,...e){return t&&0!=e.length?this.call("store","set",t,...e):Promise.reject(new Error("set need storeName and value)"))}async get(t){if(!t)return Promise.reject(new Error("store get need storeName)"));let e=await this.call("store","get",t),{$:r}=k.unpack(e.body);return r}call(t,e,...r){if(!t||!e)return Promise.reject(new Error("request need target and topic)"));let n;return n=r.length>0?k.pack(k.MB("#MsgType","8",G.CALL),k.MB("mid","16",++this.mid),k.MB("target",t),k.MB("topic",e),k.MBA(...r)):k.pack(k.MB("#MsgType","8",G.CALL),k.MB("mid","16",++this.mid),k.MB("target",t),k.MB("topic",e)),this.send_enc_mode(n),this.setMsgPromise(this.mid)}subscribe(t){const e=ie(t);this.send_enc_mode(ee.concat([k.NB("8",G.SUBSCRIBE),k.NB("8",e.byteLength),e]))}subscribe_channels(){if(this.state!==z.READY||0===this.channels.size)return;const t=Array.from(this.channels).join(",").split(","),e=t.map(t=>ie(t).byteLength),r=[];let n=[],i=0;t.forEach((t,o)=>{n.length&&i+1+e[o]>H.TAG_LEN1&&(r.push(n.join(",")),n=[],i=0),i+=(n.length?1:0)+e[o],n.push(t)}),n.length&&r.push(n.join(",")),r.forEach(t=>this.subscribe(t))}unsubscribe(t=""){const e=ie(t);if(""==t)this.channels.clear();else{t.split(",").forEach(t=>{this.channels.delete(t)})}this.send_enc_mode(ee.concat([k.NB("8",G.UNSUBSCRIBE),k.NB("8",e.byteLength),e]))}listen(t,e){if("string"!=typeof t)throw TypeError("tag should be string.");if(ie(t,!1),"function"!=typeof e)throw TypeError("handler is not a function.");0!==t.indexOf("@")&&this.channels.add(t),this.on(t,e)}link(t,e,r){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");if("string"!=typeof e)throw TypeError("tag is not a string.");if(ie(e,!1),"function"!=typeof r)throw TypeError("handler is not a function.");let n;0!==e.indexOf("@")&&this.channels.add(e),n=this.linkMap.has(t)?this.linkMap.get(t):new Set,n.add(e),this.linkMap.set(t,n),this.on(e,r),this.subscribe(e)}unlink(t,e){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");if("string"!=typeof e)throw TypeError("tag is not a string.");ie(e,!1);const r=this.linkMap.get(t);r&&r.has(e)&&(this.unsubscribe(e),this.removeAllListeners(e),r.delete(e),0===r.size&&this.linkMap.delete(t))}unlinkAll(t){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");const e=this.linkMap.get(t);if(e){for(const t of e)this.unsubscribe(t),this.removeAllListeners(t);this.linkMap.delete(t)}}getMetric(){return{tx:this.txCounter,rx:this.rxCounter,txb:this.txBytes,rxb:this.rxBytes,last:(Date.now()-this.lastTxRxTime)/1e3}}getState(){return this.state}getStateName(){return z[this.state].toLowerCase()}getSecurity(){return{useAuth:this.useAuth,isTLS:this.TLS,isAuthorized:this.boho.isAuthorized,encMode:this.encMode,usingEncryption:this.getEncryptionMode()}}stateChange(t,e){let r=t.toLowerCase();const n=z[t.toUpperCase()];if("number"!=typeof n)throw new TypeError("Unknown state: "+t);const i=this.state!==n;this.state=n,this.stateName=r,i&&this._stateRevision++;const o=this._stateRevision;return i&&this.emit("change",r),o===this._stateRevision&&(e&&this.emit(r,e),o===this._stateRevision)}}const se=te.Buffer;class fe extends oe{static version="6.1.2";static binaryType="arraybuffer";static Boho=te;static MBP=te.MBP;static Buffer=te.Buffer;static constants=Y;static instanceCount=0;static webSocketCount=0;constructor(t){super(t),fe.instanceCount++,this.boundBrowserVisiblePing=this.browserVisiblePing.bind(this),document.addEventListener("visibilitychange",this.boundBrowserVisiblePing),t&&this.open()}browserVisiblePing(){"visible"===document.visibilityState&&this.ping()}stop(){super.stop()}destroy(){document.removeEventListener("visibilitychange",this.boundBrowserVisiblePing),super.destroy()}keepConnection(){this.autoReconnect&&(this.socket&&this.socket.readyState!==WebSocket.CLOSED||this.open())}createConnection(t){fe.webSocketCount++;const e=this.socket=new WebSocket(t);this._closed=!1,this.socket.binaryType=fe.binaryType,this.socket.onopen=()=>{this.socket===e&&("arraybuffer"==this.socket.binaryType?this.socket.onmessage=t=>{this.socket===e&&this.onWebSocketMessage(t)}:this.socket.onmessage=t=>{this.socket===e&&this.onWebSocketMessageBlob(t)},this.emit("open"))},this.socket.onerror=t=>{this.socket===e&&this.emit("error",t)},this.socket.onclose=()=>{this.socket===e&&this.emit("close")},this.stateChange("connecting","connecting")}onWebSocketMessage(t){this.rxCounter++,this.lastTxRxTime=Date.now();let e=se.from(t.data);this.rxBytes+=e.byteLength,this.emit("socket_data",e)}async onWebSocketMessageBlob(t){const e=this.socket;let r;if(this.rxCounter++,this.lastTxRxTime=Date.now(),t.data instanceof Blob){let e=await t.data.arrayBuffer();r=se.from(e)}else r=se.from(t.data);this.rxBytes+=r.byteLength,this.socket===e&&this.emit("socket_data",r)}socket_send(t){1===this.socket?.readyState?(this.socket.send(t),this.txCounter++,this.txBytes+=t.byteLength,this.lastTxRxTime=Date.now()):console.log(".")}}export{fe as default};
|
|
22
|
+
*/var Yt=(zt||(zt=1,function(t){const e=function(){if(Dt)return Ht;Dt=1,Ht.byteLength=function(t){var e=o(t),r=e[0],n=e[1];return 3*(r+n)/4-n},Ht.toByteArray=function(t){var n,i,s=o(t),f=s[0],u=s[1],h=new r(function(t,e,r){return 3*(e+r)/4-r}(0,f,u)),a=0,c=u>0?f-4:f;for(i=0;i<c;i+=4)n=e[t.charCodeAt(i)]<<18|e[t.charCodeAt(i+1)]<<12|e[t.charCodeAt(i+2)]<<6|e[t.charCodeAt(i+3)],h[a++]=n>>16&255,h[a++]=n>>8&255,h[a++]=255&n;return 2===u&&(n=e[t.charCodeAt(i)]<<2|e[t.charCodeAt(i+1)]>>4,h[a++]=255&n),1===u&&(n=e[t.charCodeAt(i)]<<10|e[t.charCodeAt(i+1)]<<4|e[t.charCodeAt(i+2)]>>2,h[a++]=n>>8&255,h[a++]=255&n),h},Ht.fromByteArray=function(e){for(var r,n=e.length,i=n%3,o=[],s=16383,u=0,h=n-i;u<h;u+=s)o.push(f(e,u,u+s>h?h:u+s));return 1===i?(r=e[n-1],o.push(t[r>>2]+t[r<<4&63]+"==")):2===i&&(r=(e[n-2]<<8)+e[n-1],o.push(t[r>>10]+t[r>>4&63]+t[r<<2&63]+"=")),o.join("")};for(var t=[],e=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)t[i]=n[i],e[n.charCodeAt(i)]=i;function o(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function s(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[63&e]}function f(t,e,r){for(var n,i=[],o=e;o<r;o+=3)n=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(255&t[o+2]),i.push(s(n));return i.join("")}return e["-".charCodeAt(0)]=62,e["_".charCodeAt(0)]=63,Ht}(),r=Gt(),n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=s,t.SlowBuffer=function(t){return+t!=t&&(t=0),s.alloc(+t)},t.INSPECT_MAX_BYTES=50;const i=2147483647;function o(t){if(t>i)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,s.prototype),e}function s(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return h(t)}return f(t,e,r)}function f(t,e,r){if("string"==typeof t)return function(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!s.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|p(t,e);let n=o(r);const i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(q(t,Uint8Array)){const e=new Uint8Array(t);return c(e.buffer,e.byteOffset,e.byteLength)}return a(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(q(t,ArrayBuffer)||t&&q(t.buffer,ArrayBuffer))return c(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(q(t,SharedArrayBuffer)||t&&q(t.buffer,SharedArrayBuffer)))return c(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return s.from(n,e,r);const i=function(t){if(s.isBuffer(t)){const e=0|l(t.length),r=o(e);return 0===r.length||t.copy(r,0,0,e),r}return void 0!==t.length?"number"!=typeof t.length||K(t.length)?o(0):a(t):"Buffer"===t.type&&Array.isArray(t.data)?a(t.data):void 0}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return s.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function u(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function h(t){return u(t),o(t<0?0:0|l(t))}function a(t){const e=t.length<0?0:0|l(t.length),r=o(e);for(let n=0;n<e;n+=1)r[n]=255&t[n];return r}function c(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===e&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,e):new Uint8Array(t,e,r),Object.setPrototypeOf(n,s.prototype),n}function l(t){if(t>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|t}function p(t,e){if(s.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||q(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return V(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(t).length;default:if(i)return n?-1:V(t).length;e=(""+e).toLowerCase(),i=!0}}function y(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return I(this,e,r);case"ascii":return U(this,e,r);case"latin1":case"binary":return L(this,e,r);case"base64":return A(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function g(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function d(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),K(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=s.from(e,n)),s.isBuffer(e))return 0===e.length?-1:b(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):b(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(t,e,r,n,i){let o,s=1,f=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,f/=2,u/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){let n=-1;for(o=r;o<f;o++)if(h(t,o)===h(e,-1===n?0:o-n)){if(-1===n&&(n=o),o-n+1===u)return n*s}else-1!==n&&(o-=o-n),n=-1}else for(r+u>f&&(r=f-u),o=r;o>=0;o--){let r=!0;for(let n=0;n<u;n++)if(h(t,o+n)!==h(e,n)){r=!1;break}if(r)return o}return-1}function w(t,e,r,n){r=Number(r)||0;const i=t.length-r;n?(n=Number(n))>i&&(n=i):n=i;const o=e.length;let s;for(n>o/2&&(n=o/2),s=0;s<n;++s){const n=parseInt(e.substr(2*s,2),16);if(K(n))return s;t[r+s]=n}return s}function E(t,e,r,n){return Y(V(e,t.length-r),t,r,n)}function B(t,e,r,n){return Y(function(t){const e=[];for(let r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function m(t,e,r,n){return Y(G(e),t,r,n)}function _(t,e,r,n){return Y(function(t,e){let r,n,i;const o=[];for(let s=0;s<t.length&&!((e-=2)<0);++s)r=t.charCodeAt(s),n=r>>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function A(t,r,n){return 0===r&&n===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(r,n))}function I(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i<r;){const e=t[i];let o=null,s=e>239?4:e>223?3:e>191?2:1;if(i+s<=r){let r,n,f,u;switch(s){case 1:e<128&&(o=e);break;case 2:r=t[i+1],128==(192&r)&&(u=(31&e)<<6|63&r,u>127&&(o=u));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(u=(15&e)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(o=u));break;case 4:r=t[i+1],n=t[i+2],f=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&f)&&(u=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&f,u>65535&&u<1114112&&(o=u))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(t){const e=t.length;if(e<=v)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=v));return r}(n)}t.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=function(){try{const t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),42===t.foo()}catch(t){return!1}}(),s.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(t,e,r){return f(t,e,r)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(t,e,r){return function(t,e,r){return u(t),t<=0?o(t):void 0!==e?"string"==typeof r?o(t).fill(e,r):o(t).fill(e):o(t)}(t,e,r)},s.allocUnsafe=function(t){return h(t)},s.allocUnsafeSlow=function(t){return h(t)},s.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==s.prototype},s.compare=function(t,e){if(q(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),q(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(t)||!s.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;let r=t.length,n=e.length;for(let i=0,o=Math.min(r,n);i<o;++i)if(t[i]!==e[i]){r=t[i],n=e[i];break}return r<n?-1:n<r?1:0},s.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(t,e){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return s.alloc(0);let r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;const n=s.allocUnsafe(e);let i=0;for(r=0;r<t.length;++r){let e=t[r];if(q(e,Uint8Array))i+e.length>n.length?(s.isBuffer(e)||(e=s.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!s.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},s.byteLength=p,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;e<t;e+=2)g(this,e,e+1);return this},s.prototype.swap32=function(){const t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let e=0;e<t;e+=4)g(this,e,e+3),g(this,e+1,e+2);return this},s.prototype.swap64=function(){const t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let e=0;e<t;e+=8)g(this,e,e+7),g(this,e+1,e+6),g(this,e+2,e+5),g(this,e+3,e+4);return this},s.prototype.toString=function(){const t=this.length;return 0===t?"":0===arguments.length?I(this,0,t):y.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(t){if(!s.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===s.compare(this,t)},s.prototype.inspect=function(){let e="";const r=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},n&&(s.prototype[n]=s.prototype.inspect),s.prototype.compare=function(t,e,r,n,i){if(q(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let o=(i>>>=0)-(n>>>=0),f=(r>>>=0)-(e>>>=0);const u=Math.min(o,f),h=this.slice(n,i),a=t.slice(e,r);for(let t=0;t<u;++t)if(h[t]!==a[t]){o=h[t],f=a[t];break}return o<f?-1:f<o?1:0},s.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},s.prototype.indexOf=function(t,e,r){return d(this,t,e,r,!0)},s.prototype.lastIndexOf=function(t,e,r){return d(this,t,e,r,!1)},s.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return w(this,t,e,r);case"utf8":case"utf-8":return E(this,t,e,r);case"ascii":case"latin1":case"binary":return B(this,t,e,r);case"base64":return m(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const v=4096;function U(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(127&t[i]);return n}function L(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function T(t,e,r){const n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);let i="";for(let n=e;n<r;++n)i+=J[t[n]];return i}function S(t,e,r){const n=t.slice(e,r);let i="";for(let t=0;t<n.length-1;t+=2)i+=String.fromCharCode(n[t]+256*n[t+1]);return i}function R(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,r,n,i,o){if(!s.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<o)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function M(t,e,r,n,i){j(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,r}function C(t,e,r,n,i){j(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r+7]=o,o>>=8,t[r+6]=o,o>>=8,t[r+5]=o,o>>=8,t[r+4]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=s,s>>=8,t[r+2]=s,s>>=8,t[r+1]=s,s>>=8,t[r]=s,r+8}function N(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function k(t,e,n,i,o){return e=+e,n>>>=0,o||N(t,0,n,4),r.write(t,e,n,i,23,4),n+4}function x(t,e,n,i,o){return e=+e,n>>>=0,o||N(t,0,n,8),r.write(t,e,n,i,52,8),n+8}s.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e<t&&(e=t);const n=this.subarray(t,e);return Object.setPrototypeOf(n,s.prototype),n},s.prototype.readUintLE=s.prototype.readUIntLE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t],i=1,o=0;for(;++o<e&&(i*=256);)n+=this[t+o]*i;return n},s.prototype.readUintBE=s.prototype.readUIntBE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},s.prototype.readUint8=s.prototype.readUInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),this[t]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]|this[t+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]<<8|this[t+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},s.prototype.readBigUInt64LE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))}),s.prototype.readBigUInt64BE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)}),s.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t],i=1,o=0;for(;++o<e&&(i*=256);)n+=this[t+o]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*e)),n},s.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=e,i=1,o=this[t+--n];for(;n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},s.prototype.readInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},s.prototype.readInt16LE=function(t,e){t>>>=0,e||R(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(t,e){t>>>=0,e||R(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},s.prototype.readInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},s.prototype.readBigInt64LE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(e+256*this[++t]+65536*this[++t]+this[++t]*2**24)}),s.prototype.readBigInt64BE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<<BigInt(32))+BigInt(this[++t]*2**24+65536*this[++t]+256*this[++t]+r)}),s.prototype.readFloatLE=function(t,e){return t>>>=0,e||R(t,4,this.length),r.read(this,t,!0,23,4)},s.prototype.readFloatBE=function(t,e){return t>>>=0,e||R(t,4,this.length),r.read(this,t,!1,23,4)},s.prototype.readDoubleLE=function(t,e){return t>>>=0,e||R(t,8,this.length),r.read(this,t,!0,52,8)},s.prototype.readDoubleBE=function(t,e){return t>>>=0,e||R(t,8,this.length),r.read(this,t,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||O(this,t,e,r,Math.pow(2,8*r)-1,0);let i=1,o=0;for(this[e]=255&t;++o<r&&(i*=256);)this[e+o]=t/i&255;return e+r},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||O(this,t,e,r,Math.pow(2,8*r)-1,0);let i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},s.prototype.writeUint8=s.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,1,255,0),this[e]=255&t,e+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeBigUInt64LE=Q(function(t,e=0){return M(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(t,e=0){return C(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);O(this,t,e,r,n-1,-n)}let i=0,o=1,s=0;for(this[e]=255&t;++i<r&&(o*=256);)t<0&&0===s&&0!==this[e+i-1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},s.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);O(this,t,e,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[e+i]=255&t;--i>=0&&(o*=256);)t<0&&0===s&&0!==this[e+i+1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},s.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},s.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},s.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeBigInt64LE=Q(function(t,e=0){return M(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(t,e=0){return C(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(t,e,r){return k(this,t,e,!0,r)},s.prototype.writeFloatBE=function(t,e,r){return k(this,t,e,!1,r)},s.prototype.writeDoubleLE=function(t,e,r){return x(this,t,e,!0,r)},s.prototype.writeDoubleBE=function(t,e,r){return x(this,t,e,!1,r)},s.prototype.copy=function(t,e,r,n){if(!s.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-r&&(n=t.length-e+r);const i=n-r;return this===t&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(e,r,n):Uint8Array.prototype.set.call(t,this.subarray(r,n),e),i},s.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){const e=t.charCodeAt(0);("utf8"===n&&e<128||"latin1"===n)&&(t=e)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;let i;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i<r;++i)this[i]=t;else{const o=s.isBuffer(t)?t:s.from(t,n),f=o.length;if(0===f)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(i=0;i<r-e;++i)this[i+e]=o[i%f]}return this};const P={};function $(t,e,r){P[t]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(t){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:t,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}function D(t){let e="",r=t.length;const n="-"===t[0]?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function j(t,e,r,n,i,o){if(t>r||t<e){const r="bigint"==typeof e?"n":"";let n;throw n=0===e||e===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(o+1)}${r}`:`>= -(2${r} ** ${8*(o+1)-1}${r}) and < 2 ** ${8*(o+1)-1}${r}`,new P.ERR_OUT_OF_RANGE("value",n,t)}!function(t,e,r){z(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||F(e,t.length-(r+1))}(n,i,o)}function z(t,e){if("number"!=typeof t)throw new P.ERR_INVALID_ARG_TYPE(e,"number",t)}function F(t,e,r){if(Math.floor(t)!==t)throw z(t,r),new P.ERR_OUT_OF_RANGE("offset","an integer",t);if(e<0)throw new P.ERR_BUFFER_OUT_OF_BOUNDS;throw new P.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${e}`,t)}$("ERR_BUFFER_OUT_OF_BOUNDS",function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),$("ERR_INVALID_ARG_TYPE",function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`},TypeError),$("ERR_OUT_OF_RANGE",function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=D(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=D(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);const H=/[^+/0-9A-Za-z-_]/g;function V(t,e){let r;e=e||1/0;const n=t.length;let i=null;const o=[];for(let s=0;s<n;++s){if(r=t.charCodeAt(s),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function G(t){return e.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(H,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Y(t,e,r,n){let i;for(i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function q(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function K(t){return t!=t}const J=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Q(t){return"undefined"==typeof BigInt?W:t}function W(){throw new Error("BigInt not supported")}}(Ft)),Ft);let qt={SERVER_TIME_NONCE:176,AUTH_REQ:177,AUTH_RES:178,AUTH_FAIL:179,ENC_PACK:182,ENC_E2E:183,ENC_488:184};for(let t in qt)qt[qt[t]]=t;const Kt={SERVER_TIME_NONCE:Pt.meta(Pt.MB("header","8",0),Pt.MB("unixTime","32L",0),Pt.MB("milTime","16L",0),Pt.MB("counter","16L",0),Pt.MB("nonce",Yt.Buffer.alloc(4))),AUTH_REQ:Pt.meta(Pt.MB("header","8",0),Pt.MB("id8",Yt.Buffer.alloc(8)),Pt.MB("nonce",Yt.Buffer.alloc(4)),Pt.MB("hmac32",Yt.Buffer.alloc(32))),AUTH_RES:Pt.meta(Pt.MB("header","8",0),Pt.MB("hmac32",Yt.Buffer.alloc(32))),ENC_PACK:Pt.meta(Pt.MB("type","8",0),Pt.MB("len","32L",0),Pt.MB("salt12",Yt.Buffer.alloc(12)),Pt.MB("hmac",8,0)),ENC_488:Pt.meta(Pt.MB("type","8",0),Pt.MB("len","32L",0),Pt.MB("otpSrc8",Yt.Buffer.alloc(8)),Pt.MB("hmac8",Yt.Buffer.alloc(8)))};function Jt(t){let e=t[t.length-1];return e[2]+e[3]}const Qt={SERVER_TIME_NONCE:Jt(Kt.SERVER_TIME_NONCE),AUTH_REQ:Jt(Kt.AUTH_REQ),AUTH_RES:Jt(Kt.AUTH_RES),ENC_PACK:Jt(Kt.ENC_PACK),ENC_488:Jt(Kt.ENC_488)};function Wt(t,e){if(!(t instanceof Uint8Array&&e instanceof Uint8Array&&t.length===e.length))return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return 0===r}function Xt(t,e,r,n,i=!1){if(!(t instanceof Uint8Array))return;const o=Yt.Buffer.from(t);return o.length<r||o[0]!==e||(i?o.readUInt32LE(1)!==o.length-r:o.length!==r)?void 0:Pt.unpack(o,n)}function Zt(t){return globalThis.crypto.getRandomValues(Yt.Buffer.alloc(t))}class te{constructor(){this._id8=Yt.Buffer.alloc(8),this._otpSrc44=Yt.Buffer.alloc(44),this._otp36=Yt.Buffer.alloc(36),this._hmac=Yt.Buffer.alloc(32),this.auth_salt12=Yt.Buffer.alloc(12),this.localNonce=Yt.Buffer.alloc(4),this.remoteNonce=Yt.Buffer.alloc(4),this.isAuthorized=!1,this.counter=0,this._hasKey=!1,this._lastSendTime=0}clearAuth(){this._id8.fill(0),this._otpSrc44.fill(0),this._otp36.fill(0),this._hmac.fill(0),this.auth_salt12.fill(0),this.localNonce.fill(0),this.remoteNonce.fill(0),this.isAuthorized=!1,this.counter=0,this._hasKey=!1,this._lastSendTime=0}set_hash_id8(t){Pt.B8($t.hash(t)).copy(this._id8,0,0,8)}set_id8(t){let e=Pt.B8(t);this._id8.fill(0),e.copy(this._id8,0,0,8)}set_key(t){const e=Pt.B8(t);if(!e||0===e.length)throw new TypeError("Key must not be empty");this.copy_key(Pt.B8($t.hash(e)))}set_id_key(t){let e=t.indexOf(".");if(-1==e)return;let r=t.substring(0,e),n=t.substring(e+1);this.set_id8(r),this.set_key(n)}copy_id8(t){t.copy(this._id8,0,0,8)}copy_key(t){if(!(t instanceof Uint8Array)||32!==t.length)throw new TypeError("copy_key requires exactly 32 bytes");this._otpSrc44.set(t,0),this._hasKey=!0}sha256_n(t,e){let r=$t.hash(t);for(let t=0;t<e;t++)r=$t.hash(r);return r}set_clock_rand(){this.set_clock_nonce(Zt(4))}set_clock_nonce(t){if(!(t instanceof Uint8Array)||4!==t.length)throw new TypeError("Nonce must be 4 bytes");let e=Math.max(Date.now(),this._lastSendTime);if(this.counter=this.counter+1&65535,0===this.counter&&e===this._lastSendTime&&e++,!Number.isSafeInteger(e)||e<0||Math.floor(e/1e3)>4294967295)throw new RangeError("Clock is outside the protocol range");this._lastSendTime=e,Yt.Buffer.concat([Pt.NB("32L",Math.floor(e/1e3)),Pt.NB("16L",e%1e3),Pt.NB("16L",this.counter),Yt.Buffer.from(t)]).copy(this._otpSrc44,32)}_requireKey(){if(!this._hasKey)throw new Error("Set a key before encryption or authentication")}set_salt12(t,e){if(12!=t.byteLength)throw TypeError("set_salt12: Invalid salt12 byteLength.");t.copy(this._otpSrc44,32)}resetOTP(){this._requireKey(),Pt.B8($t.hash(this._otpSrc44)).copy(this._otp36,0,0,32)}getIndexOTP(t){return this._otp36.writeUInt32LE(t,32),$t.hash(this._otp36)}generateHMAC(t){this._requireKey();let e=Yt.Buffer.concat([this._otpSrc44,t]);this._hmac=Pt.B8($t.hash(e))}getHMAC8(t){this._requireKey();let e=Yt.Buffer.concat([this._otpSrc44,t]);return this._hmac=Pt.B8($t.hash(e)),this._hmac.subarray(0,8)}xotp(t,e=0,r=!1){let n=(t=Pt.B8(t,r)).byteLength,i=e,o=0,s=0;for(;n>0;){s=n<32?n:32;let e=this.getIndexOTP(++i);for(let r=0;r<s;r++)t[o++]^=e[r];n-=32}return t}server_time_nonce(){const t=Date.now(),e=Math.floor(t/1e3),r=t%1e3;return this.localNonce=Zt(4),this.auth_salt12=Yt.Buffer.concat([Pt.NB("32L",e),Pt.NB("16L",r),Zt(2),this.localNonce]),Yt.Buffer.concat([Pt.NB("8",qt.SERVER_TIME_NONCE),this.auth_salt12])}auth_req(t){if(!this._hasKey)return!1;let e=Xt(t,qt.SERVER_TIME_NONCE,Qt.SERVER_TIME_NONCE,Kt.SERVER_TIME_NONCE);if(e&&e.milTime>=1e3)return!1;if(e){let t=Yt.Buffer.concat([Pt.NB("32L",e.unixTime),Pt.NB("16L",e.milTime),Pt.NB("16L",e.counter),e.nonce]);return this.set_salt12(t,"auth_req"),this.localNonce=Zt(4),this.generateHMAC(this.localNonce),this.remoteNonce=e.nonce,Pt.pack(Pt.MB("#header","8",qt.AUTH_REQ),Pt.MB("#id8",this._id8),Pt.MB("#nonce",this.localNonce),Pt.MB("#hmac32",this._hmac))}return!1}verify_auth_req(t){if(!this._hasKey)return!1;let e;if(t instanceof Uint8Array?e=Xt(t,qt.AUTH_REQ,Qt.AUTH_REQ,Kt.AUTH_REQ):t&&"object"==typeof t&&(e=t),!e||e.header!==qt.AUTH_REQ||!(e.id8 instanceof Uint8Array)||8!==e.id8.length||!(e.nonce instanceof Uint8Array)||4!==e.nonce.length||!(e.hmac32 instanceof Uint8Array)||32!==e.hmac32.length||e.$OTHERS&&0!==e.$OTHERS.length)return!1;this.set_salt12(this.auth_salt12,"verify_auth_req 1/2"),this.generateHMAC(e.nonce);let r=this._hmac;if(Wt(e.hmac32,r)){this.remoteNonce=Yt.Buffer.from(e.nonce);let t=Yt.Buffer.concat([this.localNonce,this.remoteNonce,this.localNonce]);this.set_salt12(t,"verify_auth_req 2/2"),this.generateHMAC(e.nonce);let r=this._hmac,n=Pt.rawPack(Pt.MB("header","8",qt.AUTH_RES),Pt.MB("hmac32",r));return this.isAuthorized=!0,n}return!1}verify_auth_res(t){if(!this._hasKey)return!1;let e=Xt(t,qt.AUTH_RES,Qt.AUTH_RES,Kt.AUTH_RES);if(e){let t=Yt.Buffer.concat([this.remoteNonce,this.localNonce,this.remoteNonce]);if(this.set_salt12(t,"verify_auth_res"),this.generateHMAC(this.localNonce),Wt(this._hmac,e.hmac32))return this.isAuthorized=!0,!0}}encrypt_488(t){if(!this.isAuthorized||!this._hasKey)return;t=Pt.B8(t),this.set_clock_nonce(this.remoteNonce),this.resetOTP();let e=this.getHMAC8(t),r=this.xotp(t);return Pt.pack(Pt.MB("#type","8",qt.ENC_488),Pt.MB("#len","32L",t.byteLength),Pt.MB("#otpSrc8",this._otpSrc44.subarray(32,40)),Pt.MB("#hmac8",e),Pt.MB("#xdata",r))}decrypt_488(t){if(!this.isAuthorized||!this._hasKey)return;let e=t;if(t instanceof Uint8Array&&t[0]===qt.ENC_E2E){if(t.length<Qt.ENC_488)return;const r=Yt.Buffer.from(t),n=r.readUInt32LE(1);if(n>r.length-Qt.ENC_488)return;e=Yt.Buffer.from(r.subarray(0,Qt.ENC_488+n)),e[0]=qt.ENC_488}const r=Xt(e,qt.ENC_488,Qt.ENC_488,Kt.ENC_488,!0);if(!(r&&(n=r.otpSrc8,n.readUInt16LE(4)<1e3)))return;var n;this.set_salt12(Yt.Buffer.concat([r.otpSrc8,this.localNonce]),"decrypt_488"),this.resetOTP();const i=this.xotp(r.$OTHERS??Yt.Buffer.alloc(0));return Wt(this.getHMAC8(i),r.hmac8)?i:void 0}encryptPack(t){this._requireKey(),t=Pt.B8(t),this.set_clock_rand(),this.resetOTP();let e=this.getHMAC8(t),r=this.xotp(t);return Pt.pack(Pt.MB("#type","8",qt.ENC_PACK),Pt.MB("#len","32L",t.byteLength),Pt.MB("#salt12",this._otpSrc44.subarray(32)),Pt.MB("#hmac8",e),Pt.MB("#xdata",r))}decryptPack(t){if(!this._hasKey)return;const e=Xt(t,qt.ENC_PACK,Qt.ENC_PACK,Kt.ENC_PACK,!0);if(!e)return;this.set_salt12(e.salt12,"decryptPack"),this.resetOTP();const r=this.xotp(e.$OTHERS??Yt.Buffer.alloc(0));return Wt(e.hmac,this.getHMAC8(r))?(e.data=r,e):void 0}encrypt_e2e(t,e){return this._withKey(e,()=>this.encryptPack(t))}decrypt_e2e(t,e){return this._withKey(e,()=>this.decryptPack(t))}_withKey(t,e){const r=Pt.B8(t);if(!r||0===r.length)throw new TypeError("Key must not be empty");const n=[Yt.Buffer.from(this._otpSrc44),Yt.Buffer.from(this._otp36),Yt.Buffer.from(this._hmac)],i=this._hasKey;try{return this._otpSrc44.set($t.hash(r),0),this._hasKey=!0,e()}finally{this._otpSrc44.set(n[0]),this._otp36.set(n[1]),this._hmac.set(n[2]),this._hasKey=i;for(const t of n)t.fill(0)}}}te.RAND=Zt,te.BohoMsg=qt,te.Meta=Kt,te.MetaSize=Qt,te.sha256=$t,te.MBP=Pt,te.Buffer=Yt.Buffer;const ee=k.Buffer,re=new TextEncoder,ne=new TextDecoder;function ie(t,e=!0){if("string"!=typeof t)throw TypeError("tag should be string.");const r=re.encode(t);if(!e&&0===r.byteLength||r.byteLength>H.TAG_LEN1)throw TypeError("tag UTF-8 byte length must be "+(e?"0":"1")+"~255");return r}class oe extends j{constructor(t){super(),this.cid="",this.ip="",this.socket=null,this.url=t,this.state=z.CLOSED,this.stateName=this.getStateName(),this._stateRevision=0,this.txCounter=0,this.rxCounter=0,this.txBytes=0,this.rxBytes=0,this.lastTxRxTime=Date.now(),this.connectionCheckerPeriod=H.CONNECTION_CHECKER_PERIOD,this.connectionCheckerIntervalID=null,this.boho=new te,this.serverTimeNonce=ee.alloc(te.MetaSize.SERVER_TIME_NONCE),this.TLS=!1,this.encMode=F.AUTO,this.useAuth=!1,this.nick="",this.channels=new Set,this.promiseMap=new Map,this.promiseTimeOut=H.PROMISE_TIMEOUT,this.mid=0,this.level=3,this.quota=q[this.level],this.serverSet={},this.linkMap=new Map,this.autoReconnect=!0,this._closed=!1,this.on("open",this.onOpen.bind(this)),this.on("close",this.onClose.bind(this)),this.on("socket_data",this.onData.bind(this))}close(){if(!1===this.autoReconnect&&(clearInterval(this.connectionCheckerIntervalID),this.connectionCheckerIntervalID=null),!this._closed){if(this._closed=!0,this.socket){if(0===this.socket.readyState){const t=this.socket;t.onopen=()=>{t&&t.close()},t.onmessage=null,t.onerror=null,t.onclose=null}else try{this.socket.close?.()}catch{}this.socket=null}this.promiseMap.clear(),this.cid="",this.boho&&(this.boho.isAuthorized=!1),this.state!==z.STOP&&this.stateChange("closed")&&this.emit("closed")}}stop(){this.autoReconnect=!1,this.close(),this.cid="",this.stateChange("stop","stop")}destroy(){this.stop(),this.removeAllListeners(),this.channels.clear(),this.linkMap.clear(),this.boho=null}keepAlive(){this.keepConnection(),Date.now()-this.lastTxRxTime>H.CLIENT_PING_PERIOD&&this.ping()}redirect(t){this.stateChange("redirecting","redirecting"),this.close(),this.createConnection(t)}open(t){this.socket&&this.close(),t&&(this.url=t),this.url?(this.createConnection(this.url),this._closed||this.connectionCheckerIntervalID||(this.connectionCheckerIntervalID=setInterval(this.keepAlive.bind(this),this.connectionCheckerPeriod))):this.emit("error",new Error("URL is not set."))}onOpen(){this._closed=!1,this.url.includes("wss://")?this.TLS=!0:this.TLS=!1,this.stateChange("open")}onClose(){this.close()}login(t,e){if(this.serverTimeNonce){this.auth(t,e),this.useAuth=!0;let r=this.boho.auth_req(this.serverTimeNonce);this.send(r),this.stateChange("auth_req","auth_req")}return this}auth(t,e){return t||e||this.emit("error",new Error("auth failed. no id and key.")),!e&&t.includes(".")?this.boho.set_id_key(t):t&&e?(this.boho.set_id8(t),this.boho.set_key(e)):this.emit("error",new Error("auth failed. no id or key.")),this.useAuth=!0,this}onData(t){let e,r=t[0];if(r===te.BohoMsg.ENC_488)e=this.boho.decrypt_488(t),e&&(r=e[0],t=e);else if(r===te.BohoMsg.ENC_E2E)try{if(e=this.boho.decrypt_488(t),!e)return;r=e[0],t.set(e,te.MetaSize.ENC_488),t=t.subarray(te.MetaSize.ENC_488)}catch(t){return}let n=G[r];switch(n||(n=te.BohoMsg[r]),r){case G.OVER_SIZE:console.log("## server sent: over_size event."),this.emit("over_size","over_size");break;case G.PING:this.pong();break;case G.PONG:break;case G.ECHO:try{let e=ne.decode(t.subarray(1));this.emit("echo",e)}catch(t){this.emit("error",new Error("ECHO data error"))}break;case G.IAM_RES:try{let e=ne.decode(t.subarray(1)),r=JSON.parse(e);r.ip&&(this.ip=r.ip),r.nick&&(this.nick=r.nick),r.did&&(this.did=r.did),r.uid&&(this.uid=r.uid),this.emit("iam_res",e)}catch(t){this.emit("error",new Error("IAM_RES data error"))}break;case G.CID_RES:let r=ne.decode(t.subarray(1));this.cid=r,this.stateChange("ready","cid_ready"),this.subscribe_channels();break;case G.QUOTA_LEVEL:let n=t[1];this.level=n,this.quota=q[n];break;case G.AUTH_CLEAR:this.useAuth=!1,this.boho.clearAuth(),this.stateChange("auth_clear","server request auth_clear."),this.stop();break;case G.SERVER_REDIRECT:let i,o,s;7==t.byteLength?(i=function(t){if(6!=t.byteLength)return;return t[0].toString()+"."+t[1].toString()+"."+t[2].toString()+"."+t[3].toString()+":"+((t[4]<<8)+t[5]).toString()}(t.subarray(1)),s="cong://"):(i=ne.decode(t.subarray(1)),s=""),o=s+i,this.redirect(o);break;case te.BohoMsg.SERVER_TIME_NONCE:if(t.copy(this.serverTimeNonce),!this.stateChange("server_ready","server_ready"))break;this.useAuth?(this.send(this.boho.auth_req(t)),this.stateChange("auth_req","auth_req")):this.send(ee.from([G.CID_REQ]));break;case G.SERVER_SIGNAL:try{let e=ne.decode(t.subarray(1)),r=JSON.parse(e);r.event&&r.data&&(this.serverSet=r.data,this.emit(r.event,r.data))}catch(t){this.emit("error",new Error("SERVER_SIGNAL parsing error"))}break;case G.SET:try{let e=k.unpack(t);e&&this.emit(e.topic,...e.args)}catch(t){this.emit("error",new Error("SET parsing error"))}break;case G.SIGNAL_E2E:case G.SIGNAL:try{let e=t.readUint8(1),r=t.subarray(2,2+e),n=ne.decode(r),i=t.readUint8(2+e),o=t.subarray(3+e);switch(i){case V.EMPTY:0===n.indexOf("@")?this.emit("@",n):(this.emit(n,n),this.emit("message",n));break;case V.TEXT:let t=o;0===o[o.byteLength-1]&&(t=o.subarray(0,o.byteLength-1));let e=ne.decode(t);0===n.indexOf("@")?this.emit("@",n,e):(this.emit(n,n,e),this.emit("message",n,e));break;case V.BINARY:0===n.indexOf("@")?this.emit("@",n,o):(this.emit(n,n,o),this.emit("message",n,o));break;case V.OBJECT:let r=ne.decode(o),i=JSON.parse(r);0===n.indexOf("@")?this.emit("@",n,i):(this.emit(n,n,i),this.emit("message",n,i));break;case V.MJSON:let s=ne.decode(o),f=JSON.parse(s);0===n.indexOf("@")?this.emit("@",n,...f):(this.emit(n,n,...f),this.emit("message",n,...f));break;case V.MBA:let u=k.unpack(o);0===n.indexOf("@")?this.emit("@",n,...u.args):(this.emit(n,n,...u.args),this.emit("message",n,...u.args))}}catch(t){console.log("IOCore IOMsg.SIGNAL parser err",t)}break;case G.RESPONSE_MBP:this.testPromise(t);break;case te.BohoMsg.AUTH_FAIL:this.boho.isAuthorized=!1,this.stateChange("auth_fail","auth_fail from server.");break;case te.BohoMsg.AUTH_RES:if(this.boho.verify_auth_res(t)){if(!this.stateChange("auth_res","server sent auth_res"))break;this.send(ee.from([G.CID_REQ]))}else this.boho.isAuthorized=!1,this.stateChange("auth_fail","verify_auth_res() invalid server_hmac");break;default:try{e=ne.decode(t),this.emit("text_message",e)}catch(t){}}}iam(t){t?this.send_enc_mode(k.pack(k.MB("#MsgType","8",G.IAM),k.MB("#",t))):this.send_enc_mode(k.pack(k.MB("#MsgType","8",G.IAM)))}ping(){this.send(ee.from([G.PING]))}pong(){this.send(ee.from([G.PONG]))}echo(t){t?this.send_enc_mode(k.pack(k.MB("#MsgType","8",G.ECHO),k.MB("#msg",t))):this.send(ee.from([G.ECHO]))}bin(...t){this.send(k.U8pack(...t))}send(t){if(t.byteLength>this.quota.signalSize)return this.emit("over_size"),console.log("## QUOTA LIMIT OVER!! \nsignal message.byteLength: ",t.byteLength),void console.log("## your maximum signalSize(bytes) is:",this.quota.signalSize);this.socket_send(t)}getEncryptionMode(){return!(this.encMode!==F.YES&&(this.encMode!==F.AUTO||this.TLS||!this.boho.isAuthorized))}send_enc_mode(t,e){if(void 0===e&&(e=this.getEncryptionMode()),t[0]==G.SIGNAL_E2E&&e){let e=t[1],r=this.boho.encrypt_488(t.subarray(0,3+e));r[0]=te.BohoMsg.ENC_E2E,this.send(ee.concat([r,t.subarray(3+e)]))}else if(e){let e=this.boho.encrypt_488(t);this.send(e)}else this.send(t)}setMsgPromise(t){return new Promise((e,r)=>{const n=setTimeout(e=>{this.promiseMap.has(t)&&(r("timeout"),this.promiseMap.delete(t))},this.promiseTimeOut);this.promiseMap.set(t,[e,r,n])})}testPromise(t){let e=k.unpack(t);if(e)if(this.promiseMap.has(e.mid)){let[t,r,n]=this.promiseMap.get(e.mid);clearTimeout(n),this.promiseMap.delete(e.mid),e.status<128?(e.ok=!0,t(e)):(e.ok=!1,r(e))}else console.log("no promise id")}publish(t,...e){this.signal(t,...e)}signal(t,...e){if("string"!=typeof t)throw TypeError("tag should be string.");t.startsWith("@")&&this.cid&&ie(this.cid+t);let r=J(t,...e);this.send_enc_mode(r)}decrypt_e2e(t,e){return this.boho.decrypt_e2e(t,e)}signal_e2e(t,e,r){const n=ie(t);if(t.startsWith("@")&&this.cid&&ie(this.cid+t),!this.boho.isAuthorized)return;let i=k.B8(e),o=this.boho.encrypt_e2e(i,r),s=k.pack(k.MB("#MsgType","8",G.SIGNAL_E2E),k.MB("#tagLen","8",n.byteLength),k.MB("#tag",n),k.MB("#payloadType","8",V.BINARY),k.MB("#payload",o));this.send_enc_mode(s)}set(t,...e){return t&&0!=e.length?this.call("store","set",t,...e):Promise.reject(new Error("set need storeName and value)"))}async get(t){if(!t)return Promise.reject(new Error("store get need storeName)"));let e=await this.call("store","get",t),{$:r}=k.unpack(e.body);return r}call(t,e,...r){if(!t||!e)return Promise.reject(new Error("request need target and topic)"));let n;return n=r.length>0?k.pack(k.MB("#MsgType","8",G.CALL),k.MB("mid","16",++this.mid),k.MB("target",t),k.MB("topic",e),k.MBA(...r)):k.pack(k.MB("#MsgType","8",G.CALL),k.MB("mid","16",++this.mid),k.MB("target",t),k.MB("topic",e)),this.send_enc_mode(n),this.setMsgPromise(this.mid)}subscribe(t){const e=ie(t);this.send_enc_mode(ee.concat([k.NB("8",G.SUBSCRIBE),k.NB("8",e.byteLength),e]))}subscribe_channels(){if(this.state!==z.READY||0===this.channels.size)return;const t=Array.from(this.channels).join(",").split(","),e=t.map(t=>ie(t).byteLength),r=[];let n=[],i=0;t.forEach((t,o)=>{n.length&&i+1+e[o]>H.TAG_LEN1&&(r.push(n.join(",")),n=[],i=0),i+=(n.length?1:0)+e[o],n.push(t)}),n.length&&r.push(n.join(",")),r.forEach(t=>this.subscribe(t))}unsubscribe(t=""){const e=ie(t);if(""==t)this.channels.clear();else{t.split(",").forEach(t=>{this.channels.delete(t)})}this.send_enc_mode(ee.concat([k.NB("8",G.UNSUBSCRIBE),k.NB("8",e.byteLength),e]))}listen(t,e){if("string"!=typeof t)throw TypeError("tag should be string.");if(ie(t,!1),"function"!=typeof e)throw TypeError("handler is not a function.");0!==t.indexOf("@")&&this.channels.add(t),this.on(t,e)}link(t,e,r){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");if("string"!=typeof e)throw TypeError("tag is not a string.");if(ie(e,!1),"function"!=typeof r)throw TypeError("handler is not a function.");let n;0!==e.indexOf("@")&&this.channels.add(e),n=this.linkMap.has(t)?this.linkMap.get(t):new Set,n.add(e),this.linkMap.set(t,n),this.on(e,r),this.subscribe(e)}unlink(t,e){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");if("string"!=typeof e)throw TypeError("tag is not a string.");ie(e,!1);const r=this.linkMap.get(t);r&&r.has(e)&&(this.unsubscribe(e),this.removeAllListeners(e),r.delete(e),0===r.size&&this.linkMap.delete(t))}unlinkAll(t){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");const e=this.linkMap.get(t);if(e){for(const t of e)this.unsubscribe(t),this.removeAllListeners(t);this.linkMap.delete(t)}}getMetric(){return{tx:this.txCounter,rx:this.rxCounter,txb:this.txBytes,rxb:this.rxBytes,last:(Date.now()-this.lastTxRxTime)/1e3}}getState(){return this.state}getStateName(){return z[this.state].toLowerCase()}getSecurity(){return{useAuth:this.useAuth,isTLS:this.TLS,isAuthorized:this.boho.isAuthorized,encMode:this.encMode,usingEncryption:this.getEncryptionMode()}}stateChange(t,e){let r=t.toLowerCase();const n=z[t.toUpperCase()];if("number"!=typeof n)throw new TypeError("Unknown state: "+t);const i=this.state!==n;this.state=n,this.stateName=r,i&&this._stateRevision++;const o=this._stateRevision;return i&&this.emit("change",r),o===this._stateRevision&&(e&&this.emit(r,e),o===this._stateRevision)}}const se=te.Buffer;class fe extends oe{static version="7.0.0";static binaryType="arraybuffer";static Boho=te;static MBP=te.MBP;static Buffer=te.Buffer;static constants=Y;static instanceCount=0;static webSocketCount=0;constructor(t){super(t),fe.instanceCount++,this.boundBrowserVisiblePing=this.browserVisiblePing.bind(this),document.addEventListener("visibilitychange",this.boundBrowserVisiblePing),t&&this.open()}browserVisiblePing(){"visible"===document.visibilityState&&this.ping()}stop(){super.stop()}destroy(){document.removeEventListener("visibilitychange",this.boundBrowserVisiblePing),super.destroy()}keepConnection(){this.autoReconnect&&(this.socket&&this.socket.readyState!==WebSocket.CLOSED||this.open())}createConnection(t){fe.webSocketCount++;const e=this.socket=new WebSocket(t);this._closed=!1,this.socket.binaryType=fe.binaryType,this.socket.onopen=()=>{this.socket===e&&("arraybuffer"==this.socket.binaryType?this.socket.onmessage=t=>{this.socket===e&&this.onWebSocketMessage(t)}:this.socket.onmessage=t=>{this.socket===e&&this.onWebSocketMessageBlob(t)},this.emit("open"))},this.socket.onerror=t=>{this.socket===e&&this.emit("error",t)},this.socket.onclose=()=>{this.socket===e&&this.emit("close")},this.stateChange("connecting","connecting")}onWebSocketMessage(t){this.rxCounter++,this.lastTxRxTime=Date.now();let e=se.from(t.data);this.rxBytes+=e.byteLength,this.emit("socket_data",e)}async onWebSocketMessageBlob(t){const e=this.socket;let r;if(this.rxCounter++,this.lastTxRxTime=Date.now(),t.data instanceof Blob){let e=await t.data.arrayBuffer();r=se.from(e)}else r=se.from(t.data);this.rxBytes+=r.byteLength,this.socket===e&&this.emit("socket_data",r)}socket_send(t){1===this.socket?.readyState?(this.socket.send(t),this.txCounter++,this.txBytes+=t.byteLength,this.lastTxRxTime=Date.now()):console.log(".")}}export{fe as default};
|
|
23
23
|
//# sourceMappingURL=io.js.map
|
package/dist/browser/iife/io.js
CHANGED
|
@@ -19,5 +19,5 @@ var s=(r||(r=1,function(r){const n=function(){if(t)return i;t=1,i.byteLength=fun
|
|
|
19
19
|
*
|
|
20
20
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
21
21
|
* @license MIT
|
|
22
|
-
*/var Yt=(zt||(zt=1,function(t){const e=function(){if(Dt)return Ht;Dt=1,Ht.byteLength=function(t){var e=o(t),r=e[0],n=e[1];return 3*(r+n)/4-n},Ht.toByteArray=function(t){var n,i,s=o(t),f=s[0],u=s[1],h=new r(function(t,e,r){return 3*(e+r)/4-r}(0,f,u)),a=0,c=u>0?f-4:f;for(i=0;i<c;i+=4)n=e[t.charCodeAt(i)]<<18|e[t.charCodeAt(i+1)]<<12|e[t.charCodeAt(i+2)]<<6|e[t.charCodeAt(i+3)],h[a++]=n>>16&255,h[a++]=n>>8&255,h[a++]=255&n;return 2===u&&(n=e[t.charCodeAt(i)]<<2|e[t.charCodeAt(i+1)]>>4,h[a++]=255&n),1===u&&(n=e[t.charCodeAt(i)]<<10|e[t.charCodeAt(i+1)]<<4|e[t.charCodeAt(i+2)]>>2,h[a++]=n>>8&255,h[a++]=255&n),h},Ht.fromByteArray=function(e){for(var r,n=e.length,i=n%3,o=[],s=16383,u=0,h=n-i;u<h;u+=s)o.push(f(e,u,u+s>h?h:u+s));return 1===i?(r=e[n-1],o.push(t[r>>2]+t[r<<4&63]+"==")):2===i&&(r=(e[n-2]<<8)+e[n-1],o.push(t[r>>10]+t[r>>4&63]+t[r<<2&63]+"=")),o.join("")};for(var t=[],e=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)t[i]=n[i],e[n.charCodeAt(i)]=i;function o(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function s(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[63&e]}function f(t,e,r){for(var n,i=[],o=e;o<r;o+=3)n=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(255&t[o+2]),i.push(s(n));return i.join("")}return e["-".charCodeAt(0)]=62,e["_".charCodeAt(0)]=63,Ht}(),r=Gt(),n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=s,t.SlowBuffer=function(t){return+t!=t&&(t=0),s.alloc(+t)},t.INSPECT_MAX_BYTES=50;const i=2147483647;function o(t){if(t>i)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,s.prototype),e}function s(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return h(t)}return f(t,e,r)}function f(t,e,r){if("string"==typeof t)return function(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!s.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|p(t,e);let n=o(r);const i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(q(t,Uint8Array)){const e=new Uint8Array(t);return c(e.buffer,e.byteOffset,e.byteLength)}return a(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(q(t,ArrayBuffer)||t&&q(t.buffer,ArrayBuffer))return c(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(q(t,SharedArrayBuffer)||t&&q(t.buffer,SharedArrayBuffer)))return c(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return s.from(n,e,r);const i=function(t){if(s.isBuffer(t)){const e=0|l(t.length),r=o(e);return 0===r.length||t.copy(r,0,0,e),r}return void 0!==t.length?"number"!=typeof t.length||K(t.length)?o(0):a(t):"Buffer"===t.type&&Array.isArray(t.data)?a(t.data):void 0}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return s.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function u(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function h(t){return u(t),o(t<0?0:0|l(t))}function a(t){const e=t.length<0?0:0|l(t.length),r=o(e);for(let n=0;n<e;n+=1)r[n]=255&t[n];return r}function c(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===e&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,e):new Uint8Array(t,e,r),Object.setPrototypeOf(n,s.prototype),n}function l(t){if(t>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|t}function p(t,e){if(s.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||q(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return V(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(t).length;default:if(i)return n?-1:V(t).length;e=(""+e).toLowerCase(),i=!0}}function y(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return I(this,e,r);case"ascii":return U(this,e,r);case"latin1":case"binary":return L(this,e,r);case"base64":return A(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function g(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function d(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),K(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=s.from(e,n)),s.isBuffer(e))return 0===e.length?-1:b(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):b(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(t,e,r,n,i){let o,s=1,f=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,f/=2,u/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){let n=-1;for(o=r;o<f;o++)if(h(t,o)===h(e,-1===n?0:o-n)){if(-1===n&&(n=o),o-n+1===u)return n*s}else-1!==n&&(o-=o-n),n=-1}else for(r+u>f&&(r=f-u),o=r;o>=0;o--){let r=!0;for(let n=0;n<u;n++)if(h(t,o+n)!==h(e,n)){r=!1;break}if(r)return o}return-1}function w(t,e,r,n){r=Number(r)||0;const i=t.length-r;n?(n=Number(n))>i&&(n=i):n=i;const o=e.length;let s;for(n>o/2&&(n=o/2),s=0;s<n;++s){const n=parseInt(e.substr(2*s,2),16);if(K(n))return s;t[r+s]=n}return s}function E(t,e,r,n){return Y(V(e,t.length-r),t,r,n)}function B(t,e,r,n){return Y(function(t){const e=[];for(let r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function m(t,e,r,n){return Y(G(e),t,r,n)}function _(t,e,r,n){return Y(function(t,e){let r,n,i;const o=[];for(let s=0;s<t.length&&!((e-=2)<0);++s)r=t.charCodeAt(s),n=r>>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function A(t,r,n){return 0===r&&n===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(r,n))}function I(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i<r;){const e=t[i];let o=null,s=e>239?4:e>223?3:e>191?2:1;if(i+s<=r){let r,n,f,u;switch(s){case 1:e<128&&(o=e);break;case 2:r=t[i+1],128==(192&r)&&(u=(31&e)<<6|63&r,u>127&&(o=u));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(u=(15&e)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(o=u));break;case 4:r=t[i+1],n=t[i+2],f=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&f)&&(u=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&f,u>65535&&u<1114112&&(o=u))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(t){const e=t.length;if(e<=v)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=v));return r}(n)}t.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=function(){try{const t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),42===t.foo()}catch(t){return!1}}(),s.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(t,e,r){return f(t,e,r)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(t,e,r){return function(t,e,r){return u(t),t<=0?o(t):void 0!==e?"string"==typeof r?o(t).fill(e,r):o(t).fill(e):o(t)}(t,e,r)},s.allocUnsafe=function(t){return h(t)},s.allocUnsafeSlow=function(t){return h(t)},s.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==s.prototype},s.compare=function(t,e){if(q(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),q(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(t)||!s.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;let r=t.length,n=e.length;for(let i=0,o=Math.min(r,n);i<o;++i)if(t[i]!==e[i]){r=t[i],n=e[i];break}return r<n?-1:n<r?1:0},s.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(t,e){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return s.alloc(0);let r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;const n=s.allocUnsafe(e);let i=0;for(r=0;r<t.length;++r){let e=t[r];if(q(e,Uint8Array))i+e.length>n.length?(s.isBuffer(e)||(e=s.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!s.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},s.byteLength=p,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;e<t;e+=2)g(this,e,e+1);return this},s.prototype.swap32=function(){const t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let e=0;e<t;e+=4)g(this,e,e+3),g(this,e+1,e+2);return this},s.prototype.swap64=function(){const t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let e=0;e<t;e+=8)g(this,e,e+7),g(this,e+1,e+6),g(this,e+2,e+5),g(this,e+3,e+4);return this},s.prototype.toString=function(){const t=this.length;return 0===t?"":0===arguments.length?I(this,0,t):y.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(t){if(!s.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===s.compare(this,t)},s.prototype.inspect=function(){let e="";const r=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},n&&(s.prototype[n]=s.prototype.inspect),s.prototype.compare=function(t,e,r,n,i){if(q(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let o=(i>>>=0)-(n>>>=0),f=(r>>>=0)-(e>>>=0);const u=Math.min(o,f),h=this.slice(n,i),a=t.slice(e,r);for(let t=0;t<u;++t)if(h[t]!==a[t]){o=h[t],f=a[t];break}return o<f?-1:f<o?1:0},s.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},s.prototype.indexOf=function(t,e,r){return d(this,t,e,r,!0)},s.prototype.lastIndexOf=function(t,e,r){return d(this,t,e,r,!1)},s.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return w(this,t,e,r);case"utf8":case"utf-8":return E(this,t,e,r);case"ascii":case"latin1":case"binary":return B(this,t,e,r);case"base64":return m(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const v=4096;function U(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(127&t[i]);return n}function L(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function T(t,e,r){const n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);let i="";for(let n=e;n<r;++n)i+=J[t[n]];return i}function S(t,e,r){const n=t.slice(e,r);let i="";for(let t=0;t<n.length-1;t+=2)i+=String.fromCharCode(n[t]+256*n[t+1]);return i}function R(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,r,n,i,o){if(!s.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<o)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function M(t,e,r,n,i){j(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,r}function C(t,e,r,n,i){j(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r+7]=o,o>>=8,t[r+6]=o,o>>=8,t[r+5]=o,o>>=8,t[r+4]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=s,s>>=8,t[r+2]=s,s>>=8,t[r+1]=s,s>>=8,t[r]=s,r+8}function N(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function k(t,e,n,i,o){return e=+e,n>>>=0,o||N(t,0,n,4),r.write(t,e,n,i,23,4),n+4}function x(t,e,n,i,o){return e=+e,n>>>=0,o||N(t,0,n,8),r.write(t,e,n,i,52,8),n+8}s.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e<t&&(e=t);const n=this.subarray(t,e);return Object.setPrototypeOf(n,s.prototype),n},s.prototype.readUintLE=s.prototype.readUIntLE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t],i=1,o=0;for(;++o<e&&(i*=256);)n+=this[t+o]*i;return n},s.prototype.readUintBE=s.prototype.readUIntBE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},s.prototype.readUint8=s.prototype.readUInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),this[t]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]|this[t+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]<<8|this[t+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},s.prototype.readBigUInt64LE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))}),s.prototype.readBigUInt64BE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)}),s.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t],i=1,o=0;for(;++o<e&&(i*=256);)n+=this[t+o]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*e)),n},s.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=e,i=1,o=this[t+--n];for(;n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},s.prototype.readInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},s.prototype.readInt16LE=function(t,e){t>>>=0,e||R(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(t,e){t>>>=0,e||R(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},s.prototype.readInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},s.prototype.readBigInt64LE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(e+256*this[++t]+65536*this[++t]+this[++t]*2**24)}),s.prototype.readBigInt64BE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<<BigInt(32))+BigInt(this[++t]*2**24+65536*this[++t]+256*this[++t]+r)}),s.prototype.readFloatLE=function(t,e){return t>>>=0,e||R(t,4,this.length),r.read(this,t,!0,23,4)},s.prototype.readFloatBE=function(t,e){return t>>>=0,e||R(t,4,this.length),r.read(this,t,!1,23,4)},s.prototype.readDoubleLE=function(t,e){return t>>>=0,e||R(t,8,this.length),r.read(this,t,!0,52,8)},s.prototype.readDoubleBE=function(t,e){return t>>>=0,e||R(t,8,this.length),r.read(this,t,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||O(this,t,e,r,Math.pow(2,8*r)-1,0);let i=1,o=0;for(this[e]=255&t;++o<r&&(i*=256);)this[e+o]=t/i&255;return e+r},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||O(this,t,e,r,Math.pow(2,8*r)-1,0);let i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},s.prototype.writeUint8=s.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,1,255,0),this[e]=255&t,e+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeBigUInt64LE=Q(function(t,e=0){return M(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(t,e=0){return C(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);O(this,t,e,r,n-1,-n)}let i=0,o=1,s=0;for(this[e]=255&t;++i<r&&(o*=256);)t<0&&0===s&&0!==this[e+i-1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},s.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);O(this,t,e,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[e+i]=255&t;--i>=0&&(o*=256);)t<0&&0===s&&0!==this[e+i+1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},s.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},s.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},s.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeBigInt64LE=Q(function(t,e=0){return M(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(t,e=0){return C(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(t,e,r){return k(this,t,e,!0,r)},s.prototype.writeFloatBE=function(t,e,r){return k(this,t,e,!1,r)},s.prototype.writeDoubleLE=function(t,e,r){return x(this,t,e,!0,r)},s.prototype.writeDoubleBE=function(t,e,r){return x(this,t,e,!1,r)},s.prototype.copy=function(t,e,r,n){if(!s.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-r&&(n=t.length-e+r);const i=n-r;return this===t&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(e,r,n):Uint8Array.prototype.set.call(t,this.subarray(r,n),e),i},s.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){const e=t.charCodeAt(0);("utf8"===n&&e<128||"latin1"===n)&&(t=e)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;let i;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i<r;++i)this[i]=t;else{const o=s.isBuffer(t)?t:s.from(t,n),f=o.length;if(0===f)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(i=0;i<r-e;++i)this[i+e]=o[i%f]}return this};const P={};function $(t,e,r){P[t]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(t){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:t,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}function D(t){let e="",r=t.length;const n="-"===t[0]?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function j(t,e,r,n,i,o){if(t>r||t<e){const r="bigint"==typeof e?"n":"";let n;throw n=0===e||e===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(o+1)}${r}`:`>= -(2${r} ** ${8*(o+1)-1}${r}) and < 2 ** ${8*(o+1)-1}${r}`,new P.ERR_OUT_OF_RANGE("value",n,t)}!function(t,e,r){z(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||F(e,t.length-(r+1))}(n,i,o)}function z(t,e){if("number"!=typeof t)throw new P.ERR_INVALID_ARG_TYPE(e,"number",t)}function F(t,e,r){if(Math.floor(t)!==t)throw z(t,r),new P.ERR_OUT_OF_RANGE("offset","an integer",t);if(e<0)throw new P.ERR_BUFFER_OUT_OF_BOUNDS;throw new P.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${e}`,t)}$("ERR_BUFFER_OUT_OF_BOUNDS",function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),$("ERR_INVALID_ARG_TYPE",function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`},TypeError),$("ERR_OUT_OF_RANGE",function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=D(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=D(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);const H=/[^+/0-9A-Za-z-_]/g;function V(t,e){let r;e=e||1/0;const n=t.length;let i=null;const o=[];for(let s=0;s<n;++s){if(r=t.charCodeAt(s),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function G(t){return e.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(H,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Y(t,e,r,n){let i;for(i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function q(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function K(t){return t!=t}const J=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Q(t){return"undefined"==typeof BigInt?W:t}function W(){throw new Error("BigInt not supported")}}(Ft)),Ft);let qt={SERVER_TIME_NONCE:176,AUTH_REQ:177,AUTH_RES:178,AUTH_FAIL:179,ENC_PACK:182,ENC_E2E:183,ENC_488:184};for(let t in qt)qt[qt[t]]=t;const Kt={SERVER_TIME_NONCE:Pt.meta(Pt.MB("header","8",0),Pt.MB("unixTime","32L",0),Pt.MB("milTime","16L",0),Pt.MB("counter","16L",0),Pt.MB("nonce",Yt.Buffer.alloc(4))),AUTH_REQ:Pt.meta(Pt.MB("header","8",0),Pt.MB("id8",Yt.Buffer.alloc(8)),Pt.MB("nonce",Yt.Buffer.alloc(4)),Pt.MB("hmac32",Yt.Buffer.alloc(32))),AUTH_RES:Pt.meta(Pt.MB("header","8",0),Pt.MB("hmac32",Yt.Buffer.alloc(32))),ENC_PACK:Pt.meta(Pt.MB("type","8",0),Pt.MB("len","32L",0),Pt.MB("salt12",Yt.Buffer.alloc(12)),Pt.MB("hmac",8,0)),ENC_488:Pt.meta(Pt.MB("type","8",0),Pt.MB("len","32L",0),Pt.MB("otpSrc8",Yt.Buffer.alloc(8)),Pt.MB("hmac8",Yt.Buffer.alloc(8)))};function Jt(t){let e=t[t.length-1];return e[2]+e[3]}const Qt={SERVER_TIME_NONCE:Jt(Kt.SERVER_TIME_NONCE),AUTH_REQ:Jt(Kt.AUTH_REQ),AUTH_RES:Jt(Kt.AUTH_RES),ENC_PACK:Jt(Kt.ENC_PACK),ENC_488:Jt(Kt.ENC_488)};function Wt(t,e){if(!(t instanceof Uint8Array&&e instanceof Uint8Array&&t.length===e.length))return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return 0===r}function Xt(t,e,r,n,i=!1){if(!(t instanceof Uint8Array))return;const o=Yt.Buffer.from(t);return o.length<r||o[0]!==e||(i?o.readUInt32LE(1)!==o.length-r:o.length!==r)?void 0:Pt.unpack(o,n)}function Zt(t){return globalThis.crypto.getRandomValues(Yt.Buffer.alloc(t))}class te{constructor(){this._id8=Yt.Buffer.alloc(8),this._otpSrc44=Yt.Buffer.alloc(44),this._otp36=Yt.Buffer.alloc(36),this._hmac=Yt.Buffer.alloc(32),this.auth_salt12=Yt.Buffer.alloc(12),this.localNonce=Yt.Buffer.alloc(4),this.remoteNonce=Yt.Buffer.alloc(4),this.isAuthorized=!1,this.counter=0,this._hasKey=!1,this._lastSendTime=0}clearAuth(){this._id8.fill(0),this._otpSrc44.fill(0),this._otp36.fill(0),this._hmac.fill(0),this.auth_salt12.fill(0),this.localNonce.fill(0),this.remoteNonce.fill(0),this.isAuthorized=!1,this.counter=0,this._hasKey=!1,this._lastSendTime=0}set_hash_id8(t){Pt.B8($t.hash(t)).copy(this._id8,0,0,8)}set_id8(t){let e=Pt.B8(t);this._id8.fill(0),e.copy(this._id8,0,0,8)}set_key(t){const e=Pt.B8(t);if(!e||0===e.length)throw new TypeError("Key must not be empty");this.copy_key(Pt.B8($t.hash(e)))}set_id_key(t){let e=t.indexOf(".");if(-1==e)return;let r=t.substring(0,e),n=t.substring(e+1);this.set_id8(r),this.set_key(n)}copy_id8(t){t.copy(this._id8,0,0,8)}copy_key(t){if(!(t instanceof Uint8Array)||32!==t.length)throw new TypeError("copy_key requires exactly 32 bytes");this._otpSrc44.set(t,0),this._hasKey=!0}sha256_n(t,e){let r=$t.hash(t);for(let t=0;t<e;t++)r=$t.hash(r);return r}set_clock_rand(){this.set_clock_nonce(Zt(4))}set_clock_nonce(t){if(!(t instanceof Uint8Array)||4!==t.length)throw new TypeError("Nonce must be 4 bytes");let e=Math.max(Date.now(),this._lastSendTime);if(this.counter=this.counter+1&65535,0===this.counter&&e===this._lastSendTime&&e++,!Number.isSafeInteger(e)||e<0||Math.floor(e/1e3)>4294967295)throw new RangeError("Clock is outside the protocol range");this._lastSendTime=e,Yt.Buffer.concat([Pt.NB("32L",Math.floor(e/1e3)),Pt.NB("16L",e%1e3),Pt.NB("16L",this.counter),Yt.Buffer.from(t)]).copy(this._otpSrc44,32)}_requireKey(){if(!this._hasKey)throw new Error("Set a key before encryption or authentication")}set_salt12(t,e){if(12!=t.byteLength)throw TypeError("set_salt12: Invalid salt12 byteLength.");t.copy(this._otpSrc44,32)}resetOTP(){this._requireKey(),Pt.B8($t.hash(this._otpSrc44)).copy(this._otp36,0,0,32)}getIndexOTP(t){return this._otp36.writeUInt32LE(t,32),$t.hash(this._otp36)}generateHMAC(t){this._requireKey();let e=Yt.Buffer.concat([this._otpSrc44,t]);this._hmac=Pt.B8($t.hash(e))}getHMAC8(t){this._requireKey();let e=Yt.Buffer.concat([this._otpSrc44,t]);return this._hmac=Pt.B8($t.hash(e)),this._hmac.subarray(0,8)}xotp(t,e=0,r=!1){let n=(t=Pt.B8(t,r)).byteLength,i=e,o=0,s=0;for(;n>0;){s=n<32?n:32;let e=this.getIndexOTP(++i);for(let r=0;r<s;r++)t[o++]^=e[r];n-=32}return t}server_time_nonce(){const t=Date.now(),e=Math.floor(t/1e3),r=t%1e3;return this.localNonce=Zt(4),this.auth_salt12=Yt.Buffer.concat([Pt.NB("32L",e),Pt.NB("16L",r),Zt(2),this.localNonce]),Yt.Buffer.concat([Pt.NB("8",qt.SERVER_TIME_NONCE),this.auth_salt12])}auth_req(t){if(!this._hasKey)return!1;let e=Xt(t,qt.SERVER_TIME_NONCE,Qt.SERVER_TIME_NONCE,Kt.SERVER_TIME_NONCE);if(e&&e.milTime>=1e3)return!1;if(e){let t=Yt.Buffer.concat([Pt.NB("32L",e.unixTime),Pt.NB("16L",e.milTime),Pt.NB("16L",e.counter),e.nonce]);return this.set_salt12(t,"auth_req"),this.localNonce=Zt(4),this.generateHMAC(this.localNonce),this.remoteNonce=e.nonce,Pt.pack(Pt.MB("#header","8",qt.AUTH_REQ),Pt.MB("#id8",this._id8),Pt.MB("#nonce",this.localNonce),Pt.MB("#hmac32",this._hmac))}return!1}verify_auth_req(t){if(!this._hasKey)return!1;let e;if(t instanceof Uint8Array?e=Xt(t,qt.AUTH_REQ,Qt.AUTH_REQ,Kt.AUTH_REQ):t&&"object"==typeof t&&(e=t),!e||e.header!==qt.AUTH_REQ||!(e.id8 instanceof Uint8Array)||8!==e.id8.length||!(e.nonce instanceof Uint8Array)||4!==e.nonce.length||!(e.hmac32 instanceof Uint8Array)||32!==e.hmac32.length||e.$OTHERS&&0!==e.$OTHERS.length)return!1;this.set_salt12(this.auth_salt12,"verify_auth_req 1/2"),this.generateHMAC(e.nonce);let r=this._hmac;if(Wt(e.hmac32,r)){this.remoteNonce=Yt.Buffer.from(e.nonce);let t=Yt.Buffer.concat([this.localNonce,this.remoteNonce,this.localNonce]);this.set_salt12(t,"verify_auth_req 2/2"),this.generateHMAC(e.nonce);let r=this._hmac,n=Pt.rawPack(Pt.MB("header","8",qt.AUTH_RES),Pt.MB("hmac32",r));return this.isAuthorized=!0,n}return!1}verify_auth_res(t){if(!this._hasKey)return!1;let e=Xt(t,qt.AUTH_RES,Qt.AUTH_RES,Kt.AUTH_RES);if(e){let t=Yt.Buffer.concat([this.remoteNonce,this.localNonce,this.remoteNonce]);if(this.set_salt12(t,"verify_auth_res"),this.generateHMAC(this.localNonce),Wt(this._hmac,e.hmac32))return this.isAuthorized=!0,!0}}encrypt_488(t){if(!this.isAuthorized||!this._hasKey)return;t=Pt.B8(t),this.set_clock_nonce(this.remoteNonce),this.resetOTP();let e=this.getHMAC8(t),r=this.xotp(t);return Pt.pack(Pt.MB("#type","8",qt.ENC_488),Pt.MB("#len","32L",t.byteLength),Pt.MB("#otpSrc8",this._otpSrc44.subarray(32,40)),Pt.MB("#hmac8",e),Pt.MB("#xdata",r))}decrypt_488(t){if(!this.isAuthorized||!this._hasKey)return;let e=t;if(t instanceof Uint8Array&&t[0]===qt.ENC_E2E){if(t.length<Qt.ENC_488)return;const r=Yt.Buffer.from(t),n=r.readUInt32LE(1);if(n>r.length-Qt.ENC_488)return;e=Yt.Buffer.from(r.subarray(0,Qt.ENC_488+n)),e[0]=qt.ENC_488}const r=Xt(e,qt.ENC_488,Qt.ENC_488,Kt.ENC_488,!0);if(!(r&&(n=r.otpSrc8,n.readUInt16LE(4)<1e3)))return;var n;this.set_salt12(Yt.Buffer.concat([r.otpSrc8,this.localNonce]),"decrypt_488"),this.resetOTP();const i=this.xotp(r.$OTHERS??Yt.Buffer.alloc(0));return Wt(this.getHMAC8(i),r.hmac8)?i:void 0}encryptPack(t){this._requireKey(),t=Pt.B8(t),this.set_clock_rand(),this.resetOTP();let e=this.getHMAC8(t),r=this.xotp(t);return Pt.pack(Pt.MB("#type","8",qt.ENC_PACK),Pt.MB("#len","32L",t.byteLength),Pt.MB("#salt12",this._otpSrc44.subarray(32)),Pt.MB("#hmac8",e),Pt.MB("#xdata",r))}decryptPack(t){if(!this._hasKey)return;const e=Xt(t,qt.ENC_PACK,Qt.ENC_PACK,Kt.ENC_PACK,!0);if(!e)return;this.set_salt12(e.salt12,"decryptPack"),this.resetOTP();const r=this.xotp(e.$OTHERS??Yt.Buffer.alloc(0));return Wt(e.hmac,this.getHMAC8(r))?(e.data=r,e):void 0}encrypt_e2e(t,e){return this._withKey(e,()=>this.encryptPack(t))}decrypt_e2e(t,e){return this._withKey(e,()=>this.decryptPack(t))}_withKey(t,e){const r=Pt.B8(t);if(!r||0===r.length)throw new TypeError("Key must not be empty");const n=[Yt.Buffer.from(this._otpSrc44),Yt.Buffer.from(this._otp36),Yt.Buffer.from(this._hmac)],i=this._hasKey;try{return this._otpSrc44.set($t.hash(r),0),this._hasKey=!0,e()}finally{this._otpSrc44.set(n[0]),this._otp36.set(n[1]),this._hmac.set(n[2]),this._hasKey=i;for(const t of n)t.fill(0)}}}te.RAND=Zt,te.BohoMsg=qt,te.Meta=Kt,te.MetaSize=Qt,te.sha256=$t,te.MBP=Pt,te.Buffer=Yt.Buffer;const ee=k.Buffer,re=new TextEncoder,ne=new TextDecoder;function ie(t,e=!0){if("string"!=typeof t)throw TypeError("tag should be string.");const r=re.encode(t);if(!e&&0===r.byteLength||r.byteLength>H.TAG_LEN1)throw TypeError("tag UTF-8 byte length must be "+(e?"0":"1")+"~255");return r}class oe extends j{constructor(t){super(),this.cid="",this.ip="",this.socket=null,this.url=t,this.state=z.CLOSED,this.stateName=this.getStateName(),this._stateRevision=0,this.txCounter=0,this.rxCounter=0,this.txBytes=0,this.rxBytes=0,this.lastTxRxTime=Date.now(),this.connectionCheckerPeriod=H.CONNECTION_CHECKER_PERIOD,this.connectionCheckerIntervalID=null,this.boho=new te,this.serverTimeNonce=ee.alloc(te.MetaSize.SERVER_TIME_NONCE),this.TLS=!1,this.encMode=F.AUTO,this.useAuth=!1,this.nick="",this.channels=new Set,this.promiseMap=new Map,this.promiseTimeOut=H.PROMISE_TIMEOUT,this.mid=0,this.level=3,this.quota=q[this.level],this.serverSet={},this.linkMap=new Map,this.autoReconnect=!0,this._closed=!1,this.on("open",this.onOpen.bind(this)),this.on("close",this.onClose.bind(this)),this.on("socket_data",this.onData.bind(this))}close(){if(!1===this.autoReconnect&&(clearInterval(this.connectionCheckerIntervalID),this.connectionCheckerIntervalID=null),!this._closed){if(this._closed=!0,this.socket){if(0===this.socket.readyState){const t=this.socket;t.onopen=()=>{t&&t.close()},t.onmessage=null,t.onerror=null,t.onclose=null}else try{this.socket.close?.()}catch{}this.socket=null}this.promiseMap.clear(),this.cid="",this.boho&&(this.boho.isAuthorized=!1),this.state!==z.STOP&&this.stateChange("closed")&&this.emit("closed")}}stop(){this.autoReconnect=!1,this.close(),this.cid="",this.stateChange("stop","stop")}destroy(){this.stop(),this.removeAllListeners(),this.channels.clear(),this.linkMap.clear(),this.boho=null}keepAlive(){this.keepConnection(),Date.now()-this.lastTxRxTime>H.CLIENT_PING_PERIOD&&this.ping()}redirect(t){this.stateChange("redirecting","redirecting"),this.close(),this.createConnection(t)}open(t){this.socket&&this.close(),t&&(this.url=t),this.url?(this.createConnection(this.url),this._closed||this.connectionCheckerIntervalID||(this.connectionCheckerIntervalID=setInterval(this.keepAlive.bind(this),this.connectionCheckerPeriod))):this.emit("error",new Error("URL is not set."))}onOpen(){this._closed=!1,this.url.includes("wss://")?this.TLS=!0:this.TLS=!1,this.stateChange("open")}onClose(){this.close()}login(t,e){if(this.serverTimeNonce){this.auth(t,e),this.useAuth=!0;let r=this.boho.auth_req(this.serverTimeNonce);this.send(r),this.stateChange("auth_req","auth_req")}return this}auth(t,e){return t||e||this.emit("error",new Error("auth failed. no id and key.")),!e&&t.includes(".")?this.boho.set_id_key(t):t&&e?(this.boho.set_id8(t),this.boho.set_key(e)):this.emit("error",new Error("auth failed. no id or key.")),this.useAuth=!0,this}onData(t){let e,r=t[0];if(r===te.BohoMsg.ENC_488)e=this.boho.decrypt_488(t),e&&(r=e[0],t=e);else if(r===te.BohoMsg.ENC_E2E)try{if(e=this.boho.decrypt_488(t),!e)return;r=e[0],t.set(e,te.MetaSize.ENC_488),t=t.subarray(te.MetaSize.ENC_488)}catch(t){return}let n=G[r];switch(n||(n=te.BohoMsg[r]),r){case G.OVER_SIZE:console.log("## server sent: over_size event."),this.emit("over_size","over_size");break;case G.PING:this.pong();break;case G.PONG:break;case G.ECHO:try{let e=ne.decode(t.subarray(1));this.emit("echo",e)}catch(t){this.emit("error",new Error("ECHO data error"))}break;case G.IAM_RES:try{let e=ne.decode(t.subarray(1)),r=JSON.parse(e);r.ip&&(this.ip=r.ip),r.nick&&(this.nick=r.nick),r.did&&(this.did=r.did),r.uid&&(this.uid=r.uid),this.emit("iam_res",e)}catch(t){this.emit("error",new Error("IAM_RES data error"))}break;case G.CID_RES:let r=ne.decode(t.subarray(1));this.cid=r,this.stateChange("ready","cid_ready"),this.subscribe_channels();break;case G.QUOTA_LEVEL:let n=t[1];this.level=n,this.quota=q[n];break;case G.AUTH_CLEAR:this.useAuth=!1,this.boho.clearAuth(),this.stateChange("auth_clear","server request auth_clear."),this.stop();break;case G.SERVER_REDIRECT:let i,o,s;7==t.byteLength?(i=function(t){if(6!=t.byteLength)return;return t[0].toString()+"."+t[1].toString()+"."+t[2].toString()+"."+t[3].toString()+":"+((t[4]<<8)+t[5]).toString()}(t.subarray(1)),s="cong://"):(i=ne.decode(t.subarray(1)),s=""),o=s+i,this.redirect(o);break;case te.BohoMsg.SERVER_TIME_NONCE:if(t.copy(this.serverTimeNonce),!this.stateChange("server_ready","server_ready"))break;this.useAuth?(this.send(this.boho.auth_req(t)),this.stateChange("auth_req","auth_req")):this.send(ee.from([G.CID_REQ]));break;case G.SERVER_SIGNAL:try{let e=ne.decode(t.subarray(1)),r=JSON.parse(e);r.event&&r.data&&(this.serverSet=r.data,this.emit(r.event,r.data))}catch(t){this.emit("error",new Error("SERVER_SIGNAL parsing error"))}break;case G.SET:try{let e=k.unpack(t);e&&this.emit(e.topic,...e.args)}catch(t){this.emit("error",new Error("SET parsing error"))}break;case G.SIGNAL_E2E:case G.SIGNAL:try{let e=t.readUint8(1),r=t.subarray(2,2+e),n=ne.decode(r),i=t.readUint8(2+e),o=t.subarray(3+e);switch(i){case V.EMPTY:0===n.indexOf("@")?this.emit("@",n):(this.emit(n,n),this.emit("message",n));break;case V.TEXT:let t=o;0===o[o.byteLength-1]&&(t=o.subarray(0,o.byteLength-1));let e=ne.decode(t);0===n.indexOf("@")?this.emit("@",n,e):(this.emit(n,n,e),this.emit("message",n,e));break;case V.BINARY:0===n.indexOf("@")?this.emit("@",n,o):(this.emit(n,n,o),this.emit("message",n,o));break;case V.OBJECT:let r=ne.decode(o),i=JSON.parse(r);0===n.indexOf("@")?this.emit("@",n,i):(this.emit(n,n,i),this.emit("message",n,i));break;case V.MJSON:let s=ne.decode(o),f=JSON.parse(s);0===n.indexOf("@")?this.emit("@",n,...f):(this.emit(n,n,...f),this.emit("message",n,...f));break;case V.MBA:let u=k.unpack(o);0===n.indexOf("@")?this.emit("@",n,...u.args):(this.emit(n,n,...u.args),this.emit("message",n,...u.args))}}catch(t){console.log("IOCore IOMsg.SIGNAL parser err",t)}break;case G.RESPONSE_MBP:this.testPromise(t);break;case te.BohoMsg.AUTH_FAIL:this.boho.isAuthorized=!1,this.stateChange("auth_fail","auth_fail from server.");break;case te.BohoMsg.AUTH_RES:if(this.boho.verify_auth_res(t)){if(!this.stateChange("auth_res","server sent auth_res"))break;this.send(ee.from([G.CID_REQ]))}else this.boho.isAuthorized=!1,this.stateChange("auth_fail","verify_auth_res() invalid server_hmac");break;default:try{e=ne.decode(t),this.emit("text_message",e)}catch(t){}}}iam(t){t?this.send_enc_mode(k.pack(k.MB("#MsgType","8",G.IAM),k.MB("#",t))):this.send_enc_mode(k.pack(k.MB("#MsgType","8",G.IAM)))}ping(){this.send(ee.from([G.PING]))}pong(){this.send(ee.from([G.PONG]))}echo(t){t?this.send_enc_mode(k.pack(k.MB("#MsgType","8",G.ECHO),k.MB("#msg",t))):this.send(ee.from([G.ECHO]))}bin(...t){this.send(k.U8pack(...t))}send(t){if(t.byteLength>this.quota.signalSize)return this.emit("over_size"),console.log("## QUOTA LIMIT OVER!! \nsignal message.byteLength: ",t.byteLength),void console.log("## your maximum signalSize(bytes) is:",this.quota.signalSize);this.socket_send(t)}getEncryptionMode(){return!(this.encMode!==F.YES&&(this.encMode!==F.AUTO||this.TLS||!this.boho.isAuthorized))}send_enc_mode(t,e){if(void 0===e&&(e=this.getEncryptionMode()),t[0]==G.SIGNAL_E2E&&e){let e=t[1],r=this.boho.encrypt_488(t.subarray(0,3+e));r[0]=te.BohoMsg.ENC_E2E,this.send(ee.concat([r,t.subarray(3+e)]))}else if(e){let e=this.boho.encrypt_488(t);this.send(e)}else this.send(t)}setMsgPromise(t){return new Promise((e,r)=>{const n=setTimeout(e=>{this.promiseMap.has(t)&&(r("timeout"),this.promiseMap.delete(t))},this.promiseTimeOut);this.promiseMap.set(t,[e,r,n])})}testPromise(t){let e=k.unpack(t);if(e)if(this.promiseMap.has(e.mid)){let[t,r,n]=this.promiseMap.get(e.mid);clearTimeout(n),this.promiseMap.delete(e.mid),e.status<128?(e.ok=!0,t(e)):(e.ok=!1,r(e))}else console.log("no promise id")}publish(t,...e){this.signal(t,...e)}signal(t,...e){if("string"!=typeof t)throw TypeError("tag should be string.");t.startsWith("@")&&this.cid&&ie(this.cid+t);let r=J(t,...e);this.send_enc_mode(r)}decrypt_e2e(t,e){return this.boho.decrypt_e2e(t,e)}signal_e2e(t,e,r){const n=ie(t);if(t.startsWith("@")&&this.cid&&ie(this.cid+t),!this.boho.isAuthorized)return;let i=k.B8(e),o=this.boho.encrypt_e2e(i,r),s=k.pack(k.MB("#MsgType","8",G.SIGNAL_E2E),k.MB("#tagLen","8",n.byteLength),k.MB("#tag",n),k.MB("#payloadType","8",V.BINARY),k.MB("#payload",o));this.send_enc_mode(s)}set(t,...e){return t&&0!=e.length?this.call("store","set",t,...e):Promise.reject(new Error("set need storeName and value)"))}async get(t){if(!t)return Promise.reject(new Error("store get need storeName)"));let e=await this.call("store","get",t),{$:r}=k.unpack(e.body);return r}call(t,e,...r){if(!t||!e)return Promise.reject(new Error("request need target and topic)"));let n;return n=r.length>0?k.pack(k.MB("#MsgType","8",G.CALL),k.MB("mid","16",++this.mid),k.MB("target",t),k.MB("topic",e),k.MBA(...r)):k.pack(k.MB("#MsgType","8",G.CALL),k.MB("mid","16",++this.mid),k.MB("target",t),k.MB("topic",e)),this.send_enc_mode(n),this.setMsgPromise(this.mid)}subscribe(t){const e=ie(t);this.send_enc_mode(ee.concat([k.NB("8",G.SUBSCRIBE),k.NB("8",e.byteLength),e]))}subscribe_channels(){if(this.state!==z.READY||0===this.channels.size)return;const t=Array.from(this.channels).join(",").split(","),e=t.map(t=>ie(t).byteLength),r=[];let n=[],i=0;t.forEach((t,o)=>{n.length&&i+1+e[o]>H.TAG_LEN1&&(r.push(n.join(",")),n=[],i=0),i+=(n.length?1:0)+e[o],n.push(t)}),n.length&&r.push(n.join(",")),r.forEach(t=>this.subscribe(t))}unsubscribe(t=""){const e=ie(t);if(""==t)this.channels.clear();else{t.split(",").forEach(t=>{this.channels.delete(t)})}this.send_enc_mode(ee.concat([k.NB("8",G.UNSUBSCRIBE),k.NB("8",e.byteLength),e]))}listen(t,e){if("string"!=typeof t)throw TypeError("tag should be string.");if(ie(t,!1),"function"!=typeof e)throw TypeError("handler is not a function.");0!==t.indexOf("@")&&this.channels.add(t),this.on(t,e)}link(t,e,r){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");if("string"!=typeof e)throw TypeError("tag is not a string.");if(ie(e,!1),"function"!=typeof r)throw TypeError("handler is not a function.");let n;0!==e.indexOf("@")&&this.channels.add(e),n=this.linkMap.has(t)?this.linkMap.get(t):new Set,n.add(e),this.linkMap.set(t,n),this.on(e,r),this.subscribe(e)}unlink(t,e){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");if("string"!=typeof e)throw TypeError("tag is not a string.");ie(e,!1);const r=this.linkMap.get(t);r&&r.has(e)&&(this.unsubscribe(e),this.removeAllListeners(e),r.delete(e),0===r.size&&this.linkMap.delete(t))}unlinkAll(t){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");const e=this.linkMap.get(t);if(e){for(const t of e)this.unsubscribe(t),this.removeAllListeners(t);this.linkMap.delete(t)}}getMetric(){return{tx:this.txCounter,rx:this.rxCounter,txb:this.txBytes,rxb:this.rxBytes,last:(Date.now()-this.lastTxRxTime)/1e3}}getState(){return this.state}getStateName(){return z[this.state].toLowerCase()}getSecurity(){return{useAuth:this.useAuth,isTLS:this.TLS,isAuthorized:this.boho.isAuthorized,encMode:this.encMode,usingEncryption:this.getEncryptionMode()}}stateChange(t,e){let r=t.toLowerCase();const n=z[t.toUpperCase()];if("number"!=typeof n)throw new TypeError("Unknown state: "+t);const i=this.state!==n;this.state=n,this.stateName=r,i&&this._stateRevision++;const o=this._stateRevision;return i&&this.emit("change",r),o===this._stateRevision&&(e&&this.emit(r,e),o===this._stateRevision)}}const se=te.Buffer;class fe extends oe{static version="6.1.2";static binaryType="arraybuffer";static Boho=te;static MBP=te.MBP;static Buffer=te.Buffer;static constants=Y;static instanceCount=0;static webSocketCount=0;constructor(t){super(t),fe.instanceCount++,this.boundBrowserVisiblePing=this.browserVisiblePing.bind(this),document.addEventListener("visibilitychange",this.boundBrowserVisiblePing),t&&this.open()}browserVisiblePing(){"visible"===document.visibilityState&&this.ping()}stop(){super.stop()}destroy(){document.removeEventListener("visibilitychange",this.boundBrowserVisiblePing),super.destroy()}keepConnection(){this.autoReconnect&&(this.socket&&this.socket.readyState!==WebSocket.CLOSED||this.open())}createConnection(t){fe.webSocketCount++;const e=this.socket=new WebSocket(t);this._closed=!1,this.socket.binaryType=fe.binaryType,this.socket.onopen=()=>{this.socket===e&&("arraybuffer"==this.socket.binaryType?this.socket.onmessage=t=>{this.socket===e&&this.onWebSocketMessage(t)}:this.socket.onmessage=t=>{this.socket===e&&this.onWebSocketMessageBlob(t)},this.emit("open"))},this.socket.onerror=t=>{this.socket===e&&this.emit("error",t)},this.socket.onclose=()=>{this.socket===e&&this.emit("close")},this.stateChange("connecting","connecting")}onWebSocketMessage(t){this.rxCounter++,this.lastTxRxTime=Date.now();let e=se.from(t.data);this.rxBytes+=e.byteLength,this.emit("socket_data",e)}async onWebSocketMessageBlob(t){const e=this.socket;let r;if(this.rxCounter++,this.lastTxRxTime=Date.now(),t.data instanceof Blob){let e=await t.data.arrayBuffer();r=se.from(e)}else r=se.from(t.data);this.rxBytes+=r.byteLength,this.socket===e&&this.emit("socket_data",r)}socket_send(t){1===this.socket?.readyState?(this.socket.send(t),this.txCounter++,this.txBytes+=t.byteLength,this.lastTxRxTime=Date.now()):console.log(".")}}return fe}();
|
|
22
|
+
*/var Yt=(zt||(zt=1,function(t){const e=function(){if(Dt)return Ht;Dt=1,Ht.byteLength=function(t){var e=o(t),r=e[0],n=e[1];return 3*(r+n)/4-n},Ht.toByteArray=function(t){var n,i,s=o(t),f=s[0],u=s[1],h=new r(function(t,e,r){return 3*(e+r)/4-r}(0,f,u)),a=0,c=u>0?f-4:f;for(i=0;i<c;i+=4)n=e[t.charCodeAt(i)]<<18|e[t.charCodeAt(i+1)]<<12|e[t.charCodeAt(i+2)]<<6|e[t.charCodeAt(i+3)],h[a++]=n>>16&255,h[a++]=n>>8&255,h[a++]=255&n;return 2===u&&(n=e[t.charCodeAt(i)]<<2|e[t.charCodeAt(i+1)]>>4,h[a++]=255&n),1===u&&(n=e[t.charCodeAt(i)]<<10|e[t.charCodeAt(i+1)]<<4|e[t.charCodeAt(i+2)]>>2,h[a++]=n>>8&255,h[a++]=255&n),h},Ht.fromByteArray=function(e){for(var r,n=e.length,i=n%3,o=[],s=16383,u=0,h=n-i;u<h;u+=s)o.push(f(e,u,u+s>h?h:u+s));return 1===i?(r=e[n-1],o.push(t[r>>2]+t[r<<4&63]+"==")):2===i&&(r=(e[n-2]<<8)+e[n-1],o.push(t[r>>10]+t[r>>4&63]+t[r<<2&63]+"=")),o.join("")};for(var t=[],e=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=0;i<64;++i)t[i]=n[i],e[n.charCodeAt(i)]=i;function o(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");return-1===r&&(r=e),[r,r===e?0:4-r%4]}function s(e){return t[e>>18&63]+t[e>>12&63]+t[e>>6&63]+t[63&e]}function f(t,e,r){for(var n,i=[],o=e;o<r;o+=3)n=(t[o]<<16&16711680)+(t[o+1]<<8&65280)+(255&t[o+2]),i.push(s(n));return i.join("")}return e["-".charCodeAt(0)]=62,e["_".charCodeAt(0)]=63,Ht}(),r=Gt(),n="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=s,t.SlowBuffer=function(t){return+t!=t&&(t=0),s.alloc(+t)},t.INSPECT_MAX_BYTES=50;const i=2147483647;function o(t){if(t>i)throw new RangeError('The value "'+t+'" is invalid for option "size"');const e=new Uint8Array(t);return Object.setPrototypeOf(e,s.prototype),e}function s(t,e,r){if("number"==typeof t){if("string"==typeof e)throw new TypeError('The "string" argument must be of type string. Received type number');return h(t)}return f(t,e,r)}function f(t,e,r){if("string"==typeof t)return function(t,e){if("string"==typeof e&&""!==e||(e="utf8"),!s.isEncoding(e))throw new TypeError("Unknown encoding: "+e);const r=0|p(t,e);let n=o(r);const i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}(t,e);if(ArrayBuffer.isView(t))return function(t){if(q(t,Uint8Array)){const e=new Uint8Array(t);return c(e.buffer,e.byteOffset,e.byteLength)}return a(t)}(t);if(null==t)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(q(t,ArrayBuffer)||t&&q(t.buffer,ArrayBuffer))return c(t,e,r);if("undefined"!=typeof SharedArrayBuffer&&(q(t,SharedArrayBuffer)||t&&q(t.buffer,SharedArrayBuffer)))return c(t,e,r);if("number"==typeof t)throw new TypeError('The "value" argument must not be of type number. Received type number');const n=t.valueOf&&t.valueOf();if(null!=n&&n!==t)return s.from(n,e,r);const i=function(t){if(s.isBuffer(t)){const e=0|l(t.length),r=o(e);return 0===r.length||t.copy(r,0,0,e),r}return void 0!==t.length?"number"!=typeof t.length||K(t.length)?o(0):a(t):"Buffer"===t.type&&Array.isArray(t.data)?a(t.data):void 0}(t);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof t[Symbol.toPrimitive])return s.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}function u(t){if("number"!=typeof t)throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function h(t){return u(t),o(t<0?0:0|l(t))}function a(t){const e=t.length<0?0:0|l(t.length),r=o(e);for(let n=0;n<e;n+=1)r[n]=255&t[n];return r}function c(t,e,r){if(e<0||t.byteLength<e)throw new RangeError('"offset" is outside of buffer bounds');if(t.byteLength<e+(r||0))throw new RangeError('"length" is outside of buffer bounds');let n;return n=void 0===e&&void 0===r?new Uint8Array(t):void 0===r?new Uint8Array(t,e):new Uint8Array(t,e,r),Object.setPrototypeOf(n,s.prototype),n}function l(t){if(t>=i)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+i.toString(16)+" bytes");return 0|t}function p(t,e){if(s.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||q(t,ArrayBuffer))return t.byteLength;if("string"!=typeof t)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);const r=t.length,n=arguments.length>2&&!0===arguments[2];if(!n&&0===r)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return V(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(t).length;default:if(i)return n?-1:V(t).length;e=(""+e).toLowerCase(),i=!0}}function y(t,e,r){let n=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return T(this,e,r);case"utf8":case"utf-8":return I(this,e,r);case"ascii":return U(this,e,r);case"latin1":case"binary":return L(this,e,r);case"base64":return A(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function g(t,e,r){const n=t[e];t[e]=t[r],t[r]=n}function d(t,e,r,n,i){if(0===t.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),K(r=+r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0){if(!i)return-1;r=0}if("string"==typeof e&&(e=s.from(e,n)),s.isBuffer(e))return 0===e.length?-1:b(t,e,r,n,i);if("number"==typeof e)return e&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):b(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function b(t,e,r,n,i){let o,s=1,f=t.length,u=e.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||e.length<2)return-1;s=2,f/=2,u/=2,r/=2}function h(t,e){return 1===s?t[e]:t.readUInt16BE(e*s)}if(i){let n=-1;for(o=r;o<f;o++)if(h(t,o)===h(e,-1===n?0:o-n)){if(-1===n&&(n=o),o-n+1===u)return n*s}else-1!==n&&(o-=o-n),n=-1}else for(r+u>f&&(r=f-u),o=r;o>=0;o--){let r=!0;for(let n=0;n<u;n++)if(h(t,o+n)!==h(e,n)){r=!1;break}if(r)return o}return-1}function w(t,e,r,n){r=Number(r)||0;const i=t.length-r;n?(n=Number(n))>i&&(n=i):n=i;const o=e.length;let s;for(n>o/2&&(n=o/2),s=0;s<n;++s){const n=parseInt(e.substr(2*s,2),16);if(K(n))return s;t[r+s]=n}return s}function E(t,e,r,n){return Y(V(e,t.length-r),t,r,n)}function B(t,e,r,n){return Y(function(t){const e=[];for(let r=0;r<t.length;++r)e.push(255&t.charCodeAt(r));return e}(e),t,r,n)}function m(t,e,r,n){return Y(G(e),t,r,n)}function _(t,e,r,n){return Y(function(t,e){let r,n,i;const o=[];for(let s=0;s<t.length&&!((e-=2)<0);++s)r=t.charCodeAt(s),n=r>>8,i=r%256,o.push(i),o.push(n);return o}(e,t.length-r),t,r,n)}function A(t,r,n){return 0===r&&n===t.length?e.fromByteArray(t):e.fromByteArray(t.slice(r,n))}function I(t,e,r){r=Math.min(t.length,r);const n=[];let i=e;for(;i<r;){const e=t[i];let o=null,s=e>239?4:e>223?3:e>191?2:1;if(i+s<=r){let r,n,f,u;switch(s){case 1:e<128&&(o=e);break;case 2:r=t[i+1],128==(192&r)&&(u=(31&e)<<6|63&r,u>127&&(o=u));break;case 3:r=t[i+1],n=t[i+2],128==(192&r)&&128==(192&n)&&(u=(15&e)<<12|(63&r)<<6|63&n,u>2047&&(u<55296||u>57343)&&(o=u));break;case 4:r=t[i+1],n=t[i+2],f=t[i+3],128==(192&r)&&128==(192&n)&&128==(192&f)&&(u=(15&e)<<18|(63&r)<<12|(63&n)<<6|63&f,u>65535&&u<1114112&&(o=u))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),i+=s}return function(t){const e=t.length;if(e<=v)return String.fromCharCode.apply(String,t);let r="",n=0;for(;n<e;)r+=String.fromCharCode.apply(String,t.slice(n,n+=v));return r}(n)}t.kMaxLength=i,s.TYPED_ARRAY_SUPPORT=function(){try{const t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),42===t.foo()}catch(t){return!1}}(),s.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(s.prototype,"parent",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.buffer}}),Object.defineProperty(s.prototype,"offset",{enumerable:!0,get:function(){if(s.isBuffer(this))return this.byteOffset}}),s.poolSize=8192,s.from=function(t,e,r){return f(t,e,r)},Object.setPrototypeOf(s.prototype,Uint8Array.prototype),Object.setPrototypeOf(s,Uint8Array),s.alloc=function(t,e,r){return function(t,e,r){return u(t),t<=0?o(t):void 0!==e?"string"==typeof r?o(t).fill(e,r):o(t).fill(e):o(t)}(t,e,r)},s.allocUnsafe=function(t){return h(t)},s.allocUnsafeSlow=function(t){return h(t)},s.isBuffer=function(t){return null!=t&&!0===t._isBuffer&&t!==s.prototype},s.compare=function(t,e){if(q(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),q(e,Uint8Array)&&(e=s.from(e,e.offset,e.byteLength)),!s.isBuffer(t)||!s.isBuffer(e))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(t===e)return 0;let r=t.length,n=e.length;for(let i=0,o=Math.min(r,n);i<o;++i)if(t[i]!==e[i]){r=t[i],n=e[i];break}return r<n?-1:n<r?1:0},s.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},s.concat=function(t,e){if(!Array.isArray(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return s.alloc(0);let r;if(void 0===e)for(e=0,r=0;r<t.length;++r)e+=t[r].length;const n=s.allocUnsafe(e);let i=0;for(r=0;r<t.length;++r){let e=t[r];if(q(e,Uint8Array))i+e.length>n.length?(s.isBuffer(e)||(e=s.from(e)),e.copy(n,i)):Uint8Array.prototype.set.call(n,e,i);else{if(!s.isBuffer(e))throw new TypeError('"list" argument must be an Array of Buffers');e.copy(n,i)}i+=e.length}return n},s.byteLength=p,s.prototype._isBuffer=!0,s.prototype.swap16=function(){const t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let e=0;e<t;e+=2)g(this,e,e+1);return this},s.prototype.swap32=function(){const t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let e=0;e<t;e+=4)g(this,e,e+3),g(this,e+1,e+2);return this},s.prototype.swap64=function(){const t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let e=0;e<t;e+=8)g(this,e,e+7),g(this,e+1,e+6),g(this,e+2,e+5),g(this,e+3,e+4);return this},s.prototype.toString=function(){const t=this.length;return 0===t?"":0===arguments.length?I(this,0,t):y.apply(this,arguments)},s.prototype.toLocaleString=s.prototype.toString,s.prototype.equals=function(t){if(!s.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===s.compare(this,t)},s.prototype.inspect=function(){let e="";const r=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(e+=" ... "),"<Buffer "+e+">"},n&&(s.prototype[n]=s.prototype.inspect),s.prototype.compare=function(t,e,r,n,i){if(q(t,Uint8Array)&&(t=s.from(t,t.offset,t.byteLength)),!s.isBuffer(t))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof t);if(void 0===e&&(e=0),void 0===r&&(r=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),e<0||r>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&e>=r)return 0;if(n>=i)return-1;if(e>=r)return 1;if(this===t)return 0;let o=(i>>>=0)-(n>>>=0),f=(r>>>=0)-(e>>>=0);const u=Math.min(o,f),h=this.slice(n,i),a=t.slice(e,r);for(let t=0;t<u;++t)if(h[t]!==a[t]){o=h[t],f=a[t];break}return o<f?-1:f<o?1:0},s.prototype.includes=function(t,e,r){return-1!==this.indexOf(t,e,r)},s.prototype.indexOf=function(t,e,r){return d(this,t,e,r,!0)},s.prototype.lastIndexOf=function(t,e,r){return d(this,t,e,r,!1)},s.prototype.write=function(t,e,r,n){if(void 0===e)n="utf8",r=this.length,e=0;else if(void 0===r&&"string"==typeof e)n=e,r=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e>>>=0,isFinite(r)?(r>>>=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}const i=this.length-e;if((void 0===r||r>i)&&(r=i),t.length>0&&(r<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");let o=!1;for(;;)switch(n){case"hex":return w(this,t,e,r);case"utf8":case"utf-8":return E(this,t,e,r);case"ascii":case"latin1":case"binary":return B(this,t,e,r);case"base64":return m(this,t,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,t,e,r);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},s.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const v=4096;function U(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(127&t[i]);return n}function L(t,e,r){let n="";r=Math.min(t.length,r);for(let i=e;i<r;++i)n+=String.fromCharCode(t[i]);return n}function T(t,e,r){const n=t.length;(!e||e<0)&&(e=0),(!r||r<0||r>n)&&(r=n);let i="";for(let n=e;n<r;++n)i+=J[t[n]];return i}function S(t,e,r){const n=t.slice(e,r);let i="";for(let t=0;t<n.length-1;t+=2)i+=String.fromCharCode(n[t]+256*n[t+1]);return i}function R(t,e,r){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>r)throw new RangeError("Trying to access beyond buffer length")}function O(t,e,r,n,i,o){if(!s.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||e<o)throw new RangeError('"value" argument is out of bounds');if(r+n>t.length)throw new RangeError("Index out of range")}function M(t,e,r,n,i){j(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o,o>>=8,t[r++]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,s>>=8,t[r++]=s,r}function C(t,e,r,n,i){j(e,n,i,t,r,7);let o=Number(e&BigInt(4294967295));t[r+7]=o,o>>=8,t[r+6]=o,o>>=8,t[r+5]=o,o>>=8,t[r+4]=o;let s=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=s,s>>=8,t[r+2]=s,s>>=8,t[r+1]=s,s>>=8,t[r]=s,r+8}function N(t,e,r,n,i,o){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function k(t,e,n,i,o){return e=+e,n>>>=0,o||N(t,0,n,4),r.write(t,e,n,i,23,4),n+4}function x(t,e,n,i,o){return e=+e,n>>>=0,o||N(t,0,n,8),r.write(t,e,n,i,52,8),n+8}s.prototype.slice=function(t,e){const r=this.length;(t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e<t&&(e=t);const n=this.subarray(t,e);return Object.setPrototypeOf(n,s.prototype),n},s.prototype.readUintLE=s.prototype.readUIntLE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t],i=1,o=0;for(;++o<e&&(i*=256);)n+=this[t+o]*i;return n},s.prototype.readUintBE=s.prototype.readUIntBE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t+--e],i=1;for(;e>0&&(i*=256);)n+=this[t+--e]*i;return n},s.prototype.readUint8=s.prototype.readUInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),this[t]},s.prototype.readUint16LE=s.prototype.readUInt16LE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]|this[t+1]<<8},s.prototype.readUint16BE=s.prototype.readUInt16BE=function(t,e){return t>>>=0,e||R(t,2,this.length),this[t]<<8|this[t+1]},s.prototype.readUint32LE=s.prototype.readUInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},s.prototype.readUint32BE=s.prototype.readUInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},s.prototype.readBigUInt64LE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=e+256*this[++t]+65536*this[++t]+this[++t]*2**24,i=this[++t]+256*this[++t]+65536*this[++t]+r*2**24;return BigInt(n)+(BigInt(i)<<BigInt(32))}),s.prototype.readBigUInt64BE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=e*2**24+65536*this[++t]+256*this[++t]+this[++t],i=this[++t]*2**24+65536*this[++t]+256*this[++t]+r;return(BigInt(n)<<BigInt(32))+BigInt(i)}),s.prototype.readIntLE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=this[t],i=1,o=0;for(;++o<e&&(i*=256);)n+=this[t+o]*i;return i*=128,n>=i&&(n-=Math.pow(2,8*e)),n},s.prototype.readIntBE=function(t,e,r){t>>>=0,e>>>=0,r||R(t,e,this.length);let n=e,i=1,o=this[t+--n];for(;n>0&&(i*=256);)o+=this[t+--n]*i;return i*=128,o>=i&&(o-=Math.pow(2,8*e)),o},s.prototype.readInt8=function(t,e){return t>>>=0,e||R(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},s.prototype.readInt16LE=function(t,e){t>>>=0,e||R(t,2,this.length);const r=this[t]|this[t+1]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt16BE=function(t,e){t>>>=0,e||R(t,2,this.length);const r=this[t+1]|this[t]<<8;return 32768&r?4294901760|r:r},s.prototype.readInt32LE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},s.prototype.readInt32BE=function(t,e){return t>>>=0,e||R(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},s.prototype.readBigInt64LE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=this[t+4]+256*this[t+5]+65536*this[t+6]+(r<<24);return(BigInt(n)<<BigInt(32))+BigInt(e+256*this[++t]+65536*this[++t]+this[++t]*2**24)}),s.prototype.readBigInt64BE=Q(function(t){z(t>>>=0,"offset");const e=this[t],r=this[t+7];void 0!==e&&void 0!==r||F(t,this.length-8);const n=(e<<24)+65536*this[++t]+256*this[++t]+this[++t];return(BigInt(n)<<BigInt(32))+BigInt(this[++t]*2**24+65536*this[++t]+256*this[++t]+r)}),s.prototype.readFloatLE=function(t,e){return t>>>=0,e||R(t,4,this.length),r.read(this,t,!0,23,4)},s.prototype.readFloatBE=function(t,e){return t>>>=0,e||R(t,4,this.length),r.read(this,t,!1,23,4)},s.prototype.readDoubleLE=function(t,e){return t>>>=0,e||R(t,8,this.length),r.read(this,t,!0,52,8)},s.prototype.readDoubleBE=function(t,e){return t>>>=0,e||R(t,8,this.length),r.read(this,t,!1,52,8)},s.prototype.writeUintLE=s.prototype.writeUIntLE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||O(this,t,e,r,Math.pow(2,8*r)-1,0);let i=1,o=0;for(this[e]=255&t;++o<r&&(i*=256);)this[e+o]=t/i&255;return e+r},s.prototype.writeUintBE=s.prototype.writeUIntBE=function(t,e,r,n){t=+t,e>>>=0,r>>>=0,n||O(this,t,e,r,Math.pow(2,8*r)-1,0);let i=r-1,o=1;for(this[e+i]=255&t;--i>=0&&(o*=256);)this[e+i]=t/o&255;return e+r},s.prototype.writeUint8=s.prototype.writeUInt8=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,1,255,0),this[e]=255&t,e+1},s.prototype.writeUint16LE=s.prototype.writeUInt16LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,65535,0),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeUint16BE=s.prototype.writeUInt16BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,65535,0),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeUint32LE=s.prototype.writeUInt32LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,4294967295,0),this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t,e+4},s.prototype.writeUint32BE=s.prototype.writeUInt32BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,4294967295,0),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeBigUInt64LE=Q(function(t,e=0){return M(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeBigUInt64BE=Q(function(t,e=0){return C(this,t,e,BigInt(0),BigInt("0xffffffffffffffff"))}),s.prototype.writeIntLE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);O(this,t,e,r,n-1,-n)}let i=0,o=1,s=0;for(this[e]=255&t;++i<r&&(o*=256);)t<0&&0===s&&0!==this[e+i-1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},s.prototype.writeIntBE=function(t,e,r,n){if(t=+t,e>>>=0,!n){const n=Math.pow(2,8*r-1);O(this,t,e,r,n-1,-n)}let i=r-1,o=1,s=0;for(this[e+i]=255&t;--i>=0&&(o*=256);)t<0&&0===s&&0!==this[e+i+1]&&(s=1),this[e+i]=(t/o|0)-s&255;return e+r},s.prototype.writeInt8=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,1,127,-128),t<0&&(t=255+t+1),this[e]=255&t,e+1},s.prototype.writeInt16LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,32767,-32768),this[e]=255&t,this[e+1]=t>>>8,e+2},s.prototype.writeInt16BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,2,32767,-32768),this[e]=t>>>8,this[e+1]=255&t,e+2},s.prototype.writeInt32LE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,2147483647,-2147483648),this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24,e+4},s.prototype.writeInt32BE=function(t,e,r){return t=+t,e>>>=0,r||O(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t,e+4},s.prototype.writeBigInt64LE=Q(function(t,e=0){return M(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeBigInt64BE=Q(function(t,e=0){return C(this,t,e,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),s.prototype.writeFloatLE=function(t,e,r){return k(this,t,e,!0,r)},s.prototype.writeFloatBE=function(t,e,r){return k(this,t,e,!1,r)},s.prototype.writeDoubleLE=function(t,e,r){return x(this,t,e,!0,r)},s.prototype.writeDoubleBE=function(t,e,r){return x(this,t,e,!1,r)},s.prototype.copy=function(t,e,r,n){if(!s.isBuffer(t))throw new TypeError("argument should be a Buffer");if(r||(r=0),n||0===n||(n=this.length),e>=t.length&&(e=t.length),e||(e=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-e<n-r&&(n=t.length-e+r);const i=n-r;return this===t&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(e,r,n):Uint8Array.prototype.set.call(t,this.subarray(r,n),e),i},s.prototype.fill=function(t,e,r,n){if("string"==typeof t){if("string"==typeof e?(n=e,e=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!s.isEncoding(n))throw new TypeError("Unknown encoding: "+n);if(1===t.length){const e=t.charCodeAt(0);("utf8"===n&&e<128||"latin1"===n)&&(t=e)}}else"number"==typeof t?t&=255:"boolean"==typeof t&&(t=Number(t));if(e<0||this.length<e||this.length<r)throw new RangeError("Out of range index");if(r<=e)return this;let i;if(e>>>=0,r=void 0===r?this.length:r>>>0,t||(t=0),"number"==typeof t)for(i=e;i<r;++i)this[i]=t;else{const o=s.isBuffer(t)?t:s.from(t,n),f=o.length;if(0===f)throw new TypeError('The value "'+t+'" is invalid for argument "value"');for(i=0;i<r-e;++i)this[i+e]=o[i%f]}return this};const P={};function $(t,e,r){P[t]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:e.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${t}]`,this.stack,delete this.name}get code(){return t}set code(t){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:t,writable:!0})}toString(){return`${this.name} [${t}]: ${this.message}`}}}function D(t){let e="",r=t.length;const n="-"===t[0]?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function j(t,e,r,n,i,o){if(t>r||t<e){const r="bigint"==typeof e?"n":"";let n;throw n=0===e||e===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(o+1)}${r}`:`>= -(2${r} ** ${8*(o+1)-1}${r}) and < 2 ** ${8*(o+1)-1}${r}`,new P.ERR_OUT_OF_RANGE("value",n,t)}!function(t,e,r){z(e,"offset"),void 0!==t[e]&&void 0!==t[e+r]||F(e,t.length-(r+1))}(n,i,o)}function z(t,e){if("number"!=typeof t)throw new P.ERR_INVALID_ARG_TYPE(e,"number",t)}function F(t,e,r){if(Math.floor(t)!==t)throw z(t,r),new P.ERR_OUT_OF_RANGE("offset","an integer",t);if(e<0)throw new P.ERR_BUFFER_OUT_OF_BOUNDS;throw new P.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${e}`,t)}$("ERR_BUFFER_OUT_OF_BOUNDS",function(t){return t?`${t} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),$("ERR_INVALID_ARG_TYPE",function(t,e){return`The "${t}" argument must be of type number. Received type ${typeof e}`},TypeError),$("ERR_OUT_OF_RANGE",function(t,e,r){let n=`The value of "${t}" is out of range.`,i=r;return Number.isInteger(r)&&Math.abs(r)>2**32?i=D(String(r)):"bigint"==typeof r&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=D(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);const H=/[^+/0-9A-Za-z-_]/g;function V(t,e){let r;e=e||1/0;const n=t.length;let i=null;const o=[];for(let s=0;s<n;++s){if(r=t.charCodeAt(s),r>55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&o.push(239,191,189);continue}if(s+1===n){(e-=3)>-1&&o.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&o.push(239,191,189),i=r;continue}r=65536+(i-55296<<10|r-56320)}else i&&(e-=3)>-1&&o.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;o.push(r)}else if(r<2048){if((e-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((e-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function G(t){return e.toByteArray(function(t){if((t=(t=t.split("=")[0]).trim().replace(H,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function Y(t,e,r,n){let i;for(i=0;i<n&&!(i+r>=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function q(t,e){return t instanceof e||null!=t&&null!=t.constructor&&null!=t.constructor.name&&t.constructor.name===e.name}function K(t){return t!=t}const J=function(){const t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){const n=16*r;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function Q(t){return"undefined"==typeof BigInt?W:t}function W(){throw new Error("BigInt not supported")}}(Ft)),Ft);let qt={SERVER_TIME_NONCE:176,AUTH_REQ:177,AUTH_RES:178,AUTH_FAIL:179,ENC_PACK:182,ENC_E2E:183,ENC_488:184};for(let t in qt)qt[qt[t]]=t;const Kt={SERVER_TIME_NONCE:Pt.meta(Pt.MB("header","8",0),Pt.MB("unixTime","32L",0),Pt.MB("milTime","16L",0),Pt.MB("counter","16L",0),Pt.MB("nonce",Yt.Buffer.alloc(4))),AUTH_REQ:Pt.meta(Pt.MB("header","8",0),Pt.MB("id8",Yt.Buffer.alloc(8)),Pt.MB("nonce",Yt.Buffer.alloc(4)),Pt.MB("hmac32",Yt.Buffer.alloc(32))),AUTH_RES:Pt.meta(Pt.MB("header","8",0),Pt.MB("hmac32",Yt.Buffer.alloc(32))),ENC_PACK:Pt.meta(Pt.MB("type","8",0),Pt.MB("len","32L",0),Pt.MB("salt12",Yt.Buffer.alloc(12)),Pt.MB("hmac",8,0)),ENC_488:Pt.meta(Pt.MB("type","8",0),Pt.MB("len","32L",0),Pt.MB("otpSrc8",Yt.Buffer.alloc(8)),Pt.MB("hmac8",Yt.Buffer.alloc(8)))};function Jt(t){let e=t[t.length-1];return e[2]+e[3]}const Qt={SERVER_TIME_NONCE:Jt(Kt.SERVER_TIME_NONCE),AUTH_REQ:Jt(Kt.AUTH_REQ),AUTH_RES:Jt(Kt.AUTH_RES),ENC_PACK:Jt(Kt.ENC_PACK),ENC_488:Jt(Kt.ENC_488)};function Wt(t,e){if(!(t instanceof Uint8Array&&e instanceof Uint8Array&&t.length===e.length))return!1;let r=0;for(let n=0;n<t.length;n++)r|=t[n]^e[n];return 0===r}function Xt(t,e,r,n,i=!1){if(!(t instanceof Uint8Array))return;const o=Yt.Buffer.from(t);return o.length<r||o[0]!==e||(i?o.readUInt32LE(1)!==o.length-r:o.length!==r)?void 0:Pt.unpack(o,n)}function Zt(t){return globalThis.crypto.getRandomValues(Yt.Buffer.alloc(t))}class te{constructor(){this._id8=Yt.Buffer.alloc(8),this._otpSrc44=Yt.Buffer.alloc(44),this._otp36=Yt.Buffer.alloc(36),this._hmac=Yt.Buffer.alloc(32),this.auth_salt12=Yt.Buffer.alloc(12),this.localNonce=Yt.Buffer.alloc(4),this.remoteNonce=Yt.Buffer.alloc(4),this.isAuthorized=!1,this.counter=0,this._hasKey=!1,this._lastSendTime=0}clearAuth(){this._id8.fill(0),this._otpSrc44.fill(0),this._otp36.fill(0),this._hmac.fill(0),this.auth_salt12.fill(0),this.localNonce.fill(0),this.remoteNonce.fill(0),this.isAuthorized=!1,this.counter=0,this._hasKey=!1,this._lastSendTime=0}set_hash_id8(t){Pt.B8($t.hash(t)).copy(this._id8,0,0,8)}set_id8(t){let e=Pt.B8(t);this._id8.fill(0),e.copy(this._id8,0,0,8)}set_key(t){const e=Pt.B8(t);if(!e||0===e.length)throw new TypeError("Key must not be empty");this.copy_key(Pt.B8($t.hash(e)))}set_id_key(t){let e=t.indexOf(".");if(-1==e)return;let r=t.substring(0,e),n=t.substring(e+1);this.set_id8(r),this.set_key(n)}copy_id8(t){t.copy(this._id8,0,0,8)}copy_key(t){if(!(t instanceof Uint8Array)||32!==t.length)throw new TypeError("copy_key requires exactly 32 bytes");this._otpSrc44.set(t,0),this._hasKey=!0}sha256_n(t,e){let r=$t.hash(t);for(let t=0;t<e;t++)r=$t.hash(r);return r}set_clock_rand(){this.set_clock_nonce(Zt(4))}set_clock_nonce(t){if(!(t instanceof Uint8Array)||4!==t.length)throw new TypeError("Nonce must be 4 bytes");let e=Math.max(Date.now(),this._lastSendTime);if(this.counter=this.counter+1&65535,0===this.counter&&e===this._lastSendTime&&e++,!Number.isSafeInteger(e)||e<0||Math.floor(e/1e3)>4294967295)throw new RangeError("Clock is outside the protocol range");this._lastSendTime=e,Yt.Buffer.concat([Pt.NB("32L",Math.floor(e/1e3)),Pt.NB("16L",e%1e3),Pt.NB("16L",this.counter),Yt.Buffer.from(t)]).copy(this._otpSrc44,32)}_requireKey(){if(!this._hasKey)throw new Error("Set a key before encryption or authentication")}set_salt12(t,e){if(12!=t.byteLength)throw TypeError("set_salt12: Invalid salt12 byteLength.");t.copy(this._otpSrc44,32)}resetOTP(){this._requireKey(),Pt.B8($t.hash(this._otpSrc44)).copy(this._otp36,0,0,32)}getIndexOTP(t){return this._otp36.writeUInt32LE(t,32),$t.hash(this._otp36)}generateHMAC(t){this._requireKey();let e=Yt.Buffer.concat([this._otpSrc44,t]);this._hmac=Pt.B8($t.hash(e))}getHMAC8(t){this._requireKey();let e=Yt.Buffer.concat([this._otpSrc44,t]);return this._hmac=Pt.B8($t.hash(e)),this._hmac.subarray(0,8)}xotp(t,e=0,r=!1){let n=(t=Pt.B8(t,r)).byteLength,i=e,o=0,s=0;for(;n>0;){s=n<32?n:32;let e=this.getIndexOTP(++i);for(let r=0;r<s;r++)t[o++]^=e[r];n-=32}return t}server_time_nonce(){const t=Date.now(),e=Math.floor(t/1e3),r=t%1e3;return this.localNonce=Zt(4),this.auth_salt12=Yt.Buffer.concat([Pt.NB("32L",e),Pt.NB("16L",r),Zt(2),this.localNonce]),Yt.Buffer.concat([Pt.NB("8",qt.SERVER_TIME_NONCE),this.auth_salt12])}auth_req(t){if(!this._hasKey)return!1;let e=Xt(t,qt.SERVER_TIME_NONCE,Qt.SERVER_TIME_NONCE,Kt.SERVER_TIME_NONCE);if(e&&e.milTime>=1e3)return!1;if(e){let t=Yt.Buffer.concat([Pt.NB("32L",e.unixTime),Pt.NB("16L",e.milTime),Pt.NB("16L",e.counter),e.nonce]);return this.set_salt12(t,"auth_req"),this.localNonce=Zt(4),this.generateHMAC(this.localNonce),this.remoteNonce=e.nonce,Pt.pack(Pt.MB("#header","8",qt.AUTH_REQ),Pt.MB("#id8",this._id8),Pt.MB("#nonce",this.localNonce),Pt.MB("#hmac32",this._hmac))}return!1}verify_auth_req(t){if(!this._hasKey)return!1;let e;if(t instanceof Uint8Array?e=Xt(t,qt.AUTH_REQ,Qt.AUTH_REQ,Kt.AUTH_REQ):t&&"object"==typeof t&&(e=t),!e||e.header!==qt.AUTH_REQ||!(e.id8 instanceof Uint8Array)||8!==e.id8.length||!(e.nonce instanceof Uint8Array)||4!==e.nonce.length||!(e.hmac32 instanceof Uint8Array)||32!==e.hmac32.length||e.$OTHERS&&0!==e.$OTHERS.length)return!1;this.set_salt12(this.auth_salt12,"verify_auth_req 1/2"),this.generateHMAC(e.nonce);let r=this._hmac;if(Wt(e.hmac32,r)){this.remoteNonce=Yt.Buffer.from(e.nonce);let t=Yt.Buffer.concat([this.localNonce,this.remoteNonce,this.localNonce]);this.set_salt12(t,"verify_auth_req 2/2"),this.generateHMAC(e.nonce);let r=this._hmac,n=Pt.rawPack(Pt.MB("header","8",qt.AUTH_RES),Pt.MB("hmac32",r));return this.isAuthorized=!0,n}return!1}verify_auth_res(t){if(!this._hasKey)return!1;let e=Xt(t,qt.AUTH_RES,Qt.AUTH_RES,Kt.AUTH_RES);if(e){let t=Yt.Buffer.concat([this.remoteNonce,this.localNonce,this.remoteNonce]);if(this.set_salt12(t,"verify_auth_res"),this.generateHMAC(this.localNonce),Wt(this._hmac,e.hmac32))return this.isAuthorized=!0,!0}}encrypt_488(t){if(!this.isAuthorized||!this._hasKey)return;t=Pt.B8(t),this.set_clock_nonce(this.remoteNonce),this.resetOTP();let e=this.getHMAC8(t),r=this.xotp(t);return Pt.pack(Pt.MB("#type","8",qt.ENC_488),Pt.MB("#len","32L",t.byteLength),Pt.MB("#otpSrc8",this._otpSrc44.subarray(32,40)),Pt.MB("#hmac8",e),Pt.MB("#xdata",r))}decrypt_488(t){if(!this.isAuthorized||!this._hasKey)return;let e=t;if(t instanceof Uint8Array&&t[0]===qt.ENC_E2E){if(t.length<Qt.ENC_488)return;const r=Yt.Buffer.from(t),n=r.readUInt32LE(1);if(n>r.length-Qt.ENC_488)return;e=Yt.Buffer.from(r.subarray(0,Qt.ENC_488+n)),e[0]=qt.ENC_488}const r=Xt(e,qt.ENC_488,Qt.ENC_488,Kt.ENC_488,!0);if(!(r&&(n=r.otpSrc8,n.readUInt16LE(4)<1e3)))return;var n;this.set_salt12(Yt.Buffer.concat([r.otpSrc8,this.localNonce]),"decrypt_488"),this.resetOTP();const i=this.xotp(r.$OTHERS??Yt.Buffer.alloc(0));return Wt(this.getHMAC8(i),r.hmac8)?i:void 0}encryptPack(t){this._requireKey(),t=Pt.B8(t),this.set_clock_rand(),this.resetOTP();let e=this.getHMAC8(t),r=this.xotp(t);return Pt.pack(Pt.MB("#type","8",qt.ENC_PACK),Pt.MB("#len","32L",t.byteLength),Pt.MB("#salt12",this._otpSrc44.subarray(32)),Pt.MB("#hmac8",e),Pt.MB("#xdata",r))}decryptPack(t){if(!this._hasKey)return;const e=Xt(t,qt.ENC_PACK,Qt.ENC_PACK,Kt.ENC_PACK,!0);if(!e)return;this.set_salt12(e.salt12,"decryptPack"),this.resetOTP();const r=this.xotp(e.$OTHERS??Yt.Buffer.alloc(0));return Wt(e.hmac,this.getHMAC8(r))?(e.data=r,e):void 0}encrypt_e2e(t,e){return this._withKey(e,()=>this.encryptPack(t))}decrypt_e2e(t,e){return this._withKey(e,()=>this.decryptPack(t))}_withKey(t,e){const r=Pt.B8(t);if(!r||0===r.length)throw new TypeError("Key must not be empty");const n=[Yt.Buffer.from(this._otpSrc44),Yt.Buffer.from(this._otp36),Yt.Buffer.from(this._hmac)],i=this._hasKey;try{return this._otpSrc44.set($t.hash(r),0),this._hasKey=!0,e()}finally{this._otpSrc44.set(n[0]),this._otp36.set(n[1]),this._hmac.set(n[2]),this._hasKey=i;for(const t of n)t.fill(0)}}}te.RAND=Zt,te.BohoMsg=qt,te.Meta=Kt,te.MetaSize=Qt,te.sha256=$t,te.MBP=Pt,te.Buffer=Yt.Buffer;const ee=k.Buffer,re=new TextEncoder,ne=new TextDecoder;function ie(t,e=!0){if("string"!=typeof t)throw TypeError("tag should be string.");const r=re.encode(t);if(!e&&0===r.byteLength||r.byteLength>H.TAG_LEN1)throw TypeError("tag UTF-8 byte length must be "+(e?"0":"1")+"~255");return r}class oe extends j{constructor(t){super(),this.cid="",this.ip="",this.socket=null,this.url=t,this.state=z.CLOSED,this.stateName=this.getStateName(),this._stateRevision=0,this.txCounter=0,this.rxCounter=0,this.txBytes=0,this.rxBytes=0,this.lastTxRxTime=Date.now(),this.connectionCheckerPeriod=H.CONNECTION_CHECKER_PERIOD,this.connectionCheckerIntervalID=null,this.boho=new te,this.serverTimeNonce=ee.alloc(te.MetaSize.SERVER_TIME_NONCE),this.TLS=!1,this.encMode=F.AUTO,this.useAuth=!1,this.nick="",this.channels=new Set,this.promiseMap=new Map,this.promiseTimeOut=H.PROMISE_TIMEOUT,this.mid=0,this.level=3,this.quota=q[this.level],this.serverSet={},this.linkMap=new Map,this.autoReconnect=!0,this._closed=!1,this.on("open",this.onOpen.bind(this)),this.on("close",this.onClose.bind(this)),this.on("socket_data",this.onData.bind(this))}close(){if(!1===this.autoReconnect&&(clearInterval(this.connectionCheckerIntervalID),this.connectionCheckerIntervalID=null),!this._closed){if(this._closed=!0,this.socket){if(0===this.socket.readyState){const t=this.socket;t.onopen=()=>{t&&t.close()},t.onmessage=null,t.onerror=null,t.onclose=null}else try{this.socket.close?.()}catch{}this.socket=null}this.promiseMap.clear(),this.cid="",this.boho&&(this.boho.isAuthorized=!1),this.state!==z.STOP&&this.stateChange("closed")&&this.emit("closed")}}stop(){this.autoReconnect=!1,this.close(),this.cid="",this.stateChange("stop","stop")}destroy(){this.stop(),this.removeAllListeners(),this.channels.clear(),this.linkMap.clear(),this.boho=null}keepAlive(){this.keepConnection(),Date.now()-this.lastTxRxTime>H.CLIENT_PING_PERIOD&&this.ping()}redirect(t){this.stateChange("redirecting","redirecting"),this.close(),this.createConnection(t)}open(t){this.socket&&this.close(),t&&(this.url=t),this.url?(this.createConnection(this.url),this._closed||this.connectionCheckerIntervalID||(this.connectionCheckerIntervalID=setInterval(this.keepAlive.bind(this),this.connectionCheckerPeriod))):this.emit("error",new Error("URL is not set."))}onOpen(){this._closed=!1,this.url.includes("wss://")?this.TLS=!0:this.TLS=!1,this.stateChange("open")}onClose(){this.close()}login(t,e){if(this.serverTimeNonce){this.auth(t,e),this.useAuth=!0;let r=this.boho.auth_req(this.serverTimeNonce);this.send(r),this.stateChange("auth_req","auth_req")}return this}auth(t,e){return t||e||this.emit("error",new Error("auth failed. no id and key.")),!e&&t.includes(".")?this.boho.set_id_key(t):t&&e?(this.boho.set_id8(t),this.boho.set_key(e)):this.emit("error",new Error("auth failed. no id or key.")),this.useAuth=!0,this}onData(t){let e,r=t[0];if(r===te.BohoMsg.ENC_488)e=this.boho.decrypt_488(t),e&&(r=e[0],t=e);else if(r===te.BohoMsg.ENC_E2E)try{if(e=this.boho.decrypt_488(t),!e)return;r=e[0],t.set(e,te.MetaSize.ENC_488),t=t.subarray(te.MetaSize.ENC_488)}catch(t){return}let n=G[r];switch(n||(n=te.BohoMsg[r]),r){case G.OVER_SIZE:console.log("## server sent: over_size event."),this.emit("over_size","over_size");break;case G.PING:this.pong();break;case G.PONG:break;case G.ECHO:try{let e=ne.decode(t.subarray(1));this.emit("echo",e)}catch(t){this.emit("error",new Error("ECHO data error"))}break;case G.IAM_RES:try{let e=ne.decode(t.subarray(1)),r=JSON.parse(e);r.ip&&(this.ip=r.ip),r.nick&&(this.nick=r.nick),r.did&&(this.did=r.did),r.uid&&(this.uid=r.uid),this.emit("iam_res",e)}catch(t){this.emit("error",new Error("IAM_RES data error"))}break;case G.CID_RES:let r=ne.decode(t.subarray(1));this.cid=r,this.stateChange("ready","cid_ready"),this.subscribe_channels();break;case G.QUOTA_LEVEL:let n=t[1];this.level=n,this.quota=q[n];break;case G.AUTH_CLEAR:this.useAuth=!1,this.boho.clearAuth(),this.stateChange("auth_clear","server request auth_clear."),this.stop();break;case G.SERVER_REDIRECT:let i,o,s;7==t.byteLength?(i=function(t){if(6!=t.byteLength)return;return t[0].toString()+"."+t[1].toString()+"."+t[2].toString()+"."+t[3].toString()+":"+((t[4]<<8)+t[5]).toString()}(t.subarray(1)),s="cong://"):(i=ne.decode(t.subarray(1)),s=""),o=s+i,this.redirect(o);break;case te.BohoMsg.SERVER_TIME_NONCE:if(t.copy(this.serverTimeNonce),!this.stateChange("server_ready","server_ready"))break;this.useAuth?(this.send(this.boho.auth_req(t)),this.stateChange("auth_req","auth_req")):this.send(ee.from([G.CID_REQ]));break;case G.SERVER_SIGNAL:try{let e=ne.decode(t.subarray(1)),r=JSON.parse(e);r.event&&r.data&&(this.serverSet=r.data,this.emit(r.event,r.data))}catch(t){this.emit("error",new Error("SERVER_SIGNAL parsing error"))}break;case G.SET:try{let e=k.unpack(t);e&&this.emit(e.topic,...e.args)}catch(t){this.emit("error",new Error("SET parsing error"))}break;case G.SIGNAL_E2E:case G.SIGNAL:try{let e=t.readUint8(1),r=t.subarray(2,2+e),n=ne.decode(r),i=t.readUint8(2+e),o=t.subarray(3+e);switch(i){case V.EMPTY:0===n.indexOf("@")?this.emit("@",n):(this.emit(n,n),this.emit("message",n));break;case V.TEXT:let t=o;0===o[o.byteLength-1]&&(t=o.subarray(0,o.byteLength-1));let e=ne.decode(t);0===n.indexOf("@")?this.emit("@",n,e):(this.emit(n,n,e),this.emit("message",n,e));break;case V.BINARY:0===n.indexOf("@")?this.emit("@",n,o):(this.emit(n,n,o),this.emit("message",n,o));break;case V.OBJECT:let r=ne.decode(o),i=JSON.parse(r);0===n.indexOf("@")?this.emit("@",n,i):(this.emit(n,n,i),this.emit("message",n,i));break;case V.MJSON:let s=ne.decode(o),f=JSON.parse(s);0===n.indexOf("@")?this.emit("@",n,...f):(this.emit(n,n,...f),this.emit("message",n,...f));break;case V.MBA:let u=k.unpack(o);0===n.indexOf("@")?this.emit("@",n,...u.args):(this.emit(n,n,...u.args),this.emit("message",n,...u.args))}}catch(t){console.log("IOCore IOMsg.SIGNAL parser err",t)}break;case G.RESPONSE_MBP:this.testPromise(t);break;case te.BohoMsg.AUTH_FAIL:this.boho.isAuthorized=!1,this.stateChange("auth_fail","auth_fail from server.");break;case te.BohoMsg.AUTH_RES:if(this.boho.verify_auth_res(t)){if(!this.stateChange("auth_res","server sent auth_res"))break;this.send(ee.from([G.CID_REQ]))}else this.boho.isAuthorized=!1,this.stateChange("auth_fail","verify_auth_res() invalid server_hmac");break;default:try{e=ne.decode(t),this.emit("text_message",e)}catch(t){}}}iam(t){t?this.send_enc_mode(k.pack(k.MB("#MsgType","8",G.IAM),k.MB("#",t))):this.send_enc_mode(k.pack(k.MB("#MsgType","8",G.IAM)))}ping(){this.send(ee.from([G.PING]))}pong(){this.send(ee.from([G.PONG]))}echo(t){t?this.send_enc_mode(k.pack(k.MB("#MsgType","8",G.ECHO),k.MB("#msg",t))):this.send(ee.from([G.ECHO]))}bin(...t){this.send(k.U8pack(...t))}send(t){if(t.byteLength>this.quota.signalSize)return this.emit("over_size"),console.log("## QUOTA LIMIT OVER!! \nsignal message.byteLength: ",t.byteLength),void console.log("## your maximum signalSize(bytes) is:",this.quota.signalSize);this.socket_send(t)}getEncryptionMode(){return!(this.encMode!==F.YES&&(this.encMode!==F.AUTO||this.TLS||!this.boho.isAuthorized))}send_enc_mode(t,e){if(void 0===e&&(e=this.getEncryptionMode()),t[0]==G.SIGNAL_E2E&&e){let e=t[1],r=this.boho.encrypt_488(t.subarray(0,3+e));r[0]=te.BohoMsg.ENC_E2E,this.send(ee.concat([r,t.subarray(3+e)]))}else if(e){let e=this.boho.encrypt_488(t);this.send(e)}else this.send(t)}setMsgPromise(t){return new Promise((e,r)=>{const n=setTimeout(e=>{this.promiseMap.has(t)&&(r("timeout"),this.promiseMap.delete(t))},this.promiseTimeOut);this.promiseMap.set(t,[e,r,n])})}testPromise(t){let e=k.unpack(t);if(e)if(this.promiseMap.has(e.mid)){let[t,r,n]=this.promiseMap.get(e.mid);clearTimeout(n),this.promiseMap.delete(e.mid),e.status<128?(e.ok=!0,t(e)):(e.ok=!1,r(e))}else console.log("no promise id")}publish(t,...e){this.signal(t,...e)}signal(t,...e){if("string"!=typeof t)throw TypeError("tag should be string.");t.startsWith("@")&&this.cid&&ie(this.cid+t);let r=J(t,...e);this.send_enc_mode(r)}decrypt_e2e(t,e){return this.boho.decrypt_e2e(t,e)}signal_e2e(t,e,r){const n=ie(t);if(t.startsWith("@")&&this.cid&&ie(this.cid+t),!this.boho.isAuthorized)return;let i=k.B8(e),o=this.boho.encrypt_e2e(i,r),s=k.pack(k.MB("#MsgType","8",G.SIGNAL_E2E),k.MB("#tagLen","8",n.byteLength),k.MB("#tag",n),k.MB("#payloadType","8",V.BINARY),k.MB("#payload",o));this.send_enc_mode(s)}set(t,...e){return t&&0!=e.length?this.call("store","set",t,...e):Promise.reject(new Error("set need storeName and value)"))}async get(t){if(!t)return Promise.reject(new Error("store get need storeName)"));let e=await this.call("store","get",t),{$:r}=k.unpack(e.body);return r}call(t,e,...r){if(!t||!e)return Promise.reject(new Error("request need target and topic)"));let n;return n=r.length>0?k.pack(k.MB("#MsgType","8",G.CALL),k.MB("mid","16",++this.mid),k.MB("target",t),k.MB("topic",e),k.MBA(...r)):k.pack(k.MB("#MsgType","8",G.CALL),k.MB("mid","16",++this.mid),k.MB("target",t),k.MB("topic",e)),this.send_enc_mode(n),this.setMsgPromise(this.mid)}subscribe(t){const e=ie(t);this.send_enc_mode(ee.concat([k.NB("8",G.SUBSCRIBE),k.NB("8",e.byteLength),e]))}subscribe_channels(){if(this.state!==z.READY||0===this.channels.size)return;const t=Array.from(this.channels).join(",").split(","),e=t.map(t=>ie(t).byteLength),r=[];let n=[],i=0;t.forEach((t,o)=>{n.length&&i+1+e[o]>H.TAG_LEN1&&(r.push(n.join(",")),n=[],i=0),i+=(n.length?1:0)+e[o],n.push(t)}),n.length&&r.push(n.join(",")),r.forEach(t=>this.subscribe(t))}unsubscribe(t=""){const e=ie(t);if(""==t)this.channels.clear();else{t.split(",").forEach(t=>{this.channels.delete(t)})}this.send_enc_mode(ee.concat([k.NB("8",G.UNSUBSCRIBE),k.NB("8",e.byteLength),e]))}listen(t,e){if("string"!=typeof t)throw TypeError("tag should be string.");if(ie(t,!1),"function"!=typeof e)throw TypeError("handler is not a function.");0!==t.indexOf("@")&&this.channels.add(t),this.on(t,e)}link(t,e,r){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");if("string"!=typeof e)throw TypeError("tag is not a string.");if(ie(e,!1),"function"!=typeof r)throw TypeError("handler is not a function.");let n;0!==e.indexOf("@")&&this.channels.add(e),n=this.linkMap.has(t)?this.linkMap.get(t):new Set,n.add(e),this.linkMap.set(t,n),this.on(e,r),this.subscribe(e)}unlink(t,e){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");if("string"!=typeof e)throw TypeError("tag is not a string.");ie(e,!1);const r=this.linkMap.get(t);r&&r.has(e)&&(this.unsubscribe(e),this.removeAllListeners(e),r.delete(e),0===r.size&&this.linkMap.delete(t))}unlinkAll(t){if("string"!=typeof t)throw TypeError("to(local link target) is not a string.");const e=this.linkMap.get(t);if(e){for(const t of e)this.unsubscribe(t),this.removeAllListeners(t);this.linkMap.delete(t)}}getMetric(){return{tx:this.txCounter,rx:this.rxCounter,txb:this.txBytes,rxb:this.rxBytes,last:(Date.now()-this.lastTxRxTime)/1e3}}getState(){return this.state}getStateName(){return z[this.state].toLowerCase()}getSecurity(){return{useAuth:this.useAuth,isTLS:this.TLS,isAuthorized:this.boho.isAuthorized,encMode:this.encMode,usingEncryption:this.getEncryptionMode()}}stateChange(t,e){let r=t.toLowerCase();const n=z[t.toUpperCase()];if("number"!=typeof n)throw new TypeError("Unknown state: "+t);const i=this.state!==n;this.state=n,this.stateName=r,i&&this._stateRevision++;const o=this._stateRevision;return i&&this.emit("change",r),o===this._stateRevision&&(e&&this.emit(r,e),o===this._stateRevision)}}const se=te.Buffer;class fe extends oe{static version="7.0.0";static binaryType="arraybuffer";static Boho=te;static MBP=te.MBP;static Buffer=te.Buffer;static constants=Y;static instanceCount=0;static webSocketCount=0;constructor(t){super(t),fe.instanceCount++,this.boundBrowserVisiblePing=this.browserVisiblePing.bind(this),document.addEventListener("visibilitychange",this.boundBrowserVisiblePing),t&&this.open()}browserVisiblePing(){"visible"===document.visibilityState&&this.ping()}stop(){super.stop()}destroy(){document.removeEventListener("visibilitychange",this.boundBrowserVisiblePing),super.destroy()}keepConnection(){this.autoReconnect&&(this.socket&&this.socket.readyState!==WebSocket.CLOSED||this.open())}createConnection(t){fe.webSocketCount++;const e=this.socket=new WebSocket(t);this._closed=!1,this.socket.binaryType=fe.binaryType,this.socket.onopen=()=>{this.socket===e&&("arraybuffer"==this.socket.binaryType?this.socket.onmessage=t=>{this.socket===e&&this.onWebSocketMessage(t)}:this.socket.onmessage=t=>{this.socket===e&&this.onWebSocketMessageBlob(t)},this.emit("open"))},this.socket.onerror=t=>{this.socket===e&&this.emit("error",t)},this.socket.onclose=()=>{this.socket===e&&this.emit("close")},this.stateChange("connecting","connecting")}onWebSocketMessage(t){this.rxCounter++,this.lastTxRxTime=Date.now();let e=se.from(t.data);this.rxBytes+=e.byteLength,this.emit("socket_data",e)}async onWebSocketMessageBlob(t){const e=this.socket;let r;if(this.rxCounter++,this.lastTxRxTime=Date.now(),t.data instanceof Blob){let e=await t.data.arrayBuffer();r=se.from(e)}else r=se.from(t.data);this.rxBytes+=r.byteLength,this.socket===e&&this.emit("socket_data",r)}socket_send(t){1===this.socket?.readyState?(this.socket.send(t),this.txCounter++,this.txBytes+=t.byteLength,this.lastTxRxTime=Date.now()):console.log(".")}}return fe}();
|
|
23
23
|
//# sourceMappingURL=io.js.map
|
package/dist/node/iosignal.cjs
CHANGED
|
@@ -11,12 +11,13 @@ var require$$7 = require('url');
|
|
|
11
11
|
var require$$0$1 = require('zlib');
|
|
12
12
|
var require$$0$2 = require('buffer');
|
|
13
13
|
var require$$2 = require('util');
|
|
14
|
+
var node_perf_hooks = require('node:perf_hooks');
|
|
14
15
|
var os = require('os');
|
|
15
16
|
var fs = require('fs');
|
|
16
17
|
var process$1 = require('process');
|
|
17
18
|
var path = require('path');
|
|
18
19
|
|
|
19
|
-
var version$1 = "
|
|
20
|
+
var version$1 = "7.0.0";
|
|
20
21
|
var pkg = {
|
|
21
22
|
version: version$1};
|
|
22
23
|
|
|
@@ -7371,6 +7372,13 @@ let serverOption = {
|
|
|
7371
7372
|
limitCounter: 1000
|
|
7372
7373
|
},
|
|
7373
7374
|
|
|
7375
|
+
// Applied to each new Server instance; packet layouts remain unchanged.
|
|
7376
|
+
security: {
|
|
7377
|
+
maxClockSkewMs: 60000,
|
|
7378
|
+
authChallengeMaxAgeMs: 60000,
|
|
7379
|
+
maxReplayEntries: 65536
|
|
7380
|
+
},
|
|
7381
|
+
|
|
7374
7382
|
auth: {
|
|
7375
7383
|
delay_auth_fail: 600
|
|
7376
7384
|
},
|
|
@@ -7394,6 +7402,13 @@ class RemoteCore {
|
|
|
7394
7402
|
socket.openTime = Date.now();
|
|
7395
7403
|
|
|
7396
7404
|
this.boho = new it();
|
|
7405
|
+
this.security = manager.server.security;
|
|
7406
|
+
this._challengeIssuedAt = null;
|
|
7407
|
+
this._challengeUsed = false;
|
|
7408
|
+
this._replayBuckets = new Map();
|
|
7409
|
+
this._replayEntries = 0;
|
|
7410
|
+
this._replayExpiredBefore = 0;
|
|
7411
|
+
this.securityFailure = null;
|
|
7397
7412
|
this.encMode = ENC_MODE.AUTO;
|
|
7398
7413
|
this.channels = new Set(); // subscribed tags
|
|
7399
7414
|
this.retain_signal = new Map();
|
|
@@ -7482,15 +7497,92 @@ class RemoteCore {
|
|
|
7482
7497
|
return true;
|
|
7483
7498
|
}
|
|
7484
7499
|
|
|
7500
|
+
issueAuthChallenge() {
|
|
7501
|
+
const packet = this.boho.server_time_nonce();
|
|
7502
|
+
this._challengeIssuedAt = node_perf_hooks.performance.now();
|
|
7503
|
+
return packet;
|
|
7504
|
+
}
|
|
7505
|
+
|
|
7506
|
+
securityMismatch(reason) {
|
|
7507
|
+
if (this._closing || this.state === STATE.CLOSED) return false;
|
|
7508
|
+
this.securityFailure = reason;
|
|
7509
|
+
this.boho.clearAuth();
|
|
7510
|
+
this.isAdmin = false;
|
|
7511
|
+
this._replayBuckets.clear();
|
|
7512
|
+
this._replayEntries = 0;
|
|
7513
|
+
this.close(true);
|
|
7514
|
+
this.manager.attackLogger?.log(`SECURITY #${this.ssid} reason:${reason}`);
|
|
7515
|
+
this.manager.server.emit('security:mismatch', this, reason);
|
|
7516
|
+
return false;
|
|
7517
|
+
}
|
|
7518
|
+
|
|
7519
|
+
checkAuthChallenge() {
|
|
7520
|
+
if (this._closing || this.state === STATE.CLOSED) return false;
|
|
7521
|
+
if (this._challengeUsed) return this.securityMismatch('AUTH_CHALLENGE_REUSED');
|
|
7522
|
+
if (this._challengeIssuedAt === null ||
|
|
7523
|
+
node_perf_hooks.performance.now() - this._challengeIssuedAt > this.security.authChallengeMaxAgeMs) {
|
|
7524
|
+
return this.securityMismatch('AUTH_CHALLENGE_EXPIRED');
|
|
7525
|
+
}
|
|
7526
|
+
return true;
|
|
7527
|
+
}
|
|
7528
|
+
|
|
7529
|
+
// Called only after Boho has authenticated the packet's clock and payload.
|
|
7530
|
+
acceptEncryptedClock(message, receivedAtMs) {
|
|
7531
|
+
const seconds = message.readUInt32LE(5);
|
|
7532
|
+
const milliseconds = message.readUInt16LE(9);
|
|
7533
|
+
const counter = message.readUInt16LE(11);
|
|
7534
|
+
const packetTime = seconds * 1000 + milliseconds;
|
|
7535
|
+
const earliest = receivedAtMs - this.security.maxClockSkewMs;
|
|
7536
|
+
if (milliseconds >= 1000 || Math.abs(receivedAtMs - packetTime) > this.security.maxClockSkewMs ||
|
|
7537
|
+
packetTime < this._replayExpiredBefore) {
|
|
7538
|
+
return this.securityMismatch('TIME_MISMATCH');
|
|
7539
|
+
}
|
|
7540
|
+
// Never reopen an expired timestamp range after the server clock moves back.
|
|
7541
|
+
this._replayExpiredBefore = Math.max(this._replayExpiredBefore, earliest);
|
|
7542
|
+
for (const [second, values] of this._replayBuckets) {
|
|
7543
|
+
if ((second + 1) * 1000 <= this._replayExpiredBefore) {
|
|
7544
|
+
this._replayEntries -= values.size;
|
|
7545
|
+
this._replayBuckets.delete(second);
|
|
7546
|
+
}
|
|
7547
|
+
}
|
|
7548
|
+
let bucket = this._replayBuckets.get(seconds);
|
|
7549
|
+
const value = milliseconds * 65536 + counter;
|
|
7550
|
+
if (bucket?.has(value)) return this.securityMismatch('REPLAY_DETECTED');
|
|
7551
|
+
// Fail closed instead of evicting still-valid replay evidence under load.
|
|
7552
|
+
if (this._replayEntries >= this.security.maxReplayEntries) {
|
|
7553
|
+
return this.securityMismatch('REPLAY_CAPACITY_EXCEEDED');
|
|
7554
|
+
}
|
|
7555
|
+
if (!bucket) this._replayBuckets.set(seconds, bucket = new Set());
|
|
7556
|
+
bucket.add(value);
|
|
7557
|
+
this._replayEntries++;
|
|
7558
|
+
return true;
|
|
7559
|
+
}
|
|
7560
|
+
|
|
7561
|
+
decryptSessionPacket(message, receivedAtMs) {
|
|
7562
|
+
let decoded;
|
|
7563
|
+
try {
|
|
7564
|
+
decoded = this.boho.decrypt_488(message);
|
|
7565
|
+
} catch {
|
|
7566
|
+
this.securityMismatch('INVALID_ENCRYPTED_PACKET');
|
|
7567
|
+
return;
|
|
7568
|
+
}
|
|
7569
|
+
if (!decoded) {
|
|
7570
|
+
this.securityMismatch('INVALID_ENCRYPTED_PACKET');
|
|
7571
|
+
return;
|
|
7572
|
+
}
|
|
7573
|
+
if (this.acceptEncryptedClock(message, receivedAtMs)) return decoded;
|
|
7574
|
+
}
|
|
7575
|
+
|
|
7485
7576
|
onTimeDelayMessage(message, isBinary = true) {
|
|
7577
|
+
const receivedAtMs = Date.now();
|
|
7486
7578
|
setTimeout(() => {
|
|
7487
|
-
this.onSocketMessage(message, isBinary);
|
|
7579
|
+
this.onSocketMessage(message, isBinary, receivedAtMs);
|
|
7488
7580
|
}
|
|
7489
7581
|
, serverOption.debug.delay);
|
|
7490
7582
|
}
|
|
7491
7583
|
|
|
7492
7584
|
// CongSocket or WebSocket
|
|
7493
|
-
onSocketMessage(message, isBinary = true) {
|
|
7585
|
+
onSocketMessage(message, isBinary = true, receivedAtMs = Date.now()) {
|
|
7494
7586
|
|
|
7495
7587
|
if (this._closing || this.state === STATE.CLOSED) return;
|
|
7496
7588
|
|
|
@@ -7506,12 +7598,7 @@ class RemoteCore {
|
|
|
7506
7598
|
|
|
7507
7599
|
if (msgType === it.BohoMsg.ENC_488) {
|
|
7508
7600
|
|
|
7509
|
-
|
|
7510
|
-
decoded = this.boho.decrypt_488(message);
|
|
7511
|
-
} catch (err) {
|
|
7512
|
-
console.log('-- E488 DEC_FAIL', err);
|
|
7513
|
-
return
|
|
7514
|
-
}
|
|
7601
|
+
decoded = this.decryptSessionPacket(message, receivedAtMs);
|
|
7515
7602
|
|
|
7516
7603
|
if (decoded) {
|
|
7517
7604
|
msgType = decoded[0];
|
|
@@ -7521,12 +7608,7 @@ class RemoteCore {
|
|
|
7521
7608
|
}
|
|
7522
7609
|
|
|
7523
7610
|
} else if (msgType === it.BohoMsg.ENC_E2E) { // symetric E2EE Signal
|
|
7524
|
-
|
|
7525
|
-
decoded = this.boho.decrypt_488(message);
|
|
7526
|
-
} catch (err) {
|
|
7527
|
-
// console.log('-- E2E DEC_FAIL', err)
|
|
7528
|
-
return
|
|
7529
|
-
}
|
|
7611
|
+
decoded = this.decryptSessionPacket(message, receivedAtMs);
|
|
7530
7612
|
// console.log('e2e unpack:', decoded )
|
|
7531
7613
|
if (decoded) {
|
|
7532
7614
|
msgType = decoded[0];
|
|
@@ -7671,13 +7753,17 @@ class RemoteCore {
|
|
|
7671
7753
|
// client's auth requst
|
|
7672
7754
|
case it.BohoMsg.AUTH_REQ:
|
|
7673
7755
|
if (!this.manager.authManager) return
|
|
7674
|
-
//
|
|
7675
|
-
if (this.state === STATE.AUTH_REQ)
|
|
7756
|
+
// A second request while verification is pending must not restart auth.
|
|
7757
|
+
if (this.state === STATE.AUTH_REQ) {
|
|
7758
|
+
this.securityMismatch('AUTH_IN_PROGRESS');
|
|
7759
|
+
return;
|
|
7760
|
+
}
|
|
7676
7761
|
if (![STATE.SERVER_READY, STATE.AUTH_RES, STATE.AUTH_FAIL, STATE.CID_RES].includes(this.state)) {
|
|
7677
7762
|
console.log('protocol error. must called auth_req after server_ready');
|
|
7678
7763
|
this.close();
|
|
7679
7764
|
return;
|
|
7680
7765
|
}
|
|
7766
|
+
if (!this.checkAuthChallenge()) return;
|
|
7681
7767
|
this.setState(STATE.AUTH_REQ);
|
|
7682
7768
|
//async
|
|
7683
7769
|
this.manager.authManager.verify_auth_req(message, this)
|
|
@@ -8319,7 +8405,7 @@ class Manager {
|
|
|
8319
8405
|
socket.isAlive = true;
|
|
8320
8406
|
let remote = new Remote(socket, req, this);
|
|
8321
8407
|
this.remotes.add(remote);
|
|
8322
|
-
remote.send(
|
|
8408
|
+
remote.send(remote.issueAuthChallenge());
|
|
8323
8409
|
remote.send( Buffer.from([ IOMsg.SERVER_READY]) );
|
|
8324
8410
|
remote.setState(STATE.SERVER_READY);
|
|
8325
8411
|
this.lastSSID = remote.ssid;
|
|
@@ -8701,6 +8787,13 @@ class Server extends require$$0$3 {
|
|
|
8701
8787
|
|
|
8702
8788
|
constructor(options, authManager) {
|
|
8703
8789
|
super();
|
|
8790
|
+
const security = { ...serverOption.security, ...options.security };
|
|
8791
|
+
for (const name of ['maxClockSkewMs', 'authChallengeMaxAgeMs', 'maxReplayEntries']) {
|
|
8792
|
+
if (!Number.isSafeInteger(security[name]) || security[name] <= 0) {
|
|
8793
|
+
throw new RangeError(`security.${name} must be a positive safe integer`);
|
|
8794
|
+
}
|
|
8795
|
+
}
|
|
8796
|
+
this.security = Object.freeze(security);
|
|
8704
8797
|
this.serviceNames = new Set();
|
|
8705
8798
|
this.wss = {};
|
|
8706
8799
|
this.port = null;
|
|
@@ -8962,6 +9055,12 @@ class BohoAuth {
|
|
|
8962
9055
|
|
|
8963
9056
|
async verify_auth_req(auth_req, peer) {
|
|
8964
9057
|
try {
|
|
9058
|
+
if (!peer.checkAuthChallenge()) return;
|
|
9059
|
+
if (!(auth_req instanceof Uint8Array) || auth_req.length !== it.MetaSize.AUTH_REQ ||
|
|
9060
|
+
auth_req[0] !== it.BohoMsg.AUTH_REQ) {
|
|
9061
|
+
peer.securityMismatch('INVALID_AUTH_PACKET');
|
|
9062
|
+
return;
|
|
9063
|
+
}
|
|
8965
9064
|
//1. unpack
|
|
8966
9065
|
let infoPack = $$1.unpack(auth_req, it.Meta.AUTH_REQ);
|
|
8967
9066
|
if (!infoPack) {
|
|
@@ -8978,7 +9077,7 @@ class BohoAuth {
|
|
|
8978
9077
|
|
|
8979
9078
|
//2. get key of id from DB
|
|
8980
9079
|
let authInfo = await this.keyProvider.getAuth(id);
|
|
8981
|
-
if (peer.
|
|
9080
|
+
if (!peer.checkAuthChallenge()) return;
|
|
8982
9081
|
if (!authInfo) {
|
|
8983
9082
|
this.send_auth_fail(peer, 'NO ID:' + id);
|
|
8984
9083
|
return
|
|
@@ -9008,6 +9107,10 @@ class BohoAuth {
|
|
|
9008
9107
|
return
|
|
9009
9108
|
}
|
|
9010
9109
|
|
|
9110
|
+
// A valid proof consumes this challenge even if account policy rejects it.
|
|
9111
|
+
// Reauthentication requires a new connection, never a replay-state reset.
|
|
9112
|
+
peer._challengeUsed = true;
|
|
9113
|
+
|
|
9011
9114
|
//4. get info
|
|
9012
9115
|
|
|
9013
9116
|
//5. check duplicate login.
|
package/dist/node/iosignal.js
CHANGED
|
@@ -9,12 +9,13 @@ import require$$7 from 'url';
|
|
|
9
9
|
import require$$0 from 'zlib';
|
|
10
10
|
import require$$0$1 from 'buffer';
|
|
11
11
|
import require$$2 from 'util';
|
|
12
|
+
import { performance } from 'node:perf_hooks';
|
|
12
13
|
import { networkInterfaces } from 'os';
|
|
13
14
|
import fs, { readFileSync } from 'fs';
|
|
14
15
|
import { memoryUsage } from 'process';
|
|
15
16
|
import path from 'path';
|
|
16
17
|
|
|
17
|
-
var version$1 = "
|
|
18
|
+
var version$1 = "7.0.0";
|
|
18
19
|
var pkg = {
|
|
19
20
|
version: version$1};
|
|
20
21
|
|
|
@@ -7369,6 +7370,13 @@ let serverOption = {
|
|
|
7369
7370
|
limitCounter: 1000
|
|
7370
7371
|
},
|
|
7371
7372
|
|
|
7373
|
+
// Applied to each new Server instance; packet layouts remain unchanged.
|
|
7374
|
+
security: {
|
|
7375
|
+
maxClockSkewMs: 60000,
|
|
7376
|
+
authChallengeMaxAgeMs: 60000,
|
|
7377
|
+
maxReplayEntries: 65536
|
|
7378
|
+
},
|
|
7379
|
+
|
|
7372
7380
|
auth: {
|
|
7373
7381
|
delay_auth_fail: 600
|
|
7374
7382
|
},
|
|
@@ -7392,6 +7400,13 @@ class RemoteCore {
|
|
|
7392
7400
|
socket.openTime = Date.now();
|
|
7393
7401
|
|
|
7394
7402
|
this.boho = new it();
|
|
7403
|
+
this.security = manager.server.security;
|
|
7404
|
+
this._challengeIssuedAt = null;
|
|
7405
|
+
this._challengeUsed = false;
|
|
7406
|
+
this._replayBuckets = new Map();
|
|
7407
|
+
this._replayEntries = 0;
|
|
7408
|
+
this._replayExpiredBefore = 0;
|
|
7409
|
+
this.securityFailure = null;
|
|
7395
7410
|
this.encMode = ENC_MODE.AUTO;
|
|
7396
7411
|
this.channels = new Set(); // subscribed tags
|
|
7397
7412
|
this.retain_signal = new Map();
|
|
@@ -7480,15 +7495,92 @@ class RemoteCore {
|
|
|
7480
7495
|
return true;
|
|
7481
7496
|
}
|
|
7482
7497
|
|
|
7498
|
+
issueAuthChallenge() {
|
|
7499
|
+
const packet = this.boho.server_time_nonce();
|
|
7500
|
+
this._challengeIssuedAt = performance.now();
|
|
7501
|
+
return packet;
|
|
7502
|
+
}
|
|
7503
|
+
|
|
7504
|
+
securityMismatch(reason) {
|
|
7505
|
+
if (this._closing || this.state === STATE.CLOSED) return false;
|
|
7506
|
+
this.securityFailure = reason;
|
|
7507
|
+
this.boho.clearAuth();
|
|
7508
|
+
this.isAdmin = false;
|
|
7509
|
+
this._replayBuckets.clear();
|
|
7510
|
+
this._replayEntries = 0;
|
|
7511
|
+
this.close(true);
|
|
7512
|
+
this.manager.attackLogger?.log(`SECURITY #${this.ssid} reason:${reason}`);
|
|
7513
|
+
this.manager.server.emit('security:mismatch', this, reason);
|
|
7514
|
+
return false;
|
|
7515
|
+
}
|
|
7516
|
+
|
|
7517
|
+
checkAuthChallenge() {
|
|
7518
|
+
if (this._closing || this.state === STATE.CLOSED) return false;
|
|
7519
|
+
if (this._challengeUsed) return this.securityMismatch('AUTH_CHALLENGE_REUSED');
|
|
7520
|
+
if (this._challengeIssuedAt === null ||
|
|
7521
|
+
performance.now() - this._challengeIssuedAt > this.security.authChallengeMaxAgeMs) {
|
|
7522
|
+
return this.securityMismatch('AUTH_CHALLENGE_EXPIRED');
|
|
7523
|
+
}
|
|
7524
|
+
return true;
|
|
7525
|
+
}
|
|
7526
|
+
|
|
7527
|
+
// Called only after Boho has authenticated the packet's clock and payload.
|
|
7528
|
+
acceptEncryptedClock(message, receivedAtMs) {
|
|
7529
|
+
const seconds = message.readUInt32LE(5);
|
|
7530
|
+
const milliseconds = message.readUInt16LE(9);
|
|
7531
|
+
const counter = message.readUInt16LE(11);
|
|
7532
|
+
const packetTime = seconds * 1000 + milliseconds;
|
|
7533
|
+
const earliest = receivedAtMs - this.security.maxClockSkewMs;
|
|
7534
|
+
if (milliseconds >= 1000 || Math.abs(receivedAtMs - packetTime) > this.security.maxClockSkewMs ||
|
|
7535
|
+
packetTime < this._replayExpiredBefore) {
|
|
7536
|
+
return this.securityMismatch('TIME_MISMATCH');
|
|
7537
|
+
}
|
|
7538
|
+
// Never reopen an expired timestamp range after the server clock moves back.
|
|
7539
|
+
this._replayExpiredBefore = Math.max(this._replayExpiredBefore, earliest);
|
|
7540
|
+
for (const [second, values] of this._replayBuckets) {
|
|
7541
|
+
if ((second + 1) * 1000 <= this._replayExpiredBefore) {
|
|
7542
|
+
this._replayEntries -= values.size;
|
|
7543
|
+
this._replayBuckets.delete(second);
|
|
7544
|
+
}
|
|
7545
|
+
}
|
|
7546
|
+
let bucket = this._replayBuckets.get(seconds);
|
|
7547
|
+
const value = milliseconds * 65536 + counter;
|
|
7548
|
+
if (bucket?.has(value)) return this.securityMismatch('REPLAY_DETECTED');
|
|
7549
|
+
// Fail closed instead of evicting still-valid replay evidence under load.
|
|
7550
|
+
if (this._replayEntries >= this.security.maxReplayEntries) {
|
|
7551
|
+
return this.securityMismatch('REPLAY_CAPACITY_EXCEEDED');
|
|
7552
|
+
}
|
|
7553
|
+
if (!bucket) this._replayBuckets.set(seconds, bucket = new Set());
|
|
7554
|
+
bucket.add(value);
|
|
7555
|
+
this._replayEntries++;
|
|
7556
|
+
return true;
|
|
7557
|
+
}
|
|
7558
|
+
|
|
7559
|
+
decryptSessionPacket(message, receivedAtMs) {
|
|
7560
|
+
let decoded;
|
|
7561
|
+
try {
|
|
7562
|
+
decoded = this.boho.decrypt_488(message);
|
|
7563
|
+
} catch {
|
|
7564
|
+
this.securityMismatch('INVALID_ENCRYPTED_PACKET');
|
|
7565
|
+
return;
|
|
7566
|
+
}
|
|
7567
|
+
if (!decoded) {
|
|
7568
|
+
this.securityMismatch('INVALID_ENCRYPTED_PACKET');
|
|
7569
|
+
return;
|
|
7570
|
+
}
|
|
7571
|
+
if (this.acceptEncryptedClock(message, receivedAtMs)) return decoded;
|
|
7572
|
+
}
|
|
7573
|
+
|
|
7483
7574
|
onTimeDelayMessage(message, isBinary = true) {
|
|
7575
|
+
const receivedAtMs = Date.now();
|
|
7484
7576
|
setTimeout(() => {
|
|
7485
|
-
this.onSocketMessage(message, isBinary);
|
|
7577
|
+
this.onSocketMessage(message, isBinary, receivedAtMs);
|
|
7486
7578
|
}
|
|
7487
7579
|
, serverOption.debug.delay);
|
|
7488
7580
|
}
|
|
7489
7581
|
|
|
7490
7582
|
// CongSocket or WebSocket
|
|
7491
|
-
onSocketMessage(message, isBinary = true) {
|
|
7583
|
+
onSocketMessage(message, isBinary = true, receivedAtMs = Date.now()) {
|
|
7492
7584
|
|
|
7493
7585
|
if (this._closing || this.state === STATE.CLOSED) return;
|
|
7494
7586
|
|
|
@@ -7504,12 +7596,7 @@ class RemoteCore {
|
|
|
7504
7596
|
|
|
7505
7597
|
if (msgType === it.BohoMsg.ENC_488) {
|
|
7506
7598
|
|
|
7507
|
-
|
|
7508
|
-
decoded = this.boho.decrypt_488(message);
|
|
7509
|
-
} catch (err) {
|
|
7510
|
-
console.log('-- E488 DEC_FAIL', err);
|
|
7511
|
-
return
|
|
7512
|
-
}
|
|
7599
|
+
decoded = this.decryptSessionPacket(message, receivedAtMs);
|
|
7513
7600
|
|
|
7514
7601
|
if (decoded) {
|
|
7515
7602
|
msgType = decoded[0];
|
|
@@ -7519,12 +7606,7 @@ class RemoteCore {
|
|
|
7519
7606
|
}
|
|
7520
7607
|
|
|
7521
7608
|
} else if (msgType === it.BohoMsg.ENC_E2E) { // symetric E2EE Signal
|
|
7522
|
-
|
|
7523
|
-
decoded = this.boho.decrypt_488(message);
|
|
7524
|
-
} catch (err) {
|
|
7525
|
-
// console.log('-- E2E DEC_FAIL', err)
|
|
7526
|
-
return
|
|
7527
|
-
}
|
|
7609
|
+
decoded = this.decryptSessionPacket(message, receivedAtMs);
|
|
7528
7610
|
// console.log('e2e unpack:', decoded )
|
|
7529
7611
|
if (decoded) {
|
|
7530
7612
|
msgType = decoded[0];
|
|
@@ -7669,13 +7751,17 @@ class RemoteCore {
|
|
|
7669
7751
|
// client's auth requst
|
|
7670
7752
|
case it.BohoMsg.AUTH_REQ:
|
|
7671
7753
|
if (!this.manager.authManager) return
|
|
7672
|
-
//
|
|
7673
|
-
if (this.state === STATE.AUTH_REQ)
|
|
7754
|
+
// A second request while verification is pending must not restart auth.
|
|
7755
|
+
if (this.state === STATE.AUTH_REQ) {
|
|
7756
|
+
this.securityMismatch('AUTH_IN_PROGRESS');
|
|
7757
|
+
return;
|
|
7758
|
+
}
|
|
7674
7759
|
if (![STATE.SERVER_READY, STATE.AUTH_RES, STATE.AUTH_FAIL, STATE.CID_RES].includes(this.state)) {
|
|
7675
7760
|
console.log('protocol error. must called auth_req after server_ready');
|
|
7676
7761
|
this.close();
|
|
7677
7762
|
return;
|
|
7678
7763
|
}
|
|
7764
|
+
if (!this.checkAuthChallenge()) return;
|
|
7679
7765
|
this.setState(STATE.AUTH_REQ);
|
|
7680
7766
|
//async
|
|
7681
7767
|
this.manager.authManager.verify_auth_req(message, this)
|
|
@@ -8317,7 +8403,7 @@ class Manager {
|
|
|
8317
8403
|
socket.isAlive = true;
|
|
8318
8404
|
let remote = new Remote(socket, req, this);
|
|
8319
8405
|
this.remotes.add(remote);
|
|
8320
|
-
remote.send(
|
|
8406
|
+
remote.send(remote.issueAuthChallenge());
|
|
8321
8407
|
remote.send( Buffer.from([ IOMsg.SERVER_READY]) );
|
|
8322
8408
|
remote.setState(STATE.SERVER_READY);
|
|
8323
8409
|
this.lastSSID = remote.ssid;
|
|
@@ -8699,6 +8785,13 @@ class Server extends require$$0$3 {
|
|
|
8699
8785
|
|
|
8700
8786
|
constructor(options, authManager) {
|
|
8701
8787
|
super();
|
|
8788
|
+
const security = { ...serverOption.security, ...options.security };
|
|
8789
|
+
for (const name of ['maxClockSkewMs', 'authChallengeMaxAgeMs', 'maxReplayEntries']) {
|
|
8790
|
+
if (!Number.isSafeInteger(security[name]) || security[name] <= 0) {
|
|
8791
|
+
throw new RangeError(`security.${name} must be a positive safe integer`);
|
|
8792
|
+
}
|
|
8793
|
+
}
|
|
8794
|
+
this.security = Object.freeze(security);
|
|
8702
8795
|
this.serviceNames = new Set();
|
|
8703
8796
|
this.wss = {};
|
|
8704
8797
|
this.port = null;
|
|
@@ -8960,6 +9053,12 @@ class BohoAuth {
|
|
|
8960
9053
|
|
|
8961
9054
|
async verify_auth_req(auth_req, peer) {
|
|
8962
9055
|
try {
|
|
9056
|
+
if (!peer.checkAuthChallenge()) return;
|
|
9057
|
+
if (!(auth_req instanceof Uint8Array) || auth_req.length !== it.MetaSize.AUTH_REQ ||
|
|
9058
|
+
auth_req[0] !== it.BohoMsg.AUTH_REQ) {
|
|
9059
|
+
peer.securityMismatch('INVALID_AUTH_PACKET');
|
|
9060
|
+
return;
|
|
9061
|
+
}
|
|
8963
9062
|
//1. unpack
|
|
8964
9063
|
let infoPack = $$1.unpack(auth_req, it.Meta.AUTH_REQ);
|
|
8965
9064
|
if (!infoPack) {
|
|
@@ -8976,7 +9075,7 @@ class BohoAuth {
|
|
|
8976
9075
|
|
|
8977
9076
|
//2. get key of id from DB
|
|
8978
9077
|
let authInfo = await this.keyProvider.getAuth(id);
|
|
8979
|
-
if (peer.
|
|
9078
|
+
if (!peer.checkAuthChallenge()) return;
|
|
8980
9079
|
if (!authInfo) {
|
|
8981
9080
|
this.send_auth_fail(peer, 'NO ID:' + id);
|
|
8982
9081
|
return
|
|
@@ -9006,6 +9105,10 @@ class BohoAuth {
|
|
|
9006
9105
|
return
|
|
9007
9106
|
}
|
|
9008
9107
|
|
|
9108
|
+
// A valid proof consumes this challenge even if account policy rejects it.
|
|
9109
|
+
// Reauthentication requires a new connection, never a replay-state reset.
|
|
9110
|
+
peer._challengeUsed = true;
|
|
9111
|
+
|
|
9009
9112
|
//4. get info
|
|
9010
9113
|
|
|
9011
9114
|
//5. check duplicate login.
|