@tsplc/agent 0.5.10 → 0.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,17 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { readFile, rename, writeFile } from "node:fs/promises";
3
3
  import { join } from "node:path";
4
- import { tsplcConfigSchema } from "@tsplc/config";
4
+ import type { PlantVariables } from "@tsplc/config";
5
5
  import { z } from "zod";
6
6
  import type { AuditLog } from "./audit";
7
7
  import { AgentError, errorMessage } from "./errors";
8
8
  import type { Operations } from "./operations";
9
9
  import {
10
10
  type EnvironmentEntry,
11
+ type EnvironmentListing,
11
12
  environmentValueSchema,
12
13
  type Identity,
14
+ variableName,
13
15
  } from "./protocol";
14
16
  import { loadRelease } from "./releases";
15
17
  import type { ApiRoute } from "./routes";
@@ -17,23 +19,38 @@ import { environmentService } from "./secrets";
17
19
  import type { ServerSupervisor } from "./server-process";
18
20
  import type { AgentState } from "./state";
19
21
 
20
- /** The config's rule for a secret's name: an environment variable's. */
21
- const secretName = tsplcConfigSchema.shape.secrets.unwrap().shape.names.element;
22
-
23
22
  /** `environment.json` in the state directory `state`. */
24
23
  export const environmentFile = (state: string) =>
25
24
  join(state, "environment.json");
26
25
 
26
+ /** `variables.json` in the state directory `state`. */
27
+ export const variablesFile = (state: string) => join(state, "variables.json");
28
+
27
29
  /**
28
30
  * `environment.json`: the names the dashboard stored by Bun.secrets service, since Bun.secrets
29
31
  * can't list a service's names. Never a value.
30
32
  */
31
- const storedNamesSchema = z.record(z.string(), z.array(secretName));
33
+ const storedNamesSchema = z.record(z.string(), z.array(variableName));
34
+
35
+ /** `variables.json`: the plain variables set on this PC, by name. */
36
+ const storedVariablesSchema = z.record(variableName, z.string());
37
+
38
+ const readJson = async <T>(file: string, schema: z.ZodType<T>, empty: T) =>
39
+ existsSync(file)
40
+ ? schema.parse(JSON.parse(await readFile(file, "utf8")))
41
+ : empty;
42
+
43
+ const writeJson = async (file: string, value: unknown) => {
44
+ await writeFile(`${file}.tmp`, JSON.stringify(value, null, 2));
45
+ await rename(`${file}.tmp`, file);
46
+ };
32
47
 
33
48
  /**
34
- * The deployed release's secrets, set and replaced but never read back, and the server's
35
- * restart. The release's config names the Bun.secrets service they live in, which its
36
- * deployments fill the ST from and its server starts with.
49
+ * The plant PC's variables: plain ones, shown and edited here, and secrets, set and replaced but
50
+ * never read back; what the running release was built with; and the server's restart. `tsplc
51
+ * deploy` builds the PLC's program with the plain values and carries them to the server, and the
52
+ * agent fills the secrets in from the Bun.secrets service the release names, so a change reaches
53
+ * both with the next deployment.
37
54
  */
