@nexum-hub/agent 0.0.2 → 0.0.3-next.10
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 +20 -0
- package/dist/application/connection.d.ts +4 -2
- package/dist/application/connection.js +19 -2
- package/dist/application/connection.js.map +1 -1
- package/dist/application/main.js +22 -2
- package/dist/application/main.js.map +1 -1
- package/dist/cli.js +28 -1
- package/dist/cli.js.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/package.json +6 -3
- package/scripts/npm-install.mjs +336 -0
- package/scripts/service-runner.mjs +118 -0
- package/scripts/service.mjs +593 -0
|
@@ -0,0 +1,593 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { homedir, tmpdir } from "node:os";
|
|
3
|
+
import {
|
|
4
|
+
mkdir,
|
|
5
|
+
writeFile,
|
|
6
|
+
rename,
|
|
7
|
+
lstat,
|
|
8
|
+
readFile,
|
|
9
|
+
rm,
|
|
10
|
+
realpath,
|
|
11
|
+
} from "node:fs/promises";
|
|
12
|
+
import { spawnSync } from "node:child_process";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
import { fileURLToPath } from "node:url";
|
|
15
|
+
|
|
16
|
+
export const NODE_VERSION = "24.22.1";
|
|
17
|
+
const profiles = new Set(["development", "production"]);
|
|
18
|
+
const clean = (value) => {
|
|
19
|
+
if (typeof value !== "string" || !value || /[\0\r\n]/.test(value))
|
|
20
|
+
throw new Error("Invalid service path or identity.");
|
|
21
|
+
return value;
|
|
22
|
+
};
|
|
23
|
+
const xml = (value) =>
|
|
24
|
+
clean(value)
|
|
25
|
+
.replaceAll("&", "&")
|
|
26
|
+
.replaceAll("<", "<")
|
|
27
|
+
.replaceAll(">", ">")
|
|
28
|
+
.replaceAll('"', """)
|
|
29
|
+
.replaceAll("'", "'");
|
|
30
|
+
const ps = (value) => "'" + clean(value).replaceAll("'", "''") + "'";
|
|
31
|
+
// The current-user Task Scheduler stops its PowerShell action, not necessarily
|
|
32
|
+
// that action's Node child. An unnamed native Job belongs to this launcher for
|
|
33
|
+
// its entire lifetime; Windows closes the handle and kills inherited children
|
|
34
|
+
// when the launcher exits. No PID-file lookup or separate resident is involved.
|
|
35
|
+
const windowsServiceJob = String.raw`
|
|
36
|
+
using System;
|
|
37
|
+
using System.ComponentModel;
|
|
38
|
+
using System.Runtime.InteropServices;
|
|
39
|
+
namespace NexumAgentService {
|
|
40
|
+
public static class JobOwner {
|
|
41
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
42
|
+
struct BasicLimits {
|
|
43
|
+
public long ProcessTime, JobTime;
|
|
44
|
+
public uint Flags;
|
|
45
|
+
public UIntPtr MinWorkingSet, MaxWorkingSet;
|
|
46
|
+
public uint ActiveProcesses;
|
|
47
|
+
public UIntPtr Affinity;
|
|
48
|
+
public uint Priority, Scheduling;
|
|
49
|
+
}
|
|
50
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
51
|
+
struct IoCounters {
|
|
52
|
+
public ulong Reads, Writes, Other, ReadBytes, WriteBytes, OtherBytes;
|
|
53
|
+
}
|
|
54
|
+
[StructLayout(LayoutKind.Sequential)]
|
|
55
|
+
struct Limits {
|
|
56
|
+
public BasicLimits Basic;
|
|
57
|
+
public IoCounters Io;
|
|
58
|
+
public UIntPtr ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
|
|
59
|
+
}
|
|
60
|
+
[DllImport("kernel32.dll", EntryPoint="CreateJobObjectW", ExactSpelling=true, CharSet=CharSet.Unicode, SetLastError=true)]
|
|
61
|
+
static extern IntPtr CreateJobObject(IntPtr attributes, string name);
|
|
62
|
+
[DllImport("kernel32.dll", SetLastError=true)]
|
|
63
|
+
static extern bool SetInformationJobObject(IntPtr job, int kind, ref Limits limits, uint size);
|
|
64
|
+
[DllImport("kernel32.dll", SetLastError=true)]
|
|
65
|
+
static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
|
|
66
|
+
[DllImport("kernel32.dll")]
|
|
67
|
+
static extern IntPtr GetCurrentProcess();
|
|
68
|
+
[DllImport("kernel32.dll", SetLastError=true)]
|
|
69
|
+
static extern bool CloseHandle(IntPtr handle);
|
|
70
|
+
public static IntPtr Bind() {
|
|
71
|
+
var job = CreateJobObject(IntPtr.Zero, null);
|
|
72
|
+
if (job == IntPtr.Zero) throw new Win32Exception(Marshal.GetLastWin32Error());
|
|
73
|
+
var limits = new Limits();
|
|
74
|
+
limits.Basic.Flags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
|
|
75
|
+
if (!SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf(typeof(Limits))) ||
|
|
76
|
+
!AssignProcessToJobObject(job, GetCurrentProcess())) {
|
|
77
|
+
var error = Marshal.GetLastWin32Error();
|
|
78
|
+
CloseHandle(job);
|
|
79
|
+
throw new Win32Exception(error);
|
|
80
|
+
}
|
|
81
|
+
// Do not close a successful handle here: its owner is this process, which
|
|
82
|
+
// is itself a member. Native process teardown owns the final handle close.
|
|
83
|
+
return job;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
`;
|
|
88
|
+
const unit = (value) =>
|
|
89
|
+
'"' +
|
|
90
|
+
clean(value)
|
|
91
|
+
.replaceAll("\\", "\\\\")
|
|
92
|
+
.replaceAll('"', '\\"')
|
|
93
|
+
.replaceAll("%", "%%") +
|
|
94
|
+
'"';
|
|
95
|
+
export function windowsArgument(value) {
|
|
96
|
+
clean(value);
|
|
97
|
+
return (
|
|
98
|
+
'"' + value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, "$1$1") + '"'
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
export function childEnvironment(source = process.env) {
|
|
102
|
+
// These fixed installer/service commands use Windows PowerShell 5.1. When
|
|
103
|
+
// launched through Node under pwsh, its inherited PS7 path bypasses PowerShell's
|
|
104
|
+
// direct-child compatibility cleanup and can load incompatible system modules.
|
|
105
|
+
return Object.fromEntries(
|
|
106
|
+
Object.entries(source).filter(
|
|
107
|
+
([key]) =>
|
|
108
|
+
!/^(?:NODE_OPTIONS|NODE_PATH|NODE_REPL_EXTERNAL_MODULE|PSModulePath|NEXUM(?:_.*|$)|npm_config_.*auth.*|.*(?:TOKEN|SECRET|PASSWORD|CREDENTIAL|AUTHORIZATION|API_?KEY|PRIVATE_?KEY).*)$/i.test(
|
|
109
|
+
key,
|
|
110
|
+
),
|
|
111
|
+
),
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
export function servicePlan({
|
|
115
|
+
profile,
|
|
116
|
+
programDir,
|
|
117
|
+
npmManaged = false,
|
|
118
|
+
home = homedir(),
|
|
119
|
+
platform = process.platform,
|
|
120
|
+
userId = process.getuid?.(),
|
|
121
|
+
windowsSid,
|
|
122
|
+
preview = false,
|
|
123
|
+
} = {}) {
|
|
124
|
+
if (
|
|
125
|
+
!profiles.has(profile) ||
|
|
126
|
+
!["darwin", "linux", "win32"].includes(platform)
|
|
127
|
+
)
|
|
128
|
+
throw new Error("Select an explicit supported Agent profile and platform.");
|
|
129
|
+
const p = platform === "win32" ? path.win32 : path.posix;
|
|
130
|
+
if (!p.isAbsolute(clean(home)) || !p.isAbsolute(clean(programDir)))
|
|
131
|
+
throw new Error("Service paths must be absolute.");
|
|
132
|
+
const root = p.join(
|
|
133
|
+
home,
|
|
134
|
+
profile === "development" ? ".nexum-dev" : ".nexum",
|
|
135
|
+
),
|
|
136
|
+
versions = p.join(root, "program", "versions");
|
|
137
|
+
const relative = p.relative(versions, programDir);
|
|
138
|
+
if (
|
|
139
|
+
!relative ||
|
|
140
|
+
relative.startsWith("..") ||
|
|
141
|
+
p.isAbsolute(relative) ||
|
|
142
|
+
relative.includes(p.sep)
|
|
143
|
+
)
|
|
144
|
+
throw new Error(
|
|
145
|
+
"Use one immutable version inside this profile's program directory.",
|
|
146
|
+
);
|
|
147
|
+
const node = p.join(
|
|
148
|
+
npmManaged
|
|
149
|
+
? p.join(root, "program", "runtime")
|
|
150
|
+
: p.join(programDir, "runtime"),
|
|
151
|
+
platform === "win32" ? "node.exe" : "bin/node",
|
|
152
|
+
),
|
|
153
|
+
entry = npmManaged
|
|
154
|
+
? p.join(root, "program", "service-runner.mjs")
|
|
155
|
+
: p.join(programDir, "app", "dist", "cli.js");
|
|
156
|
+
const args = npmManaged
|
|
157
|
+
? [entry, "--profile", profile]
|
|
158
|
+
: ["--experimental-vm-modules", entry, "run", "--profile", profile];
|
|
159
|
+
const runtimePath =
|
|
160
|
+
p.dirname(node) +
|
|
161
|
+
(platform === "win32" ? ";" : ":") +
|
|
162
|
+
(platform === "win32"
|
|
163
|
+
? (process.env.PATH ?? "")
|
|
164
|
+
: "/usr/local/bin:/opt/homebrew/bin:/usr/bin:/bin:/usr/sbin:/sbin");
|
|
165
|
+
const logs = p.join(root, "logs"),
|
|
166
|
+
state = p.join(root, "state");
|
|
167
|
+
const base = {
|
|
168
|
+
profile,
|
|
169
|
+
platform,
|
|
170
|
+
home,
|
|
171
|
+
root,
|
|
172
|
+
programDir,
|
|
173
|
+
node,
|
|
174
|
+
entry,
|
|
175
|
+
args,
|
|
176
|
+
logs,
|
|
177
|
+
state,
|
|
178
|
+
};
|
|
179
|
+
if (platform === "darwin") {
|
|
180
|
+
if (!Number.isSafeInteger(userId) || userId < 0)
|
|
181
|
+
throw new Error("Use the current target user's uid.");
|
|
182
|
+
const label = `com.nexum.agent.${profile}.${createHash("sha256").update(root).digest("hex").slice(0, 12)}`;
|
|
183
|
+
const program = [
|
|
184
|
+
"/usr/bin/env",
|
|
185
|
+
"-u",
|
|
186
|
+
"NODE_OPTIONS",
|
|
187
|
+
"-u",
|
|
188
|
+
"NODE_PATH",
|
|
189
|
+
"-u",
|
|
190
|
+
"NODE_REPL_EXTERNAL_MODULE",
|
|
191
|
+
node,
|
|
192
|
+
...args,
|
|
193
|
+
];
|
|
194
|
+
const content = `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict><key>Label</key><string>${label}</string><key>ProgramArguments</key><array>${program.map((x) => `<string>${xml(x)}</string>`).join("")}</array><key>WorkingDirectory</key><string>${xml(root)}</string><key>EnvironmentVariables</key><dict><key>HOME</key><string>${xml(home)}</string><key>PATH</key><string>${xml(runtimePath)}</string></dict><key>RunAtLoad</key><true/><key>KeepAlive</key><dict><key>SuccessfulExit</key><false/></dict><key>ThrottleInterval</key><integer>10</integer><key>StandardOutPath</key><string>/dev/null</string><key>StandardErrorPath</key><string>/dev/null</string></dict></plist>\n`;
|
|
195
|
+
return {
|
|
196
|
+
...base,
|
|
197
|
+
label,
|
|
198
|
+
target: `gui/${userId}/${label}`,
|
|
199
|
+
domain: `gui/${userId}`,
|
|
200
|
+
manifestPath: preview
|
|
201
|
+
? p.join(state, "service-preview.plist")
|
|
202
|
+
: p.join(home, "Library", "LaunchAgents", label + ".plist"),
|
|
203
|
+
content,
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
if (platform === "linux") {
|
|
207
|
+
const label = `nexum-agent-${profile}-${createHash("sha256").update(root).digest("hex").slice(0, 12)}.service`;
|
|
208
|
+
const content = `[Unit]\nDescription=Nexum Agent (${profile})\nStartLimitIntervalSec=0\n\n[Service]\nType=simple\nExecStart=:${[node, ...args].map(unit).join(" ")}\nWorkingDirectory=${clean(root).replaceAll("%", "%%")}\nEnvironment=${unit("HOME=" + home)}\nEnvironment=${unit("PATH=" + runtimePath)}\nUnsetEnvironment=NODE_OPTIONS NODE_PATH NODE_REPL_EXTERNAL_MODULE\nRestart=on-failure\nRestartSec=10s\nTimeoutStopSec=60s\nKillMode=mixed\nUMask=0077\n\n[Install]\nWantedBy=default.target\n`;
|
|
209
|
+
return {
|
|
210
|
+
...base,
|
|
211
|
+
label,
|
|
212
|
+
manifestPath: preview
|
|
213
|
+
? p.join(state, "service-preview.service")
|
|
214
|
+
: p.join(home, ".config", "systemd", "user", label),
|
|
215
|
+
content,
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
if (typeof windowsSid !== "string" || !/^S-1-[0-9-]+$/.test(windowsSid))
|
|
219
|
+
throw new Error("Use the current Windows user's actual SID.");
|
|
220
|
+
const label = `Nexum.Agent.${profile}.${createHash("sha256")
|
|
221
|
+
.update(windowsSid + "\n" + root)
|
|
222
|
+
.digest("hex")
|
|
223
|
+
.slice(0, 12)}`;
|
|
224
|
+
const launcherPath = p.join(
|
|
225
|
+
state,
|
|
226
|
+
preview ? "service-preview-launch.ps1" : "service-launch.ps1",
|
|
227
|
+
);
|
|
228
|
+
// Task Scheduler retries failure to start an action, not a completed app's
|
|
229
|
+
// nonzero exit. Keep app retries here, bounded, under that same user task.
|
|
230
|
+
const launcher = `$ErrorActionPreference = 'Stop'\nRemove-Item Env:NODE_OPTIONS,Env:NODE_PATH,Env:NODE_REPL_EXTERNAL_MODULE -ErrorAction SilentlyContinue\n${"$env:PATH = " + ps(p.dirname(node) + ";") + " + $env:PATH"}\n$env:USERPROFILE = ${ps(home)}\nAdd-Type -TypeDefinition @'\n${windowsServiceJob}\n'@\n$nexumJob = [NexumAgentService.JobOwner]::Bind()\nfor ($nexumAttempt = 0; $nexumAttempt -le 255; $nexumAttempt++) {\n $global:LASTEXITCODE = $null\n $nexumExit = 1\n try {\n & ${ps(node)} ${args.map(ps).join(" ")}\n if ($LASTEXITCODE -is [int]) { $nexumExit = $LASTEXITCODE }\n } catch { $nexumExit = 1 }\n if ($nexumExit -eq 0 -or $nexumAttempt -eq 255) { exit $nexumExit }\n Start-Sleep -Seconds 10\n}\n`;
|
|
231
|
+
const executable = p.join(
|
|
232
|
+
process.env.SystemRoot || "C:\\Windows",
|
|
233
|
+
"System32",
|
|
234
|
+
"WindowsPowerShell",
|
|
235
|
+
"v1.0",
|
|
236
|
+
"powershell.exe",
|
|
237
|
+
);
|
|
238
|
+
const actionArgs = [
|
|
239
|
+
"-NoLogo",
|
|
240
|
+
"-NoProfile",
|
|
241
|
+
"-NonInteractive",
|
|
242
|
+
"-ExecutionPolicy",
|
|
243
|
+
"Bypass",
|
|
244
|
+
"-File",
|
|
245
|
+
launcherPath,
|
|
246
|
+
]
|
|
247
|
+
.map(windowsArgument)
|
|
248
|
+
.join(" ");
|
|
249
|
+
const content = `<?xml version="1.0" encoding="UTF-16"?>\n<Task version="1.4" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task"><RegistrationInfo><Description>Nexum Agent (${profile}), current-user authority</Description></RegistrationInfo><Triggers><LogonTrigger><Enabled>true</Enabled><UserId>${xml(windowsSid)}</UserId></LogonTrigger></Triggers><Principals><Principal id="TargetUser"><UserId>${xml(windowsSid)}</UserId><LogonType>InteractiveToken</LogonType><RunLevel>LeastPrivilege</RunLevel></Principal></Principals><Settings><MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy><DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries><StopIfGoingOnBatteries>false</StopIfGoingOnBatteries><AllowHardTerminate>true</AllowHardTerminate><StartWhenAvailable>true</StartWhenAvailable><RunOnlyIfIdle>false</RunOnlyIfIdle><ExecutionTimeLimit>PT0S</ExecutionTimeLimit><RestartOnFailure><Interval>PT1M</Interval><Count>255</Count></RestartOnFailure></Settings><Actions Context="TargetUser"><Exec><Command>${xml(executable)}</Command><Arguments>${xml(actionArgs)}</Arguments><WorkingDirectory>${xml(root)}</WorkingDirectory></Exec></Actions></Task>\n`;
|
|
250
|
+
return {
|
|
251
|
+
...base,
|
|
252
|
+
label,
|
|
253
|
+
windowsSid,
|
|
254
|
+
launcherPath,
|
|
255
|
+
launcher,
|
|
256
|
+
manifestPath: p.join(
|
|
257
|
+
state,
|
|
258
|
+
preview ? "service-preview.xml" : "service-task.xml",
|
|
259
|
+
),
|
|
260
|
+
content,
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
async function writePrivate(filename, content, encoding = "utf8") {
|
|
264
|
+
await mkdir(path.dirname(filename), { recursive: true, mode: 0o700 });
|
|
265
|
+
try {
|
|
266
|
+
const previous = await lstat(filename);
|
|
267
|
+
if (!previous.isFile() || previous.isSymbolicLink())
|
|
268
|
+
throw new Error("The service manifest is not a regular local file.");
|
|
269
|
+
} catch (error) {
|
|
270
|
+
if (error.code !== "ENOENT") throw error;
|
|
271
|
+
}
|
|
272
|
+
const temporary = filename + `.${process.pid}.new`;
|
|
273
|
+
await writeFile(temporary, content, { flag: "wx", mode: 0o600, encoding });
|
|
274
|
+
await rename(temporary, filename);
|
|
275
|
+
}
|
|
276
|
+
export async function writeServiceManifest(plan) {
|
|
277
|
+
const base = path.resolve(plan.home);
|
|
278
|
+
if ((await realpath(base)) !== base)
|
|
279
|
+
throw new Error("Use a canonical target home for service files.");
|
|
280
|
+
const ensure = async (destination) => {
|
|
281
|
+
const relative = path.relative(base, destination);
|
|
282
|
+
if (relative.startsWith("..") || path.isAbsolute(relative))
|
|
283
|
+
throw new Error("A service file escaped the target user's home.");
|
|
284
|
+
let current = base;
|
|
285
|
+
for (const part of relative.split(path.sep).filter(Boolean)) {
|
|
286
|
+
current = path.join(current, part);
|
|
287
|
+
try {
|
|
288
|
+
await mkdir(current, { mode: 0o700 });
|
|
289
|
+
} catch (error) {
|
|
290
|
+
if (error.code !== "EEXIST") throw error;
|
|
291
|
+
}
|
|
292
|
+
const info = await lstat(current);
|
|
293
|
+
if (
|
|
294
|
+
!info.isDirectory() ||
|
|
295
|
+
info.isSymbolicLink() ||
|
|
296
|
+
(await realpath(current)) !== current
|
|
297
|
+
)
|
|
298
|
+
throw new Error("Service directories must remain canonical.");
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
for (const directory of [
|
|
302
|
+
plan.logs,
|
|
303
|
+
plan.state,
|
|
304
|
+
path.dirname(plan.manifestPath),
|
|
305
|
+
])
|
|
306
|
+
await ensure(directory);
|
|
307
|
+
if (plan.launcher)
|
|
308
|
+
await writePrivate(plan.launcherPath, "\uFEFF" + plan.launcher);
|
|
309
|
+
await writePrivate(
|
|
310
|
+
plan.manifestPath,
|
|
311
|
+
plan.platform === "win32" ? "\uFEFF" + plan.content : plan.content,
|
|
312
|
+
plan.platform === "win32" ? "utf16le" : "utf8",
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function execute(file, args, { allowFailure = false } = {}) {
|
|
317
|
+
const result = spawnSync(file, args, {
|
|
318
|
+
encoding: "utf8",
|
|
319
|
+
env: childEnvironment(),
|
|
320
|
+
windowsHide: true,
|
|
321
|
+
maxBuffer: 1024 * 1024,
|
|
322
|
+
});
|
|
323
|
+
if (result.error || (result.status !== 0 && !allowFailure))
|
|
324
|
+
throw new Error(
|
|
325
|
+
"The native user service command failed; inspect its current state before repeating a mutation.",
|
|
326
|
+
);
|
|
327
|
+
return result;
|
|
328
|
+
}
|
|
329
|
+
function powershell(script) {
|
|
330
|
+
return execute(
|
|
331
|
+
path.join(
|
|
332
|
+
process.env.SystemRoot || "C:\\Windows",
|
|
333
|
+
"System32",
|
|
334
|
+
"WindowsPowerShell",
|
|
335
|
+
"v1.0",
|
|
336
|
+
"powershell.exe",
|
|
337
|
+
),
|
|
338
|
+
[
|
|
339
|
+
"-NoLogo",
|
|
340
|
+
"-NoProfile",
|
|
341
|
+
"-NonInteractive",
|
|
342
|
+
"-Command",
|
|
343
|
+
"$ErrorActionPreference='Stop';[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false);" +
|
|
344
|
+
script,
|
|
345
|
+
],
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
export function currentWindowsSid() {
|
|
349
|
+
return powershell(
|
|
350
|
+
"[System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value",
|
|
351
|
+
).stdout.trim();
|
|
352
|
+
}
|
|
353
|
+
export async function serviceAction(
|
|
354
|
+
plan,
|
|
355
|
+
action,
|
|
356
|
+
{ isolatedHome = false } = {},
|
|
357
|
+
) {
|
|
358
|
+
if (plan.platform !== process.platform)
|
|
359
|
+
throw new Error("Use the actual native platform.");
|
|
360
|
+
if (path.resolve(plan.home) !== path.resolve(homedir())) {
|
|
361
|
+
const base = await realpath(process.env.RUNNER_TEMP || tmpdir()),
|
|
362
|
+
actual = await realpath(plan.home),
|
|
363
|
+
relative = path.relative(base, actual),
|
|
364
|
+
info = await lstat(actual);
|
|
365
|
+
if (
|
|
366
|
+
!isolatedHome ||
|
|
367
|
+
!relative ||
|
|
368
|
+
relative.startsWith("..") ||
|
|
369
|
+
path.isAbsolute(relative) ||
|
|
370
|
+
actual !== path.resolve(plan.home) ||
|
|
371
|
+
!info.isDirectory() ||
|
|
372
|
+
info.isSymbolicLink() ||
|
|
373
|
+
(process.getuid && info.uid !== process.getuid())
|
|
374
|
+
)
|
|
375
|
+
throw new Error(
|
|
376
|
+
"Native registration requires the actual current user's home or an explicit owned isolated home.",
|
|
377
|
+
);
|
|
378
|
+
}
|
|
379
|
+
if (!["install", "start", "stop", "status", "remove"].includes(action))
|
|
380
|
+
throw new Error("Unknown service action.");
|
|
381
|
+
if (action === "install") await writeServiceManifest(plan);
|
|
382
|
+
if (plan.platform === "linux") {
|
|
383
|
+
if (action === "install") {
|
|
384
|
+
execute("systemctl", [
|
|
385
|
+
"--user",
|
|
386
|
+
...(isolatedHome ? ["--runtime"] : []),
|
|
387
|
+
"enable",
|
|
388
|
+
plan.manifestPath,
|
|
389
|
+
]);
|
|
390
|
+
execute("systemctl", ["--user", "daemon-reload"]);
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
if (action === "status") {
|
|
394
|
+
const result = execute(
|
|
395
|
+
"systemctl",
|
|
396
|
+
[
|
|
397
|
+
"--user",
|
|
398
|
+
"show",
|
|
399
|
+
plan.label,
|
|
400
|
+
"--property=LoadState,ActiveState,UnitFileState",
|
|
401
|
+
"--no-pager",
|
|
402
|
+
],
|
|
403
|
+
{ allowFailure: true },
|
|
404
|
+
);
|
|
405
|
+
const output = result.stdout;
|
|
406
|
+
const values = Object.fromEntries(
|
|
407
|
+
output
|
|
408
|
+
.trim()
|
|
409
|
+
.split(/\r?\n/)
|
|
410
|
+
.map((line) => line.split(/=(.*)/s).slice(0, 2)),
|
|
411
|
+
);
|
|
412
|
+
if (
|
|
413
|
+
!values.LoadState ||
|
|
414
|
+
(result.status !== 0 && values.LoadState !== "not-found")
|
|
415
|
+
)
|
|
416
|
+
throw new Error("The current user service state is unknown.");
|
|
417
|
+
return {
|
|
418
|
+
registered: values.LoadState !== "not-found",
|
|
419
|
+
state: values.ActiveState ?? "unknown",
|
|
420
|
+
enabled: [
|
|
421
|
+
"enabled",
|
|
422
|
+
"enabled-runtime",
|
|
423
|
+
"linked",
|
|
424
|
+
"linked-runtime",
|
|
425
|
+
].includes(values.UnitFileState),
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
if (action === "start") {
|
|
429
|
+
execute("systemctl", [
|
|
430
|
+
"--user",
|
|
431
|
+
...(isolatedHome ? ["--runtime"] : []),
|
|
432
|
+
"enable",
|
|
433
|
+
plan.manifestPath,
|
|
434
|
+
]);
|
|
435
|
+
execute("systemctl", ["--user", "daemon-reload"]);
|
|
436
|
+
return execute("systemctl", ["--user", "start", plan.label]);
|
|
437
|
+
}
|
|
438
|
+
const current = await serviceAction(plan, "status", { isolatedHome });
|
|
439
|
+
if (current.registered)
|
|
440
|
+
execute("systemctl", [
|
|
441
|
+
"--user",
|
|
442
|
+
...(isolatedHome ? ["--runtime"] : []),
|
|
443
|
+
"disable",
|
|
444
|
+
"--now",
|
|
445
|
+
plan.label,
|
|
446
|
+
]);
|
|
447
|
+
if (action === "remove") {
|
|
448
|
+
await rm(plan.manifestPath, { force: true });
|
|
449
|
+
execute("systemctl", ["--user", "daemon-reload"]);
|
|
450
|
+
}
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
if (plan.platform === "darwin") {
|
|
454
|
+
const loaded = () => {
|
|
455
|
+
const result = execute("/bin/launchctl", ["print", plan.target], {
|
|
456
|
+
allowFailure: true,
|
|
457
|
+
});
|
|
458
|
+
if (result.status === 0) return result;
|
|
459
|
+
if (result.status === 113) return null;
|
|
460
|
+
throw new Error(
|
|
461
|
+
"The current launchd state is unknown; no mutation was retried.",
|
|
462
|
+
);
|
|
463
|
+
};
|
|
464
|
+
if (action === "install") {
|
|
465
|
+
execute("/bin/launchctl", ["enable", plan.target]);
|
|
466
|
+
return;
|
|
467
|
+
}
|
|
468
|
+
if (action === "start") {
|
|
469
|
+
const current = loaded();
|
|
470
|
+
execute("/bin/launchctl", ["enable", plan.target]);
|
|
471
|
+
return current
|
|
472
|
+
? execute("/bin/launchctl", ["kickstart", plan.target])
|
|
473
|
+
: execute("/bin/launchctl", [
|
|
474
|
+
"bootstrap",
|
|
475
|
+
plan.domain,
|
|
476
|
+
plan.manifestPath,
|
|
477
|
+
]);
|
|
478
|
+
}
|
|
479
|
+
const current = loaded(),
|
|
480
|
+
pid = current
|
|
481
|
+
? Number(/^\s*pid = ([1-9][0-9]*)\s*$/m.exec(current.stdout)?.[1] ?? 0)
|
|
482
|
+
: 0;
|
|
483
|
+
if (action === "status") {
|
|
484
|
+
let file = false;
|
|
485
|
+
try {
|
|
486
|
+
const info = await lstat(plan.manifestPath);
|
|
487
|
+
if (!info.isFile() || info.isSymbolicLink())
|
|
488
|
+
throw new Error("The service file is not regular.");
|
|
489
|
+
file = true;
|
|
490
|
+
} catch (error) {
|
|
491
|
+
if (error.code !== "ENOENT") throw error;
|
|
492
|
+
}
|
|
493
|
+
return {
|
|
494
|
+
registered: !!current || file,
|
|
495
|
+
loaded: !!current,
|
|
496
|
+
state: pid ? "running" : current ? "idle" : "unloaded",
|
|
497
|
+
...(pid ? { pid } : {}),
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
execute("/bin/launchctl", ["disable", plan.target]);
|
|
501
|
+
if (current) execute("/bin/launchctl", ["bootout", plan.target]);
|
|
502
|
+
if (pid) {
|
|
503
|
+
const deadline = performance.now() + 60000;
|
|
504
|
+
while (true) {
|
|
505
|
+
try {
|
|
506
|
+
process.kill(pid, 0);
|
|
507
|
+
} catch (error) {
|
|
508
|
+
if (error.code === "ESRCH") break;
|
|
509
|
+
throw error;
|
|
510
|
+
}
|
|
511
|
+
if (performance.now() >= deadline)
|
|
512
|
+
throw new Error(
|
|
513
|
+
"The previous service leader has not confirmed closure.",
|
|
514
|
+
);
|
|
515
|
+
await new Promise((resolve) => setTimeout(resolve, 100));
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
if (action === "remove") {
|
|
519
|
+
await rm(plan.manifestPath, { force: true });
|
|
520
|
+
execute("/bin/launchctl", ["enable", plan.target]);
|
|
521
|
+
}
|
|
522
|
+
return;
|
|
523
|
+
}
|
|
524
|
+
const name = ps(plan.label);
|
|
525
|
+
const stateScript = `try{$t=Get-ScheduledTask -TaskName ${name} -ErrorAction Stop}catch{if($_.FullyQualifiedErrorId -like 'CmdletizationQuery_NotFound*'){[Console]::Write('{"registered":false,"state":"absent"}');exit 0}else{throw}};$i=Get-ScheduledTaskInfo -TaskName ${name};@{registered=$true;state=[string]$t.State;lastResult=$i.LastTaskResult}|ConvertTo-Json -Compress`;
|
|
526
|
+
if (action === "install")
|
|
527
|
+
return powershell(
|
|
528
|
+
`Register-ScheduledTask -TaskName ${name} -Xml ([System.IO.File]::ReadAllText(${ps(plan.manifestPath)})) -Force | Out-Null`,
|
|
529
|
+
);
|
|
530
|
+
if (action === "status") return JSON.parse(powershell(stateScript).stdout);
|
|
531
|
+
if (action === "start")
|
|
532
|
+
return powershell(
|
|
533
|
+
`Enable-ScheduledTask -TaskName ${name}|Out-Null;Start-ScheduledTask -TaskName ${name}`,
|
|
534
|
+
);
|
|
535
|
+
const current = JSON.parse(powershell(stateScript).stdout);
|
|
536
|
+
if (current.registered) {
|
|
537
|
+
powershell(`Disable-ScheduledTask -TaskName ${name}|Out-Null`);
|
|
538
|
+
if (["Running", "Queued"].includes(current.state))
|
|
539
|
+
powershell(`Stop-ScheduledTask -TaskName ${name}`);
|
|
540
|
+
else if (!["Ready", "Disabled"].includes(current.state))
|
|
541
|
+
throw new Error("The task's stop state is unknown.");
|
|
542
|
+
}
|
|
543
|
+
if (action === "remove") {
|
|
544
|
+
if (current.registered)
|
|
545
|
+
powershell(`Unregister-ScheduledTask -TaskName ${name} -Confirm:$false`);
|
|
546
|
+
await rm(plan.manifestPath, { force: true });
|
|
547
|
+
await rm(plan.launcherPath, { force: true });
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
export async function loadServicePlan(profile, home = homedir()) {
|
|
552
|
+
if (!profiles.has(profile))
|
|
553
|
+
throw new Error("Select an explicit Agent profile.");
|
|
554
|
+
const root = path.join(
|
|
555
|
+
home,
|
|
556
|
+
profile === "development" ? ".nexum-dev" : ".nexum",
|
|
557
|
+
);
|
|
558
|
+
const active = JSON.parse(
|
|
559
|
+
await readFile(path.join(root, "program", "active.json"), "utf8"),
|
|
560
|
+
);
|
|
561
|
+
const npmManaged =
|
|
562
|
+
typeof active.directory === "string" &&
|
|
563
|
+
active.directory === active.version &&
|
|
564
|
+
/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-next\.[0-9]+)?$/.test(
|
|
565
|
+
active.version,
|
|
566
|
+
);
|
|
567
|
+
return servicePlan({
|
|
568
|
+
profile,
|
|
569
|
+
home,
|
|
570
|
+
programDir: npmManaged
|
|
571
|
+
? path.join(root, "program", "versions", active.directory)
|
|
572
|
+
: active.programDir,
|
|
573
|
+
npmManaged,
|
|
574
|
+
windowsSid: process.platform === "win32" ? currentWindowsSid() : undefined,
|
|
575
|
+
});
|
|
576
|
+
}
|
|
577
|
+
if (
|
|
578
|
+
process.argv[1] &&
|
|
579
|
+
path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
|
580
|
+
) {
|
|
581
|
+
const [action, ...rest] = process.argv.slice(2);
|
|
582
|
+
if (rest.length !== 2 || rest[0] !== "--profile")
|
|
583
|
+
throw new Error("Use ACTION --profile development|production.");
|
|
584
|
+
const plan = await loadServicePlan(rest[1]);
|
|
585
|
+
const result = await serviceAction(plan, action);
|
|
586
|
+
console.log(
|
|
587
|
+
JSON.stringify(
|
|
588
|
+
action === "status"
|
|
589
|
+
? result
|
|
590
|
+
: { profile: plan.profile, action, acknowledged: true },
|
|
591
|
+
),
|
|
592
|
+
);
|
|
593
|
+
}
|