@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.
- package/dist/cli.js +2462 -533
- package/dist/cli.js.map +30 -17
- package/dist/client.js +238 -36
- package/dist/client.js.map +4 -4
- package/dist/index.js +2162 -416
- package/dist/index.js.map +25 -13
- package/package.json +5 -5
- package/src/access.ts +257 -0
- package/src/agent.ts +101 -29
- package/src/audit.ts +64 -0
- package/src/cli.ts +58 -4
- package/src/client.ts +181 -36
- package/src/dashboard/index.ts +116 -0
- package/src/dashboard/ui/access.ts +192 -0
- package/src/dashboard/ui/actions.ts +142 -0
- package/src/dashboard/ui/api.ts +147 -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 +16 -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 +224 -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 +171 -0
- package/src/dashboard/ui/source.ts +144 -0
- package/src/deploy.ts +138 -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 +205 -0
- package/src/index.ts +4 -0
- package/src/operations.ts +5 -1
- package/src/protocol.ts +218 -2
- package/src/releases.ts +73 -1
- package/src/routes.ts +52 -0
- package/src/secrets.ts +43 -2
- 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.10",
|
|
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,10 @@
|
|
|
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.10",
|
|
46
|
+
"@tsplc/config": "0.5.10",
|
|
47
|
+
"@tsplc/debug": "0.5.10",
|
|
48
|
+
"@tsplc/iec": "0.5.10",
|
|
49
49
|
"zod": "4.3.6"
|
|
50
50
|
},
|
|
51
51
|
"bin": {
|
package/src/access.ts
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
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 type { AuditLog } from "./audit";
|
|
8
|
+
import { errorMessage } from "./errors";
|
|
9
|
+
import {
|
|
10
|
+
type AccessConfig,
|
|
11
|
+
accessConfigSchema,
|
|
12
|
+
type Identity,
|
|
13
|
+
sessionRequestSchema,
|
|
14
|
+
} from "./protocol";
|
|
15
|
+
import type { ApiRoute } from "./routes";
|
|
16
|
+
import { createSessions } from "./sessions";
|
|
17
|
+
import { peerKind, type Whois } from "./tailscale";
|
|
18
|
+
|
|
19
|
+
/** `access.json` in the state directory `state`. */
|
|
20
|
+
export const accessFile = (state: string) => join(state, "access.json");
|
|
21
|
+
|
|
22
|
+
/** Without `access.json`, no tailnet member has a role. */
|
|
23
|
+
const noAccess: AccessConfig = { roles: {}, tailnetDefault: null };
|
|
24
|
+
|
|
25
|
+
export const readAccessConfig = async (file: string) =>
|
|
26
|
+
existsSync(file)
|
|
27
|
+
? accessConfigSchema.parse(JSON.parse(await readFile(file, "utf8")))
|
|
28
|
+
: noAccess;
|
|
29
|
+
|
|
30
|
+
/** Replaces `access.json` whole, so a reader never sees half of it. */
|
|
31
|
+
export const writeAccessConfig = async (file: string, config: AccessConfig) => {
|
|
32
|
+
await writeFile(`${file}.tmp`, JSON.stringify(config, null, 2));
|
|
33
|
+
await rename(`${file}.tmp`, file);
|
|
34
|
+
};
|
|
35
|
+
|
|
36
|
+
/** Compares digests, so the time taken says nothing about the token, not even its length. */
|
|
37
|
+
const matches = (presented: string, token: string) =>
|
|
38
|
+
timingSafeEqual(
|
|
39
|
+
createHash("sha256").update(presented).digest(),
|
|
40
|
+
createHash("sha256").update(token).digest(),
|
|
41
|
+
);
|
|
42
|
+
|
|
43
|
+
/** Where a request came from, as the HTTP server reports it. */
|
|
44
|
+
export interface Peer {
|
|
45
|
+
address: string;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const refuse = (status: 401 | 403, error: string) =>
|
|
49
|
+
Response.json({ error }, { status });
|
|
50
|
+
const unauthorized = () => refuse(401, "Unauthorized");
|
|
51
|
+
|
|
52
|
+
/** A proxy on the agent's PC would make every request it forwards look local. */
|
|
53
|
+
const forwardingHeaders = [
|
|
54
|
+
"forwarded",
|
|
55
|
+
"x-forwarded-for",
|
|
56
|
+
"tailscale-user-login",
|
|
57
|
+
];
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Whether the request names the agent by an address, a single-label name or a MagicDNS name.
|
|
61
|
+
* Another site that points its own name at the agent (DNS rebinding) names it by that, and gets
|
|
62
|
+
* no identity from where the browser runs.
|
|
63
|
+
*/
|
|
64
|
+
const namesAgentDirectly = (request: Request) => {
|
|
65
|
+
const host = new URL(request.url).hostname.replace(/^\[(.*)\]$/, "$1");
|
|
66
|
+
return (
|
|
67
|
+
isIP(host) !== 0 ||
|
|
68
|
+
!host.includes(".") ||
|
|
69
|
+
host.endsWith(".ts.net") ||
|
|
70
|
+
host === "localhost"
|
|
71
|
+
);
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
/** Anything but `GET` may change something, so another site must not be able to send it. */
|
|
75
|
+
const changes = (request: Request) => request.method !== "GET";
|
|
76
|
+
const fromDashboard = (request: Request) =>
|
|
77
|
+
request.headers.get(dashboardHeader) === "1";
|
|
78
|
+
const crossSite = () =>
|
|
79
|
+
refuse(
|
|
80
|
+
403,
|
|
81
|
+
`A browser's request that changes something needs the ${dashboardHeader}: 1 header`,
|
|
82
|
+
);
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* 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
|
+
* `/debug`, a request from the agent's own PC is an admin, and one from a tailnet member has the
|
|
88
|
+
* role `access.json` gives their login.
|
|
89
|
+
*/
|
|
90
|
+
export const createAccess = (options: {
|
|
91
|
+
token: string;
|
|
92
|
+
readToken: string | undefined;
|
|
93
|
+
/** `access.json`, read on each tailnet request so `tsplc-agent access` applies at once. */
|
|
94
|
+
file: string;
|
|
95
|
+
whois: Whois;
|
|
96
|
+
audit: AuditLog;
|
|
97
|
+
now: () => number;
|
|
98
|
+
log: (message: string) => void;
|
|
99
|
+
}) => {
|
|
100
|
+
const sessions = createSessions(options.now);
|
|
101
|
+
|
|
102
|
+
const tokenIdentity = (presented: string): Identity | null => {
|
|
103
|
+
if (matches(presented, options.token)) {
|
|
104
|
+
return { login: null, name: "Agent token", role: "admin", via: "token" };
|
|
105
|
+
}
|
|
106
|
+
if (
|
|
107
|
+
options.readToken !== undefined &&
|
|
108
|
+
matches(presented, options.readToken)
|
|
109
|
+
) {
|
|
110
|
+
return {
|
|
111
|
+
login: null,
|
|
112
|
+
name: "Read token",
|
|
113
|
+
role: "viewer",
|
|
114
|
+
via: "token",
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
return null;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const peerIdentity = async (
|
|
121
|
+
request: Request,
|
|
122
|
+
peer: Peer | null,
|
|
123
|
+
): Promise<Identity | null> => {
|
|
124
|
+
if (
|
|
125
|
+
!peer ||
|
|
126
|
+
!namesAgentDirectly(request) ||
|
|
127
|
+
forwardingHeaders.some((name) => request.headers.has(name))
|
|
128
|
+
) {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
const kind = peerKind(peer.address);
|
|
132
|
+
if (kind === "loopback") {
|
|
133
|
+
return { login: null, name: "This PC", role: "admin", via: "local" };
|
|
134
|
+
}
|
|
135
|
+
if (kind !== "tailnet") {
|
|
136
|
+
return null;
|
|
137
|
+
}
|
|
138
|
+
const user = await options.whois(peer.address);
|
|
139
|
+
if (!user) {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
// A hand-edited file that doesn't parse gives no one a role until it is fixed.
|
|
143
|
+
const config = await readAccessConfig(options.file).catch(
|
|
144
|
+
(error: unknown) => {
|
|
145
|
+
options.log(`Can't read ${options.file}: ${errorMessage(error)}`);
|
|
146
|
+
return noAccess;
|
|
147
|
+
},
|
|
148
|
+
);
|
|
149
|
+
const role = config.roles[user.login] ?? config.tailnetDefault;
|
|
150
|
+
return (
|
|
151
|
+
role && { login: user.login, name: user.name, role, via: "tailscale" }
|
|
152
|
+
);
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
/** The request's identity, or the refusal to answer it with. */
|
|
156
|
+
const identify = async (
|
|
157
|
+
request: Request,
|
|
158
|
+
peer: Peer | null,
|
|
159
|
+
): Promise<Identity | Response> => {
|
|
160
|
+
const { searchParams, pathname } = new URL(request.url);
|
|
161
|
+
// EventSource can't send headers, so the debugger also takes `?token=`.
|
|
162
|
+
const presented =
|
|
163
|
+
/^Bearer (.+)$/.exec(request.headers.get("authorization") ?? "")?.[1] ??
|
|
164
|
+
(pathname.startsWith("/debug/") ? searchParams.get("token") : null);
|
|
165
|
+
if (presented !== null) {
|
|
166
|
+
return tokenIdentity(presented) ?? unauthorized();
|
|
167
|
+
}
|
|
168
|
+
// The CLI's routes keep their tokens, but for the status the dashboard shows too.
|
|
169
|
+
const browserRoute =
|
|
170
|
+
pathname.startsWith("/api/") ||
|
|
171
|
+
pathname.startsWith("/debug/") ||
|
|
172
|
+
(request.method === "GET" && pathname === "/status");
|
|
173
|
+
if (!browserRoute) {
|
|
174
|
+
return unauthorized();
|
|
175
|
+
}
|
|
176
|
+
const identity =
|
|
177
|
+
sessions.find(request) ?? (await peerIdentity(request, peer));
|
|
178
|
+
if (!identity) {
|
|
179
|
+
return unauthorized();
|
|
180
|
+
}
|
|
181
|
+
return changes(request) && !fromDashboard(request) ? crossSite() : identity;
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
/** Signs a browser in and out, which needs no identity: the answer, or null for another route. */
|
|
185
|
+
const handle = async (request: Request): Promise<Response | null> => {
|
|
186
|
+
const { pathname } = new URL(request.url);
|
|
187
|
+
if (
|
|
188
|
+
pathname !== "/api/session" ||
|
|
189
|
+
(request.method !== "POST" && request.method !== "DELETE")
|
|
190
|
+
) {
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
if (!fromDashboard(request)) {
|
|
194
|
+
return crossSite();
|
|
195
|
+
}
|
|
196
|
+
if (request.method === "DELETE") {
|
|
197
|
+
return new Response(null, {
|
|
198
|
+
status: 204,
|
|
199
|
+
headers: { "Set-Cookie": sessions.close(request) },
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
const body = sessionRequestSchema.safeParse(
|
|
203
|
+
await request.json().catch(() => null),
|
|
204
|
+
);
|
|
205
|
+
if (!body.success) {
|
|
206
|
+
return Response.json({ error: "Send { token }" }, { status: 400 });
|
|
207
|
+
}
|
|
208
|
+
const identity = tokenIdentity(body.data.token);
|
|
209
|
+
if (!identity) {
|
|
210
|
+
return unauthorized();
|
|
211
|
+
}
|
|
212
|
+
return Response.json(identity, {
|
|
213
|
+
headers: { "Set-Cookie": sessions.open(identity) },
|
|
214
|
+
});
|
|
215
|
+
};
|
|
216
|
+
|
|
217
|
+
const routes: ApiRoute[] = [
|
|
218
|
+
{
|
|
219
|
+
method: "GET",
|
|
220
|
+
pattern: "/api/session",
|
|
221
|
+
role: "viewer",
|
|
222
|
+
handle: async (_request, { identity }) => Response.json(identity),
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
method: "GET",
|
|
226
|
+
pattern: "/api/access",
|
|
227
|
+
role: "admin",
|
|
228
|
+
handle: async () => Response.json(await readAccessConfig(options.file)),
|
|
229
|
+
},
|
|
230
|
+
{
|
|
231
|
+
method: "PUT",
|
|
232
|
+
pattern: "/api/access",
|
|
233
|
+
role: "admin",
|
|
234
|
+
handle: async (request, { identity }) => {
|
|
235
|
+
const config = accessConfigSchema.parse(await request.json());
|
|
236
|
+
const previous = await readAccessConfig(options.file);
|
|
237
|
+
await writeAccessConfig(options.file, config);
|
|
238
|
+
await options.audit.record({
|
|
239
|
+
identity,
|
|
240
|
+
command: "access",
|
|
241
|
+
values: auditedAccess(config),
|
|
242
|
+
previous: auditedAccess(previous),
|
|
243
|
+
error: null,
|
|
244
|
+
});
|
|
245
|
+
return Response.json(config);
|
|
246
|
+
},
|
|
247
|
+
},
|
|
248
|
+
];
|
|
249
|
+
return { identify, handle, routes };
|
|
250
|
+
};
|
|
251
|
+
export type Access = ReturnType<typeof createAccess>;
|
|
252
|
+
|
|
253
|
+
/** Who has which role, as the audit log lists it: each login's role, and the tailnet default. */
|
|
254
|
+
const auditedAccess = (config: AccessConfig) => ({
|
|
255
|
+
...config.roles,
|
|
256
|
+
"(tailnet default)": config.tailnetDefault ?? "none",
|
|
257
|
+
});
|
package/src/agent.ts
CHANGED
|
@@ -1,11 +1,15 @@
|
|
|
1
|
-
import { timingSafeEqual } from "node:crypto";
|
|
2
1
|
import { join } from "node:path";
|
|
3
2
|
import { loginCommandSchema } from "@tsplc/build";
|
|
4
3
|
import { z } from "zod";
|
|
4
|
+
import { accessFile, createAccess, type Peer } from "./access";
|
|
5
|
+
import { createAudit } from "./audit";
|
|
5
6
|
import { type CodesysSettings, describeBuilder } from "./codesys";
|
|
7
|
+
import { createDashboard } from "./dashboard";
|
|
6
8
|
import { createDebugging } from "./debugging";
|
|
7
9
|
import { createDeployments } from "./deploy";
|
|
10
|
+
import { createDeploymentRoutes } from "./deployments/routes";
|
|
8
11
|
import { discoverControllers, networkInterfaces } from "./discovery";
|
|
12
|
+
import { createEnvironment, environmentFile } from "./environment";
|
|
9
13
|
import { AgentError, errorMessage } from "./errors";
|
|
10
14
|
import { type AgentExit, exitSchema } from "./instance";
|
|
11
15
|
import { createLogin } from "./login";
|
|
@@ -13,30 +17,28 @@ import { createOperations } from "./operations";
|
|
|
13
17
|
import {
|
|
14
18
|
type AgentStatus,
|
|
15
19
|
agentVersionHeader,
|
|
20
|
+
allows,
|
|
16
21
|
clientIdentity,
|
|
17
22
|
clientRelease,
|
|
18
23
|
compareRequestSchema,
|
|
19
24
|
credentialsSchema,
|
|
20
25
|
discoverSchema,
|
|
26
|
+
type Identity,
|
|
21
27
|
targetSchema,
|
|
22
28
|
tsplcVersion,
|
|
23
29
|
} from "./protocol";
|
|
24
30
|
import { createReleaseStore, readDeployRequest } from "./releases";
|
|
25
|
-
import {
|
|
31
|
+
import { type ApiRoute, matchRoute } from "./routes";
|
|
32
|
+
import { serverEnvironment, storedCredentials } from "./secrets";
|
|
26
33
|
import { createServerSupervisor } from "./server-process";
|
|
27
34
|
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
|
-
};
|
|
35
|
+
import { createWhois, runCommand } from "./tailscale";
|
|
34
36
|
|
|
35
37
|
export interface AgentOptions {
|
|
36
38
|
/** Releases, the controller's download baseline and the selected target live here. */
|
|
37
39
|
state: string;
|
|
38
40
|
token: string;
|
|
39
|
-
/**
|
|
41
|
+
/** A viewer's: the debugger (`/debug/*`), `GET /status` and the dashboard's reading routes. */
|
|
40
42
|
readToken?: string;
|
|
41
43
|
/** The deployed server's health route; without it a server that stays up 5 s counts as started. */
|
|
42
44
|
serverHealthUrl?: string;
|
|
@@ -56,10 +58,13 @@ export interface AgentOptions {
|
|
|
56
58
|
export const createAgent = async (options: AgentOptions) => {
|
|
57
59
|
const { log } = options;
|
|
58
60
|
const state = await openState(options.state);
|
|
61
|
+
const environmentVariables = options.environment ?? { ...process.env };
|
|
59
62
|
const server = createServerSupervisor({
|
|
60
63
|
healthUrl: options.serverHealthUrl,
|
|
61
64
|
record: state.paths.server,
|
|
62
65
|
output: state.paths.serverLog,
|
|
66
|
+
environment: (executable) =>
|
|
67
|
+
serverEnvironment(state.paths.releases, executable, environmentVariables),
|
|
63
68
|
log,
|
|
64
69
|
});
|
|
65
70
|
const deployed = await state.release();
|
|
@@ -85,19 +90,52 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
85
90
|
readLogin: login.read,
|
|
86
91
|
loginStatus: login.status,
|
|
87
92
|
serverHealthUrl: options.serverHealthUrl,
|
|
88
|
-
environment:
|
|
93
|
+
environment: environmentVariables,
|
|
89
94
|
log,
|
|
90
95
|
});
|
|
91
|
-
const deployments = createDeployments({
|
|
96
|
+
const deployments = await createDeployments({
|
|
92
97
|
state,
|
|
93
98
|
operations,
|
|
94
99
|
codesys,
|
|
95
100
|
server,
|
|
96
101
|
debugging,
|
|
102
|
+
serverHealthUrl: options.serverHealthUrl,
|
|
103
|
+
now: () => new Date(),
|
|
104
|
+
log,
|
|
105
|
+
});
|
|
106
|
+
const audit = createAudit({
|
|
107
|
+
file: state.paths.audit,
|
|
108
|
+
onRecord: (entry) => debugging.record(entry),
|
|
109
|
+
});
|
|
110
|
+
const access = createAccess({
|
|
111
|
+
token: options.token,
|
|
112
|
+
readToken: options.readToken,
|
|
113
|
+
file: accessFile(options.state),
|
|
114
|
+
whois: createWhois({ run: runCommand, now: Date.now, log }),
|
|
115
|
+
audit,
|
|
116
|
+
now: Date.now,
|
|
97
117
|
log,
|
|
98
118
|
});
|
|
119
|
+
const environment = createEnvironment({
|
|
120
|
+
state,
|
|
121
|
+
server,
|
|
122
|
+
operations,
|
|
123
|
+
audit,
|
|
124
|
+
file: environmentFile(options.state),
|
|
125
|
+
log,
|
|
126
|
+
});
|
|
127
|
+
const dashboard = createDashboard();
|
|
128
|
+
const apiRoutes: ApiRoute[] = [
|
|
129
|
+
...createDeploymentRoutes({ runner: deployments.runner, releases }),
|
|
130
|
+
...access.routes,
|
|
131
|
+
...environment.routes,
|
|
132
|
+
...audit.routes,
|
|
133
|
+
];
|
|
99
134
|
|
|
100
|
-
const route = async (
|
|
135
|
+
const route = async (
|
|
136
|
+
request: Request,
|
|
137
|
+
identity: Identity,
|
|
138
|
+
): Promise<Response> => {
|
|
101
139
|
const { pathname } = new URL(request.url);
|
|
102
140
|
const key = `${request.method} ${pathname}`;
|
|
103
141
|
switch (key) {
|
|
@@ -147,6 +185,7 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
147
185
|
case "POST /deploy":
|
|
148
186
|
return deployments.deploy(
|
|
149
187
|
() => readDeployRequest(releases, request),
|
|
188
|
+
identity,
|
|
150
189
|
clientIdentity(request),
|
|
151
190
|
clientRelease(request),
|
|
152
191
|
);
|
|
@@ -204,8 +243,11 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
204
243
|
}
|
|
205
244
|
};
|
|
206
245
|
|
|
207
|
-
const respond = async (
|
|
208
|
-
|
|
246
|
+
const respond = async (
|
|
247
|
+
request: Request,
|
|
248
|
+
peer: Peer | null,
|
|
249
|
+
): Promise<Response> => {
|
|
250
|
+
const { pathname, search } = new URL(request.url);
|
|
209
251
|
const debugPath = pathname.startsWith("/debug/");
|
|
210
252
|
// The UI's relative links need the trailing slash.
|
|
211
253
|
if (pathname === "/debug") {
|
|
@@ -221,24 +263,54 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
221
263
|
) {
|
|
222
264
|
return debugging.handle(request, pathname.slice("/debug".length));
|
|
223
265
|
}
|
|
224
|
-
//
|
|
225
|
-
const
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
const
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
if (
|
|
235
|
-
return
|
|
266
|
+
// The dashboard's pages hold no data; what they show comes from `/api` as whoever is signed in.
|
|
267
|
+
const page = await dashboard.handle(request);
|
|
268
|
+
if (page) {
|
|
269
|
+
return page;
|
|
270
|
+
}
|
|
271
|
+
const signing = await access.handle(request);
|
|
272
|
+
if (signing) {
|
|
273
|
+
return signing;
|
|
274
|
+
}
|
|
275
|
+
const identity = await access.identify(request, peer);
|
|
276
|
+
if (identity instanceof Response) {
|
|
277
|
+
return identity;
|
|
278
|
+
}
|
|
279
|
+
const api = pathname.startsWith("/api/")
|
|
280
|
+
? matchRoute(apiRoutes, request.method, pathname)
|
|
281
|
+
: undefined;
|
|
282
|
+
// The routes before `/api` are the CLI's: a viewer may only read status and the debugger.
|
|
283
|
+
const required = api
|
|
284
|
+
? api.route.role
|
|
285
|
+
: debugPath || (request.method === "GET" && pathname === "/status")
|
|
286
|
+
? "viewer"
|
|
287
|
+
: "admin";
|
|
288
|
+
if (!allows(identity.role, required)) {
|
|
289
|
+
// The CLI's routes answered a read token as if it were none, which its client relies on.
|
|
290
|
+
return api
|
|
291
|
+
? Response.json(
|
|
292
|
+
{ error: `This needs the ${required} role` },
|
|
293
|
+
{ status: 403 },
|
|
294
|
+
)
|
|
295
|
+
: Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
236
296
|
}
|
|
237
297
|
try {
|
|
298
|
+
if (api) {
|
|
299
|
+
return await api.route.handle(request, {
|
|
300
|
+
identity,
|
|
301
|
+
params: api.params,
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
if (pathname.startsWith("/api/")) {
|
|
305
|
+
return Response.json(
|
|
306
|
+
{ error: `No route ${request.method} ${pathname}` },
|
|
307
|
+
{ status: 404 },
|
|
308
|
+
);
|
|
309
|
+
}
|
|
238
310
|
if (debugPath) {
|
|
239
311
|
return await debugging.handle(request, pathname.slice("/debug".length));
|
|
240
312
|
}
|
|
241
|
-
return await route(request);
|
|
313
|
+
return await route(request, identity);
|
|
242
314
|
} catch (error) {
|
|
243
315
|
if (error instanceof AgentError) {
|
|
244
316
|
return Response.json(
|
|
@@ -272,8 +344,8 @@ export const createAgent = async (options: AgentOptions) => {
|
|
|
272
344
|
|
|
273
345
|
return {
|
|
274
346
|
/** 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);
|
|
347
|
+
fetch: async (request: Request, peer: Peer | null = null) => {
|
|
348
|
+
const response = await respond(request, peer);
|
|
277
349
|
// A proxied debugger response's headers are immutable.
|
|
278
350
|
const headers = new Headers(response.headers);
|
|
279
351
|
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>;
|
package/src/cli.ts
CHANGED
|
@@ -1,14 +1,16 @@
|
|
|
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";
|
|
13
|
+
import { type AccessConfig, roleSchema, tsplcVersion } from "./protocol";
|
|
12
14
|
import { agentService, agentSetting, controllerSecretNames } from "./secrets";
|
|
13
15
|
import { supervisedEnv } from "./service";
|
|
14
16
|
import { openState } from "./state";
|
|
@@ -21,6 +23,7 @@ tsplc-agent upgrade [version] [--state directory]
|
|
|
21
23
|
tsplc-agent service install|uninstall|status [serve options] [--stop-server]
|
|
22
24
|
tsplc-agent secrets set|delete <name> [--service ${agentService}]
|
|
23
25
|
tsplc-agent secrets set-controller
|
|
26
|
+
tsplc-agent access list|grant <login> <role>|revoke <login>|default <role|none> [--state directory]
|
|
24
27
|
|
|
25
28
|
setup Builds the CODESYS builder and gateway images, keeping each that is already right for
|
|
26
29
|
this tsPLC. Builder containers run the installed tsPLC's code and CODESYS scripts, so
|
|
@@ -30,7 +33,8 @@ setup Builds the CODESYS builder and gateway images, keeping each that is alre
|
|
|
30
33
|
serve Serves deployments and logins. --listen is required: use the machine's Tailscale
|
|
31
34
|
address, such as 100.101.102.103:4850. TSPLC_AGENT_TOKEN must hold a shared secret of
|
|
32
35
|
at least 32 characters, such as one from \`openssl rand -hex 32\`. An optional
|
|
33
|
-
TSPLC_AGENT_READ_TOKEN, as long, only
|
|
36
|
+
TSPLC_AGENT_READ_TOKEN, as long, only reads: the debugger at /debug, GET /status
|
|
37
|
+
and the dashboard.
|
|
34
38
|
Each comes from its environment variable, or else from \`secrets set\` under ${agentService}.
|
|
35
39
|
--bulk-import (experimental) brings a download without a baseline's POUs into CODESYS
|
|
36
40
|
in one PLCopenXML import, importing one at a time if CODESYS reports any problem.
|
|
@@ -47,7 +51,12 @@ service Runs the agent as a Windows service: a Task Scheduler task that starts i
|
|
|
47
51
|
line's server running unless --stop-server.
|
|
48
52
|
secrets Stores a value a release's secrets name, typed without echo, in Bun.secrets under
|
|
49
53
|
--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
|
|
54
|
+
and logins then use when they send none. Run it as the user the agent runs as.
|
|
55
|
+
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
|
|
57
|
+
gives every other tailnet member a role, none by default. The full token is an admin,
|
|
58
|
+
the read token a viewer, and a request from this PC an admin. The agent applies a
|
|
59
|
+
change at once.`;
|
|
51
60
|
|
|
52
61
|
const { values, positionals } = parseArgs({
|
|
53
62
|
allowPositionals: true,
|
|
@@ -69,6 +78,7 @@ if (!command || values.help) {
|
|
|
69
78
|
}
|
|
70
79
|
const takesArguments: Record<string, number> = {
|
|
71
80
|
secrets: 3,
|
|
81
|
+
access: 3,
|
|
72
82
|
upgrade: 1,
|
|
73
83
|
service: 1,
|
|
74
84
|
};
|
|
@@ -138,7 +148,7 @@ if (command === "setup") {
|
|
|
138
148
|
const server = Bun.serve({
|
|
139
149
|
hostname,
|
|
140
150
|
port,
|
|
141
|
-
fetch: agent.fetch,
|
|
151
|
+
fetch: (request, server) => agent.fetch(request, server.requestIP(request)),
|
|
142
152
|
// Deployments stream for minutes and upload a server executable.
|
|
143
153
|
idleTimeout: 0,
|
|
144
154
|
maxRequestBodySize: 2 ** 30,
|
|
@@ -203,6 +213,50 @@ if (command === "setup") {
|
|
|
203
213
|
"Usage: tsplc-agent secrets set|delete <name> [--service service], or secrets set-controller",
|
|
204
214
|
);
|
|
205
215
|
}
|
|
216
|
+
} else if (command === "access") {
|
|
217
|
+
const file = accessFile(stateDirectory);
|
|
218
|
+
const config = await readAccessConfig(file);
|
|
219
|
+
const [action, first, second, ...extra] = args;
|
|
220
|
+
const change = ((): AccessConfig | null => {
|
|
221
|
+
if (action === "grant" && first && second && !extra.length) {
|
|
222
|
+
return {
|
|
223
|
+
...config,
|
|
224
|
+
roles: { ...config.roles, [first]: roleSchema.parse(second) },
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
if (action === "revoke" && first && !second) {
|
|
228
|
+
if (!(first in config.roles)) {
|
|
229
|
+
throw new Error(`${first} has no role.`);
|
|
230
|
+
}
|
|
231
|
+
return {
|
|
232
|
+
...config,
|
|
233
|
+
roles: Object.fromEntries(
|
|
234
|
+
Object.entries(config.roles).filter(([login]) => login !== first),
|
|
235
|
+
),
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
if (action === "default" && first && !second) {
|
|
239
|
+
return {
|
|
240
|
+
...config,
|
|
241
|
+
tailnetDefault: first === "none" ? null : roleSchema.parse(first),
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
if (action === "list" && !first) {
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
throw new Error(
|
|
248
|
+
"Usage: tsplc-agent access list|grant <login> <role>|revoke <login>|default <role|none>",
|
|
249
|
+
);
|
|
250
|
+
})();
|
|
251
|
+
if (change) {
|
|
252
|
+
await mkdir(stateDirectory, { recursive: true });
|
|
253
|
+
await writeAccessConfig(file, change);
|
|
254
|
+
}
|
|
255
|
+
const shown = change ?? config;
|
|
256
|
+
for (const [login, role] of Object.entries(shown.roles)) {
|
|
257
|
+
console.log(`${login}\t${role}`);
|
|
258
|
+
}
|
|
259
|
+
console.log(`Other tailnet members: ${shown.tailnetDefault ?? "none"}`);
|
|
206
260
|
} else {
|
|
207
261
|
throw new Error(`Unknown command ${command}.`);
|
|
208
262
|
}
|