@tsplc/agent 0.5.10 → 0.5.12

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tsplc/agent",
3
- "version": "0.5.10",
3
+ "version": "0.5.12",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "description": "The tsPLC plant agent: deploys a program and its server to a controller on the plant network, and holds an engineering login for reads, writes and forces.",
@@ -42,10 +42,11 @@
42
42
  "bun": ">=1.4.3"
43
43
  },
44
44
  "dependencies": {
45
- "@tsplc/build": "0.5.10",
46
- "@tsplc/config": "0.5.10",
47
- "@tsplc/debug": "0.5.10",
48
- "@tsplc/iec": "0.5.10",
45
+ "@tsplc/build": "0.5.12",
46
+ "@tsplc/config": "0.5.12",
47
+ "@tsplc/debug": "0.5.12",
48
+ "@tsplc/iec": "0.5.12",
49
+ "@tsplc/server": "0.5.12",
49
50
  "zod": "4.3.6"
50
51
  },
51
52
  "bin": {
package/src/access.ts CHANGED
@@ -4,6 +4,7 @@ import { readFile, rename, writeFile } from "node:fs/promises";
4
4
  import { isIP } from "node:net";
5
5
  import { join } from "node:path";
6
6
  import { dashboardHeader } from "@tsplc/debug/api";
7
+ import { controllerRestartPath } from "@tsplc/server/plant-agent";
7
8
  import type { AuditLog } from "./audit";
8
9
  import { errorMessage } from "./errors";
9
10
  import {
@@ -83,13 +84,16 @@ const crossSite = () =>
83
84
 
84
85
  /**
85
86
  * Who a request is from, and the role that gives them. The full token is an admin and the read
86
- * token a viewer, as a bearer token or a browser session signed in with one. Under `/api` and
87
+ * token a viewer, as a bearer token or a browser session signed in with one. The deployed server's
88
+ * token restarts the controller and does nothing else; no browser signs in with it. Under `/api` and
87
89
  * `/debug`, a request from the agent's own PC is an admin, and one from a tailnet member has the
88
90
  * role `access.json` gives their login.
89
91
  */
90
92
  export const createAccess = (options: {
91
93
  token: string;
92
94
  readToken: string | undefined;
95
+ /** The token the agent starts the deployed server with, which may only restart the controller. */
96
+ serverToken: string | null;
93
97
  /** `access.json`, read on each tailnet request so `tsplc-agent access` applies at once. */
94
98
  file: string;
95
99
  whois: Whois;
@@ -117,6 +121,13 @@ export const createAccess = (options: {
117
121
  return null;
118
122
  };
119
123
 
124
+ const serverIdentity: Identity = {
125
+ login: null,
126
+ name: "Line server",
127
+ role: "deployer",
128
+ via: "server",
129
+ };
130
+
120
131
  const peerIdentity = async (
121
132
  request: Request,
122
133
  peer: Peer | null,
@@ -163,6 +174,14 @@ export const createAccess = (options: {
163
174
  /^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ??
164
175
  (pathname.startsWith("/debug/") ? searchParams.get("token") : null);
165
176
  if (presented !== null) {
177
+ if (
178
+ options.serverToken !== null &&
179
+ matches(presented, options.serverToken)
180
+ ) {
181
+ return request.method === "POST" && pathname === controllerRestartPath
182
+ ? serverIdentity
183
+ : refuse(403, "The server's token only restarts the controller");
184
+ }
166
185
  return tokenIdentity(presented) ?? unauthorized();
167
186
  }
168
187
  // The CLI's routes keep their tokens, but for the status the dashboard shows too.
package/src/agent.ts CHANGED
@@ -1,15 +1,21 @@
1
1
  import { join } from "node:path";
2
2
  import { loginCommandSchema } from "@tsplc/build";
3
+ import { plantAgentEnv } from "@tsplc/server/plant-agent";
3
4
  import { z } from "zod";
4
5
  import { accessFile, createAccess, type Peer } from "./access";
5
6
  import { createAudit } from "./audit";
6
7
  import { type CodesysSettings, describeBuilder } from "./codesys";
8
+ import { createControllerRoutes } from "./controller";
7
9
  import { createDashboard } from "./dashboard";
8
10
  import { createDebugging } from "./debugging";
9
11
  import { createDeployments } from "./deploy";
10
12
  import { createDeploymentRoutes } from "./deployments/routes";
11
13
  import { discoverControllers, networkInterfaces } from "./discovery";
12
- import { createEnvironment, environmentFile } from "./environment";
14
+ import {
15
+ createEnvironment,
16
+ environmentFile,
17
+ variablesFile,
18
+ } from "./environment";
13
19
  import { AgentError, errorMessage } from "./errors";
14
20
  import { type AgentExit, exitSchema } from "./instance";
15
21
  import { createLogin } from "./login";
@@ -44,6 +50,11 @@ export interface AgentOptions {
44
50
  serverHealthUrl?: string;
45
51
  /** Where a release's `serverTokenEnv` is read from; this process's environment by default. */
46
52
  environment?: Readonly<Record<string, string | undefined>>;
53
+ /**
54
+ * How the deployed server reaches this agent: its URL, and the token that lets the server restart
55
+ * the controller, which the server is started with. Without it the server can't.
56
+ */
57
+ serverAccess?: { url: string; token: string };
47
58
  /** Experimental: downloads without a baseline import their POUs in one PLCopenXML import. */
48
59
  bulkImport?: boolean;
49
60
  log: (message: string) => void;
@@ -63,8 +74,18 @@ export const createAgent = async (options: AgentOptions) => {
63
74
  healthUrl: options.serverHealthUrl,
64
75
  record: state.paths.server,
65
76
  output: state.paths.serverLog,
66
- environment: (executable) =>
67
- serverEnvironment(state.paths.releases, executable, environmentVariables),
77
+ // The agent's own address and token for the server win over anything a release sets.
78
+ environment: async (executable) => ({
79
+ ...(await serverEnvironment(
80
+ state.paths.releases,
81
+ executable,
82
+ environmentVariables,
83
+ )),
84
+ ...(options.serverAccess && {
85
+ [plantAgentEnv.url]: options.serverAccess.url,
86
+ [plantAgentEnv.token]: options.serverAccess.token,
87
+ }),
88
+ }),
68
89
  log,
69
90
  });
70
91
  const deployed = await state.release();
@@ -110,6 +131,7 @@ export const createAgent = async (options: AgentOptions) => {
110
131
  const access = createAccess({
111
132
  token: options.token,
112
133
  readToken: options.readToken,
134
+ serverToken: options.serverAccess?.token ?? null,
113
135
  file: accessFile(options.state),
114
136
  whois: createWhois({ run: runCommand, now: Date.now, log }),
115
137
  audit,
@@ -122,6 +144,7 @@ export const createAgent = async (options: AgentOptions) => {
122
144
  operations,
123
145
  audit,
124
146
  file: environmentFile(options.state),
147
+ variables: variablesFile(options.state),
125
148
  log,
126
149
  });
127
150
  const dashboard = createDashboard();
@@ -129,6 +152,12 @@ export const createAgent = async (options: AgentOptions) => {
129
152
  ...createDeploymentRoutes({ runner: deployments.runner, releases }),
130
153
  ...access.routes,
131
154
  ...environment.routes,
155
+ ...createControllerRoutes({
156
+ login,
157
+ warm: deployments.restart,
158
+ audit,
159
+ log,
160
+ }),
132
161
  ...audit.routes,
133
162
  ];
134
163
 
package/src/cli.ts CHANGED
@@ -11,7 +11,12 @@ import { createAgent } from "./agent";
11
11
  import { removeInstance, restartStatus, writeInstance } from "./instance";
12
12
  import { serviceCommand, upgradeCommand } from "./maintenance";
13
13
  import { type AccessConfig, roleSchema, tsplcVersion } from "./protocol";
14
- import { agentService, agentSetting, controllerSecretNames } from "./secrets";
14
+ import {
15
+ agentService,
16
+ agentSetting,
17
+ controllerSecretNames,
18
+ serverToken,
19
+ } from "./secrets";
15
20
  import { supervisedEnv } from "./service";
16
21
  import { openState } from "./state";
17
22
  import { askCredentials, askSecret } from "./terminal";
@@ -53,7 +58,7 @@ secrets Stores a value a release's secrets name, typed without echo, in Bun.secr
53
58
  --service, or deletes it. set-controller stores the controller user, which deployments
54
59
  and logins then use when they send none. Run it as the user the agent runs as.
55
60
  access Who on the tailnet may use the dashboard, by Tailscale login: viewer reads, deployer
56
- also deploys and restarts the server, admin also manages secrets and access. default
61
+ also deploys and restarts the server, admin also manages variables and access. default
57
62
  gives every other tailnet member a role, none by default. The full token is an admin,
58
63
  the read token a viewer, and a request from this PC an admin. The agent applies a
59
64
  change at once.`;
@@ -87,6 +92,19 @@ if (args.length > (takesArguments[command] ?? 0)) {
87
92
  }
88
93
  const stateDirectory = values.state ?? join(homedir(), ".tsplc-agent");
89
94
 
95
+ /** Wildcard listen addresses, and the loopback a process on this PC reaches them by. */
96
+ const loopbackFor: Record<string, string> = {
97
+ "0.0.0.0": "127.0.0.1",
98
+ "::": "::1",
99
+ };
100
+
101
+ /** Where a process on this PC, such as the deployed server, reaches the agent. */
102
+ const reachableUrl = (hostname: string, port: number) => {
103
+ const bare = hostname.replace(/^\[(.*)\]$/, "$1");
104
+ const host = loopbackFor[bare] ?? bare;
105
+ return `http://${host.includes(":") ? `[${host}]` : host}:${port}/`;
106
+ };
107
+
90
108
  /** The serve options as given, which the service and an upgraded agent repeat. */
91
109
  const serveOptions = () => {
92
110
  const [, hostname, portText] = /^(.+):(\d+)$/.exec(values.listen ?? "") ?? [];
@@ -138,6 +156,10 @@ if (command === "setup") {
138
156
  serverHealthUrl: values["server-health"],
139
157
  bulkImport: values["bulk-import"] ?? false,
140
158
  environment: process.env,
159
+ serverAccess: {
160
+ url: reachableUrl(hostname, port),
161
+ token: await serverToken(),
162
+ },
141
163
  log: (message) => console.log(`${new Date().toISOString()} ${message}`),
142
164
  exit: ({ restart }) => {
143
165
  void removeInstance(paths.agent, process.pid).then(() =>
package/src/client.ts CHANGED
@@ -5,6 +5,11 @@ import {
5
5
  type Rollback,
6
6
  workerScriptsDigest,
7
7
  } from "@tsplc/build";
8
+ import {
9
+ type ControllerRestart,
10
+ controllerRestartPath,
11
+ controllerRestartReplySchema,
12
+ } from "@tsplc/server/plant-agent";
8
13
  import { z } from "zod";
9
14
  import {
10
15
  agentVersionHeader,
@@ -25,6 +30,7 @@ import {
25
30
  eventSchema,
26
31
  logoutSchema,
27
32
  networkInterfaceSchema,
33
+ plantVariablesSchema,
28
34
  type ReleaseManifest,
29
35
  type ReleaseUpload,
30
36
  releaseSchema,
@@ -355,6 +361,23 @@ export const createAgentClient = (options: { url: string; token: string }) => {
355
361
  {},
356
362
  deploymentCreatedSchema,
357
363
  ),
364
+ /**
365
+ * The plant PC's plain variables, and the secrets it holds in `service`, or in the agent's
366
+ * own service when null: what a release is built with.
367
+ */
368
+ releaseVariables: (service: string | null) =>
369
+ get(
370
+ `/api/environment/release${service === null ? "" : `?${new URLSearchParams({ service })}`}`,
371
+ plantVariablesSchema,
372
+ ),
373
+ /** Resets the controller's application and starts it again; answers once it runs. */
374
+ restartController: (restart: ControllerRestart) =>
375
+ send(
376
+ "POST",
377
+ controllerRestartPath,
378
+ restart,
379
+ controllerRestartReplySchema,
380
+ ),
358
381
  login: async (
359
382
  credentials: Credentials | null,
360
383
  onProgress: (message: string) => void,
@@ -0,0 +1,60 @@
1
+ import type { ResetKind } from "@tsplc/build";
2
+ import {
3
+ controllerRestartPath,
4
+ type controllerRestartReplySchema,
5
+ controllerRestartSchema,
6
+ } from "@tsplc/server/plant-agent";
7
+ import type { z } from "zod";
8
+ import type { AuditLog } from "./audit";
9
+ import { AgentError, errorMessage } from "./errors";
10
+ import type { ApiRoute } from "./routes";
11
+
12
+ type Restart = (
13
+ reset: ResetKind,
14
+ ) => Promise<z.infer<typeof controllerRestartReplySchema>>;
15
+
16
+ /**
17
+ * Resetting the controller's application and starting it again, for the dashboard, `tsplc restart`
18
+ * and the deployed server: through the open login when there is one, which a deployment would
19
+ * also wait for, else through the CODESYS kept running for deployments. Each restart is audited.
20
+ */
21
+ export const createControllerRoutes = (context: {
22
+ login: { isOpen: () => Promise<boolean>; restart: Restart };
23
+ warm: Restart;
24
+ audit: AuditLog;
25
+ log: (message: string) => void;
26
+ }): ApiRoute[] => [
27
+ {
28
+ method: "POST",
29
+ pattern: controllerRestartPath,
30
+ role: "deployer",
31
+ handle: async (request, { identity }) => {
32
+ const { reset } = controllerRestartSchema.parse(await request.json());
33
+ const restart = (await context.login.isOpen())
34
+ ? context.login.restart
35
+ : context.warm;
36
+ const outcome = await restart(reset === "warm" ? "Warm" : "Cold").then(
37
+ (reply) => ({ reply, failure: null }),
38
+ (failure: unknown) => ({ reply: null, failure }),
39
+ );
40
+ // Refused before it began, such as while a deployment runs: nothing happened to record.
41
+ if (outcome.failure instanceof AgentError) {
42
+ throw outcome.failure;
43
+ }
44
+ await context.audit.record({
45
+ identity,
46
+ command: reset === "warm" ? "restart" : "restart --cold",
47
+ values: {},
48
+ previous: null,
49
+ error: outcome.failure === null ? null : errorMessage(outcome.failure),
50
+ });
51
+ if (outcome.reply === null) {
52
+ context.log(
53
+ `Restarting the controller failed: ${errorMessage(outcome.failure)}`,
54
+ );
55
+ throw new AgentError(errorMessage(outcome.failure), 500);
56
+ }
57
+ return Response.json(outcome.reply);
58
+ },
59
+ },
60
+ ];
@@ -1,5 +1,6 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { basename, dirname, resolve } from "node:path";
3
+ import { controllerRestartPath } from "@tsplc/server/plant-agent";
3
4
  import { errorMessage } from "../errors";
4
5
  import { allows, roles } from "../protocol";
5
6
 
@@ -12,12 +13,13 @@ export const dashboardAssets = "/dashboard-assets/";
12
13
  const page = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>tsPLC</title><script>document.documentElement.dataset.theme=localStorage.getItem("tsplc-theme")||""</script><link rel="stylesheet" href="${dashboardAssets}dashboard.css"><script type="module" src="${dashboardAssets}main.js"></script></head><body><main id="app"></main></body></html>`;
13
14
 
14
15
  /**
15
- * What the browser needs from protocol.ts at run time. The bundle can't import protocol.ts,
16
- * whose other schemas load the agent's Node-only packages, so the bundle is given the owner's
17
- * answers instead.
16
+ * What the browser needs from protocol.ts and the server's agent contract at run time. The bundle
17
+ * can't import protocol.ts, whose other schemas load the agent's Node-only packages, so the bundle
18
+ * is given the owners' answers instead.
18
19
  */
19
20
  const contract = {
20
21
  roles,
22
+ controllerRestartPath,
21
23
  permissions: Object.fromEntries(
22
24
  roles.map((role) => [
23
25
  role,
@@ -87,7 +87,7 @@ export const accessView = (app: App): View => {
87
87
  h(
88
88
  "p",
89
89
  { class: "muted" },
90
- "A viewer reads deployments, logs, the debugger and the audit log. A deployer also deploys, approves, rolls back and restarts the server. An admin also manages secrets and access.",
90
+ "A viewer reads deployments, logs, the debugger and the audit log. A deployer also deploys, approves, rolls back and restarts the server. An admin also manages the environment's variables and access.",
91
91
  ),
92
92
  rows.length
93
93
  ? h(
@@ -5,6 +5,56 @@ import { h } from "./dom";
5
5
  import { cancelable, shortId, states } from "./format";
6
6
  import { confirm, dialog, type MenuItem, toast } from "./overlay";
7
7
 
8
+ /**
9
+ * Resets the controller's application, warm or cold as chosen, and starts it again: CODESYS's
10
+ * "Reset warm" then "Start", for clearing a state the application got stuck in.
11
+ */
12
+ export const restartController = async (
13
+ /** Told when the restart is sent and when the agent has answered. */
14
+ running: (busy: boolean) => void,
15
+ ) => {
16
+ const reset = await dialog<"warm" | "cold" | null>({
17
+ title: "Reset and start the application?",
18
+ body: [
19
+ h(
20
+ "p",
21
+ {},
22
+ "The application stops, its variables go back to their initial values, and it starts again with the same code. The line stops for a moment.",
23
+ ),
24
+ h(
25
+ "p",
26
+ { class: "muted" },
27
+ "A warm reset keeps retain variables; a cold reset resets them too.",
28
+ ),
29
+ ],
30
+ actions: (close) => [
31
+ h("button", { class: "button", onclick: () => close(null) }, "Cancel"),
32
+ h(
33
+ "button",
34
+ { class: "button danger", onclick: () => close("cold") },
35
+ "Reset cold and start",
36
+ ),
37
+ h(
38
+ "button",
39
+ { class: "button primary", onclick: () => close("warm") },
40
+ "Reset warm and start",
41
+ ),
42
+ ],
43
+ });
44
+ if (!reset) {
45
+ return;
46
+ }
47
+ running(true);
48
+ try {
49
+ await attempt(
50
+ () => api.restartController({ reset }),
51
+ `Reset ${reset}; the application runs again`,
52
+ );
53
+ } finally {
54
+ running(false);
55
+ }
56
+ };
57
+
8
58
  /** Deploys a deployment's release again, applied at once or reviewed first, then opens the new one. */
9
59
  export const redeploy = async (app: App, record: DeploymentRecord) => {
10
60
  const mode = await dialog<DeploymentMode>({
@@ -1,3 +1,7 @@
1
+ import type {
2
+ ControllerRestart,
3
+ controllerRestartReplySchema,
4
+ } from "@tsplc/server/plant-agent";
1
5
  import type { z } from "zod";
2
6
  import type {
3
7
  AccessConfig,
@@ -9,9 +13,12 @@ import type {
9
13
  deploymentCreatedSchema,
10
14
  deploymentListSchema,
11
15
  deploymentSourceSchema,
16
+ EnvironmentListing,
17
+ EnvironmentValue,
12
18
  environmentEntrySchema,
13
19
  Identity,
14
20
  } from "../../protocol";
21
+ import { controllerRestartPath } from "./contract";
15
22
 
16
23
  // The answers come from the agent that served this page, built from the same sources, so they are
17
24
  // trusted: protocol.ts can't be bundled for a browser to parse them, since it loads @tsplc/build.
@@ -132,13 +139,17 @@ export const api = {
132
139
  eventsUrl: (id: string, after: number) =>
133
140
  `${deploymentPath(id)}/events?after=${after}`,
134
141
 
135
- environment: (): Promise<EnvironmentEntry[]> => get("/api/environment"),
136
- setEnvironment: (name: string, value: string): Promise<unknown> =>
137
- send("PUT", `/api/environment/${encodeURIComponent(name)}`, { value }),
142
+ environment: (): Promise<EnvironmentListing> => get("/api/environment"),
143
+ setEnvironment: (name: string, change: EnvironmentValue): Promise<unknown> =>
144
+ send("PUT", `/api/environment/${encodeURIComponent(name)}`, change),
138
145
  deleteEnvironment: (name: string): Promise<unknown> =>
139
146
  send("DELETE", `/api/environment/${encodeURIComponent(name)}`, null),
140
147
  restartServer: (): Promise<unknown> =>
141
148
  send("POST", "/api/server/restart", null),
149
+ restartController: (
150
+ restart: ControllerRestart,
151
+ ): Promise<z.infer<typeof controllerRestartReplySchema>> =>
152
+ send("POST", controllerRestartPath, restart),
142
153
 
143
154
  audit: (limit: number): Promise<Audit[]> => get(`/api/audit?limit=${limit}`),
144
155
  access: (): Promise<AccessConfig> => get("/api/access"),
@@ -1,15 +1,18 @@
1
+ import type { controllerRestartPath as restartPath } from "@tsplc/server/plant-agent";
1
2
  import type { Role, roles } from "../../protocol";
2
3
 
3
4
  /**
4
- * Put into the bundle by `createDashboard`, from protocol.ts: the bundle can't import protocol.ts,
5
+ * Put into the bundle by `createDashboard`, from protocol.ts and `@tsplc/server/plant-agent`: the bundle can't import protocol.ts,
5
6
  * whose other schemas load the agent's Node-only packages.
6
7
  */
7
8
  declare const TSPLC_CONTRACT: {
8
9
  roles: typeof roles;
10
+ controllerRestartPath: typeof restartPath;
9
11
  permissions: Readonly<Record<Role, Readonly<Record<Role, boolean>>>>;
10
12
  };
11
13
 
12
14
  export const roleNames = TSPLC_CONTRACT.roles;
15
+ export const controllerRestartPath = TSPLC_CONTRACT.controllerRestartPath;
13
16
 
14
17
  /** Whether `role` includes `required`, as protocol.ts's `allows` answered it. */
15
18
  export const allows = (role: Role, required: Role) =>