@ptkl/toolkit 1.7.0 → 1.9.0

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/README.md CHANGED
@@ -20,6 +20,10 @@ ptkl init
20
20
 
21
21
  This creates a `~/.ptkl` directory where profiles and settings are stored.
22
22
 
23
+ ### Authenticating from the environment
24
+
25
+ When `PROJECT_API_TOKEN` is set and no profile is chosen (`--profile` or `PTKL_ACTIVE_PROFILE`), ptkl uses that token instead of a stored profile. `API_HOST` (the platform API base URL, required) and `PROJECT_UUID` (the project uuid) complete it. Useful in CI. Inside a Kiln machine ptkl is ready: those three variables are set and it is authenticated as the machine's run identity. The token is never printed. `PROJECT_ENV` (`live` inside a Kiln machine) sets the default env; `--env` overrides it.
26
+
23
27
  ### 2. Create a Profile
24
28
 
25
29
  A profile stores your authentication credentials and connection settings for a Protokol instance.
@@ -185,6 +189,13 @@ ptkl forge dev -p <path> [options]
185
189
  | `--platform-url <url>` | Platform UI URL for consent/permission flows |
186
190
  | `-m, --mode <mode>` | Vite mode (defaults to `development`) |
187
191
  | `--env <env>` | Target environment (`dev` or `live`) |
192
+ | `--public-host <host>` | Host name other machines use to reach this one (e.g. its Tailscale name). Off by default |
193
+
194
+ #### Opening the dev app from another machine
195
+
196
+ By default the dev page, the dev hub and the dev services only work from the machine running `ptkl forge dev`. If the app runs on machine A and you browse from machine B, pass `--public-host <host>` with the name B uses to reach A, then open `http://<host>:<port>`.
197
+
198
+ This exposes the dev page, the app token it carries and the dev services to the network, so use it only on a network you trust (for example a private Tailscale network).
188
199
 
189
200
  #### Multi-view development
190
201
 
