@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.
@@ -0,0 +1,336 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { spawnSync } from "node:child_process";
3
+ import { existsSync } from "node:fs";
4
+ import {
5
+ cp,
6
+ lstat,
7
+ mkdir,
8
+ readFile,
9
+ realpath,
10
+ rename,
11
+ rm,
12
+ writeFile,
13
+ } from "node:fs/promises";
14
+ import { homedir } from "node:os";
15
+ import path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ import {
18
+ NODE_VERSION,
19
+ childEnvironment,
20
+ currentWindowsSid,
21
+ serviceAction,
22
+ servicePlan,
23
+ } from "./service.mjs";
24
+
25
+ const self = path.resolve(fileURLToPath(new URL("../", import.meta.url)));
26
+ const precise = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-next\.[0-9]+)?$/;
27
+ const nodeBin = (root) =>
28
+ path.join(root, process.platform === "win32" ? "node.exe" : "bin/node");
29
+ const npmBin = (root) =>
30
+ path.join(
31
+ root,
32
+ process.platform === "win32"
33
+ ? "node_modules/npm/bin/npm-cli.js"
34
+ : "lib/node_modules/npm/bin/npm-cli.js",
35
+ );
36
+ const fail = (condition, reason) => {
37
+ if (!condition) throw new Error(reason);
38
+ };
39
+ const rootFor = (home, profile) =>
40
+ path.join(home, profile === "production" ? ".nexum" : ".nexum-dev");
41
+ const nodeHome = () =>
42
+ process.platform === "win32"
43
+ ? path.dirname(process.execPath)
44
+ : path.dirname(path.dirname(process.execPath));
45
+ function exec(file, args, cwd) {
46
+ const result = spawnSync(file, args, {
47
+ cwd,
48
+ env: childEnvironment(),
49
+ windowsHide: true,
50
+ encoding: "utf8",
51
+ timeout: 180000,
52
+ maxBuffer: 1024 * 1024,
53
+ });
54
+ fail(!result.error && result.status === 0, "The npm/Node command failed.");
55
+ return result.stdout.trim();
56
+ }
57
+ async function directory(value) {
58
+ await mkdir(value, { recursive: true, mode: 0o700 });
59
+ const info = await lstat(value);
60
+ fail(
61
+ info.isDirectory() &&
62
+ !info.isSymbolicLink() &&
63
+ (await realpath(value)) === value,
64
+ "A local installation directory is unsafe.",
65
+ );
66
+ }
67
+ export async function readState(file) {
68
+ try {
69
+ const info = await lstat(file);
70
+ fail(
71
+ info.isFile() && !info.isSymbolicLink() && info.size <= 16384,
72
+ "The stored Agent state is invalid.",
73
+ );
74
+ return JSON.parse(await readFile(file, "utf8"));
75
+ } catch (error) {
76
+ if (error.code === "ENOENT") return undefined;
77
+ throw error;
78
+ }
79
+ }
80
+ export async function writeState(file, value) {
81
+ const temp = file + "." + randomUUID() + ".new";
82
+ await writeFile(temp, JSON.stringify(value) + "\n", {
83
+ flag: "wx",
84
+ mode: 0o600,
85
+ });
86
+ try {
87
+ await rename(temp, file);
88
+ } finally {
89
+ await rm(temp, { force: true });
90
+ }
91
+ }
92
+ function configuration(value, profile) {
93
+ fail(
94
+ value &&
95
+ typeof value === "object" &&
96
+ !Array.isArray(value) &&
97
+ Object.keys(value).every((k) => ["server_url", "token"].includes(k)) &&
98
+ typeof value.server_url === "string" &&
99
+ typeof value.token === "string" &&
100
+ /^[\x21-\x7e]{1,8192}$/.test(value.token),
101
+ "The private Agent configuration is invalid.",
102
+ );
103
+ const url = new URL(value.server_url);
104
+ fail(
105
+ ["http:", "https:"].includes(url.protocol) &&
106
+ (profile === "development" || url.protocol === "https:") &&
107
+ !url.username &&
108
+ !url.password &&
109
+ !url.search &&
110
+ !url.hash &&
111
+ !/[\x00-\x20\x7f]/.test(value.server_url),
112
+ "The selected profile Server URL is invalid.",
113
+ );
114
+ return { server_url: url.href, token: value.token };
115
+ }
116
+ async function runtime(program) {
117
+ const installed = path.join(program, "runtime");
118
+ if (existsSync(installed)) {
119
+ fail(
120
+ exec(nodeBin(installed), ["--version"]) === `v${NODE_VERSION}`,
121
+ "The managed Node is incompatible.",
122
+ );
123
+ return installed;
124
+ }
125
+ const stage = path.join(program, ".runtime-" + randomUUID());
126
+ await directory(stage);
127
+ try {
128
+ const root = nodeHome();
129
+ const names =
130
+ process.platform === "win32"
131
+ ? ["node.exe", "node_modules/npm", "npm.cmd", "npx.cmd"]
132
+ : ["bin/node", "lib/node_modules/npm", "bin/npm", "bin/npx"];
133
+ for (const name of names) {
134
+ await mkdir(path.dirname(path.join(stage, name)), { recursive: true });
135
+ await cp(path.join(root, name), path.join(stage, name), {
136
+ recursive: true,
137
+ verbatimSymlinks: true,
138
+ });
139
+ }
140
+ fail(
141
+ exec(nodeBin(stage), ["--version"]) === `v${NODE_VERSION}`,
142
+ "The managed Node version is invalid.",
143
+ );
144
+ await rename(stage, installed);
145
+ return installed;
146
+ } finally {
147
+ await rm(stage, { recursive: true, force: true });
148
+ }
149
+ }
150
+ function dependenciesOf(source) {
151
+ let candidate = source;
152
+ while (path.dirname(candidate) !== candidate) {
153
+ if (path.basename(candidate) === "node_modules") return candidate;
154
+ candidate = path.dirname(candidate);
155
+ }
156
+ return path.join(source, "node_modules");
157
+ }
158
+ async function packageStage(stage, version, managedNode, source) {
159
+ const scratch = path.join(stage, ".resolve");
160
+ let from = source;
161
+ if (!from) {
162
+ await directory(scratch);
163
+ exec(nodeBin(managedNode), [
164
+ npmBin(managedNode),
165
+ "install",
166
+ "--prefix",
167
+ scratch,
168
+ "--no-save",
169
+ "--no-package-lock",
170
+ "--omit=dev",
171
+ "--no-audit",
172
+ "--no-fund",
173
+ "--registry=https://registry.npmjs.org/",
174
+ `@nexum-hub/agent@${version}`,
175
+ ]);
176
+ from = path.join(scratch, "node_modules", "@nexum-hub", "agent");
177
+ }
178
+ const manifest = JSON.parse(
179
+ await readFile(path.join(from, "package.json"), "utf8"),
180
+ );
181
+ fail(
182
+ manifest.name === "@nexum-hub/agent" && manifest.version === version,
183
+ "The resolved Agent npm version differs.",
184
+ );
185
+ const app = path.join(stage, "app");
186
+ await directory(app);
187
+ for (const name of [
188
+ "dist",
189
+ "contracts",
190
+ "package.json",
191
+ "scripts/service.mjs",
192
+ "scripts/npm-install.mjs",
193
+ "scripts/service-runner.mjs",
194
+ ]) {
195
+ await mkdir(path.dirname(path.join(app, name)), { recursive: true });
196
+ await cp(path.join(from, name), path.join(app, name), {
197
+ recursive: true,
198
+ verbatimSymlinks: true,
199
+ });
200
+ }
201
+ await cp(dependenciesOf(from), path.join(app, "node_modules"), {
202
+ recursive: true,
203
+ verbatimSymlinks: true,
204
+ });
205
+ fail(
206
+ exec(nodeBin(managedNode), [
207
+ path.join(app, "dist", "cli.js"),
208
+ "--version",
209
+ ]) === version,
210
+ "The installed Agent did not report the expected version.",
211
+ );
212
+ await rm(scratch, { force: true, recursive: true });
213
+ }
214
+ export async function installNpmAgent({
215
+ profile,
216
+ version,
217
+ config,
218
+ home = homedir(),
219
+ register = true,
220
+ start = true,
221
+ source,
222
+ fromUpdate = false,
223
+ } = {}) {
224
+ fail(
225
+ ["production", "development"].includes(profile),
226
+ "Invalid Agent profile.",
227
+ );
228
+ fail(precise.test(version), "Expected a precise Agent npm version.");
229
+ fail(
230
+ process.versions.node === NODE_VERSION,
231
+ "The installer requires Node " + NODE_VERSION + ".",
232
+ );
233
+ fail(
234
+ (await realpath(home)) === path.resolve(home),
235
+ "Use the canonical user home.",
236
+ );
237
+ const root = rootFor(home, profile);
238
+ const program = path.join(root, "program"),
239
+ versions = path.join(program, "versions");
240
+ for (const part of [root, program, versions]) await directory(part);
241
+ const configPath = path.join(root, "config.json");
242
+ const previousConfig = await readState(configPath);
243
+ const nextConfig = config
244
+ ? configuration(config, profile)
245
+ : previousConfig
246
+ ? configuration(previousConfig, profile)
247
+ : null;
248
+ fail(
249
+ nextConfig,
250
+ "The first installation needs the Server URL and Agent Token.",
251
+ );
252
+ fail(
253
+ !fromUpdate || !config,
254
+ "Automatic updates never replace Agent credentials.",
255
+ );
256
+ const lock = path.join(program, "install.lock");
257
+ await writeFile(lock, String(process.pid), { flag: "wx", mode: 0o600 });
258
+ let staging;
259
+ try {
260
+ const managedNode = await runtime(program);
261
+ const destination = path.join(versions, version);
262
+ if (!existsSync(destination)) {
263
+ staging = path.join(versions, ".install-" + randomUUID());
264
+ await directory(staging);
265
+ await packageStage(
266
+ staging,
267
+ version,
268
+ managedNode,
269
+ fromUpdate ? undefined : (source ?? self),
270
+ );
271
+ await rename(staging, destination);
272
+ staging = undefined;
273
+ } else {
274
+ const stored = JSON.parse(
275
+ await readFile(path.join(destination, "app", "package.json"), "utf8"),
276
+ );
277
+ fail(
278
+ stored.name === "@nexum-hub/agent" && stored.version === version,
279
+ "An existing version is invalid.",
280
+ );
281
+ }
282
+ const launcher = path.join(program, "service-runner.mjs");
283
+ if (!existsSync(launcher))
284
+ await cp(
285
+ path.join(destination, "app", "scripts", "service-runner.mjs"),
286
+ launcher,
287
+ { errorOnExist: true },
288
+ );
289
+ const activePath = path.join(program, "active.json"),
290
+ old = await readState(activePath);
291
+ const plan = servicePlan({
292
+ profile,
293
+ home,
294
+ programDir: destination,
295
+ npmManaged: true,
296
+ ...(process.platform === "win32"
297
+ ? { windowsSid: currentWindowsSid() }
298
+ : {}),
299
+ });
300
+ if (register && old) {
301
+ const state = await serviceAction(plan, "status");
302
+ if (state.registered) await serviceAction(plan, "stop");
303
+ }
304
+ if (
305
+ !previousConfig ||
306
+ JSON.stringify(previousConfig) !== JSON.stringify(nextConfig)
307
+ )
308
+ await writeState(configPath, nextConfig);
309
+ await writeState(activePath, { version, directory: version });
310
+ if (register) {
311
+ await serviceAction(plan, "install");
312
+ if (start) await serviceAction(plan, "start");
313
+ }
314
+ return {
315
+ profile,
316
+ version,
317
+ serviceRegistered: register,
318
+ startRequested: register && start,
319
+ };
320
+ } finally {
321
+ if (staging) await rm(staging, { recursive: true, force: true });
322
+ await rm(lock, { force: true });
323
+ }
324
+ }
325
+ export async function updateNpmAgent({ profile, version, home = homedir() }) {
326
+ const result = await installNpmAgent({
327
+ profile,
328
+ version,
329
+ home,
330
+ register: false,
331
+ fromUpdate: true,
332
+ });
333
+ const update = path.join(rootFor(home, profile), "program", "update.json");
334
+ if ((await readState(update))?.version === version) await rm(update);
335
+ return result;
336
+ }
@@ -0,0 +1,118 @@
1
+ import { spawn } from "node:child_process";
2
+ import { appendFile, readFile } from "node:fs/promises";
3
+ import { homedir } from "node:os";
4
+ import path from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+
7
+ const profile = process.argv[2] === "--profile" ? process.argv[3] : undefined;
8
+ if (
9
+ !["production", "development"].includes(profile) ||
10
+ process.argv.length !== 4
11
+ )
12
+ throw new Error("The managed Agent service requires one explicit profile.");
13
+
14
+ const root = path.join(
15
+ homedir(),
16
+ profile === "production" ? ".nexum" : ".nexum-dev",
17
+ );
18
+ const program = path.join(root, "program");
19
+ const node = process.execPath;
20
+ const precise = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-next\.[0-9]+)?$/;
21
+ const delay = (ms) => new Promise((done) => setTimeout(done, ms));
22
+ const diagnostic = async (code) => {
23
+ try {
24
+ await appendFile(
25
+ path.join(root, "logs", "agent.log"),
26
+ new Date().toISOString() + " " + code + "\n",
27
+ { mode: 0o600 },
28
+ );
29
+ } catch {
30
+ process.stderr.write(code + "\n");
31
+ }
32
+ };
33
+ async function state(filename) {
34
+ const value = JSON.parse(
35
+ await readFile(path.join(program, filename), "utf8"),
36
+ );
37
+ if (!value || typeof value !== "object")
38
+ throw new Error("The Agent release state is invalid.");
39
+ return value;
40
+ }
41
+ let stopped = false;
42
+ process.on("SIGINT", () => {
43
+ stopped = true;
44
+ });
45
+ process.on("SIGTERM", () => {
46
+ stopped = true;
47
+ });
48
+
49
+ let failures = 0;
50
+ while (!stopped) {
51
+ let active;
52
+ try {
53
+ active = await state("active.json");
54
+ if (!precise.test(active.version) || active.directory !== active.version)
55
+ throw new Error("Invalid active Agent release.");
56
+ let pending;
57
+ try {
58
+ pending = await state("update.json");
59
+ } catch (cause) {
60
+ if (cause.code !== "ENOENT") throw cause;
61
+ }
62
+ if (pending && pending.version !== active.version) {
63
+ if (!precise.test(pending.version))
64
+ throw new Error("Invalid requested Agent version.");
65
+ const installer = path.join(
66
+ program,
67
+ "versions",
68
+ active.directory,
69
+ "app",
70
+ "scripts",
71
+ "npm-install.mjs",
72
+ );
73
+ const tool = await import(pathToFileURL(installer).href);
74
+ await tool.updateNpmAgent({ profile, version: pending.version });
75
+ failures = 0;
76
+ continue;
77
+ }
78
+ const cli = path.join(
79
+ program,
80
+ "versions",
81
+ active.directory,
82
+ "app",
83
+ "dist",
84
+ "cli.js",
85
+ );
86
+ const result = await new Promise((resolve, reject) => {
87
+ const child = spawn(
88
+ node,
89
+ ["--experimental-vm-modules", cli, "run", "--profile", profile],
90
+ {
91
+ stdio: "inherit",
92
+ windowsHide: true,
93
+ },
94
+ );
95
+ const forward = () => child.kill("SIGTERM");
96
+ process.on("SIGINT", forward);
97
+ process.on("SIGTERM", forward);
98
+ const finish = (error, code) => {
99
+ process.off("SIGINT", forward);
100
+ process.off("SIGTERM", forward);
101
+ error ? reject(error) : resolve(code);
102
+ };
103
+ child.once("error", (error) => finish(error));
104
+ child.once("exit", (code) => finish(null, code));
105
+ });
106
+ if (stopped || result === 0) break;
107
+ if (result === 75) {
108
+ failures = 0;
109
+ continue;
110
+ }
111
+ process.exitCode = 1;
112
+ break;
113
+ } catch {
114
+ if (stopped) break;
115
+ await diagnostic("agent_update_or_start_failed");
116
+ await delay(Math.min(30000, 1000 * 2 ** Math.min(failures++, 5)));
117
+ }
118
+ }