@xkwdstore/agent 2.1.0 → 2.1.2
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/README.md +278 -278
- package/package.json +41 -63
- package/scripts/broker-service-host.cs +208 -0
- package/scripts/install-machine-agent.ps1 +1 -1
- package/scripts/session-launcher.cs +163 -0
- package/scripts/worker-entry.js +1 -1
- package/src/brokerConnectionSupervisor.js +263 -0
- package/src/cli.js +1108 -1108
- package/src/ed25519Codec.js +158 -0
- package/src/index.js +2013 -0
- package/src/updater.js +578 -0
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
// XKWDStore Agent 2.1.0 — compiled Windows Service host (broker).
|
|
2
|
+
//
|
|
3
|
+
// WHY COMPILED: a Windows service binary must call StartServiceCtrlDispatcher and
|
|
4
|
+
// report SERVICE_RUNNING. `powershell.exe -File <script>` proved unreliable as an
|
|
5
|
+
// SCM binary (it exits before running). This EXE is compiled by the installer with
|
|
6
|
+
// the IN-BOX .NET Framework compiler (csc.exe, no external dependency) and is the
|
|
7
|
+
// SCM-facing process. It:
|
|
8
|
+
//
|
|
9
|
+
// 1. launches `node <cli.js> service ...` as a CHILD in Session 0 with a fixed
|
|
10
|
+
// working directory, no window, and file-redirected stdio;
|
|
11
|
+
// 2. reports SERVICE_RUNNING immediately;
|
|
12
|
+
// 3. kills the child on stop/shutdown;
|
|
13
|
+
// 4. restarts the child if it exits unexpectedly (bounded backoff) so a broker
|
|
14
|
+
// crash recovers without relying solely on the SCM;
|
|
15
|
+
// 5. logs SAFE lifecycle info only (no credentials, no key material).
|
|
16
|
+
//
|
|
17
|
+
// The broker owns the machine identity/WebSocket/leases and never launches
|
|
18
|
+
// Chromium; browser work is delegated to an interactive-session worker.
|
|
19
|
+
|
|
20
|
+
using System;
|
|
21
|
+
using System.Diagnostics;
|
|
22
|
+
using System.IO;
|
|
23
|
+
using System.ServiceProcess;
|
|
24
|
+
using System.Threading;
|
|
25
|
+
|
|
26
|
+
public sealed class XkwdBrokerService : ServiceBase
|
|
27
|
+
{
|
|
28
|
+
private readonly string _node;
|
|
29
|
+
private readonly string _argLine;
|
|
30
|
+
private readonly string _workDir;
|
|
31
|
+
private readonly string _logFile;
|
|
32
|
+
private readonly string _outFile;
|
|
33
|
+
private readonly string _errFile;
|
|
34
|
+
|
|
35
|
+
private Process _child;
|
|
36
|
+
private Thread _watch;
|
|
37
|
+
private volatile bool _stopping;
|
|
38
|
+
private static readonly object _logLock = new object();
|
|
39
|
+
|
|
40
|
+
public XkwdBrokerService(string node, string argLine, string workDir, string logFile, string outFile, string errFile)
|
|
41
|
+
{
|
|
42
|
+
this.ServiceName = "XKWDStoreAgentBroker";
|
|
43
|
+
this.CanStop = true;
|
|
44
|
+
this.CanShutdown = true;
|
|
45
|
+
this.CanPauseAndContinue = false;
|
|
46
|
+
_node = node; _argLine = argLine; _workDir = workDir;
|
|
47
|
+
_logFile = logFile; _outFile = outFile; _errFile = errFile;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
private static void Log(string file, string message)
|
|
51
|
+
{
|
|
52
|
+
try
|
|
53
|
+
{
|
|
54
|
+
lock (_logLock)
|
|
55
|
+
{
|
|
56
|
+
File.AppendAllText(file, string.Format("[{0}] {1}{2}", DateTime.UtcNow.ToString("o"), message, Environment.NewLine));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
catch { }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
private void Log(string message) { Log(_logFile, message); }
|
|
63
|
+
|
|
64
|
+
private void StartChild()
|
|
65
|
+
{
|
|
66
|
+
var psi = new ProcessStartInfo(_node, _argLine);
|
|
67
|
+
psi.UseShellExecute = false;
|
|
68
|
+
psi.CreateNoWindow = true;
|
|
69
|
+
psi.WorkingDirectory = _workDir;
|
|
70
|
+
psi.RedirectStandardOutput = true;
|
|
71
|
+
psi.RedirectStandardError = true;
|
|
72
|
+
var p = new Process();
|
|
73
|
+
p.StartInfo = psi;
|
|
74
|
+
p.OutputDataReceived += (s, e) => { if (e.Data != null) Log(_outFile, e.Data); };
|
|
75
|
+
p.ErrorDataReceived += (s, e) => { if (e.Data != null) Log(_errFile, e.Data); };
|
|
76
|
+
p.Start();
|
|
77
|
+
p.BeginOutputReadLine();
|
|
78
|
+
p.BeginErrorReadLine();
|
|
79
|
+
_child = p;
|
|
80
|
+
Log("broker child started pid=" + p.Id);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
protected override void OnStart(string[] args)
|
|
84
|
+
{
|
|
85
|
+
Log("service OnStart node=" + _node + " workdir=" + _workDir);
|
|
86
|
+
try { StartChild(); }
|
|
87
|
+
catch (Exception ex) { Log("broker child start FAILED: " + ex.Message); }
|
|
88
|
+
// Watchdog: if the broker dies unexpectedly (not during stop), restart it
|
|
89
|
+
// with a bounded backoff so a crash does not require a manual restart.
|
|
90
|
+
_watch = new Thread(() =>
|
|
91
|
+
{
|
|
92
|
+
int attempts = 0;
|
|
93
|
+
int[] delays = new int[] { 5000, 15000, 60000 };
|
|
94
|
+
while (!_stopping)
|
|
95
|
+
{
|
|
96
|
+
Thread.Sleep(2000);
|
|
97
|
+
if (_stopping) break;
|
|
98
|
+
Process c = _child;
|
|
99
|
+
if (c == null) continue;
|
|
100
|
+
try
|
|
101
|
+
{
|
|
102
|
+
if (!c.HasExited)
|
|
103
|
+
{
|
|
104
|
+
if (attempts != 0) attempts = 0; // healthy
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
catch { continue; }
|
|
109
|
+
if (_stopping) break;
|
|
110
|
+
int d = delays[Math.Min(attempts, delays.Length - 1)];
|
|
111
|
+
attempts++;
|
|
112
|
+
Log("broker child exited code=" + (SafeExit(c)) + "; restart in " + d + "ms (attempt " + attempts + ")");
|
|
113
|
+
Thread.Sleep(d);
|
|
114
|
+
if (_stopping) break;
|
|
115
|
+
try { StartChild(); } catch (Exception ex) { Log("broker restart failed: " + ex.Message); }
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
_watch.IsBackground = true;
|
|
119
|
+
_watch.Start();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
private static string SafeExit(Process p)
|
|
123
|
+
{
|
|
124
|
+
try { return p.ExitCode.ToString(); } catch { return "unknown"; }
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
protected override void OnStop()
|
|
128
|
+
{
|
|
129
|
+
_stopping = true;
|
|
130
|
+
Log("service OnStop");
|
|
131
|
+
StopChild();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
protected override void OnShutdown()
|
|
135
|
+
{
|
|
136
|
+
_stopping = true;
|
|
137
|
+
Log("service OnShutdown");
|
|
138
|
+
StopChild();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
private void StopChild()
|
|
142
|
+
{
|
|
143
|
+
try
|
|
144
|
+
{
|
|
145
|
+
Process c = _child;
|
|
146
|
+
if (c != null && !c.HasExited)
|
|
147
|
+
{
|
|
148
|
+
c.Kill();
|
|
149
|
+
c.WaitForExit(15000);
|
|
150
|
+
Log("broker child stopped");
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch (Exception ex) { Log("StopChild error: " + ex.Message); }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
public static void Main()
|
|
157
|
+
{
|
|
158
|
+
try
|
|
159
|
+
{
|
|
160
|
+
string node = null, cli = null, root = null, server = "https://x.kwdstore.com";
|
|
161
|
+
// Args are supplied by the SCM binPath as: -Node <n> -Cli <c> -Root <r> -Server <s>
|
|
162
|
+
var a = Environment.GetCommandLineArgs();
|
|
163
|
+
for (int i = 1; i < a.Length - 1; i++)
|
|
164
|
+
{
|
|
165
|
+
switch (a[i])
|
|
166
|
+
{
|
|
167
|
+
case "-Node": node = a[++i]; break;
|
|
168
|
+
case "-Cli": cli = a[++i]; break;
|
|
169
|
+
case "-Root": root = a[++i]; break;
|
|
170
|
+
case "-Server": server = a[++i]; break;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
if (node == null || cli == null || root == null)
|
|
174
|
+
{
|
|
175
|
+
// Not enough info to run as a service.
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
string workDir = Path.GetDirectoryName(cli);
|
|
179
|
+
string logDir = Path.Combine(root, "logs");
|
|
180
|
+
Directory.CreateDirectory(logDir);
|
|
181
|
+
string logFile = Path.Combine(logDir, "service-host.log");
|
|
182
|
+
string outFile = Path.Combine(logDir, "broker.out.log");
|
|
183
|
+
string errFile = Path.Combine(logDir, "broker.err.log");
|
|
184
|
+
|
|
185
|
+
Environment.SetEnvironmentVariable("XKWDSTORE_MACHINE_ROOT", root);
|
|
186
|
+
Environment.SetEnvironmentVariable("XKWDSTORE_DPAPI_SCOPE", "LocalMachine");
|
|
187
|
+
|
|
188
|
+
string argLine = "\"" + cli + "\" service --server \"" + server + "\"";
|
|
189
|
+
ServiceBase.Run(new XkwdBrokerService(node, argLine, workDir, logFile, outFile, errFile));
|
|
190
|
+
}
|
|
191
|
+
catch (Exception ex)
|
|
192
|
+
{
|
|
193
|
+
try
|
|
194
|
+
{
|
|
195
|
+
string root = null;
|
|
196
|
+
var a = Environment.GetCommandLineArgs();
|
|
197
|
+
for (int i = 1; i < a.Length - 1; i++) if (a[i] == "-Root") root = a[++i];
|
|
198
|
+
if (root != null)
|
|
199
|
+
{
|
|
200
|
+
string logDir = Path.Combine(root, "logs");
|
|
201
|
+
Directory.CreateDirectory(logDir);
|
|
202
|
+
Log(Path.Combine(logDir, "service-host.log"), "FATAL Main: " + ex.ToString());
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
catch { }
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
# -NoLaunch (test) validate + write files, never start a process
|
|
36
36
|
|
|
37
37
|
param(
|
|
38
|
-
[string]$AgentVersion = '2.1.
|
|
38
|
+
[string]$AgentVersion = '2.1.2',
|
|
39
39
|
[string]$Server = 'https://x.kwdstore.com',
|
|
40
40
|
[string]$ServiceAccount = 'LocalSystem',
|
|
41
41
|
[string]$AgentRoot,
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
// XKWDStore Agent 2.1.0 — interactive-session process launcher.
|
|
2
|
+
//
|
|
3
|
+
// WHY THIS EXISTS
|
|
4
|
+
// ---------------
|
|
5
|
+
// The machine broker runs as a Windows SERVICE in Session 0. Session 0 has no
|
|
6
|
+
// interactive desktop, so a Chromium window launched from the broker would be
|
|
7
|
+
// invisible/non-functional. The broker must launch its Browser Worker into the
|
|
8
|
+
// ACTIVE INTERACTIVE USER SESSION.
|
|
9
|
+
//
|
|
10
|
+
// This helper, run by the broker (LocalSystem), launches a process in the active
|
|
11
|
+
// console session using CreateProcessAsUser with the session's user token:
|
|
12
|
+
//
|
|
13
|
+
// WTSGetActiveConsoleSessionId -> WTSQueryUserToken ->
|
|
14
|
+
// DuplicateTokenEx -> CreateEnvironmentBlock -> CreateProcessAsUser
|
|
15
|
+
//
|
|
16
|
+
// It requires SeTcbPrivilege (LocalSystem has it). It launches EXACTLY the
|
|
17
|
+
// command it is given (node + worker.js + invite), never a shell, and passes no
|
|
18
|
+
// secret. The worker then authenticates to the broker over the loopback channel.
|
|
19
|
+
//
|
|
20
|
+
// The launched child inherits the USER's desktop (session), so Chromium appears
|
|
21
|
+
// on that user's screen.
|
|
22
|
+
|
|
23
|
+
using System;
|
|
24
|
+
using System.ComponentModel;
|
|
25
|
+
using System.Diagnostics;
|
|
26
|
+
using System.Runtime.InteropServices;
|
|
27
|
+
|
|
28
|
+
internal static class SessionLauncher
|
|
29
|
+
{
|
|
30
|
+
[DllImport("kernel32.dll")]
|
|
31
|
+
private static extern uint WTSGetActiveConsoleSessionId();
|
|
32
|
+
|
|
33
|
+
[DllImport("wtsapi32.dll", SetLastError = true)]
|
|
34
|
+
private static extern bool WTSQueryUserToken(uint sessionId, out IntPtr token);
|
|
35
|
+
|
|
36
|
+
[DllImport("advapi32.dll", SetLastError = true)]
|
|
37
|
+
private static extern bool DuplicateTokenEx(IntPtr existing, uint desiredAccess, IntPtr attrs,
|
|
38
|
+
int impersonationLevel, int tokenType, out IntPtr newToken);
|
|
39
|
+
|
|
40
|
+
[DllImport("userenv.dll", SetLastError = true)]
|
|
41
|
+
private static extern bool CreateEnvironmentBlock(out IntPtr env, IntPtr token, bool inherit);
|
|
42
|
+
|
|
43
|
+
[DllImport("userenv.dll", SetLastError = true)]
|
|
44
|
+
private static extern bool DestroyEnvironmentBlock(IntPtr env);
|
|
45
|
+
|
|
46
|
+
[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
47
|
+
private static extern bool CreateProcessAsUser(IntPtr token, string app, string cmdLine,
|
|
48
|
+
IntPtr procAttrs, IntPtr threadAttrs, bool inherit, uint flags, IntPtr env, string cwd,
|
|
49
|
+
ref STARTUPINFO si, out PROCESS_INFORMATION pi);
|
|
50
|
+
|
|
51
|
+
[DllImport("kernel32.dll", SetLastError = true)]
|
|
52
|
+
private static extern bool CloseHandle(IntPtr h);
|
|
53
|
+
|
|
54
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
55
|
+
private struct SECURITY_ATTRIBUTES { public int nLength; public IntPtr lpSecurityDescriptor; public bool bInheritHandle; }
|
|
56
|
+
|
|
57
|
+
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
|
|
58
|
+
private static extern IntPtr CreateFile(string name, uint access, uint share, ref SECURITY_ATTRIBUTES sa,
|
|
59
|
+
uint creation, uint flags, IntPtr template);
|
|
60
|
+
|
|
61
|
+
private const uint GENERIC_WRITE = 0x40000000;
|
|
62
|
+
private const uint FILE_SHARE_WRITE = 0x00000002;
|
|
63
|
+
private const uint FILE_SHARE_READ = 0x00000001;
|
|
64
|
+
private const uint CREATE_ALWAYS = 2;
|
|
65
|
+
private const uint FILE_ATTRIBUTE_NORMAL = 0x80;
|
|
66
|
+
private const int STARTF_USESTDHANDLES = 0x00000100;
|
|
67
|
+
|
|
68
|
+
private const uint TOKEN_ALL_ACCESS = 0xF01FF;
|
|
69
|
+
private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;
|
|
70
|
+
|
|
71
|
+
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
|
|
72
|
+
private struct STARTUPINFO
|
|
73
|
+
{
|
|
74
|
+
public int cb;
|
|
75
|
+
public string lpReserved;
|
|
76
|
+
public string lpDesktop;
|
|
77
|
+
public string lpTitle;
|
|
78
|
+
public int dwX, dwY, dwXSize, dwYSize, dwXCountChars, dwYCountChars, dwFillAttribute, dwFlags;
|
|
79
|
+
public short wShowWindow, cbReserved2;
|
|
80
|
+
public IntPtr lpReserved2, hStdInput, hStdOutput, hStdError;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
84
|
+
private struct PROCESS_INFORMATION
|
|
85
|
+
{
|
|
86
|
+
public IntPtr hProcess, hThread;
|
|
87
|
+
public int dwProcessId, dwThreadId;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
public static int Main(string[] args)
|
|
91
|
+
{
|
|
92
|
+
// Args: -Exe <node.exe> -Args "<worker args>" [-Cwd <dir>] [-Out <file>] [-Err <file>]
|
|
93
|
+
// -Query -> print the ACTIVE CONSOLE session id and exit (broker session check)
|
|
94
|
+
string exe = null, argLine = null, cwd = null, outFile = null, errFile = null;
|
|
95
|
+
bool query = false;
|
|
96
|
+
for (int i = 0; i < args.Length; i++)
|
|
97
|
+
{
|
|
98
|
+
switch (args[i])
|
|
99
|
+
{
|
|
100
|
+
case "-Exe": if (i + 1 < args.Length) exe = args[++i]; break;
|
|
101
|
+
case "-Args": if (i + 1 < args.Length) argLine = args[++i]; break;
|
|
102
|
+
case "-Cwd": if (i + 1 < args.Length) cwd = args[++i]; break;
|
|
103
|
+
case "-Out": if (i + 1 < args.Length) outFile = args[++i]; break;
|
|
104
|
+
case "-Err": if (i + 1 < args.Length) errFile = args[++i]; break;
|
|
105
|
+
case "-Query": query = true; break;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (query)
|
|
109
|
+
{
|
|
110
|
+
uint qs = WTSGetActiveConsoleSessionId();
|
|
111
|
+
Console.WriteLine("SESSION=" + (qs == 0xFFFFFFFF ? "-1" : qs.ToString()));
|
|
112
|
+
return 0;
|
|
113
|
+
}
|
|
114
|
+
if (exe == null || argLine == null) { Console.Error.WriteLine("usage: -Exe <exe> -Args <args> [-Cwd <dir>] | -Query"); return 2; }
|
|
115
|
+
|
|
116
|
+
uint session = WTSGetActiveConsoleSessionId();
|
|
117
|
+
if (session == 0xFFFFFFFF) { Console.Error.WriteLine("no active console session"); return 3; }
|
|
118
|
+
|
|
119
|
+
IntPtr userToken;
|
|
120
|
+
if (!WTSQueryUserToken(session, out userToken)) { Console.Error.WriteLine("WTSQueryUserToken failed: " + new Win32Exception(Marshal.GetLastWin32Error()).Message); return 4; }
|
|
121
|
+
|
|
122
|
+
IntPtr dup;
|
|
123
|
+
if (!DuplicateTokenEx(userToken, TOKEN_ALL_ACCESS, IntPtr.Zero, 2 /*SecurityImpersonation*/, 1 /*Primary*/, out dup))
|
|
124
|
+
{ Console.Error.WriteLine("DuplicateTokenEx failed: " + new Win32Exception(Marshal.GetLastWin32Error()).Message); return 5; }
|
|
125
|
+
|
|
126
|
+
IntPtr env = IntPtr.Zero;
|
|
127
|
+
CreateEnvironmentBlock(out env, dup, false);
|
|
128
|
+
|
|
129
|
+
var si = new STARTUPINFO();
|
|
130
|
+
si.cb = Marshal.SizeOf(si);
|
|
131
|
+
si.lpDesktop = "winsta0\\default";
|
|
132
|
+
|
|
133
|
+
// Redirect child stdio to files (a service-session launch has no console,
|
|
134
|
+
// so otherwise the worker's errors would be lost).
|
|
135
|
+
IntPtr outHandle = IntPtr.Zero, errHandle = IntPtr.Zero;
|
|
136
|
+
if (outFile != null || errFile != null)
|
|
137
|
+
{
|
|
138
|
+
var sa = new SECURITY_ATTRIBUTES();
|
|
139
|
+
sa.nLength = Marshal.SizeOf(sa);
|
|
140
|
+
sa.bInheritHandle = true;
|
|
141
|
+
outHandle = CreateFile(outFile ?? "NUL", GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, ref sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
|
|
142
|
+
errHandle = CreateFile(errFile ?? (outFile ?? "NUL"), GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, ref sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, IntPtr.Zero);
|
|
143
|
+
si.dwFlags |= STARTF_USESTDHANDLES;
|
|
144
|
+
si.hStdOutput = outHandle;
|
|
145
|
+
si.hStdError = errHandle;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
PROCESS_INFORMATION pi;
|
|
149
|
+
// Quote the executable path (it contains spaces); node parses argv itself
|
|
150
|
+
// when launched via CreateProcessAsUser without a shell.
|
|
151
|
+
string cmd = "\"" + exe + "\" " + argLine;
|
|
152
|
+
bool ok = CreateProcessAsUser(dup, exe, cmd, IntPtr.Zero, IntPtr.Zero,
|
|
153
|
+
(outHandle != IntPtr.Zero), CREATE_UNICODE_ENVIRONMENT, env, string.IsNullOrEmpty(cwd) ? null : cwd, ref si, out pi);
|
|
154
|
+
if (!ok) { Console.Error.WriteLine("CreateProcessAsUser failed: " + new Win32Exception(Marshal.GetLastWin32Error()).Message); return 6; }
|
|
155
|
+
|
|
156
|
+
Console.WriteLine("LAUNCHED pid=" + pi.dwProcessId + " session=" + session);
|
|
157
|
+
CloseHandle(pi.hThread); CloseHandle(pi.hProcess); CloseHandle(dup); CloseHandle(userToken);
|
|
158
|
+
if (outHandle != IntPtr.Zero) CloseHandle(outHandle);
|
|
159
|
+
if (errHandle != IntPtr.Zero) CloseHandle(errHandle);
|
|
160
|
+
if (env != IntPtr.Zero) DestroyEnvironmentBlock(env);
|
|
161
|
+
return 0;
|
|
162
|
+
}
|
|
163
|
+
}
|
package/scripts/worker-entry.js
CHANGED
|
@@ -27,7 +27,7 @@ const { spawn } = require('child_process');
|
|
|
27
27
|
|
|
28
28
|
function main() {
|
|
29
29
|
let machineState;
|
|
30
|
-
try { machineState = require('../machineState'); } catch { process.exit(0); }
|
|
30
|
+
try { machineState = require('../src/machineState'); } catch { process.exit(0); }
|
|
31
31
|
|
|
32
32
|
const invitePath = path.join(machineState.paths.runtime, 'worker-invite.json');
|
|
33
33
|
let invite = null;
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* BrokerConnectionSupervisor — ONE reconnect lifecycle shared by the foreground
|
|
5
|
+
* `start` agent and the machine `service` broker (2.1.0 reconnect fix).
|
|
6
|
+
*
|
|
7
|
+
* WHY THIS EXISTS
|
|
8
|
+
* The production machine broker must be long-lived. A transient loss of network,
|
|
9
|
+
* DNS, TLS reachability, backend availability, the WebSocket, or a heartbeat must
|
|
10
|
+
* NOT require a manual service restart, a user login, a re-pair, or a new device
|
|
11
|
+
* identity. The broker must transparently reconnect with the SAME enrolled
|
|
12
|
+
* identity.
|
|
13
|
+
*
|
|
14
|
+
* The foreground `start` path had an ad-hoc reconnect; the `service` path had
|
|
15
|
+
* NONE, so a dropped production WebSocket left the broker idle forever. This
|
|
16
|
+
* module is the single supervisor used by BOTH paths.
|
|
17
|
+
*
|
|
18
|
+
* GUARANTEES
|
|
19
|
+
* - at most ONE reconnect timer and ONE in-flight connect attempt (Phase 7);
|
|
20
|
+
* - at most ONE active WebSocket; a stale socket's close is ignored;
|
|
21
|
+
* - bounded exponential backoff with jitter, reset after a stable connect;
|
|
22
|
+
* - `stop()` cancels the timer and prevents any later reconnect;
|
|
23
|
+
* - a pong watchdog terminates a half-open socket so the close path runs;
|
|
24
|
+
* - transport recovery only: it never touches the device id/key/pairing.
|
|
25
|
+
*
|
|
26
|
+
* Dependencies (timers, random, now, connect) are injectable for deterministic
|
|
27
|
+
* tests. No secrets are ever logged.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
const DEFAULT_BACKOFF = Object.freeze({ baseMs: 1000, maxMs: 60000, jitterMs: 1000, factor: 2 });
|
|
31
|
+
// The agent heartbeat is every 10s (see sessionHandler). A half-open socket is
|
|
32
|
+
// terminated only after several missed pongs — deliberately NOT aggressive.
|
|
33
|
+
const DEFAULT_PONG_TIMEOUT_MS = 60000;
|
|
34
|
+
|
|
35
|
+
function _safeMsg(e) { return String((e && e.message) || e || 'unknown').slice(0, 200); }
|
|
36
|
+
|
|
37
|
+
/** Auth/credential failures must not busy-loop AND must not regenerate identity. */
|
|
38
|
+
function isAuthErrorMessage(msg) {
|
|
39
|
+
return /4003|device authentication failed|unauthorized|revoked|unknown key|invalid (device|machine) identity|protocol version|unsupported protocol/i.test(String(msg || ''));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function createBrokerConnectionSupervisor(opts = {}) {
|
|
43
|
+
const connect = opts.connect;
|
|
44
|
+
if (typeof connect !== 'function') throw new Error('createBrokerConnectionSupervisor: connect is required');
|
|
45
|
+
|
|
46
|
+
const onConnected = opts.onConnected || (() => {});
|
|
47
|
+
const onDisconnected = opts.onDisconnected || (() => {});
|
|
48
|
+
const onAuthRejected = opts.onAuthRejected || null;
|
|
49
|
+
const onStateChange = opts.onStateChange || null;
|
|
50
|
+
const log = opts.log || (() => {});
|
|
51
|
+
const timer = opts.timers || {};
|
|
52
|
+
const setTimeoutFn = timer.setTimeout || setTimeout;
|
|
53
|
+
const clearTimeoutFn = timer.clearTimeout || clearTimeout;
|
|
54
|
+
const setIntervalFn = timer.setInterval || setInterval;
|
|
55
|
+
const clearIntervalFn = timer.clearInterval || clearInterval;
|
|
56
|
+
const now = opts.now || (() => Date.now());
|
|
57
|
+
const random = opts.random || Math.random;
|
|
58
|
+
const backoff = { ...DEFAULT_BACKOFF, ...(opts.backoff || {}) };
|
|
59
|
+
// 0 = retry forever (machine service). >0 = bounded (foreground start).
|
|
60
|
+
const maxAttempts = Number.isInteger(opts.maxAttempts) ? opts.maxAttempts : 0;
|
|
61
|
+
const pongTimeoutMs = Number.isInteger(opts.pongTimeoutMs) ? opts.pongTimeoutMs : DEFAULT_PONG_TIMEOUT_MS;
|
|
62
|
+
|
|
63
|
+
let state = 'idle'; // idle|connecting|connected|disconnected|reconnecting|auth_blocked|stopping
|
|
64
|
+
let ws = null;
|
|
65
|
+
let retryTimer = null;
|
|
66
|
+
let stopped = false;
|
|
67
|
+
let attempt = 0;
|
|
68
|
+
let connectInFlight = false;
|
|
69
|
+
let heartbeatTimer = null;
|
|
70
|
+
let lastPongAt = 0;
|
|
71
|
+
|
|
72
|
+
const diag = {
|
|
73
|
+
lastConnectedAt: null,
|
|
74
|
+
lastDisconnectedAt: null,
|
|
75
|
+
lastDisconnectCode: null,
|
|
76
|
+
lastDisconnectReason: null,
|
|
77
|
+
reconnectAttempt: 0,
|
|
78
|
+
nextRetryMs: null,
|
|
79
|
+
authBlocked: false,
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
function getState() {
|
|
83
|
+
return {
|
|
84
|
+
state,
|
|
85
|
+
deviceIdentityPreserved: true,
|
|
86
|
+
...diag,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function setState(s) {
|
|
91
|
+
state = s;
|
|
92
|
+
try { if (onStateChange) onStateChange(s, getState()); } catch { /* never break the lifecycle */ }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function _clearRetry() {
|
|
96
|
+
if (retryTimer) { try { clearTimeoutFn(retryTimer); } catch {} retryTimer = null; }
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function _stopHeartbeatWatch() {
|
|
100
|
+
if (heartbeatTimer) { try { clearIntervalFn(heartbeatTimer); } catch {} heartbeatTimer = null; }
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function _startHeartbeatWatch(sock) {
|
|
104
|
+
_stopHeartbeatWatch();
|
|
105
|
+
lastPongAt = now();
|
|
106
|
+
try {
|
|
107
|
+
sock.on('pong', () => { lastPongAt = now(); });
|
|
108
|
+
} catch { /* fake sockets in tests may not support on */ }
|
|
109
|
+
heartbeatTimer = setIntervalFn(() => {
|
|
110
|
+
if (stopped || ws !== sock) { _stopHeartbeatWatch(); return; }
|
|
111
|
+
const silentFor = now() - lastPongAt;
|
|
112
|
+
if (silentFor > pongTimeoutMs) {
|
|
113
|
+
// Half-open socket: the TCP peer is gone but no close event arrived.
|
|
114
|
+
// Terminating drives the normal close path -> reconnect.
|
|
115
|
+
log(`[broker] heartbeat timeout (silent ${Math.round(silentFor)}ms); terminating socket`);
|
|
116
|
+
try { sock.terminate(); } catch {}
|
|
117
|
+
}
|
|
118
|
+
}, Math.max(1000, Math.floor(pongTimeoutMs / 3)));
|
|
119
|
+
if (typeof heartbeatTimer.unref === 'function') heartbeatTimer.unref();
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function _scheduleReconnect(info = {}) {
|
|
123
|
+
if (stopped) return;
|
|
124
|
+
if (retryTimer) return; // SINGLE reconnect timer invariant
|
|
125
|
+
attempt += 1;
|
|
126
|
+
diag.reconnectAttempt = attempt;
|
|
127
|
+
diag.authBlocked = info.auth === true;
|
|
128
|
+
|
|
129
|
+
if (maxAttempts > 0 && attempt > maxAttempts) {
|
|
130
|
+
setState('disconnected');
|
|
131
|
+
log(`[broker] reconnect exhausted after ${maxAttempts} attempts; giving up (identity preserved)`);
|
|
132
|
+
if (opts.onExhausted) { try { opts.onExhausted(getState()); } catch {} }
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const exp = Math.min(backoff.baseMs * Math.pow(backoff.factor, attempt - 1), backoff.maxMs);
|
|
137
|
+
const jitter = Math.floor(random() * backoff.jitterMs);
|
|
138
|
+
const delay = exp + jitter;
|
|
139
|
+
diag.nextRetryMs = delay;
|
|
140
|
+
setState(info.auth ? 'auth_blocked' : 'reconnecting');
|
|
141
|
+
log(`[broker] reconnect scheduled attempt=${attempt} retry=${Math.round(delay)}ms${info.auth ? ' auth=blocked' : ''}`);
|
|
142
|
+
retryTimer = setTimeoutFn(() => { retryTimer = null; _attemptConnect(); }, delay);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async function _attemptConnect() {
|
|
146
|
+
if (stopped) return;
|
|
147
|
+
if (connectInFlight) return; // SINGLE in-flight attempt invariant
|
|
148
|
+
if (ws) return; // already connected
|
|
149
|
+
connectInFlight = true;
|
|
150
|
+
setState(attempt > 0 ? 'reconnecting' : 'connecting');
|
|
151
|
+
log(`[broker] ${attempt > 0 ? 'reconnecting' : 'connecting'} attempt=${attempt}`);
|
|
152
|
+
|
|
153
|
+
let sock;
|
|
154
|
+
try {
|
|
155
|
+
sock = await connect();
|
|
156
|
+
} catch (err) {
|
|
157
|
+
connectInFlight = false;
|
|
158
|
+
if (stopped) return;
|
|
159
|
+
const auth = isAuthErrorMessage(_safeMsg(err));
|
|
160
|
+
log(`[broker] connect failed: ${_safeMsg(err)}`);
|
|
161
|
+
if (auth && onAuthRejected) { try { onAuthRejected({ error: err }); } catch {} }
|
|
162
|
+
_scheduleReconnect({ auth });
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
connectInFlight = false;
|
|
166
|
+
if (stopped) { try { sock.close(1000, 'stopping'); } catch {} return; }
|
|
167
|
+
|
|
168
|
+
ws = sock;
|
|
169
|
+
attempt = 0;
|
|
170
|
+
diag.lastConnectedAt = now();
|
|
171
|
+
diag.nextRetryMs = null;
|
|
172
|
+
diag.reconnectAttempt = 0;
|
|
173
|
+
diag.authBlocked = false;
|
|
174
|
+
setState('connected');
|
|
175
|
+
log('[broker] connected');
|
|
176
|
+
|
|
177
|
+
try { sock.on('close', (code, reason) => _handleClose(sock, code, reason)); } catch {}
|
|
178
|
+
// An 'error' event immediately preceded by nothing else must not crash the
|
|
179
|
+
// process; the close path handles reconnection.
|
|
180
|
+
try { sock.on('error', () => {}); } catch {}
|
|
181
|
+
_startHeartbeatWatch(sock);
|
|
182
|
+
|
|
183
|
+
try { await onConnected(sock); } catch (e) { log(`[broker] onConnected error: ${_safeMsg(e)}`); }
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function _handleClose(closedSock, code, reason) {
|
|
187
|
+
if (stopped) return;
|
|
188
|
+
if (ws !== closedSock) return; // stale socket (already replaced) — ignore
|
|
189
|
+
ws = null;
|
|
190
|
+
_stopHeartbeatWatch();
|
|
191
|
+
const reasonStr = reason ? reason.toString() : '';
|
|
192
|
+
diag.lastDisconnectedAt = now();
|
|
193
|
+
diag.lastDisconnectCode = code;
|
|
194
|
+
diag.lastDisconnectReason = reasonStr;
|
|
195
|
+
|
|
196
|
+
if (code === 4003) {
|
|
197
|
+
diag.authBlocked = true;
|
|
198
|
+
log('[broker] disconnected code=4003 (authentication/identity)');
|
|
199
|
+
if (onAuthRejected) { try { onAuthRejected({ code, reason: reasonStr }); } catch {} }
|
|
200
|
+
// Conservative retry; identity is NEVER regenerated or deleted here.
|
|
201
|
+
_scheduleReconnect({ auth: true });
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
log(`[broker] disconnected code=${code}${reasonStr ? ' reason=' + reasonStr : ''}`);
|
|
206
|
+
try { const r = onDisconnected({ code, reason: reasonStr }); if (r && typeof r.catch === 'function') r.catch(() => {}); } catch {}
|
|
207
|
+
_scheduleReconnect({});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function start() {
|
|
211
|
+
stopped = false;
|
|
212
|
+
attempt = 0;
|
|
213
|
+
return _attemptConnect();
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Adopt an ALREADY-authenticated socket (the foreground `start` path connects
|
|
218
|
+
* first, including its one-time enrollment flow, then hands the live socket to
|
|
219
|
+
* the supervisor for its reconnect lifecycle). Binding happens through
|
|
220
|
+
* `onConnected` exactly once, so the handler is never double-installed.
|
|
221
|
+
*/
|
|
222
|
+
function adopt(sock) {
|
|
223
|
+
if (!sock) return;
|
|
224
|
+
stopped = false;
|
|
225
|
+
connectInFlight = false;
|
|
226
|
+
attempt = 0;
|
|
227
|
+
ws = sock;
|
|
228
|
+
diag.lastConnectedAt = now();
|
|
229
|
+
diag.nextRetryMs = null;
|
|
230
|
+
diag.reconnectAttempt = 0;
|
|
231
|
+
diag.authBlocked = false;
|
|
232
|
+
setState('connected');
|
|
233
|
+
log('[broker] connected');
|
|
234
|
+
try { sock.on('close', (code, reason) => _handleClose(sock, code, reason)); } catch {}
|
|
235
|
+
try { sock.on('error', () => {}); } catch {}
|
|
236
|
+
_startHeartbeatWatch(sock);
|
|
237
|
+
try { const r = onConnected(sock); if (r && typeof r.catch === 'function') r.catch(() => {}); } catch {}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function stop() {
|
|
241
|
+
if (stopped) return;
|
|
242
|
+
stopped = true;
|
|
243
|
+
_clearRetry();
|
|
244
|
+
_stopHeartbeatWatch();
|
|
245
|
+
setState('stopping');
|
|
246
|
+
const sock = ws;
|
|
247
|
+
ws = null;
|
|
248
|
+
if (sock) { try { sock.close(1000, 'shutdown'); } catch {} }
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return {
|
|
252
|
+
start,
|
|
253
|
+
adopt,
|
|
254
|
+
stop,
|
|
255
|
+
getState,
|
|
256
|
+
// Exported for white-box deterministic tests.
|
|
257
|
+
_handleClose,
|
|
258
|
+
_attemptConnect,
|
|
259
|
+
_isAuthError: (e) => isAuthErrorMessage(_safeMsg(e)),
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
module.exports = { createBrokerConnectionSupervisor, isAuthErrorMessage, DEFAULT_BACKOFF, DEFAULT_PONG_TIMEOUT_MS };
|