@tsplc/agent 0.2.14 → 0.2.17
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 +292 -29
- package/dist/cli.js.map +7 -6
- package/dist/client.js +29 -4
- package/dist/client.js.map +4 -4
- package/dist/index.js +292 -28
- package/dist/index.js.map +6 -5
- package/package.json +4 -3
- package/src/agent.ts +267 -17
- package/src/cli.ts +9 -1
- package/src/client.ts +7 -2
- package/src/logs.ts +39 -0
- package/src/protocol.ts +39 -0
package/dist/cli.js
CHANGED
|
@@ -11,8 +11,8 @@ 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";
|
|
@@ -27,6 +27,15 @@ import {
|
|
|
27
27
|
startWarmController,
|
|
28
28
|
updateWarmController
|
|
29
29
|
} from "@tsplc/build";
|
|
30
|
+
import {
|
|
31
|
+
createDebugger,
|
|
32
|
+
createDebugHandler,
|
|
33
|
+
createLoginAdapter,
|
|
34
|
+
loadManifest,
|
|
35
|
+
LoginUnavailable,
|
|
36
|
+
noLogin,
|
|
37
|
+
timelineEntries
|
|
38
|
+
} from "@tsplc/debug";
|
|
30
39
|
import { z as z3 } from "zod";
|
|
31
40
|
|
|
32
41
|
// packages/agent/src/discovery.ts
|
|
@@ -79,6 +88,7 @@ var discoverControllers = async (network, port = runtimePort) => {
|
|
|
79
88
|
};
|
|
80
89
|
|
|
81
90
|
// packages/agent/src/protocol.ts
|
|
91
|
+
import { tsplcConfigSchema } from "@tsplc/config";
|
|
82
92
|
import { z } from "zod";
|
|
83
93
|
var targetSchema = z.strictObject({
|
|
84
94
|
host: z.string().nonempty(),
|
|
@@ -102,7 +112,9 @@ var variableSchema = z.strictObject({ path: z.string(), type: z.string() });
|
|
|
102
112
|
var releaseManifestSchema = z.strictObject({
|
|
103
113
|
config: z.record(z.string(), z.unknown()),
|
|
104
114
|
variables: z.array(variableSchema),
|
|
105
|
-
server: z.string().nonempty().optional()
|
|
115
|
+
server: z.string().nonempty().optional(),
|
|
116
|
+
debug: tsplcConfigSchema.shape.debug,
|
|
117
|
+
serverTokenEnv: z.string().nonempty().optional()
|
|
106
118
|
});
|
|
107
119
|
var uploadEncoding = "gzip";
|
|
108
120
|
var deployOptionsSchema = z.strictObject({
|
|
@@ -135,11 +147,65 @@ var statusSchema = z.strictObject({
|
|
|
135
147
|
z.strictObject({ error: z.string() })
|
|
136
148
|
]).nullable()
|
|
137
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()
|
|
169
|
+
});
|
|
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
|
+
};
|
|
138
204
|
|
|
139
205
|
// packages/agent/src/releases.ts
|
|
140
206
|
import { createHash } from "node:crypto";
|
|
141
|
-
import { existsSync } from "node:fs";
|
|
142
|
-
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";
|
|
143
209
|
import { dirname, join, posix } from "node:path";
|
|
144
210
|
import { z as z2 } from "zod";
|
|
145
211
|
var filePrefix = "files/";
|
|
@@ -167,7 +233,7 @@ var saveRelease = async (releases, { manifest, files }) => {
|
|
|
167
233
|
hash.update(file.path).update(createHash("sha256").update(file.content).digest("hex"));
|
|
168
234
|
const id = hash.digest("hex").slice(0, 16);
|
|
169
235
|
const directory = join(releases, id);
|
|
170
|
-
if (!
|
|
236
|
+
if (!existsSync2(directory)) {
|
|
171
237
|
await mkdir(releases, { recursive: true });
|
|
172
238
|
const staging = await mkdtemp(join(releases, ".upload-"));
|
|
173
239
|
try {
|
|
@@ -178,7 +244,7 @@ var saveRelease = async (releases, { manifest, files }) => {
|
|
|
178
244
|
});
|
|
179
245
|
}
|
|
180
246
|
await writeFile(join(staging, "manifest.json"), JSON.stringify(manifest, null, 2));
|
|
181
|
-
await
|
|
247
|
+
await rename2(staging, directory);
|
|
182
248
|
} catch (cause) {
|
|
183
249
|
await rm(staging, { recursive: true, force: true });
|
|
184
250
|
throw cause;
|
|
@@ -188,7 +254,7 @@ var saveRelease = async (releases, { manifest, files }) => {
|
|
|
188
254
|
};
|
|
189
255
|
var loadRelease = async (releases, id) => {
|
|
190
256
|
const directory = join(releases, id);
|
|
191
|
-
const manifest = releaseManifestSchema.parse(JSON.parse(await
|
|
257
|
+
const manifest = releaseManifestSchema.parse(JSON.parse(await readFile2(join(directory, "manifest.json"), "utf8")));
|
|
192
258
|
return { id, directory, manifest };
|
|
193
259
|
};
|
|
194
260
|
|
|
@@ -287,7 +353,40 @@ class AgentError extends Error {
|
|
|
287
353
|
}
|
|
288
354
|
}
|
|
289
355
|
var json = (body, status = 200) => Response.json(body, { status });
|
|
290
|
-
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;
|
|
291
390
|
var docker = (...args) => execute("docker", args).then(({ stdout }) => stdout.trim());
|
|
292
391
|
var ensureNetwork = async (name, ...options) => {
|
|
293
392
|
if (!await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`))
|
|
@@ -323,16 +422,16 @@ var followProgress = (controller, emit) => {
|
|
|
323
422
|
let offset = 0;
|
|
324
423
|
while (following) {
|
|
325
424
|
await delay2(2000);
|
|
326
|
-
if (!log &&
|
|
425
|
+
if (!log && existsSync3(jobs)) {
|
|
327
426
|
for (const job of await readdir(jobs)) {
|
|
328
427
|
const path = join2(jobs, job, ".codesys/controller/progress.log");
|
|
329
|
-
if (
|
|
428
|
+
if (existsSync3(path) && (await stat2(path)).mtimeMs >= since)
|
|
330
429
|
log = path;
|
|
331
430
|
}
|
|
332
431
|
}
|
|
333
432
|
if (!log)
|
|
334
433
|
continue;
|
|
335
|
-
const text = await
|
|
434
|
+
const text = await readFile3(log, "utf8");
|
|
336
435
|
for (const line of text.slice(offset).split(`
|
|
337
436
|
`).filter(Boolean))
|
|
338
437
|
emit({ kind: "progress", message: line.replace(/^\S+Z /, "") });
|
|
@@ -349,7 +448,10 @@ var createAgent = async (options) => {
|
|
|
349
448
|
releases: join2(options.state, "releases"),
|
|
350
449
|
controller: join2(options.state, "controller"),
|
|
351
450
|
release: join2(options.state, "release.json"),
|
|
352
|
-
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")
|
|
353
455
|
};
|
|
354
456
|
await mkdir2(options.state, { recursive: true });
|
|
355
457
|
const server = createServerSupervisor({ healthUrl: options.serverHealthUrl, log: options.log });
|
|
@@ -386,6 +488,78 @@ var createAgent = async (options) => {
|
|
|
386
488
|
})().catch((error) => {
|
|
387
489
|
options.log(`Starting CODESYS failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
388
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
|
+
};
|
|
389
563
|
const operation = (name, run) => {
|
|
390
564
|
if (busy)
|
|
391
565
|
throw new AgentError(`The agent is busy with ${busy}`, 409);
|
|
@@ -423,7 +597,7 @@ var createAgent = async (options) => {
|
|
|
423
597
|
}
|
|
424
598
|
}), { headers: { "Content-Type": "application/x-ndjson" } });
|
|
425
599
|
};
|
|
426
|
-
const deploy = async (form) => {
|
|
600
|
+
const deploy = async (form, client) => {
|
|
427
601
|
const settings = deployOptionsSchema.parse(JSON.parse(z3.string().parse(form.get("options"))));
|
|
428
602
|
const upload = await readUpload(form);
|
|
429
603
|
const target = await requireTarget();
|
|
@@ -432,7 +606,7 @@ var createAgent = async (options) => {
|
|
|
432
606
|
return operation("a deployment", async (emit) => {
|
|
433
607
|
const release = await saveRelease(paths.releases, upload);
|
|
434
608
|
const config = controllerConfig(release, target);
|
|
435
|
-
if (!settings.download && !
|
|
609
|
+
if (!settings.download && !existsSync3(join2(paths.controller, ".codesys/controller/current.json")))
|
|
436
610
|
throw new AgentError("The controller has no application downloaded by this agent; only a full download can deploy", 409, true);
|
|
437
611
|
const previous = await readJson(paths.release, releaseSchema);
|
|
438
612
|
const serverPath = release.manifest.server && `${release.id}/${release.manifest.server}`;
|
|
@@ -463,6 +637,16 @@ var createAgent = async (options) => {
|
|
|
463
637
|
server: serverPath ?? previous?.server
|
|
464
638
|
};
|
|
465
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();
|
|
466
650
|
return deployedRelease;
|
|
467
651
|
});
|
|
468
652
|
};
|
|
@@ -475,21 +659,68 @@ var createAgent = async (options) => {
|
|
|
475
659
|
emit({ kind: "progress", message: "Logging in; CODESYS takes minutes to start" });
|
|
476
660
|
await ensureGateway();
|
|
477
661
|
const login = await withCredentials(credentials, () => openControllerLogin(config, loginContainer));
|
|
478
|
-
return
|
|
662
|
+
return send(login, { command: "state" });
|
|
479
663
|
});
|
|
480
664
|
};
|
|
481
665
|
const requireLogin = async () => {
|
|
666
|
+
if (busy)
|
|
667
|
+
throw new AgentError(`The agent is busy with ${busy}`, 409);
|
|
668
|
+
const generation = loginGeneration;
|
|
482
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);
|
|
483
674
|
if (!login)
|
|
484
675
|
throw new AgentError("No login is open: tsplc login", 409);
|
|
485
676
|
return login;
|
|
486
677
|
};
|
|
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
|
+
};
|
|
487
711
|
const loginStatus = async () => {
|
|
488
712
|
const login = await findControllerLogin(loginContainer);
|
|
489
|
-
if (!login
|
|
713
|
+
if (!login)
|
|
490
714
|
return null;
|
|
715
|
+
if (!await login.ready())
|
|
716
|
+
return busy === "a login" ? null : stoppedAnswering;
|
|
491
717
|
try {
|
|
492
|
-
const state = await
|
|
718
|
+
const state = await Promise.race([
|
|
719
|
+
send(login, { command: "state" }),
|
|
720
|
+
delay2(loginStateTimeout, null)
|
|
721
|
+
]);
|
|
722
|
+
if (!state)
|
|
723
|
+
return stoppedAnswering;
|
|
493
724
|
return "state" in state ? state : null;
|
|
494
725
|
} catch (error) {
|
|
495
726
|
return { error: failureReason(error) };
|
|
@@ -524,25 +755,51 @@ var createAgent = async (options) => {
|
|
|
524
755
|
case "GET /variables":
|
|
525
756
|
return json((await currentRelease()).manifest.variables);
|
|
526
757
|
case "POST /deploy":
|
|
527
|
-
return deploy(await request.formData());
|
|
758
|
+
return deploy(await request.formData(), clientOf(request));
|
|
528
759
|
case "POST /login":
|
|
529
760
|
return openLogin(credentialsSchema.parse(await request.json()));
|
|
530
761
|
case "POST /login/command":
|
|
531
|
-
return json(await (
|
|
532
|
-
case "DELETE /login":
|
|
533
|
-
|
|
534
|
-
|
|
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
|
+
}
|
|
535
777
|
default:
|
|
536
778
|
return json({ error: `No route ${key}` }, 404);
|
|
537
779
|
}
|
|
538
780
|
};
|
|
539
|
-
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
|
+
};
|
|
540
787
|
return {
|
|
541
788
|
fetch: async (request) => {
|
|
542
|
-
const
|
|
543
|
-
|
|
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)
|
|
544
799
|
return json({ error: "Unauthorized" }, 401);
|
|
545
800
|
try {
|
|
801
|
+
if (debugPath)
|
|
802
|
+
return await debugRoute(request, pathname.slice("/debug".length));
|
|
546
803
|
return await route(request);
|
|
547
804
|
} catch (error) {
|
|
548
805
|
if (error instanceof AgentError)
|
|
@@ -553,7 +810,10 @@ var createAgent = async (options) => {
|
|
|
553
810
|
return json({ error: error instanceof Error ? error.message : String(error) }, 500);
|
|
554
811
|
}
|
|
555
812
|
},
|
|
556
|
-
stop: () =>
|
|
813
|
+
stop: async () => {
|
|
814
|
+
await (await debugging)?.debug.close();
|
|
815
|
+
await server.stop();
|
|
816
|
+
}
|
|
557
817
|
};
|
|
558
818
|
};
|
|
559
819
|
|
|
@@ -563,7 +823,8 @@ var usage = `tsplc-agent setup|serve [--listen host:port] [--state directory] [-
|
|
|
563
823
|
setup Builds the CODESYS builder and gateway images. Run it once, and after updating tsPLC.
|
|
564
824
|
serve Serves deployments and logins. --listen is required: use the machine's Tailscale
|
|
565
825
|
address, such as 100.101.102.103:4850. TSPLC_AGENT_TOKEN must hold a shared secret of
|
|
566
|
-
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.`;
|
|
567
828
|
var { values, positionals } = parseArgs({
|
|
568
829
|
allowPositionals: true,
|
|
569
830
|
options: {
|
|
@@ -588,9 +849,11 @@ if (command === "setup") {
|
|
|
588
849
|
if (!hostname || !port)
|
|
589
850
|
throw new Error("--listen host:port is required.");
|
|
590
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"]);
|
|
591
853
|
const agent = await createAgent({
|
|
592
854
|
state: values.state ?? join3(homedir(), ".tsplc-agent"),
|
|
593
855
|
token,
|
|
856
|
+
readToken,
|
|
594
857
|
serverHealthUrl: values["server-health"],
|
|
595
858
|
log: (message) => console.log(`${new Date().toISOString()} ${message}`)
|
|
596
859
|
});
|
|
@@ -609,5 +872,5 @@ if (command === "setup") {
|
|
|
609
872
|
} else
|
|
610
873
|
throw new Error(`Unknown command ${command}.`);
|
|
611
874
|
|
|
612
|
-
//# debugId=
|
|
875
|
+
//# debugId=160936FEA2AC6AE664756E2164756E21
|
|
613
876
|
//# sourceMappingURL=cli.js.map
|