@tsplc/agent 0.5.9 → 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.
Files changed (51) hide show
  1. package/dist/cli.js +2660 -525
  2. package/dist/cli.js.map +32 -18
  3. package/dist/client.js +262 -37
  4. package/dist/client.js.map +4 -4
  5. package/dist/index.js +2325 -415
  6. package/dist/index.js.map +27 -14
  7. package/package.json +6 -5
  8. package/src/access.ts +276 -0
  9. package/src/agent.ts +130 -29
  10. package/src/audit.ts +64 -0
  11. package/src/cli.ts +81 -5
  12. package/src/client.ts +204 -36
  13. package/src/controller.ts +60 -0
  14. package/src/dashboard/index.ts +118 -0
  15. package/src/dashboard/ui/access.ts +192 -0
  16. package/src/dashboard/ui/actions.ts +192 -0
  17. package/src/dashboard/ui/api.ts +158 -0
  18. package/src/dashboard/ui/app.ts +41 -0
  19. package/src/dashboard/ui/approval.ts +132 -0
  20. package/src/dashboard/ui/audit.ts +115 -0
  21. package/src/dashboard/ui/contract.ts +19 -0
  22. package/src/dashboard/ui/dashboard.css +1332 -0
  23. package/src/dashboard/ui/deployment.ts +432 -0
  24. package/src/dashboard/ui/deployments.ts +317 -0
  25. package/src/dashboard/ui/details.ts +240 -0
  26. package/src/dashboard/ui/dom.ts +91 -0
  27. package/src/dashboard/ui/environment.ts +326 -0
  28. package/src/dashboard/ui/format.ts +118 -0
  29. package/src/dashboard/ui/logs.ts +127 -0
  30. package/src/dashboard/ui/main.ts +86 -0
  31. package/src/dashboard/ui/overlay.ts +146 -0
  32. package/src/dashboard/ui/shell.ts +192 -0
  33. package/src/dashboard/ui/source.ts +144 -0
  34. package/src/deploy.ts +174 -144
  35. package/src/deployments/health.ts +80 -0
  36. package/src/deployments/retention.ts +45 -0
  37. package/src/deployments/routes.ts +273 -0
  38. package/src/deployments/runner.ts +877 -0
  39. package/src/deployments/store.ts +233 -0
  40. package/src/environment.ts +284 -0
  41. package/src/index.ts +4 -0
  42. package/src/login.ts +17 -0
  43. package/src/operations.ts +6 -1
  44. package/src/protocol.ts +259 -2
  45. package/src/releases.ts +73 -1
  46. package/src/routes.ts +52 -0
  47. package/src/secrets.ts +74 -4
  48. package/src/server-process.ts +33 -16
  49. package/src/sessions.ts +58 -0
  50. package/src/state.ts +2 -0
  51. package/src/tailscale.ts +112 -0
package/src/cli.ts CHANGED
@@ -1,15 +1,22 @@
1
1
  #!/usr/bin/env bun
2
+ import { mkdir } from "node:fs/promises";
2
3
  import { homedir } from "node:os";
3
4
  import { join } from "node:path";
4
5
  import { parseArgs } from "node:util";
5
6
  import { configureDocker, configureGateway } from "@tsplc/build";
6
7
  import { tcpPort } from "@tsplc/config/build";
7
8
  import { z } from "zod";
9
+ import { accessFile, readAccessConfig, writeAccessConfig } from "./access";
8
10
  import { createAgent } from "./agent";
9
11
  import { removeInstance, restartStatus, writeInstance } from "./instance";
10
12
  import { serviceCommand, upgradeCommand } from "./maintenance";
11
- import { tsplcVersion } from "./protocol";
12
- import { agentService, agentSetting, controllerSecretNames } from "./secrets";
13
+ import { type AccessConfig, roleSchema, tsplcVersion } from "./protocol";
14
+ import {
15
+ agentService,
16
+ agentSetting,
17
+ controllerSecretNames,
18
+ serverToken,
19
+ } from "./secrets";
13
20
  import { supervisedEnv } from "./service";
14
21
  import { openState } from "./state";
15
22
  import { askCredentials, askSecret } from "./terminal";
@@ -21,6 +28,7 @@ tsplc-agent upgrade [version] [--state directory]
21
28
  tsplc-agent service install|uninstall|status [serve options] [--stop-server]
