@nr-connect/node-red 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +151 -3
- package/examples/starter-demo.json +776 -0
- package/index.html +1939 -0
- package/index.js +76 -0
- package/lib/binaryManager.js +557 -0
- package/lib/connectionManager.js +1060 -0
- package/lib/connectorManifest.json +61 -0
- package/lib/dashboardRbac.js +670 -0
- package/lib/expressInterceptor.js +917 -0
- package/lib/pageSyncAgent.js +149 -0
- package/lib/pushAgent.js +253 -0
- package/lib/qrCode.js +625 -0
- package/lib/statusEndpoint.js +231 -0
- package/lib/tokenCodec.js +98 -0
- package/lib/tunnelDaemon.js +236 -0
- package/nodes/nr-connect-notify.html +258 -0
- package/nodes/nr-connect-notify.js +303 -0
- package/nodes/ui-nr-connect-profile.html +211 -0
- package/nodes/ui-nr-connect-profile.js +66 -0
- package/package.json +80 -6
- package/resources/ui-nr-connect-profile.umd.js +213 -0
- package/ui/UINrConnectProfile.js +1173 -0
- package/ui/profile.js +1 -0
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const crypto = require("crypto");
|
|
4
|
+
const { version: PACKAGE_VERSION = "1.0.0" } = require("../package.json");
|
|
5
|
+
const { verifyWorkerHeaders } = require("./expressInterceptor");
|
|
6
|
+
|
|
7
|
+
const STATUS_PATH = "/_nrc/status";
|
|
8
|
+
const PROTOCOL_VERSION = 1;
|
|
9
|
+
|
|
10
|
+
function getHeader(req, name) {
|
|
11
|
+
if (!req || !req.headers) return undefined;
|
|
12
|
+
const val = req.headers[name] ?? req.headers[name.toLowerCase()];
|
|
13
|
+
return Array.isArray(val) ? val[0] : val;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function getNormalizedPathname(req) {
|
|
17
|
+
const raw = req?.url || req?.originalUrl || req?.path || "";
|
|
18
|
+
if (typeof raw !== "string" || !raw) return "";
|
|
19
|
+
const withoutHash = raw.split("#")[0];
|
|
20
|
+
const withoutQuery = withoutHash.split("?")[0];
|
|
21
|
+
return withoutQuery;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function sendJson(res, statusCode, payload) {
|
|
25
|
+
const body = JSON.stringify(payload);
|
|
26
|
+
res.writeHead(statusCode, {
|
|
27
|
+
"Content-Type": "application/json; charset=utf-8",
|
|
28
|
+
"Cache-Control": "no-store",
|
|
29
|
+
"Content-Length": Buffer.byteLength(body, "utf8"),
|
|
30
|
+
});
|
|
31
|
+
res.end(body);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Verify a Worker-signed GET /_nrc/status probe request.
|
|
36
|
+
* Always fail-closed: requires V1 + V2 + purpose="status" + tunnelId-bound status signature,
|
|
37
|
+
* regardless of requireSecureAccess and with NO loopback / unlock escape hatch.
|
|
38
|
+
*
|
|
39
|
+
* @param {object} req
|
|
40
|
+
* @param {{ sharedSecret?: string, tunnelId?: string } | null} config
|
|
41
|
+
* @param {number} [nowMs]
|
|
42
|
+
* @returns {{ user: object, allowedPages: string[] } | null}
|
|
43
|
+
*/
|
|
44
|
+
function verifyStatusProbeRequest(req, config, nowMs = Date.now()) {
|
|
45
|
+
if (!config || !config.sharedSecret || !config.tunnelId) {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const method = typeof req?.method === "string" ? req.method.toUpperCase() : "";
|
|
50
|
+
if (method !== "GET") {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const pathname = getNormalizedPathname(req);
|
|
55
|
+
if (pathname !== STATUS_PATH) {
|
|
56
|
+
return null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const signatureV2 = getHeader(req, "x-nr-connect-signature-v2");
|
|
60
|
+
const purpose = getHeader(req, "x-nr-connect-purpose");
|
|
61
|
+
const statusSignature = getHeader(req, "x-nr-connect-status-signature");
|
|
62
|
+
const timestamp = getHeader(req, "x-nr-connect-timestamp");
|
|
63
|
+
const userJson = getHeader(req, "x-nr-connect-user");
|
|
64
|
+
|
|
65
|
+
if (!signatureV2 || purpose !== "status" || !statusSignature || !timestamp || !userJson) {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const verified = verifyWorkerHeaders(req, config.sharedSecret, nowMs);
|
|
70
|
+
if (!verified) {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const expectedStatusSigHex = crypto
|
|
75
|
+
.createHmac("sha256", config.sharedSecret)
|
|
76
|
+
.update(`${timestamp}.GET.${STATUS_PATH}.status.${config.tunnelId}.${userJson}`)
|
|
77
|
+
.digest("hex");
|
|
78
|
+
|
|
79
|
+
const providedBuf = Buffer.from(String(statusSignature).trim().toLowerCase(), "utf8");
|
|
80
|
+
const expectedBuf = Buffer.from(expectedStatusSigHex, "utf8");
|
|
81
|
+
|
|
82
|
+
if (
|
|
83
|
+
providedBuf.length !== expectedBuf.length ||
|
|
84
|
+
!crypto.timingSafeEqual(providedBuf, expectedBuf)
|
|
85
|
+
) {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return verified;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Create a request handler for GET /_nrc/status.
|
|
94
|
+
* Returns true if the request matched /_nrc/status and was handled, false otherwise.
|
|
95
|
+
*
|
|
96
|
+
* @param {{
|
|
97
|
+
* getPluginConfig: Function,
|
|
98
|
+
* getRuntimeStatus?: Function,
|
|
99
|
+
* runtimeSessionId?: string,
|
|
100
|
+
* pluginVersion?: string,
|
|
101
|
+
* nowMs?: Function,
|
|
102
|
+
* }} options
|
|
103
|
+
*/
|
|
104
|
+
function createStatusRequestHandler(options) {
|
|
105
|
+
const {
|
|
106
|
+
getPluginConfig,
|
|
107
|
+
getRuntimeStatus,
|
|
108
|
+
runtimeSessionId = crypto.randomBytes(8).toString("hex"),
|
|
109
|
+
pluginVersion = PACKAGE_VERSION,
|
|
110
|
+
nowMs = () => Date.now(),
|
|
111
|
+
} = options || {};
|
|
112
|
+
|
|
113
|
+
return function handleStatusRequest(req, res) {
|
|
114
|
+
const pathname = getNormalizedPathname(req);
|
|
115
|
+
if (pathname !== STATUS_PATH) {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const method = typeof req?.method === "string" ? req.method.toUpperCase() : "";
|
|
120
|
+
if (method !== "GET") {
|
|
121
|
+
sendJson(res, 405, { ok: false, error: "method_not_allowed" });
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const config = typeof getPluginConfig === "function" ? getPluginConfig() : null;
|
|
126
|
+
if (!config || !config.sharedSecret || !config.tunnelId) {
|
|
127
|
+
sendJson(res, 503, { ok: false, error: "not_connected" });
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const verified = verifyStatusProbeRequest(req, config, nowMs());
|
|
132
|
+
if (!verified) {
|
|
133
|
+
sendJson(res, 403, { ok: false, error: "forbidden" });
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const status = typeof getRuntimeStatus === "function" ? getRuntimeStatus() : null;
|
|
138
|
+
const daemonState =
|
|
139
|
+
typeof status?.connector === "string" && status.connector
|
|
140
|
+
? status.connector
|
|
141
|
+
: "connected";
|
|
142
|
+
|
|
143
|
+
sendJson(res, 200, {
|
|
144
|
+
ok: true,
|
|
145
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
146
|
+
instanceId: config.tunnelId,
|
|
147
|
+
runtimeSessionId,
|
|
148
|
+
daemonState,
|
|
149
|
+
pluginVersion,
|
|
150
|
+
serverTimeIso: new Date(nowMs()).toISOString(),
|
|
151
|
+
});
|
|
152
|
+
return true;
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Attach GET /_nrc/status directly on RED.server before Express/httpAdmin/httpNode routing
|
|
158
|
+
* so it works regardless of custom httpAdminRoot or httpNodeRoot settings and never
|
|
159
|
+
* triggers double-response errors on Node-RED's Express handlers.
|
|
160
|
+
*
|
|
161
|
+
* Returns an idempotent uninstall function for clean teardown in onremove().
|
|
162
|
+
*
|
|
163
|
+
* @param {object} RED
|
|
164
|
+
* @param {{
|
|
165
|
+
* getPluginConfig: Function,
|
|
166
|
+
* getRuntimeStatus?: Function,
|
|
167
|
+
* runtimeSessionId?: string,
|
|
168
|
+
* pluginVersion?: string,
|
|
169
|
+
* nowMs?: Function,
|
|
170
|
+
* }} options
|
|
171
|
+
* @returns {Function} uninstall
|
|
172
|
+
*/
|
|
173
|
+
function installStatusEndpoint(RED, options) {
|
|
174
|
+
const server = RED?.server;
|
|
175
|
+
if (!server) {
|
|
176
|
+
return () => {};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
if (typeof server.__nrConnectUninstallStatusEndpoint === "function") {
|
|
180
|
+
return server.__nrConnectUninstallStatusEndpoint;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const handleStatusRequest = createStatusRequestHandler(options);
|
|
184
|
+
|
|
185
|
+
if (typeof server.emit === "function") {
|
|
186
|
+
let active = true;
|
|
187
|
+
const originalEmit = server.emit;
|
|
188
|
+
const patchedEmit = function nrConnectStatusEmit(event, req, res, ...rest) {
|
|
189
|
+
if (active && event === "request" && req && res && handleStatusRequest(req, res)) {
|
|
190
|
+
return true;
|
|
191
|
+
}
|
|
192
|
+
return originalEmit.call(this, event, req, res, ...rest);
|
|
193
|
+
};
|
|
194
|
+
server.emit = patchedEmit;
|
|
195
|
+
|
|
196
|
+
const uninstall = () => {
|
|
197
|
+
active = false;
|
|
198
|
+
if (server.emit === patchedEmit) {
|
|
199
|
+
server.emit = originalEmit;
|
|
200
|
+
}
|
|
201
|
+
delete server.__nrConnectUninstallStatusEndpoint;
|
|
202
|
+
};
|
|
203
|
+
server.__nrConnectUninstallStatusEndpoint = uninstall;
|
|
204
|
+
return uninstall;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
if (typeof server.prependListener === "function") {
|
|
208
|
+
const onRequest = (req, res) => {
|
|
209
|
+
handleStatusRequest(req, res);
|
|
210
|
+
};
|
|
211
|
+
server.prependListener("request", onRequest);
|
|
212
|
+
const uninstall = () => {
|
|
213
|
+
if (typeof server.removeListener === "function") {
|
|
214
|
+
server.removeListener("request", onRequest);
|
|
215
|
+
}
|
|
216
|
+
delete server.__nrConnectUninstallStatusEndpoint;
|
|
217
|
+
};
|
|
218
|
+
server.__nrConnectUninstallStatusEndpoint = uninstall;
|
|
219
|
+
return uninstall;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return () => {};
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
module.exports = {
|
|
226
|
+
STATUS_PATH,
|
|
227
|
+
PROTOCOL_VERSION,
|
|
228
|
+
verifyStatusProbeRequest,
|
|
229
|
+
createStatusRequestHandler,
|
|
230
|
+
installStatusEndpoint,
|
|
231
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const TOKEN_PREFIX = "nrc_";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Encode a composite tunnel provisioning payload into a single `nrc_...` token string.
|
|
7
|
+
* @param {{ tunnelId: string, cfTunnelToken: string, sharedSecret: string, apiUrl: string }} payload
|
|
8
|
+
* @returns {string}
|
|
9
|
+
*/
|
|
10
|
+
function encodeCompositeToken(payload) {
|
|
11
|
+
if (!payload || typeof payload !== "object") {
|
|
12
|
+
throw new TypeError("Composite token payload must be an object");
|
|
13
|
+
}
|
|
14
|
+
const { tunnelId, cfTunnelToken, sharedSecret, apiUrl } = payload;
|
|
15
|
+
if (!tunnelId || !cfTunnelToken || !sharedSecret || !apiUrl) {
|
|
16
|
+
throw new Error("Missing required fields for composite token (tunnelId, cfTunnelToken, sharedSecret, apiUrl)");
|
|
17
|
+
}
|
|
18
|
+
const normalized = {
|
|
19
|
+
tunnelId: String(tunnelId),
|
|
20
|
+
cfTunnelToken: String(cfTunnelToken),
|
|
21
|
+
sharedSecret: String(sharedSecret),
|
|
22
|
+
apiUrl: String(apiUrl).replace(/\/+$/, ""),
|
|
23
|
+
};
|
|
24
|
+
const encoded = Buffer.from(JSON.stringify(normalized), "utf8").toString("base64url");
|
|
25
|
+
return `${TOKEN_PREFIX}${encoded}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Decode and validate an `nrc_...` composite tunnel token.
|
|
30
|
+
* Supports both Base64URL and standard Base64 payloads.
|
|
31
|
+
* @param {string} rawToken
|
|
32
|
+
* @returns {{ tunnelId: string, cfTunnelToken: string, sharedSecret: string, apiUrl: string, rawToken: string }}
|
|
33
|
+
*/
|
|
34
|
+
function decodeCompositeToken(rawToken) {
|
|
35
|
+
if (typeof rawToken !== "string") {
|
|
36
|
+
throw new Error("Tunnel token must be a string");
|
|
37
|
+
}
|
|
38
|
+
const trimmed = rawToken.trim();
|
|
39
|
+
if (!trimmed.startsWith(TOKEN_PREFIX)) {
|
|
40
|
+
throw new Error(`Invalid tunnel token format: expected '${TOKEN_PREFIX}' prefix`);
|
|
41
|
+
}
|
|
42
|
+
const encodedPart = trimmed.slice(TOKEN_PREFIX.length);
|
|
43
|
+
if (!encodedPart) {
|
|
44
|
+
throw new Error("Invalid tunnel token: empty payload");
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Normalize standard base64 or base64url into base64url for Node Buffer decoding
|
|
48
|
+
const normalizedB64 = encodedPart.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
49
|
+
let parsed;
|
|
50
|
+
try {
|
|
51
|
+
const jsonStr = Buffer.from(normalizedB64, "base64url").toString("utf8");
|
|
52
|
+
parsed = JSON.parse(jsonStr);
|
|
53
|
+
} catch (err) {
|
|
54
|
+
throw new Error(`Failed to decode tunnel token JSON: ${err.message}`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (!parsed || typeof parsed !== "object") {
|
|
58
|
+
throw new Error("Invalid tunnel token payload");
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const requiredFields = ["tunnelId", "cfTunnelToken", "sharedSecret", "apiUrl"];
|
|
62
|
+
for (const field of requiredFields) {
|
|
63
|
+
if (typeof parsed[field] !== "string" || parsed[field].trim() === "") {
|
|
64
|
+
throw new Error(`Invalid tunnel token: missing '${field}'`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const apiUrl = parsed.apiUrl.trim().replace(/\/+$/, "");
|
|
69
|
+
let parsedApiUrl;
|
|
70
|
+
try {
|
|
71
|
+
parsedApiUrl = new URL(apiUrl);
|
|
72
|
+
} catch {
|
|
73
|
+
throw new Error("Invalid tunnel token: malformed 'apiUrl'");
|
|
74
|
+
}
|
|
75
|
+
const apiHost = parsedApiUrl.hostname.toLowerCase();
|
|
76
|
+
const isLoopbackApi =
|
|
77
|
+
apiHost === "localhost" || apiHost === "127.0.0.1" || apiHost === "::1" || apiHost === "[::1]";
|
|
78
|
+
if (
|
|
79
|
+
parsedApiUrl.protocol !== "https:" &&
|
|
80
|
+
!(parsedApiUrl.protocol === "http:" && isLoopbackApi)
|
|
81
|
+
) {
|
|
82
|
+
throw new Error("Invalid tunnel token: 'apiUrl' must use https");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
tunnelId: parsed.tunnelId.trim(),
|
|
87
|
+
cfTunnelToken: parsed.cfTunnelToken.trim(),
|
|
88
|
+
sharedSecret: parsed.sharedSecret.trim(),
|
|
89
|
+
apiUrl,
|
|
90
|
+
rawToken: trimmed,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
module.exports = {
|
|
95
|
+
TOKEN_PREFIX,
|
|
96
|
+
encodeCompositeToken,
|
|
97
|
+
decodeCompositeToken,
|
|
98
|
+
};
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const { spawn } = require("child_process");
|
|
4
|
+
|
|
5
|
+
function sanitizeProcessError(err, binaryPath) {
|
|
6
|
+
let msg = typeof err?.message === "string" ? err.message : String(err || "unknown error");
|
|
7
|
+
if (typeof binaryPath === "string" && binaryPath) {
|
|
8
|
+
msg = msg.split(binaryPath).join("connector");
|
|
9
|
+
}
|
|
10
|
+
msg = msg
|
|
11
|
+
.replace(/cloudflared(?:\.exe)?/gi, "connector")
|
|
12
|
+
.replace(/cloudflare/gi, "remote");
|
|
13
|
+
return msg;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Supervises a single `cloudflared` daemon child process with exponential backoff restarts.
|
|
18
|
+
*/
|
|
19
|
+
class TunnelDaemon {
|
|
20
|
+
/**
|
|
21
|
+
* @param {{
|
|
22
|
+
* binaryPath: string,
|
|
23
|
+
* cfTunnelToken: string,
|
|
24
|
+
* logger?: { info?: Function, warn?: Function, error?: Function, debug?: Function },
|
|
25
|
+
* onStatusChange?: (status: { state: string, detail?: string, pid?: number|null, lastError?: string|null }) => void,
|
|
26
|
+
* spawnImpl?: Function
|
|
27
|
+
* }} opts
|
|
28
|
+
*/
|
|
29
|
+
constructor(opts) {
|
|
30
|
+
this.binaryPath = opts.binaryPath;
|
|
31
|
+
this.cfTunnelToken = opts.cfTunnelToken;
|
|
32
|
+
this.logger = opts.logger || console;
|
|
33
|
+
this.onStatusChange = opts.onStatusChange || (() => {});
|
|
34
|
+
this.spawnImpl = opts.spawnImpl || spawn;
|
|
35
|
+
|
|
36
|
+
this.child = null;
|
|
37
|
+
this.stopped = false;
|
|
38
|
+
this.restartAttempts = 0;
|
|
39
|
+
this.restartTimer = null;
|
|
40
|
+
this.state = "idle";
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
setState(state, detail = "", lastError = null) {
|
|
44
|
+
this.state = state;
|
|
45
|
+
this.onStatusChange({
|
|
46
|
+
state,
|
|
47
|
+
detail,
|
|
48
|
+
pid: this.child ? this.child.pid : null,
|
|
49
|
+
lastError,
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
start() {
|
|
54
|
+
this.stopped = false;
|
|
55
|
+
this._launchProcess();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
_launchProcess() {
|
|
59
|
+
if (this.stopped) return;
|
|
60
|
+
if (this.restartTimer) {
|
|
61
|
+
clearTimeout(this.restartTimer);
|
|
62
|
+
this.restartTimer = null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
this.setState("connecting", "Starting connector");
|
|
66
|
+
|
|
67
|
+
const args = ["tunnel", "--no-autoupdate", "run"];
|
|
68
|
+
const child = this.spawnImpl(this.binaryPath, args, {
|
|
69
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
70
|
+
windowsHide: true,
|
|
71
|
+
env: {
|
|
72
|
+
...process.env,
|
|
73
|
+
TUNNEL_TOKEN: this.cfTunnelToken,
|
|
74
|
+
},
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
this.child = child;
|
|
78
|
+
|
|
79
|
+
const handleLogLine = (chunk) => {
|
|
80
|
+
const text = chunk.toString("utf8").trim();
|
|
81
|
+
if (!text) return;
|
|
82
|
+
for (const line of text.split(/\r?\n/)) {
|
|
83
|
+
if (/Registered tunnel connection/i.test(line) || /Connection .* registered/i.test(line)) {
|
|
84
|
+
this.restartAttempts = 0;
|
|
85
|
+
this.setState("connected", "Remote connector connected");
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
child.stdout?.on("data", handleLogLine);
|
|
91
|
+
child.stderr?.on("data", handleLogLine);
|
|
92
|
+
|
|
93
|
+
child.on("error", (err) => {
|
|
94
|
+
const safeMessage = sanitizeProcessError(err, this.binaryPath);
|
|
95
|
+
this.logger.error?.(`[NR Connect] Connector process error: ${safeMessage}`);
|
|
96
|
+
this.setState("error", "Failed to start connector", safeMessage);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
child.on("exit", (code, signal) => {
|
|
100
|
+
this.child = null;
|
|
101
|
+
if (this.stopped) {
|
|
102
|
+
this.setState("stopped", "Connector stopped");
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const reason = signal ? `signal ${signal}` : `exit code ${code}`;
|
|
107
|
+
this.logger.warn?.(`[NR Connect] Connector exited unexpectedly (${reason})`);
|
|
108
|
+
this._scheduleRestart(reason);
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
_scheduleRestart(reason) {
|
|
113
|
+
if (this.stopped) return;
|
|
114
|
+
this.restartAttempts += 1;
|
|
115
|
+
const delayMs = Math.min(30000, 1000 * Math.pow(2, Math.min(this.restartAttempts - 1, 5)));
|
|
116
|
+
this.setState("reconnecting", `Restarting in ${Math.round(delayMs / 1000)}s (${reason})`, reason);
|
|
117
|
+
this.restartTimer = setTimeout(() => {
|
|
118
|
+
this._launchProcess();
|
|
119
|
+
}, delayMs);
|
|
120
|
+
if (typeof this.restartTimer.unref === "function") {
|
|
121
|
+
this.restartTimer.unref();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
stop() {
|
|
126
|
+
this.stopped = true;
|
|
127
|
+
if (this.restartTimer) {
|
|
128
|
+
clearTimeout(this.restartTimer);
|
|
129
|
+
this.restartTimer = null;
|
|
130
|
+
}
|
|
131
|
+
if (this.child && !this.child.killed) {
|
|
132
|
+
try {
|
|
133
|
+
this.child.kill("SIGTERM");
|
|
134
|
+
} catch {
|
|
135
|
+
// Ignore termination failure
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
this.child = null;
|
|
139
|
+
this.setState("stopped", "Connector stopped");
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Stop the supervised daemon and wait until the OS process exits so binary files
|
|
144
|
+
* (especially on Windows) can be replaced cleanly without file-lock errors.
|
|
145
|
+
* @param {number} [timeoutMs]
|
|
146
|
+
* @returns {Promise<void>}
|
|
147
|
+
*/
|
|
148
|
+
stopAndWait(timeoutMs = 5000) {
|
|
149
|
+
this.stopped = true;
|
|
150
|
+
if (this.restartTimer) {
|
|
151
|
+
clearTimeout(this.restartTimer);
|
|
152
|
+
this.restartTimer = null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const child = this.child;
|
|
156
|
+
if (!child || child.exitCode !== null || child.signalCode !== null) {
|
|
157
|
+
this.child = null;
|
|
158
|
+
this.setState("stopped", "Connector stopped");
|
|
159
|
+
return Promise.resolve();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
return new Promise((resolve) => {
|
|
163
|
+
let settled = false;
|
|
164
|
+
let killTimer = null;
|
|
165
|
+
let forceFinishTimer = null;
|
|
166
|
+
|
|
167
|
+
const finish = () => {
|
|
168
|
+
if (settled) return;
|
|
169
|
+
settled = true;
|
|
170
|
+
if (killTimer) clearTimeout(killTimer);
|
|
171
|
+
if (forceFinishTimer) clearTimeout(forceFinishTimer);
|
|
172
|
+
if (typeof child.off === "function") {
|
|
173
|
+
child.off("exit", finish);
|
|
174
|
+
} else if (typeof child.removeListener === "function") {
|
|
175
|
+
child.removeListener("exit", finish);
|
|
176
|
+
}
|
|
177
|
+
this.child = null;
|
|
178
|
+
this.setState("stopped", "Connector stopped");
|
|
179
|
+
resolve();
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
if (typeof child.once === "function") {
|
|
183
|
+
child.once("exit", finish);
|
|
184
|
+
} else if (typeof child.on === "function") {
|
|
185
|
+
child.on("exit", finish);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
killTimer = setTimeout(() => {
|
|
189
|
+
if (!settled) {
|
|
190
|
+
try {
|
|
191
|
+
child.kill("SIGKILL");
|
|
192
|
+
} catch {
|
|
193
|
+
// Ignore force-kill errors
|
|
194
|
+
}
|
|
195
|
+
forceFinishTimer = setTimeout(finish, 100);
|
|
196
|
+
}
|
|
197
|
+
}, timeoutMs);
|
|
198
|
+
|
|
199
|
+
try {
|
|
200
|
+
child.kill("SIGTERM");
|
|
201
|
+
} catch {
|
|
202
|
+
finish();
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Replace the supervised binary path cleanly and relaunch the daemon.
|
|
209
|
+
* @param {string} newBinaryPath
|
|
210
|
+
* @returns {Promise<void>}
|
|
211
|
+
*/
|
|
212
|
+
async restartWithBinary(newBinaryPath) {
|
|
213
|
+
await this.stopAndWait();
|
|
214
|
+
if (newBinaryPath) {
|
|
215
|
+
this.binaryPath = newBinaryPath;
|
|
216
|
+
}
|
|
217
|
+
this.restartAttempts = 0;
|
|
218
|
+
this.start();
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Convenience factory to spawn and immediately start a supervised cloudflared daemon.
|
|
224
|
+
* @param {object} opts
|
|
225
|
+
* @returns {TunnelDaemon}
|
|
226
|
+
*/
|
|
227
|
+
function spawnCloudflared(opts) {
|
|
228
|
+
const daemon = new TunnelDaemon(opts);
|
|
229
|
+
daemon.start();
|
|
230
|
+
return daemon;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
module.exports = {
|
|
234
|
+
TunnelDaemon,
|
|
235
|
+
spawnCloudflared,
|
|
236
|
+
};
|