@tsplc/agent 0.5.8 → 0.5.10

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 (49) hide show
  1. package/dist/cli.js +2462 -533
  2. package/dist/cli.js.map +30 -17
  3. package/dist/client.js +238 -36
  4. package/dist/client.js.map +4 -4
  5. package/dist/index.js +2162 -416
  6. package/dist/index.js.map +25 -13
  7. package/package.json +5 -5
  8. package/src/access.ts +257 -0
  9. package/src/agent.ts +101 -29
  10. package/src/audit.ts +64 -0
  11. package/src/cli.ts +58 -4
  12. package/src/client.ts +181 -36
  13. package/src/dashboard/index.ts +116 -0
  14. package/src/dashboard/ui/access.ts +192 -0
  15. package/src/dashboard/ui/actions.ts +142 -0
  16. package/src/dashboard/ui/api.ts +147 -0
  17. package/src/dashboard/ui/app.ts +41 -0
  18. package/src/dashboard/ui/approval.ts +132 -0
  19. package/src/dashboard/ui/audit.ts +115 -0
  20. package/src/dashboard/ui/contract.ts +16 -0
  21. package/src/dashboard/ui/dashboard.css +1332 -0
  22. package/src/dashboard/ui/deployment.ts +432 -0
  23. package/src/dashboard/ui/deployments.ts +317 -0
  24. package/src/dashboard/ui/details.ts +240 -0
  25. package/src/dashboard/ui/dom.ts +91 -0
  26. package/src/dashboard/ui/environment.ts +224 -0
  27. package/src/dashboard/ui/format.ts +118 -0
  28. package/src/dashboard/ui/logs.ts +127 -0
  29. package/src/dashboard/ui/main.ts +86 -0
  30. package/src/dashboard/ui/overlay.ts +146 -0
  31. package/src/dashboard/ui/shell.ts +171 -0
  32. package/src/dashboard/ui/source.ts +144 -0
  33. package/src/deploy.ts +138 -144
  34. package/src/deployments/health.ts +80 -0
  35. package/src/deployments/retention.ts +45 -0
  36. package/src/deployments/routes.ts +273 -0
  37. package/src/deployments/runner.ts +877 -0
  38. package/src/deployments/store.ts +233 -0
  39. package/src/environment.ts +205 -0
  40. package/src/index.ts +4 -0
  41. package/src/operations.ts +5 -1
  42. package/src/protocol.ts +218 -2
  43. package/src/releases.ts +73 -1
  44. package/src/routes.ts +52 -0
  45. package/src/secrets.ts +43 -2
  46. package/src/server-process.ts +33 -16
  47. package/src/sessions.ts +58 -0
  48. package/src/state.ts +2 -0
  49. package/src/tailscale.ts +112 -0