22
29
  tsplc-agent secrets set|delete <name> [--service ${agentService}]
23
30
  tsplc-agent secrets set-controller
31
+ tsplc-agent access list|grant <login> <role>|revoke <login>|default <role|none> [--state directory]
24
32
 
25
33
  setup Builds the CODESYS builder and gateway images, keeping each that is already right for
26
34
  this tsPLC. Builder containers run the installed tsPLC's code and CODESYS scripts, so
@@ -30,7 +38,8 @@ setup Builds the CODESYS builder and gateway images, keeping each that is alre
30
38
  serve Serves deployments and logins. --listen is required: use the machine's Tailscale
31
39
  address, such as 100.101.102.103:4850. TSPLC_AGENT_TOKEN must hold a shared secret of
32
40
  at least 32 characters, such as one from \`openssl rand -hex 32\`. An optional
33
- TSPLC_AGENT_READ_TOKEN, as long, only opens the debugger at /debug and GET /status.
41
+ TSPLC_AGENT_READ_TOKEN, as long, only reads: the debugger at /debug, GET /status
42
+ and the dashboard.
34
43
  Each comes from its environment variable, or else from \`secrets set\` under ${agentService}.
35
44
  --bulk-import (experimental) brings a download without a baseline's POUs into CODESYS
36
45
  in one PLCopenXML import, importing one at a time if CODESYS reports any problem.
@@ -47,7 +56,12 @@ service Runs the agent as a Windows service: a Task Scheduler task that starts i
47
56
  line's server running unless --stop-server.
48
57
  secrets Stores a value a release's secrets name, typed without echo, in Bun.secrets under
49
58
  --service, or deletes it. set-controller stores the controller user, which deployments
50
- and logins then use when they send none. Run it as the user the agent runs as.`;
59
+ and logins then use when they send none. Run it as the user the agent runs as.
60
+ access Who on the tailnet may use the dashboard, by Tailscale login: viewer reads, deployer
61
+ also deploys and restarts the server, admin also manages variables and access. default
62
+ gives every other tailnet member a role, none by default. The full token is an admin,
63
+ the read token a viewer, and a request from this PC an admin. The agent applies a
64
+ change at once.`;
51
65
 
52
66
  const { values, positionals } = parseArgs({
53
67
  allowPositionals: true,
@@ -69,6 +83,7 @@ if (!command || values.help) {
69
83
  }
70
84
  const takesArguments: Record<string, number> = {
71
85
  secrets: 3,
86
+ access: 3,
72
87
  upgrade: 1,
73
88
  service: 1,
74
89
  };
@@ -77,6 +92,19 @@ if (args.length > (takesArguments[command] ?? 0)) {
77
92
  }
78
93
  const stateDirectory = values.state ?? join(homedir(), ".tsplc-agent");
79
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
+
80
108
  /** The serve options as given, which the service and an upgraded agent repeat. */
81
109
  const serveOptions = () => {
82
110
  const [, hostname, portText] = /^(.+):(\d+)$/.exec(values.listen ?? "") ?? [];
@@ -128,6 +156,10 @@ if (command === "setup") {
128
156
  serverHealthUrl: values["server-health"],
129
157
  bulkImport: values["bulk-import"] ?? false,
130
158
  environment: process.env,
159
+ serverAccess: {
160
+ url: reachableUrl(hostname, port),
161
+ token: await serverToken(),
162
+ },
131
163
  log: (message) => console.log(`${new Date().toISOString()} ${message}`),
132
164
  exit: ({ restart }) => {
133
165
  void removeInstance(paths.agent, process.pid).then(() =>
@@ -138,7 +170,7 @@ if (command === "setup") {
138
170
  const server = Bun.serve({
139
171
  hostname,
140
172
  port,
141
- fetch: agent.fetch,
173
+ fetch: (request, server) => agent.fetch(request, server.requestIP(request)),
142
174
  // Deployments stream for minutes and upload a server executable.
143
175
  idleTimeout: 0,
144
176
  maxRequestBodySize: 2 ** 30,
@@ -203,6 +235,50 @@ if (command === "setup") {
203
235
  "Usage: tsplc-agent secrets set|delete <name> [--service service], or secrets set-controller",
204
236
  );
205
237
  }
238
+ } else if (command === "access") {
239
+ const file = accessFile(stateDirectory);
240
+ const config = await readAccessConfig(file);
241
+ const [action, first, second, ...extra] = args;
242
+ const change = ((): AccessConfig | null => {
243
+ if (action === "grant" && first && second && !extra.length) {
244
+ return {
245
+ ...config,
246
+ roles: { ...config.roles, [first]: roleSchema.parse(second) },
247
+ };
248
+ }
249
+ if (action === "revoke" && first && !second) {
250
+ if (!(first in config.roles)) {
251
+ throw new Error(`${first} has no role.`);
252
+ }
253
+ return {
254
+ ...config,
255
+ roles: Object.fromEntries(
256
+ Object.entries(config.roles).filter(([login]) => login !== first),
257
+ ),
258
+ };
259
+ }
260
+ if (action === "default" && first && !second) {
261
+ return {
262
+ ...config,
263
+ tailnetDefault: first === "none" ? null : roleSchema.parse(first),
264
+ };
265
+ }
266
+ if (action === "list" && !first) {
267
+ return null;
268
+ }
269
+ throw new Error(
270
+ "Usage: tsplc-agent access list|grant <login> <role>|revoke <login>|default <role|none>",
271
+ );
272
+ })();
273
+ if (change) {
274
+ await mkdir(stateDirectory, { recursive: true });
275
+ await writeAccessConfig(file, change);
276
+ }
277
+ const shown = change ?? config;
278
+ for (const [login, role] of Object.entries(shown.roles)) {
279
+ console.log(`${login}\t${role}`);
280
+ }
281
+ console.log(`Other tailnet members: ${shown.tailnetDefault ?? "none"}`);
206
282
  } else {
207
283
  throw new Error(`Unknown command ${command}.`);
208
284
  }
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,
@@ -13,11 +18,19 @@ import {
13
18
  clientHeaders,
14
19
  comparisonSchema,
15
20
  controllerSchema,
21
+ type DeploymentLogLine,
22
+ type DeploymentMode,
23
+ type DeploymentRecord,
16
24
  type DeployOptions,
25
+ deploymentCreatedSchema,
26
+ deploymentListSchema,
27
+ deploymentLogLineSchema,
28
+ deploymentRecordSchema,
17
29
  errorSchema,
18
30
  eventSchema,
19
31
  logoutSchema,
20
32
  networkInterfaceSchema,
33
+ plantVariablesSchema,
21
34
  type ReleaseManifest,
22
35
  type ReleaseUpload,
23
36
  releaseSchema,
@@ -59,6 +72,52 @@ export class AgentOperationError extends Error {
59
72
  }
60
73
  }
61
74
 
75
+ /** The agent can't be reached, or the connection to it broke; trying again may succeed. */
76
+ export class AgentUnreachable extends Error {}
77
+
78
+ /** One of a deployment's server-sent events: the whole record, or one log line. */
79
+ export type DeploymentEvent =
80
+ | { kind: "record"; record: DeploymentRecord }
81
+ | { kind: "log"; line: DeploymentLogLine };
82
+
83
+ /** Each event of a `text/event-stream` body as its name and data; comments and other fields are skipped. */
84
+ async function* serverSentEvents(body: NonNullable<Response["body"]>) {
85
+ const reader = body.pipeThrough(new TextDecoderStream()).getReader();
86
+ let buffered = "";
87
+ let name = "message";
88
+ let data: string[] = [];
89
+ try {
90
+ while (true) {
91
+ const { done, value } = await reader.read().catch((cause: unknown) => {
92
+ throw new AgentUnreachable("The connection to the agent broke", {
93
+ cause,
94
+ });
95
+ });
96
+ if (done) {
97
+ return;
98
+ }
99
+ buffered += value;
100
+ const lines = buffered.split(/\r?\n/);
101
+ buffered = lines.pop() ?? "";
102
+ for (const line of lines) {
103
+ if (line === "") {
104
+ if (data.length) {
105
+ yield { name, data: data.join("\n") };
106
+ }
107
+ name = "message";
108
+ data = [];
109
+ } else if (line.startsWith("event:")) {
110
+ name = line.slice("event:".length).trim();
111
+ } else if (line.startsWith("data:")) {
112
+ data.push(line.slice("data:".length).replace(/^ /, ""));
113
+ }
114
+ }
115
+ }
116
+ } finally {
117
+ await reader.cancel().catch(() => {});
118
+ }
119
+ }
120
+
62
121
  /** A file to upload, at its path in the release. */
63
122
  export interface ReleaseFile {
64
123
  path: string;
@@ -80,8 +139,8 @@ export const createAgentClient = (options: { url: string; token: string }) => {
80
139
  [clientHeaders.version]: tsplcVersion,
81
140
  ...scripts,
82
141
  }));
83
- const call = async (path: string, init: RequestInit = {}) => {
84
- const response = await fetch(new URL(path, options.url), {
142
+ const request = async (path: string, init: RequestInit = {}) =>
143
+ fetch(new URL(path, options.url), {
85
144
  ...init,
86
145
  headers: {
87
146
  ...init.headers,
@@ -89,10 +148,12 @@ export const createAgentClient = (options: { url: string; token: string }) => {
89
148
  Authorization: `Bearer ${options.token}`,
90
149
  },
91
150
  }).catch((cause: unknown) => {
92
- throw new Error(`Cannot reach the plant agent at ${options.url}`, {
93
- cause,
94
- });
151
+ throw new AgentUnreachable(
152
+ `Cannot reach the plant agent at ${options.url}`,
153
+ { cause },
154
+ );
95
155
  });
156
+ const answered = async (response: Response) => {
96
157
  if (!response.ok) {
97
158
  const body = await response.json().catch(() => ({}));
98
159
  throw new AgentOperationError(
@@ -102,6 +163,8 @@ export const createAgentClient = (options: { url: string; token: string }) => {
102
163
  }
103
164
  return response;
104
165
  };
166
+ const call = async (path: string, init: RequestInit = {}) =>
167
+ answered(await request(path, init));
105
168
  const get = async <T>(path: string, schema: z.ZodType<T>) =>
106
169
  schema.parse(await (await call(path)).json());
107
170
  const send = async <T>(
@@ -160,49 +223,64 @@ export const createAgentClient = (options: { url: string; token: string }) => {
160
223
  const compare = (buckets: string[]) =>
161
224
  send("POST", "/releases/compare", { buckets }, comparisonSchema);
162
225
 
226
+ /**
227
+ * The upload body of `release`, built on what the agent already holds. Refuses an agent of
228
+ * another version first.
229
+ */
230
+ const upload = async (
231
+ release: { manifest: ReleaseManifest; files: ReleaseFile[] },
232
+ settings: DeployOptions,
233
+ onProgress: (message: string) => void,
234
+ ) => {
235
+ // Before uploading: an agent of another version, including one from before version checks,
236
+ // would compile the release with scripts this client doesn't expect.
237
+ const agentVersion = (await call("/status")).headers.get(
238
+ agentVersionHeader,
239
+ );
240
+ if (agentVersion !== tsplcVersion) {
241
+ throw new AgentOperationError(
242
+ versionMismatch({
243
+ agent: agentVersion,
244
+ client: tsplcVersion,
245
+ agentUpgrades: upgradesItself(agentVersion),
246
+ }),
247
+ );
248
+ }
249
+ const files = await Promise.all(
250
+ release.files.map(async ({ path, content }) => ({
251
+ path,
252
+ content: await content.bytes(),
253
+ })),
254
+ );
255
+ const digests = files.map(({ path, content }) => ({
256
+ path,
257
+ digest: shortDigest(content),
258
+ }));
259
+ const buckets = bucketDigests(digests);
260
+ return releaseUpload(
261
+ { manifest: release.manifest, options: settings, buckets },
262
+ files,
263
+ await compare(buckets),
264
+ onProgress,
265
+ );
266
+ };
267
+
163
268
  return {
269
+ /** The agent's address, where its dashboard is. */
270
+ url: options.url,
164
271
  status: () => get("/status", statusSchema),
165
272
  interfaces: () => get("/interfaces", z.array(networkInterfaceSchema)),
166
273
  discover: (name: string) =>
167
274
  send("POST", "/discover", { name }, z.array(controllerSchema)),
168
275
  setTarget: (target: Target) => send("PUT", "/target", target, targetSchema),
169
276
  variables: () => get("/variables", z.array(variableSchema)),
277
+ /** Deploys `release` at once, streaming its progress: `POST /deploy`. */
170
278
  deploy: async (
171
279
  release: { manifest: ReleaseManifest; files: ReleaseFile[] },
172
280
  settings: DeployOptions,
173
281
  onProgress: (message: string) => void,
174
282
  ) => {
175
- // Before uploading: an agent of another version, including one from before version checks,
176
- // would compile the release with scripts this client doesn't expect.
177
- const agentVersion = (await call("/status")).headers.get(
178
- agentVersionHeader,
179
- );
180
- if (agentVersion !== tsplcVersion) {
181
- throw new AgentOperationError(
182
- versionMismatch({
183
- agent: agentVersion,
184
- client: tsplcVersion,
185
- agentUpgrades: upgradesItself(agentVersion),
186
- }),
187
- );
188
- }
189
- const files = await Promise.all(
190
- release.files.map(async ({ path, content }) => ({
191
- path,
192
- content: await content.bytes(),
193
- })),
194
- );
195
- const digests = files.map(({ path, content }) => ({
196
- path,
197
- digest: shortDigest(content),
198
- }));
199
- const buckets = bucketDigests(digests);
200
- const body = await releaseUpload(
201
- { manifest: release.manifest, options: settings, buckets },
202
- files,
203
- await compare(buckets),
204
- onProgress,
205
- );
283
+ const body = await upload(release, settings, onProgress);
206
284
  return releaseSchema.parse(
207
285
  await operation(
208
286
  await call("/deploy", { method: "POST", ...body }),
@@ -210,6 +288,96 @@ export const createAgentClient = (options: { url: string; token: string }) => {
210
288
  ),
211
289
  );
212
290
  },
291
+ /**
292
+ * Queues `release` as a deployment the agent runs on its own: `POST /api/deployments`. Null
293
+ * when the agent has no deployments API, so the caller can deploy at once instead.
294
+ */
295
+ queueDeployment: async (
296
+ release: { manifest: ReleaseManifest; files: ReleaseFile[] },
297
+ settings: DeployOptions,
298
+ onProgress: (message: string) => void,
299
+ ) => {
300
+ const body = await upload(release, settings, onProgress);
301
+ const response = await request("/api/deployments", {
302
+ method: "POST",
303
+ ...body,
304
+ });
305
+ if (response.status === 404) {
306
+ return null;
307
+ }
308
+ return deploymentCreatedSchema.parse(
309
+ await (await answered(response)).json(),
310
+ );
311
+ },
312
+ deployments: () => get("/api/deployments", deploymentListSchema),
313
+ /**
314
+ * A deployment's events from after log line `after`, until the agent ends the stream once
315
+ * the deployment finishes. A broken connection throws `AgentUnreachable`.
316
+ */
317
+ deploymentEvents: async function* (
318
+ id: string,
319
+ after: number,
320
+ ): AsyncGenerator<DeploymentEvent> {
321
+ const response = await call(
322
+ `/api/deployments/${encodeURIComponent(id)}/events?after=${after}`,
323
+ { headers: { Accept: "text/event-stream" } },
324
+ );
325
+ if (!response.body) {
326
+ throw new AgentUnreachable("The agent returned no event stream");
327
+ }
328
+ for await (const event of serverSentEvents(response.body)) {
329
+ if (event.name === "record") {
330
+ yield {
331
+ kind: "record",
332
+ record: deploymentRecordSchema.parse(JSON.parse(event.data)),
333
+ };
334
+ } else if (event.name === "log") {
335
+ yield {
336
+ kind: "log",
337
+ line: deploymentLogLineSchema.parse(JSON.parse(event.data)),
338
+ };
339
+ }
340
+ }
341
+ },
342
+ /** Approves a deployment that waits on a person, as a full download when `download`. */
343
+ approve: async (id: string, approval: { download: boolean }) => {
344
+ await call(`/api/deployments/${encodeURIComponent(id)}/approve`, {
345
+ method: "POST",
346
+ headers: { "Content-Type": "application/json" },
347
+ body: JSON.stringify(approval),
348
+ });
349
+ },
350
+ redeploy: (id: string, mode: DeploymentMode) =>
351
+ send(
352
+ "POST",
353
+ `/api/deployments/${encodeURIComponent(id)}/redeploy`,
354
+ { mode },
355
+ deploymentCreatedSchema,
356
+ ),
357
+ rollback: (id: string) =>
358
+ send(
359
+ "POST",
360
+ `/api/deployments/${encodeURIComponent(id)}/rollback`,
361
+ {},
362
+ deploymentCreatedSchema,
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
+ ),
213
381
  login: async (
214
382
  credentials: Credentials | null,
215
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
+ ];
@@ -0,0 +1,118 @@
1
+ import { createRequire } from "node:module";
2
+ import { basename, dirname, resolve } from "node:path";
3
+ import { controllerRestartPath } from "@tsplc/server/plant-agent";
4
+ import { errorMessage } from "../errors";
5
+ import { allows, roles } from "../protocol";
6
+
7
+ /** The pages a browser loads: they hold no data, which they fetch from `/api` as whoever is signed in. */
8
+ const pages = ["/", "/deployments", "/environment", "/audit", "/access"];
9
+
10
+ /** Where the pages' script and stylesheet are served; like the pages, they hold no data. */
11
+ 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>`;
14
+
15
+ /**
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.
19
+ */
20
+ const contract = {
21
+ roles,
22
+ controllerRestartPath,
23
+ permissions: Object.fromEntries(
24
+ roles.map((role) => [
25
+ role,
26
+ Object.fromEntries(
27
+ roles.map((required) => [required, allows(role, required)]),
28
+ ),
29
+ ]),
30
+ ),
31
+ };
32
+
33
+ interface Asset {
34
+ text: string;
35
+ type: string;
36
+ }
37
+
38
+ const bundle = async () => {
39
+ // Resolved through the package, so a published `dist/` bundle finds the shipped sources.
40
+ const sources = resolve(
41
+ dirname(createRequire(import.meta.url).resolve("@tsplc/agent")),
42
+ "../src/dashboard/ui",
43
+ );
44
+ const result = await Bun.build({
45
+ entrypoints: [
46
+ resolve(sources, "main.ts"),
47
+ resolve(sources, "dashboard.css"),
48
+ ],
49
+ target: "browser",
50
+ // Workspace packages resolve to their sources, as they do for the host, so no build is needed first.
51
+ conditions: ["bun"],
52
+ minify: true,
53
+ naming: "[name].[ext]",
54
+ define: { TSPLC_CONTRACT: JSON.stringify(contract) },
55
+ });
56
+ if (!result.success) {
57
+ throw new Error(
58
+ `Bundling the dashboard failed:\n${result.logs.map(String).join("\n")}`,
59
+ );
60
+ }
61
+ const assets = new Map<string, Asset>();
62
+ for (const output of result.outputs) {
63
+ assets.set(basename(output.path), {
64
+ text: await output.text(),
65
+ type: output.type,
66
+ });
67
+ }
68
+ return assets;
69
+ };
70
+
71
+ const isPage = (pathname: string) =>
72
+ pages.some(
73
+ (path) =>
74
+ pathname === path || (path !== "/" && pathname.startsWith(`${path}/`)),
75
+ );
76
+
77
+ /**
78
+ * The agent's dashboard: its pages, answered for any path under them, and their script and
79
+ * stylesheet, bundled on first request and then kept.
80
+ */
81
+ export const createDashboard = () => {
82
+ let assets: Promise<Map<string, Asset>> | undefined;
83
+ return {
84
+ handle: async (request: Request): Promise<Response | undefined> => {
85
+ const { pathname } = new URL(request.url);
86
+ if (request.method !== "GET") {
87
+ return undefined;
88
+ }
89
+ if (isPage(pathname)) {
90
+ return new Response(page, {
91
+ headers: {
92
+ "Content-Type": "text/html; charset=utf-8",
93
+ "Cache-Control": "no-cache",
94
+ },
95
+ });
96
+ }
97
+ if (!pathname.startsWith(dashboardAssets)) {
98
+ return undefined;
99
+ }
100
+ assets ??= bundle();
101
+ try {
102
+ const asset = (await assets).get(
103
+ pathname.slice(dashboardAssets.length),
104
+ );
105
+ if (!asset) {
106
+ return undefined;
107
+ }
108
+ return new Response(asset.text, {
109
+ headers: { "Content-Type": asset.type, "Cache-Control": "no-cache" },
110
+ });
111
+ } catch (error) {
112
+ // A failed bundle is tried again on the next request rather than kept.
113
+ assets = undefined;
114
+ return new Response(errorMessage(error), { status: 500 });
115
+ }
116
+ },
117
+ };
118
+ };