@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.
- package/dist/cli.js +2660 -525
- package/dist/cli.js.map +32 -18
- package/dist/client.js +262 -37
- package/dist/client.js.map +4 -4
- package/dist/index.js +2325 -415
- package/dist/index.js.map +27 -14
- package/package.json +6 -5
- package/src/access.ts +276 -0
- package/src/agent.ts +130 -29
- package/src/audit.ts +64 -0
- package/src/cli.ts +81 -5
- package/src/client.ts +204 -36
- package/src/controller.ts +60 -0
- package/src/dashboard/index.ts +118 -0
- package/src/dashboard/ui/access.ts +192 -0
- package/src/dashboard/ui/actions.ts +192 -0
- package/src/dashboard/ui/api.ts +158 -0
- package/src/dashboard/ui/app.ts +41 -0
- package/src/dashboard/ui/approval.ts +132 -0
- package/src/dashboard/ui/audit.ts +115 -0
- package/src/dashboard/ui/contract.ts +19 -0
- package/src/dashboard/ui/dashboard.css +1332 -0
- package/src/dashboard/ui/deployment.ts +432 -0
- package/src/dashboard/ui/deployments.ts +317 -0
- package/src/dashboard/ui/details.ts +240 -0
- package/src/dashboard/ui/dom.ts +91 -0
- package/src/dashboard/ui/environment.ts +326 -0
- package/src/dashboard/ui/format.ts +118 -0
- package/src/dashboard/ui/logs.ts +127 -0
- package/src/dashboard/ui/main.ts +86 -0
- package/src/dashboard/ui/overlay.ts +146 -0
- package/src/dashboard/ui/shell.ts +192 -0
- package/src/dashboard/ui/source.ts +144 -0
- package/src/deploy.ts +174 -144
- package/src/deployments/health.ts +80 -0
- package/src/deployments/retention.ts +45 -0
- package/src/deployments/routes.ts +273 -0
- package/src/deployments/runner.ts +877 -0
- package/src/deployments/store.ts +233 -0
- package/src/environment.ts +284 -0
- package/src/index.ts +4 -0
- package/src/login.ts +17 -0
- package/src/operations.ts +6 -1
- package/src/protocol.ts +259 -2
- package/src/releases.ts +73 -1
- package/src/routes.ts +52 -0
- package/src/secrets.ts +74 -4
- package/src/server-process.ts +33 -16
- package/src/sessions.ts +58 -0
- package/src/state.ts +2 -0
- package/src/tailscale.ts +112 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tsplc/agent",
|
|
3
|
-
"version": "0.5.
|
|
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.
|
|
46
|
-
"@tsplc/config": "0.5.
|
|
47
|
-
"@tsplc/debug": "0.5.
|
|
48
|
-
"@tsplc/iec": "0.5.
|
|
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
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { readFile, rename, writeFile } from "node:fs/promises";
|
|
4
|
+
import { isIP } from "node:net";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { dashboardHeader } from "@tsplc/debug/api";
|
|
7
|
+
import { controllerRestartPath } from "@tsplc/server/plant-agent";
|
|
8
|
+
import type { AuditLog } from "./audit";
|
|
9
|
+
import { errorMessage } from "./errors";
|
|
10
|
+
import {
|
|
11
|
+
type AccessConfig,
|
|
12
|
+
accessConfigSchema,
|
|
13
|
+
type Identity,
|
|
14
|
+
sessionRequestSchema,
|
|
15
|
+
} from "./protocol";
|
|
16
|
+
import type { ApiRoute } from "./routes";
|
|
17
|
+
import { createSessions } from "./sessions";
|
|
18
|
+
import { peerKind, type Whois } from "./tailscale";
|
|
19
|
+
|
|
20
|
+
/** `access.json` in the state directory `state`. */
|
|
21
|
+
export const accessFile = (state: string) => join(state, "access.json");
|
|
22
|
+
|
|
23
|
+
/** Without `access.json`, no tailnet member has a role. */
|
|
24
|
+
const noAccess: AccessConfig = { roles: {}, tailnetDefault: null };
|
|
25
|
+
|
|
26
|
+
export const readAccessConfig = async (file: string) =>
|
|
27
|
+
existsSync(file)
|
|
28
|
+
? accessConfigSchema.parse(JSON.parse(await readFile(file, "utf8")))
|
|
29
|
+
: noAccess;
|
|
30
|
+
|
|
31
|
+
/** Replaces `access.json` whole, so a reader never sees half of it. */
|
|
32
|
+
export const writeAccessConfig = async (file: string, config: AccessConfig) => {
|
|
33
|
+
await writeFile(`${file}.tmp`, JSON.stringify(config, null, 2));
|
|
34
|
+
await rename(`${file}.tmp`, file);
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
/** Compares digests, so the time taken says nothing about the token, not even its length. */
|
|
38
|
+
const matches = (presented: string, token: string) =>
|
|
39
|
+
timingSafeEqual(
|
|
40
|
+
createHash("sha256").update(presented).digest(),
|
|
41
|
+
createHash("sha256").update(token).digest(),
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
/** Where a request came from, as the HTTP server reports it. */
|
|
45
|
+
export interface Peer {
|
|
46
|
+
address: string;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const refuse = (status: 401 | 403, error: string) =>
|
|
50
|
+
Response.json({ error }, { status });
|
|
51
|
+
const unauthorized = () => refuse(401, "Unauthorized");
|
|
52
|
+
|
|
53
|
+
/** A proxy on the agent's PC would make every request it forwards look local. */
|
|
54
|
+
const forwardingHeaders = [
|
|
55
|
+
"forwarded",
|
|
56
|
+
"x-forwarded-for",
|
|
57
|
+
"tailscale-user-login",
|
|
58
|
+
];
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Whether the request names the agent by an address, a single-label name or a MagicDNS name.
|
|
62
|
+
* Another site that points its own name at the agent (DNS rebinding) names it by that, and gets
|
|
63
|
+
* no identity from where the browser runs.
|
|
64
|
+
*/
|
|
65
|
+
const namesAgentDirectly = (request: Request) => {
|
|
66
|
+
const host = new URL(request.url).hostname.replace(/^\[(.*)\]$/, "$1");
|
|
67
|
+
return (
|
|
68
|
+
isIP(host) !== 0 ||
|
|
69
|
+
!host.includes(".") ||
|
|
70
|
+
host.endsWith(".ts.net") ||
|
|
71
|
+
host === "localhost"
|
|
72
|
+
);
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
/** Anything but `GET` may change something, so another site must not be able to send it. */
|
|
76
|
+
const changes = (request: Request) => request.method !== "GET";
|
|
77
|
+
const fromDashboard = (request: Request) =>
|
|
78
|
+
request.headers.get(dashboardHeader) === "1";
|
|
79
|
+
const crossSite = () =>
|
|
80
|
+
refuse(
|
|
81
|
+
403,
|
|
82
|
+
`A browser's request that changes something needs the ${dashboardHeader}: 1 header`,
|
|
83
|
+
);
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Who a request is from, and the role that gives them. The full token is an admin and the read
|
|
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
|
|
89
|
+
* `/debug`, a request from the agent's own PC is an admin, and one from a tailnet member has the
|
|
90
|
+
* role `access.json` gives their login.
|
|
91
|
+
*/
|
|
92
|
+
export const createAccess = (options: {
|
|
93
|
+
token: string;
|
|
94
|
+
readToken: string | undefined;
|
|
95
|
+
/** The token the agent starts the deployed server with, which may only restart the controller. */
|
|
96
|
+
serverToken: string | null;
|
|
97
|
+
/** `access.json`, read on each tailnet request so `tsplc-agent access` applies at once. */
|
|
98
|
+
file: string;
|
|
99
|
+
whois: Whois;
|
|
100
|
+
audit: AuditLog;
|
|
101
|
+
now: () => number;
|
|
102
|
+
log: (message: string) => void;
|
|
103
|
+
}) => {
|
|
104
|
+
const sessions = createSessions(options.now);
|
|
105
|
+
|
|
106
|
+
const tokenIdentity = (presented: string): Identity | null => {
|
|
107
|
+
if (matches(presented, options.token)) {
|
|
108
|
+
return { login: null, name: "Agent token", role: "admin", via: "token" };
|
|
109
|
+
}
|
|
110
|
+
if (
|
|
111
|
+
options.readToken !== undefined &&
|
|
112
|
+
matches(presented, options.readToken)
|
|
113
|
+
) {
|
|
114
|
+
return {
|
|
115
|
+
login: null,
|
|
116
|
+
name: "Read token",
|
|
117
|
+
role: "viewer",
|
|
118
|
+
via: "token",
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
return null;
|
|
122
|
+
};
|
|
123
|
+
|
|
124
|
+
const serverIdentity: Identity = {
|
|
125
|
+
login: null,
|
|
126
|
+
name: "Line server",
|
|
127
|
+
role: "deployer",
|
|
128
|
+
via: "server",
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const peerIdentity = async (
|
|
132
|
+
request: Request,
|
|
133
|
+
peer: Peer | null,
|
|
134
|
+
): Promise<Identity | null> => {
|
|
135
|
+
if (
|
|
136
|
+
!peer ||
|
|
137
|
+
!namesAgentDirectly(request) ||
|
|
138
|
+
forwardingHeaders.some((name) => request.headers.has(name))
|
|
139
|
+
) {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
const kind = peerKind(peer.address);
|
|
143
|
+
if (kind === "loopback") {
|
|
144
|
+
return { login: null, name: "This PC", role: "admin", via: "local" };
|
|
145
|
+
}
|
|
146
|
+
if (kind !== "tailnet") {
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
const user = await options.whois(peer.address);
|
|
150
|
+
if (!user) {
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
// A hand-edited file that doesn't parse gives no one a role until it is fixed.
|
|
154
|
+
const config = await readAccessConfig(options.file).catch(
|
|
155
|
+
(error: unknown) => {
|
|
156
|
+
options.log(`Can't read ${options.file}: ${errorMessage(error)}`);
|
|
157
|
+
return noAccess;
|
|
158
|
+
},
|
|
159
|
+
);
|
|
160
|
+
const role = config.roles[user.login] ?? config.tailnetDefault;
|
|
161
|
+
return (
|
|
162
|
+
role && { login: user.login, name: user.name, role, via: "tailscale" }
|
|
163
|
+
);
|
|
164
|
+
};
|
|
165
|
+
|
|
166
|
+
/** The request's identity, or the refusal to answer it with. */
|
|
167
|
+
const identify = async (
|
|
168
|
+
request: Request,
|
|
169
|
+
peer: Peer | null,
|
|
170
|
+
): Promise<Identity | Response> => {
|
|
171
|
+
const { searchParams, pathname } = new URL(request.url);
|
|
172
|
+
// EventSource can't send headers, so the debugger also takes `?token=`.
|
|
173
|
+
const presented =
|
|
174
|
+
/^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ??
|
|
175
|
+
(pathname.startsWith("/debug/") ? searchParams.get("token") : null);
|
|
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
|
+
}
|
|
185
|
+
return tokenIdentity(presented) ?? unauthorized();
|
|
186
|
+
}
|
|
187
|
+
// The CLI's routes keep their tokens, but for the status the dashboard shows too.
|
|
188
|
+
const browserRoute =
|
|
189
|
+
pathname.startsWith("/api/") ||
|
|
190
|
+
pathname.startsWith("/debug/") ||
|
|
191
|
+
(request.method === "GET" && pathname === "/status");
|
|
192
|
+
if (!browserRoute) {
|
|
193
|
+
return unauthorized();
|
|
194
|
+
}
|
|
195
|
+
const identity =
|
|
196
|
+
sessions.find(request) ?? (await peerIdentity(request, peer));
|
|
197
|
+
if (!identity) {
|
|
198
|
+
return unauthorized();
|
|
199
|
+
}
|
|
200
|
+
return changes(request) && !fromDashboard(request) ? crossSite() : identity;
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
/** Signs a browser in and out, which needs no identity: the answer, or null for another route. */
|
|
204
|
+
const handle = async (request: Request): Promise<Response | null> => {
|
|
205
|
+
const { pathname } = new URL(request.url);
|
|
206
|
+
if (
|
|
207
|
+
pathname !== "/api/session" ||
|
|
208
|
+
(request.method !== "POST" && request.method !== "DELETE")
|
|
209
|
+
) {
|
|
210
|
+
return null;
|
|
211
|
+
}
|
|
212
|
+
if (!fromDashboard(request)) {
|
|
213
|
+
return crossSite();
|
|
214
|
+
}
|
|
215
|
+
if (request.method === "DELETE") {
|
|
216
|
+
return new Response(null, {
|
|
217
|
+
status: 204,
|
|
218
|
+
headers: { "Set-Cookie": sessions.close(request) },
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
const body = sessionRequestSchema.safeParse(
|
|
222
|
+
await request.json().catch(() => null),
|
|
223
|
+
);
|
|
224
|
+
if (!body.success) {
|
|
225
|
+
return Response.json({ error: "Send { token }" }, { status: 400 });
|
|
226
|
+
}
|
|
227
|
+
const identity = tokenIdentity(body.data.token);
|
|
228
|
+
if (!identity) {
|
|
229
|
+
return unauthorized();
|
|
230
|
+
}
|
|
231
|
+
return Response.json(identity, {
|
|
232
|
+
headers: { "Set-Cookie": sessions.open(identity) },
|
|
233
|
+
});
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
const routes: ApiRoute[] = [
|
|
237
|
+
{
|
|
238
|
+
method: "GET",
|
|
239
|
+
pattern: "/api/session",
|
|
240
|
+
role: "viewer",
|
|
241
|
+
handle: async (_request, { identity }) => Response.json(identity),
|
|
242
|
+
},
|
|
243
|
+
{
|
|
244
|
+
method: "GET",
|
|
245
|
+
pattern: "/api/access",
|
|
246
|
+
role: "admin",
|
|
247
|
+
handle: async () => Response.json(await readAccessConfig(options.file)),
|
|
248
|
+
},
|
|
249
|
+
{
|
|
250
|
+
method: "PUT",
|
|
251
|
+
pattern: "/api/access",
|
|
252
|
+
role: "admin",
|
|
253
|
+
handle: async (request, { identity }) => {
|
|
254
|
+
const config = accessConfigSchema.parse(await request.json());
|
|
255
|
+
const previous = await readAccessConfig(options.file);
|
|
256
|
+
await writeAccessConfig(options.file, config);
|
|
257
|
+
await options.audit.record({
|
|
258
|
+
identity,
|
|
259
|
+
command: "access",
|
|
260
|
+
values: auditedAccess(config),
|
|
261
|
+
previous: auditedAccess(previous),
|
|
262
|
+
error: null,
|
|
263
|
+
});
|
|
264
|
+
return Response.json(config);
|
|
265
|
+
},
|
|
266
|
+
},
|
|
267
|
+
];
|
|
268
|
+
return { identify, handle, routes };
|
|
269
|
+
};
|
|
270
|
+
export type Access = ReturnType<typeof createAccess>;
|
|
271
|
+
|
|
272
|
+
/** Who has which role, as the audit log lists it: each login's role, and the tailnet default. */
|
|
273
|
+
const auditedAccess = (config: AccessConfig) => ({
|
|
274
|
+
...config.roles,
|
|
275
|
+
"(tailnet default)": config.tailnetDefault ?? "none",
|
|
276
|
+
});
|
package/src/agent.ts
CHANGED
|
@@ -1,11 +1,21 @@
|
|
|
1
|
-
import { timingSafeEqual } from "node:crypto";
|
|
2
1
|
import { join } from "node:path";
|
|
3
2
|
import { loginCommandSchema } from "@tsplc/build";
|
|
3
|
+
import { plantAgentEnv } from "@tsplc/server/plant-agent";
|
|
4
4
|
import { z } from "zod";
|
|
5
|
+
import { accessFile, createAccess, type Peer } from "./access";
|
|
6
|
+
import { createAudit } from "./audit";
|
|
5
7
|
import { type CodesysSettings, describeBuilder } from "./codesys";
|
|
8
|
+
import { createControllerRoutes } from "./controller";
|
|
9
|
+
import { createDashboard } from "./dashboard";
|
|
6
10
|
import { createDebugging } from "./debugging";
|
|
7
11
|
import { createDeployments } from "./deploy";
|
|
12
|
+
import { createDeploymentRoutes } from "./deployments/routes";
|
|
8
13
|
import { discoverControllers, networkInterfaces } from "./discovery";
|
|
14
|
+
import {
|
|
15
|
+
createEnvironment,
|
|
16
|
+
environmentFile,
|
|
17
|
+
variablesFile,
|
|
18
|
+
} from "./environment";
|
|
9
19
|
import { AgentError, errorMessage } from "./errors";
|
|
10
20
|
import { type AgentExit, exitSchema } from "./instance";
|
|
11
21
|
import { createLogin } from "./login";
|
|
@@ -13,35 +23,38 @@ import { createOperations } from "./operations";
|
|
|
13
23
|
import {
|
|
14
24
|
type AgentStatus,
|
|
15
25
|
agentVersionHeader,
|
|
26
|
+
allows,
|
|
16
27
|
clientIdentity,
|
|
17
28
|
clientRelease,
|
|
18
29
|
compareRequestSchema,
|
|
19
30
|
credentialsSchema,
|
|
20
31
|
discoverSchema,
|
|
32
|
+
type Identity,
|
|
21
33
|
targetSchema,
|
|
22
34
|
tsplcVersion,
|
|
23
35
|
} from "./protocol";
|
|
24
36
|
import { createReleaseStore, readDeployRequest } from "./releases";
|
|
25
|
-
import {
|
|
37
|
+
import { type ApiRoute, matchRoute } from "./routes";
|
|
38
|
+
import { serverEnvironment, storedCredentials } from "./secrets";
|
|
26
39
|
import { createServerSupervisor } from "./server-process";
|
|
27
40
|
import { openState } from "./state";
|
|
28
|
-
|
|
29
|
-
const matches = (presented: string, token: string) => {
|
|
30
|
-
const actual = Buffer.from(presented);
|
|
31
|
-
const expected = Buffer.from(token);
|
|
32
|
-
return actual.length === expected.length && timingSafeEqual(actual, expected);
|
|
33
|
-
};
|
|
41
|
+
import { createWhois, runCommand } from "./tailscale";
|
|
34
42
|
|
|
35
43
|
export interface AgentOptions {
|
|
36
44
|
/** Releases, the controller's download baseline and the selected target live here. */
|
|
37
45
|
state: string;
|
|
38
46
|
token: string;
|
|
39
|
-
/**
|
|
47
|
+
/** A viewer's: the debugger (`/debug/*`), `GET /status` and the dashboard's reading routes. */
|
|
40
48
|
readToken?: string;
|
|
41
49
|
/** The deployed server's health route; without it a server that stays up 5 s counts as started. */
|
|
42
50
|
serverHealthUrl?: string;
|
|
43
51
|
/** Where a release's `serverTokenEnv` is read from; this process's environment by default. */
|
|
44
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 };
|
|
45
58
|
/** Experimental: downloads without a baseline import their POUs in one PLCopenXML import. */
|
|
46
59
|
bulkImport?: boolean;
|
|
47
60
|
log: (message: string) => void;
|
|
@@ -56,10 +69,23 @@ export interface AgentOptions {
|
|
|
56
69
|
export const createAgent = async (options: AgentOptions) => {
|
|
57
70
|
const { log } = options;
|
|
58
71
|
const state = await openState(options.state);
|
|
72
|
+
const environmentVariables = options.environment ?? { ...process.env };
|
|
59
73
|
const server = createServerSupervisor({
|
|
60
74
|
healthUrl: options.serverHealthUrl,
|
|
61
75
|
record: state.paths.server,
|
|
62
76
|
output: state.paths.serverLog,
|
|
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
|
+
}),
|
|
63
89
|
log,
|
|
64
90
|
});
|
|
65
91
|
const deployed = await state.release();
|
|
@@ -85,19 +111,60 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
85
111
|
readLogin: login.read,
|
|
86
112
|
loginStatus: login.status,
|
|
87
113
|
serverHealthUrl: options.serverHealthUrl,
|
|
88
|
-
environment:
|
|
114
|
+
environment: environmentVariables,
|
|
89
115
|
log,
|
|
90
116
|
});
|
|
91
|
-
const deployments = createDeployments({
|
|
117
|
+
const deployments = await createDeployments({
|
|
92
118
|
state,
|
|
93
119
|
operations,
|
|
94
120
|
codesys,
|
|
95
121
|
server,
|
|
96
122
|
debugging,
|
|
123
|
+
serverHealthUrl: options.serverHealthUrl,
|
|
124
|
+
now: () => new Date(),
|
|
125
|
+
log,
|
|
126
|
+
});
|
|
127
|
+
const audit = createAudit({
|
|
128
|
+
file: state.paths.audit,
|
|
129
|
+
onRecord: (entry) => debugging.record(entry),
|
|
130
|
+
});
|
|
131
|
+
const access = createAccess({
|
|
132
|
+
token: options.token,
|
|
133
|
+
readToken: options.readToken,
|
|
134
|
+
serverToken: options.serverAccess?.token ?? null,
|
|
135
|
+
file: accessFile(options.state),
|
|
136
|
+
whois: createWhois({ run: runCommand, now: Date.now, log }),
|
|
137
|
+
audit,
|
|
138
|
+
now: Date.now,
|
|
139
|
+
log,
|
|
140
|
+
});
|
|
141
|
+
const environment = createEnvironment({
|
|
142
|
+
state,
|
|
143
|
+
server,
|
|
144
|
+
operations,
|
|
145
|
+
audit,
|
|
146
|
+
file: environmentFile(options.state),
|
|
147
|
+
variables: variablesFile(options.state),
|
|
97
148
|
log,
|
|
98
149
|
});
|
|
150
|
+
const dashboard = createDashboard();
|
|
151
|
+
const apiRoutes: ApiRoute[] = [
|
|
152
|
+
...createDeploymentRoutes({ runner: deployments.runner, releases }),
|
|
153
|
+
...access.routes,
|
|
154
|
+
...environment.routes,
|
|
155
|
+
...createControllerRoutes({
|
|
156
|
+
login,
|
|
157
|
+
warm: deployments.restart,
|
|
158
|
+
audit,
|
|
159
|
+
log,
|
|
160
|
+
}),
|
|
161
|
+
...audit.routes,
|
|
162
|
+
];
|
|
99
163
|
|
|
100
|
-
const route = async (
|
|
164
|
+
const route = async (
|
|
165
|
+
request: Request,
|
|
166
|
+
identity: Identity,
|
|
167
|
+
): Promise<Response> => {
|
|
101
168
|
const { pathname } = new URL(request.url);
|
|
102
169
|
const key = `${request.method} ${pathname}`;
|
|
103
170
|
switch (key) {
|
|
@@ -147,6 +214,7 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
147
214
|
case "POST /deploy":
|
|
148
215
|
return deployments.deploy(
|
|
149
216
|
() => readDeployRequest(releases, request),
|
|
217
|
+
identity,
|
|
150
218
|
clientIdentity(request),
|
|
151
219
|
clientRelease(request),
|
|
152
220
|
);
|
|
@@ -204,8 +272,11 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
204
272
|
}
|
|
205
273
|
};
|
|
206
274
|
|
|
207
|
-
const respond = async (
|
|
208
|
-
|
|
275
|
+
const respond = async (
|
|
276
|
+
request: Request,
|
|
277
|
+
peer: Peer | null,
|
|
278
|
+
): Promise<Response> => {
|
|
279
|
+
const { pathname, search } = new URL(request.url);
|
|
209
280
|
const debugPath = pathname.startsWith("/debug/");
|
|
210
281
|
// The UI's relative links need the trailing slash.
|
|
211
282
|
if (pathname === "/debug") {
|
|
@@ -221,24 +292,54 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
221
292
|
) {
|
|
222
293
|
return debugging.handle(request, pathname.slice("/debug".length));
|
|
223
294
|
}
|
|
224
|
-
//
|
|
225
|
-
const
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
const
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
if (
|
|
235
|
-
return
|
|
295
|
+
// The dashboard's pages hold no data; what they show comes from `/api` as whoever is signed in.
|
|
296
|
+
const page = await dashboard.handle(request);
|
|
297
|
+
if (page) {
|
|
298
|
+
return page;
|
|
299
|
+
}
|
|
300
|
+
const signing = await access.handle(request);
|
|
301
|
+
if (signing) {
|
|
302
|
+
return signing;
|
|
303
|
+
}
|
|
304
|
+
const identity = await access.identify(request, peer);
|
|
305
|
+
if (identity instanceof Response) {
|
|
306
|
+
return identity;
|
|
307
|
+
}
|
|
308
|
+
const api = pathname.startsWith("/api/")
|
|
309
|
+
? matchRoute(apiRoutes, request.method, pathname)
|
|
310
|
+
: undefined;
|
|
311
|
+
// The routes before `/api` are the CLI's: a viewer may only read status and the debugger.
|
|
312
|
+
const required = api
|
|
313
|
+
? api.route.role
|
|
314
|
+
: debugPath || (request.method === "GET" && pathname === "/status")
|
|
315
|
+
? "viewer"
|
|
316
|
+
: "admin";
|
|
317
|
+
if (!allows(identity.role, required)) {
|
|
318
|
+
// The CLI's routes answered a read token as if it were none, which its client relies on.
|
|
319
|
+
return api
|
|
320
|
+
? Response.json(
|
|
321
|
+
{ error: `This needs the ${required} role` },
|
|
322
|
+
{ status: 403 },
|
|
323
|
+
)
|
|
324
|
+
: Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
236
325
|
}
|
|
237
326
|
try {
|
|
327
|
+
if (api) {
|
|
328
|
+
return await api.route.handle(request, {
|
|
329
|
+
identity,
|
|
330
|
+
params: api.params,
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
if (pathname.startsWith("/api/")) {
|
|
334
|
+
return Response.json(
|
|
335
|
+
{ error: `No route ${request.method} ${pathname}` },
|
|
336
|
+
{ status: 404 },
|
|
337
|
+
);
|
|
338
|
+
}
|
|
238
339
|
if (debugPath) {
|
|
239
340
|
return await debugging.handle(request, pathname.slice("/debug".length));
|
|
240
341
|
}
|
|
241
|
-
return await route(request);
|
|
342
|
+
return await route(request, identity);
|
|
242
343
|
} catch (error) {
|
|
243
344
|
if (error instanceof AgentError) {
|
|
244
345
|
return Response.json(
|
|
@@ -272,8 +373,8 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
272
373
|
|
|
273
374
|
return {
|
|
274
375
|
/** Answers `request`, naming the agent's tsPLC version so a client can refuse a mismatched agent. */
|
|
275
|
-
fetch: async (request: Request) => {
|
|
276
|
-
const response = await respond(request);
|
|
376
|
+
fetch: async (request: Request, peer: Peer | null = null) => {
|
|
377
|
+
const response = await respond(request, peer);
|
|
277
378
|
// A proxied debugger response's headers are immutable.
|
|
278
379
|
const headers = new Headers(response.headers);
|
|
279
380
|
headers.set(agentVersionHeader, tsplcVersion);
|
package/src/audit.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { appendJsonl, readJsonl } from "./logs";
|
|
3
|
+
import { type Audit, auditSchema, type Identity } from "./protocol";
|
|
4
|
+
import type { ApiRoute } from "./routes";
|
|
5
|
+
|
|
6
|
+
/** How many entries `GET /api/audit` answers without `?limit=`, and at most. */
|
|
7
|
+
export const auditLimits = { default: 100, max: 1000 } as const;
|
|
8
|
+
|
|
9
|
+
const auditQuerySchema = z.object({
|
|
10
|
+
limit: z.coerce
|
|
11
|
+
.number()
|
|
12
|
+
.int()
|
|
13
|
+
.positive()
|
|
14
|
+
.max(auditLimits.max)
|
|
15
|
+
.default(auditLimits.default),
|
|
16
|
+
});
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The agent's `audit.jsonl`: login commands that changed the controller, and the dashboard's
|
|
20
|
+
* changes to access, the environment and the server, by who made them.
|
|
21
|
+
*/
|
|
22
|
+
export const createAudit = (context: {
|
|
23
|
+
file: string;
|
|
24
|
+
/** Called with each entry once it is in the log. */
|
|
25
|
+
onRecord: (entry: Audit) => Promise<void>;
|
|
26
|
+
}) => {
|
|
27
|
+
const record = async (change: {
|
|
28
|
+
identity: Identity;
|
|
29
|
+
/** What was done, such as `environment set API_TOKEN`. */
|
|
30
|
+
command: string;
|
|
31
|
+
values: Audit["values"];
|
|
32
|
+
previous: Audit["previous"] | null;
|
|
33
|
+
error: string | null;
|
|
34
|
+
}) => {
|
|
35
|
+
const entry: Audit = {
|
|
36
|
+
at: new Date().toISOString(),
|
|
37
|
+
command: change.command,
|
|
38
|
+
values: change.values,
|
|
39
|
+
...(change.previous && { previous: change.previous }),
|
|
40
|
+
user: change.identity.login ?? change.identity.name,
|
|
41
|
+
...(change.error !== null && { error: change.error }),
|
|
42
|
+
};
|
|
43
|
+
await appendJsonl(context.file, entry);
|
|
44
|
+
await context.onRecord(entry);
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
const routes: ApiRoute[] = [
|
|
48
|
+
{
|
|
49
|
+
method: "GET",
|
|
50
|
+
pattern: "/api/audit",
|
|
51
|
+
role: "viewer",
|
|
52
|
+
handle: async (request) => {
|
|
53
|
+
const { limit } = auditQuerySchema.parse(
|
|
54
|
+
Object.fromEntries(new URL(request.url).searchParams),
|
|
55
|
+
);
|
|
56
|
+
return Response.json(
|
|
57
|
+
(await readJsonl(context.file, auditSchema, limit)).reverse(),
|
|
58
|
+
);
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
];
|
|
62
|
+
return { record, routes };
|
|
63
|
+
};
|
|
64
|
+
export type AuditLog = ReturnType<typeof createAudit>;
|