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

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,1395 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.SniRequestLimiter = exports.SniRequestError = exports.SniNodeClient = exports.DEFAULT_LOGGER_UPLOAD_PATH = exports.DEFAULT_LOGGER_UPLOAD_ORIGINS = void 0;
7
+ exports.buildSniRequestOptions = buildSniRequestOptions;
8
+ exports.canonicalizeSniDestinationIp = canonicalizeSniDestinationIp;
9
+ exports.classifyTransportError = classifyTransportError;
10
+ exports.default = void 0;
11
+ exports.formatNativeLogEvent = formatNativeLogEvent;
12
+ exports.getProxyRuleType = getProxyRuleType;
13
+ exports.headersToMaps = headersToMaps;
14
+ exports.isProxyRouteActive = isProxyRouteActive;
15
+ exports.isSniFailClosedError = isSniFailClosedError;
16
+ exports.redactIpLiterals = redactIpLiterals;
17
+ exports.safeSniLogValue = safeSniLogValue;
18
+ exports.sanitizeSniDiagnosticText = sanitizeSniDiagnosticText;
19
+ exports.validatePublicIp = validatePublicIp;
20
+ exports.validateSniRequestConfig = validateSniRequestConfig;
21
+ exports.validateSniUploadFileConfig = validateSniUploadFileConfig;
22
+ var fs = _interopRequireWildcard(require("fs"));
23
+ var fsPromises = _interopRequireWildcard(require("fs/promises"));
24
+ var _https = _interopRequireDefault(require("https"));
25
+ var nodePath = _interopRequireWildcard(require("path"));
26
+ var _url = require("url");
27
+ function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
28
+ function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
29
+ const MAX_REQUEST_ID_BYTES = 128;
30
+ const MAX_TIMEOUT_MS = 120_000;
31
+ const MAX_PATH_BYTES = 8 * 1024;
32
+ const MAX_REQUEST_BODY_BYTES = 1024 * 1024;
33
+ const MAX_UPLOAD_FILE_BYTES = 20 * 1024 * 1024;
34
+ const MAX_OPEN_UPLOAD_FILES = 64;
35
+ const MAX_RESPONSE_BODY_BYTES = 10 * 1024 * 1024;
36
+ const MAX_HEADER_COUNT = 64;
37
+ const MAX_HEADER_NAME_BYTES = 128;
38
+ const MAX_HEADER_VALUE_BYTES = 8 * 1024;
39
+ const MAX_TOTAL_HEADER_BYTES = 32 * 1024;
40
+ const MAX_TOTAL_SOCKETS = 64;
41
+ const MAX_SOCKETS_PER_PAIR = 16;
42
+ const MAX_FREE_SOCKETS = 32;
43
+ const MAX_ACTIVE_REQUESTS = 64;
44
+ const MAX_ACTIVE_REQUESTS_PER_PAIR = 16;
45
+ const MAX_PENDING_REQUESTS = 256;
46
+ const MAX_DIAGNOSTIC_TEXT_LENGTH = 120;
47
+ const UPLOAD_FILE_METHODS = new Set(['POST', 'PUT']);
48
+ const DEFAULT_LOGGER_UPLOAD_PATH = exports.DEFAULT_LOGGER_UPLOAD_PATH = '/wallet/v1/client/log';
49
+ const DEFAULT_LOGGER_UPLOAD_ORIGINS = exports.DEFAULT_LOGGER_UPLOAD_ORIGINS = new Set(['https://wallet.onekeycn.com', 'https://wallet.onekeytest.com']);
50
+ const ALLOWED_METHODS = new Set(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS']);
51
+ const MODULE_OWNED_HEADERS = new Set(['host', 'content-length', 'accept-encoding', 'x-emascurl-config-id']);
52
+ const UNSAFE_HEADERS = new Set(['connection', 'keep-alive', 'te', 'trailer', 'transfer-encoding', 'upgrade', 'expect']);
53
+ const HOSTNAME_RE = /^(?=.{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])?)*$/;
54
+ const SCHEME_RE = /^[A-Za-z][A-Za-z0-9+.-]*:/;
55
+ const HEADER_TOKEN_RE = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
56
+ const IPV4_DOTTED_RE = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
57
+ const HEX_GROUP_RE = /^[0-9A-Fa-f]{1,4}$/;
58
+ const IPV4_LOG_RE = /(^|[^\d.])((?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3})(?=$|[^\d.])/g;
59
+ const IPV4_LITERAL_LOG_RE = /^(?:25[0-5]|2[0-4]\d|1?\d?\d)(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
60
+ // An IPv6 literal with an embedded IPv4 address is at most 45 characters.
61
+ // Bound both scans before validating candidate addresses for log redaction.
62
+ const BRACKETED_IPV6_LOG_RE = /\[([0-9A-Fa-f:.]{1,45})\](?=$|:\d{1,5}\b|[^0-9A-Fa-f:.\]])/g;
63
+ const IPV6_CANDIDATE_LOG_RE = /(^|[^0-9A-Fa-f:.[])(\[?[0-9A-Fa-f:.]{1,45}\]?)(?=$|[^0-9A-Fa-f:.\]])/g;
64
+ const SNI_FAIL_CLOSED_ERROR_CODES = new Set(['SNI_INVALID_CONFIG', 'SNI_SECURITY_POLICY_FAILED', 'SNI_TLS_FAILED', 'SNI_CERT_FAILED', 'SNI_RESPONSE_FAILED', 'SNI_RESOURCE_LIMIT', 'SNI_CANCELLED']);
65
+ const SNI_FAIL_CLOSED_MESSAGE_RE = /\bSNI_(INVALID_CONFIG|SECURITY_POLICY_FAILED|TLS_FAILED|CERT_FAILED|RESPONSE_FAILED|RESOURCE_LIMIT|CANCELLED)\b/;
66
+ const SniRequestErrorClass = class SniRequestError extends Error {
67
+ constructor(code, message, failClosed = false) {
68
+ super(`${code}: ${message}`);
69
+ this.name = 'SniRequestError';
70
+ this.code = code;
71
+ this.failClosed = failClosed;
72
+ }
73
+ };
74
+ const requestErrorKey = Symbol.for('@onekeyfe/react-native-sni-connect.requestError');
75
+ const processWithSniError = process;
76
+
77
+ // Admission is process-shared, and either Node entry can consume its errors.
78
+ const SniRequestError = exports.SniRequestError = processWithSniError[requestErrorKey] ??= SniRequestErrorClass;
79
+ function isSniFailClosedError(error) {
80
+ const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : '';
81
+ if (SNI_FAIL_CLOSED_ERROR_CODES.has(code)) {
82
+ return true;
83
+ }
84
+ const message = error instanceof Error ? error.message : String(error);
85
+ return SNI_FAIL_CLOSED_MESSAGE_RE.test(message);
86
+ }
87
+ function isLikelyIpv6Literal(candidate) {
88
+ const value = candidate.startsWith('[') && candidate.endsWith(']') ? candidate.slice(1, -1) : candidate;
89
+ if (!value.includes(':')) return false;
90
+ const parts = value.split(':');
91
+ const doubleColonCount = value.split('::').length - 1;
92
+ if (doubleColonCount > 1 || value.includes(':::') || !/^[0-9A-Fa-f:.]+$/.test(value)) {
93
+ return false;
94
+ }
95
+ const hasDoubleColon = value.includes('::');
96
+ const hasEmbeddedIpv4 = value.includes('.');
97
+ const groupCount = parts.reduce((count, part, index) => {
98
+ if (part === '') return count;
99
+ if (part.includes('.')) {
100
+ return index === parts.length - 1 && IPV4_LITERAL_LOG_RE.test(part) ? count + 2 : Number.POSITIVE_INFINITY;
101
+ }
102
+ return HEX_GROUP_RE.test(part) ? count + 1 : Number.POSITIVE_INFINITY;
103
+ }, 0);
104
+ if (!Number.isFinite(groupCount)) return false;
105
+ const lastPart = parts[parts.length - 1] ?? '';
106
+ if (hasEmbeddedIpv4 && !IPV4_LITERAL_LOG_RE.test(lastPart)) {
107
+ return false;
108
+ }
109
+ return hasDoubleColon ? groupCount < 8 : groupCount === 8;
110
+ }
111
+ function redactIpLiterals(value) {
112
+ return value.replace(BRACKETED_IPV6_LOG_RE, (match, candidate) => isLikelyIpv6Literal(candidate) ? '<ip6>' : match).replace(IPV6_CANDIDATE_LOG_RE, (_match, prefix, candidate) => isLikelyIpv6Literal(candidate) ? `${prefix}<ip6>` : `${prefix}${candidate}`).replace(IPV4_LOG_RE, '$1<ip>');
113
+ }
114
+ function sanitizeSniDiagnosticText(value, maxLength = MAX_DIAGNOSTIC_TEXT_LENGTH) {
115
+ // eslint-disable-next-line no-control-regex
116
+ const singleLine = value.replace(/[\u0000-\u001f\u007f]+/g, ' ').trim();
117
+ const redacted = redactIpLiterals(singleLine);
118
+ return redacted.length > maxLength ? redacted.slice(0, maxLength) : redacted;
119
+ }
120
+ function safeSniLogValue(value) {
121
+ if (value === null || value === undefined) return 'none';
122
+ return redactIpLiterals(String(value)).replace(/[\r\n\s]+/g, '_');
123
+ }
124
+ function formatNativeLogEvent(event, fields) {
125
+ return Object.entries({
126
+ event,
127
+ ...fields
128
+ }).map(([key, value]) => {
129
+ const logValue = key === 'requestId' || key === 'ip' || key === 'requestedHost' ? String(value ?? 'none').replace(/[\r\n\s]+/g, '_') : safeSniLogValue(value);
130
+ // Keep long diagnostic IDs recoverable without matching the logger's private-key filter.
131
+ let displayedValue = logValue;
132
+ let formatSuffix = '';
133
+ if (key === 'requestId' && typeof value === 'string' && (value !== logValue || /[0-9a-fA-F]{64}/.test(value))) {
134
+ displayedValue = encodeURIComponent(Buffer.from(value, 'utf8').toString('utf8')).replace(/[!'()*~-]/g, character => `%${character.charCodeAt(0).toString(16).toUpperCase()}`).replace(/([0-9a-fA-F]{32})(?=[0-9a-fA-F]{32})/g, '$1-');
135
+ formatSuffix = ' requestIdFormat=uri-hex32';
136
+ }
137
+ return `${key}=${displayedValue}${formatSuffix}`;
138
+ }).join(' ');
139
+ }
140
+ function emitNativeLog(logger, logPrefix, level, event, fields) {
141
+ if (!logger) return;
142
+ const message = `${logPrefix} ${formatNativeLogEvent(event, fields)}`;
143
+ if (level === 'error') {
144
+ logger.error?.(message);
145
+ } else if (level === 'warn') {
146
+ logger.warn?.(message);
147
+ } else {
148
+ logger.info?.(message);
149
+ }
150
+ }
151
+ function getErrorCode(error) {
152
+ if (error && typeof error === 'object' && 'code' in error) {
153
+ const code = error.code;
154
+ if (typeof code === 'string') return code;
155
+ }
156
+ return undefined;
157
+ }
158
+ function getErrorMessage(error) {
159
+ return error instanceof Error ? error.message : String(error);
160
+ }
161
+ function getIpFamily(ip) {
162
+ return ip.includes(':') ? 'ipv6' : 'ipv4';
163
+ }
164
+
165
+ /* eslint-disable no-bitwise */
166
+ function parseIpv4Octets(ip) {
167
+ const match = IPV4_DOTTED_RE.exec(ip);
168
+ if (!match) return null;
169
+ const rawOctets = [match[1], match[2], match[3], match[4]];
170
+ const octets = [];
171
+ for (const part of rawOctets) {
172
+ if (!part || part.length > 1 && part.startsWith('0')) {
173
+ return null;
174
+ }
175
+ const value = Number(part);
176
+ if (!Number.isInteger(value) || value < 0 || value > 255) {
177
+ return null;
178
+ }
179
+ octets.push(value);
180
+ }
181
+ return [octets[0] ?? 0, octets[1] ?? 0, octets[2] ?? 0, octets[3] ?? 0];
182
+ }
183
+ function parseHexGroups(groups) {
184
+ const result = [];
185
+ for (const group of groups) {
186
+ if (!HEX_GROUP_RE.test(group)) {
187
+ return null;
188
+ }
189
+ result.push(parseInt(group, 16));
190
+ }
191
+ return result;
192
+ }
193
+ function parseIpv6Parts(ip) {
194
+ if (!ip || !ip.includes(':') || ip.includes('[') || ip.includes(']') || ip.includes('%') || ip.trim() !== ip) {
195
+ return null;
196
+ }
197
+ let normalizedIp = ip;
198
+ if (normalizedIp.includes('.')) {
199
+ const lastColon = normalizedIp.lastIndexOf(':');
200
+ if (lastColon < 0) return null;
201
+ const ipv4Octets = parseIpv4Octets(normalizedIp.slice(lastColon + 1));
202
+ if (!ipv4Octets) return null;
203
+ const high = (ipv4Octets[0] << 8 | ipv4Octets[1]).toString(16);
204
+ const low = (ipv4Octets[2] << 8 | ipv4Octets[3]).toString(16);
205
+ normalizedIp = `${normalizedIp.slice(0, lastColon + 1)}${high}:${low}`;
206
+ }
207
+ const doubleColonSides = normalizedIp.split('::');
208
+ if (doubleColonSides.length > 2) {
209
+ return null;
210
+ }
211
+ if (doubleColonSides.length === 1) {
212
+ const groups = normalizedIp.split(':');
213
+ if (groups.length !== 8) return null;
214
+ return parseHexGroups(groups);
215
+ }
216
+ const leftRaw = doubleColonSides[0] ?? '';
217
+ const rightRaw = doubleColonSides[1] ?? '';
218
+ const leftGroups = leftRaw === '' ? [] : leftRaw.split(':');
219
+ const rightGroups = rightRaw === '' ? [] : rightRaw.split(':');
220
+ if (leftGroups.length + rightGroups.length >= 8) {
221
+ return null;
222
+ }
223
+ const leftNums = parseHexGroups(leftGroups);
224
+ const rightNums = parseHexGroups(rightGroups);
225
+ if (!leftNums || !rightNums) {
226
+ return null;
227
+ }
228
+ const zeroFill = new Array(8 - leftNums.length - rightNums.length).fill(0);
229
+ return [...leftNums, ...zeroFill, ...rightNums];
230
+ }
231
+ function isIpv4MappedParts(parts) {
232
+ return parts.length === 8 && parts[0] === 0 && parts[1] === 0 && parts[2] === 0 && parts[3] === 0 && parts[4] === 0 && parts[5] === 0xffff;
233
+ }
234
+ function isIpLiteral(value) {
235
+ return parseIpv4Octets(value) !== null || parseIpv6Parts(value) !== null;
236
+ }
237
+ function canonicalizeSniDestinationIp(ip) {
238
+ const ipv4 = parseIpv4Octets(ip);
239
+ if (ipv4) {
240
+ return `${ipv4[0]}.${ipv4[1]}.${ipv4[2]}.${ipv4[3]}`;
241
+ }
242
+ const ipv6Parts = parseIpv6Parts(ip);
243
+ if (!ipv6Parts) {
244
+ return ip;
245
+ }
246
+ if (isIpv4MappedParts(ipv6Parts)) {
247
+ const part6 = ipv6Parts[6] ?? 0;
248
+ const part7 = ipv6Parts[7] ?? 0;
249
+ return `${part6 >> 8 & 0xff}.${part6 & 0xff}.${part7 >> 8 & 0xff}.${part7 & 0xff}`;
250
+ }
251
+ return ipv6Parts.map(part => part.toString(16)).join(':');
252
+ }
253
+ function getProxyRuleType(proxyRules) {
254
+ const rules = proxyRules.split(';').map(rule => rule.trim()).filter(Boolean).map(rule => rule.toUpperCase());
255
+ if (rules.length === 0) return 'unknown';
256
+ const directCount = rules.filter(rule => rule === 'DIRECT').length;
257
+ if (directCount === rules.length) return 'direct';
258
+ if (directCount === 0) return 'proxy';
259
+ return 'mixed';
260
+ }
261
+ function getHostnameForLog(url) {
262
+ try {
263
+ return new URL(url).hostname;
264
+ } catch {
265
+ return 'unknown';
266
+ }
267
+ }
268
+ function invalidConfig(message) {
269
+ throw new SniRequestError('SNI_INVALID_CONFIG', message, true);
270
+ }
271
+ function classifyTransportError(error, isUpload = false) {
272
+ if (error instanceof SniRequestError) {
273
+ return error;
274
+ }
275
+ const code = error && typeof error === 'object' && 'code' in error ? String(error.code) : '';
276
+ const message = `${code} ${error.message}`;
277
+ if (/CERT|certificate|altname|hostname|self[- ]?signed|unable to verify|expired/i.test(message)) {
278
+ return new SniRequestError('SNI_CERT_FAILED', error.message, true);
279
+ }
280
+ if (/TLS|SSL|handshake|EPROTO/i.test(message)) {
281
+ return new SniRequestError('SNI_TLS_FAILED', error.message, true);
282
+ }
283
+ if (isUpload) {
284
+ if (/\bECONNREFUSED\b/i.test(message)) {
285
+ return new SniRequestError('SNI_CONNECTION_REFUSED', error.message);
286
+ }
287
+ if (/\b(?:ENOTFOUND|EAI_AGAIN)\b/i.test(message)) {
288
+ return new SniRequestError('SNI_DNS_FAILED', error.message);
289
+ }
290
+ if (/\b(?:ENETUNREACH|EHOSTUNREACH)\b/i.test(message)) {
291
+ return new SniRequestError('SNI_NETWORK_UNREACHABLE', error.message);
292
+ }
293
+ }
294
+ return error;
295
+ }
296
+ function byteSize(value) {
297
+ return Buffer.byteLength(value, 'utf8');
298
+ }
299
+ function hasControlChar(value) {
300
+ for (let index = 0; index < value.length; index += 1) {
301
+ const code = value.charCodeAt(index);
302
+ if (code <= 0x1f || code === 0x7f) return true;
303
+ }
304
+ return false;
305
+ }
306
+ function normalizeMethod(method) {
307
+ if (hasControlChar(method)) {
308
+ invalidConfig(`Invalid method: ${method}`);
309
+ }
310
+ const normalized = method.trim().toUpperCase();
311
+ if (!ALLOWED_METHODS.has(normalized)) {
312
+ invalidConfig(`Invalid method: ${method}`);
313
+ }
314
+ return normalized;
315
+ }
316
+ function normalizePath(path) {
317
+ const trimmed = path.trim();
318
+ if (byteSize(trimmed) > MAX_PATH_BYTES) {
319
+ invalidConfig('Path too large');
320
+ }
321
+ if (hasControlChar(trimmed) || trimmed.startsWith('//') || trimmed.includes('://') || SCHEME_RE.test(trimmed.split('/')[0] ?? '')) {
322
+ invalidConfig('Invalid path');
323
+ }
324
+ if (!trimmed) return '/';
325
+ return trimmed.startsWith('/') ? trimmed : `/${trimmed}`;
326
+ }
327
+ function validateHostname(hostname) {
328
+ if (!HOSTNAME_RE.test(hostname) || /^\d+\.\d+\.\d+\.\d+$/.test(hostname) || isIpLiteral(hostname)) {
329
+ invalidConfig(`Invalid hostname: ${hostname}`);
330
+ }
331
+ }
332
+ function validateRequestId(requestId) {
333
+ if (requestId === undefined) return;
334
+ if (!requestId || hasControlChar(requestId) || byteSize(requestId) > MAX_REQUEST_ID_BYTES) {
335
+ invalidConfig('Invalid requestId');
336
+ }
337
+ }
338
+ function validateTimeout(timeout) {
339
+ if (!Number.isFinite(timeout) || timeout < 1 || timeout > MAX_TIMEOUT_MS) {
340
+ invalidConfig(`Invalid timeout: ${timeout}`);
341
+ }
342
+ }
343
+ function validateBody(body) {
344
+ if (body !== null) {
345
+ if (typeof body !== 'string') invalidConfig('Invalid request body');
346
+ if (byteSize(body) > MAX_REQUEST_BODY_BYTES) {
347
+ invalidConfig('Request body too large');
348
+ }
349
+ }
350
+ }
351
+ function getBodyBytes(config) {
352
+ if (config.bodyFile) return config.bodyFile.sizeBytes;
353
+ return config.body ? byteSize(config.body) : 0;
354
+ }
355
+ function isPathInside(root, target) {
356
+ const relative = nodePath.relative(root, target);
357
+ return !!relative && !relative.startsWith('..') && !nodePath.isAbsolute(relative);
358
+ }
359
+ async function resolveAllowedUploadRoots(getAllowedUploadRoots, signal) {
360
+ if (!getAllowedUploadRoots) {
361
+ return [];
362
+ }
363
+ let candidates = [];
364
+ try {
365
+ candidates = await getAllowedUploadRoots();
366
+ } catch {
367
+ return [];
368
+ }
369
+ signal?.throwIfAborted();
370
+ const roots = await Promise.all(candidates.map(async candidate => {
371
+ try {
372
+ return await fsPromises.realpath(candidate);
373
+ } catch {
374
+ return undefined;
375
+ }
376
+ }));
377
+ return roots.filter(root => !!root);
378
+ }
379
+ async function statCanonicalUploadPath(realPath) {
380
+ try {
381
+ const stat = await fsPromises.lstat(realPath, {
382
+ bigint: true
383
+ });
384
+ if ((await fsPromises.realpath(realPath)) === realPath) return stat;
385
+ } catch {
386
+ invalidConfig('Upload file is not readable');
387
+ }
388
+ invalidConfig('Upload file path changed during validation');
389
+ }
390
+ function isSameFile(left, right) {
391
+ return left.isFile() && right.isFile() && left.dev === right.dev && left.ino === right.ino;
392
+ }
393
+ async function resolveUploadFile(config, options, signal) {
394
+ const {
395
+ filePath
396
+ } = config;
397
+ if (typeof filePath !== 'string' || !filePath || hasControlChar(filePath)) {
398
+ invalidConfig('Invalid filePath');
399
+ }
400
+ let absolutePath = filePath;
401
+ if (filePath.startsWith('file://')) {
402
+ try {
403
+ absolutePath = (0, _url.fileURLToPath)(filePath);
404
+ } catch {
405
+ invalidConfig('Invalid filePath');
406
+ }
407
+ }
408
+ if (!nodePath.isAbsolute(absolutePath)) {
409
+ invalidConfig('filePath must be absolute');
410
+ }
411
+ let realPath;
412
+ try {
413
+ realPath = await fsPromises.realpath(nodePath.resolve(absolutePath));
414
+ } catch {
415
+ invalidConfig('Upload file is not readable');
416
+ }
417
+ signal?.throwIfAborted();
418
+ const requiredExtension = options?.requiredFileExtension === undefined ? '.zip' : options.requiredFileExtension;
419
+ const requireDirectChild = options?.requireDirectChildOfRoot ?? true;
420
+ const roots = await resolveAllowedUploadRoots(options?.getAllowedUploadRoots, signal);
421
+ signal?.throwIfAborted();
422
+ const hasValidExtension = !requiredExtension || realPath.endsWith(requiredExtension);
423
+ const isInsideAllowedRoot = roots.some(root => requireDirectChild ? nodePath.dirname(realPath) === root && isPathInside(root, realPath) : isPathInside(root, realPath));
424
+ if (!hasValidExtension || !isInsideAllowedRoot) {
425
+ invalidConfig('Upload file is outside app storage');
426
+ }
427
+ const pathStat = await statCanonicalUploadPath(realPath);
428
+ if (!pathStat.isFile()) {
429
+ invalidConfig('Upload file is not a regular file');
430
+ }
431
+ const releaseFileSlot = await sharedUploadFileLimiter.acquire(config.hostname, config.ip, {
432
+ signal
433
+ });
434
+ let handle;
435
+ try {
436
+ signal?.throwIfAborted();
437
+ // Windows does not expose the optional Unix open flags. Identity is
438
+ // checked on every platform before accepting the file.
439
+ const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
440
+ handle = await fsPromises.open(realPath, flags);
441
+ } catch {
442
+ releaseFileSlot();
443
+ signal?.throwIfAborted();
444
+ invalidConfig('Upload file is not readable');
445
+ }
446
+ let closing;
447
+ const close = () => {
448
+ signal?.removeEventListener('abort', close);
449
+ return closing ??= handle.close().catch(() => undefined).finally(releaseFileSlot);
450
+ };
451
+ signal?.addEventListener('abort', close, {
452
+ once: true
453
+ });
454
+ try {
455
+ signal?.throwIfAborted();
456
+ const stat = await handle.stat({
457
+ bigint: true
458
+ }).catch(() => invalidConfig('Upload file is not readable'));
459
+ if (!isSameFile(stat, pathStat)) {
460
+ invalidConfig('Upload file path changed during validation');
461
+ }
462
+ if (stat.size < 1n || stat.size > BigInt(MAX_UPLOAD_FILE_BYTES)) {
463
+ invalidConfig(`Invalid upload file size: ${stat.size}`);
464
+ }
465
+ const sizeBytes = Number(stat.size);
466
+ signal?.throwIfAborted();
467
+ if (options?.verifyUploadFile) {
468
+ let verified;
469
+ try {
470
+ verified = await options.verifyUploadFile(realPath, sizeBytes);
471
+ } catch {
472
+ invalidConfig('Upload file verification failed');
473
+ }
474
+ signal?.throwIfAborted();
475
+ if (!verified) {
476
+ invalidConfig('Upload file was not collected by the main process');
477
+ }
478
+ }
479
+ const verifiedPathStat = await statCanonicalUploadPath(realPath);
480
+ if (!isSameFile(stat, verifiedPathStat) || stat.size !== verifiedPathStat.size) {
481
+ invalidConfig('Upload file changed during validation');
482
+ }
483
+ signal?.throwIfAborted();
484
+ return {
485
+ filePath: realPath,
486
+ sizeBytes,
487
+ handle,
488
+ close
489
+ };
490
+ } catch (error) {
491
+ await close();
492
+ throw error;
493
+ }
494
+ }
495
+ function normalizeSniUploadFileConfig(config, options) {
496
+ if (config.body !== undefined) {
497
+ invalidConfig('uploadFile does not accept a body');
498
+ }
499
+ const method = typeof config.method === 'string' ? config.method.trim().toUpperCase() : '';
500
+ if (!UPLOAD_FILE_METHODS.has(method)) {
501
+ invalidConfig(`Invalid upload method: ${String(config.method)}`);
502
+ }
503
+ const normalized = normalizeSniRequestConfig({
504
+ requestId: config.requestId,
505
+ ip: config.ip,
506
+ hostname: config.hostname,
507
+ path: config.path,
508
+ headers: config.headers,
509
+ method,
510
+ body: null,
511
+ timeout: config.timeout
512
+ });
513
+ const allowedOriginsInput = options?.allowedUploadOrigins === undefined ? DEFAULT_LOGGER_UPLOAD_ORIGINS : options.allowedUploadOrigins;
514
+ const allowedOrigins = allowedOriginsInput instanceof Set ? allowedOriginsInput : new Set(allowedOriginsInput);
515
+ const allowedPath = options?.allowedUploadPath === undefined ? DEFAULT_LOGGER_UPLOAD_PATH : options.allowedUploadPath;
516
+ if (!allowedOrigins.has(`https://${normalized.hostname.toLowerCase()}`) || allowedPath !== null && normalized.path !== allowedPath) {
517
+ invalidConfig('Upload destination is not allowed');
518
+ }
519
+ return normalized;
520
+ }
521
+ async function validateSniUploadFileConfig(config, options, signal) {
522
+ const normalized = normalizeSniUploadFileConfig(config, options);
523
+ const file = await resolveUploadFile(config, options, signal);
524
+ await file.close();
525
+ signal?.throwIfAborted();
526
+ return {
527
+ ...normalized,
528
+ bodyFile: {
529
+ filePath: file.filePath,
530
+ sizeBytes: file.sizeBytes
531
+ }
532
+ };
533
+ }
534
+ function ipv6BytesFromParts(parts) {
535
+ return parts.flatMap(part => [part >> 8 & 0xff, part & 0xff]);
536
+ }
537
+ function isForbiddenIpv4(octets) {
538
+ const a = octets[0] ?? 0;
539
+ const b = octets[1] ?? 0;
540
+ const c = octets[2] ?? 0;
541
+ return a === 0 || a === 10 || a === 127 || a === 100 && (b & 0xc0) === 0x40 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 192 && b === 0 && c === 0 || a === 192 && b === 0 && c === 2 || a === 198 && (b === 18 || b === 19) || a === 198 && b === 51 && c === 100 || a === 203 && b === 0 && c === 113 || a >= 224;
542
+ }
543
+ function embeddedIpv4(bytes, offset) {
544
+ return [bytes[offset] ?? 0, bytes[offset + 1] ?? 0, bytes[offset + 2] ?? 0, bytes[offset + 3] ?? 0];
545
+ }
546
+ function isForbiddenIpv6(parts) {
547
+ const bytes = ipv6BytesFromParts(parts);
548
+ if (isIpv4MappedParts(parts)) {
549
+ return isForbiddenIpv4(embeddedIpv4(bytes, 12));
550
+ }
551
+ const b0 = bytes[0] ?? 0;
552
+ const b1 = bytes[1] ?? 0;
553
+ const b2 = bytes[2] ?? 0;
554
+ const b3 = bytes[3] ?? 0;
555
+ const b4 = bytes[4] ?? 0;
556
+ const b5 = bytes[5] ?? 0;
557
+ if (b0 === 0x00 && b1 === 0x64 && b2 === 0xff && b3 === 0x9b) {
558
+ if (b4 === 0x00 && b5 === 0x01) {
559
+ return true;
560
+ }
561
+ if (bytes.slice(4, 12).every(b => b === 0)) {
562
+ return isForbiddenIpv4(embeddedIpv4(bytes, 12));
563
+ }
564
+ return true;
565
+ }
566
+ if ((b0 & 0xe0) !== 0x20 || (b0 & 0xfe) === 0xfc || b0 === 0x01 && b1 === 0x00 && bytes.slice(2, 8).every(b => b === 0) || b0 === 0x20 && b1 === 0x02 || bytes.slice(0, 12).every(b => b === 0)) {
567
+ return true;
568
+ }
569
+ if (b0 === 0x20 && b1 === 0x01) {
570
+ if (b2 === 0x00 && b3 === 0x00) return true;
571
+ if (b2 === 0x00 && (b3 & 0xf0) === 0x10) return true;
572
+ if (b2 === 0x00 && b3 === 0x02) return true;
573
+ if (b2 === 0x0d && b3 === 0xb8) return true;
574
+ }
575
+ return false;
576
+ }
577
+ /* eslint-enable no-bitwise */
578
+
579
+ function validatePublicIp(ip) {
580
+ if (!ip || ip.trim() !== ip || ip.includes('[') || ip.includes(']') || ip.includes('%')) {
581
+ invalidConfig(`Invalid IP: ${ip}`);
582
+ }
583
+ const ipv4Octets = parseIpv4Octets(ip);
584
+ if (ipv4Octets) {
585
+ if (isForbiddenIpv4(ipv4Octets)) {
586
+ invalidConfig(`Forbidden IP: ${ip}`);
587
+ }
588
+ return;
589
+ }
590
+ const ipv6Parts = parseIpv6Parts(ip);
591
+ if (!ipv6Parts) {
592
+ invalidConfig(`Invalid IP: ${ip}`);
593
+ }
594
+ if (isForbiddenIpv6(ipv6Parts)) {
595
+ invalidConfig(`Forbidden IP: ${ip}`);
596
+ }
597
+ }
598
+ function normalizeHeaders(headers) {
599
+ const entries = Object.entries(headers ?? {});
600
+ if (entries.length > MAX_HEADER_COUNT) {
601
+ invalidConfig('Too many headers');
602
+ }
603
+ let totalBytes = 0;
604
+ const normalizedHeaders = new Map();
605
+ for (const [name, rawValue] of entries) {
606
+ const value = String(rawValue ?? '');
607
+ const nameBytes = byteSize(name);
608
+ const valueBytes = byteSize(value);
609
+ totalBytes += nameBytes + valueBytes;
610
+ if (!name || hasControlChar(name) || hasControlChar(value) || nameBytes > MAX_HEADER_NAME_BYTES || valueBytes > MAX_HEADER_VALUE_BYTES || !HEADER_TOKEN_RE.test(name)) {
611
+ invalidConfig(`Invalid header: ${name}`);
612
+ }
613
+ const lowerName = name.toLowerCase();
614
+ if (lowerName.startsWith(':') || lowerName.startsWith('proxy-') || UNSAFE_HEADERS.has(lowerName)) {
615
+ invalidConfig(`Unsafe header: ${name}`);
616
+ }
617
+ if (!MODULE_OWNED_HEADERS.has(lowerName)) {
618
+ normalizedHeaders.set(name, value);
619
+ }
620
+ }
621
+ if (totalBytes > MAX_TOTAL_HEADER_BYTES) {
622
+ invalidConfig('Headers too large');
623
+ }
624
+ return Object.fromEntries(normalizedHeaders);
625
+ }
626
+ function validateSniRequestConfig(config) {
627
+ if (config.bodyFile !== undefined) {
628
+ invalidConfig('request does not accept bodyFile');
629
+ }
630
+ const normalized = normalizeSniRequestConfig(config);
631
+ const {
632
+ method,
633
+ body
634
+ } = normalized;
635
+ if ((method === 'GET' || method === 'HEAD') && body !== null) {
636
+ invalidConfig(`${method} requests must not have a body`);
637
+ }
638
+ if ((method === 'POST' || method === 'PUT' || method === 'PATCH') && body === null) {
639
+ invalidConfig(`${method} requests require an explicit body`);
640
+ }
641
+ return normalized;
642
+ }
643
+ function normalizeSniRequestConfig(config) {
644
+ validateRequestId(config.requestId);
645
+ validatePublicIp(config.ip);
646
+ validateHostname(config.hostname);
647
+ validateTimeout(config.timeout);
648
+ const body = config.body ?? null;
649
+ validateBody(body);
650
+ if (config.port !== null && config.port !== undefined) {
651
+ invalidConfig('Caller-controlled ports are not allowed');
652
+ }
653
+ return {
654
+ requestId: config.requestId,
655
+ ip: config.ip,
656
+ hostname: config.hostname,
657
+ body,
658
+ headers: normalizeHeaders(config.headers ?? {}),
659
+ method: normalizeMethod(config.method ?? 'GET'),
660
+ path: normalizePath(config.path ?? '/'),
661
+ timeout: Math.trunc(config.timeout)
662
+ };
663
+ }
664
+ function createCustomAgent() {
665
+ const agent = new _https.default.Agent({
666
+ keepAlive: true,
667
+ keepAliveMsecs: 30_000,
668
+ maxSockets: MAX_SOCKETS_PER_PAIR,
669
+ maxTotalSockets: MAX_TOTAL_SOCKETS,
670
+ maxFreeSockets: MAX_FREE_SOCKETS,
671
+ timeout: MAX_TIMEOUT_MS,
672
+ scheduling: 'lifo'
673
+ });
674
+ agent.getName = options => {
675
+ const ip = options.host || '';
676
+ const hostname = options.servername || '';
677
+ const port = options.port || 443;
678
+ return `${hostname}:${canonicalizeSniDestinationIp(ip)}:${port}`;
679
+ };
680
+ return agent;
681
+ }
682
+ function createAgentState() {
683
+ return {
684
+ agent: createCustomAgent(),
685
+ activeRequests: new Set(),
686
+ destroyed: false
687
+ };
688
+ }
689
+ function isProxyRouteActive(proxyRules) {
690
+ return proxyRules.split(';').map(rule => rule.trim()).filter(Boolean).some(rule => rule.toUpperCase() !== 'DIRECT');
691
+ }
692
+ function buildSniRequestOptions(config, agent) {
693
+ const headers = {
694
+ ...config.headers,
695
+ 'Host': config.hostname,
696
+ 'Accept-Encoding': 'identity'
697
+ };
698
+ if (config.bodyFile) {
699
+ headers['Content-Length'] = String(config.bodyFile.sizeBytes);
700
+ } else if (config.body !== null) {
701
+ headers['Content-Length'] = String(Buffer.byteLength(config.body, 'utf8'));
702
+ }
703
+ return {
704
+ method: config.method,
705
+ host: config.ip,
706
+ port: 443,
707
+ path: config.path,
708
+ servername: config.hostname,
709
+ headers,
710
+ agent,
711
+ rejectUnauthorized: true
712
+ };
713
+ }
714
+ function headersToMaps(rawHeaders) {
715
+ const headers = new Map();
716
+ const multiValueHeaders = new Map();
717
+ for (let index = 0; index < rawHeaders.length; index += 2) {
718
+ const name = String(rawHeaders[index] ?? '').toLowerCase();
719
+ const value = String(rawHeaders[index + 1] ?? '');
720
+ if (name) {
721
+ headers.set(name, value);
722
+ const values = multiValueHeaders.get(name);
723
+ if (values) {
724
+ values.push(value);
725
+ } else {
726
+ multiValueHeaders.set(name, [value]);
727
+ }
728
+ }
729
+ }
730
+ return {
731
+ headers: Object.fromEntries(headers),
732
+ multiValueHeaders: Object.fromEntries(multiValueHeaders)
733
+ };
734
+ }
735
+ class SniRequestLimiter {
736
+ constructor(maxActiveRequests = MAX_ACTIVE_REQUESTS, maxActiveRequestsPerPair = MAX_ACTIVE_REQUESTS_PER_PAIR, maxPendingRequests = MAX_PENDING_REQUESTS, onLog) {
737
+ this.maxActiveRequests = maxActiveRequests;
738
+ this.maxActiveRequestsPerPair = maxActiveRequestsPerPair;
739
+ this.maxPendingRequests = maxPendingRequests;
740
+ this.onLog = onLog;
741
+ }
742
+ activeRequests = 0;
743
+ activeRequestsByPair = new Map();
744
+ pendingRequests = [];
745
+ getKey(hostname, ip) {
746
+ return `${hostname.toLowerCase()}|${canonicalizeSniDestinationIp(ip)}`;
747
+ }
748
+ hasCapacity(key) {
749
+ return this.activeRequests < this.maxActiveRequests && (this.activeRequestsByPair.get(key) ?? 0) < this.maxActiveRequestsPerPair;
750
+ }
751
+ reserveSlot(key) {
752
+ this.activeRequests += 1;
753
+ this.activeRequestsByPair.set(key, (this.activeRequestsByPair.get(key) ?? 0) + 1);
754
+ let released = false;
755
+ return () => {
756
+ if (released) return;
757
+ released = true;
758
+ this.activeRequests = Math.max(0, this.activeRequests - 1);
759
+ const nextPairCount = this.activeRequestsByPair.get(key) ?? 0;
760
+ if (nextPairCount <= 1) {
761
+ this.activeRequestsByPair.delete(key);
762
+ } else {
763
+ this.activeRequestsByPair.set(key, nextPairCount - 1);
764
+ }
765
+ this.dispatchPendingRequests();
766
+ };
767
+ }
768
+ dispatchPendingRequests() {
769
+ while (this.activeRequests < this.maxActiveRequests) {
770
+ const index = this.pendingRequests.findIndex(waiter => this.hasCapacity(waiter.key));
771
+ if (index < 0) return;
772
+ const [waiter] = this.pendingRequests.splice(index, 1);
773
+ if (!waiter) return;
774
+ if (waiter.signal && waiter.abortListener) {
775
+ waiter.signal.removeEventListener('abort', waiter.abortListener);
776
+ }
777
+ waiter.resolve(this.reserveSlot(waiter.key));
778
+ }
779
+ }
780
+ getCancellationError(signal) {
781
+ return signal.reason instanceof Error ? signal.reason : new SniRequestError('SNI_CANCELLED', 'Request cancelled', true);
782
+ }
783
+ snapshot(hostname, ip) {
784
+ const key = hostname && ip ? this.getKey(hostname, ip) : undefined;
785
+ return {
786
+ activeRequests: this.activeRequests,
787
+ activeRequestsForPair: key ? this.activeRequestsByPair.get(key) ?? 0 : 0,
788
+ pendingRequests: this.pendingRequests.length,
789
+ pendingRequestsForPair: key ? this.pendingRequests.filter(waiter => waiter.key === key).length : 0
790
+ };
791
+ }
792
+ acquire(hostname, ip, options = {}) {
793
+ const key = this.getKey(hostname, ip);
794
+ if (options.signal?.aborted) {
795
+ return Promise.reject(this.getCancellationError(options.signal));
796
+ }
797
+ if (this.hasCapacity(key)) {
798
+ return Promise.resolve(this.reserveSlot(key));
799
+ }
800
+ if (this.pendingRequests.length >= this.maxPendingRequests) {
801
+ const stats = this.snapshot(hostname, ip);
802
+ const onLog = options.onLog ?? this.onLog;
803
+ onLog?.('warn', 'desktop_sni_resource_limit', {
804
+ hostname: hostname.toLowerCase(),
805
+ ip,
806
+ ipFamily: getIpFamily(ip),
807
+ activeRequests: stats.activeRequests,
808
+ activeRequestsForPair: stats.activeRequestsForPair,
809
+ pendingRequests: stats.pendingRequests,
810
+ pendingRequestsForPair: stats.pendingRequestsForPair,
811
+ limit: this.maxPendingRequests,
812
+ reason: 'max_pending_requests'
813
+ });
814
+ return Promise.reject(new SniRequestError('SNI_RESOURCE_LIMIT', 'Too many pending SNI requests', true));
815
+ }
816
+ return new Promise((resolve, reject) => {
817
+ const waiter = {
818
+ key,
819
+ signal: options.signal,
820
+ abortListener: undefined,
821
+ resolve
822
+ };
823
+ if (options.signal) {
824
+ waiter.abortListener = () => {
825
+ const index = this.pendingRequests.indexOf(waiter);
826
+ if (index < 0) return;
827
+ this.pendingRequests.splice(index, 1);
828
+ reject(this.getCancellationError(options.signal));
829
+ };
830
+ options.signal.addEventListener('abort', waiter.abortListener, {
831
+ once: true
832
+ });
833
+ }
834
+ this.pendingRequests.push(waiter);
835
+ });
836
+ }
837
+ }
838
+
839
+ // Both package entry points must use the same limiter in the main process.
840
+ exports.SniRequestLimiter = SniRequestLimiter;
841
+ const limiterKey = Symbol.for('@onekeyfe/react-native-sni-connect.requestLimiter');
842
+ const fileLimiterKey = Symbol.for('@onekeyfe/react-native-sni-connect.uploadFileLimiter');
843
+ const sniProcess = process;
844
+ const sharedRequestLimiter = sniProcess[limiterKey] ??= new SniRequestLimiter();
845
+ const sharedUploadFileLimiter = sniProcess[fileLimiterKey] ??= new SniRequestLimiter(MAX_OPEN_UPLOAD_FILES, MAX_OPEN_UPLOAD_FILES);
846
+ class SniNodeClient {
847
+ requestsById = new Map();
848
+ allRequests = new Set();
849
+ allActiveRequests = new Set();
850
+ requestAgentStates = new Map();
851
+ requestLimiter = sharedRequestLimiter;
852
+ constructor(options = {}) {
853
+ this.options = options;
854
+ this.logPrefix = options.logPrefix ?? '[DesktopApiSniRequest]';
855
+ this.agentState = createAgentState();
856
+ }
857
+ getRequestLimiter() {
858
+ return this.requestLimiter;
859
+ }
860
+ setRequestLimiter(limiter) {
861
+ this.requestLimiter = limiter;
862
+ }
863
+ getAgentState() {
864
+ return this.agentState;
865
+ }
866
+ writeNativeLog(level, event, fields) {
867
+ emitNativeLog(this.options.logger, this.logPrefix, level, event, fields);
868
+ }
869
+ maybeDestroyIdleAgentState(agentState) {
870
+ if (agentState !== this.agentState && agentState.activeRequests.size === 0 && !agentState.destroyed) {
871
+ agentState.destroyed = true;
872
+ agentState.agent.destroy();
873
+ }
874
+ }
875
+ removeRequestState(requestState, request, agentState) {
876
+ requestState.clearDeadline();
877
+ requestState.settled = true;
878
+ requestState.uploadProgress = undefined;
879
+ let cleanupAgentState = agentState;
880
+ if (requestState.requestId && this.requestsById.get(requestState.requestId) === requestState) {
881
+ this.requestsById.delete(requestState.requestId);
882
+ }
883
+ this.allRequests.delete(requestState);
884
+ if (request) {
885
+ const state = agentState ?? this.requestAgentStates.get(request);
886
+ this.allActiveRequests.delete(request);
887
+ state?.activeRequests.delete(request);
888
+ this.requestAgentStates.delete(request);
889
+ cleanupAgentState = state;
890
+ }
891
+ if (cleanupAgentState) {
892
+ this.maybeDestroyIdleAgentState(cleanupAgentState);
893
+ }
894
+ }
895
+ async isProxyActiveForUrl(url) {
896
+ const startedAt = Date.now();
897
+ const hostname = getHostnameForLog(url);
898
+ try {
899
+ const proxyRules = await this.options.resolveProxy?.(url);
900
+ const proxyRuleType = getProxyRuleType(proxyRules ?? '');
901
+ if (proxyRuleType === 'unknown') {
902
+ throw new SniRequestError('SNI_UNSUPPORTED', 'Proxy preflight is unavailable');
903
+ }
904
+ const proxyActive = proxyRuleType !== 'direct';
905
+ this.writeNativeLog('info', 'desktop_sni_proxy_preflight', {
906
+ hostname,
907
+ proxyActive,
908
+ proxyRuleType,
909
+ durationMs: Date.now() - startedAt
910
+ });
911
+ return proxyActive;
912
+ } catch (error) {
913
+ this.writeNativeLog('error', 'desktop_sni_proxy_preflight', {
914
+ hostname,
915
+ proxyActive: 'unknown',
916
+ proxyRuleType: 'unknown',
917
+ durationMs: Date.now() - startedAt,
918
+ errorCode: getErrorCode(error) ?? 'none',
919
+ errorMessage: getErrorMessage(error)
920
+ });
921
+ throw error;
922
+ }
923
+ }
924
+ logInvalidConfig(config, bodyBytes, error, startedAt) {
925
+ this.writeNativeLog('error', 'desktop_sni_request_failed', {
926
+ code: getErrorCode(error) ?? 'SNI_INVALID_CONFIG',
927
+ failClosed: isSniFailClosedError(error),
928
+ hostname: config.hostname ?? 'unknown',
929
+ ip: config.ip,
930
+ ipFamily: config.ip ? getIpFamily(config.ip) : 'unknown',
931
+ method: config.method ?? 'GET',
932
+ timeout: config.timeout ?? 'unknown',
933
+ pathBytes: config.path ? byteSize(config.path) : 0,
934
+ bodyBytes,
935
+ headerCount: Object.keys(config.headers ?? {}).length,
936
+ activeRequests: this.requestLimiter.snapshot().activeRequests,
937
+ activeRequestsForPair: 0,
938
+ pendingRequests: this.requestLimiter.snapshot().pendingRequests,
939
+ pendingRequestsForPair: 0,
940
+ durationMs: Date.now() - startedAt,
941
+ errorMessage: getErrorMessage(error)
942
+ });
943
+ }
944
+ createRequestState(requestId, isUpload, timeout, startedAt) {
945
+ const abortController = new AbortController();
946
+ const deadline = startedAt + timeout;
947
+ const cancelForTimeout = () => requestState.cancel(new SniRequestError('SNI_TIMEOUT', `SNI request timeout after ${timeout}ms`));
948
+ const timer = setTimeout(cancelForTimeout, Math.max(0, deadline - Date.now()));
949
+ const requestState = {
950
+ requestId,
951
+ settled: false,
952
+ uploadProgress: requestId && isUpload ? {
953
+ bytesSent: 0,
954
+ totalBytes: 0
955
+ } : undefined,
956
+ signal: abortController.signal,
957
+ checkDeadline: () => {
958
+ if (Date.now() >= deadline) cancelForTimeout();
959
+ abortController.signal.throwIfAborted();
960
+ },
961
+ clearDeadline: () => clearTimeout(timer),
962
+ cancel: error => {
963
+ requestState.settled = true;
964
+ requestState.uploadProgress = undefined;
965
+ abortController.abort(error);
966
+ }
967
+ };
968
+ if (requestId) {
969
+ const previous = this.requestsById.get(requestId);
970
+ if (previous) {
971
+ this.writeNativeLog('warn', 'desktop_sni_lifecycle', {
972
+ action: 'duplicate_request_id',
973
+ requestId,
974
+ success: true,
975
+ activeCount: this.allActiveRequests.size,
976
+ pendingCount: this.requestLimiter.snapshot().pendingRequests
977
+ });
978
+ previous.cancel(new SniRequestError('SNI_CANCELLED', 'Request cancelled', true));
979
+ }
980
+ this.requestsById.set(requestId, requestState);
981
+ }
982
+ this.allRequests.add(requestState);
983
+ return requestState;
984
+ }
985
+ async request(config) {
986
+ const startedAt = Date.now();
987
+ let normalizedConfig;
988
+ try {
989
+ normalizedConfig = validateSniRequestConfig(config);
990
+ } catch (error) {
991
+ this.logInvalidConfig(config, config.body ? byteSize(config.body) : 0, error, startedAt);
992
+ return Promise.reject(error);
993
+ }
994
+ const requestState = this.createRequestState(normalizedConfig.requestId, false, normalizedConfig.timeout, startedAt);
995
+ return this.execute(normalizedConfig, startedAt, requestState);
996
+ }
997
+ async uploadFile(config) {
998
+ const startedAt = Date.now();
999
+ try {
1000
+ validateRequestId(config.requestId);
1001
+ validateTimeout(config.timeout);
1002
+ } catch (error) {
1003
+ this.logInvalidConfig(config, 0, error, startedAt);
1004
+ throw error;
1005
+ }
1006
+ const requestState = this.createRequestState(config.requestId, true, Math.trunc(config.timeout), startedAt);
1007
+ const {
1008
+ signal
1009
+ } = requestState;
1010
+ let rejectOnAbort;
1011
+ let normalizedConfig;
1012
+ let file;
1013
+ try {
1014
+ requestState.checkDeadline();
1015
+ normalizedConfig = normalizeSniUploadFileConfig(config, this.options);
1016
+ file = await new Promise((resolve, reject) => {
1017
+ rejectOnAbort = () => reject(signal.reason);
1018
+ signal.addEventListener('abort', rejectOnAbort, {
1019
+ once: true
1020
+ });
1021
+ resolveUploadFile(config, this.options, signal).then(resolve, reject);
1022
+ });
1023
+ requestState.checkDeadline();
1024
+ } catch (error) {
1025
+ this.removeRequestState(requestState, undefined, undefined);
1026
+ file?.close();
1027
+ this.logInvalidConfig(config, 0, error, startedAt);
1028
+ throw error;
1029
+ } finally {
1030
+ if (rejectOnAbort) signal.removeEventListener('abort', rejectOnAbort);
1031
+ }
1032
+ if (requestState.uploadProgress) {
1033
+ requestState.uploadProgress.totalBytes = file.sizeBytes;
1034
+ }
1035
+ try {
1036
+ return await this.execute(normalizedConfig, startedAt, requestState, file);
1037
+ } finally {
1038
+ file.close();
1039
+ }
1040
+ }
1041
+ async getUploadProgress(requestId) {
1042
+ if (!requestId) {
1043
+ return null;
1044
+ }
1045
+ const requestState = this.requestsById.get(requestId);
1046
+ if (!requestState || requestState.settled || !requestState.uploadProgress) {
1047
+ return null;
1048
+ }
1049
+ return {
1050
+ bytesSent: requestState.uploadProgress.bytesSent,
1051
+ totalBytes: requestState.uploadProgress.totalBytes
1052
+ };
1053
+ }
1054
+ async execute(config, startedAt, requestState, bodyFile) {
1055
+ const normalizedConfig = bodyFile ? {
1056
+ ...config,
1057
+ bodyFile
1058
+ } : config;
1059
+ let releaseRequestSlot;
1060
+ let activeRequest;
1061
+ let activeAgentState;
1062
+ let activeFileStream;
1063
+ const {
1064
+ signal
1065
+ } = requestState;
1066
+ const limiter = this.requestLimiter;
1067
+ try {
1068
+ requestState.checkDeadline();
1069
+ releaseRequestSlot = await limiter.acquire(normalizedConfig.hostname, normalizedConfig.ip, {
1070
+ signal,
1071
+ onLog: (level, event, fields) => this.writeNativeLog(level, event, fields)
1072
+ });
1073
+ requestState.checkDeadline();
1074
+ } catch (error) {
1075
+ releaseRequestSlot?.();
1076
+ releaseRequestSlot = undefined;
1077
+ this.removeRequestState(requestState, undefined, undefined);
1078
+ const stats = this.requestLimiter.snapshot(normalizedConfig.hostname, normalizedConfig.ip);
1079
+ this.writeNativeLog('error', 'desktop_sni_request_failed', {
1080
+ code: getErrorCode(error) ?? 'SNI_RESOURCE_LIMIT',
1081
+ failClosed: isSniFailClosedError(error),
1082
+ hostname: normalizedConfig.hostname,
1083
+ ip: normalizedConfig.ip,
1084
+ ipFamily: getIpFamily(normalizedConfig.ip),
1085
+ method: normalizedConfig.method,
1086
+ timeout: normalizedConfig.timeout,
1087
+ pathBytes: byteSize(normalizedConfig.path),
1088
+ bodyBytes: getBodyBytes(normalizedConfig),
1089
+ headerCount: Object.keys(normalizedConfig.headers).length,
1090
+ activeRequests: stats.activeRequests,
1091
+ activeRequestsForPair: stats.activeRequestsForPair,
1092
+ pendingRequests: stats.pendingRequests,
1093
+ pendingRequestsForPair: stats.pendingRequestsForPair,
1094
+ durationMs: Date.now() - startedAt,
1095
+ errorMessage: getErrorMessage(error)
1096
+ });
1097
+ return Promise.reject(error);
1098
+ }
1099
+ return new Promise((resolve, reject) => {
1100
+ let settled = false;
1101
+ let responseStarted = false;
1102
+ const cleanup = () => {
1103
+ signal.removeEventListener('abort', onAbort);
1104
+ // Close through the handle first so the file slot tracks its close
1105
+ // Promise even when destroying the stream initiates descriptor cleanup.
1106
+ bodyFile?.close();
1107
+ activeFileStream?.destroy();
1108
+ this.removeRequestState(requestState, activeRequest, activeAgentState);
1109
+ releaseRequestSlot?.();
1110
+ };
1111
+ const settleReject = error => {
1112
+ if (settled) return;
1113
+ settled = true;
1114
+ activeRequest?.destroy();
1115
+ cleanup();
1116
+ const stats = limiter.snapshot(normalizedConfig.hostname, normalizedConfig.ip);
1117
+ this.writeNativeLog('error', 'desktop_sni_request_failed', {
1118
+ code: getErrorCode(error) ?? 'SNI_REQUEST_FAILED',
1119
+ failClosed: isSniFailClosedError(error),
1120
+ hostname: normalizedConfig.hostname,
1121
+ ip: normalizedConfig.ip,
1122
+ ipFamily: getIpFamily(normalizedConfig.ip),
1123
+ method: normalizedConfig.method,
1124
+ timeout: normalizedConfig.timeout,
1125
+ pathBytes: byteSize(normalizedConfig.path),
1126
+ bodyBytes: getBodyBytes(normalizedConfig),
1127
+ headerCount: Object.keys(normalizedConfig.headers).length,
1128
+ activeRequests: stats.activeRequests,
1129
+ activeRequestsForPair: stats.activeRequestsForPair,
1130
+ pendingRequests: stats.pendingRequests,
1131
+ pendingRequestsForPair: stats.pendingRequestsForPair,
1132
+ durationMs: Date.now() - startedAt,
1133
+ errorMessage: error.message
1134
+ });
1135
+ reject(error);
1136
+ };
1137
+ const settleResolve = response => {
1138
+ if (settled) return;
1139
+ settled = true;
1140
+ if (bodyFile && activeRequest && !activeRequest.writableEnded) {
1141
+ activeRequest.destroy();
1142
+ }
1143
+ cleanup();
1144
+ this.writeNativeLog('info', 'desktop_sni_request_result', {
1145
+ result: 'response',
1146
+ status: response.statusCode,
1147
+ hostname: normalizedConfig.hostname,
1148
+ ip: normalizedConfig.ip,
1149
+ ipFamily: getIpFamily(normalizedConfig.ip),
1150
+ method: normalizedConfig.method,
1151
+ timeout: normalizedConfig.timeout,
1152
+ responseBytes: response.body ? byteSize(response.body) : 0,
1153
+ durationMs: Date.now() - startedAt
1154
+ });
1155
+ resolve(response);
1156
+ };
1157
+ const onAbort = () => settleReject(signal.reason);
1158
+ signal.addEventListener('abort', onAbort, {
1159
+ once: true
1160
+ });
1161
+ try {
1162
+ activeAgentState = this.agentState;
1163
+ const requestOptions = buildSniRequestOptions(normalizedConfig, activeAgentState.agent);
1164
+ const request = _https.default.request(requestOptions, response => {
1165
+ responseStarted = true;
1166
+ response.on('error', error => {
1167
+ settleReject(error instanceof SniRequestError ? error : new SniRequestError('SNI_RESPONSE_FAILED', `Response stream error: ${error.message}`, true));
1168
+ });
1169
+ if (settled) {
1170
+ response.destroy();
1171
+ return;
1172
+ }
1173
+ const encoding = response.headers['content-encoding'];
1174
+ if (encoding && encoding !== 'identity') {
1175
+ settleReject(new SniRequestError('SNI_RESPONSE_FAILED', `Unsupported content encoding: ${String(encoding)}`, true));
1176
+ return;
1177
+ }
1178
+ const chunks = [];
1179
+ let totalBytes = 0;
1180
+ response.on('data', chunk => {
1181
+ if (settled) return;
1182
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf8');
1183
+ totalBytes += buffer.length;
1184
+ if (totalBytes > MAX_RESPONSE_BODY_BYTES) {
1185
+ settleReject(new SniRequestError('SNI_RESPONSE_FAILED', 'Response body too large', true));
1186
+ return;
1187
+ }
1188
+ chunks.push(buffer);
1189
+ });
1190
+ response.on('end', () => {
1191
+ if (settled) return;
1192
+ const headerMaps = headersToMaps(response.rawHeaders ?? []);
1193
+ const body = Buffer.concat(chunks).toString('utf8');
1194
+ const statusCode = response.statusCode || 0;
1195
+ settleResolve({
1196
+ statusCode,
1197
+ status: statusCode,
1198
+ statusText: response.statusMessage || '',
1199
+ headers: headerMaps.headers,
1200
+ multiValueHeaders: headerMaps.multiValueHeaders,
1201
+ body,
1202
+ data: body
1203
+ });
1204
+ });
1205
+ });
1206
+ activeRequest = request;
1207
+ this.allActiveRequests.add(request);
1208
+ activeAgentState.activeRequests.add(request);
1209
+ this.requestAgentStates.set(request, activeAgentState);
1210
+ request.on('error', error => {
1211
+ settleReject(classifyTransportError(error, Boolean(bodyFile)));
1212
+ });
1213
+ request.once('upgrade', (_response, socket) => {
1214
+ socket.destroy();
1215
+ settleReject(new SniRequestError('SNI_SECURITY_POLICY_FAILED', 'Protocol upgrades are not supported', true));
1216
+ });
1217
+ request.once('close', () => {
1218
+ if (settled) return;
1219
+ settleReject(new SniRequestError(responseStarted ? 'SNI_RESPONSE_FAILED' : 'SNI_REQUEST_FAILED', 'Request closed before completion', responseStarted));
1220
+ });
1221
+ const stats = limiter.snapshot(normalizedConfig.hostname, normalizedConfig.ip);
1222
+ this.writeNativeLog('info', 'desktop_sni_request_start', {
1223
+ requestId: normalizedConfig.requestId,
1224
+ hostname: normalizedConfig.hostname,
1225
+ ip: normalizedConfig.ip,
1226
+ ipFamily: getIpFamily(normalizedConfig.ip),
1227
+ method: normalizedConfig.method,
1228
+ timeout: normalizedConfig.timeout,
1229
+ pathBytes: byteSize(normalizedConfig.path),
1230
+ bodyBytes: getBodyBytes(normalizedConfig),
1231
+ headerCount: Object.keys(normalizedConfig.headers).length,
1232
+ activeRequests: stats.activeRequests,
1233
+ activeRequestsForPair: stats.activeRequestsForPair,
1234
+ pendingRequests: stats.pendingRequests,
1235
+ pendingRequestsForPair: stats.pendingRequestsForPair
1236
+ });
1237
+ if (settled) return;
1238
+ if (bodyFile) {
1239
+ // Stream the validated object and cap reads at the declared length.
1240
+ const fileStream = bodyFile.handle.createReadStream({
1241
+ start: 0,
1242
+ end: bodyFile.sizeBytes - 1,
1243
+ autoClose: false
1244
+ });
1245
+ activeFileStream = fileStream;
1246
+ const rejectFileRead = () => settleReject(new SniRequestError('SNI_FILE_READ_FAILED', 'Upload file read failed', true));
1247
+ fileStream.on('error', rejectFileRead);
1248
+ let bytesRead = 0;
1249
+ let fileEnded = false;
1250
+ let bytesSent = 0;
1251
+ let lastProgressAt = 0;
1252
+ const sendProgress = () => {
1253
+ if (!normalizedConfig.requestId || settled || requestState.settled) {
1254
+ return;
1255
+ }
1256
+ const now = Date.now();
1257
+ if (bytesSent < bodyFile.sizeBytes && now - lastProgressAt < 100) {
1258
+ return;
1259
+ }
1260
+ lastProgressAt = now;
1261
+ this.options.onUploadProgress?.({
1262
+ requestId: normalizedConfig.requestId,
1263
+ bytesSent,
1264
+ totalBytes: bodyFile.sizeBytes,
1265
+ progressPercent: Math.min(99, Math.floor(bytesSent / bodyFile.sizeBytes * 100))
1266
+ });
1267
+ };
1268
+ fileStream.on('data', chunk => {
1269
+ if (settled) return;
1270
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1271
+ bytesRead += bytes.length;
1272
+ fileStream.pause();
1273
+ request.write(bytes, error => {
1274
+ if (settled || requestState.settled) return;
1275
+ if (error) {
1276
+ settleReject(classifyTransportError(error, true));
1277
+ return;
1278
+ }
1279
+ bytesSent += bytes.length;
1280
+ if (requestState.uploadProgress) {
1281
+ requestState.uploadProgress = {
1282
+ bytesSent,
1283
+ totalBytes: bodyFile.sizeBytes
1284
+ };
1285
+ }
1286
+ try {
1287
+ sendProgress();
1288
+ } catch {
1289
+ /* Progress must not fail upload. */
1290
+ }
1291
+ if (fileEnded) {
1292
+ request.end();
1293
+ } else {
1294
+ fileStream.resume();
1295
+ }
1296
+ });
1297
+ });
1298
+ fileStream.on('end', () => {
1299
+ if (settled) return;
1300
+ if (bytesRead !== bodyFile.sizeBytes) {
1301
+ rejectFileRead();
1302
+ return;
1303
+ }
1304
+ fileEnded = true;
1305
+ if (bytesSent === bytesRead) request.end();
1306
+ });
1307
+ return;
1308
+ }
1309
+ if (normalizedConfig.body) {
1310
+ request.write(normalizedConfig.body);
1311
+ }
1312
+ request.end();
1313
+ } catch (error) {
1314
+ settleReject(error instanceof Error ? error : new Error(String(error)));
1315
+ }
1316
+ });
1317
+ }
1318
+ async cancelRequest(requestId) {
1319
+ const requestState = this.requestsById.get(requestId);
1320
+ if (!requestState) {
1321
+ this.writeNativeLog('warn', 'desktop_sni_lifecycle', {
1322
+ action: 'cancel_request',
1323
+ requestId,
1324
+ success: false,
1325
+ activeCount: this.allActiveRequests.size,
1326
+ pendingCount: this.requestLimiter.snapshot().pendingRequests
1327
+ });
1328
+ return {
1329
+ success: false
1330
+ };
1331
+ }
1332
+ this.requestsById.delete(requestId);
1333
+ requestState.cancel(new SniRequestError('SNI_CANCELLED', 'Request cancelled', true));
1334
+ this.writeNativeLog('info', 'desktop_sni_lifecycle', {
1335
+ action: 'cancel_request',
1336
+ requestId,
1337
+ success: true,
1338
+ activeCount: this.allActiveRequests.size,
1339
+ pendingCount: this.requestLimiter.snapshot().pendingRequests
1340
+ });
1341
+ return {
1342
+ success: true
1343
+ };
1344
+ }
1345
+ async getDebugSnapshot({
1346
+ hostname,
1347
+ ip
1348
+ }) {
1349
+ validateHostname(hostname);
1350
+ validatePublicIp(ip);
1351
+ return this.requestLimiter.snapshot(hostname, ip);
1352
+ }
1353
+ async cancelAllRequests() {
1354
+ const requests = Array.from(this.allRequests);
1355
+ this.requestsById.clear();
1356
+ this.allRequests.clear();
1357
+ for (const request of requests) {
1358
+ request.cancel(new SniRequestError('SNI_CANCELLED', 'Request cancelled', true));
1359
+ }
1360
+ this.writeNativeLog('info', 'desktop_sni_lifecycle', {
1361
+ action: 'cancel_all_requests',
1362
+ success: true,
1363
+ requestCount: requests.length,
1364
+ activeCount: this.allActiveRequests.size,
1365
+ pendingCount: this.requestLimiter.snapshot().pendingRequests
1366
+ });
1367
+ return {
1368
+ success: true
1369
+ };
1370
+ }
1371
+ async clearDNSCache() {
1372
+ const previousAgentState = this.agentState;
1373
+ this.agentState = createAgentState();
1374
+ const previousAgent = previousAgentState.agent;
1375
+ previousAgent.keepSocketAlive = () => false;
1376
+ for (const sockets of Object.values(previousAgent.freeSockets)) {
1377
+ sockets?.forEach(socket => socket.destroy());
1378
+ }
1379
+ this.maybeDestroyIdleAgentState(previousAgentState);
1380
+ this.writeNativeLog('info', 'desktop_sni_lifecycle', {
1381
+ action: 'clear_dns_cache',
1382
+ success: true,
1383
+ activeCount: previousAgentState.activeRequests.size
1384
+ });
1385
+ return {
1386
+ success: true
1387
+ };
1388
+ }
1389
+ async isSupported() {
1390
+ return true;
1391
+ }
1392
+ }
1393
+ exports.SniNodeClient = SniNodeClient;
1394
+ var _default = exports.default = SniNodeClient;
1395
+ //# sourceMappingURL=index.js.map