38
55
  export const createEnvironment = (context: {
39
56
  state: AgentState;
@@ -42,35 +59,36 @@ export const createEnvironment = (context: {
42
59
  audit: AuditLog;
43
60
  /** `environment.json`. */
44
61
  file: string;
62
+ /** `variables.json`. */
63
+ variables: string;
45
64
  log: (message: string) => void;
46
65
  }) => {
47
66
  const { state, audit } = context;
48
67
 
49
- const storedNames = async () =>
50
- existsSync(context.file)
51
- ? storedNamesSchema.parse(
52
- JSON.parse(await readFile(context.file, "utf8")),
53
- )
54
- : {};
68
+ const storedNames = () => readJson(context.file, storedNamesSchema, {});
55
69
  const writeStoredNames = async (
56
70
  service: string,
57
71
  update: (names: string[]) => string[],
58
72
  ) => {
59
73
  const stored = await storedNames();
60
- const names = update(stored[service] ?? []);
61
- await writeFile(
62
- `${context.file}.tmp`,
63
- JSON.stringify({ ...stored, [service]: names }, null, 2),
64
- );
65
- await rename(`${context.file}.tmp`, context.file);
74
+ await writeJson(context.file, {
75
+ ...stored,
76
+ [service]: update(stored[service] ?? []),
77
+ });
66
78
  };
79
+ const storedVariables = () =>
80
+ readJson(context.variables, storedVariablesSchema, {});
67
81
 
68
- /** The service the deployed release keeps its secrets in, and the names it declares. */
69
- const declared = async () => {
82
+ const deployedManifest = async () => {
70
83
  const release = await state.release();
71
- const secrets =
72
- release &&
73
- (await loadRelease(state.paths.releases, release.id)).manifest.secrets;
84
+ return release
85
+ ? (await loadRelease(state.paths.releases, release.id)).manifest
86
+ : undefined;
87
+ };
88
+
89
+ /** The service the deployed release keeps its secrets in, and the names it reads. */
90
+ const declared = async () => {
91
+ const secrets = (await deployedManifest())?.secrets;
74
92
  return secrets
75
93
  ? { service: secrets.service, names: secrets.names }
76
94
  : { service: environmentService, names: [] };
@@ -104,43 +122,101 @@ export const createEnvironment = (context: {
104
122
  ];
105
123
  };
106
124
 
107
- /** Records a change by the secret's name and who made it, never its value. */
108
- const record = (identity: Identity, command: string) =>
125
+ const listing = async (): Promise<EnvironmentListing> => ({
126
+ values: (await deployedManifest())?.values ?? {},
127
+ variables: await storedVariables(),
128
+ secrets: await entries(),
129
+ });
130
+
131
+ /** What `tsplc deploy` builds with: the plain values, and the secrets set in `service`. */
132
+ const forRelease = async (service: string): Promise<PlantVariables> => {
133
+ const held = (await storedNames())[service] ?? [];
134
+ const set = await Promise.all(
135
+ held.map(async (name) => ((await isSet(service, name)) ? [name] : [])),
136
+ );
137
+ return { service, values: await storedVariables(), secrets: set.flat() };
138
+ };
139
+
140
+ /** Records a change by the variable's name, with a plain one's value; never a secret's. */
141
+ const record = (
142
+ identity: Identity,
143
+ command: string,
144
+ change: {
145
+ values: Record<string, string>;
146
+ previous: Record<string, string> | null;
147
+ },
148
+ ) =>
109
149
  audit.record({
110
150
  identity,
111
151
  command,
112
- values: {},
113
- previous: null,
152
+ values: change.values,
153
+ previous: change.previous,
114
154
  error: null,
115
155
  });
156
+ /** A secret's change: its name alone. */
157
+ const nameOnly = { values: {}, previous: null };
158
+
159
+ const withoutVariable = async (name: string) => {
160
+ const { [name]: removed, ...rest } = await storedVariables();
161
+ if (removed !== undefined) {
162
+ await writeJson(context.variables, rest);
163
+ }
164
+ return removed;
165
+ };
116
166
 
117
167
  const routes: ApiRoute[] = [
118
168
  {
119
169
  method: "GET",
120
170
  pattern: "/api/environment",
121
171
  role: "viewer",
122
- handle: async () => Response.json(await entries()),
172
+ handle: async () => Response.json(await listing()),
173
+ },
174
+ {
175
+ method: "GET",
176
+ pattern: "/api/environment/release",
177
+ role: "deployer",
178
+ handle: async (request) =>
179
+ Response.json(
180
+ await forRelease(
181
+ new URL(request.url).searchParams.get("service") ||
182
+ environmentService,
183
+ ),
184
+ ),
123
185
  },
124
186
  {
125
187
  method: "PUT",
126
188
  pattern: "/api/environment/:name",
127
189
  role: "admin",
128
190
  handle: async (request, { identity, params }) => {
129
- const name = secretName.parse(params.name);
130
- const { value } = environmentValueSchema.parse(await request.json());
131
- const { service, names } = await declared();
132
- await Bun.secrets.set({ service, name, value });
133
- await writeStoredNames(service, (stored) => [
134
- ...stored.filter((other) => other !== name),
135
- name,
136
- ]);
137
- await record(identity, `environment set ${name}`);
138
- const entry: EnvironmentEntry = {
139
- name,
140
- declared: names.includes(name),
141
- set: true,
142
- };
143
- return Response.json(entry);
191
+ const name = variableName.parse(params.name);
192
+ const change = environmentValueSchema.parse(await request.json());
193
+ const { service } = await declared();
194
+ if (change.secret) {
195
+ await Bun.secrets.set({ service, name, value: change.value });
196
+ await writeStoredNames(service, (stored) => [
197
+ ...stored.filter((other) => other !== name),
198
+ name,
199
+ ]);
200
+ await withoutVariable(name);
201
+ await record(identity, `environment set ${name}`, nameOnly);
202
+ return Response.json(await listing());
203
+ }
204
+ const previous = (await storedVariables())[name];
205
+ await writeJson(context.variables, {
206
+ ...(await storedVariables()),
207
+ [name]: change.value,
208
+ });
209
+ // A name is a plain variable or a secret, never both.
210
+ if (await Bun.secrets.delete({ service, name })) {
211
+ await writeStoredNames(service, (stored) =>
212
+ stored.filter((other) => other !== name),
213
+ );
214
+ }
215
+ await record(identity, `environment set ${name}`, {
216
+ values: { [name]: change.value },
217
+ previous: previous === undefined ? null : { [name]: previous },
218
+ });
219
+ return Response.json(await listing());
144
220
  },
145
221
  },
146
222
  {
@@ -148,21 +224,24 @@ export const createEnvironment = (context: {
148
224
  pattern: "/api/environment/:name",
149
225
  role: "admin",
150
226
  handle: async (_request, { identity, params }) => {
151
- const name = secretName.parse(params.name);
152
- const { service, names } = await declared();
227
+ const name = variableName.parse(params.name);
228
+ const removed = await withoutVariable(name);
229
+ if (removed !== undefined) {
230
+ await record(identity, `environment delete ${name}`, {
231
+ values: {},
232
+ previous: { [name]: removed },
233
+ });
234
+ return Response.json(await listing());
235
+ }
236
+ const { service } = await declared();
153
237
  if (!(await Bun.secrets.delete({ service, name }))) {
154
238
  throw new AgentError(`${name} isn't set`, 404);
155
239
  }
156
240
  await writeStoredNames(service, (stored) =>
157
241
  stored.filter((other) => other !== name),
158
242
  );
159
- await record(identity, `environment delete ${name}`);
160
- const entry: EnvironmentEntry = {
161
- name,
162
- declared: names.includes(name),
163
- set: false,
164
- };
165
- return Response.json(entry);
243
+ await record(identity, `environment delete ${name}`, nameOnly);
244
+ return Response.json(await listing());
166
245
  },
167
246
  },
168
247
  {
package/src/login.ts CHANGED
@@ -5,6 +5,7 @@ import {
5
5
  findControllerLogin,
6
6
  type LoginCommand,
7
7
  openControllerLogin,
8
+ type ResetKind,
8
9
  settleWarmController,
9
10
  } from "@tsplc/build";
10
11
  import { LoginUnavailable, noLogin } from "@tsplc/debug";
@@ -202,6 +203,22 @@ export const createLogin = (context: {
202
203
  });
203
204
  },
204
205
 
206
+ /**
207
+ * Resets the application through the open login and starts it again, as `tsplc reset` then
208
+ * `tsplc start` do. Returns the state it runs in.
209
+ */
210
+ restart: async (reset: ResetKind) => {
211
+ const login = await requireLogin();
212
+ return enqueue(async () => {
213
+ await login.send({ command: "reset", kind: reset });
214
+ const started = await login.send({ command: "start" });
215
+ if (!("state" in started)) {
216
+ throw new Error("The login answered a start without the state");
217
+ }
218
+ return { state: started.state };
219
+ });
220
+ },
221
+
205
222
  /** Whether a login's container runs, open or opening. */
206
223
  isOpen: async () =>
207
224
  (await findControllerLogin(loginContainer)) !== undefined,
package/src/operations.ts CHANGED
@@ -7,7 +7,8 @@ export type Operation =
7
7
  | "a deployment"
8
8
  | "a login"
9
9
  | "a logout"
10
- | "a server restart";
10
+ | "a server restart"
11
+ | "a controller restart";
11
12
 
12
13
  /** The agent runs one deployment, login or logout at a time, and none while it is held for an upgrade. */
13
14
  export const createOperations = (log: (message: string) => void) => {
package/src/protocol.ts CHANGED
@@ -49,6 +49,14 @@ export const variableSchema = z.strictObject({
49
49
  });
50
50
  export type Variable = z.infer<typeof variableSchema>;
51
51
 
52
+ /** A target's values, by the config's rule for them. */
53
+ const targetValuesSchema =
54
+ tsplcConfigSchema.shape.targets.unwrap().valueType.shape.values;
55
+
56
+ /** The config's rule for a variable's name: an environment variable's. */
57
+ export const variableName =
58
+ tsplcConfigSchema.shape.secrets.unwrap().shape.names.element;
59
+
52
60
  /**
53
61
  * What `tsplc deploy` uploads beside its files. `config` is the build config with paths
54
62
  * relative to the release: `st/`, `template.project` and `libraries/`.
@@ -73,6 +81,8 @@ export const releaseManifestSchema = z.strictObject({
73
81
  serverTokenEnv: z.string().nonempty().optional(),
74
82
  /** The project's `secrets`, whose placeholders in the ST the agent fills in from Bun.secrets. */
75
83
  secrets: tsplcConfigSchema.shape.secrets,
84
+ /** The values of the target it was built for, which its server starts with; none in a release from before 0.5.12. */
85
+ values: targetValuesSchema,
76
86
  });
77
87
  export type ReleaseManifest = z.infer<typeof releaseManifestSchema>;
78
88
 
@@ -299,7 +309,8 @@ export const identitySchema = z.strictObject({
299
309
  /** A name to show: the Tailscale display name, or how the token or PC is known. */
300
310
  name: z.string(),
301
311
  role: roleSchema,
302
- via: z.enum(["tailscale", "token", "local"]),
312
+ /** `server`: the deployed server, with the token the agent started it with. */
313
+ via: z.enum(["tailscale", "token", "local", "server"]),
303
314
  });
304
315
  export type Identity = z.infer<typeof identitySchema>;
305
316
 
@@ -476,6 +487,16 @@ export const environmentEntrySchema = z.strictObject({
476
487
  });
477
488
  export type EnvironmentEntry = z.infer<typeof environmentEntrySchema>;
478
489
 
490
+ /** `GET /api/environment`: the plant PC's variables, and what the running release was built with. */
491
+ export const environmentSchema = z.strictObject({
492
+ /** The plain values the running release was built with, from the config's target and this PC. */
493
+ values: targetValuesSchema,
494
+ /** The plain variables stored on this PC, which the next deployment is built with. */
495
+ variables: z.record(variableName, z.string()),
496
+ secrets: z.array(environmentEntrySchema),
497
+ });
498
+ export type EnvironmentListing = z.infer<typeof environmentSchema>;
499
+
479
500
  /**
480
501
  * `access.json` in the agent's state directory, and the body of `GET` and `PUT /api/access`: the
481
502
  * role of each Tailscale login, and the role a tailnet member without one gets, none by default.
@@ -489,5 +510,25 @@ export type AccessConfig = z.infer<typeof accessConfigSchema>;
489
510
  /** `POST /api/session`: the agent's full or read token, which signs a browser in. */
490
511
  export const sessionRequestSchema = z.strictObject({ token: z.string() });
491
512
 
492
- /** `PUT /api/environment/:name`: the secret's new value. */
493
- export const environmentValueSchema = z.strictObject({ value: secretValue });
513
+ /** A plain variable's value, which the PLC's program may read through `env()`: no NUL. */
514
+ const plainValue = z
515
+ .string()
516
+ .nonempty("is empty")
517
+ .regex(/^[^\0]*$/, "holds a NUL");
518
+
519
+ /** `PUT /api/environment/:name`: a plain variable's new value, shown and built with, or a secret's. */
520
+ export const environmentValueSchema = z.discriminatedUnion("secret", [
521
+ z.strictObject({ secret: z.literal(false), value: plainValue }),
522
+ z.strictObject({ secret: z.literal(true), value: secretValue }),
523
+ ]);
524
+ export type EnvironmentValue = z.infer<typeof environmentValueSchema>;
525
+
526
+ /**
527
+ * `GET /api/environment/release?service=`: what `tsplc deploy` builds a release with, the plain
528
+ * variables' values and the names of the secrets the PC holds in the service.
529
+ */
530
+ export const plantVariablesSchema = z.strictObject({
531
+ service: z.string().nonempty(),
532
+ values: z.record(variableName, z.string()),
533
+ secrets: z.array(variableName),
534
+ });
package/src/secrets.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomBytes } from "node:crypto";
1
2
  import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
3
  import { dirname, join, relative, sep } from "node:path";
3
4
  import {
@@ -28,6 +29,21 @@ export const agentSetting = async (
28
29
  (await Bun.secrets.get({ service: agentService, name })) ??
29
30
  undefined;
30
31
 
32
+ /**
33
+ * The token the deployed server is started with, made once and kept under the agent's service, so
34
+ * a server an earlier agent started still has a valid one.
35
+ */
36
+ export const serverToken = async () => {
37
+ const name = "server-token";
38
+ const stored = await Bun.secrets.get({ service: agentService, name });
39
+ if (stored) {
40
+ return stored;
41
+ }
42
+ const token = randomBytes(32).toString("hex");
43
+ await Bun.secrets.set({ service: agentService, name, value: token });
44
+ return token;
45
+ };
46
+
31
47
  /** The controller user stored with `tsplc-agent secrets set-controller`, or null. */
32
48
  export const storedCredentials = async (): Promise<Credentials | null> => {
33
49
  const [username, password] = await Promise.all([
@@ -86,7 +102,10 @@ export const readSecrets = async (secrets: ReleaseManifest["secrets"]) => {
86
102
  return values;
87
103
  };
88
104
 
89
- /** Variable `name` for the agent's own use: from Bun.secrets when the release names it as a secret, otherwise `environment`. */
105
+ /**
106
+ * Variable `name` for the agent's own use, as the release's server reads it: from Bun.secrets when
107
+ * the release names it as a secret, else the release's value, else `environment`.
108
+ */
90
109
  export const releaseVariable = async (
91
110
  manifest: ReleaseManifest,
92
111
  name: string,
@@ -94,12 +113,31 @@ export const releaseVariable = async (
94
113
  ) =>
95
114
  manifest.secrets?.names.includes(name)
96
115
  ? Bun.secrets.get({ service: manifest.secrets.service, name })
97
- : environment[name];
116
+ : (manifest.values[name] ?? environment[name]);
117
+
118
+ /** The release's secrets that Bun.secrets holds, by name. */
119
+ const storedSecrets = async (secrets: ReleaseManifest["secrets"]) => {
120
+ if (!secrets) {
121
+ return {};
122
+ }
123
+ const stored = await Promise.all(
124
+ secrets.names.map(async (name) => ({
125
+ name,
126
+ value: await Bun.secrets.get({ service: secrets.service, name }),
127
+ })),
128
+ );
129
+ return Object.fromEntries(
130
+ stored.flatMap(({ name, value }): [string, string][] =>
131
+ value === null ? [] : [[name, value]],
132
+ ),
133
+ );
134
+ };
98
135
 
99
136
  /**
100
137
  * The environment the server at `executable`, in a release under `releases`, runs in:
101
- * `environment` with the release's secrets that Bun.secrets holds, so a server reads them as the
102
- * variables they are.
138
+ * `environment`, then the values of the target the release was built for, as the PLC's program
139
+ * got them, then the release's secrets that Bun.secrets holds, so a server reads each as the
140
+ * variable it is.
103
141
  */
104
142
  export const serverEnvironment = async (
105
143
  releases: string,
@@ -107,26 +145,17 @@ export const serverEnvironment = async (
107
145
  environment: Environment,
108
146
  ): Promise<Environment> => {
109
147
  const [id = ""] = relative(releases, executable).split(sep);
110
- const secrets = await loadRelease(releases, id).then(
111
- ({ manifest }) => manifest.secrets,
148
+ const manifest = await loadRelease(releases, id).then(
149
+ (release) => release.manifest,
112
150
  () => undefined,
113
151
  );
114
- if (!secrets) {
152
+ if (!manifest) {
115
153
  return environment;
116
154
  }
117
- const stored = await Promise.all(
118
- secrets.names.map(async (name) => ({
119
- name,
120
- value: await Bun.secrets.get({ service: secrets.service, name }),
121
- })),
122
- );
123
155
  return {
124
156
  ...environment,
125
- ...Object.fromEntries(
126
- stored.flatMap(({ name, value }): [string, string][] =>
127
- value === null ? [] : [[name, value]],
128
- ),
129
- ),
157
+ ...manifest.values,
158
+ ...(await storedSecrets(manifest.secrets)),
130
159
  };
131
160
  };
132
161