-
-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathindex.js
More file actions
202 lines (172 loc) · 5 KB
/
Copy pathindex.js
File metadata and controls
202 lines (172 loc) · 5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
import os from 'node:os';
import {channel} from 'node:diagnostics_channel';
import {withHttpError, withTimeout} from 'fetch-extras';
import {publicIpv4, publicIpv6} from 'public-ip';
import pAny from 'p-any';
import pTimeout from 'p-timeout';
const diagnosticsChannel = channel('is-online:connectivity-check');
const publishFailure = (url, error) => {
if (!diagnosticsChannel.hasSubscribers) {
return;
}
try {
diagnosticsChannel.publish({
timestamp: Date.now(),
url,
error: {
name: error.constructor.name,
message: error.message,
code: error.code,
},
});
} catch {
// Ignore diagnostics errors - never affect main functionality
}
};
const fetchUrl = async (url, options, signal, fetchOptions = {}) => {
const fetchWithTimeout = withHttpError(withTimeout(globalThis.fetch, options.timeout));
return fetchWithTimeout(url, {signal, ...fetchOptions});
};
const appleCheck = async (options, signal) => {
const url = 'https://captive.apple.com/hotspot-detect.html';
try {
const response = await fetchUrl(url, options, signal, {
method: 'GET', // Apple captive portal requires GET to return body content
headers: {
'user-agent': 'CaptiveNetworkSupport/1.0 wispr',
},
});
const body = await response.text();
if (!body?.includes('Success')) {
throw new Error('Apple check failed');
}
} catch (error) {
publishFailure(url, error);
throw error;
}
};
const urlCheck = async (url, options, signal) => {
// Validate URL
let urlObject;
try {
urlObject = new URL(url);
} catch (error) {
// Invalid URL format
publishFailure(url, error);
throw error;
}
// Only allow HTTP and HTTPS
if (!['http:', 'https:'].includes(urlObject.protocol)) {
const error = new Error(`Unsupported protocol: ${urlObject.protocol}`);
publishFailure(url, error);
throw error;
}
try {
// Use HEAD request when possible to minimize data transfer
await fetchUrl(url, options, signal, {method: 'HEAD'});
} catch (error) {
// If HEAD fails, try GET as fallback (some servers don't support HEAD)
if (error.status === 405 || error.message?.includes('Method Not Allowed')) {
await fetchUrl(url, options, signal, {method: 'GET'});
} else {
// Publish failure for this specific URL
publishFailure(url, error);
throw error;
}
}
};
const createAbortPromise = signal => new Promise((resolve, reject) => {
if (signal.aborted) {
reject(new Error('Aborted'));
} else {
signal.addEventListener('abort', () => {
reject(new Error('Aborted'));
}, {once: true});
}
});
const tryFallbackUrls = async options => {
if (!options.fallbackUrls?.length) {
return false;
}
if (options.signal?.aborted) {
return false;
}
try {
const urlPromise = checkUrls(options.fallbackUrls, options, options.signal);
if (options.signal) {
const abortPromise = createAbortPromise(options.signal);
await pTimeout(Promise.race([urlPromise, abortPromise]), {milliseconds: options.timeout});
} else {
await pTimeout(urlPromise, {milliseconds: options.timeout});
}
return true;
} catch {
// Individual URL failures are already published by urlCheck
return false;
}
};
const checkUrls = async (urls, options, signal) => {
if (!urls?.length) {
throw new Error('No URLs to check');
}
const promises = urls.map(async url => {
await urlCheck(url, options, signal);
return true;
});
return pAny(promises);
};
export default async function isOnline(options = {}) {
options = {
timeout: 5000,
ipVersion: 4,
...options,
};
if (Object.values(os.networkInterfaces()).flat().every(({internal}) => internal)) {
return false;
}
if (![4, 6].includes(options.ipVersion)) {
throw new TypeError('`ipVersion` must be 4 or 6');
}
if (options.signal?.aborted) {
return false;
}
const publicIpFunction = options.ipVersion === 4 ? publicIpv4 : publicIpv6;
const publicIpCheck = async (onlyHttps = false) => {
const serviceName = onlyHttps ? 'https://api.ipify.org' : 'https://icanhazip.com';
try {
await publicIpFunction({...options, onlyHttps, signal: options.signal});
} catch (error) {
publishFailure(serviceName, error);
throw error;
}
};
const promise = (async () => {
const promises = [
publicIpCheck(false),
publicIpCheck(true),
appleCheck(options, options.signal),
// Cloudflare as additional fallback
urlCheck('https://cloudflare.com/', options, options.signal),
].map(async promise => {
await promise;
return true;
});
return pAny(promises);
})();
// Try main checks first
// eslint-disable-next-line no-warning-comments
// TODO: Use AbortSignal.timeout() instead of pTimeout when it's widely supported
const tryMainChecks = async () => {
if (options.signal) {
const abortPromise = createAbortPromise(options.signal);
return pTimeout(Promise.race([promise, abortPromise]), {milliseconds: options.timeout});
}
return pTimeout(promise, {milliseconds: options.timeout});
};
try {
return await tryMainChecks();
} catch {
// Individual check failures are already published by each check
return tryFallbackUrls(options);
}
}