@onekeyfe/react-native-sni-connect 6.8.0-alpha.514 → 6.8.0-alpha.539

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.
@@ -0,0 +1,2059 @@
1
+ import * as fs from 'fs';
2
+ import * as fsPromises from 'fs/promises';
3
+ import type { ClientRequest } from 'http';
4
+ import https, { type RequestOptions } from 'https';
5
+ import * as nodePath from 'path';
6
+ import { fileURLToPath } from 'url';
7
+
8
+ const MAX_REQUEST_ID_BYTES = 128;
9
+ const MAX_TIMEOUT_MS = 120_000;
10
+ const MAX_PATH_BYTES = 8 * 1024;
11
+ const MAX_REQUEST_BODY_BYTES = 1024 * 1024;
12
+ const MAX_UPLOAD_FILE_BYTES = 20 * 1024 * 1024;
13
+ const MAX_OPEN_UPLOAD_FILES = 64;
14
+ const MAX_RESPONSE_BODY_BYTES = 10 * 1024 * 1024;
15
+ const MAX_HEADER_COUNT = 64;
16
+ const MAX_HEADER_NAME_BYTES = 128;
17
+ const MAX_HEADER_VALUE_BYTES = 8 * 1024;
18
+ const MAX_TOTAL_HEADER_BYTES = 32 * 1024;
19
+ const MAX_TOTAL_SOCKETS = 64;
20
+ const MAX_SOCKETS_PER_PAIR = 16;
21
+ const MAX_FREE_SOCKETS = 32;
22
+ const MAX_ACTIVE_REQUESTS = 64;
23
+ const MAX_ACTIVE_REQUESTS_PER_PAIR = 16;
24
+ const MAX_PENDING_REQUESTS = 256;
25
+ const MAX_DIAGNOSTIC_TEXT_LENGTH = 120;
26
+
27
+ const UPLOAD_FILE_METHODS = new Set(['POST', 'PUT']);
28
+ export const DEFAULT_LOGGER_UPLOAD_PATH = '/wallet/v1/client/log';
29
+ export const DEFAULT_LOGGER_UPLOAD_ORIGINS = new Set([
30
+ 'https://wallet.onekeycn.com',
31
+ 'https://wallet.onekeytest.com',
32
+ ]);
33
+
34
+ const ALLOWED_METHODS = new Set([
35
+ 'GET',
36
+ 'POST',
37
+ 'PUT',
38
+ 'PATCH',
39
+ 'DELETE',
40
+ 'HEAD',
41
+ 'OPTIONS',
42
+ ]);
43
+
44
+ const MODULE_OWNED_HEADERS = new Set([
45
+ 'host',
46
+ 'content-length',
47
+ 'accept-encoding',
48
+ 'x-emascurl-config-id',
49
+ ]);
50
+
51
+ const UNSAFE_HEADERS = new Set([
52
+ 'connection',
53
+ 'keep-alive',
54
+ 'te',
55
+ 'trailer',
56
+ 'transfer-encoding',
57
+ 'upgrade',
58
+ 'expect',
59
+ ]);
60
+
61
+ const HOSTNAME_RE =
62
+ /^(?=.{1,253}$)([A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;
63
+ const SCHEME_RE = /^[A-Za-z][A-Za-z0-9+.-]*:/;
64
+ const HEADER_TOKEN_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
65
+ const IPV4_DOTTED_RE = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
66
+ const HEX_GROUP_RE = /^[0-9A-Fa-f]{1,4}$/;
67
+
68
+ const IPV4_LOG_RE =
69
+ /(^|[^\d.])((?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3})(?=$|[^\d.])/g;
70
+ const IPV4_LITERAL_LOG_RE =
71
+ /^(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
72
+ // An IPv6 literal with an embedded IPv4 address is at most 45 characters.
73
+ // Bound both scans before validating candidate addresses for log redaction.
74
+ const BRACKETED_IPV6_LOG_RE =
75
+ /\[([0-9A-Fa-f:.]{1,45})\](?=$|:\d{1,5}\b|[^0-9A-Fa-f:.\]])/g;
76
+ const IPV6_CANDIDATE_LOG_RE =
77
+ /(^|[^0-9A-Fa-f:.[])(\[?[0-9A-Fa-f:.]{1,45}\]?)(?=$|[^0-9A-Fa-f:.\]])/g;
78
+
79
+ const SNI_FAIL_CLOSED_ERROR_CODES = new Set([
80
+ 'SNI_INVALID_CONFIG',
81
+ 'SNI_SECURITY_POLICY_FAILED',
82
+ 'SNI_TLS_FAILED',
83
+ 'SNI_CERT_FAILED',
84
+ 'SNI_RESPONSE_FAILED',
85
+ 'SNI_RESOURCE_LIMIT',
86
+ 'SNI_CANCELLED',
87
+ ]);
88
+
89
+ const SNI_FAIL_CLOSED_MESSAGE_RE =
90
+ /\bSNI_(INVALID_CONFIG|SECURITY_POLICY_FAILED|TLS_FAILED|CERT_FAILED|RESPONSE_FAILED|RESOURCE_LIMIT|CANCELLED)\b/;
91
+
92
+ export interface SniNodeRequestConfig {
93
+ requestId?: string;
94
+ ip: string;
95
+ hostname: string;
96
+ path: string;
97
+ headers: Record<string, string>;
98
+ method: string;
99
+ body: string | null;
100
+ timeout: number;
101
+ port?: number | null;
102
+ }
103
+
104
+ export interface SniNodeUploadFileConfig {
105
+ requestId?: string;
106
+ ip: string;
107
+ hostname: string;
108
+ path: string;
109
+ headers: Record<string, string>;
110
+ method: 'POST' | 'PUT';
111
+ filePath: string;
112
+ timeout: number;
113
+ }
114
+
115
+ export interface SniNodeResponse {
116
+ data: string;
117
+ status: number;
118
+ statusText: string;
119
+ statusCode: number;
120
+ headers: Record<string, string>;
121
+ multiValueHeaders?: Record<string, string[]>;
122
+ body: string;
123
+ }
124
+
125
+ export interface SniNodeDebugSnapshot {
126
+ activeRequests: number;
127
+ activeRequestsForPair: number;
128
+ pendingRequests: number;
129
+ pendingRequestsForPair: number;
130
+ }
131
+
132
+ export interface SniNodeLogSink {
133
+ info?: (message: string) => void;
134
+ warn?: (message: string) => void;
135
+ error?: (message: string) => void;
136
+ }
137
+
138
+ export interface SniNodeUploadProgress {
139
+ bytesSent: number;
140
+ totalBytes: number;
141
+ }
142
+
143
+ export interface SniNodeUploadProgressEvent extends SniNodeUploadProgress {
144
+ requestId: string;
145
+ progressPercent: number;
146
+ }
147
+
148
+ export interface SniNodeUploadValidationOptions {
149
+ allowedUploadOrigins?: ReadonlySet<string> | readonly string[];
150
+ allowedUploadPath?: string | null;
151
+ requiredFileExtension?: string | null;
152
+ requireDirectChildOfRoot?: boolean;
153
+ getAllowedUploadRoots?: () => Promise<readonly string[]> | readonly string[];
154
+ verifyUploadFile?: (
155
+ realPath: string,
156
+ sizeBytes: number
157
+ ) => Promise<boolean> | boolean;
158
+ }
159
+
160
+ export interface SniNodeClientOptions extends SniNodeUploadValidationOptions {
161
+ logger?: SniNodeLogSink;
162
+ logPrefix?: string;
163
+ resolveProxy?: (url: string) => Promise<string>;
164
+ onUploadProgress?: (event: SniNodeUploadProgressEvent) => void;
165
+ }
166
+
167
+ export type NormalizedSniRequestConfig = Omit<
168
+ SniNodeRequestConfig,
169
+ 'body' | 'headers' | 'method' | 'path' | 'port'
170
+ > & {
171
+ body: string | null;
172
+ // Set only by uploadFile(); the file is streamed instead of `body`.
173
+ bodyFile?: { filePath: string; sizeBytes: number };
174
+ headers: Record<string, string>;
175
+ method: string;
176
+ path: string;
177
+ };
178
+
179
+ export type SniAgentState = {
180
+ agent: https.Agent;
181
+ activeRequests: Set<ClientRequest>;
182
+ destroyed: boolean;
183
+ };
184
+
185
+ type SniRequestLimiterWaiter = {
186
+ key: string;
187
+ signal: AbortSignal | undefined;
188
+ abortListener: (() => void) | undefined;
189
+ resolve: (release: () => void) => void;
190
+ };
191
+
192
+ type SniRequestState = {
193
+ requestId: string | undefined;
194
+ settled: boolean;
195
+ uploadProgress: SniNodeUploadProgress | undefined;
196
+ signal: AbortSignal;
197
+ checkDeadline: () => void;
198
+ clearDeadline: () => void;
199
+ cancel: (error: SniRequestError) => void;
200
+ };
201
+
202
+ const SniRequestErrorClass = class SniRequestError extends Error {
203
+ code: string;
204
+ failClosed: boolean;
205
+
206
+ constructor(code: string, message: string, failClosed = false) {
207
+ super(`${code}: ${message}`);
208
+ this.name = 'SniRequestError';
209
+ this.code = code;
210
+ this.failClosed = failClosed;
211
+ }
212
+ };
213
+
214
+ const requestErrorKey = Symbol.for(
215
+ '@onekeyfe/react-native-sni-connect.requestError'
216
+ );
217
+ const processWithSniError = process as typeof process & {
218
+ [requestErrorKey]?: typeof SniRequestErrorClass;
219
+ };
220
+
221
+ // Admission is process-shared, and either Node entry can consume its errors.
222
+ export const SniRequestError = (processWithSniError[requestErrorKey] ??=
223
+ SniRequestErrorClass);
224
+ export type SniRequestError = InstanceType<typeof SniRequestErrorClass>;
225
+
226
+ export function isSniFailClosedError(error: unknown): boolean {
227
+ const code =
228
+ error && typeof error === 'object' && 'code' in error
229
+ ? String((error as { code?: unknown }).code)
230
+ : '';
231
+ if (SNI_FAIL_CLOSED_ERROR_CODES.has(code)) {
232
+ return true;
233
+ }
234
+
235
+ const message = error instanceof Error ? error.message : String(error);
236
+ return SNI_FAIL_CLOSED_MESSAGE_RE.test(message);
237
+ }
238
+
239
+ function isLikelyIpv6Literal(candidate: string): boolean {
240
+ const value =
241
+ candidate.startsWith('[') && candidate.endsWith(']')
242
+ ? candidate.slice(1, -1)
243
+ : candidate;
244
+ if (!value.includes(':')) return false;
245
+ const parts = value.split(':');
246
+ const doubleColonCount = value.split('::').length - 1;
247
+
248
+ if (
249
+ doubleColonCount > 1 ||
250
+ value.includes(':::') ||
251
+ !/^[0-9A-Fa-f:.]+$/.test(value)
252
+ ) {
253
+ return false;
254
+ }
255
+
256
+ const hasDoubleColon = value.includes('::');
257
+ const hasEmbeddedIpv4 = value.includes('.');
258
+ const groupCount = parts.reduce((count, part, index) => {
259
+ if (part === '') return count;
260
+ if (part.includes('.')) {
261
+ return index === parts.length - 1 && IPV4_LITERAL_LOG_RE.test(part)
262
+ ? count + 2
263
+ : Number.POSITIVE_INFINITY;
264
+ }
265
+ return HEX_GROUP_RE.test(part) ? count + 1 : Number.POSITIVE_INFINITY;
266
+ }, 0);
267
+
268
+ if (!Number.isFinite(groupCount)) return false;
269
+ const lastPart = parts[parts.length - 1] ?? '';
270
+ if (hasEmbeddedIpv4 && !IPV4_LITERAL_LOG_RE.test(lastPart)) {
271
+ return false;
272
+ }
273
+ return hasDoubleColon ? groupCount < 8 : groupCount === 8;
274
+ }
275
+
276
+ export function redactIpLiterals(value: string): string {
277
+ return value
278
+ .replace(BRACKETED_IPV6_LOG_RE, (match, candidate: string) =>
279
+ isLikelyIpv6Literal(candidate) ? '<ip6>' : match
280
+ )
281
+ .replace(
282
+ IPV6_CANDIDATE_LOG_RE,
283
+ (_match, prefix: string, candidate: string) =>
284
+ isLikelyIpv6Literal(candidate)
285
+ ? `${prefix}<ip6>`
286
+ : `${prefix}${candidate}`
287
+ )
288
+ .replace(IPV4_LOG_RE, '$1<ip>');
289
+ }
290
+
291
+ export function sanitizeSniDiagnosticText(
292
+ value: string,
293
+ maxLength = MAX_DIAGNOSTIC_TEXT_LENGTH
294
+ ): string {
295
+ // eslint-disable-next-line no-control-regex
296
+ const singleLine = value.replace(/[\u0000-\u001f\u007f]+/g, ' ').trim();
297
+ const redacted = redactIpLiterals(singleLine);
298
+ return redacted.length > maxLength ? redacted.slice(0, maxLength) : redacted;
299
+ }
300
+
301
+ export function safeSniLogValue(value: unknown): string {
302
+ if (value === null || value === undefined) return 'none';
303
+ return redactIpLiterals(String(value)).replace(/[\r\n\s]+/g, '_');
304
+ }
305
+
306
+ export function formatNativeLogEvent(
307
+ event: string,
308
+ fields: Record<string, unknown>
309
+ ): string {
310
+ return Object.entries({ event, ...fields })
311
+ .map(([key, value]) => {
312
+ const logValue =
313
+ key === 'requestId' || key === 'ip' || key === 'requestedHost'
314
+ ? String(value ?? 'none').replace(/[\r\n\s]+/g, '_')
315
+ : safeSniLogValue(value);
316
+ // Keep long diagnostic IDs recoverable without matching the logger's private-key filter.
317
+ let displayedValue = logValue;
318
+ let formatSuffix = '';
319
+ if (
320
+ key === 'requestId' &&
321
+ typeof value === 'string' &&
322
+ (value !== logValue || /[0-9a-fA-F]{64}/.test(value))
323
+ ) {
324
+ displayedValue = encodeURIComponent(
325
+ Buffer.from(value, 'utf8').toString('utf8')
326
+ )
327
+ .replace(
328
+ /[!'()*~-]/g,
329
+ (character) =>
330
+ `%${character.charCodeAt(0).toString(16).toUpperCase()}`
331
+ )
332
+ .replace(/([0-9a-fA-F]{32})(?=[0-9a-fA-F]{32})/g, '$1-');
333
+ formatSuffix = ' requestIdFormat=uri-hex32';
334
+ }
335
+ return `${key}=${displayedValue}${formatSuffix}`;
336
+ })
337
+ .join(' ');
338
+ }
339
+
340
+ function emitNativeLog(
341
+ logger: SniNodeLogSink | undefined,
342
+ logPrefix: string,
343
+ level: 'info' | 'warn' | 'error',
344
+ event: string,
345
+ fields: Record<string, unknown>
346
+ ): void {
347
+ if (!logger) return;
348
+ const message = `${logPrefix} ${formatNativeLogEvent(event, fields)}`;
349
+ if (level === 'error') {
350
+ logger.error?.(message);
351
+ } else if (level === 'warn') {
352
+ logger.warn?.(message);
353
+ } else {
354
+ logger.info?.(message);
355
+ }
356
+ }
357
+
358
+ function getErrorCode(error: unknown): string | undefined {
359
+ if (error && typeof error === 'object' && 'code' in error) {
360
+ const code = (error as { code?: unknown }).code;
361
+ if (typeof code === 'string') return code;
362
+ }
363
+ return undefined;
364
+ }
365
+
366
+ function getErrorMessage(error: unknown): string {
367
+ return error instanceof Error ? error.message : String(error);
368
+ }
369
+
370
+ function getIpFamily(ip: string): string {
371
+ return ip.includes(':') ? 'ipv6' : 'ipv4';
372
+ }
373
+
374
+ /* eslint-disable no-bitwise */
375
+ function parseIpv4Octets(ip: string): [number, number, number, number] | null {
376
+ const match = IPV4_DOTTED_RE.exec(ip);
377
+ if (!match) return null;
378
+ const rawOctets = [match[1], match[2], match[3], match[4]];
379
+ const octets: number[] = [];
380
+ for (const part of rawOctets) {
381
+ if (!part || (part.length > 1 && part.startsWith('0'))) {
382
+ return null;
383
+ }
384
+ const value = Number(part);
385
+ if (!Number.isInteger(value) || value < 0 || value > 255) {
386
+ return null;
387
+ }
388
+ octets.push(value);
389
+ }
390
+ return [octets[0] ?? 0, octets[1] ?? 0, octets[2] ?? 0, octets[3] ?? 0];
391
+ }
392
+
393
+ function parseHexGroups(groups: readonly string[]): number[] | null {
394
+ const result: number[] = [];
395
+ for (const group of groups) {
396
+ if (!HEX_GROUP_RE.test(group)) {
397
+ return null;
398
+ }
399
+ result.push(parseInt(group, 16));
400
+ }
401
+ return result;
402
+ }
403
+
404
+ function parseIpv6Parts(ip: string): number[] | null {
405
+ if (
406
+ !ip ||
407
+ !ip.includes(':') ||
408
+ ip.includes('[') ||
409
+ ip.includes(']') ||
410
+ ip.includes('%') ||
411
+ ip.trim() !== ip
412
+ ) {
413
+ return null;
414
+ }
415
+
416
+ let normalizedIp = ip;
417
+ if (normalizedIp.includes('.')) {
418
+ const lastColon = normalizedIp.lastIndexOf(':');
419
+ if (lastColon < 0) return null;
420
+ const ipv4Octets = parseIpv4Octets(normalizedIp.slice(lastColon + 1));
421
+ if (!ipv4Octets) return null;
422
+ const high = ((ipv4Octets[0] << 8) | ipv4Octets[1]).toString(16);
423
+ const low = ((ipv4Octets[2] << 8) | ipv4Octets[3]).toString(16);
424
+ normalizedIp = `${normalizedIp.slice(0, lastColon + 1)}${high}:${low}`;
425
+ }
426
+
427
+ const doubleColonSides = normalizedIp.split('::');
428
+ if (doubleColonSides.length > 2) {
429
+ return null;
430
+ }
431
+
432
+ if (doubleColonSides.length === 1) {
433
+ const groups = normalizedIp.split(':');
434
+ if (groups.length !== 8) return null;
435
+ return parseHexGroups(groups);
436
+ }
437
+
438
+ const leftRaw = doubleColonSides[0] ?? '';
439
+ const rightRaw = doubleColonSides[1] ?? '';
440
+ const leftGroups = leftRaw === '' ? [] : leftRaw.split(':');
441
+ const rightGroups = rightRaw === '' ? [] : rightRaw.split(':');
442
+ if (leftGroups.length + rightGroups.length >= 8) {
443
+ return null;
444
+ }
445
+ const leftNums = parseHexGroups(leftGroups);
446
+ const rightNums = parseHexGroups(rightGroups);
447
+ if (!leftNums || !rightNums) {
448
+ return null;
449
+ }
450
+ const zeroFill = new Array<number>(
451
+ 8 - leftNums.length - rightNums.length
452
+ ).fill(0);
453
+ return [...leftNums, ...zeroFill, ...rightNums];
454
+ }
455
+
456
+ function isIpv4MappedParts(parts: readonly number[]): boolean {
457
+ return (
458
+ parts.length === 8 &&
459
+ parts[0] === 0 &&
460
+ parts[1] === 0 &&
461
+ parts[2] === 0 &&
462
+ parts[3] === 0 &&
463
+ parts[4] === 0 &&
464
+ parts[5] === 0xffff
465
+ );
466
+ }
467
+
468
+ function isIpLiteral(value: string): boolean {
469
+ return parseIpv4Octets(value) !== null || parseIpv6Parts(value) !== null;
470
+ }
471
+
472
+ export function canonicalizeSniDestinationIp(ip: string): string {
473
+ const ipv4 = parseIpv4Octets(ip);
474
+ if (ipv4) {
475
+ return `${ipv4[0]}.${ipv4[1]}.${ipv4[2]}.${ipv4[3]}`;
476
+ }
477
+ const ipv6Parts = parseIpv6Parts(ip);
478
+ if (!ipv6Parts) {
479
+ return ip;
480
+ }
481
+ if (isIpv4MappedParts(ipv6Parts)) {
482
+ const part6 = ipv6Parts[6] ?? 0;
483
+ const part7 = ipv6Parts[7] ?? 0;
484
+ return `${(part6 >> 8) & 0xff}.${part6 & 0xff}.${(part7 >> 8) & 0xff}.${
485
+ part7 & 0xff
486
+ }`;
487
+ }
488
+ return ipv6Parts.map((part) => part.toString(16)).join(':');
489
+ }
490
+
491
+ export function getProxyRuleType(
492
+ proxyRules: string
493
+ ): 'direct' | 'proxy' | 'mixed' | 'unknown' {
494
+ const rules = proxyRules
495
+ .split(';')
496
+ .map((rule) => rule.trim())
497
+ .filter(Boolean)
498
+ .map((rule) => rule.toUpperCase());
499
+ if (rules.length === 0) return 'unknown';
500
+ const directCount = rules.filter((rule) => rule === 'DIRECT').length;
501
+ if (directCount === rules.length) return 'direct';
502
+ if (directCount === 0) return 'proxy';
503
+ return 'mixed';
504
+ }
505
+
506
+ function getHostnameForLog(url: string): string {
507
+ try {
508
+ return new URL(url).hostname;
509
+ } catch {
510
+ return 'unknown';
511
+ }
512
+ }
513
+
514
+ function invalidConfig(message: string): never {
515
+ throw new SniRequestError('SNI_INVALID_CONFIG', message, true);
516
+ }
517
+
518
+ export function classifyTransportError(error: Error, isUpload = false): Error {
519
+ if (error instanceof SniRequestError) {
520
+ return error;
521
+ }
522
+
523
+ const code =
524
+ error && typeof error === 'object' && 'code' in error
525
+ ? String((error as { code?: unknown }).code)
526
+ : '';
527
+ const message = `${code} ${error.message}`;
528
+ if (
529
+ /CERT|certificate|altname|hostname|self[- ]?signed|unable to verify|expired/i.test(
530
+ message
531
+ )
532
+ ) {
533
+ return new SniRequestError('SNI_CERT_FAILED', error.message, true);
534
+ }
535
+ if (/TLS|SSL|handshake|EPROTO/i.test(message)) {
536
+ return new SniRequestError('SNI_TLS_FAILED', error.message, true);
537
+ }
538
+ if (isUpload) {
539
+ if (/\bECONNREFUSED\b/i.test(message)) {
540
+ return new SniRequestError('SNI_CONNECTION_REFUSED', error.message);
541
+ }
542
+ if (/\b(?:ENOTFOUND|EAI_AGAIN)\b/i.test(message)) {
543
+ return new SniRequestError('SNI_DNS_FAILED', error.message);
544
+ }
545
+ if (/\b(?:ENETUNREACH|EHOSTUNREACH)\b/i.test(message)) {
546
+ return new SniRequestError('SNI_NETWORK_UNREACHABLE', error.message);
547
+ }
548
+ }
549
+ return error;
550
+ }
551
+
552
+ function byteSize(value: string): number {
553
+ return Buffer.byteLength(value, 'utf8');
554
+ }
555
+
556
+ function hasControlChar(value: string): boolean {
557
+ for (let index = 0; index < value.length; index += 1) {
558
+ const code = value.charCodeAt(index);
559
+ if (code <= 0x1f || code === 0x7f) return true;
560
+ }
561
+ return false;
562
+ }
563
+
564
+ function normalizeMethod(method: string): string {
565
+ if (hasControlChar(method)) {
566
+ invalidConfig(`Invalid method: ${method}`);
567
+ }
568
+ const normalized = method.trim().toUpperCase();
569
+ if (!ALLOWED_METHODS.has(normalized)) {
570
+ invalidConfig(`Invalid method: ${method}`);
571
+ }
572
+ return normalized;
573
+ }
574
+
575
+ function normalizePath(path: string): string {
576
+ const trimmed = path.trim();
577
+ if (byteSize(trimmed) > MAX_PATH_BYTES) {
578
+ invalidConfig('Path too large');
579
+ }
580
+ if (
581
+ hasControlChar(trimmed) ||
582
+ trimmed.startsWith('//') ||
583
+ trimmed.includes('://') ||
584
+ SCHEME_RE.test(trimmed.split('/')[0] ?? '')
585
+ ) {
586
+ invalidConfig('Invalid path');
587
+ }
588
+ if (!trimmed) return '/';
589
+ return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
590
+ }
591
+
592
+ function validateHostname(hostname: string): void {
593
+ if (
594
+ !HOSTNAME_RE.test(hostname) ||
595
+ /^\d+\.\d+\.\d+\.\d+$/.test(hostname) ||
596
+ isIpLiteral(hostname)
597
+ ) {
598
+ invalidConfig(`Invalid hostname: ${hostname}`);
599
+ }
600
+ }
601
+
602
+ function validateRequestId(requestId: string | undefined): void {
603
+ if (requestId === undefined) return;
604
+ if (
605
+ !requestId ||
606
+ hasControlChar(requestId) ||
607
+ byteSize(requestId) > MAX_REQUEST_ID_BYTES
608
+ ) {
609
+ invalidConfig('Invalid requestId');
610
+ }
611
+ }
612
+
613
+ function validateTimeout(timeout: number): void {
614
+ if (!Number.isFinite(timeout) || timeout < 1 || timeout > MAX_TIMEOUT_MS) {
615
+ invalidConfig(`Invalid timeout: ${timeout}`);
616
+ }
617
+ }
618
+
619
+ function validateBody(body: string | null): void {
620
+ if (body !== null) {
621
+ if (typeof body !== 'string') invalidConfig('Invalid request body');
622
+ if (byteSize(body) > MAX_REQUEST_BODY_BYTES) {
623
+ invalidConfig('Request body too large');
624
+ }
625
+ }
626
+ }
627
+
628
+ function getBodyBytes(config: NormalizedSniRequestConfig): number {
629
+ if (config.bodyFile) return config.bodyFile.sizeBytes;
630
+ return config.body ? byteSize(config.body) : 0;
631
+ }
632
+
633
+ function isPathInside(root: string, target: string): boolean {
634
+ const relative = nodePath.relative(root, target);
635
+ return (
636
+ !!relative && !relative.startsWith('..') && !nodePath.isAbsolute(relative)
637
+ );
638
+ }
639
+
640
+ async function resolveAllowedUploadRoots(
641
+ getAllowedUploadRoots?: () => Promise<readonly string[]> | readonly string[],
642
+ signal?: AbortSignal
643
+ ): Promise<string[]> {
644
+ if (!getAllowedUploadRoots) {
645
+ return [];
646
+ }
647
+ let candidates: readonly string[] = [];
648
+ try {
649
+ candidates = await getAllowedUploadRoots();
650
+ } catch {
651
+ return [];
652
+ }
653
+ signal?.throwIfAborted();
654
+ const roots = await Promise.all(
655
+ candidates.map(async (candidate) => {
656
+ try {
657
+ return await fsPromises.realpath(candidate);
658
+ } catch {
659
+ return undefined;
660
+ }
661
+ })
662
+ );
663
+ return roots.filter((root): root is string => !!root);
664
+ }
665
+
666
+ type OpenedUploadFile = {
667
+ filePath: string;
668
+ sizeBytes: number;
669
+ handle: fsPromises.FileHandle;
670
+ close: () => Promise<void>;
671
+ };
672
+
673
+ async function statCanonicalUploadPath(
674
+ realPath: string
675
+ ): Promise<fs.BigIntStats> {
676
+ try {
677
+ const stat = await fsPromises.lstat(realPath, { bigint: true });
678
+ if ((await fsPromises.realpath(realPath)) === realPath) return stat;
679
+ } catch {
680
+ invalidConfig('Upload file is not readable');
681
+ }
682
+ invalidConfig('Upload file path changed during validation');
683
+ }
684
+
685
+ function isSameFile(left: fs.BigIntStats, right: fs.BigIntStats): boolean {
686
+ return (
687
+ left.isFile() &&
688
+ right.isFile() &&
689
+ left.dev === right.dev &&
690
+ left.ino === right.ino
691
+ );
692
+ }
693
+
694
+ async function resolveUploadFile(
695
+ config: SniNodeUploadFileConfig,
696
+ options?: SniNodeUploadValidationOptions,
697
+ signal?: AbortSignal
698
+ ): Promise<OpenedUploadFile> {
699
+ const { filePath } = config;
700
+ if (typeof filePath !== 'string' || !filePath || hasControlChar(filePath)) {
701
+ invalidConfig('Invalid filePath');
702
+ }
703
+ let absolutePath = filePath;
704
+ if (filePath.startsWith('file://')) {
705
+ try {
706
+ absolutePath = fileURLToPath(filePath);
707
+ } catch {
708
+ invalidConfig('Invalid filePath');
709
+ }
710
+ }
711
+ if (!nodePath.isAbsolute(absolutePath)) {
712
+ invalidConfig('filePath must be absolute');
713
+ }
714
+
715
+ let realPath: string;
716
+ try {
717
+ realPath = await fsPromises.realpath(nodePath.resolve(absolutePath));
718
+ } catch {
719
+ invalidConfig('Upload file is not readable');
720
+ }
721
+
722
+ signal?.throwIfAborted();
723
+ const requiredExtension =
724
+ options?.requiredFileExtension === undefined
725
+ ? '.zip'
726
+ : options.requiredFileExtension;
727
+ const requireDirectChild = options?.requireDirectChildOfRoot ?? true;
728
+ const roots = await resolveAllowedUploadRoots(
729
+ options?.getAllowedUploadRoots,
730
+ signal
731
+ );
732
+ signal?.throwIfAborted();
733
+
734
+ const hasValidExtension =
735
+ !requiredExtension || realPath.endsWith(requiredExtension);
736
+ const isInsideAllowedRoot = roots.some((root) =>
737
+ requireDirectChild
738
+ ? nodePath.dirname(realPath) === root && isPathInside(root, realPath)
739
+ : isPathInside(root, realPath)
740
+ );
741
+
742
+ if (!hasValidExtension || !isInsideAllowedRoot) {
743
+ invalidConfig('Upload file is outside app storage');
744
+ }
745
+
746
+ const pathStat = await statCanonicalUploadPath(realPath);
747
+ if (!pathStat.isFile()) {
748
+ invalidConfig('Upload file is not a regular file');
749
+ }
750
+ const releaseFileSlot = await sharedUploadFileLimiter.acquire(
751
+ config.hostname,
752
+ config.ip,
753
+ { signal }
754
+ );
755
+
756
+ let handle: fsPromises.FileHandle;
757
+ try {
758
+ signal?.throwIfAborted();
759
+ // Windows does not expose the optional Unix open flags. Identity is
760
+ // checked on every platform before accepting the file.
761
+ const flags =
762
+ fs.constants.O_RDONLY |
763
+ (fs.constants.O_NOFOLLOW ?? 0) |
764
+ (fs.constants.O_NONBLOCK ?? 0);
765
+ handle = await fsPromises.open(realPath, flags);
766
+ } catch {
767
+ releaseFileSlot();
768
+ signal?.throwIfAborted();
769
+ invalidConfig('Upload file is not readable');
770
+ }
771
+
772
+ let closing: Promise<void> | undefined;
773
+ const close = () => {
774
+ signal?.removeEventListener('abort', close);
775
+ return (closing ??= handle
776
+ .close()
777
+ .catch(() => undefined)
778
+ .finally(releaseFileSlot));
779
+ };
780
+ signal?.addEventListener('abort', close, { once: true });
781
+
782
+ try {
783
+ signal?.throwIfAborted();
784
+ const stat = await handle
785
+ .stat({ bigint: true })
786
+ .catch(() => invalidConfig('Upload file is not readable'));
787
+ if (!isSameFile(stat, pathStat)) {
788
+ invalidConfig('Upload file path changed during validation');
789
+ }
790
+ if (stat.size < 1n || stat.size > BigInt(MAX_UPLOAD_FILE_BYTES)) {
791
+ invalidConfig(`Invalid upload file size: ${stat.size}`);
792
+ }
793
+ const sizeBytes = Number(stat.size);
794
+ signal?.throwIfAborted();
795
+
796
+ if (options?.verifyUploadFile) {
797
+ let verified: boolean;
798
+ try {
799
+ verified = await options.verifyUploadFile(realPath, sizeBytes);
800
+ } catch {
801
+ invalidConfig('Upload file verification failed');
802
+ }
803
+ signal?.throwIfAborted();
804
+ if (!verified) {
805
+ invalidConfig('Upload file was not collected by the main process');
806
+ }
807
+ }
808
+
809
+ const verifiedPathStat = await statCanonicalUploadPath(realPath);
810
+ if (
811
+ !isSameFile(stat, verifiedPathStat) ||
812
+ stat.size !== verifiedPathStat.size
813
+ ) {
814
+ invalidConfig('Upload file changed during validation');
815
+ }
816
+ signal?.throwIfAborted();
817
+ return { filePath: realPath, sizeBytes, handle, close };
818
+ } catch (error) {
819
+ await close();
820
+ throw error;
821
+ }
822
+ }
823
+
824
+ function normalizeSniUploadFileConfig(
825
+ config: SniNodeUploadFileConfig,
826
+ options?: SniNodeUploadValidationOptions
827
+ ): NormalizedSniRequestConfig {
828
+ if ((config as { body?: unknown }).body !== undefined) {
829
+ invalidConfig('uploadFile does not accept a body');
830
+ }
831
+ const method =
832
+ typeof config.method === 'string' ? config.method.trim().toUpperCase() : '';
833
+ if (!UPLOAD_FILE_METHODS.has(method)) {
834
+ invalidConfig(`Invalid upload method: ${String(config.method)}`);
835
+ }
836
+ const normalized = normalizeSniRequestConfig({
837
+ requestId: config.requestId,
838
+ ip: config.ip,
839
+ hostname: config.hostname,
840
+ path: config.path,
841
+ headers: config.headers,
842
+ method,
843
+ body: null,
844
+ timeout: config.timeout,
845
+ });
846
+
847
+ const allowedOriginsInput =
848
+ options?.allowedUploadOrigins === undefined
849
+ ? DEFAULT_LOGGER_UPLOAD_ORIGINS
850
+ : options.allowedUploadOrigins;
851
+ const allowedOrigins =
852
+ allowedOriginsInput instanceof Set
853
+ ? allowedOriginsInput
854
+ : new Set(allowedOriginsInput);
855
+ const allowedPath =
856
+ options?.allowedUploadPath === undefined
857
+ ? DEFAULT_LOGGER_UPLOAD_PATH
858
+ : options.allowedUploadPath;
859
+
860
+ if (
861
+ !allowedOrigins.has(`https://${normalized.hostname.toLowerCase()}`) ||
862
+ (allowedPath !== null && normalized.path !== allowedPath)
863
+ ) {
864
+ invalidConfig('Upload destination is not allowed');
865
+ }
866
+ return normalized;
867
+ }
868
+
869
+ export async function validateSniUploadFileConfig(
870
+ config: SniNodeUploadFileConfig,
871
+ options?: SniNodeUploadValidationOptions,
872
+ signal?: AbortSignal
873
+ ): Promise<NormalizedSniRequestConfig> {
874
+ const normalized = normalizeSniUploadFileConfig(config, options);
875
+ const file = await resolveUploadFile(config, options, signal);
876
+ await file.close();
877
+ signal?.throwIfAborted();
878
+ return {
879
+ ...normalized,
880
+ bodyFile: { filePath: file.filePath, sizeBytes: file.sizeBytes },
881
+ };
882
+ }
883
+
884
+ function ipv6BytesFromParts(parts: readonly number[]): number[] {
885
+ return parts.flatMap((part) => [(part >> 8) & 0xff, part & 0xff]);
886
+ }
887
+
888
+ function isForbiddenIpv4(octets: readonly number[]): boolean {
889
+ const a = octets[0] ?? 0;
890
+ const b = octets[1] ?? 0;
891
+ const c = octets[2] ?? 0;
892
+ return (
893
+ a === 0 ||
894
+ a === 10 ||
895
+ a === 127 ||
896
+ (a === 100 && (b & 0xc0) === 0x40) ||
897
+ (a === 169 && b === 254) ||
898
+ (a === 172 && b >= 16 && b <= 31) ||
899
+ (a === 192 && b === 168) ||
900
+ (a === 192 && b === 0 && c === 0) ||
901
+ (a === 192 && b === 0 && c === 2) ||
902
+ (a === 198 && (b === 18 || b === 19)) ||
903
+ (a === 198 && b === 51 && c === 100) ||
904
+ (a === 203 && b === 0 && c === 113) ||
905
+ a >= 224
906
+ );
907
+ }
908
+
909
+ function embeddedIpv4(bytes: readonly number[], offset: number): number[] {
910
+ return [
911
+ bytes[offset] ?? 0,
912
+ bytes[offset + 1] ?? 0,
913
+ bytes[offset + 2] ?? 0,
914
+ bytes[offset + 3] ?? 0,
915
+ ];
916
+ }
917
+
918
+ function isForbiddenIpv6(parts: readonly number[]): boolean {
919
+ const bytes = ipv6BytesFromParts(parts);
920
+ if (isIpv4MappedParts(parts)) {
921
+ return isForbiddenIpv4(embeddedIpv4(bytes, 12));
922
+ }
923
+
924
+ const b0 = bytes[0] ?? 0;
925
+ const b1 = bytes[1] ?? 0;
926
+ const b2 = bytes[2] ?? 0;
927
+ const b3 = bytes[3] ?? 0;
928
+ const b4 = bytes[4] ?? 0;
929
+ const b5 = bytes[5] ?? 0;
930
+
931
+ if (b0 === 0x00 && b1 === 0x64 && b2 === 0xff && b3 === 0x9b) {
932
+ if (b4 === 0x00 && b5 === 0x01) {
933
+ return true;
934
+ }
935
+ if (bytes.slice(4, 12).every((b) => b === 0)) {
936
+ return isForbiddenIpv4(embeddedIpv4(bytes, 12));
937
+ }
938
+ return true;
939
+ }
940
+
941
+ if (
942
+ (b0 & 0xe0) !== 0x20 ||
943
+ (b0 & 0xfe) === 0xfc ||
944
+ (b0 === 0x01 && b1 === 0x00 && bytes.slice(2, 8).every((b) => b === 0)) ||
945
+ (b0 === 0x20 && b1 === 0x02) ||
946
+ bytes.slice(0, 12).every((b) => b === 0)
947
+ ) {
948
+ return true;
949
+ }
950
+ if (b0 === 0x20 && b1 === 0x01) {
951
+ if (b2 === 0x00 && b3 === 0x00) return true;
952
+ if (b2 === 0x00 && (b3 & 0xf0) === 0x10) return true;
953
+ if (b2 === 0x00 && b3 === 0x02) return true;
954
+ if (b2 === 0x0d && b3 === 0xb8) return true;
955
+ }
956
+ return false;
957
+ }
958
+ /* eslint-enable no-bitwise */
959
+
960
+ export function validatePublicIp(ip: string): void {
961
+ if (
962
+ !ip ||
963
+ ip.trim() !== ip ||
964
+ ip.includes('[') ||
965
+ ip.includes(']') ||
966
+ ip.includes('%')
967
+ ) {
968
+ invalidConfig(`Invalid IP: ${ip}`);
969
+ }
970
+
971
+ const ipv4Octets = parseIpv4Octets(ip);
972
+ if (ipv4Octets) {
973
+ if (isForbiddenIpv4(ipv4Octets)) {
974
+ invalidConfig(`Forbidden IP: ${ip}`);
975
+ }
976
+ return;
977
+ }
978
+
979
+ const ipv6Parts = parseIpv6Parts(ip);
980
+ if (!ipv6Parts) {
981
+ invalidConfig(`Invalid IP: ${ip}`);
982
+ }
983
+ if (isForbiddenIpv6(ipv6Parts)) {
984
+ invalidConfig(`Forbidden IP: ${ip}`);
985
+ }
986
+ }
987
+
988
+ function normalizeHeaders(
989
+ headers: Record<string, string>
990
+ ): Record<string, string> {
991
+ const entries = Object.entries(headers ?? {});
992
+ if (entries.length > MAX_HEADER_COUNT) {
993
+ invalidConfig('Too many headers');
994
+ }
995
+
996
+ let totalBytes = 0;
997
+ const normalizedHeaders = new Map<string, string>();
998
+ for (const [name, rawValue] of entries) {
999
+ const value = String(rawValue ?? '');
1000
+ const nameBytes = byteSize(name);
1001
+ const valueBytes = byteSize(value);
1002
+ totalBytes += nameBytes + valueBytes;
1003
+
1004
+ if (
1005
+ !name ||
1006
+ hasControlChar(name) ||
1007
+ hasControlChar(value) ||
1008
+ nameBytes > MAX_HEADER_NAME_BYTES ||
1009
+ valueBytes > MAX_HEADER_VALUE_BYTES ||
1010
+ !HEADER_TOKEN_RE.test(name)
1011
+ ) {
1012
+ invalidConfig(`Invalid header: ${name}`);
1013
+ }
1014
+
1015
+ const lowerName = name.toLowerCase();
1016
+ if (
1017
+ lowerName.startsWith(':') ||
1018
+ lowerName.startsWith('proxy-') ||
1019
+ UNSAFE_HEADERS.has(lowerName)
1020
+ ) {
1021
+ invalidConfig(`Unsafe header: ${name}`);
1022
+ }
1023
+ if (!MODULE_OWNED_HEADERS.has(lowerName)) {
1024
+ normalizedHeaders.set(name, value);
1025
+ }
1026
+ }
1027
+
1028
+ if (totalBytes > MAX_TOTAL_HEADER_BYTES) {
1029
+ invalidConfig('Headers too large');
1030
+ }
1031
+ return Object.fromEntries(normalizedHeaders);
1032
+ }
1033
+
1034
+ export function validateSniRequestConfig(
1035
+ config: SniNodeRequestConfig
1036
+ ): NormalizedSniRequestConfig {
1037
+ if ((config as { bodyFile?: unknown }).bodyFile !== undefined) {
1038
+ invalidConfig('request does not accept bodyFile');
1039
+ }
1040
+ const normalized = normalizeSniRequestConfig(config);
1041
+ const { method, body } = normalized;
1042
+ if ((method === 'GET' || method === 'HEAD') && body !== null) {
1043
+ invalidConfig(`${method} requests must not have a body`);
1044
+ }
1045
+ if (
1046
+ (method === 'POST' || method === 'PUT' || method === 'PATCH') &&
1047
+ body === null
1048
+ ) {
1049
+ invalidConfig(`${method} requests require an explicit body`);
1050
+ }
1051
+ return normalized;
1052
+ }
1053
+
1054
+ function normalizeSniRequestConfig(
1055
+ config: SniNodeRequestConfig
1056
+ ): NormalizedSniRequestConfig {
1057
+ validateRequestId(config.requestId);
1058
+ validatePublicIp(config.ip);
1059
+ validateHostname(config.hostname);
1060
+ validateTimeout(config.timeout);
1061
+ const body = config.body ?? null;
1062
+ validateBody(body);
1063
+
1064
+ if (config.port !== null && config.port !== undefined) {
1065
+ invalidConfig('Caller-controlled ports are not allowed');
1066
+ }
1067
+
1068
+ return {
1069
+ requestId: config.requestId,
1070
+ ip: config.ip,
1071
+ hostname: config.hostname,
1072
+ body,
1073
+ headers: normalizeHeaders(config.headers ?? {}),
1074
+ method: normalizeMethod(config.method ?? 'GET'),
1075
+ path: normalizePath(config.path ?? '/'),
1076
+ timeout: Math.trunc(config.timeout),
1077
+ };
1078
+ }
1079
+
1080
+ function createCustomAgent(): https.Agent {
1081
+ const agent = new https.Agent({
1082
+ keepAlive: true,
1083
+ keepAliveMsecs: 30_000,
1084
+ maxSockets: MAX_SOCKETS_PER_PAIR,
1085
+ maxTotalSockets: MAX_TOTAL_SOCKETS,
1086
+ maxFreeSockets: MAX_FREE_SOCKETS,
1087
+ timeout: MAX_TIMEOUT_MS,
1088
+ scheduling: 'lifo',
1089
+ });
1090
+
1091
+ (
1092
+ agent as https.Agent & {
1093
+ getName(options: RequestOptions): string;
1094
+ }
1095
+ ).getName = (options: RequestOptions): string => {
1096
+ const ip = options.host || '';
1097
+ const hostname = options.servername || '';
1098
+ const port = options.port || 443;
1099
+ return `${hostname}:${canonicalizeSniDestinationIp(ip)}:${port}`;
1100
+ };
1101
+ return agent;
1102
+ }
1103
+
1104
+ function createAgentState(): SniAgentState {
1105
+ return {
1106
+ agent: createCustomAgent(),
1107
+ activeRequests: new Set<ClientRequest>(),
1108
+ destroyed: false,
1109
+ };
1110
+ }
1111
+
1112
+ export function isProxyRouteActive(proxyRules: string): boolean {
1113
+ return proxyRules
1114
+ .split(';')
1115
+ .map((rule) => rule.trim())
1116
+ .filter(Boolean)
1117
+ .some((rule) => rule.toUpperCase() !== 'DIRECT');
1118
+ }
1119
+
1120
+ export function buildSniRequestOptions(
1121
+ config: NormalizedSniRequestConfig,
1122
+ agent: https.Agent
1123
+ ): RequestOptions {
1124
+ const headers: Record<string, string> = {
1125
+ ...config.headers,
1126
+ 'Host': config.hostname,
1127
+ 'Accept-Encoding': 'identity',
1128
+ };
1129
+ if (config.bodyFile) {
1130
+ headers['Content-Length'] = String(config.bodyFile.sizeBytes);
1131
+ } else if (config.body !== null) {
1132
+ headers['Content-Length'] = String(Buffer.byteLength(config.body, 'utf8'));
1133
+ }
1134
+
1135
+ return {
1136
+ method: config.method,
1137
+ host: config.ip,
1138
+ port: 443,
1139
+ path: config.path,
1140
+ servername: config.hostname,
1141
+ headers,
1142
+ agent,
1143
+ rejectUnauthorized: true,
1144
+ };
1145
+ }
1146
+
1147
+ export function headersToMaps(rawHeaders: string[]): {
1148
+ headers: Record<string, string>;
1149
+ multiValueHeaders: Record<string, string[]>;
1150
+ } {
1151
+ const headers = new Map<string, string>();
1152
+ const multiValueHeaders = new Map<string, string[]>();
1153
+ for (let index = 0; index < rawHeaders.length; index += 2) {
1154
+ const name = String(rawHeaders[index] ?? '').toLowerCase();
1155
+ const value = String(rawHeaders[index + 1] ?? '');
1156
+ if (name) {
1157
+ headers.set(name, value);
1158
+ const values = multiValueHeaders.get(name);
1159
+ if (values) {
1160
+ values.push(value);
1161
+ } else {
1162
+ multiValueHeaders.set(name, [value]);
1163
+ }
1164
+ }
1165
+ }
1166
+ return {
1167
+ headers: Object.fromEntries(headers),
1168
+ multiValueHeaders: Object.fromEntries(multiValueHeaders),
1169
+ };
1170
+ }
1171
+
1172
+ type SniLimiterLog = (
1173
+ level: 'info' | 'warn' | 'error',
1174
+ event: string,
1175
+ fields: Record<string, unknown>
1176
+ ) => void;
1177
+
1178
+ export class SniRequestLimiter {
1179
+ private maxActiveRequests: number;
1180
+ private maxActiveRequestsPerPair: number;
1181
+ private maxPendingRequests: number;
1182
+ private onLog: SniLimiterLog | undefined;
1183
+
1184
+ constructor(
1185
+ maxActiveRequests = MAX_ACTIVE_REQUESTS,
1186
+ maxActiveRequestsPerPair = MAX_ACTIVE_REQUESTS_PER_PAIR,
1187
+ maxPendingRequests = MAX_PENDING_REQUESTS,
1188
+ onLog?: SniLimiterLog
1189
+ ) {
1190
+ this.maxActiveRequests = maxActiveRequests;
1191
+ this.maxActiveRequestsPerPair = maxActiveRequestsPerPair;
1192
+ this.maxPendingRequests = maxPendingRequests;
1193
+ this.onLog = onLog;
1194
+ }
1195
+
1196
+ private activeRequests = 0;
1197
+
1198
+ private activeRequestsByPair = new Map<string, number>();
1199
+
1200
+ private pendingRequests: SniRequestLimiterWaiter[] = [];
1201
+
1202
+ private getKey(hostname: string, ip: string): string {
1203
+ return `${hostname.toLowerCase()}|${canonicalizeSniDestinationIp(ip)}`;
1204
+ }
1205
+
1206
+ private hasCapacity(key: string): boolean {
1207
+ return (
1208
+ this.activeRequests < this.maxActiveRequests &&
1209
+ (this.activeRequestsByPair.get(key) ?? 0) < this.maxActiveRequestsPerPair
1210
+ );
1211
+ }
1212
+
1213
+ private reserveSlot(key: string): () => void {
1214
+ this.activeRequests += 1;
1215
+ this.activeRequestsByPair.set(
1216
+ key,
1217
+ (this.activeRequestsByPair.get(key) ?? 0) + 1
1218
+ );
1219
+
1220
+ let released = false;
1221
+ return () => {
1222
+ if (released) return;
1223
+ released = true;
1224
+ this.activeRequests = Math.max(0, this.activeRequests - 1);
1225
+ const nextPairCount = this.activeRequestsByPair.get(key) ?? 0;
1226
+ if (nextPairCount <= 1) {
1227
+ this.activeRequestsByPair.delete(key);
1228
+ } else {
1229
+ this.activeRequestsByPair.set(key, nextPairCount - 1);
1230
+ }
1231
+ this.dispatchPendingRequests();
1232
+ };
1233
+ }
1234
+
1235
+ private dispatchPendingRequests(): void {
1236
+ while (this.activeRequests < this.maxActiveRequests) {
1237
+ const index = this.pendingRequests.findIndex((waiter) =>
1238
+ this.hasCapacity(waiter.key)
1239
+ );
1240
+ if (index < 0) return;
1241
+
1242
+ const [waiter] = this.pendingRequests.splice(index, 1);
1243
+ if (!waiter) return;
1244
+ if (waiter.signal && waiter.abortListener) {
1245
+ waiter.signal.removeEventListener('abort', waiter.abortListener);
1246
+ }
1247
+ waiter.resolve(this.reserveSlot(waiter.key));
1248
+ }
1249
+ }
1250
+
1251
+ private getCancellationError(signal: AbortSignal): Error {
1252
+ return signal.reason instanceof Error
1253
+ ? signal.reason
1254
+ : new SniRequestError('SNI_CANCELLED', 'Request cancelled', true);
1255
+ }
1256
+
1257
+ snapshot(hostname?: string, ip?: string): SniNodeDebugSnapshot {
1258
+ const key = hostname && ip ? this.getKey(hostname, ip) : undefined;
1259
+ return {
1260
+ activeRequests: this.activeRequests,
1261
+ activeRequestsForPair: key ? this.activeRequestsByPair.get(key) ?? 0 : 0,
1262
+ pendingRequests: this.pendingRequests.length,
1263
+ pendingRequestsForPair: key
1264
+ ? this.pendingRequests.filter((waiter) => waiter.key === key).length
1265
+ : 0,
1266
+ };
1267
+ }
1268
+
1269
+ acquire(
1270
+ hostname: string,
1271
+ ip: string,
1272
+ options: { signal?: AbortSignal; onLog?: SniLimiterLog } = {}
1273
+ ): Promise<() => void> {
1274
+ const key = this.getKey(hostname, ip);
1275
+ if (options.signal?.aborted) {
1276
+ return Promise.reject(this.getCancellationError(options.signal));
1277
+ }
1278
+ if (this.hasCapacity(key)) {
1279
+ return Promise.resolve(this.reserveSlot(key));
1280
+ }
1281
+ if (this.pendingRequests.length >= this.maxPendingRequests) {
1282
+ const stats = this.snapshot(hostname, ip);
1283
+ const onLog = options.onLog ?? this.onLog;
1284
+ onLog?.('warn', 'desktop_sni_resource_limit', {
1285
+ hostname: hostname.toLowerCase(),
1286
+ ip,
1287
+ ipFamily: getIpFamily(ip),
1288
+ activeRequests: stats.activeRequests,
1289
+ activeRequestsForPair: stats.activeRequestsForPair,
1290
+ pendingRequests: stats.pendingRequests,
1291
+ pendingRequestsForPair: stats.pendingRequestsForPair,
1292
+ limit: this.maxPendingRequests,
1293
+ reason: 'max_pending_requests',
1294
+ });
1295
+ return Promise.reject(
1296
+ new SniRequestError(
1297
+ 'SNI_RESOURCE_LIMIT',
1298
+ 'Too many pending SNI requests',
1299
+ true
1300
+ )
1301
+ );
1302
+ }
1303
+
1304
+ return new Promise((resolve, reject) => {
1305
+ const waiter: SniRequestLimiterWaiter = {
1306
+ key,
1307
+ signal: options.signal,
1308
+ abortListener: undefined,
1309
+ resolve,
1310
+ };
1311
+ if (options.signal) {
1312
+ waiter.abortListener = () => {
1313
+ const index = this.pendingRequests.indexOf(waiter);
1314
+ if (index < 0) return;
1315
+ this.pendingRequests.splice(index, 1);
1316
+ reject(this.getCancellationError(options.signal as AbortSignal));
1317
+ };
1318
+ options.signal.addEventListener('abort', waiter.abortListener, {
1319
+ once: true,
1320
+ });
1321
+ }
1322
+ this.pendingRequests.push(waiter);
1323
+ });
1324
+ }
1325
+ }
1326
+
1327
+ // Both package entry points must use the same limiter in the main process.
1328
+ const limiterKey = Symbol.for(
1329
+ '@onekeyfe/react-native-sni-connect.requestLimiter'
1330
+ );
1331
+ const fileLimiterKey = Symbol.for(
1332
+ '@onekeyfe/react-native-sni-connect.uploadFileLimiter'
1333
+ );
1334
+ const sniProcess = process as typeof process & {
1335
+ [limiterKey]?: SniRequestLimiter;
1336
+ [fileLimiterKey]?: SniRequestLimiter;
1337
+ };
1338
+ const sharedRequestLimiter = (sniProcess[limiterKey] ??=
1339
+ new SniRequestLimiter());
1340
+ const sharedUploadFileLimiter = (sniProcess[fileLimiterKey] ??=
1341
+ new SniRequestLimiter(MAX_OPEN_UPLOAD_FILES, MAX_OPEN_UPLOAD_FILES));
1342
+
1343
+ export class SniNodeClient {
1344
+ private options: SniNodeClientOptions;
1345
+
1346
+ private logPrefix: string;
1347
+
1348
+ private agentState: SniAgentState;
1349
+
1350
+ private requestsById = new Map<string, SniRequestState>();
1351
+
1352
+ private allRequests = new Set<SniRequestState>();
1353
+
1354
+ private allActiveRequests = new Set<ClientRequest>();
1355
+
1356
+ private requestAgentStates = new Map<ClientRequest, SniAgentState>();
1357
+
1358
+ private requestLimiter = sharedRequestLimiter;
1359
+
1360
+ constructor(options: SniNodeClientOptions = {}) {
1361
+ this.options = options;
1362
+ this.logPrefix = options.logPrefix ?? '[DesktopApiSniRequest]';
1363
+ this.agentState = createAgentState();
1364
+ }
1365
+
1366
+ getRequestLimiter(): SniRequestLimiter {
1367
+ return this.requestLimiter;
1368
+ }
1369
+
1370
+ setRequestLimiter(limiter: SniRequestLimiter): void {
1371
+ this.requestLimiter = limiter;
1372
+ }
1373
+
1374
+ getAgentState(): SniAgentState {
1375
+ return this.agentState;
1376
+ }
1377
+
1378
+ private writeNativeLog(
1379
+ level: 'info' | 'warn' | 'error',
1380
+ event: string,
1381
+ fields: Record<string, unknown>
1382
+ ): void {
1383
+ emitNativeLog(this.options.logger, this.logPrefix, level, event, fields);
1384
+ }
1385
+
1386
+ private maybeDestroyIdleAgentState(agentState: SniAgentState): void {
1387
+ if (
1388
+ agentState !== this.agentState &&
1389
+ agentState.activeRequests.size === 0 &&
1390
+ !agentState.destroyed
1391
+ ) {
1392
+ agentState.destroyed = true;
1393
+ agentState.agent.destroy();
1394
+ }
1395
+ }
1396
+
1397
+ private removeRequestState(
1398
+ requestState: SniRequestState,
1399
+ request: ClientRequest | undefined,
1400
+ agentState: SniAgentState | undefined
1401
+ ): void {
1402
+ requestState.clearDeadline();
1403
+ requestState.settled = true;
1404
+ requestState.uploadProgress = undefined;
1405
+ let cleanupAgentState = agentState;
1406
+ if (
1407
+ requestState.requestId &&
1408
+ this.requestsById.get(requestState.requestId) === requestState
1409
+ ) {
1410
+ this.requestsById.delete(requestState.requestId);
1411
+ }
1412
+ this.allRequests.delete(requestState);
1413
+ if (request) {
1414
+ const state = agentState ?? this.requestAgentStates.get(request);
1415
+ this.allActiveRequests.delete(request);
1416
+ state?.activeRequests.delete(request);
1417
+ this.requestAgentStates.delete(request);
1418
+ cleanupAgentState = state;
1419
+ }
1420
+ if (cleanupAgentState) {
1421
+ this.maybeDestroyIdleAgentState(cleanupAgentState);
1422
+ }
1423
+ }
1424
+
1425
+ async isProxyActiveForUrl(url: string): Promise<boolean> {
1426
+ const startedAt = Date.now();
1427
+ const hostname = getHostnameForLog(url);
1428
+ try {
1429
+ const proxyRules = await this.options.resolveProxy?.(url);
1430
+ const proxyRuleType = getProxyRuleType(proxyRules ?? '');
1431
+ if (proxyRuleType === 'unknown') {
1432
+ throw new SniRequestError(
1433
+ 'SNI_UNSUPPORTED',
1434
+ 'Proxy preflight is unavailable'
1435
+ );
1436
+ }
1437
+ const proxyActive = proxyRuleType !== 'direct';
1438
+ this.writeNativeLog('info', 'desktop_sni_proxy_preflight', {
1439
+ hostname,
1440
+ proxyActive,
1441
+ proxyRuleType,
1442
+ durationMs: Date.now() - startedAt,
1443
+ });
1444
+ return proxyActive;
1445
+ } catch (error) {
1446
+ this.writeNativeLog('error', 'desktop_sni_proxy_preflight', {
1447
+ hostname,
1448
+ proxyActive: 'unknown',
1449
+ proxyRuleType: 'unknown',
1450
+ durationMs: Date.now() - startedAt,
1451
+ errorCode: getErrorCode(error) ?? 'none',
1452
+ errorMessage: getErrorMessage(error),
1453
+ });
1454
+ throw error;
1455
+ }
1456
+ }
1457
+
1458
+ private logInvalidConfig(
1459
+ config: Pick<
1460
+ SniNodeRequestConfig,
1461
+ 'hostname' | 'ip' | 'method' | 'timeout' | 'path' | 'headers'
1462
+ >,
1463
+ bodyBytes: number,
1464
+ error: unknown,
1465
+ startedAt: number
1466
+ ): void {
1467
+ this.writeNativeLog('error', 'desktop_sni_request_failed', {
1468
+ code: getErrorCode(error) ?? 'SNI_INVALID_CONFIG',
1469
+ failClosed: isSniFailClosedError(error),
1470
+ hostname: config.hostname ?? 'unknown',
1471
+ ip: config.ip,
1472
+ ipFamily: config.ip ? getIpFamily(config.ip) : 'unknown',
1473
+ method: config.method ?? 'GET',
1474
+ timeout: config.timeout ?? 'unknown',
1475
+ pathBytes: config.path ? byteSize(config.path) : 0,
1476
+ bodyBytes,
1477
+ headerCount: Object.keys(config.headers ?? {}).length,
1478
+ activeRequests: this.requestLimiter.snapshot().activeRequests,
1479
+ activeRequestsForPair: 0,
1480
+ pendingRequests: this.requestLimiter.snapshot().pendingRequests,
1481
+ pendingRequestsForPair: 0,
1482
+ durationMs: Date.now() - startedAt,
1483
+ errorMessage: getErrorMessage(error),
1484
+ });
1485
+ }
1486
+
1487
+ private createRequestState(
1488
+ requestId: string | undefined,
1489
+ isUpload: boolean,
1490
+ timeout: number,
1491
+ startedAt: number
1492
+ ): SniRequestState {
1493
+ const abortController = new AbortController();
1494
+ const deadline = startedAt + timeout;
1495
+ const cancelForTimeout = () =>
1496
+ requestState.cancel(
1497
+ new SniRequestError(
1498
+ 'SNI_TIMEOUT',
1499
+ `SNI request timeout after ${timeout}ms`
1500
+ )
1501
+ );
1502
+ const timer = setTimeout(
1503
+ cancelForTimeout,
1504
+ Math.max(0, deadline - Date.now())
1505
+ );
1506
+ const requestState: SniRequestState = {
1507
+ requestId,
1508
+ settled: false,
1509
+ uploadProgress:
1510
+ requestId && isUpload ? { bytesSent: 0, totalBytes: 0 } : undefined,
1511
+ signal: abortController.signal,
1512
+ checkDeadline: () => {
1513
+ if (Date.now() >= deadline) cancelForTimeout();
1514
+ abortController.signal.throwIfAborted();
1515
+ },
1516
+ clearDeadline: () => clearTimeout(timer),
1517
+ cancel: (error) => {
1518
+ requestState.settled = true;
1519
+ requestState.uploadProgress = undefined;
1520
+ abortController.abort(error);
1521
+ },
1522
+ };
1523
+
1524
+ if (requestId) {
1525
+ const previous = this.requestsById.get(requestId);
1526
+ if (previous) {
1527
+ this.writeNativeLog('warn', 'desktop_sni_lifecycle', {
1528
+ action: 'duplicate_request_id',
1529
+ requestId,
1530
+ success: true,
1531
+ activeCount: this.allActiveRequests.size,
1532
+ pendingCount: this.requestLimiter.snapshot().pendingRequests,
1533
+ });
1534
+ previous.cancel(
1535
+ new SniRequestError('SNI_CANCELLED', 'Request cancelled', true)
1536
+ );
1537
+ }
1538
+ this.requestsById.set(requestId, requestState);
1539
+ }
1540
+ this.allRequests.add(requestState);
1541
+
1542
+ return requestState;
1543
+ }
1544
+
1545
+ async request(config: SniNodeRequestConfig): Promise<SniNodeResponse> {
1546
+ const startedAt = Date.now();
1547
+ let normalizedConfig: NormalizedSniRequestConfig;
1548
+ try {
1549
+ normalizedConfig = validateSniRequestConfig(config);
1550
+ } catch (error) {
1551
+ this.logInvalidConfig(
1552
+ config,
1553
+ config.body ? byteSize(config.body) : 0,
1554
+ error,
1555
+ startedAt
1556
+ );
1557
+ return Promise.reject(error);
1558
+ }
1559
+ const requestState = this.createRequestState(
1560
+ normalizedConfig.requestId,
1561
+ false,
1562
+ normalizedConfig.timeout,
1563
+ startedAt
1564
+ );
1565
+ return this.execute(normalizedConfig, startedAt, requestState);
1566
+ }
1567
+
1568
+ async uploadFile(config: SniNodeUploadFileConfig): Promise<SniNodeResponse> {
1569
+ const startedAt = Date.now();
1570
+ try {
1571
+ validateRequestId(config.requestId);
1572
+ validateTimeout(config.timeout);
1573
+ } catch (error) {
1574
+ this.logInvalidConfig(config, 0, error, startedAt);
1575
+ throw error;
1576
+ }
1577
+
1578
+ const requestState = this.createRequestState(
1579
+ config.requestId,
1580
+ true,
1581
+ Math.trunc(config.timeout),
1582
+ startedAt
1583
+ );
1584
+ const { signal } = requestState;
1585
+ let rejectOnAbort: (() => void) | undefined;
1586
+ let normalizedConfig: NormalizedSniRequestConfig;
1587
+ let file: OpenedUploadFile | undefined;
1588
+ try {
1589
+ requestState.checkDeadline();
1590
+ normalizedConfig = normalizeSniUploadFileConfig(config, this.options);
1591
+ file = await new Promise<OpenedUploadFile>((resolve, reject) => {
1592
+ rejectOnAbort = () => reject(signal.reason);
1593
+ signal.addEventListener('abort', rejectOnAbort, { once: true });
1594
+ resolveUploadFile(config, this.options, signal).then(resolve, reject);
1595
+ });
1596
+ requestState.checkDeadline();
1597
+ } catch (error) {
1598
+ this.removeRequestState(requestState, undefined, undefined);
1599
+ file?.close();
1600
+ this.logInvalidConfig(config, 0, error, startedAt);
1601
+ throw error;
1602
+ } finally {
1603
+ if (rejectOnAbort) signal.removeEventListener('abort', rejectOnAbort);
1604
+ }
1605
+
1606
+ if (requestState.uploadProgress) {
1607
+ requestState.uploadProgress.totalBytes = file.sizeBytes;
1608
+ }
1609
+ try {
1610
+ return await this.execute(
1611
+ normalizedConfig,
1612
+ startedAt,
1613
+ requestState,
1614
+ file
1615
+ );
1616
+ } finally {
1617
+ file.close();
1618
+ }
1619
+ }
1620
+
1621
+ async getUploadProgress(
1622
+ requestId: string
1623
+ ): Promise<SniNodeUploadProgress | null> {
1624
+ if (!requestId) {
1625
+ return null;
1626
+ }
1627
+ const requestState = this.requestsById.get(requestId);
1628
+ if (!requestState || requestState.settled || !requestState.uploadProgress) {
1629
+ return null;
1630
+ }
1631
+ return {
1632
+ bytesSent: requestState.uploadProgress.bytesSent,
1633
+ totalBytes: requestState.uploadProgress.totalBytes,
1634
+ };
1635
+ }
1636
+
1637
+ private async execute(
1638
+ config: Omit<NormalizedSniRequestConfig, 'bodyFile'>,
1639
+ startedAt: number,
1640
+ requestState: SniRequestState,
1641
+ bodyFile?: OpenedUploadFile
1642
+ ): Promise<SniNodeResponse> {
1643
+ const normalizedConfig = bodyFile ? { ...config, bodyFile } : config;
1644
+ let releaseRequestSlot: (() => void) | undefined;
1645
+ let activeRequest: ClientRequest | undefined;
1646
+ let activeAgentState: SniAgentState | undefined;
1647
+ let activeFileStream: fs.ReadStream | undefined;
1648
+ const { signal } = requestState;
1649
+ const limiter = this.requestLimiter;
1650
+
1651
+ try {
1652
+ requestState.checkDeadline();
1653
+ releaseRequestSlot = await limiter.acquire(
1654
+ normalizedConfig.hostname,
1655
+ normalizedConfig.ip,
1656
+ {
1657
+ signal,
1658
+ onLog: (level, event, fields) =>
1659
+ this.writeNativeLog(level, event, fields),
1660
+ }
1661
+ );
1662
+ requestState.checkDeadline();
1663
+ } catch (error) {
1664
+ releaseRequestSlot?.();
1665
+ releaseRequestSlot = undefined;
1666
+ this.removeRequestState(requestState, undefined, undefined);
1667
+ const stats = this.requestLimiter.snapshot(
1668
+ normalizedConfig.hostname,
1669
+ normalizedConfig.ip
1670
+ );
1671
+ this.writeNativeLog('error', 'desktop_sni_request_failed', {
1672
+ code: getErrorCode(error) ?? 'SNI_RESOURCE_LIMIT',
1673
+ failClosed: isSniFailClosedError(error),
1674
+ hostname: normalizedConfig.hostname,
1675
+ ip: normalizedConfig.ip,
1676
+ ipFamily: getIpFamily(normalizedConfig.ip),
1677
+ method: normalizedConfig.method,
1678
+ timeout: normalizedConfig.timeout,
1679
+ pathBytes: byteSize(normalizedConfig.path),
1680
+ bodyBytes: getBodyBytes(normalizedConfig),
1681
+ headerCount: Object.keys(normalizedConfig.headers).length,
1682
+ activeRequests: stats.activeRequests,
1683
+ activeRequestsForPair: stats.activeRequestsForPair,
1684
+ pendingRequests: stats.pendingRequests,
1685
+ pendingRequestsForPair: stats.pendingRequestsForPair,
1686
+ durationMs: Date.now() - startedAt,
1687
+ errorMessage: getErrorMessage(error),
1688
+ });
1689
+ return Promise.reject(error);
1690
+ }
1691
+
1692
+ return new Promise((resolve, reject) => {
1693
+ let settled = false;
1694
+ let responseStarted = false;
1695
+ const cleanup = () => {
1696
+ signal.removeEventListener('abort', onAbort);
1697
+ // Close through the handle first so the file slot tracks its close
1698
+ // Promise even when destroying the stream initiates descriptor cleanup.
1699
+ bodyFile?.close();
1700
+ activeFileStream?.destroy();
1701
+ this.removeRequestState(requestState, activeRequest, activeAgentState);
1702
+ releaseRequestSlot?.();
1703
+ };
1704
+
1705
+ const settleReject = (error: Error) => {
1706
+ if (settled) return;
1707
+ settled = true;
1708
+ activeRequest?.destroy();
1709
+ cleanup();
1710
+ const stats = limiter.snapshot(
1711
+ normalizedConfig.hostname,
1712
+ normalizedConfig.ip
1713
+ );
1714
+ this.writeNativeLog('error', 'desktop_sni_request_failed', {
1715
+ code: getErrorCode(error) ?? 'SNI_REQUEST_FAILED',
1716
+ failClosed: isSniFailClosedError(error),
1717
+ hostname: normalizedConfig.hostname,
1718
+ ip: normalizedConfig.ip,
1719
+ ipFamily: getIpFamily(normalizedConfig.ip),
1720
+ method: normalizedConfig.method,
1721
+ timeout: normalizedConfig.timeout,
1722
+ pathBytes: byteSize(normalizedConfig.path),
1723
+ bodyBytes: getBodyBytes(normalizedConfig),
1724
+ headerCount: Object.keys(normalizedConfig.headers).length,
1725
+ activeRequests: stats.activeRequests,
1726
+ activeRequestsForPair: stats.activeRequestsForPair,
1727
+ pendingRequests: stats.pendingRequests,
1728
+ pendingRequestsForPair: stats.pendingRequestsForPair,
1729
+ durationMs: Date.now() - startedAt,
1730
+ errorMessage: error.message,
1731
+ });
1732
+ reject(error);
1733
+ };
1734
+
1735
+ const settleResolve = (response: SniNodeResponse) => {
1736
+ if (settled) return;
1737
+ settled = true;
1738
+ if (bodyFile && activeRequest && !activeRequest.writableEnded) {
1739
+ activeRequest.destroy();
1740
+ }
1741
+ cleanup();
1742
+ this.writeNativeLog('info', 'desktop_sni_request_result', {
1743
+ result: 'response',
1744
+ status: response.statusCode,
1745
+ hostname: normalizedConfig.hostname,
1746
+ ip: normalizedConfig.ip,
1747
+ ipFamily: getIpFamily(normalizedConfig.ip),
1748
+ method: normalizedConfig.method,
1749
+ timeout: normalizedConfig.timeout,
1750
+ responseBytes: response.body ? byteSize(response.body) : 0,
1751
+ durationMs: Date.now() - startedAt,
1752
+ });
1753
+ resolve(response);
1754
+ };
1755
+
1756
+ const onAbort = () => settleReject(signal.reason);
1757
+ signal.addEventListener('abort', onAbort, { once: true });
1758
+
1759
+ try {
1760
+ activeAgentState = this.agentState;
1761
+ const requestOptions = buildSniRequestOptions(
1762
+ normalizedConfig,
1763
+ activeAgentState.agent
1764
+ );
1765
+
1766
+ const request = https.request(requestOptions, (response) => {
1767
+ responseStarted = true;
1768
+ response.on('error', (error: Error) => {
1769
+ settleReject(
1770
+ error instanceof SniRequestError
1771
+ ? error
1772
+ : new SniRequestError(
1773
+ 'SNI_RESPONSE_FAILED',
1774
+ `Response stream error: ${error.message}`,
1775
+ true
1776
+ )
1777
+ );
1778
+ });
1779
+
1780
+ if (settled) {
1781
+ response.destroy();
1782
+ return;
1783
+ }
1784
+ const encoding = response.headers['content-encoding'];
1785
+ if (encoding && encoding !== 'identity') {
1786
+ settleReject(
1787
+ new SniRequestError(
1788
+ 'SNI_RESPONSE_FAILED',
1789
+ `Unsupported content encoding: ${String(encoding)}`,
1790
+ true
1791
+ )
1792
+ );
1793
+ return;
1794
+ }
1795
+
1796
+ const chunks: Buffer[] = [];
1797
+ let totalBytes = 0;
1798
+ response.on('data', (chunk: Buffer | string) => {
1799
+ if (settled) return;
1800
+ const buffer = Buffer.isBuffer(chunk)
1801
+ ? chunk
1802
+ : Buffer.from(chunk, 'utf8');
1803
+ totalBytes += buffer.length;
1804
+ if (totalBytes > MAX_RESPONSE_BODY_BYTES) {
1805
+ settleReject(
1806
+ new SniRequestError(
1807
+ 'SNI_RESPONSE_FAILED',
1808
+ 'Response body too large',
1809
+ true
1810
+ )
1811
+ );
1812
+ return;
1813
+ }
1814
+ chunks.push(buffer);
1815
+ });
1816
+
1817
+ response.on('end', () => {
1818
+ if (settled) return;
1819
+ const headerMaps = headersToMaps(response.rawHeaders ?? []);
1820
+ const body = Buffer.concat(chunks).toString('utf8');
1821
+ const statusCode = response.statusCode || 0;
1822
+ settleResolve({
1823
+ statusCode,
1824
+ status: statusCode,
1825
+ statusText: response.statusMessage || '',
1826
+ headers: headerMaps.headers,
1827
+ multiValueHeaders: headerMaps.multiValueHeaders,
1828
+ body,
1829
+ data: body,
1830
+ });
1831
+ });
1832
+ });
1833
+ activeRequest = request;
1834
+ this.allActiveRequests.add(request);
1835
+ activeAgentState.activeRequests.add(request);
1836
+ this.requestAgentStates.set(request, activeAgentState);
1837
+ request.on('error', (error: Error) => {
1838
+ settleReject(classifyTransportError(error, Boolean(bodyFile)));
1839
+ });
1840
+
1841
+ request.once('upgrade', (_response, socket) => {
1842
+ socket.destroy();
1843
+ settleReject(
1844
+ new SniRequestError(
1845
+ 'SNI_SECURITY_POLICY_FAILED',
1846
+ 'Protocol upgrades are not supported',
1847
+ true
1848
+ )
1849
+ );
1850
+ });
1851
+ request.once('close', () => {
1852
+ if (settled) return;
1853
+ settleReject(
1854
+ new SniRequestError(
1855
+ responseStarted ? 'SNI_RESPONSE_FAILED' : 'SNI_REQUEST_FAILED',
1856
+ 'Request closed before completion',
1857
+ responseStarted
1858
+ )
1859
+ );
1860
+ });
1861
+
1862
+ const stats = limiter.snapshot(
1863
+ normalizedConfig.hostname,
1864
+ normalizedConfig.ip
1865
+ );
1866
+ this.writeNativeLog('info', 'desktop_sni_request_start', {
1867
+ requestId: normalizedConfig.requestId,
1868
+ hostname: normalizedConfig.hostname,
1869
+ ip: normalizedConfig.ip,
1870
+ ipFamily: getIpFamily(normalizedConfig.ip),
1871
+ method: normalizedConfig.method,
1872
+ timeout: normalizedConfig.timeout,
1873
+ pathBytes: byteSize(normalizedConfig.path),
1874
+ bodyBytes: getBodyBytes(normalizedConfig),
1875
+ headerCount: Object.keys(normalizedConfig.headers).length,
1876
+ activeRequests: stats.activeRequests,
1877
+ activeRequestsForPair: stats.activeRequestsForPair,
1878
+ pendingRequests: stats.pendingRequests,
1879
+ pendingRequestsForPair: stats.pendingRequestsForPair,
1880
+ });
1881
+
1882
+ if (settled) return;
1883
+ if (bodyFile) {
1884
+ // Stream the validated object and cap reads at the declared length.
1885
+ const fileStream = bodyFile.handle.createReadStream({
1886
+ start: 0,
1887
+ end: bodyFile.sizeBytes - 1,
1888
+ autoClose: false,
1889
+ });
1890
+ activeFileStream = fileStream;
1891
+ const rejectFileRead = () =>
1892
+ settleReject(
1893
+ new SniRequestError(
1894
+ 'SNI_FILE_READ_FAILED',
1895
+ 'Upload file read failed',
1896
+ true
1897
+ )
1898
+ );
1899
+ fileStream.on('error', rejectFileRead);
1900
+ let bytesRead = 0;
1901
+ let fileEnded = false;
1902
+ let bytesSent = 0;
1903
+ let lastProgressAt = 0;
1904
+ const sendProgress = () => {
1905
+ if (
1906
+ !normalizedConfig.requestId ||
1907
+ settled ||
1908
+ requestState.settled
1909
+ ) {
1910
+ return;
1911
+ }
1912
+ const now = Date.now();
1913
+ if (bytesSent < bodyFile.sizeBytes && now - lastProgressAt < 100) {
1914
+ return;
1915
+ }
1916
+ lastProgressAt = now;
1917
+ this.options.onUploadProgress?.({
1918
+ requestId: normalizedConfig.requestId,
1919
+ bytesSent,
1920
+ totalBytes: bodyFile.sizeBytes,
1921
+ progressPercent: Math.min(
1922
+ 99,
1923
+ Math.floor((bytesSent / bodyFile.sizeBytes) * 100)
1924
+ ),
1925
+ });
1926
+ };
1927
+ fileStream.on('data', (chunk: Buffer | string) => {
1928
+ if (settled) return;
1929
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1930
+ bytesRead += bytes.length;
1931
+ fileStream.pause();
1932
+ request.write(bytes, (error?: Error | null) => {
1933
+ if (settled || requestState.settled) return;
1934
+ if (error) {
1935
+ settleReject(classifyTransportError(error, true));
1936
+ return;
1937
+ }
1938
+ bytesSent += bytes.length;
1939
+ if (requestState.uploadProgress) {
1940
+ requestState.uploadProgress = {
1941
+ bytesSent,
1942
+ totalBytes: bodyFile.sizeBytes,
1943
+ };
1944
+ }
1945
+ try {
1946
+ sendProgress();
1947
+ } catch {
1948
+ /* Progress must not fail upload. */
1949
+ }
1950
+ if (fileEnded) {
1951
+ request.end();
1952
+ } else {
1953
+ fileStream.resume();
1954
+ }
1955
+ });
1956
+ });
1957
+ fileStream.on('end', () => {
1958
+ if (settled) return;
1959
+ if (bytesRead !== bodyFile.sizeBytes) {
1960
+ rejectFileRead();
1961
+ return;
1962
+ }
1963
+ fileEnded = true;
1964
+ if (bytesSent === bytesRead) request.end();
1965
+ });
1966
+ return;
1967
+ }
1968
+
1969
+ if (normalizedConfig.body) {
1970
+ request.write(normalizedConfig.body);
1971
+ }
1972
+
1973
+ request.end();
1974
+ } catch (error) {
1975
+ settleReject(error instanceof Error ? error : new Error(String(error)));
1976
+ }
1977
+ });
1978
+ }
1979
+
1980
+ async cancelRequest(requestId: string): Promise<{ success: boolean }> {
1981
+ const requestState = this.requestsById.get(requestId);
1982
+ if (!requestState) {
1983
+ this.writeNativeLog('warn', 'desktop_sni_lifecycle', {
1984
+ action: 'cancel_request',
1985
+ requestId,
1986
+ success: false,
1987
+ activeCount: this.allActiveRequests.size,
1988
+ pendingCount: this.requestLimiter.snapshot().pendingRequests,
1989
+ });
1990
+ return { success: false };
1991
+ }
1992
+ this.requestsById.delete(requestId);
1993
+ requestState.cancel(
1994
+ new SniRequestError('SNI_CANCELLED', 'Request cancelled', true)
1995
+ );
1996
+ this.writeNativeLog('info', 'desktop_sni_lifecycle', {
1997
+ action: 'cancel_request',
1998
+ requestId,
1999
+ success: true,
2000
+ activeCount: this.allActiveRequests.size,
2001
+ pendingCount: this.requestLimiter.snapshot().pendingRequests,
2002
+ });
2003
+ return { success: true };
2004
+ }
2005
+
2006
+ async getDebugSnapshot({
2007
+ hostname,
2008
+ ip,
2009
+ }: Pick<
2010
+ SniNodeRequestConfig,
2011
+ 'hostname' | 'ip'
2012
+ >): Promise<SniNodeDebugSnapshot> {
2013
+ validateHostname(hostname);
2014
+ validatePublicIp(ip);
2015
+ return this.requestLimiter.snapshot(hostname, ip);
2016
+ }
2017
+
2018
+ async cancelAllRequests(): Promise<{ success: boolean }> {
2019
+ const requests = Array.from(this.allRequests);
2020
+ this.requestsById.clear();
2021
+ this.allRequests.clear();
2022
+ for (const request of requests) {
2023
+ request.cancel(
2024
+ new SniRequestError('SNI_CANCELLED', 'Request cancelled', true)
2025
+ );
2026
+ }
2027
+ this.writeNativeLog('info', 'desktop_sni_lifecycle', {
2028
+ action: 'cancel_all_requests',
2029
+ success: true,
2030
+ requestCount: requests.length,
2031
+ activeCount: this.allActiveRequests.size,
2032
+ pendingCount: this.requestLimiter.snapshot().pendingRequests,
2033
+ });
2034
+ return { success: true };
2035
+ }
2036
+
2037
+ async clearDNSCache(): Promise<{ success: boolean }> {
2038
+ const previousAgentState = this.agentState;
2039
+ this.agentState = createAgentState();
2040
+ const previousAgent = previousAgentState.agent;
2041
+ previousAgent.keepSocketAlive = () => false;
2042
+ for (const sockets of Object.values(previousAgent.freeSockets)) {
2043
+ sockets?.forEach((socket) => socket.destroy());
2044
+ }
2045
+ this.maybeDestroyIdleAgentState(previousAgentState);
2046
+ this.writeNativeLog('info', 'desktop_sni_lifecycle', {
2047
+ action: 'clear_dns_cache',
2048
+ success: true,
2049
+ activeCount: previousAgentState.activeRequests.size,
2050
+ });
2051
+ return { success: true };
2052
+ }
2053
+
2054
+ async isSupported(): Promise<boolean> {
2055
+ return true;
2056
+ }
2057
+ }
2058
+
2059
+ export default SniNodeClient;