@tsplc/agent 0.2.13 → 0.2.16
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/dist/cli.js +310 -36
- package/dist/cli.js.map +7 -6
- package/dist/client.js +33 -5
- package/dist/client.js.map +4 -4
- package/dist/index.js +310 -35
- package/dist/index.js.map +6 -5
- package/package.json +4 -3
- package/src/agent.ts +281 -22
- package/src/cli.ts +9 -1
- package/src/client.ts +7 -2
- package/src/logs.ts +39 -0
- package/src/protocol.ts +46 -2
package/dist/cli.js
CHANGED
|
@@ -11,13 +11,14 @@ import { z as z4 } from "zod";
|
|
|
11
11
|
// packages/agent/src/agent.ts
|
|
12
12
|
import { execFile } from "node:child_process";
|
|
13
13
|
import { timingSafeEqual } from "node:crypto";
|
|
14
|
-
import { existsSync as
|
|
15
|
-
import { mkdir as mkdir2, readdir, readFile as
|
|
14
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
15
|
+
import { mkdir as mkdir2, readdir, readFile as readFile3, stat as stat2, writeFile as writeFile2 } from "node:fs/promises";
|
|
16
16
|
import { join as join2 } from "node:path";
|
|
17
17
|
import { setTimeout as delay2 } from "node:timers/promises";
|
|
18
18
|
import { promisify } from "node:util";
|
|
19
19
|
import {
|
|
20
20
|
explicitDownload,
|
|
21
|
+
failureReason,
|
|
21
22
|
findControllerLogin,
|
|
22
23
|
gatewayImage,
|
|
23
24
|
loginCommandSchema,
|
|
@@ -26,6 +27,15 @@ import {
|
|
|
26
27
|
startWarmController,
|
|
27
28
|
updateWarmController
|
|
28
29
|
} from "@tsplc/build";
|
|
30
|
+
import {
|
|
31
|
+
createDebugger,
|
|
32
|
+
createDebugHandler,
|
|
33
|
+
createLoginAdapter,
|
|
34
|
+
loadManifest,
|
|
35
|
+
LoginUnavailable,
|
|
36
|
+
noLogin,
|
|
37
|
+
timelineEntries
|
|
38
|
+
} from "@tsplc/debug";
|
|
29
39
|
import { z as z3 } from "zod";
|
|
30
40
|
|
|
31
41
|
// packages/agent/src/discovery.ts
|
|
@@ -78,6 +88,7 @@ var discoverControllers = async (network, port = runtimePort) => {
|
|
|
78
88
|
};
|
|
79
89
|
|
|
80
90
|
// packages/agent/src/protocol.ts
|
|
91
|
+
import { tsplcConfigSchema } from "@tsplc/config";
|
|
81
92
|
import { z } from "zod";
|
|
82
93
|
var targetSchema = z.strictObject({
|
|
83
94
|
host: z.string().nonempty(),
|
|
@@ -101,7 +112,9 @@ var variableSchema = z.strictObject({ path: z.string(), type: z.string() });
|
|
|
101
112
|
var releaseManifestSchema = z.strictObject({
|
|
102
113
|
config: z.record(z.string(), z.unknown()),
|
|
103
114
|
variables: z.array(variableSchema),
|
|
104
|
-
server: z.string().nonempty().optional()
|
|
115
|
+
server: z.string().nonempty().optional(),
|
|
116
|
+
debug: tsplcConfigSchema.shape.debug,
|
|
117
|
+
serverTokenEnv: z.string().nonempty().optional()
|
|
105
118
|
});
|
|
106
119
|
var uploadEncoding = "gzip";
|
|
107
120
|
var deployOptionsSchema = z.strictObject({
|
|
@@ -129,13 +142,70 @@ var statusSchema = z.strictObject({
|
|
|
129
142
|
target: targetSchema.nullable(),
|
|
130
143
|
release: releaseSchema.nullable(),
|
|
131
144
|
server: z.strictObject({ executable: z.string(), running: z.boolean() }).nullable(),
|
|
132
|
-
login: z.
|
|
145
|
+
login: z.union([
|
|
146
|
+
z.strictObject({ state: z.string(), forced: z.array(z.string()) }),
|
|
147
|
+
z.strictObject({ error: z.string() })
|
|
148
|
+
]).nullable()
|
|
149
|
+
});
|
|
150
|
+
var logoutSchema = z.strictObject({ failure: z.string().optional() });
|
|
151
|
+
var clientHeaders = { user: "x-tsplc-user", host: "x-tsplc-host" };
|
|
152
|
+
var deploymentSchema = z.strictObject({
|
|
153
|
+
at: z.iso.datetime(),
|
|
154
|
+
release: z.string(),
|
|
155
|
+
build: z.string().optional(),
|
|
156
|
+
operation: z.enum(["download", "online-change"]),
|
|
157
|
+
user: z.string().optional(),
|
|
158
|
+
host: z.string().optional()
|
|
159
|
+
});
|
|
160
|
+
var auditSchema = z.strictObject({
|
|
161
|
+
at: z.iso.datetime(),
|
|
162
|
+
command: z.string(),
|
|
163
|
+
values: z.record(z.string(), z.string()),
|
|
164
|
+
previous: z.record(z.string(), z.string()).optional(),
|
|
165
|
+
user: z.string().optional(),
|
|
166
|
+
host: z.string().optional(),
|
|
167
|
+
release: z.string().optional(),
|
|
168
|
+
error: z.string().optional()
|
|
133
169
|
});
|
|
134
170
|
|
|
171
|
+
// packages/agent/src/logs.ts
|
|
172
|
+
import { existsSync } from "node:fs";
|
|
173
|
+
import { open, readFile, rename, stat } from "node:fs/promises";
|
|
174
|
+
var rotateBytes = 5 * 2 ** 20;
|
|
175
|
+
var appendJsonl = async (file, value) => {
|
|
176
|
+
if (existsSync(file) && (await stat(file)).size >= rotateBytes)
|
|
177
|
+
await rename(file, `${file}.1`);
|
|
178
|
+
const log = await open(file, "a+");
|
|
179
|
+
try {
|
|
180
|
+
const { size } = await log.stat();
|
|
181
|
+
const last = Buffer.alloc(1);
|
|
182
|
+
if (size)
|
|
183
|
+
await log.read(last, 0, 1, size - 1);
|
|
184
|
+
const separator = size && last[0] !== 10 ? `
|
|
185
|
+
` : "";
|
|
186
|
+
await log.writeFile(`${separator}${JSON.stringify(value)}
|
|
187
|
+
`);
|
|
188
|
+
} finally {
|
|
189
|
+
await log.close();
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
var readJsonl = async (file, schema, limit) => {
|
|
193
|
+
if (!existsSync(file))
|
|
194
|
+
return [];
|
|
195
|
+
return (await readFile(file, "utf8")).split(`
|
|
196
|
+
`).filter(Boolean).slice(-limit).flatMap((line) => {
|
|
197
|
+
try {
|
|
198
|
+
return [schema.parse(JSON.parse(line))];
|
|
199
|
+
} catch {
|
|
200
|
+
return [];
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
};
|
|
204
|
+
|
|
135
205
|
// packages/agent/src/releases.ts
|
|
136
206
|
import { createHash } from "node:crypto";
|
|
137
|
-
import { existsSync } from "node:fs";
|
|
138
|
-
import { mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
207
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
208
|
+
import { mkdir, mkdtemp, readFile as readFile2, rename as rename2, rm, writeFile } from "node:fs/promises";
|
|
139
209
|
import { dirname, join, posix } from "node:path";
|
|
140
210
|
import { z as z2 } from "zod";
|
|
141
211
|
var filePrefix = "files/";
|
|
@@ -163,7 +233,7 @@ var saveRelease = async (releases, { manifest, files }) => {
|
|
|
163
233
|
hash.update(file.path).update(createHash("sha256").update(file.content).digest("hex"));
|
|
164
234
|
const id = hash.digest("hex").slice(0, 16);
|
|
165
235
|
const directory = join(releases, id);
|
|
166
|
-
if (!
|
|
236
|
+
if (!existsSync2(directory)) {
|
|
167
237
|
await mkdir(releases, { recursive: true });
|
|
168
238
|
const staging = await mkdtemp(join(releases, ".upload-"));
|
|
169
239
|
try {
|
|
@@ -174,7 +244,7 @@ var saveRelease = async (releases, { manifest, files }) => {
|
|
|
174
244
|
});
|
|
175
245
|
}
|
|
176
246
|
await writeFile(join(staging, "manifest.json"), JSON.stringify(manifest, null, 2));
|
|
177
|
-
await
|
|
247
|
+
await rename2(staging, directory);
|
|
178
248
|
} catch (cause) {
|
|
179
249
|
await rm(staging, { recursive: true, force: true });
|
|
180
250
|
throw cause;
|
|
@@ -184,7 +254,7 @@ var saveRelease = async (releases, { manifest, files }) => {
|
|
|
184
254
|
};
|
|
185
255
|
var loadRelease = async (releases, id) => {
|
|
186
256
|
const directory = join(releases, id);
|
|
187
|
-
const manifest = releaseManifestSchema.parse(JSON.parse(await
|
|
257
|
+
const manifest = releaseManifestSchema.parse(JSON.parse(await readFile2(join(directory, "manifest.json"), "utf8")));
|
|
188
258
|
return { id, directory, manifest };
|
|
189
259
|
};
|
|
190
260
|
|
|
@@ -283,7 +353,40 @@ class AgentError extends Error {
|
|
|
283
353
|
}
|
|
284
354
|
}
|
|
285
355
|
var json = (body, status = 200) => Response.json(body, { status });
|
|
286
|
-
var
|
|
356
|
+
var message = (error) => error instanceof Error ? error.message : String(error);
|
|
357
|
+
var loginStateTimeout = 30000;
|
|
358
|
+
var stoppedAnswering = { error: "The login stopped answering" };
|
|
359
|
+
var recentEntries = 500;
|
|
360
|
+
var clientOf = (request) => {
|
|
361
|
+
const header = (name) => request.headers.get(name)?.slice(0, 200) || undefined;
|
|
362
|
+
return { user: header(clientHeaders.user), host: header(clientHeaders.host) };
|
|
363
|
+
};
|
|
364
|
+
var auditOf = (command) => {
|
|
365
|
+
switch (command.command) {
|
|
366
|
+
case "write":
|
|
367
|
+
case "force":
|
|
368
|
+
return { command: command.command, values: command.values };
|
|
369
|
+
case "unforce":
|
|
370
|
+
return {
|
|
371
|
+
command: command.restore ? "unforce --restore" : "unforce",
|
|
372
|
+
values: Object.fromEntries(command.expressions.map((expression) => [expression, ""]))
|
|
373
|
+
};
|
|
374
|
+
case "start":
|
|
375
|
+
case "stop":
|
|
376
|
+
return { command: command.command, values: {} };
|
|
377
|
+
case "reset":
|
|
378
|
+
return { command: `reset ${command.kind.toLowerCase()}`, values: {} };
|
|
379
|
+
case "state":
|
|
380
|
+
case "read":
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
};
|
|
384
|
+
var matches = (presented, token) => {
|
|
385
|
+
const actual = Buffer.from(presented);
|
|
386
|
+
const expected = Buffer.from(token);
|
|
387
|
+
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
388
|
+
};
|
|
389
|
+
var readJson = async (path, schema) => existsSync3(path) ? schema.parse(JSON.parse(await readFile3(path, "utf8"))) : null;
|
|
287
390
|
var docker = (...args) => execute("docker", args).then(({ stdout }) => stdout.trim());
|
|
288
391
|
var ensureNetwork = async (name, ...options) => {
|
|
289
392
|
if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`))
|
|
@@ -319,16 +422,16 @@ var followProgress = (controller, emit) => {
|
|
|
319
422
|
let offset = 0;
|
|
320
423
|
while (following) {
|
|
321
424
|
await delay2(2000);
|
|
322
|
-
if (!log &&
|
|
425
|
+
if (!log && existsSync3(jobs)) {
|
|
323
426
|
for (const job of await readdir(jobs)) {
|
|
324
427
|
const path = join2(jobs, job, ".codesys/controller/progress.log");
|
|
325
|
-
if (
|
|
428
|
+
if (existsSync3(path) && (await stat2(path)).mtimeMs >= since)
|
|
326
429
|
log = path;
|
|
327
430
|
}
|
|
328
431
|
}
|
|
329
432
|
if (!log)
|
|
330
433
|
continue;
|
|
331
|
-
const text = await
|
|
434
|
+
const text = await readFile3(log, "utf8");
|
|
332
435
|
for (const line of text.slice(offset).split(`
|
|
333
436
|
`).filter(Boolean))
|
|
334
437
|
emit({ kind: "progress", message: line.replace(/^\S+Z /, "") });
|
|
@@ -345,7 +448,10 @@ var createAgent = async (options) => {
|
|
|
345
448
|
releases: join2(options.state, "releases"),
|
|
346
449
|
controller: join2(options.state, "controller"),
|
|
347
450
|
release: join2(options.state, "release.json"),
|
|
348
|
-
target: join2(options.state, "target.json")
|
|
451
|
+
target: join2(options.state, "target.json"),
|
|
452
|
+
deployments: join2(options.state, "deployments.jsonl"),
|
|
453
|
+
audit: join2(options.state, "audit.jsonl"),
|
|
454
|
+
debug: join2(options.state, "debug")
|
|
349
455
|
};
|
|
350
456
|
await mkdir2(options.state, { recursive: true });
|
|
351
457
|
const server = createServerSupervisor({ healthUrl: options.serverHealthUrl, log: options.log });
|
|
@@ -382,6 +488,78 @@ var createAgent = async (options) => {
|
|
|
382
488
|
})().catch((error) => {
|
|
383
489
|
options.log(`Starting CODESYS failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
384
490
|
});
|
|
491
|
+
let loginGeneration = 0;
|
|
492
|
+
let commands = Promise.resolve();
|
|
493
|
+
const enqueue = (run) => {
|
|
494
|
+
const generation = loginGeneration;
|
|
495
|
+
const sent = commands.then(() => {
|
|
496
|
+
if (generation !== loginGeneration)
|
|
497
|
+
throw new AgentError("The login was closed", 409);
|
|
498
|
+
return run();
|
|
499
|
+
});
|
|
500
|
+
commands = sent.catch(() => {
|
|
501
|
+
return;
|
|
502
|
+
});
|
|
503
|
+
return sent;
|
|
504
|
+
};
|
|
505
|
+
const send = (login, loginCommand) => enqueue(() => login.send(loginCommand));
|
|
506
|
+
const readLogin = async ([first, ...rest]) => {
|
|
507
|
+
if (busy === "a login")
|
|
508
|
+
throw new LoginUnavailable("The engineering login is opening", { state: "connecting" });
|
|
509
|
+
if (busy)
|
|
510
|
+
throw new LoginUnavailable(`Live values pause during ${busy}`);
|
|
511
|
+
const login = await findControllerLogin(loginContainer);
|
|
512
|
+
if (!login)
|
|
513
|
+
throw new LoginUnavailable(noLogin);
|
|
514
|
+
if (!first)
|
|
515
|
+
return {};
|
|
516
|
+
const result = await send(login, { command: "read", expressions: [first, ...rest] });
|
|
517
|
+
if (!("values" in result))
|
|
518
|
+
throw new Error("The login answered a read without values");
|
|
519
|
+
return result.values;
|
|
520
|
+
};
|
|
521
|
+
const startDebugger = async () => {
|
|
522
|
+
const release = await readJson(paths.release, releaseSchema);
|
|
523
|
+
if (!release)
|
|
524
|
+
return null;
|
|
525
|
+
const { directory, manifest: releaseManifest } = await loadRelease(paths.releases, release.id);
|
|
526
|
+
const manifestFile = join2(directory, "debug.json");
|
|
527
|
+
if (!existsSync3(manifestFile))
|
|
528
|
+
return null;
|
|
529
|
+
const manifest = await loadManifest(manifestFile);
|
|
530
|
+
const serverToken = releaseManifest.serverTokenEnv && process.env[releaseManifest.serverTokenEnv];
|
|
531
|
+
const debug = await createDebugger({
|
|
532
|
+
manifest,
|
|
533
|
+
adapter: createLoginAdapter({
|
|
534
|
+
read: readLogin,
|
|
535
|
+
probe: manifest.build.target,
|
|
536
|
+
endpoint: "the agent's login"
|
|
537
|
+
}),
|
|
538
|
+
stateDirectory: paths.debug,
|
|
539
|
+
watch: releaseManifest.debug?.watch ?? {},
|
|
540
|
+
...options.serverHealthUrl && serverToken && {
|
|
541
|
+
server: { url: new URL(options.serverHealthUrl).origin, token: serverToken }
|
|
542
|
+
},
|
|
543
|
+
release: { id: release.id, deployedAt: release.deployedAt, operation: release.operation },
|
|
544
|
+
timeline: [
|
|
545
|
+
...(await readJsonl(paths.deployments, deploymentSchema, recentEntries)).map(({ at, ...deployment }) => timelineEntries.deploy(at, deployment)),
|
|
546
|
+
...(await readJsonl(paths.audit, auditSchema, recentEntries)).map(({ at, ...audit }) => timelineEntries.audit(at, audit))
|
|
547
|
+
],
|
|
548
|
+
log: options.log
|
|
549
|
+
});
|
|
550
|
+
return { debug, handle: createDebugHandler(debug, options.log) };
|
|
551
|
+
};
|
|
552
|
+
const debuggerFailed = (error) => {
|
|
553
|
+
options.log(`Starting the debugger failed: ${message(error)}`);
|
|
554
|
+
return null;
|
|
555
|
+
};
|
|
556
|
+
let debugging = startDebugger().catch(debuggerFailed);
|
|
557
|
+
const restartDebugger = () => {
|
|
558
|
+
debugging = debugging.then(async (current) => {
|
|
559
|
+
await current?.debug.close();
|
|
560
|
+
return startDebugger().catch(debuggerFailed);
|
|
561
|
+
});
|
|
562
|
+
};
|
|
385
563
|
const operation = (name, run) => {
|
|
386
564
|
if (busy)
|
|
387
565
|
throw new AgentError(`The agent is busy with ${busy}`, 409);
|
|
@@ -419,7 +597,7 @@ var createAgent = async (options) => {
|
|
|
419
597
|
}
|
|
420
598
|
}), { headers: { "Content-Type": "application/x-ndjson" } });
|
|
421
599
|
};
|
|
422
|
-
const deploy = async (form) => {
|
|
600
|
+
const deploy = async (form, client) => {
|
|
423
601
|
const settings = deployOptionsSchema.parse(JSON.parse(z3.string().parse(form.get("options"))));
|
|
424
602
|
const upload = await readUpload(form);
|
|
425
603
|
const target = await requireTarget();
|
|
@@ -428,7 +606,7 @@ var createAgent = async (options) => {
|
|
|
428
606
|
return operation("a deployment", async (emit) => {
|
|
429
607
|
const release = await saveRelease(paths.releases, upload);
|
|
430
608
|
const config = controllerConfig(release, target);
|
|
431
|
-
if (!settings.download && !
|
|
609
|
+
if (!settings.download && !existsSync3(join2(paths.controller, ".codesys/controller/current.json")))
|
|
432
610
|
throw new AgentError("The controller has no application downloaded by this agent; only a full download can deploy", 409, true);
|
|
433
611
|
const previous = await readJson(paths.release, releaseSchema);
|
|
434
612
|
const serverPath = release.manifest.server && `${release.id}/${release.manifest.server}`;
|
|
@@ -459,6 +637,16 @@ var createAgent = async (options) => {
|
|
|
459
637
|
server: serverPath ?? previous?.server
|
|
460
638
|
};
|
|
461
639
|
await writeFile2(paths.release, JSON.stringify(deployedRelease, null, 2));
|
|
640
|
+
const debugManifest = join2(release.directory, "debug.json");
|
|
641
|
+
const deployment = {
|
|
642
|
+
at: deployedRelease.deployedAt,
|
|
643
|
+
release: release.id,
|
|
644
|
+
...existsSync3(debugManifest) && { build: (await loadManifest(debugManifest)).build.id },
|
|
645
|
+
operation: kind,
|
|
646
|
+
...client
|
|
647
|
+
};
|
|
648
|
+
await appendJsonl(paths.deployments, deployment);
|
|
649
|
+
restartDebugger();
|
|
462
650
|
return deployedRelease;
|
|
463
651
|
});
|
|
464
652
|
};
|
|
@@ -471,25 +659,79 @@ var createAgent = async (options) => {
|
|
|
471
659
|
emit({ kind: "progress", message: "Logging in; CODESYS takes minutes to start" });
|
|
472
660
|
await ensureGateway();
|
|
473
661
|
const login = await withCredentials(credentials, () => openControllerLogin(config, loginContainer));
|
|
474
|
-
return
|
|
662
|
+
return send(login, { command: "state" });
|
|
475
663
|
});
|
|
476
664
|
};
|
|
477
665
|
const requireLogin = async () => {
|
|
666
|
+
if (busy)
|
|
667
|
+
throw new AgentError(`The agent is busy with ${busy}`, 409);
|
|
668
|
+
const generation = loginGeneration;
|
|
478
669
|
const login = await findControllerLogin(loginContainer);
|
|
670
|
+
if (generation !== loginGeneration)
|
|
671
|
+
throw new AgentError("The login was closed", 409);
|
|
672
|
+
if (busy)
|
|
673
|
+
throw new AgentError(`The agent is busy with ${busy}`, 409);
|
|
479
674
|
if (!login)
|
|
480
675
|
throw new AgentError("No login is open: tsplc login", 409);
|
|
481
676
|
return login;
|
|
482
677
|
};
|
|
483
|
-
const
|
|
678
|
+
const command = async (loginCommand, client) => {
|
|
679
|
+
const login = await requireLogin();
|
|
680
|
+
const change = auditOf(loginCommand);
|
|
681
|
+
if (!change)
|
|
682
|
+
return send(login, loginCommand);
|
|
683
|
+
return enqueue(async () => {
|
|
684
|
+
const [first, ...rest] = Object.keys(change.values);
|
|
685
|
+
const previous = first ? await login.send({ command: "read", expressions: [first, ...rest] }).then((result) => ("values" in result) ? result.values : undefined).catch(() => {
|
|
686
|
+
return;
|
|
687
|
+
}) : undefined;
|
|
688
|
+
const audit = async (error) => {
|
|
689
|
+
const entry = {
|
|
690
|
+
at: new Date().toISOString(),
|
|
691
|
+
...change,
|
|
692
|
+
...previous && { previous },
|
|
693
|
+
...client,
|
|
694
|
+
release: (await readJson(paths.release, releaseSchema))?.id,
|
|
695
|
+
...error !== undefined && { error: message(error) }
|
|
696
|
+
};
|
|
697
|
+
await appendJsonl(paths.audit, entry);
|
|
698
|
+
const { at, ...details } = entry;
|
|
699
|
+
(await debugging)?.debug.record(timelineEntries.audit(at, details));
|
|
700
|
+
};
|
|
701
|
+
try {
|
|
702
|
+
const result = await login.send(loginCommand);
|
|
703
|
+
await audit();
|
|
704
|
+
return result;
|
|
705
|
+
} catch (error) {
|
|
706
|
+
await audit(error);
|
|
707
|
+
throw error;
|
|
708
|
+
}
|
|
709
|
+
});
|
|
710
|
+
};
|
|
711
|
+
const loginStatus = async () => {
|
|
484
712
|
const login = await findControllerLogin(loginContainer);
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
713
|
+
if (!login)
|
|
714
|
+
return null;
|
|
715
|
+
if (!await login.ready())
|
|
716
|
+
return busy === "a login" ? null : stoppedAnswering;
|
|
717
|
+
try {
|
|
718
|
+
const state = await Promise.race([
|
|
719
|
+
send(login, { command: "state" }),
|
|
720
|
+
delay2(loginStateTimeout, null)
|
|
721
|
+
]);
|
|
722
|
+
if (!state)
|
|
723
|
+
return stoppedAnswering;
|
|
724
|
+
return "state" in state ? state : null;
|
|
725
|
+
} catch (error) {
|
|
726
|
+
return { error: failureReason(error) };
|
|
727
|
+
}
|
|
492
728
|
};
|
|
729
|
+
const status = async () => ({
|
|
730
|
+
target: await readJson(paths.target, targetSchema),
|
|
731
|
+
release: await readJson(paths.release, releaseSchema),
|
|
732
|
+
server: server.status() ?? null,
|
|
733
|
+
login: await loginStatus()
|
|
734
|
+
});
|
|
493
735
|
const route = async (request) => {
|
|
494
736
|
const { pathname } = new URL(request.url);
|
|
495
737
|
const key = `${request.method} ${pathname}`;
|
|
@@ -513,25 +755,51 @@ var createAgent = async (options) => {
|
|
|
513
755
|
case "GET /variables":
|
|
514
756
|
return json((await currentRelease()).manifest.variables);
|
|
515
757
|
case "POST /deploy":
|
|
516
|
-
return deploy(await request.formData());
|
|
758
|
+
return deploy(await request.formData(), clientOf(request));
|
|
517
759
|
case "POST /login":
|
|
518
760
|
return openLogin(credentialsSchema.parse(await request.json()));
|
|
519
761
|
case "POST /login/command":
|
|
520
|
-
return json(await (
|
|
521
|
-
case "DELETE /login":
|
|
522
|
-
|
|
523
|
-
|
|
762
|
+
return json(await command(loginCommandSchema.parse(await request.json()), clientOf(request)));
|
|
763
|
+
case "DELETE /login": {
|
|
764
|
+
const login = await requireLogin();
|
|
765
|
+
busy = "a logout";
|
|
766
|
+
loginGeneration++;
|
|
767
|
+
try {
|
|
768
|
+
const failure = await login.close();
|
|
769
|
+
commands = Promise.resolve();
|
|
770
|
+
if (failure)
|
|
771
|
+
options.log(`The login couldn't log out (${failure}); its container was removed`);
|
|
772
|
+
return json(failure ? { failure } : {});
|
|
773
|
+
} finally {
|
|
774
|
+
busy = undefined;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
524
777
|
default:
|
|
525
778
|
return json({ error: `No route ${key}` }, 404);
|
|
526
779
|
}
|
|
527
780
|
};
|
|
528
|
-
const
|
|
781
|
+
const debugRoute = async (request, route) => {
|
|
782
|
+
const current = await debugging;
|
|
783
|
+
if (!current)
|
|
784
|
+
return json({ error: "The deployed release has no debug manifest, or the debugger failed to start" }, 503);
|
|
785
|
+
return current.handle(request, route);
|
|
786
|
+
};
|
|
529
787
|
return {
|
|
530
788
|
fetch: async (request) => {
|
|
531
|
-
const
|
|
532
|
-
|
|
789
|
+
const { pathname, search, searchParams } = new URL(request.url);
|
|
790
|
+
const debugPath = pathname.startsWith("/debug/");
|
|
791
|
+
if (pathname === "/debug")
|
|
792
|
+
return new Response(null, { status: 308, headers: { Location: `/debug/${search}` } });
|
|
793
|
+
if (request.method === "GET" && (pathname === "/debug/" || pathname === "/debug/ui.js"))
|
|
794
|
+
return debugRoute(request, pathname.slice("/debug".length));
|
|
795
|
+
const presented = /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ?? (debugPath ? searchParams.get("token") : null) ?? "";
|
|
796
|
+
const full = matches(presented, options.token);
|
|
797
|
+
const read = options.readToken !== undefined && matches(presented, options.readToken) && (debugPath || request.method === "GET" && pathname === "/status");
|
|
798
|
+
if (!full && !read)
|
|
533
799
|
return json({ error: "Unauthorized" }, 401);
|
|
534
800
|
try {
|
|
801
|
+
if (debugPath)
|
|
802
|
+
return await debugRoute(request, pathname.slice("/debug".length));
|
|
535
803
|
return await route(request);
|
|
536
804
|
} catch (error) {
|
|
537
805
|
if (error instanceof AgentError)
|
|
@@ -542,7 +810,10 @@ var createAgent = async (options) => {
|
|
|
542
810
|
return json({ error: error instanceof Error ? error.message : String(error) }, 500);
|
|
543
811
|
}
|
|
544
812
|
},
|
|
545
|
-
stop: () =>
|
|
813
|
+
stop: async () => {
|
|
814
|
+
await (await debugging)?.debug.close();
|
|
815
|
+
await server.stop();
|
|
816
|
+
}
|
|
546
817
|
};
|
|
547
818
|
};
|
|
548
819
|
|
|
@@ -552,7 +823,8 @@ var usage = `tsplc-agent setup|serve [--listen host:port] [--state directory] [-
|
|
|
552
823
|
setup Builds the CODESYS builder and gateway images. Run it once, and after updating tsPLC.
|
|
553
824
|
serve Serves deployments and logins. --listen is required: use the machine's Tailscale
|
|
554
825
|
address, such as 100.101.102.103:4850. TSPLC_AGENT_TOKEN must hold a shared secret of
|
|
555
|
-
at least 32 characters, such as one from \`openssl rand -hex 32
|
|
826
|
+
at least 32 characters, such as one from \`openssl rand -hex 32\`. An optional
|
|
827
|
+
TSPLC_AGENT_READ_TOKEN, as long, only opens the debugger at /debug and GET /status.`;
|
|
556
828
|
var { values, positionals } = parseArgs({
|
|
557
829
|
allowPositionals: true,
|
|
558
830
|
options: {
|
|
@@ -577,9 +849,11 @@ if (command === "setup") {
|
|
|
577
849
|
if (!hostname || !port)
|
|
578
850
|
throw new Error("--listen host:port is required.");
|
|
579
851
|
const token = z4.string({ error: "Set TSPLC_AGENT_TOKEN" }).min(32, "TSPLC_AGENT_TOKEN must be at least 32 characters").parse(process.env["TSPLC_AGENT_TOKEN"]);
|
|
852
|
+
const readToken = z4.string().min(32, "TSPLC_AGENT_READ_TOKEN must be at least 32 characters").refine((value) => value !== token, "TSPLC_AGENT_READ_TOKEN must differ from TSPLC_AGENT_TOKEN").optional().parse(process.env["TSPLC_AGENT_READ_TOKEN"]);
|
|
580
853
|
const agent = await createAgent({
|
|
581
854
|
state: values.state ?? join3(homedir(), ".tsplc-agent"),
|
|
582
855
|
token,
|
|
856
|
+
readToken,
|
|
583
857
|
serverHealthUrl: values["server-health"],
|
|
584
858
|
log: (message) => console.log(`${new Date().toISOString()} ${message}`)
|
|
585
859
|
});
|
|
@@ -598,5 +872,5 @@ if (command === "setup") {
|
|
|
598
872
|
} else
|
|
599
873
|
throw new Error(`Unknown command ${command}.`);
|
|
600
874
|
|
|
601
|
-
//# debugId=
|
|
875
|
+
//# debugId=160936FEA2AC6AE664756E2164756E21
|
|
602
876
|
//# sourceMappingURL=cli.js.map
|