@@ -0,0 +1,522 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
+ import axios from "axios";
3
+ import { Readable } from "node:stream";
4
+ import { execFileSync } from "node:child_process";
5
+ import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
6
+ import { tmpdir } from "node:os";
7
+ import { join } from "node:path";
8
+ import { Command } from "commander";
9
+ import { list as tarList } from "tar";
10
+ import kiln from "../kiln.js";
11
+ import KilnPack from "../../lib/kilnPack.js";
12
+ let seen = [];
13
+ let replies = [];
14
+ let out = "";
15
+ let err = "";
16
+ const realAdapter = axios.defaults.adapter;
17
+ function reply(data, status = 200, headers = {}) {
18
+ replies.push((config) => ({ data, status, statusText: "OK", headers, config }));
19
+ }
20
+ function refuse(data, status) {
21
+ replies.push(() => { throw Object.assign(new Error(`HTTP ${status}`), { response: { status, data } }); });
22
+ }
23
+ async function run(...args) {
24
+ const program = new Command().exitOverride();
25
+ program.addCommand(kiln.register());
26
+ await program.parseAsync(["node", "ptkl", "kiln", ...args]);
27
+ }
28
+ const profile = { name: "p", host: "http://platform.test/", project: "proj-1", token: "profile-token", current: true };
29
+ vi.mock("../../lib/util.js", async () => {
30
+ const { default: Real } = await vi.importActual("../../lib/util.js");
31
+ Real.getProfiles = () => [profile];
32
+ return { default: Real };
33
+ });
34
+ beforeEach(() => {
35
+ seen = [];
36
+ replies = [];
37
+ out = "";
38
+ err = "";
39
+ delete process.env.PROJECT_API_TOKEN;
40
+ delete process.env.PROJECT_UUID;
41
+ delete process.env.API_HOST;
42
+ delete process.env.PTKL_ACTIVE_PROFILE;
43
+ axios.defaults.adapter = async (config) => {
44
+ let data = config.data;
45
+ if (typeof data === "string") {
46
+ try {
47
+ data = JSON.parse(data);
48
+ }
49
+ catch { /* raw */ }
50
+ }
51
+ seen.push({ method: config.method, url: config.url, params: config.params, data, headers: { ...config.headers.toJSON() } });
52
+ const next = replies.shift();
53
+ if (!next)
54
+ throw new Error(`no reply queued for ${config.method} ${config.url}`);
55
+ return next(config);
56
+ };
57
+ vi.spyOn(process.stdout, "write").mockImplementation(((s) => { out += s; return true; }));
58
+ vi.spyOn(process.stderr, "write").mockImplementation(((s) => { err += s; return true; }));
59
+ vi.spyOn(console, "log").mockImplementation((...a) => { out += a.join(" ") + "\n"; });
60
+ vi.spyOn(console, "error").mockImplementation((...a) => { err += a.join(" ") + "\n"; });
61
+ vi.spyOn(process, "exit").mockImplementation(((code) => { throw new Error(`exit ${code}`); }));
62
+ });
63
+ afterEach(() => {
64
+ axios.defaults.adapter = realAdapter;
65
+ vi.restoreAllMocks();
66
+ });
67
+ describe("ptkl kiln requests", () => {
68
+ it("lists machines through the luma gateway with the profile's credentials", async () => {
69
+ reply({ machines: [{ uuid: "m1", state: "running", expires_at: new Date(Date.now() + 600_000).toISOString() }] });
70
+ await run("machines", "list");
71
+ expect(seen[0].method).toBe("get");
72
+ expect(seen[0].url).toBe("/machines");
73
+ expect(seen[0].headers.Authorization).toBe("Bearer profile-token");
74
+ expect(seen[0].headers["X-Project-Uuid"]).toBe("proj-1");
75
+ expect(err).toMatch(/m1: time left 10m/);
76
+ });
77
+ it("creates a machine from flags", async () => {
78
+ reply({ uuid: "m1", state: "creating", expires_at: new Date(Date.now() + 1_800_000).toISOString() }, 202);
79
+ await run("create", "--size", "512", "--image", "node", "--env-var", "A=1", "--env-var", "B=x=y", "--egress", "allowlist", "--run-as", "role:dev", "--no-start", "--", "node", "server.js");
80
+ expect(seen[0].method).toBe("post");
81
+ expect(seen[0].url).toBe("/machines");
82
+ expect(seen[0].headers["Idempotency-Key"]).toBeTruthy();
83
+ expect(seen[0].data).toEqual({
84
+ start: false, size: 512, image: "node", egress: "allowlist", run_as: "role:dev",
85
+ env: { A: "1", B: "x=y" },
86
+ sequence: { command: ["node", "server.js"] },
87
+ });
88
+ });
89
+ it("create takes minutes only when it starts", async () => {
90
+ await expect(run("create", "--no-start", "-m", "10")).rejects.toThrow("exit 1");
91
+ expect(err).toContain("minutes are given when the machine starts");
92
+ err = "";
93
+ await expect(run("create", "--step", "ls")).rejects.toThrow("exit 1");
94
+ expect(err).toContain("--minutes is required");
95
+ expect(seen).toHaveLength(0);
96
+ reply({ uuid: "m1", state: "saved", minutes: null, expires_at: null }, 201);
97
+ await run("create", "--no-start", "--step", "ls");
98
+ expect(seen[0].data).toEqual({ start: false, sequence: { steps: ["ls"] } });
99
+ });
100
+ it("start sends minutes and run:false, and maps lease errors", async () => {
101
+ reply({ uuid: "m1" }, 202);
102
+ await run("start", "m1", "--minutes", "20", "--files-first");
103
+ expect(seen[0].data).toEqual({ minutes: 20, run: false });
104
+ refuse({ error: "lease_active", message: "x" }, 409);
105
+ await expect(run("start", "m1", "-m", "5")).rejects.toThrow("exit 1");
106
+ expect(err).toContain("use `ptkl kiln extend`");
107
+ err = "";
108
+ refuse({ error: "not_leased", message: "x" }, 409);
109
+ await expect(run("extend", "m1", "5")).rejects.toThrow("exit 1");
110
+ expect(err).toContain("start it with --minutes");
111
+ err = "";
112
+ refuse({ error: "invalid", field: "minutes", message: "minutes required" }, 400);
113
+ await expect(run("start", "m1")).rejects.toThrow("exit 1");
114
+ expect(err).toContain("--minutes: minutes required");
115
+ });
116
+ it("shows null lease fields as - for a saved machine", async () => {
117
+ reply({ uuid: "m1", state: "saved", minutes: null, leased_at: null, expires_at: null, started_at: null });
118
+ await run("machines", "get", "m1", "-f", "json");
119
+ expect(out).toContain('"state": "saved"');
120
+ expect(out).toContain('"expires_at": "-"');
121
+ });
122
+ it("sends --step lines as the sequence and starts by default", async () => {
123
+ reply({ uuid: "m1" }, 202);
124
+ await run("create", "-m", "10", "--step", "npm ci", "--step", "npm start");
125
+ expect(seen[0].data).toEqual({ minutes: 10, start: true, sequence: { steps: ["npm ci", "npm start"] } });
126
+ });
127
+ it("execs a command, prints its output and exits with its code", async () => {
128
+ reply({ exit_code: 3, stdout: "hello\n", stderr: "bad\n", time_left_sec: 125 });
129
+ await run("exec", "m1", "--", "ls", "-la");
130
+ expect(process.exitCode).toBe(3);
131
+ process.exitCode = undefined;
132
+ expect(seen[0].url).toBe("/machines/m1/exec");
133
+ expect(seen[0].data).toEqual({ command: ["ls", "-la"] });
134
+ expect(out).toBe("hello\n");
135
+ expect(err).toContain("bad");
136
+ expect(err).toContain("time left: 2m 5s");
137
+ });
138
+ it("prints the process table with totals and cuts the command", async () => {
139
+ reply({
140
+ processes: [
141
+ { pid: 42, ppid: 1, user: "root", state: "R", cpu_percent: 93.456, memory_bytes: 1610612736, elapsed_sec: 7500, command: "node " + "x".repeat(300) },
142
+ { pid: 7, ppid: 1, user: "app", state: "S", cpu_percent: 0, memory_bytes: 12288, elapsed_sec: 9, command: "sh" },
143
+ ],
144
+ count: 2, cpu_percent: 93.5, memory_bytes: 1610625024, time_left_sec: 60,
145
+ });
146
+ await run("ps", "m1", "--limit", "20");
147
+ expect(seen[0].url).toBe("/machines/m1/processes");
148
+ expect(seen[0].params).toEqual({ limit: 20 });
149
+ const lines = out.trimEnd().split("\n");
150
+ expect(lines[0]).toBe("CPU 93.5% MEM 1.5 GiB 2 processes");
151
+ expect(lines[1]).toMatch(/^PID USER\s+CPU% +MEM STATE +TIME COMMAND$/);
152
+ expect(lines[2]).toMatch(/^ 42 root +93\.5 +1\.5 GiB R +2h05m node x+…$/);
153
+ expect(lines[2].length).toBeLessThanOrEqual(120);
154
+ expect(lines[3]).toMatch(/^ 7 app +0\.0 +12 KiB S +9s sh$/);
155
+ expect(err).toContain("time left: 1m 0s");
156
+ });
157
+ it("ps -f json prints the response", async () => {
158
+ reply({ processes: [], count: 0, cpu_percent: 0, memory_bytes: 0 });
159
+ await run("ps", "m1", "-f", "json");
160
+ expect(seen[0].params).toBeUndefined();
161
+ expect(JSON.parse(out)).toEqual({ processes: [], count: 0, cpu_percent: 0, memory_bytes: 0 });
162
+ });
163
+ it("shows status as used of max", async () => {
164
+ reply({ state: "running", memory_bytes: 536870912, memory_max_bytes: 2147483648, swap_bytes: 0, swap_max_bytes: 1073741824,
165
+ disk_used_bytes: 1073741824, disk_limit_bytes: 10737418240, oom_kills: 2, uptime_sec: 125, time_left_sec: 30 });
166
+ await run("status", "m1");
167
+ expect(seen[0].url).toBe("/machines/m1/status");
168
+ expect(out).toContain("memory 512 MiB of 2 GiB");
169
+ expect(out).toContain("swap 0 B of 1 GiB");
170
+ expect(out).toContain("disk 1 GiB of 10 GiB");
171
+ expect(out).toContain("oom kills 2");
172
+ expect(out).toContain("uptime 2m05s");
173
+ });
174
+ it("prints the log lines", async () => {
175
+ reply({ lines: [{ stream: "stdout", text: "one" }, { stream: "stderr", text: "two" }], time_left_sec: 30 });
176
+ await run("logs", "m1", "--since", "2026-01-01T00:00:00Z");
177
+ expect(seen[0].params).toEqual({ since: "2026-01-01T00:00:00Z" });
178
+ expect(out).toBe("one\n");
179
+ expect(err).toContain("two");
180
+ });
181
+ it("follows the log until the end event", async () => {
182
+ const events = [
183
+ { event: "ready", time_left_sec: 90 },
184
+ { event: "line", line: { stream: "stdout", text: "booting" } },
185
+ { event: "end", reason: "exited" },
186
+ { event: "line", line: { stream: "stdout", text: "after end" } },
187
+ ];
188
+ reply(Readable.from([events.map((e) => JSON.stringify(e)).join("\n") + "\n"]));
189
+ await run("logs", "m1", "--follow");
190
+ expect(seen[0].params).toEqual({ follow: "true" });
191
+ expect(out).toBe("booting\n");
192
+ expect(err).toContain("time left: 1m 30s");
193
+ expect(err).toContain("log ended: exited");
194
+ });
195
+ it("gets, puts and lists files", async () => {
196
+ reply(Buffer.from("content"), 200, { "x-kiln-time-left-sec": "60" });
197
+ await run("files", "get", "m1", "/etc/motd");
198
+ expect(seen[0].params).toEqual({ path: "/etc/motd" });
199
+ expect(out).toBe("content");
200
+ expect(err).toContain("time left: 1m 0s");
201
+ const dir = mkdtempSync(join(tmpdir(), "kiln-files-"));
202
+ writeFileSync(join(dir, "a.txt"), "abc");
203
+ reply({ bytes_written: 3, time_left_sec: 50 });
204
+ await run("files", "put", "m1", "/tmp/a.txt", "--from", join(dir, "a.txt"), "--mode", "0600");
205
+ expect(seen[1].method).toBe("put");
206
+ expect(seen[1].params).toEqual({ path: "/tmp/a.txt", mode: "0600" });
207
+ expect(Buffer.from(seen[1].data).toString()).toBe("abc");
208
+ reply({ entries: [], truncated: false, time_left_sec: 40 });
209
+ await run("files", "list", "m1", "/tmp", "--depth", "2");
210
+ expect(seen[2].method).toBe("post");
211
+ expect(seen[2].url).toBe("/machines/m1/files/list");
212
+ expect(seen[2].data).toEqual({ path: "/tmp", depth: 2 });
213
+ rmSync(dir, { recursive: true });
214
+ });
215
+ it("start, stop, force stop, extend, delete and usage", async () => {
216
+ reply({ uuid: "m1" }, 202);
217
+ await run("start", "m1");
218
+ expect(seen[0]).toMatchObject({ method: "post", url: "/machines/m1/start" });
219
+ expect(seen[0].data).toBeUndefined();
220
+ reply({ uuid: "m1" }, 202);
221
+ await run("stop", "m1");
222
+ expect(seen[1].url).toBe("/machines/m1/stop");
223
+ reply({ uuid: "m1" }, 202);
224
+ await run("stop", "m1", "--force");
225
+ expect(seen[2].url).toBe("/machines/m1/stop?force=true");
226
+ reply({ uuid: "m1" });
227
+ await run("extend", "m1", "15");
228
+ expect(seen[3].data).toEqual({ minutes: 15 });
229
+ expect(seen[3].headers["Idempotency-Key"]).toBeTruthy();
230
+ reply({ uuid: "m1", name: "web" });
231
+ reply({ uuid: "m1" }, 202);
232
+ await run("delete", "m1");
233
+ expect(seen[5]).toMatchObject({ method: "delete", url: "/machines/m1", data: { name: "web" } });
234
+ reply({ month: "2026-11", left_minutes: 100 });
235
+ await run("usage");
236
+ expect(seen[6]).toMatchObject({ method: "get", url: "/usage" });
237
+ });
238
+ });
239
+ describe("ptkl kiln code with each start", () => {
240
+ let dir;
241
+ beforeEach(() => {
242
+ dir = mkdtempSync(join(tmpdir(), "kiln-start-"));
243
+ writeFileSync(join(dir, "main.js"), "console.log(1)");
244
+ });
245
+ afterEach(() => rmSync(dir, { recursive: true, force: true }));
246
+ it("start --media sends the intake with --to", async () => {
247
+ reply({ uuid: "m1" }, 202);
248
+ await run("start", "m1", "-m", "10", "--media", "a/b.txt", "--media", "c", "--to", "/app", "--env-var", "A=1");
249
+ expect(seen).toHaveLength(1);
250
+ expect(seen[0].data).toEqual({
251
+ minutes: 10, env: { A: "1" },
252
+ intake: [{ media: "a/b.txt", to: "/app" }, { media: "c", to: "/app" }],
253
+ });
254
+ reply({ uuid: "m1" }, 202);
255
+ await run("start", "m1", "--media", "x", "--cwd", "/srv/job");
256
+ expect(seen[1].data).toEqual({ cwd: "/srv/job", intake: [{ media: "x", to: "/srv/job" }] });
257
+ reply({ uuid: "m1", cwd: "/home/app" });
258
+ reply({ uuid: "m1" }, 202);
259
+ await run("start", "m1", "--media", "x");
260
+ expect(seen[3].data).toEqual({ intake: [{ media: "x", to: "/home/app" }] });
261
+ seen = [];
262
+ err = "";
263
+ reply({ uuid: "m1" });
264
+ await expect(run("start", "m1", "--media", "x")).rejects.toThrow("exit 1");
265
+ expect(err).toContain("--to is needed: the machine has no start directory");
266
+ });
267
+ it("start --archive: start run:false, wait for created, upload, start", async () => {
268
+ const gz = join(dir, "code.tar.gz");
269
+ writeFileSync(gz, "GZ");
270
+ reply({ uuid: "m1" }, 202);
271
+ reply({ uuid: "m1", state: "created" });
272
+ reply({ bytes_written: 2 });
273
+ reply({ uuid: "m1" }, 202);
274
+ await run("start", "m1", "-m", "15", "--archive", gz, "--to", "/app", "--step", "ls");
275
+ expect(seen.map((r) => `${r.method} ${r.url}`)).toEqual([
276
+ "post /machines/m1/start", "get /machines/m1", "put /machines/m1/archive", "post /machines/m1/start",
277
+ ]);
278
+ expect(seen[0].data).toEqual({ minutes: 15, run: false, sequence: { steps: ["ls"] } });
279
+ expect(seen[2].params).toEqual({ path: "/app" });
280
+ expect(Buffer.from(seen[2].data).toString()).toBe("GZ");
281
+ expect(seen[3].data).toEqual({});
282
+ });
283
+ it("start --archive packs a directory, and media goes in the first start", async () => {
284
+ reply({ uuid: "m1" }, 202);
285
+ reply({ state: "created" });
286
+ reply({ bytes_written: 2 });
287
+ reply({ uuid: "m1" }, 202);
288
+ await run("start", "m1", "-m", "5", "--archive", dir, "--media", "x", "--to", "/code");
289
+ expect(seen[0].data).toEqual({ minutes: 5, run: false, intake: [{ media: "x", to: "/code" }] });
290
+ const names = [];
291
+ await new Promise((resolve, reject) => {
292
+ const t = tarList({ onReadEntry: (e) => names.push(e.path) });
293
+ t.on("end", resolve);
294
+ t.on("error", reject);
295
+ Readable.from([Buffer.from(seen[2].data)]).pipe(t);
296
+ });
297
+ expect(names).toEqual(["main.js"]);
298
+ });
299
+ it("start --archive fails with the machine's reason and uploads nothing; --files-first is refused", async () => {
300
+ reply({ uuid: "m1" }, 202);
301
+ reply({ state: "failed", failure_reason: "intake: media not found" });
302
+ await expect(run("start", "m1", "-m", "5", "--archive", dir, "--to", "/code")).rejects.toThrow("exit 1");
303
+ expect(err).toContain("intake: media not found");
304
+ expect(seen.map((r) => r.method)).toEqual(["post", "get"]);
305
+ seen = [];
306
+ err = "";
307
+ await expect(run("start", "m1", "--archive", dir, "--files-first")).rejects.toThrow("exit 1");
308
+ expect(err).toContain("redundant");
309
+ expect(seen).toHaveLength(0);
310
+ });
311
+ it("create --no-start refuses code; create with --media sends the intake", async () => {
312
+ await expect(run("create", "--no-start", "--media", "a")).rejects.toThrow("exit 1");
313
+ expect(err).toContain("code is given when the machine starts");
314
+ err = "";
315
+ await expect(run("create", "--no-start", "--archive", dir)).rejects.toThrow("exit 1");
316
+ expect(err).toContain("code is given when the machine starts");
317
+ expect(seen).toHaveLength(0);
318
+ reply({ uuid: "m1" }, 201);
319
+ await run("create", "-m", "10", "--media", "a", "--to", "/w", "--step", "ls");
320
+ expect(seen[0].data).toEqual({ start: true, minutes: 10, sequence: { steps: ["ls"] }, intake: [{ media: "a", to: "/w" }] });
321
+ });
322
+ it("create --archive saves, then starts with the archive", async () => {
323
+ reply({ uuid: "m1", state: "saved" }, 201);
324
+ reply({ uuid: "m1" }, 202);
325
+ reply({ state: "created" });
326
+ reply({ bytes_written: 2 });
327
+ reply({ uuid: "m1" }, 202);
328
+ await run("create", "-m", "20", "--archive", dir, "--to", "/code", "--step", "node main.js");
329
+ expect(seen.map((r) => `${r.method} ${r.url}`)).toEqual([
330
+ "post /machines", "post /machines/m1/start", "get /machines/m1", "put /machines/m1/archive", "post /machines/m1/start",
331
+ ]);
332
+ expect(seen[0].data).toEqual({ start: false, sequence: { steps: ["node main.js"] } });
333
+ expect(seen[1].data).toEqual({ minutes: 20, run: false });
334
+ expect(seen[4].data).toEqual({});
335
+ });
336
+ it("maps a 400 on env to a clear message", async () => {
337
+ refuse({ error: "invalid", field: "env", message: "env FOO is not allowed" }, 400);
338
+ await expect(run("start", "m1", "-m", "5", "--env-var", "FOO=bar")).rejects.toThrow("exit 1");
339
+ expect(err).toContain("--env-var: env FOO is not allowed");
340
+ });
341
+ });
342
+ describe("ptkl kiln --global-env", () => {
343
+ it("create and start send global keys beside literal values", async () => {
344
+ reply({ uuid: "m1" }, 202);
345
+ await run("create", "--no-start", "--env-var", "A=1", "--global-env", "NPM_TOKEN=NPM_TOKEN", "--global-env", "K=OTHER");
346
+ expect(seen[0].data).toEqual({ start: false, env: { A: "1", NPM_TOKEN: { global_env: "NPM_TOKEN" }, K: { global_env: "OTHER" } } });
347
+ reply({ uuid: "m1" }, 202);
348
+ await run("start", "m1", "-m", "5", "--global-env", "API_KEY=API_KEY");
349
+ expect(seen[1].data).toEqual({ minutes: 5, env: { API_KEY: { global_env: "API_KEY" } } });
350
+ });
351
+ it("refuses a bad pair and one name given twice", async () => {
352
+ await expect(run("start", "m1", "-m", "5", "--global-env", "NOKEY")).rejects.toThrow("exit 1");
353
+ expect(err).toContain("--global-env takes NAME=KEY");
354
+ err = "";
355
+ await expect(run("start", "m1", "-m", "5", "--env-var", "A=1", "--global-env", "A=B")).rejects.toThrow("exit 1");
356
+ expect(err).toContain("both --env-var and --global-env");
357
+ expect(seen).toHaveLength(0);
358
+ });
359
+ });
360
+ describe("ptkl kiln --project-env", () => {
361
+ it("start and create send the lease's env, validated before any request", async () => {
362
+ await expect(run("start", "m1", "-m", "5", "--project-env", "prod")).rejects.toThrow("exit 1");
363
+ expect(err).toContain("--project-env must be dev or live");
364
+ err = "";
365
+ await expect(run("create", "--no-start", "--project-env", "live")).rejects.toThrow("exit 1");
366
+ expect(err).toContain("the env is set when the machine starts");
367
+ expect(seen).toHaveLength(0);
368
+ reply({ uuid: "m1" }, 202);
369
+ await run("start", "m1", "-m", "20", "--project-env", "live");
370
+ expect(seen[0].data).toEqual({ minutes: 20, project_env: "live" });
371
+ reply({ uuid: "m1" }, 201);
372
+ await run("create", "-m", "10", "--step", "ls", "--project-env", "dev");
373
+ expect(seen[1].data).toEqual({ start: true, minutes: 10, project_env: "dev", sequence: { steps: ["ls"] } });
374
+ });
375
+ it("leaves it out when not given, and names the flag when the API refuses it", async () => {
376
+ reply({ uuid: "m1" }, 202);
377
+ await run("start", "m1", "-m", "20");
378
+ expect(seen[0].data).toEqual({ minutes: 20 });
379
+ refuse({ error: "invalid", field: "project_env", message: "the env is set when the lease starts" }, 400);
380
+ await expect(run("start", "m1", "--project-env", "live")).rejects.toThrow("exit 1");
381
+ expect(err).toContain("--project-env: the env is set when the lease starts");
382
+ });
383
+ it("jobs create and update send it", async () => {
384
+ await expect(run("jobs", "create", "--name", "a", "-m", "5", "--overlap", "skip", "--project-env", "x")).rejects.toThrow("exit 1");
385
+ expect(seen).toHaveLength(0);
386
+ reply({ uuid: "j1" }, 201);
387
+ await run("jobs", "create", "--name", "a", "-m", "5", "--overlap", "skip", "--project-env", "live");
388
+ expect(seen[0].data).toMatchObject({ project_env: "live" });
389
+ reply({ uuid: "j1" });
390
+ await run("jobs", "update", "a", "--project-env", "dev");
391
+ expect(seen[1].data).toEqual({ project_env: "dev" });
392
+ });
393
+ });
394
+ describe("ptkl kiln push", () => {
395
+ let dir;
396
+ beforeEach(() => {
397
+ dir = mkdtempSync(join(tmpdir(), "kiln-push-"));
398
+ execFileSync("git", ["init", "-q", dir]);
399
+ writeFileSync(join(dir, ".gitignore"), "secret.txt\nbuild/\n");
400
+ writeFileSync(join(dir, "main.js"), "console.log(1)");
401
+ writeFileSync(join(dir, "secret.txt"), "nope");
402
+ mkdirSync(join(dir, "build"));
403
+ writeFileSync(join(dir, "build", "o.js"), "x");
404
+ mkdirSync(join(dir, "src"));
405
+ writeFileSync(join(dir, "src", "b.js"), "y");
406
+ });
407
+ afterEach(() => rmSync(dir, { recursive: true, force: true }));
408
+ it("packs the directory without ignored files and uploads it", async () => {
409
+ reply({ bytes_written: 10, files: [], time_left_sec: 300 });
410
+ await run("push", dir, "m1", "--to", "/app");
411
+ expect(seen[0]).toMatchObject({ method: "put", url: "/machines/m1/archive", params: { path: "/app" } });
412
+ expect(seen[0].headers["Content-Type"]).toBe("application/gzip");
413
+ const names = [];
414
+ const { Readable: R } = await import("node:stream");
415
+ await new Promise((resolve, reject) => {
416
+ const t = tarList({ onReadEntry: (e) => names.push(e.path) });
417
+ t.on("end", resolve);
418
+ t.on("error", reject);
419
+ R.from([Buffer.from(seen[0].data)]).pipe(t);
420
+ });
421
+ expect(names.sort()).toEqual([".gitignore", "main.js", "src/b.js"]);
422
+ expect(err).toContain("time left: 5m 0s");
423
+ });
424
+ it("refuses an archive over the limit with a clear message and uploads nothing", async () => {
425
+ await expect(new KilnPack(10).pack(dir)).rejects.toThrow(/over .* MiB/);
426
+ await expect(run("push", join(dir, "missing"), "m1", "--to", "/app")).rejects.toThrow("exit 1");
427
+ expect(err).toContain("is not a directory");
428
+ expect(seen).toHaveLength(0);
429
+ });
430
+ it("allows pushes up to 100 MiB by default", async () => {
431
+ await expect(new KilnPack(5 * 1024 * 1024 + 1).pack(dir)).resolves.toBeInstanceOf(Buffer);
432
+ const { KILN_ARCHIVE_LIMIT } = await import("../../lib/kilnPack.js");
433
+ expect(KILN_ARCHIVE_LIMIT).toBe(100 * 1024 * 1024);
434
+ });
435
+ });
436
+ describe("PROJECT_API_TOKEN inside a machine", () => {
437
+ beforeEach(() => {
438
+ process.env.PROJECT_API_TOKEN = "super-secret-token";
439
+ process.env.API_HOST = "http://api.machine/";
440
+ process.env.PROJECT_UUID = "proj-9";
441
+ });
442
+ it("authenticates with the token against API_HOST", async () => {
443
+ reply({ uuid: "m1" });
444
+ await run("machines", "get", "m1");
445
+ expect(seen[0].headers.Authorization).toBe("Bearer super-secret-token");
446
+ });
447
+ it("builds the profile from the three variables", async () => {
448
+ const { default: Real } = await vi.importActual("../../lib/util.js");
449
+ const p = Real.envProfile();
450
+ expect(p).toMatchObject({ host: "http://api.machine/", project: "proj-9", token: "super-secret-token" });
451
+ expect(JSON.stringify(p)).not.toContain("super-secret-token");
452
+ });
453
+ it("yields to an explicit --profile", async () => {
454
+ process.env.PTKL_ACTIVE_PROFILE = "p";
455
+ reply({ uuid: "m1" });
456
+ await run("machines", "get", "m1");
457
+ expect(seen[0].headers.Authorization).toBe("Bearer profile-token");
458
+ });
459
+ it("names API_HOST, not the token, when the host is missing", async () => {
460
+ delete process.env.API_HOST;
461
+ await expect(run("machines", "get", "m1")).rejects.toThrow();
462
+ expect(err).toContain("API_HOST");
463
+ expect(err).not.toContain("super-secret-token");
464
+ });
465
+ it("never prints the token", async () => {
466
+ reply({ uuid: "m1", name: "n", state: "running" });
467
+ await run("machines", "get", "m1");
468
+ expect(out + err).not.toContain("super-secret-token");
469
+ });
470
+ });
471
+ describe("ptkl kiln jobs", () => {
472
+ it("creates a job from flags, env as global keys", async () => {
473
+ reply({ uuid: "j1", name: "nightly" }, 201);
474
+ await run("jobs", "create", "--name", "nightly", "-m", "20", "--overlap", "queue", "--schedule", "0 3 * * *", "--timezone", "Europe/Belgrade", "--global-env", "TOKEN=NPM_KEY", "--run-as", "role:dev", "--size", "256", "--", "make", "all");
475
+ expect(seen[0].method).toBe("post");
476
+ expect(seen[0].url).toBe("/jobs");
477
+ expect(seen[0].data).toEqual({
478
+ name: "nightly", minutes: 20, overlap: "queue", schedule: "0 3 * * *", time_zone: "Europe/Belgrade",
479
+ env: { TOKEN: { global_env: "NPM_KEY" } }, run_as: "role:dev", size: 256, sequence: { command: ["make", "all"] },
480
+ });
481
+ });
482
+ it("refuses a literal --env-var and a missing or bad --overlap", async () => {
483
+ await expect(run("jobs", "create", "--name", "a", "-m", "5", "--overlap", "skip", "--env-var", "A=1")).rejects.toThrow("exit 1");
484
+ expect(err).toMatch(/global env keys/);
485
+ await expect(run("jobs", "create", "--name", "a", "-m", "5")).rejects.toThrow();
486
+ await expect(run("jobs", "create", "--name", "a", "-m", "5", "--overlap", "often")).rejects.toThrow("exit 1");
487
+ expect(seen).toHaveLength(0);
488
+ });
489
+ it("lists, gets and deletes by name or id", async () => {
490
+ reply({ jobs: [{ uuid: "j1" }] });
491
+ await run("jobs", "list");
492
+ expect(seen[0].url).toBe("/jobs");
493
+ reply({ uuid: "j1" });
494
+ await run("jobs", "get", "my job");
495
+ expect(seen[1].url).toBe("/jobs/my%20job");
496
+ reply("", 204);
497
+ await run("jobs", "delete", "nightly");
498
+ expect(seen[2].method).toBe("delete");
499
+ expect(seen[2].url).toBe("/jobs/nightly");
500
+ });
501
+ it("updates only the flags given, and an empty schedule is sent", async () => {
502
+ reply({ uuid: "j1" });
503
+ await run("jobs", "update", "nightly", "--schedule", "", "--disable", "--rename", "n2");
504
+ expect(seen[0].method).toBe("patch");
505
+ expect(seen[0].url).toBe("/jobs/nightly");
506
+ expect(seen[0].data).toEqual({ name: "n2", schedule: "", enabled: false });
507
+ await expect(run("jobs", "update", "nightly")).rejects.toThrow("exit 1");
508
+ });
509
+ it("starts a run with an Idempotency-Key and reads runs", async () => {
510
+ reply({ uuid: "r1", state: "starting" }, 202);
511
+ await run("jobs", "run", "nightly");
512
+ expect(seen[0].method).toBe("post");
513
+ expect(seen[0].url).toBe("/jobs/nightly/runs");
514
+ expect(seen[0].headers["Idempotency-Key"]).toBeTruthy();
515
+ reply({ runs: [{ uuid: "r1" }] });
516
+ await run("jobs", "runs", "nightly");
517
+ expect(seen[1].url).toBe("/jobs/nightly/runs");
518
+ reply({ uuid: "r1", exit_code: 0 });
519
+ await run("jobs", "run-get", "nightly", "r1");
520
+ expect(seen[2].url).toBe("/jobs/nightly/runs/r1");
521
+ });
522
+ });
@@ -34,7 +34,7 @@ const mocks = vi.hoisted(() => {
34
34
  client[m] = reply(m, d);
35
35
  return { calls, results, client };
36
36
  });
