@cocreate/server 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.github/workflows/automated.yml +25 -13
- package/.github/workflows/manual.yml +1 -2
- package/CHANGELOG.md +37 -0
- package/demo/index.html +19 -19
- package/docs/index.html +336 -331
- package/package.json +4 -4
- package/release.config.js +12 -4
- package/src/getInfrastructure.js +362 -0
- package/src/getIp.js +113 -0
- package/src/index.js +381 -31
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cocreate/server",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.0",
|
|
4
4
|
"description": "A dynamic SSL certificate management and generation tool for proxies like NGINX, with a fallback to Node.js SSL termination. It seamlessly integrates HTTP, HTTPS, and ACME protocols to ensure secure, encrypted connections.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ssl-certificate-management",
|
|
@@ -20,8 +20,7 @@
|
|
|
20
20
|
"scripts": {
|
|
21
21
|
"start": "npx webpack --config webpack.config.js",
|
|
22
22
|
"build": "npx webpack --mode=production --config webpack.config.js",
|
|
23
|
-
"dev": "npx webpack --config webpack.config.js --watch"
|
|
24
|
-
"postinstall": "node -e \"const { execSync } = require('child_process'); try { execSync('coc --version', { stdio: 'ignore' }); } catch (error) { try { execSync('npm install -g @cocreate/cli', { stdio: 'inherit' }); console.log('Installed \"@cocreate/cli\" globally.'); } catch (error) { console.error('Failed to install \"@cocreate/cli\" globally:', error); } }\""
|
|
23
|
+
"dev": "npx webpack --config webpack.config.js --watch"
|
|
25
24
|
},
|
|
26
25
|
"repository": {
|
|
27
26
|
"type": "git",
|
|
@@ -37,8 +36,9 @@
|
|
|
37
36
|
"type": "GitHub Sponsors ❤",
|
|
38
37
|
"url": "https://github.com/sponsors/CoCreate-app"
|
|
39
38
|
},
|
|
39
|
+
"type": "module",
|
|
40
40
|
"main": "./src/index.js",
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@cocreate/acme": "^1.
|
|
42
|
+
"@cocreate/acme": "^1.3.0"
|
|
43
43
|
}
|
|
44
44
|
}
|
package/release.config.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
export default {
|
|
2
2
|
dryRun: false,
|
|
3
3
|
branches: ["master"],
|
|
4
4
|
plugins: [
|
|
@@ -10,12 +10,20 @@ module.exports = {
|
|
|
10
10
|
changelogFile: "CHANGELOG.md",
|
|
11
11
|
},
|
|
12
12
|
],
|
|
13
|
-
"@semantic-release/npm",
|
|
14
|
-
"@semantic-release/github",
|
|
13
|
+
"@semantic-release/npm",
|
|
15
14
|
[
|
|
16
|
-
"@semantic-release/
|
|
15
|
+
"@semantic-release/github",
|
|
17
16
|
{
|
|
17
|
+
successComment: false,
|
|
18
|
+
failTitle: false,
|
|
19
|
+
},
|
|
20
|
+
],
|
|
21
|
+
[
|
|
22
|
+
"@semantic-release/git",
|
|
23
|
+
{
|
|
24
|
+
// Only stage and commit the changelog and package.json
|
|
18
25
|
assets: ["CHANGELOG.md", "package.json"],
|
|
26
|
+
message: "chore(release): ${nextRelease.version} [skip ci]",
|
|
19
27
|
},
|
|
20
28
|
],
|
|
21
29
|
],
|
|
@@ -0,0 +1,362 @@
|
|
|
1
|
+
/********************************************************************************
|
|
2
|
+
* Copyright (C) 2023 CoCreate and Contributors.
|
|
3
|
+
*
|
|
4
|
+
* This program is free software: you can redistribute it and/or modify
|
|
5
|
+
* it under the terms of the GNU Affero General Public License as published
|
|
6
|
+
* by the Free Software Foundation, either version 3 of the License, or
|
|
7
|
+
* (at your option) any later version.
|
|
8
|
+
*
|
|
9
|
+
* This program is distributed in the hope that it will be useful,
|
|
10
|
+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
11
|
+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
12
|
+
* GNU Affero General Public License for more details.
|
|
13
|
+
*
|
|
14
|
+
* You should have received a copy of the GNU Affero General Public License
|
|
15
|
+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
16
|
+
********************************************************************************/
|
|
17
|
+
|
|
18
|
+
import http from 'node:http';
|
|
19
|
+
import https from 'node:https';
|
|
20
|
+
import fs from 'node:fs';
|
|
21
|
+
import os from 'node:os';
|
|
22
|
+
|
|
23
|
+
const METADATA_IP = '169.254.169.254';
|
|
24
|
+
const PROBE_TIMEOUT_MS = 500; // Fast timeout for parallel background probes
|
|
25
|
+
|
|
26
|
+
/* STREAMING_CHUNK: Structuring the native network request wrapper... */
|
|
27
|
+
/**
|
|
28
|
+
* Native, lightweight HTTP request wrapper supporting standard GET/PUT/POST operations.
|
|
29
|
+
*/
|
|
30
|
+
function request(options, data = null, useHttps = false) {
|
|
31
|
+
const client = useHttps ? https : http;
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
const req = client.request(options, (res) => {
|
|
34
|
+
if (res.statusCode < 200 || res.statusCode >= 300) {
|
|
35
|
+
reject(new Error(`Status Code: ${res.statusCode}`));
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
38
|
+
let body = '';
|
|
39
|
+
res.setEncoding('utf8');
|
|
40
|
+
res.on('data', (chunk) => { body += chunk; });
|
|
41
|
+
res.on('end', () => { resolve(body); });
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
req.on('error', (err) => { reject(err); });
|
|
45
|
+
req.setTimeout(PROBE_TIMEOUT_MS, () => {
|
|
46
|
+
req.destroy();
|
|
47
|
+
reject(new Error('Request Timeout'));
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
if (data) {
|
|
51
|
+
req.write(data);
|
|
52
|
+
}
|
|
53
|
+
req.end();
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/* STREAMING_CHUNK: Configuring AWS metadata IMDSv2 probe... */
|
|
58
|
+
/**
|
|
59
|
+
* AWS IMDSv2 Probe: Acquires session token and retrieves instance metadata.
|
|
60
|
+
*/
|
|
61
|
+
async function probeAWS() {
|
|
62
|
+
const token = await request({
|
|
63
|
+
host: METADATA_IP,
|
|
64
|
+
path: '/latest/api/token',
|
|
65
|
+
method: 'PUT',
|
|
66
|
+
headers: { 'X-aws-ec2-metadata-token-ttl-seconds': '60' }
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
const docStr = await request({
|
|
70
|
+
host: METADATA_IP,
|
|
71
|
+
path: '/latest/dynamic/instance-identity/document',
|
|
72
|
+
method: 'GET',
|
|
73
|
+
headers: { 'X-aws-ec2-metadata-token': token }
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
const doc = JSON.parse(docStr);
|
|
77
|
+
return {
|
|
78
|
+
provider: 'aws',
|
|
79
|
+
region: doc.region,
|
|
80
|
+
zone: doc.availabilityZone,
|
|
81
|
+
instanceId: doc.instanceId,
|
|
82
|
+
instanceType: doc.instanceType
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/* STREAMING_CHUNK: Configuring Google Cloud (GCP) metadata probe... */
|
|
87
|
+
/**
|
|
88
|
+
* GCP Metadata Probe: Requests instance data with the mandatory Flavor header.
|
|
89
|
+
*/
|
|
90
|
+
async function probeGCP() {
|
|
91
|
+
const docStr = await request({
|
|
92
|
+
host: 'metadata.google.internal',
|
|
93
|
+
path: '/computeMetadata/v1/instance/?recursive=true',
|
|
94
|
+
method: 'GET',
|
|
95
|
+
headers: { 'Metadata-Flavor': 'Google' }
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
const doc = JSON.parse(docStr);
|
|
99
|
+
const zone = doc.zone ? doc.zone.split('/').pop() : 'unknown';
|
|
100
|
+
const region = zone.slice(0, zone.lastIndexOf('-'));
|
|
101
|
+
const instanceType = doc.machineType ? doc.machineType.split('/').pop() : 'unknown';
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
provider: 'gcp',
|
|
105
|
+
region,
|
|
106
|
+
zone,
|
|
107
|
+
instanceId: doc.id ? String(doc.id) : 'unknown',
|
|
108
|
+
instanceType
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/* STREAMING_CHUNK: Configuring Azure metadata probe... */
|
|
113
|
+
/**
|
|
114
|
+
* Microsoft Azure Probe: Requests metadata using the validation header.
|
|
115
|
+
*/
|
|
116
|
+
async function probeAzure() {
|
|
117
|
+
const docStr = await request({
|
|
118
|
+
host: METADATA_IP,
|
|
119
|
+
path: '/metadata/instance?api-version=2021-02-01',
|
|
120
|
+
method: 'GET',
|
|
121
|
+
headers: { 'Metadata': 'true' }
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
const doc = JSON.parse(docStr);
|
|
125
|
+
const compute = doc.compute || {};
|
|
126
|
+
|
|
127
|
+
return {
|
|
128
|
+
provider: 'azure',
|
|
129
|
+
region: compute.location || 'unknown',
|
|
130
|
+
zone: compute.zone || 'unknown',
|
|
131
|
+
instanceId: compute.vmId || 'unknown',
|
|
132
|
+
instanceType: compute.vmSize || 'unknown'
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/* STREAMING_CHUNK: Configuring DigitalOcean metadata probe... */
|
|
137
|
+
/**
|
|
138
|
+
* DigitalOcean Probe: Requests droplet metadata configuration.
|
|
139
|
+
*/
|
|
140
|
+
async function probeDigitalOcean() {
|
|
141
|
+
const docStr = await request({
|
|
142
|
+
host: METADATA_IP,
|
|
143
|
+
path: '/metadata/v1.json',
|
|
144
|
+
method: 'GET'
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
const doc = JSON.parse(docStr);
|
|
148
|
+
return {
|
|
149
|
+
provider: 'digitalocean',
|
|
150
|
+
region: doc.region || 'unknown',
|
|
151
|
+
zone: doc.region ? `${doc.region}-a` : 'unknown',
|
|
152
|
+
instanceId: doc.droplet_id ? String(doc.droplet_id) : 'unknown',
|
|
153
|
+
instanceType: doc.size || 'unknown'
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/* STREAMING_CHUNK: Configuring Oracle Cloud (OCI) metadata probe... */
|
|
158
|
+
/**
|
|
159
|
+
* Oracle Cloud (OCI) Probe: Validates via the Bearer Token header required by IMDSv2.
|
|
160
|
+
*/
|
|
161
|
+
async function probeOCI() {
|
|
162
|
+
const docStr = await request({
|
|
163
|
+
host: METADATA_IP,
|
|
164
|
+
path: '/opc/v2/instance/',
|
|
165
|
+
method: 'GET',
|
|
166
|
+
headers: { 'Authorization': 'Bearer Oracle' }
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
const doc = JSON.parse(docStr);
|
|
170
|
+
return {
|
|
171
|
+
provider: 'oracle',
|
|
172
|
+
region: doc.region || 'unknown',
|
|
173
|
+
zone: doc.faultDomain || 'unknown',
|
|
174
|
+
instanceId: doc.id || 'unknown',
|
|
175
|
+
instanceType: doc.shape || 'unknown'
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/* STREAMING_CHUNK: Configuring Hetzner Cloud metadata probe... */
|
|
180
|
+
/**
|
|
181
|
+
* Hetzner Cloud Probe: Requests basic instance parameters on Hetzner routes.
|
|
182
|
+
*/
|
|
183
|
+
async function probeHetzner() {
|
|
184
|
+
const docStr = await request({
|
|
185
|
+
host: METADATA_IP,
|
|
186
|
+
path: '/hetzner/v1/metadata',
|
|
187
|
+
method: 'GET'
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
const lines = docStr.split('\n');
|
|
191
|
+
const meta = {};
|
|
192
|
+
for (const line of lines) {
|
|
193
|
+
const splitIdx = line.indexOf(':');
|
|
194
|
+
if (splitIdx !== -1) {
|
|
195
|
+
const key = line.slice(0, splitIdx).trim();
|
|
196
|
+
const val = line.slice(splitIdx + 1).trim();
|
|
197
|
+
meta[key] = val;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
const zone = meta['availability-zone'] || 'unknown';
|
|
202
|
+
const region = meta['region'] || (zone ? zone.slice(0, zone.lastIndexOf('-')) : 'unknown');
|
|
203
|
+
|
|
204
|
+
return {
|
|
205
|
+
provider: 'hetzner',
|
|
206
|
+
region,
|
|
207
|
+
zone,
|
|
208
|
+
instanceId: meta['instance-id'] || 'unknown',
|
|
209
|
+
instanceType: 'cloud-vm'
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/* STREAMING_CHUNK: Configuring Vultr and Equinix metadata probes... */
|
|
214
|
+
/**
|
|
215
|
+
* Vultr Probe: Pulls metadata configurations from standard OpenStack mapping paths.
|
|
216
|
+
*/
|
|
217
|
+
async function probeVultr() {
|
|
218
|
+
const idStr = await request({
|
|
219
|
+
host: METADATA_IP,
|
|
220
|
+
path: '/v1/instance-v2-id',
|
|
221
|
+
method: 'GET'
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
const hostStr = await request({
|
|
225
|
+
host: METADATA_IP,
|
|
226
|
+
path: '/v1/hostname',
|
|
227
|
+
method: 'GET'
|
|
228
|
+
});
|
|
229
|
+
|
|
230
|
+
return {
|
|
231
|
+
provider: 'vultr',
|
|
232
|
+
region: 'vultr-global',
|
|
233
|
+
zone: 'vultr-zone',
|
|
234
|
+
instanceId: idStr ? idStr.trim() : 'unknown',
|
|
235
|
+
instanceType: hostStr ? hostStr.trim() : 'vultr-instance'
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Equinix Metal Probe: Requests local bare metal profile metadata via direct secure gateway.
|
|
241
|
+
*/
|
|
242
|
+
async function probeEquinix() {
|
|
243
|
+
const docStr = await request({
|
|
244
|
+
host: 'metadata.platformequinix.com',
|
|
245
|
+
path: '/metadata',
|
|
246
|
+
method: 'GET'
|
|
247
|
+
}, null, true);
|
|
248
|
+
|
|
249
|
+
const doc = JSON.parse(docStr);
|
|
250
|
+
return {
|
|
251
|
+
provider: 'equinix-metal',
|
|
252
|
+
region: doc.metro || doc.facility || 'unknown',
|
|
253
|
+
zone: doc.facility || 'unknown',
|
|
254
|
+
instanceId: doc.id || 'unknown',
|
|
255
|
+
instanceType: doc.plan || 'baremetal-metal'
|
|
256
|
+
};
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/* STREAMING_CHUNK: Resolving local physical hardware profiles... */
|
|
260
|
+
/**
|
|
261
|
+
* Safely inspects Linux OS profiles to identify local Bare-Metal / Physical system models.
|
|
262
|
+
*/
|
|
263
|
+
function resolveBareMetalIdentity() {
|
|
264
|
+
try {
|
|
265
|
+
if (fs.existsSync('/sys/class/dmi/id/product_name')) {
|
|
266
|
+
const productName = fs.readFileSync('/sys/class/dmi/id/product_name', 'utf8').trim();
|
|
267
|
+
const vendorName = fs.existsSync('/sys/class/dmi/id/sys_vendor')
|
|
268
|
+
? fs.readFileSync('/sys/class/dmi/id/sys_vendor', 'utf8').trim()
|
|
269
|
+
: 'BareMetal';
|
|
270
|
+
|
|
271
|
+
let isVirtual = false;
|
|
272
|
+
const virtualClues = ['qemu', 'kvm', 'virtualbox', 'vmware', 'xen'];
|
|
273
|
+
for (const clue of virtualClues) {
|
|
274
|
+
if (productName.toLowerCase().includes(clue) || vendorName.toLowerCase().includes(clue)) {
|
|
275
|
+
isVirtual = true;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
if (!isVirtual) {
|
|
280
|
+
return {
|
|
281
|
+
provider: 'baremetal',
|
|
282
|
+
region: 'on-premise',
|
|
283
|
+
zone: 'on-premise-datacenter',
|
|
284
|
+
instanceId: productName.replace(/\s+/g, '-').toLowerCase(),
|
|
285
|
+
instanceType: `${vendorName}-${productName}`.replace(/\s+/g, '-').toLowerCase()
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
} catch (err) {
|
|
290
|
+
// Non-blocking fallback
|
|
291
|
+
}
|
|
292
|
+
return null;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/* STREAMING_CHUNK: Running the infallible infrastructure resolver... */
|
|
296
|
+
/**
|
|
297
|
+
* Dynamically resolves the host's physical infrastructure environment.
|
|
298
|
+
* Runs exactly once during the server boot sequence. Guaranteed to never throw.
|
|
299
|
+
*
|
|
300
|
+
* @param {string} masterInstanceId - The pre-configured fallback instance ID
|
|
301
|
+
* @returns {Promise<Object>} Resolved server.infrastructure payload
|
|
302
|
+
*/
|
|
303
|
+
export async function getInfrastructure(masterInstanceId) {
|
|
304
|
+
const localFallback = {
|
|
305
|
+
provider: 'local',
|
|
306
|
+
region: 'local',
|
|
307
|
+
zone: 'local',
|
|
308
|
+
instanceId: masterInstanceId,
|
|
309
|
+
instanceType: 'local'
|
|
310
|
+
};
|
|
311
|
+
|
|
312
|
+
try {
|
|
313
|
+
// Phase 1: Concurrently race cloud metadata IMDS probes
|
|
314
|
+
try {
|
|
315
|
+
const cloudMetadata = await Promise.any([
|
|
316
|
+
probeAWS(),
|
|
317
|
+
probeGCP(),
|
|
318
|
+
probeAzure(),
|
|
319
|
+
probeDigitalOcean(),
|
|
320
|
+
probeOCI(),
|
|
321
|
+
probeHetzner(),
|
|
322
|
+
probeVultr(),
|
|
323
|
+
probeEquinix()
|
|
324
|
+
]);
|
|
325
|
+
if (cloudMetadata) {
|
|
326
|
+
return cloudMetadata;
|
|
327
|
+
}
|
|
328
|
+
} catch (err) {
|
|
329
|
+
// Proceed to local sweeps
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Phase 2: Detect local On-Prem Bare Metal Hardware
|
|
333
|
+
try {
|
|
334
|
+
const bareMetalInfo = resolveBareMetalIdentity();
|
|
335
|
+
if (bareMetalInfo) {
|
|
336
|
+
bareMetalInfo.instanceId = masterInstanceId;
|
|
337
|
+
return bareMetalInfo;
|
|
338
|
+
}
|
|
339
|
+
} catch (err) {
|
|
340
|
+
// Proceed to env checks
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// Phase 3: Check Environment Variable Overrides
|
|
344
|
+
if (process.env.PROVIDER) {
|
|
345
|
+
return {
|
|
346
|
+
provider: process.env.PROVIDER,
|
|
347
|
+
region: process.env.REGION || 'unknown',
|
|
348
|
+
zone: process.env.ZONE || 'unknown',
|
|
349
|
+
instanceId: process.env.INSTANCE_ID || masterInstanceId,
|
|
350
|
+
instanceType: process.env.INSTANCE_TYPE || 'unknown'
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
} catch (globalErr) {
|
|
355
|
+
// Suppress any unexpected error contexts and fall back cleanly
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// Phase 4: Developer Machine Fallback
|
|
359
|
+
return localFallback;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
export default getInfrastructure;
|
package/src/getIp.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/********************************************************************************
|
|
2
|
+
* Copyright (C) 2023 CoCreate and Contributors.
|
|
3
|
+
*
|
|
4
|
+
* This program is free software: you can redistribute it and/or modify
|
|
5
|
+
* it under the terms of the GNU Affero General Public License as published
|
|
6
|
+
* by the Free Software Foundation, either version 3 of the License, or
|
|
7
|
+
* (at your option) any later version.
|
|
8
|
+
*
|
|
9
|
+
* This program is distributed in the hope that it will be useful,
|
|
10
|
+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
11
|
+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
12
|
+
* GNU Affero General Public License for more details.
|
|
13
|
+
*
|
|
14
|
+
* You should have received a copy of the GNU Affero General Public License
|
|
15
|
+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
16
|
+
********************************************************************************/
|
|
17
|
+
|
|
18
|
+
import https from 'node:https';
|
|
19
|
+
import os from 'node:os';
|
|
20
|
+
|
|
21
|
+
// Prioritized list of reliable public IP lookup APIs
|
|
22
|
+
const IP_PROVIDERS = [
|
|
23
|
+
'https://api.ipify.org',
|
|
24
|
+
'https://icanhazip.com',
|
|
25
|
+
'https://ifconfig.me/ip',
|
|
26
|
+
'https://ipinfo.io/ip'
|
|
27
|
+
];
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Initiates an HTTPS GET request to a specific IP provider with a hard timeout.
|
|
31
|
+
*
|
|
32
|
+
* @param {string} url - The URL of the IP lookup provider
|
|
33
|
+
* @param {number} timeoutMs - Max execution limit before canceling the promise
|
|
34
|
+
* @returns {Promise<string>} - Resolves with the plain-text IP address
|
|
35
|
+
*/
|
|
36
|
+
function fetchIpFromProvider(url, timeoutMs = 3000) {
|
|
37
|
+
return new Promise((resolve, reject) => {
|
|
38
|
+
const req = https.get(url, (res) => {
|
|
39
|
+
if (res.statusCode !== 200) {
|
|
40
|
+
reject(new Error(`Non-200 response code: ${res.statusCode}`));
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
let data = '';
|
|
45
|
+
res.on('data', (chunk) => { data += chunk; });
|
|
46
|
+
|
|
47
|
+
res.on('end', () => {
|
|
48
|
+
const cleanIp = data.trim();
|
|
49
|
+
const ipv4Regex = /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/;
|
|
50
|
+
if (ipv4Regex.test(cleanIp)) {
|
|
51
|
+
resolve(cleanIp);
|
|
52
|
+
} else {
|
|
53
|
+
reject(new Error(`Returned invalid IP structure: "${cleanIp}"`));
|
|
54
|
+
}
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
req.on('error', (err) => { reject(err); });
|
|
59
|
+
|
|
60
|
+
req.setTimeout(timeoutMs, () => {
|
|
61
|
+
req.destroy();
|
|
62
|
+
reject(new Error(`Request timed out`));
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Scans the local machine's physical network adapters to find the primary local IP.
|
|
69
|
+
* Used as a fallback if the machine has no active internet connection or is fully offline.
|
|
70
|
+
*
|
|
71
|
+
* @returns {string} - Returns the first valid local IPv4 address, or '127.0.0.1'
|
|
72
|
+
*/
|
|
73
|
+
export function getLocalIPFallback() {
|
|
74
|
+
try {
|
|
75
|
+
const interfaces = os.networkInterfaces();
|
|
76
|
+
for (const devName in interfaces) {
|
|
77
|
+
const face = interfaces[devName];
|
|
78
|
+
for (let i = 0; i < face.length; i++) {
|
|
79
|
+
const alias = face[i];
|
|
80
|
+
// Check for standard IPv4 and exclude typical loopbacks
|
|
81
|
+
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
|
|
82
|
+
return alias.address;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
} catch (err) {
|
|
87
|
+
// Safe, non-blocking fallback context
|
|
88
|
+
}
|
|
89
|
+
return '127.0.0.1';
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Robust universal public IP resolution function.
|
|
94
|
+
* Iterates through highly redundant public IP lookup services.
|
|
95
|
+
* Guaranteed to never throw errors.
|
|
96
|
+
*
|
|
97
|
+
* @returns {Promise<string>} - The resolved public IP (or local IP if completely offline)
|
|
98
|
+
*/
|
|
99
|
+
export async function getIp() {
|
|
100
|
+
for (const url of IP_PROVIDERS) {
|
|
101
|
+
try {
|
|
102
|
+
const ip = await fetchIpFromProvider(url);
|
|
103
|
+
return ip;
|
|
104
|
+
} catch (error) {
|
|
105
|
+
// Suppress fallback exceptions to attempt the next endpoint seamlessly
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Offline / Air-Gapped Fallback
|
|
110
|
+
return getLocalIPFallback();
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
export default getIp;
|