@@ -0,0 +1,142 @@
1
+ import type { DeploymentMode, DeploymentRecord } from "../../protocol";
2
+ import { api } from "./api";
3
+ import { type App, attempt, deploymentHref } from "./app";
4
+ import { h } from "./dom";
5
+ import { cancelable, shortId, states } from "./format";
6
+ import { confirm, dialog, type MenuItem, toast } from "./overlay";
7
+
8
+ /** Deploys a deployment's release again, applied at once or reviewed first, then opens the new one. */
9
+ export const redeploy = async (app: App, record: DeploymentRecord) => {
10
+ const mode = await dialog<DeploymentMode>({
11
+ title: "Redeploy",
12
+ body: [
13
+ h(
14
+ "p",
15
+ {},
16
+ "Deploy the release of ",
17
+ h("code", {}, shortId(record.id)),
18
+ " again as a new deployment.",
19
+ ),
20
+ h(
21
+ "p",
22
+ { class: "muted" },
23
+ "Apply runs it as soon as it is its turn. Review checks what an online change would do first, and waits for someone to approve it.",
24
+ ),
25
+ ],
26
+ actions: (close) => [
27
+ h(
28
+ "button",
29
+ { class: "button", onclick: () => close("review") },
30
+ "Review first",
31
+ ),
32
+ h(
33
+ "button",
34
+ { class: "button primary", onclick: () => close("apply") },
35
+ "Redeploy",
36
+ ),
37
+ ],
38
+ });
39
+ if (!mode) {
40
+ return;
41
+ }
42
+ const created = await attempt(() => api.redeploy(record.id, mode), null);
43
+ if (created) {
44
+ app.navigate(deploymentHref(created.id));
45
+ }
46
+ };
47
+
48
+ /** Deploys a deployment's release again as an online change, after a confirmation, then opens the new one. */
49
+ export const rollback = async (app: App, record: DeploymentRecord) => {
50
+ const confirmed = await confirm({
51
+ title: "Roll back to this deployment?",
52
+ body: [
53
+ h(
54
+ "p",
55
+ {},
56
+ "A new deployment applies the release of ",
57
+ h("code", {}, shortId(record.id)),
58
+ ` (${record.release.slice(0, 12)}) to the controller as an online change, and starts its server.`,
59
+ ),
60
+ h(
61
+ "p",
62
+ { class: "muted" },
63
+ "If an online change can't apply it, the deployment waits for approval of a full download rather than stopping the line by itself.",
64
+ ),
65
+ ],
66
+ confirm: "Roll back",
67
+ tone: "primary",
68
+ });
69
+ if (!confirmed) {
70
+ return;
71
+ }
72
+ const created = await attempt(() => api.rollback(record.id), null);
73
+ if (created) {
74
+ app.navigate(deploymentHref(created.id));
75
+ }
76
+ };
77
+
78
+ export const cancel = async (record: DeploymentRecord) => {
79
+ const confirmed = await confirm({
80
+ title: "Cancel this deployment?",
81
+ body: [
82
+ h(
83
+ "p",
84
+ {},
85
+ "The controller is left as it is; nothing of this deployment is applied.",
86
+ ),
87
+ ],
88
+ confirm: "Cancel deployment",
89
+ tone: "danger",
90
+ });
91
+ if (confirmed) {
92
+ await attempt(() => api.cancel(record.id), "Deployment canceled");
93
+ }
94
+ };
95
+
96
+ /** A deployment's actions, as a menu offers them: only the ones the signed-in role may take. */
97
+ export const deploymentMenu = (
98
+ app: App,
99
+ record: DeploymentRecord,
100
+ { current, open }: { current: boolean; open: boolean },
101
+ ): MenuItem[] => {
102
+ const deployer = app.can("deployer");
103
+ const finished = states[record.state].finished;
104
+ const items: MenuItem[] = [];
105
+ if (open) {
106
+ items.push({
107
+ label: "Open",
108
+ run: () => app.navigate(deploymentHref(record.id)),
109
+ });
110
+ }
111
+ if (deployer) {
112
+ items.push(
113
+ {
114
+ label: "Redeploy…",
115
+ run: () => void redeploy(app, record),
116
+ disabled: !finished,
117
+ },
118
+ {
119
+ label: "Rollback to this…",
120
+ run: () => void rollback(app, record),
121
+ // Only a release that once ran healthy, and not the one running now.
122
+ disabled: record.state !== "ready" || current,
123
+ },
124
+ );
125
+ if (cancelable(record.state)) {
126
+ items.push({
127
+ label: "Cancel…",
128
+ run: () => void cancel(record),
129
+ tone: "danger",
130
+ });
131
+ }
132
+ }
133
+ items.push("separator", {
134
+ label: "Copy id",
135
+ run: () =>
136
+ void navigator.clipboard.writeText(record.id).then(
137
+ () => toast("Copied the deployment id", "ok"),
138
+ () => toast("The browser refused the clipboard", "error"),
139
+ ),
140
+ });
141
+ return items;
142
+ };
@@ -0,0 +1,147 @@
1
+ import type { z } from "zod";
2
+ import type {
3
+ AccessConfig,
4
+ AgentStatus,
5
+ Audit,
6
+ DeploymentLogLine,
7
+ DeploymentMode,
8
+ DeploymentRecord,
9
+ deploymentCreatedSchema,
10
+ deploymentListSchema,
11
+ deploymentSourceSchema,
12
+ environmentEntrySchema,
13
+ Identity,
14
+ } from "../../protocol";
15
+
16
+ // The answers come from the agent that served this page, built from the same sources, so they are
17
+ // trusted: protocol.ts can't be bundled for a browser to parse them, since it loads @tsplc/build.
18
+
19
+ export type DeploymentList = z.infer<typeof deploymentListSchema>;
20
+ export type DeploymentCreated = z.infer<typeof deploymentCreatedSchema>;
21
+ export type EnvironmentEntry = z.infer<typeof environmentEntrySchema>;
22
+
23
+ export type SourceFile = z.infer<
24
+ typeof deploymentSourceSchema
25
+ >["files"][number];
26
+
27
+ /** A refused or failed request, with the agent's message. */
28
+ export class ApiError extends Error {
29
+ constructor(
30
+ readonly status: number,
31
+ message: string,
32
+ ) {
33
+ super(message);
34
+ }
35
+ }
36
+
37
+ const failure = async (response: Response) => {
38
+ const text = await response.text();
39
+ try {
40
+ const body: unknown = JSON.parse(text);
41
+ if (
42
+ typeof body === "object" &&
43
+ body !== null &&
44
+ "error" in body &&
45
+ typeof body.error === "string"
46
+ ) {
47
+ return new ApiError(response.status, body.error);
48
+ }
49
+ } catch {
50
+ // Not JSON: the text is the message.
51
+ }
52
+ return new ApiError(
53
+ response.status,
54
+ text || `${response.status} ${response.statusText}`,
55
+ );
56
+ };
57
+
58
+ let version: string | null = null;
59
+
60
+ /** The tsPLC version of the agent, as its last answer named it. */
61
+ export const agentVersion = () => version;
62
+
63
+ const call = async (
64
+ method: "GET" | "POST" | "PUT" | "DELETE",
65
+ path: string,
66
+ body: { json: unknown } | null,
67
+ ) => {
68
+ const response = await fetch(path, {
69
+ method,
70
+ credentials: "same-origin",
71
+ // A signed-in browser must mark what it changes, so another site can't make it send one.
72
+ headers: {
73
+ ...(method !== "GET" && { "x-tsplc-dashboard": "1" }),
74
+ ...(body && { "Content-Type": "application/json" }),
75
+ },
76
+ body: body ? JSON.stringify(body.json) : null,
77
+ });
78
+ version = response.headers.get("x-tsplc-agent-version") ?? version;
79
+ if (!response.ok) {
80
+ throw await failure(response);
81
+ }
82
+ return response;
83
+ };
84
+
85
+ const get = async (path: string) => (await call("GET", path, null)).json();
86
+ /** A change's answer, which some routes leave empty. */
87
+ const send = async (
88
+ method: "POST" | "PUT" | "DELETE",
89
+ path: string,
90
+ json: unknown,
91
+ ) => {
92
+ const text = await (
93
+ await call(method, path, json === null ? null : { json })
94
+ ).text();
95
+ return text ? JSON.parse(text) : null;
96
+ };
97
+
98
+ const deploymentPath = (id: string) =>
99
+ `/api/deployments/${encodeURIComponent(id)}`;
100
+
101
+ export const api = {
102
+ session: (): Promise<Identity> => get("/api/session"),
103
+ signIn: (token: string): Promise<unknown> =>
104
+ send("POST", "/api/session", { token }),
105
+ signOut: (): Promise<unknown> => send("DELETE", "/api/session", null),
106
+ status: (): Promise<AgentStatus> => get("/status"),
107
+
108
+ deployments: (): Promise<DeploymentList> => get("/api/deployments"),
109
+ deployment: (id: string): Promise<DeploymentRecord> =>
110
+ get(deploymentPath(id)),
111
+ logs: async (id: string, after: number): Promise<DeploymentLogLine[]> =>
112
+ (await get(`${deploymentPath(id)}/logs?after=${after}`)).lines,
113
+ approve: (id: string, download: boolean): Promise<DeploymentRecord> =>
114
+ send("POST", `${deploymentPath(id)}/approve`, { download }),
115
+ cancel: (id: string): Promise<DeploymentRecord> =>
116
+ send("POST", `${deploymentPath(id)}/cancel`, null),
117
+ redeploy: (id: string, mode: DeploymentMode): Promise<DeploymentCreated> =>
118
+ send("POST", `${deploymentPath(id)}/redeploy`, { mode }),
119
+ rollback: (id: string): Promise<DeploymentCreated> =>
120
+ send("POST", `${deploymentPath(id)}/rollback`, null),
121
+ source: async (id: string): Promise<SourceFile[]> =>
122
+ (await get(`${deploymentPath(id)}/source`)).files,
123
+ sourceFile: async (id: string, path: string) =>
124
+ (
125
+ await call(
126
+ "GET",
127
+ `${deploymentPath(id)}/source/${path.split("/").map(encodeURIComponent).join("/")}`,
128
+ null,
129
+ )
130
+ ).text(),
131
+ /** The URL of a deployment's live events, from the log line after `after`. */
132
+ eventsUrl: (id: string, after: number) =>
133
+ `${deploymentPath(id)}/events?after=${after}`,
134
+
135
+ environment: (): Promise<EnvironmentEntry[]> => get("/api/environment"),
136
+ setEnvironment: (name: string, value: string): Promise<unknown> =>
137
+ send("PUT", `/api/environment/${encodeURIComponent(name)}`, { value }),
138
+ deleteEnvironment: (name: string): Promise<unknown> =>
139
+ send("DELETE", `/api/environment/${encodeURIComponent(name)}`, null),
140
+ restartServer: (): Promise<unknown> =>
141
+ send("POST", "/api/server/restart", null),
142
+
143
+ audit: (limit: number): Promise<Audit[]> => get(`/api/audit?limit=${limit}`),
144
+ access: (): Promise<AccessConfig> => get("/api/access"),
145
+ saveAccess: (access: AccessConfig): Promise<AccessConfig> =>
146
+ send("PUT", "/api/access", access),
147
+ };
@@ -0,0 +1,41 @@
1
+ import { errorMessage } from "../../errors";
2
+ import type { Identity, Role } from "../../protocol";
3
+ import { allows } from "./contract";
4
+ import { toast } from "./overlay";
5
+
6
+ /** What every page is given: who is signed in, and how to move between pages. */
7
+ export interface App {
8
+ identity: Identity;
9
+ /** Whether the signed-in role includes `required`. */
10
+ can(required: Role): boolean;
11
+ navigate(path: string): void;
12
+ }
13
+
14
+ export const createApp = (
15
+ identity: Identity,
16
+ navigate: (path: string) => void,
17
+ ): App => ({
18
+ identity,
19
+ can: (required) => allows(identity.role, required),
20
+ navigate,
21
+ });
22
+
23
+ /** Runs a change, telling the user how it went: `done` on success, the agent's message on failure. */
24
+ export const attempt = async <T>(
25
+ run: () => Promise<T>,
26
+ done: string | null,
27
+ ): Promise<T | null> => {
28
+ try {
29
+ const result = await run();
30
+ if (done) {
31
+ toast(done, "ok");
32
+ }
33
+ return result;
34
+ } catch (error) {
35
+ toast(errorMessage(error), "error");
36
+ return null;
37
+ }
38
+ };
39
+
40
+ export const deploymentHref = (id: string, tab = "") =>
41
+ `/deployments/${encodeURIComponent(id)}${tab ? `/${tab}` : ""}`;
@@ -0,0 +1,132 @@
1
+ import type { DeploymentRecord } from "../../protocol";
2
+ import { cancel } from "./actions";
3
+ import { api } from "./api";
4
+ import { type App, attempt } from "./app";
5
+ import { h } from "./dom";
6
+
7
+ /**
8
+ * What a deployment waiting in `awaitingApproval` asks of a deployer. A full download stops the
9
+ * line, so approving one takes an explicit acknowledgement first.
10
+ */
11
+ export const approvalBanner = (
12
+ app: App,
13
+ record: DeploymentRecord,
14
+ onChanged: () => void,
15
+ ) => {
16
+ const { approval } = record;
17
+ if (record.state !== "awaitingApproval" || !approval) {
18
+ return null;
19
+ }
20
+ const deployer = app.can("deployer");
21
+ const cancelButton = h(
22
+ "button",
23
+ {
24
+ class: "button",
25
+ onclick: () => void cancel(record).then(onChanged),
26
+ },
27
+ "Cancel deployment",
28
+ );
29
+ if (approval.reason === "review") {
30
+ return h(
31
+ "section",
32
+ { class: "banner t-waiting" },
33
+ h(
34
+ "div",
35
+ { class: "banner-text" },
36
+ h("h3", {}, "Waiting for review"),
37
+ h("p", {}, approval.message),
38
+ h(
39
+ "p",
40
+ { class: "muted" },
41
+ record.findings.length
42
+ ? `The online-change check found ${record.findings.length} ${record.findings.length === 1 ? "thing" : "things"} to look at: see Changes.`
43
+ : "The online-change check found nothing to report.",
44
+ ),
45
+ ),
46
+ deployer
47
+ ? h(
48
+ "div",
49
+ { class: "banner-actions" },
50
+ cancelButton,
51
+ h(
52
+ "button",
53
+ {
54
+ class: "button primary",
55
+ onclick: () =>
56
+ void attempt(
57
+ () => api.approve(record.id, false),
58
+ "Approved: the deployment applies now",
59
+ ).then(onChanged),
60
+ },
61
+ "Approve and apply",
62
+ ),
63
+ )
64
+ : h("p", { class: "muted" }, "A deployer must approve it."),
65
+ );
66
+ }
67
+ const refusals = record.findings.filter((finding) => finding.refuses);
68
+ const acknowledge = h("input", { type: "checkbox" });
69
+ const approve = h(
70
+ "button",
71
+ {
72
+ class: "button danger",
73
+ disabled: true,
74
+ onclick: () =>
75
+ void attempt(
76
+ () => api.approve(record.id, true),
77
+ "Approved: the full download starts now",
78
+ ).then(onChanged),
79
+ },
80
+ "Approve full download",
81
+ );
82
+ acknowledge.addEventListener("change", () => {
83
+ approve.disabled = !acknowledge.checked;
84
+ });
85
+ return h(
86
+ "section",
87
+ { class: "banner t-error" },
88
+ h(
89
+ "div",
90
+ { class: "banner-text" },
91
+ h("h3", {}, "A full download stops the line"),
92
+ h("p", {}, approval.message),
93
+ h(
94
+ "p",
95
+ {},
96
+ "An online change can't apply this release. A full download stops the PLC application, and the line with it, until the download has finished and the application runs again.",
97
+ ),
98
+ refusals.length
99
+ ? h(
100
+ "ul",
101
+ { class: "refusals" },
102
+ ...refusals.map((finding) =>
103
+ h(
104
+ "li",
105
+ {},
106
+ h(
107
+ "span",
108
+ { class: "mono" },
109
+ finding.variable
110
+ ? `${finding.object}.${finding.variable}`
111
+ : finding.object,
112
+ ),
113
+ ": ",
114
+ finding.advice,
115
+ ),
116
+ ),
117
+ )
118
+ : null,
119
+ deployer
120
+ ? h(
121
+ "label",
122
+ { class: "check acknowledge" },
123
+ acknowledge,
124
+ "I understand that approving stops the line while the controller downloads.",
125
+ )
126
+ : null,
127
+ ),
128
+ deployer
129
+ ? h("div", { class: "banner-actions" }, cancelButton, approve)
130
+ : h("p", { class: "muted" }, "A deployer must approve it."),
131
+ );
132
+ };
@@ -0,0 +1,115 @@
1
+ import { errorMessage } from "../../errors";
2
+ import type { Audit } from "../../protocol";
3
+ import { api } from "./api";
4
+ import type { App } from "./app";
5
+ import { empty, fill, h, pageHeader, type View } from "./dom";
6
+ import { formatAgo, formatTimestamp } from "./format";
7
+
8
+ const limits = [100, 500, 2000];
9
+
10
+ const values = (entries: Record<string, string>) => {
11
+ const pairs = Object.entries(entries);
12
+ if (!pairs.length) {
13
+ return h("span", { class: "muted" }, "—");
14
+ }
15
+ return h(
16
+ "div",
17
+ { class: "values" },
18
+ ...pairs.map(([expression, value]) =>
19
+ h(
20
+ "div",
21
+ { class: "mono" },
22
+ expression,
23
+ value ? h("span", { class: "muted" }, ` = ${value}`) : null,
24
+ ),
25
+ ),
26
+ );
27
+ };
28
+
29
+ const row = (entry: Audit, now: number) =>
30
+ h(
31
+ "tr",
32
+ { class: entry.error ? "failed" : "" },
33
+ h(
34
+ "td",
35
+ { class: "nowrap", title: formatTimestamp(entry.at) },
36
+ formatAgo(entry.at, now),
37
+ ),
38
+ h("td", { class: "mono nowrap" }, entry.command),
39
+ h("td", {}, values(entry.values)),
40
+ h(
41
+ "td",
42
+ {},
43
+ entry.previous
44
+ ? values(entry.previous)
45
+ : h("span", { class: "muted" }, "—"),
46
+ ),
47
+ h(
48
+ "td",
49
+ { class: "nowrap" },
50
+ [entry.user, entry.host].filter(Boolean).join("@") || "—",
51
+ ),
52
+ h("td", { class: "mono nowrap" }, entry.release?.slice(0, 12) ?? "—"),
53
+ h("td", { class: "error-text" }, entry.error ?? ""),
54
+ );
55
+
56
+ /** What was changed on the controller through the agent's login, newest first. */
57
+ export const auditView = (_app: App): View => {
58
+ const limit = h(
59
+ "select",
60
+ { class: "input", "aria-label": "Entries" },
61
+ ...limits.map((value) => h("option", { value }, `Last ${value}`)),
62
+ );
63
+ const holder = h("div", {}, empty("Loading the audit log…"));
64
+
65
+ const load = async () => {
66
+ try {
67
+ const entries = await api.audit(Number(limit.value));
68
+ const now = Date.now();
69
+ fill(
70
+ holder,
71
+ entries.length
72
+ ? h(
73
+ "table",
74
+ { class: "table" },
75
+ h(
76
+ "thead",
77
+ {},
78
+ h(
79
+ "tr",
80
+ {},
81
+ ...[
82
+ "When",
83
+ "Command",
84
+ "Values",
85
+ "Before",
86
+ "By",
87
+ "Release",
88
+ "Error",
89
+ ].map((label) => h("th", {}, label)),
90
+ ),
91
+ ),
92
+ h("tbody", {}, ...entries.map((entry) => row(entry, now))),
93
+ )
94
+ : empty("Nothing has been written or forced through the agent yet."),
95
+ );
96
+ } catch (error) {
97
+ fill(holder, h("p", { class: "error-text" }, errorMessage(error)));
98
+ }
99
+ };
100
+ limit.addEventListener("change", () => void load());
101
+ void load();
102
+
103
+ return {
104
+ element: h(
105
+ "div",
106
+ { class: "page" },
107
+ pageHeader(
108
+ "Audit",
109
+ "Writes, forces and resets through the agent's login, newest first.",
110
+ limit,
111
+ ),
112
+ holder,
113
+ ),
114
+ };
115
+ };
@@ -0,0 +1,16 @@
1
+ import type { Role, roles } from "../../protocol";
2
+
3
+ /**
4
+ * Put into the bundle by `createDashboard`, from protocol.ts: the bundle can't import protocol.ts,
5
+ * whose other schemas load the agent's Node-only packages.
6
+ */
7
+ declare const TSPLC_CONTRACT: {
8
+ roles: typeof roles;
9
+ permissions: Readonly<Record<Role, Readonly<Record<Role, boolean>>>>;
10
+ };
11
+
12
+ export const roleNames = TSPLC_CONTRACT.roles;
13
+
14
+ /** Whether `role` includes `required`, as protocol.ts's `allows` answered it. */
15
+ export const allows = (role: Role, required: Role) =>
16
+ TSPLC_CONTRACT.permissions[role][required];