37
- vi.mock("../../lib/sdk.js", () => ({ kortex: () => mocks.client }));
37
+ vi.mock("../../lib/sdk.js", async (orig) => ({ ...(await orig()), kortex: () => mocks.client }));
38
38
  vi.mock("../../lib/util.js", () => ({
39
39
  default: { getCurrentProfile: () => ({ name: "test", host: "http://platform.test", token: "t", project: "p" }) },
40
40
  }));
@@ -11,6 +11,7 @@ import { dirname, extname, isAbsolute, join } from 'path';
11
11
  import { forgeDevKernelPlugin } from '../lib/forgeDevKernelPlugin.js';
12
12
  import { ForgeDevToken } from '../lib/forgeDevToken.js';
13
13
  import { ForgeDevServiceExec } from '../lib/forgeDevServiceExec.js';
14
+ import { ForgeDevPublicHost } from '../lib/forgeDevPublicHost.js';
14
15
  import { ForgeDevServiceServer } from '../lib/forgeDevServiceServer.js';
15
16
  import { kortexDevPlugin } from '../lib/kortexDevPlugin.js';
16
17
  import * as sdk from "../lib/sdk.js";
@@ -439,6 +440,7 @@ class ForgeCommand {
439
440
  .option("-m, --mode <mode>", "Vite mode (controls which .env.[mode] files are loaded). Defaults to 'development'.")
440
441
  .option("--env <env>", "Run for a specific env only (dev or live)")
441
442
  .option("--view <view>", "Which view to serve (defaults to 'main')")
443
+ .option("--public-host <host>", "Host name other machines use to reach this one (e.g. its Tailscale name). Off by default. With it, the dev page, the token it carries and the dev services are reachable from the network.")
442
444
  .action(this.runDev))
