@tsplc/agent 0.2.17 → 0.2.19

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/src/cli.ts CHANGED
@@ -5,64 +5,112 @@ import { parseArgs } from "node:util";
5
5
  import { configureDocker, configureGateway } from "@tsplc/build";
6
6
  import { z } from "zod";
7
7
  import { createAgent } from "./agent.ts";
8
+ import { agentService, controllerSecretNames } from "./secrets.ts";
9
+ import { askCredentials, askSecret } from "./terminal.ts";
8
10
 
9
11
  const usage = `tsplc-agent setup|serve [--listen host:port] [--state directory] [--server-health url]
12
+ tsplc-agent secrets set|delete <name> [--service ${agentService}]
13
+ tsplc-agent secrets set-controller
10
14
 
11
15
  setup Builds the CODESYS builder and gateway images. Run it once, and after updating tsPLC.
12
16
  serve Serves deployments and logins. --listen is required: use the machine's Tailscale
13
17
  address, such as 100.101.102.103:4850. TSPLC_AGENT_TOKEN must hold a shared secret of
14
18
  at least 32 characters, such as one from \`openssl rand -hex 32\`. An optional
15
- TSPLC_AGENT_READ_TOKEN, as long, only opens the debugger at /debug and GET /status.`;
19
+ TSPLC_AGENT_READ_TOKEN, as long, only opens the debugger at /debug and GET /status.
20
+ secrets Stores a value a release's secrets name, typed without echo, in Bun.secrets under
21
+ --service, or deletes it. set-controller stores the controller user, which deployments
22
+ and logins then use when they send none. Run it as the user the agent runs as.`;
16
23
 
17
24
  const { values, positionals } = parseArgs({
18
- allowPositionals: true,
19
- options: {
20
- help: { type: "boolean", short: "h" },
21
- listen: { type: "string" },
22
- state: { type: "string" },
23
- "server-health": { type: "string" },
24
- },
25
+ allowPositionals: true,
26
+ options: {
27
+ help: { type: "boolean", short: "h" },
28
+ listen: { type: "string" },
29
+ state: { type: "string" },
30
+ "server-health": { type: "string" },
31
+ service: { type: "string" },
32
+ },
25
33
  });
26
- const command = positionals[0];
34
+ const [command, ...args] = positionals;
27
35
  if (!command || values.help) {
28
- console.log(usage);
29
- process.exit(0);
36
+ console.log(usage);
37
+ process.exit(0);
38
+ }
39
+ if (command !== "secrets" && args.length) {
40
+ throw new Error("Specify one command.");
30
41
  }
31
- if (positionals.length > 1) throw new Error("Specify one command.");
32
42
  if (command === "setup") {
33
- await configureDocker();
34
- await configureGateway();
43
+ await configureDocker();
44
+ await configureGateway();
35
45
  } else if (command === "serve") {
36
- const [, hostname, port] = /^(.+):(\d+)$/.exec(values.listen ?? "") ?? [];
37
- if (!hostname || !port) throw new Error("--listen host:port is required.");
38
- const token = z
39
- .string({ error: "Set TSPLC_AGENT_TOKEN" })
40
- .min(32, "TSPLC_AGENT_TOKEN must be at least 32 characters")
41
- .parse(process.env["TSPLC_AGENT_TOKEN"]);
42
- const readToken = z
43
- .string()
44
- .min(32, "TSPLC_AGENT_READ_TOKEN must be at least 32 characters")
45
- .refine((value) => value !== token, "TSPLC_AGENT_READ_TOKEN must differ from TSPLC_AGENT_TOKEN")
46
- .optional()
47
- .parse(process.env["TSPLC_AGENT_READ_TOKEN"]);
48
- const agent = await createAgent({
49
- state: values.state ?? join(homedir(), ".tsplc-agent"),
50
- token,
51
- readToken,
52
- serverHealthUrl: values["server-health"],
53
- log: (message) => console.log(`${new Date().toISOString()} ${message}`),
54
- });
55
- const server = Bun.serve({
56
- hostname,
57
- port: Number(port),
58
- fetch: agent.fetch,
59
- // Deployments stream for minutes and upload a server executable.
60
- idleTimeout: 0,
61
- maxRequestBodySize: 2 ** 30,
62
- });
63
- console.log(`tsPLC agent listening on ${server.url}`);
64
- for (const signal of ["SIGINT", "SIGTERM"] as const)
65
- process.on(signal, () => {
66
- void agent.stop().then(() => process.exit(0));
67
- });
68
- } else throw new Error(`Unknown command ${command}.`);
46
+ const [, hostname, port] = /^(.+):(\d+)$/.exec(values.listen ?? "") ?? [];
47
+ if (!hostname || !port) {
48
+ throw new Error("--listen host:port is required.");
49
+ }
50
+ const token = z
51
+ .string({ error: "Set TSPLC_AGENT_TOKEN" })
52
+ .min(32, "TSPLC_AGENT_TOKEN must be at least 32 characters")
53
+ .parse(process.env["TSPLC_AGENT_TOKEN"]);
54
+ const readToken = z
55
+ .string()
56
+ .min(32, "TSPLC_AGENT_READ_TOKEN must be at least 32 characters")
57
+ .refine(
58
+ (value) => value !== token,
59
+ "TSPLC_AGENT_READ_TOKEN must differ from TSPLC_AGENT_TOKEN",
60
+ )
61
+ .optional()
62
+ .parse(process.env["TSPLC_AGENT_READ_TOKEN"]);
63
+ const agent = await createAgent({
64
+ state: values.state ?? join(homedir(), ".tsplc-agent"),
65
+ token,
66
+ readToken,
67
+ serverHealthUrl: values["server-health"],
68
+ log: (message) => console.log(`${new Date().toISOString()} ${message}`),
69
+ });
70
+ const server = Bun.serve({
71
+ hostname,
72
+ port: Number(port),
73
+ fetch: agent.fetch,
74
+ // Deployments stream for minutes and upload a server executable.
75
+ idleTimeout: 0,
76
+ maxRequestBodySize: 2 ** 30,
77
+ });
78
+ console.log(`tsPLC agent listening on ${server.url}`);
79
+ for (const signal of ["SIGINT", "SIGTERM"] as const) {
80
+ process.on(signal, () => {
81
+ void agent.stop().then(() => process.exit(0));
82
+ });
83
+ }
84
+ } else if (command === "secrets") {
85
+ const [action, name, ...extra] = args;
86
+ const service = values.service ?? agentService;
87
+ if (action === "set" && name && !extra.length) {
88
+ await Bun.secrets.set({
89
+ service,
90
+ name,
91
+ value: await askSecret(`${name}: `),
92
+ });
93
+ } else if (action === "delete" && name && !extra.length) {
94
+ if (!(await Bun.secrets.delete({ service, name }))) {
95
+ throw new Error(`Service ${service} has no ${name}.`);
96
+ }
97
+ } else if (action === "set-controller" && !name) {
98
+ const { username, password } = await askCredentials();
99
+ await Bun.secrets.set({
100
+ service: agentService,
101
+ name: controllerSecretNames.username,
102
+ value: username,
103
+ });
104
+ await Bun.secrets.set({
105
+ service: agentService,
106
+ name: controllerSecretNames.password,
107
+ value: password,
108
+ });
109
+ } else {
110
+ throw new Error(
111
+ "Usage: tsplc-agent secrets set|delete <name> [--service service], or secrets set-controller",
112
+ );
113
+ }
114
+ } else {
115
+ throw new Error(`Unknown command ${command}.`);
116
+ }
package/src/client.ts CHANGED
@@ -2,131 +2,167 @@ import { hostname, userInfo } from "node:os";
2
2
  import { type LoginCommand, loginResultSchema } from "@tsplc/build";
3
3
  import { z } from "zod";
4
4
  import {
5
- type AgentEvent,
6
- clientHeaders,
7
- controllerSchema,
8
- type Credentials,
9
- type DeployOptions,
10
- eventSchema,
11
- logoutSchema,
12
- networkInterfaceSchema,
13
- type ReleaseManifest,
14
- releaseSchema,
15
- statusSchema,
16
- uploadEncoding,
17
- type Target,
18
- targetSchema,
19
- variableSchema,
5
+ clientHeaders,
6
+ controllerSchema,
7
+ type Credentials,
8
+ type DeployOptions,
9
+ errorSchema,
10
+ eventSchema,
11
+ logoutSchema,
12
+ networkInterfaceSchema,
13
+ type ReleaseManifest,
14
+ releaseSchema,
15
+ statusSchema,
16
+ uploadEncoding,
17
+ type Target,
18
+ targetSchema,
19
+ variableSchema,
20
20
  } from "./protocol";
21
21
 
22
22
  /** A failed agent operation; `downloadRequired` means only a full download can deploy. */
23
23
  export class AgentOperationError extends Error {
24
- constructor(
25
- message: string,
26
- readonly downloadRequired = false,
27
- ) {
28
- super(message);
29
- }
24
+ constructor(
25
+ message: string,
26
+ readonly downloadRequired = false,
27
+ ) {
28
+ super(message);
29
+ }
30
30
  }
31
31
 
32
32
  /** A file to upload, at its path in the release. */
33
33
  export interface ReleaseFile {
34
- path: string;
35
- content: Blob;
34
+ path: string;
35
+ content: Blob;
36
36
  }
37
37
 
38
38
  /** Talks to a plant agent at `url`, such as its Tailscale name and port. */
39
39
  export const createAgentClient = (options: { url: string; token: string }) => {
40
- // The agent records who deployed and who changed the controller.
41
- const identity = { [clientHeaders.user]: userInfo().username, [clientHeaders.host]: hostname() };
42
- const call = async (path: string, init: RequestInit = {}) => {
43
- const response = await fetch(new URL(path, options.url), {
44
- ...init,
45
- headers: { ...init.headers, ...identity, Authorization: `Bearer ${options.token}` },
46
- }).catch((cause: unknown) => {
47
- throw new Error(`Cannot reach the plant agent at ${options.url}`, { cause });
48
- });
49
- if (!response.ok) {
50
- const body = await response.json().catch(() => ({}));
51
- throw new AgentOperationError(
52
- z.object({ error: z.string() }).safeParse(body).data?.error ??
53
- `The agent answered ${response.status}`,
54
- );
55
- }
56
- return response;
57
- };
58
- const get = async <T>(path: string, schema: z.ZodType<T>) =>
59
- schema.parse(await (await call(path)).json());
60
- const send = async <T>(method: string, path: string, body: unknown, schema: z.ZodType<T>) =>
61
- schema.parse(
62
- await (
63
- await call(path, {
64
- method,
65
- headers: { "Content-Type": "application/json" },
66
- body: JSON.stringify(body),
67
- })
68
- ).json(),
69
- );
40
+ // The agent records who deployed and who changed the controller.
41
+ const identity = {
42
+ [clientHeaders.user]: userInfo().username,
43
+ [clientHeaders.host]: hostname(),
44
+ };
45
+ const call = async (path: string, init: RequestInit = {}) => {
46
+ const response = await fetch(new URL(path, options.url), {
47
+ ...init,
48
+ headers: {
49
+ ...init.headers,
50
+ ...identity,
51
+ Authorization: `Bearer ${options.token}`,
52
+ },
53
+ }).catch((cause: unknown) => {
54
+ throw new Error(`Cannot reach the plant agent at ${options.url}`, {
55
+ cause,
56
+ });
57
+ });
58
+ if (!response.ok) {
59
+ const body = await response.json().catch(() => ({}));
60
+ throw new AgentOperationError(
61
+ errorSchema.safeParse(body).data?.error ??
62
+ `The agent answered ${response.status}`,
63
+ );
64
+ }
65
+ return response;
66
+ };
67
+ const get = async <T>(path: string, schema: z.ZodType<T>) =>
68
+ schema.parse(await (await call(path)).json());
69
+ const send = async <T>(
70
+ method: string,
71
+ path: string,
72
+ body: unknown,
73
+ schema: z.ZodType<T>,
74
+ ) =>
75
+ schema.parse(
76
+ await (
77
+ await call(path, {
78
+ method,
79
+ headers: { "Content-Type": "application/json" },
80
+ body: JSON.stringify(body),
81
+ })
82
+ ).json(),
83
+ );
70
84
 
71
- /** Reads a streamed operation, reporting progress, until its result or failure. */
72
- const operation = async (response: Response, onProgress: (message: string) => void) => {
73
- const reader = response.body?.pipeThrough(new TextDecoderStream()).getReader();
74
- if (!reader) throw new Error("The agent returned no operation stream");
75
- let buffered = "";
76
- while (true) {
77
- const { done, value } = await reader.read();
78
- if (done) throw new Error("The agent closed the operation without a result");
79
- buffered += value;
80
- const lines = buffered.split("\n");
81
- buffered = lines.pop() ?? "";
82
- for (const line of lines.filter(Boolean)) {
83
- const event: AgentEvent = eventSchema.parse(JSON.parse(line));
84
- if (event.kind === "progress") onProgress(event.message);
85
- else if (event.kind === "done") return event.result;
86
- else throw new AgentOperationError(event.message, event.downloadRequired);
87
- }
88
- }
89
- };
85
+ /** Reads a streamed operation, reporting progress, until its result or failure. */
86
+ const operation = async (
87
+ response: Response,
88
+ onProgress: (message: string) => void,
89
+ ) => {
90
+ const reader = response.body
91
+ ?.pipeThrough(new TextDecoderStream())
92
+ .getReader();
93
+ if (!reader) {
94
+ throw new Error("The agent returned no operation stream");
95
+ }
96
+ let buffered = "";
97
+ while (true) {
98
+ const { done, value } = await reader.read();
99
+ if (done) {
100
+ throw new Error("The agent closed the operation without a result");
101
+ }
102
+ buffered += value;
103
+ const lines = buffered.split("\n");
104
+ buffered = lines.pop() ?? "";
105
+ for (const line of lines.filter(Boolean)) {
106
+ const event = eventSchema.parse(JSON.parse(line));
107
+ if (event.kind === "progress") {
108
+ onProgress(event.message);
109
+ } else if (event.kind === "done") {
110
+ return event.result;
111
+ } else {
112
+ throw new AgentOperationError(event.message, event.downloadRequired);
113
+ }
114
+ }
115
+ }
116
+ };
90
117
 
91
- return {
92
- status: () => get("/status", statusSchema),
93
- interfaces: () => get("/interfaces", z.array(networkInterfaceSchema)),
94
- discover: (name: string) => send("POST", "/discover", { name }, z.array(controllerSchema)),
95
- setTarget: (target: Target) => send("PUT", "/target", target, targetSchema),
96
- variables: () => get("/variables", z.array(variableSchema)),
97
- deploy: async (
98
- release: { manifest: ReleaseManifest; files: ReleaseFile[] },
99
- settings: DeployOptions,
100
- onProgress: (message: string) => void,
101
- ) => {
102
- const form = new FormData();
103
- form.set("manifest", JSON.stringify(release.manifest));
104
- form.set("options", JSON.stringify(settings));
105
- // Plants are often reached through a slow relay, and ST and scripts compress several times over.
106
- form.set("encoding", uploadEncoding);
107
- for (const file of release.files)
108
- form.set(
109
- `files/${file.path}`,
110
- new Blob([Bun.gzipSync(await file.content.bytes())]),
111
- file.path,
112
- );
113
- return releaseSchema.parse(
114
- await operation(await call("/deploy", { method: "POST", body: form }), onProgress),
115
- );
116
- },
117
- login: async (credentials: Credentials, onProgress: (message: string) => void) =>
118
- loginResultSchema.parse(
119
- await operation(
120
- await call("/login", {
121
- method: "POST",
122
- headers: { "Content-Type": "application/json" },
123
- body: JSON.stringify(credentials),
124
- }),
125
- onProgress,
126
- ),
127
- ),
128
- command: (command: LoginCommand) => send("POST", "/login/command", command, loginResultSchema),
129
- logout: () => send("DELETE", "/login", undefined, logoutSchema),
130
- };
118
+ return {
119
+ status: () => get("/status", statusSchema),
120
+ interfaces: () => get("/interfaces", z.array(networkInterfaceSchema)),
121
+ discover: (name: string) =>
122
+ send("POST", "/discover", { name }, z.array(controllerSchema)),
123
+ setTarget: (target: Target) => send("PUT", "/target", target, targetSchema),
124
+ variables: () => get("/variables", z.array(variableSchema)),
125
+ deploy: async (
126
+ release: { manifest: ReleaseManifest; files: ReleaseFile[] },
127
+ settings: DeployOptions,
128
+ onProgress: (message: string) => void,
129
+ ) => {
130
+ const form = new FormData();
131
+ form.set("manifest", JSON.stringify(release.manifest));
132
+ form.set("options", JSON.stringify(settings));
133
+ // Plants are often reached through a slow relay, and ST and scripts compress several times over.
134
+ form.set("encoding", uploadEncoding);
135
+ for (const file of release.files) {
136
+ form.set(
137
+ `files/${file.path}`,
138
+ new Blob([Bun.gzipSync(await file.content.bytes())]),
139
+ file.path,
140
+ );
141
+ }
142
+ return releaseSchema.parse(
143
+ await operation(
144
+ await call("/deploy", { method: "POST", body: form }),
145
+ onProgress,
146
+ ),
147
+ );
148
+ },
149
+ login: async (
150
+ credentials: Credentials | null,
151
+ onProgress: (message: string) => void,
152
+ ) =>
153
+ loginResultSchema.parse(
154
+ await operation(
155
+ await call("/login", {
156
+ method: "POST",
157
+ headers: { "Content-Type": "application/json" },
158
+ body: JSON.stringify(credentials),
159
+ }),
160
+ onProgress,
161
+ ),
162
+ ),
163
+ command: (command: LoginCommand) =>
164
+ send("POST", "/login/command", command, loginResultSchema),
165
+ logout: () => send("DELETE", "/login", undefined, logoutSchema),
166
+ };
131
167
  };
132
168
  export type AgentClient = ReturnType<typeof createAgentClient>;
package/src/codesys.ts ADDED
@@ -0,0 +1,117 @@
1
+ import { execFile } from "node:child_process";
2
+ import { join } from "node:path";
3
+ import { promisify } from "node:util";
4
+ import { gatewayImage, resolveConfig } from "@tsplc/build";
5
+ import type { Credentials, Target } from "./protocol";
6
+ import type { StoredRelease } from "./releases";
7
+
8
+ /** The gateway reaches controllers through this Docker network. */
9
+ const network = "tsplc-agent";
10
+ /**
11
+ * Builder containers reach the gateway by name on this internal network, which has no internet.
12
+ * With internet, CODESYS asks a certificate authority about each DLL it loads, without caching
13
+ * the answer, and opening a project takes minutes instead of seconds.
14
+ */
15
+ const codesysNetwork = "tsplc-agent-codesys";
16
+ const gateway = { host: "tsplc-agent-gateway", port: 1217 };
17
+ export const loginContainer = "tsplc-agent-login";
18
+ /** Keeps CODESYS running between deployments, so each skips starting it. */
19
+ export const deployContainer = "tsplc-agent-deploy";
20
+ /** CODESYS reads the controller user from these for one operation; the agent never stores it. */
21
+ const credentialNames = {
22
+ usernameEnv: "TSPLC_DEVICE_USERNAME",
23
+ passwordEnv: "TSPLC_DEVICE_PASSWORD",
24
+ };
25
+
26
+ const docker = async (...args: string[]) => {
27
+ const { stdout } = await promisify(execFile)("docker", args);
28
+ return stdout.trim();
29
+ };
30
+
31
+ const ensureNetwork = async (name: string, ...options: string[]) => {
32
+ if (
33
+ !(await docker("network", "ls", "--quiet", "--filter", `name=^${name}$`))
34
+ ) {
35
+ await docker("network", "create", ...options, name);
36
+ }
37
+ };
38
+
39
+ /** The gateway container stays up between operations, as a CODESYS gateway service would. */
40
+ export const ensureGateway = async () => {
41
+ await ensureNetwork(network);
42
+ await ensureNetwork(codesysNetwork, "--internal");
43
+ if (
44
+ !(await docker(
45
+ "container",
46
+ "ls",
47
+ "--quiet",
48
+ "--filter",
49
+ `name=^${gateway.host}$`,
50
+ ))
51
+ ) {
52
+ await docker("rm", "--force", gateway.host);
53
+ await docker(
54
+ "run",
55
+ "--detach",
56
+ "--restart",
57
+ "unless-stopped",
58
+ "--platform",
59
+ "linux/amd64",
60
+ "--network",
61
+ network,
62
+ "--name",
63
+ gateway.host,
64
+ gatewayImage,
65
+ );
66
+ }
67
+ // Gateways started by earlier agents are only on `network`.
68
+ const networks = await docker(
69
+ "inspect",
70
+ "--format",
71
+ "{{json .NetworkSettings.Networks}}",
72
+ gateway.host,
73
+ );
74
+ if (!(codesysNetwork in JSON.parse(networks))) {
75
+ await docker("network", "connect", codesysNetwork, gateway.host);
76
+ }
77
+ };
78
+
79
+ /** Hands the controller user to CODESYS through the environment for the duration of `run`. */
80
+ export const withCredentials = async <T>(
81
+ credentials: Credentials,
82
+ run: () => Promise<T>,
83
+ ) => {
84
+ process.env[credentialNames.usernameEnv] = credentials.username;
85
+ process.env[credentialNames.passwordEnv] = credentials.password;
86
+ try {
87
+ return await run();
88
+ } finally {
89
+ delete process.env[credentialNames.usernameEnv];
90
+ delete process.env[credentialNames.passwordEnv];
91
+ }
92
+ };
93
+
94
+ /**
95
+ * The release's build config, aimed at `target` through the agent's gateway. The download
96
+ * baseline in `controllerDirectory` outlives releases: an online change compares against the
97
+ * last download.
98
+ */
99
+ export const controllerConfig = (
100
+ release: StoredRelease,
101
+ target: Target,
102
+ controllerDirectory: string,
103
+ ) => ({
104
+ ...resolveConfig(
105
+ {
106
+ ...release.manifest.config,
107
+ online: {
108
+ network: codesysNetwork,
109
+ gateway,
110
+ device: target,
111
+ credentials: credentialNames,
112
+ },
113
+ },
114
+ join(release.directory, "manifest.json"),
115
+ ),
116
+ outDir: controllerDirectory,
117
+ });