443
445
  .addCommand(new Command("setup")
444
446
  .description("Scaffold a new Forge app in a directory (ptkl.config.js, vite, index.html, entry, deps)")
@@ -927,6 +929,17 @@ class ForgeCommand {
927
929
  async runDev(options) {
928
930
  const { path: rawPath, platformUrl, mode, env, view: viewFlag } = options;
929
931
  const path = isAbsolute(rawPath) ? rawPath : join(process.cwd(), rawPath);
932
+ let publicHost;
933
+ try {
934
+ publicHost = new ForgeDevPublicHost(options.publicHost);
935
+ }
936
+ catch (err) {
937
+ console.error(`❌ ${err.message}`);
938
+ process.exit(1);
939
+ }
940
+ if (publicHost.enabled) {
941
+ console.warn(`⚠️ --public-host ${publicHost.name}: the dev page, its token and the dev services are reachable from the network.`);
942
+ }
930
943
  const host = Util.getCurrentProfile().host;
931
944
  // Load ptkl.config.js to discover views, services, and app name
932
945
  let appName;
@@ -953,8 +966,8 @@ class ForgeCommand {
953
966
  const { ensureHubRunning, pushBundle, DEV_HUB_PORT } = await import('../lib/devHub.js');
954
967
  const hubStatus = await ensureHubRunning();
955
968
  console.log(hubStatus === 'started'
956
- ? `🔌 Dev hub started on http://localhost:${DEV_HUB_PORT}`
957
- : `🔌 Reusing existing dev hub on http://localhost:${DEV_HUB_PORT}`);
969
+ ? `🔌 Dev hub started on ${publicHost.baseUrl(DEV_HUB_PORT)}`
970
+ : `🔌 Reusing existing dev hub on ${publicHost.baseUrl(DEV_HUB_PORT)}`);
958
971
  // Resolve the entry for the selected view
959
972
  const selectedView = viewFlag ?? 'main';
960
973
  let viewEntry;
@@ -997,6 +1010,7 @@ class ForgeCommand {
997
1010
  const server = await createServer({
998
1011
  root: path,
999
1012
  mode: mode ?? 'development',
1013
+ ...(publicHost.enabled ? { server: { host: true, allowedHosts: [publicHost.name] } } : {}),
1000
1014
  resolve: {
1001
1015
  // One React instance even when @ptkl/components is npm-linked (the
1002
1016
  // linked repo carries its own node_modules/react) — two copies break
@@ -1009,12 +1023,12 @@ class ForgeCommand {
1009
1023
  INTEGRATION_API: `${host}/luma/integrations`,
1010
1024
  PROJECT_API_TOKEN: Util.getCurrentProfile().token,
1011
1025
  PROJECT_ENV: env ?? "dev",
1012
- ...(servicePort ? { FORGE_DEV_SERVICE_URL: `http://localhost:${servicePort}` } : {}),
1026
+ ...(servicePort ? { FORGE_DEV_SERVICE_URL: publicHost.baseUrl(servicePort) } : {}),
1013
1027
  }),
1014
1028
  DEV_HUB_PORT
1015
1029
  },
1016
1030
  plugins: [
1017
- forgeDevKernelPlugin(appName, platformUrl, DEV_HUB_PORT, env ?? 'dev', host, pageToken),
1031
+ forgeDevKernelPlugin(appName, platformUrl, DEV_HUB_PORT, env ?? 'dev', host, pageToken, publicHost),
1018
1032
  kortexDevPlugin({
1019
1033
  host,
1020
1034
  token: Util.getCurrentProfile().token,
@@ -1080,7 +1094,9 @@ class ForgeCommand {
1080
1094
  });
1081
1095
  await server.listen();
1082
1096
  console.log('Current profile:', Util.getCurrentProfile().name);
1083
- console.log(`Dev server running at: ${server?.resolvedUrls?.local[0]}${viewFlag ? ` (view: ${selectedView})` : ''}`);
1097
+ const localUrl = server?.resolvedUrls?.local[0];
1098
+ const serverUrl = publicHost.enabled && localUrl ? publicHost.baseUrl(Number(new URL(localUrl).port)) + '/' : localUrl;
1099
+ console.log(`Dev server running at: ${serverUrl}${viewFlag ? ` (view: ${selectedView})` : ''}`);
1084
1100
  // Build every view declared in ptkl.config.js in watch mode.
1085
1101
  // On each successful rebuild the bundle is pushed to the dev hub so any
1086
1102
  // other locally-running app that embeds this view via AppView picks it up instantly.
@@ -1262,10 +1278,11 @@ class ForgeCommand {
1262
1278
  services: services,
1263
1279
  bundles: serviceBundles,
1264
1280
  exec: serviceExec,
1281
+ publicHost,
1265
1282
  }).listen(() => {
1266
- console.log(`\n⚡ Service dev server running at http://localhost:${SERVICE_PORT}`);
1283
+ console.log(`\n⚡ Service dev server running at ${publicHost.baseUrl(SERVICE_PORT)}`);
1267
1284
  for (const svc of services) {
1268
- console.log(` POST http://localhost:${SERVICE_PORT}/${svc.name}`);
1285
+ console.log(` POST ${publicHost.baseUrl(SERVICE_PORT)}/${svc.name}`);
1269
1286
  }
1270
1287
  console.log('');
1271
1288
  });