@lizard-build/cli 4.0.129 → 4.0.131
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/.github/workflows/release.yml +14 -0
- package/dist/commands/gha.d.ts +14 -0
- package/dist/commands/gha.js +13 -2
- package/dist/commands/gha.js.map +1 -1
- package/dist/commands/run.js +13 -2
- package/dist/commands/run.js.map +1 -1
- package/dist/commands/sandbox-schedules.d.ts +40 -0
- package/dist/commands/sandbox-schedules.js +61 -2
- package/dist/commands/sandbox-schedules.js.map +1 -1
- package/dist/commands/sandbox.js +37 -3
- package/dist/commands/sandbox.js.map +1 -1
- package/dist/lib/checkout.d.ts +5 -0
- package/dist/lib/checkout.js +92 -16
- package/dist/lib/checkout.js.map +1 -1
- package/dist/lib/env-guard.d.ts +1 -0
- package/dist/lib/env-guard.js +37 -0
- package/dist/lib/env-guard.js.map +1 -0
- package/dist/lib/skills-data.generated.js +1 -1
- package/dist/lib/skills-data.generated.js.map +1 -1
- package/dist/lib/updater.d.ts +10 -1
- package/dist/lib/updater.js +33 -2
- package/dist/lib/updater.js.map +1 -1
- package/package.json +1 -1
- package/scripts/sign-release.mjs +36 -0
- package/skill-data/core/references/sandboxes.md +12 -3
- package/src/commands/gha.ts +16 -2
- package/src/commands/run.ts +12 -2
- package/src/commands/sandbox-schedules.ts +58 -2
- package/src/commands/sandbox.ts +36 -3
- package/src/lib/checkout.ts +83 -14
- package/src/lib/env-guard.ts +37 -0
- package/src/lib/updater.ts +32 -2
- package/test/unit/checkout-symlink.test.ts +103 -0
- package/test/unit/env-guard.test.ts +26 -0
- package/test/unit/release-signature.test.ts +39 -0
|
@@ -75,6 +75,57 @@ function addTaskOptions(c: Command, forCreate: boolean) {
|
|
|
75
75
|
.option("--name <name>", "A label for the schedule");
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
+
/**
|
|
79
|
+
* The schedule options of `lizard sandbox create`: a schedule is set when a sandbox is created.
|
|
80
|
+
* The same options as `sandbox schedule`, except the two whose names `create` already uses for
|
|
81
|
+
* the sandbox itself: --run-timeout (create's --timeout is the sandbox's lifetime) and
|
|
82
|
+
* --schedule-name.
|
|
83
|
+
*/
|
|
84
|
+
export function addCreateScheduleOptions(c: Command): Command {
|
|
85
|
+
return c
|
|
86
|
+
.option("--every <interval>", "Schedule: wake the sandbox this often and run --command or --prompt (1m minimum, e.g. 5m, 1h, 1d)")
|
|
87
|
+
.option("--cron <expr>", 'Schedule by cron instead: "m h dom mon dow", e.g. "0 9 * * mon-fri", @daily')
|
|
88
|
+
.option("--tz <zone>", "Time zone for --cron (IANA name, e.g. Europe/Berlin)")
|
|
89
|
+
.option("--command <cmd>", "Schedule: run this shell command (in /workspace, as root)")
|
|
90
|
+
.option("--prompt <text>", "Schedule: run the coding agent with this prompt, a new conversation each run (needs an agent template: -t claude, codex, ...)")
|
|
91
|
+
.option("--prompt-file <path>", "Schedule: read the prompt from a file")
|
|
92
|
+
.option("--agent <agent>", "Agent for --prompt (codex, claude, ...)")
|
|
93
|
+
.option("-m, --model <model>", "Model for --prompt")
|
|
94
|
+
.option("--effort <level>", "Reasoning effort for --prompt (minimal, low, medium, high, xhigh)")
|
|
95
|
+
.option("--run-timeout <duration>", "Schedule: stop a run after this long (default 10m)", parseDuration)
|
|
96
|
+
.option("--schedule-name <name>", "A label for the schedule");
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The schedule a `sandbox create` asked for, checked before anything is created; null: none. */
|
|
100
|
+
export function createScheduleBody(opts: Record<string, any>): Record<string, unknown> | null {
|
|
101
|
+
const timing = !!(opts.every || opts.cron);
|
|
102
|
+
const task = !!(opts.prompt || opts.promptFile || opts.command);
|
|
103
|
+
const extras = ["tz", "agent", "model", "effort", "runTimeout", "scheduleName"].filter((k) => opts[k] !== undefined);
|
|
104
|
+
if (!timing && !task) {
|
|
105
|
+
if (extras.length) fail("These options belong to a schedule: add --every 10m (or --cron) and --command \"...\" (or --prompt)", 2, "USAGE");
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
if (!timing) fail("Say how often the schedule runs: --every 5m, or --cron \"*/5 * * * *\"", 2, "USAGE");
|
|
109
|
+
if (!task) fail("Say what the schedule runs: --command \"...\" or --prompt \"...\"", 2, "USAGE");
|
|
110
|
+
return taskBody({ ...opts, timeout: opts.runTimeout, name: opts.scheduleName });
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Sets the schedule on a sandbox that was just created. The created schedule, or the error text. */
|
|
114
|
+
export async function scheduleNewSandbox(sandboxId: string, body: Record<string, unknown>): Promise<{ schedule?: Schedule; error?: string }> {
|
|
115
|
+
// The sandbox's row lands a moment after its create answers: one retry.
|
|
116
|
+
for (let attempt = 0; ; attempt++) {
|
|
117
|
+
try {
|
|
118
|
+
return { schedule: await api.post<Schedule>(`/api/sandboxes/${sandboxId}/schedules`, body) };
|
|
119
|
+
} catch (e: any) {
|
|
120
|
+
if (attempt === 0 && e?.status === 404) { await new Promise((r) => setTimeout(r, 1500)); continue; }
|
|
121
|
+
return { error: String(e?.message ?? e) };
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** One line for `sandbox create`'s output. */
|
|
127
|
+
export const scheduleLine = (s: Schedule) => `${s.id}: ${when(s)}${s.nextRunAt ? `, first run ${inFuture(s.nextRunAt)}` : ""}`;
|
|
128
|
+
|
|
78
129
|
function taskBody(opts: Record<string, any>): Record<string, unknown> {
|
|
79
130
|
const body: Record<string, unknown> = {};
|
|
80
131
|
if (opts.every) body.every = opts.every;
|
|
@@ -96,7 +147,7 @@ export function registerSandboxScheduleCommands(sb: Command) {
|
|
|
96
147
|
addTaskOptions(
|
|
97
148
|
sb.command("schedule")
|
|
98
149
|
.argument("<id>", "Sandbox ID")
|
|
99
|
-
.description("
|
|
150
|
+
.description("Set a schedule on a sandbox you just created (its first 15 minutes): wake it, run a prompt or command, put it back to sleep. Usually set at creation: lizard sandbox create --every ... --command ..."),
|
|
100
151
|
true,
|
|
101
152
|
)
|
|
102
153
|
.option("--disabled", "Create it switched off")
|
|
@@ -108,6 +159,11 @@ left running. You pay only while it is awake. Files in /workspace carry over bet
|
|
|
108
159
|
A run that is still going when the next one is due makes that one skip. Five failed runs in
|
|
109
160
|
a row switch the schedule off.
|
|
110
161
|
|
|
162
|
+
A schedule is set when a sandbox is created: \`lizard sandbox create --every 10m --command "..."\`
|
|
163
|
+
does both. This command works on a sandbox created in the last 15 minutes; an older one takes no
|
|
164
|
+
new schedule (SCHEDULE_ONLY_AT_CREATE), though its schedules can still be changed (schedule-set),
|
|
165
|
+
run (schedule-run) and deleted (unschedule).
|
|
166
|
+
|
|
111
167
|
Examples:
|
|
112
168
|
lizard sandbox schedule sb_abc123 --every 5m --prompt "Continue the research in /workspace/research; append findings to notes.md"
|
|
113
169
|
lizard sandbox schedule sb_abc123 --every 10m --command "python3 /workspace/job.py"
|
|
@@ -132,7 +188,7 @@ Examples:
|
|
|
132
188
|
? await api.get<{ schedules: Schedule[] }>(`/api/sandboxes/${id}/schedules`)
|
|
133
189
|
: await api.get<{ schedules: Schedule[] }>(`/api/sandbox-schedules`);
|
|
134
190
|
if (isJSONMode()) return printJSON(schedules);
|
|
135
|
-
if (!schedules.length) return info("No schedules.
|
|
191
|
+
if (!schedules.length) return info("No schedules. One is set when a sandbox is created: lizard sandbox create --every 10m --command \"...\"");
|
|
136
192
|
table(["id", "sandbox", "when", "runs", "next", "last"], schedules.map((s) => [
|
|
137
193
|
s.id, s.sandboxId, when(s), what(s),
|
|
138
194
|
!s.enabled ? chalk.dim("off") : s.running ? chalk.yellow("running") : s.nextRunAt ? inFuture(s.nextRunAt) : "-",
|
package/src/commands/sandbox.ts
CHANGED
|
@@ -14,7 +14,7 @@ import { resolveVolume } from "../lib/volume.js";
|
|
|
14
14
|
import { sandboxShell } from "./sandbox-ssh.js";
|
|
15
15
|
import { startVncTunnel, vncTarget } from "./sandbox-vnc.js";
|
|
16
16
|
import { registerSandboxAgentCommands } from "./agents.js";
|
|
17
|
-
import { registerSandboxScheduleCommands } from "./sandbox-schedules.js";
|
|
17
|
+
import { registerSandboxScheduleCommands, addCreateScheduleOptions, createScheduleBody, scheduleNewSandbox, scheduleLine } from "./sandbox-schedules.js";
|
|
18
18
|
import { success, info, warn, error, isJSONMode, printJSON, table, statusColor, timeAgo, isTTY } from "../lib/format.js";
|
|
19
19
|
|
|
20
20
|
// Templates are per-region rows in sandbox_templates, not a constant. Hardcoding them
|
|
@@ -178,7 +178,7 @@ export function registerSandbox(program: Command) {
|
|
|
178
178
|
.alias("sb")
|
|
179
179
|
.description("Manage ephemeral compute sandboxes");
|
|
180
180
|
|
|
181
|
-
sb.command("create")
|
|
181
|
+
addCreateScheduleOptions(sb.command("create")
|
|
182
182
|
.description("Create a sandbox")
|
|
183
183
|
.option("-t, --template <name>", `Template (${TEMPLATE_HINT}; server validates)`, "base")
|
|
184
184
|
.addOption(new Option("-s, --size <size>", `Machine size (${SIZE_HINT}); default medium, small on the Pro trial (1 Small, 2 Mini and 2 Nano at a time, US regions only; Medium, Large and Big unlock after the first payment). Mini works only with the ${MINI_TEMPLATES} templates, Nano only with ${NANO_TEMPLATES}`).choices(SANDBOX_SIZES))
|
|
@@ -193,7 +193,19 @@ export function registerSandbox(program: Command) {
|
|
|
193
193
|
.option("--proxy <url>", "Send all of the sandbox's internet traffic through your proxy, any supplier: http://user:pass@host:port or socks5://user:pass@host:port. See `lizard sandbox proxy --help`")
|
|
194
194
|
.option("--repo <owner/name>", "Start with this GitHub repository cloned into /workspace/<name>; the sandbox can push and open pull requests to it (only it). Needs GitHub connected and Lizard's GitHub App on the repository's owner")
|
|
195
195
|
.option("--repo-workflows", "With --repo: may also change .github/workflows")
|
|
196
|
+
.option("-e, --environment <name>", "Start with the variables of this sandbox environment of the project (Sandboxes → Environment) instead of its default ones"))
|
|
197
|
+
.addHelpText("after", `
|
|
198
|
+
A schedule is set here, when the sandbox is created:
|
|
199
|
+
lizard sandbox create --timeout 0 --every 10m --command "python3 /workspace/job.py"
|
|
200
|
+
lizard sandbox create -t claude --timeout 0 --cron "0 9 * * mon-fri" --tz Europe/Berlin --prompt "Write today's report to /workspace/report.md"
|
|
201
|
+
Each run wakes the sandbox, runs the command or prompt, and puts it back to sleep (files only).
|
|
202
|
+
A prompt needs a sandbox from an agent template (claude, codex, opencode, pi, prime).`)
|
|
196
203
|
.action(async (opts) => {
|
|
204
|
+
const scheduleBody = createScheduleBody(opts);
|
|
205
|
+
// Refused before anything is created: the server only finds out once the sandbox runs.
|
|
206
|
+
if (scheduleBody?.prompt && !opts.snapshot && ["base", "interpreter"].includes(opts.template)) {
|
|
207
|
+
throw new Error(`--prompt needs a sandbox with a coding agent, and the '${opts.template}' template has none. Add -t claude (or codex, opencode, pi, prime), or schedule a --command instead.`);
|
|
208
|
+
}
|
|
197
209
|
// A snapshot restores at its source's size (a Firecracker VM's memory is part of it; a
|
|
198
210
|
// pod snapshot goes back onto the machine it was captured on), so the server ignores a
|
|
199
211
|
// size alongside it. Say so rather than quietly creating something other than asked.
|
|
@@ -273,6 +285,7 @@ export function registerSandbox(program: Command) {
|
|
|
273
285
|
...(opts.allowHost?.length ? { allowedHosts: opts.allowHost } : {}),
|
|
274
286
|
...(opts.proxy ? { proxy: opts.proxy } : {}),
|
|
275
287
|
...(opts.repo ? { repo: opts.repo, repoWorkflows: !!opts.repoWorkflows } : {}),
|
|
288
|
+
...(opts.environment ? { environment: opts.environment } : {}),
|
|
276
289
|
};
|
|
277
290
|
try {
|
|
278
291
|
sandbox = await createInDefaultRegion(body, defaultRegion);
|
|
@@ -313,8 +326,20 @@ export function registerSandbox(program: Command) {
|
|
|
313
326
|
throw new Error("This region's platform does not support --proxy yet; the sandbox it started went out directly and was deleted.");
|
|
314
327
|
}
|
|
315
328
|
|
|
329
|
+
// A platform that predates environments ignores the option: the sandbox would start with
|
|
330
|
+
// the project's default variables, not the ones asked for, so it is deleted.
|
|
331
|
+
if (opts.environment && opts.environment.trim().toLowerCase() !== "default" && !(sandbox as any).environment) {
|
|
332
|
+
await api.delete(`/api/sandboxes/${sandbox.id}`).catch(() => {});
|
|
333
|
+
throw new Error("This region's platform does not support --environment yet; the sandbox it started had the project's default variables and was deleted.");
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// The schedule, right after the create. If it is refused the sandbox stays: it works, and
|
|
337
|
+
// the schedule can be set again in its first 15 minutes.
|
|
338
|
+
const scheduled = scheduleBody ? await scheduleNewSandbox(sandbox.id, scheduleBody) : null;
|
|
339
|
+
|
|
316
340
|
if (isJSONMode()) {
|
|
317
|
-
printJSON(sandbox);
|
|
341
|
+
printJSON(scheduled ? { ...sandbox, schedule: scheduled.schedule ?? null, ...(scheduled.error ? { scheduleError: scheduled.error } : {}) } : sandbox);
|
|
342
|
+
if (scheduled?.error) process.exitCode = 1;
|
|
318
343
|
return;
|
|
319
344
|
}
|
|
320
345
|
success(`Sandbox ${chalk.bold(sandbox.id)} created`);
|
|
@@ -339,6 +364,14 @@ export function registerSandbox(program: Command) {
|
|
|
339
364
|
else info(chalk.dim(` Repo: ${r.fullName} -> ${r.path}${r.status === "cloning" ? " (still cloning)" : ""}`));
|
|
340
365
|
if (r.readOnly) info(chalk.yellow(` Read only: GitHub has not given Lizard write access on this account yet. Accept it at ${r.manageUrl}`));
|
|
341
366
|
}
|
|
367
|
+
const usedEnvironment = (sandbox as any).environment as { name: string } | undefined;
|
|
368
|
+
if (usedEnvironment) info(chalk.dim(` Environment: ${usedEnvironment.name}`));
|
|
369
|
+
if (scheduled?.schedule) info(chalk.dim(` Schedule: ${scheduleLine(scheduled.schedule)}`));
|
|
370
|
+
if (scheduled?.error) {
|
|
371
|
+
warn(`The sandbox was created, but its schedule was not: ${scheduled.error}`);
|
|
372
|
+
info(chalk.dim(` Set it within 15 minutes: lizard sandbox schedule ${sandbox.id} --every ... --command "..."`));
|
|
373
|
+
process.exitCode = 1;
|
|
374
|
+
}
|
|
342
375
|
info("");
|
|
343
376
|
info(sandboxNextSteps(sandbox.id));
|
|
344
377
|
});
|
package/src/lib/checkout.ts
CHANGED
|
@@ -233,18 +233,58 @@ function safeJoin(root: string, p: string): string {
|
|
|
233
233
|
return join(root, ...p.split("/"));
|
|
234
234
|
}
|
|
235
235
|
|
|
236
|
-
|
|
236
|
+
/** A working-file path one of whose folders is a symlink: writing or deleting it would act outside the checkout. */
|
|
237
|
+
export class UnsafePathError extends APIError {
|
|
238
|
+
constructor(p: string, link: string) {
|
|
239
|
+
super(400, `refusing ${p}: ${link} is a symlink, and the file would be written through it (outside the checkout)`, "UNSAFE_PATH");
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* safeJoin, and every folder between the checkout and the file must be a real folder (or not
|
|
245
|
+
* exist yet). A repository can hold a symlink `d -> ~/.ssh` and, in a later commit, a file
|
|
246
|
+
* `d/authorized_keys`: written blindly, that file lands wherever the link points.
|
|
247
|
+
*/
|
|
248
|
+
function safeTarget(root: string, p: string): string {
|
|
237
249
|
const full = safeJoin(root, p);
|
|
238
|
-
|
|
250
|
+
const parts = p.split("/");
|
|
251
|
+
let d = root;
|
|
252
|
+
for (const part of parts.slice(0, -1)) {
|
|
253
|
+
d = join(d, part);
|
|
254
|
+
let st;
|
|
255
|
+
try {
|
|
256
|
+
st = lstatSync(d);
|
|
257
|
+
} catch {
|
|
258
|
+
break; // missing: mkdir makes real folders from here on
|
|
259
|
+
}
|
|
260
|
+
if (st.isSymbolicLink()) throw new UnsafePathError(p, relative(root, d));
|
|
261
|
+
}
|
|
262
|
+
return full;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Remove whatever is at full (file, symlink or folder) without following a symlink. */
|
|
266
|
+
function clearPath(full: string): void {
|
|
239
267
|
try {
|
|
240
268
|
const st = lstatSync(full);
|
|
241
269
|
if (st.isDirectory()) rmSync(full, { recursive: true });
|
|
242
270
|
else unlinkSync(full);
|
|
243
271
|
} catch {}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Write a regular file at full, never through a symlink already there. */
|
|
275
|
+
function writeNoFollow(full: string, content: Buffer): void {
|
|
276
|
+
clearPath(full);
|
|
277
|
+
writeFileSync(full, content, { flag: "wx" }); // fails rather than follow a link that appeared
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function writeFile(root: string, p: string, content: Buffer, mode: string): FileState {
|
|
281
|
+
const full = safeTarget(root, p);
|
|
282
|
+
mkdirSync(dirname(full), { recursive: true });
|
|
244
283
|
if (mode === "120000") {
|
|
284
|
+
clearPath(full);
|
|
245
285
|
symlinkSync(content.toString(), full);
|
|
246
286
|
} else {
|
|
247
|
-
|
|
287
|
+
writeNoFollow(full, content);
|
|
248
288
|
chmodSync(full, mode === "100755" ? 0o755 : 0o644);
|
|
249
289
|
}
|
|
250
290
|
const st = lstatSync(full);
|
|
@@ -256,7 +296,13 @@ export function removeFileAt(root: string, p: string): void {
|
|
|
256
296
|
}
|
|
257
297
|
|
|
258
298
|
function removeFile(root: string, p: string): void {
|
|
259
|
-
|
|
299
|
+
let full: string;
|
|
300
|
+
try {
|
|
301
|
+
full = safeTarget(root, p);
|
|
302
|
+
} catch (e) {
|
|
303
|
+
if (e instanceof UnsafePathError) return; // never delete through a symlinked folder
|
|
304
|
+
throw e;
|
|
305
|
+
}
|
|
260
306
|
try {
|
|
261
307
|
unlinkSync(full);
|
|
262
308
|
} catch {}
|
|
@@ -447,6 +493,19 @@ export async function sync(root: string, c: Checkout, toBranch?: string): Promis
|
|
|
447
493
|
const clashSet = new Set(clash);
|
|
448
494
|
const merged: string[] = [];
|
|
449
495
|
const conflicts: Conflict[] = [];
|
|
496
|
+
// Removals first: a symlink the branch deleted must be gone before a file is written under
|
|
497
|
+
// its name (else the file lands where the link pointed).
|
|
498
|
+
for (const p of toRemove) {
|
|
499
|
+
if (clashSet.has(p)) continue;
|
|
500
|
+
if (!dirty.has(p)) removeFile(root, p);
|
|
501
|
+
delete c.files[p];
|
|
502
|
+
res.removed.push(p);
|
|
503
|
+
}
|
|
504
|
+
const unsafe = (p: string, e: unknown): boolean => {
|
|
505
|
+
if (!(e instanceof UnsafePathError)) return false;
|
|
506
|
+
conflicts.push({ path: p, reason: e.message });
|
|
507
|
+
return true;
|
|
508
|
+
};
|
|
450
509
|
if (clash.length) {
|
|
451
510
|
const need = new Set<string>();
|
|
452
511
|
for (const p of clash) {
|
|
@@ -465,7 +524,12 @@ export async function sync(root: string, c: Checkout, toBranch?: string): Promis
|
|
|
465
524
|
}
|
|
466
525
|
if (!l) {
|
|
467
526
|
// Deleted here, changed on the branch: theirs comes back; deleting it again is one rm away.
|
|
468
|
-
|
|
527
|
+
try {
|
|
528
|
+
c.files[p] = writeFile(root, p, got.get(w!.h)!, w!.m);
|
|
529
|
+
} catch (e) {
|
|
530
|
+
if (unsafe(p, e)) continue;
|
|
531
|
+
throw e;
|
|
532
|
+
}
|
|
469
533
|
conflicts.push({ path: p, reason: `you deleted it, ${branch} changed it: their version is back (delete it again if you meant to)` });
|
|
470
534
|
continue;
|
|
471
535
|
}
|
|
@@ -475,13 +539,19 @@ export async function sync(root: string, c: Checkout, toBranch?: string): Promis
|
|
|
475
539
|
conflicts.push({ path: p, reason: `${branch} deleted it, you changed it: your version is kept` });
|
|
476
540
|
continue;
|
|
477
541
|
}
|
|
478
|
-
|
|
542
|
+
let full: string;
|
|
543
|
+
try {
|
|
544
|
+
full = safeTarget(root, p);
|
|
545
|
+
} catch (e) {
|
|
546
|
+
if (unsafe(p, e)) continue;
|
|
547
|
+
throw e;
|
|
548
|
+
}
|
|
479
549
|
const ours = l.m === "120000" ? Buffer.from(readlinkSync(full)) : readFileSync(full);
|
|
480
550
|
const base = baseF ? got.get(baseF.h)! : Buffer.alloc(0);
|
|
481
551
|
const theirs = got.get(w.h)!;
|
|
482
552
|
c.files[p] = { h: w.h, m: w.m }; // the branch's version is what yours now differs from
|
|
483
553
|
if (l.m === "120000" || w.m === "120000" || isBinaryBuf(base) || isBinaryBuf(ours) || isBinaryBuf(theirs)) {
|
|
484
|
-
|
|
554
|
+
writeNoFollow(full + ".theirs", theirs);
|
|
485
555
|
conflicts.push({ path: p, reason: `binary, changed on both sides: yours kept, theirs saved as ${p}.theirs` });
|
|
486
556
|
continue;
|
|
487
557
|
}
|
|
@@ -499,15 +569,14 @@ export async function sync(root: string, c: Checkout, toBranch?: string): Promis
|
|
|
499
569
|
c.files[p] = { ...local.get(p)!, h: f.h, m: f.m }; // already identical locally
|
|
500
570
|
continue;
|
|
501
571
|
}
|
|
502
|
-
|
|
572
|
+
try {
|
|
573
|
+
c.files[p] = writeFile(root, p, blobs.get(f.h)!, f.m);
|
|
574
|
+
} catch (e) {
|
|
575
|
+
if (unsafe(p, e)) continue;
|
|
576
|
+
throw e;
|
|
577
|
+
}
|
|
503
578
|
res.updated.push(p);
|
|
504
579
|
}
|
|
505
|
-
for (const p of toRemove) {
|
|
506
|
-
if (clashSet.has(p)) continue;
|
|
507
|
-
if (!dirty.has(p)) removeFile(root, p);
|
|
508
|
-
delete c.files[p];
|
|
509
|
-
res.removed.push(p);
|
|
510
|
-
}
|
|
511
580
|
c.base = r.id;
|
|
512
581
|
c.root = r.root;
|
|
513
582
|
c.branch = branch;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Variables that change how a program starts rather than what it does: a loader to preload, code
|
|
3
|
+
* a shell or runtime runs first, where commands are looked up, git config and helpers.
|
|
4
|
+
* `lizard run` puts a project's variables into a command on this machine, and anyone who can
|
|
5
|
+
* edit the project's variables could set these to run code here; so they are not set locally
|
|
6
|
+
* (they still apply to the service on Lizard).
|
|
7
|
+
*/
|
|
8
|
+
const EXACT = new Set([
|
|
9
|
+
"NODE_OPTIONS",
|
|
10
|
+
"NODE_PATH",
|
|
11
|
+
"BASH_ENV",
|
|
12
|
+
"ENV",
|
|
13
|
+
"PROMPT_COMMAND",
|
|
14
|
+
"PATH",
|
|
15
|
+
"PYTHONSTARTUP",
|
|
16
|
+
"PYTHONPATH",
|
|
17
|
+
"PYTHONHOME",
|
|
18
|
+
"PERL5OPT",
|
|
19
|
+
"PERL5LIB",
|
|
20
|
+
"RUBYOPT",
|
|
21
|
+
"RUBYLIB",
|
|
22
|
+
"GIT_EXEC_PATH",
|
|
23
|
+
"GIT_ASKPASS",
|
|
24
|
+
"SSH_ASKPASS",
|
|
25
|
+
"SHELLOPTS",
|
|
26
|
+
"BASHOPTS",
|
|
27
|
+
"IFS",
|
|
28
|
+
"JAVA_TOOL_OPTIONS",
|
|
29
|
+
"_JAVA_OPTIONS",
|
|
30
|
+
"ZDOTDIR",
|
|
31
|
+
]);
|
|
32
|
+
const PREFIXES = ["LD_", "DYLD_", "GIT_CONFIG", "GIT_SSH", "BASH_FUNC_"];
|
|
33
|
+
|
|
34
|
+
export function isStartupEnvName(name: string): boolean {
|
|
35
|
+
const n = process.platform === "win32" ? name.toUpperCase() : name;
|
|
36
|
+
return EXACT.has(n) || PREFIXES.some((p) => n.startsWith(p));
|
|
37
|
+
}
|
package/src/lib/updater.ts
CHANGED
|
@@ -4,11 +4,34 @@ import { Readable } from "node:stream";
|
|
|
4
4
|
import { join, dirname } from "node:path";
|
|
5
5
|
import os from "node:os";
|
|
6
6
|
import { spawn } from "node:child_process";
|
|
7
|
+
import { createPublicKey, verify } from "node:crypto";
|
|
7
8
|
|
|
8
|
-
export const CURRENT_VERSION = "4.0.
|
|
9
|
+
export const CURRENT_VERSION = "4.0.131";
|
|
9
10
|
const RELEASES_API = "https://api.github.com/repos/lizard-build/lizard-cli/releases/latest";
|
|
10
11
|
const RELEASE_BASE = "https://github.com/lizard-build/lizard-cli/releases/latest/download";
|
|
11
12
|
|
|
13
|
+
/**
|
|
14
|
+
* The key every release binary is signed with (Ed25519; the release workflow signs with the
|
|
15
|
+
* private half, a GitHub Actions secret, and publishes `<asset>.sig`: the signature in base64).
|
|
16
|
+
* An update is installed only if its signature checks out against this key, so a release asset
|
|
17
|
+
* swapped by anyone without the key (a leaked GitHub token, a tampered download) is refused.
|
|
18
|
+
*/
|
|
19
|
+
export const RELEASE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
|
20
|
+
MCowBQYDK2VwAyEALrK9fMg2zspZJZpIx5bZi69eIpRYsXMsC2uYPZ97d/w=
|
|
21
|
+
-----END PUBLIC KEY-----
|
|
22
|
+
`;
|
|
23
|
+
|
|
24
|
+
/** Does sigB64 (the text of `<asset>.sig`) sign data with the release key? */
|
|
25
|
+
export function verifyReleaseSignature(data: Uint8Array, sigB64: string, publicKeyPem = RELEASE_PUBLIC_KEY): boolean {
|
|
26
|
+
const sig = Buffer.from(sigB64.trim(), "base64");
|
|
27
|
+
if (sig.length !== 64) return false;
|
|
28
|
+
try {
|
|
29
|
+
return verify(null, data, createPublicKey(publicKeyPem), sig);
|
|
30
|
+
} catch {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
12
35
|
/** Minimum gap between background update checks. */
|
|
13
36
|
const CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000; // 6h
|
|
14
37
|
|
|
@@ -143,9 +166,16 @@ export async function selfUpdate(onProgress?: (msg: string) => void): Promise<bo
|
|
|
143
166
|
try {
|
|
144
167
|
const res = await fetch(url, { signal: AbortSignal.timeout(60000) });
|
|
145
168
|
if (!res.ok) throw new Error(`Download failed: ${res.status}`);
|
|
169
|
+
const sigRes = await fetch(`${url}.sig`, { signal: AbortSignal.timeout(15000) });
|
|
170
|
+
if (!sigRes.ok) throw new Error(`No signature for ${binaryName} (${sigRes.status}): not installing it`);
|
|
171
|
+
const sig = await sigRes.text();
|
|
146
172
|
|
|
147
|
-
const writer = createWriteStream(tmp);
|
|
173
|
+
const writer = createWriteStream(tmp, { mode: 0o600 });
|
|
148
174
|
await pipeline(Readable.fromWeb(res.body as any), writer);
|
|
175
|
+
// Check what is on disk, the bytes that would run.
|
|
176
|
+
if (!verifyReleaseSignature(readFileSync(tmp), sig)) {
|
|
177
|
+
throw new Error(`${binaryName}: the signature does not match Lizard's release key; not installing it`);
|
|
178
|
+
}
|
|
149
179
|
chmodSync(tmp, 0o755);
|
|
150
180
|
|
|
151
181
|
onProgress?.("Installing...");
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";
|
|
2
|
+
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, symlinkSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { saveCheckout, sha256, sync, type Checkout } from "../../src/lib/checkout.js";
|
|
6
|
+
|
|
7
|
+
// A fake Lizard Git that serves one changeset: `tree` maps paths to contents (a symlink is
|
|
8
|
+
// { link: target }). Trees are addressed by a made-up hash, blobs by their sha256.
|
|
9
|
+
function serve(tree: Record<string, string | { link: string }>, older: string[] = []) {
|
|
10
|
+
const trees: Record<string, any[]> = {};
|
|
11
|
+
const blobs: Record<string, string> = {};
|
|
12
|
+
for (const b of older) blobs[sha256(b)] = Buffer.from(b).toString("base64"); // contents of the base changeset
|
|
13
|
+
let n = 0;
|
|
14
|
+
const build = (prefix: string): string => {
|
|
15
|
+
const names = new Set<string>();
|
|
16
|
+
for (const p of Object.keys(tree)) if (p.startsWith(prefix)) names.add(p.slice(prefix.length).split("/")[0]);
|
|
17
|
+
const entries = [...names].sort().map((name) => {
|
|
18
|
+
const full = prefix + name;
|
|
19
|
+
const v = tree[full];
|
|
20
|
+
if (v === undefined) return { name, mode: "040000", type: "tree", hash: build(full + "/"), size: 0 };
|
|
21
|
+
const body = typeof v === "string" ? v : v.link;
|
|
22
|
+
const h = sha256(body);
|
|
23
|
+
blobs[h] = Buffer.from(body).toString("base64");
|
|
24
|
+
return { name, mode: typeof v === "string" ? "100644" : "120000", type: "blob", hash: h, size: body.length };
|
|
25
|
+
});
|
|
26
|
+
const h = `tree${n++}`.padEnd(64, "0");
|
|
27
|
+
trees[h] = entries;
|
|
28
|
+
return h;
|
|
29
|
+
};
|
|
30
|
+
const root = build("");
|
|
31
|
+
vi.stubGlobal("fetch", vi.fn(async (url: string, init: any) => {
|
|
32
|
+
if (url.includes("/resolve")) return new Response(JSON.stringify({ id: "c".repeat(64), root }), { status: 200 });
|
|
33
|
+
if (url.endsWith("/objects")) {
|
|
34
|
+
const req = JSON.parse(init.body);
|
|
35
|
+
const out = { trees: {} as any, blobs: {} as any, fetchSeparately: [] };
|
|
36
|
+
for (const h of req.trees) out.trees[h] = trees[h];
|
|
37
|
+
for (const h of req.blobs) out.blobs[h] = blobs[h];
|
|
38
|
+
return new Response(JSON.stringify(out), { status: 200 });
|
|
39
|
+
}
|
|
40
|
+
return new Response("{}", { status: 404 });
|
|
41
|
+
}));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
let outside: string;
|
|
45
|
+
let root: string;
|
|
46
|
+
beforeEach(() => {
|
|
47
|
+
vi.stubEnv("LIZARD_GIT_CACHE", mkdtempSync(join(tmpdir(), "lzg-cache-")));
|
|
48
|
+
vi.stubEnv("LIZARD_TOKEN", "liz_test");
|
|
49
|
+
outside = mkdtempSync(join(tmpdir(), "lzg-outside-"));
|
|
50
|
+
root = mkdtempSync(join(tmpdir(), "lzg-root-"));
|
|
51
|
+
});
|
|
52
|
+
afterEach(() => {
|
|
53
|
+
vi.unstubAllGlobals();
|
|
54
|
+
vi.unstubAllEnvs();
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
const checkout = (files: Checkout["files"]): Checkout => {
|
|
58
|
+
const c: Checkout = { version: 1, url: "x", repo: "alice/app", branch: "main", base: "b".repeat(64), root: "r".repeat(64), sparse: null, files };
|
|
59
|
+
saveCheckout(root, c);
|
|
60
|
+
return c;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
describe("lizard git sync never writes through a symlink", () => {
|
|
64
|
+
it("a deleted symlink is gone before a file is written under its name", async () => {
|
|
65
|
+
symlinkSync(outside, join(root, "d"));
|
|
66
|
+
const c = checkout({ d: { h: sha256(outside), m: "120000" } });
|
|
67
|
+
serve({ "d/authorized_keys": "attacker key" });
|
|
68
|
+
await sync(root, c);
|
|
69
|
+
expect(existsSync(join(outside, "authorized_keys"))).toBe(false);
|
|
70
|
+
expect(lstatSync(join(root, "d")).isDirectory()).toBe(true);
|
|
71
|
+
expect(readFileSync(join(root, "d/authorized_keys"), "utf8")).toBe("attacker key");
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
it("a symlinked folder that stays (changed here) refuses the file instead", async () => {
|
|
75
|
+
symlinkSync(outside, join(root, "d")); // tracked with another target: a local change
|
|
76
|
+
const c = checkout({ d: { h: sha256("elsewhere"), m: "120000" } });
|
|
77
|
+
serve({ "d/x": "payload" }, ["elsewhere"]);
|
|
78
|
+
const r = await sync(root, c);
|
|
79
|
+
expect(existsSync(join(outside, "x"))).toBe(false);
|
|
80
|
+
expect(r.conflicts?.map((x) => x.path)).toContain("d/x");
|
|
81
|
+
expect(c.files["d/x"]).toBeUndefined();
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it("a folder replaced by a symlink: the folder's files are removed here, not where the link points", async () => {
|
|
85
|
+
mkdirSync(join(root, "d"));
|
|
86
|
+
writeFileSync(join(root, "d/authorized_keys"), "mine");
|
|
87
|
+
writeFileSync(join(outside, "authorized_keys"), "victim");
|
|
88
|
+
const c = checkout({ "d/authorized_keys": { h: sha256("mine"), m: "100644" } });
|
|
89
|
+
serve({ d: { link: outside } });
|
|
90
|
+
await sync(root, c);
|
|
91
|
+
expect(readFileSync(join(outside, "authorized_keys"), "utf8")).toBe("victim");
|
|
92
|
+
expect(lstatSync(join(root, "d")).isSymbolicLink()).toBe(true);
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it("a new symlink in the changeset is created as a link, nothing goes through it", async () => {
|
|
96
|
+
const c = checkout({});
|
|
97
|
+
serve({ d: { link: outside }, "e/x": "ok" });
|
|
98
|
+
await sync(root, c);
|
|
99
|
+
// the link itself is fine to create; nothing was written through it
|
|
100
|
+
expect(lstatSync(join(root, "d")).isSymbolicLink()).toBe(true);
|
|
101
|
+
expect(readFileSync(join(root, "e/x"), "utf8")).toBe("ok");
|
|
102
|
+
});
|
|
103
|
+
});
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { isStartupEnvName } from "../../src/lib/env-guard.js";
|
|
3
|
+
import { writableChanges } from "../../src/commands/gha.js";
|
|
4
|
+
|
|
5
|
+
describe("lizard run: variables that change how programs start are not set locally", () => {
|
|
6
|
+
it.each(["LD_PRELOAD", "LD_LIBRARY_PATH", "DYLD_INSERT_LIBRARIES", "NODE_OPTIONS", "BASH_ENV", "ENV", "PROMPT_COMMAND", "PATH",
|
|
7
|
+
"PYTHONSTARTUP", "PYTHONPATH", "PERL5OPT", "RUBYOPT", "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_GLOBAL", "GIT_SSH_COMMAND", "GIT_EXEC_PATH",
|
|
8
|
+
"BASH_FUNC_ls%%"])("%s is skipped", (n) => expect(isStartupEnvName(n)).toBe(true));
|
|
9
|
+
|
|
10
|
+
it.each(["DATABASE_URL", "NODE_ENV", "PORT", "REDIS_URL", "API_KEY", "PATHNAME", "ENVIRONMENT", "GITHUB_TOKEN"])("%s is set", (n) =>
|
|
11
|
+
expect(isStartupEnvName(n)).toBe(false));
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
describe("lizard gha migrate writes only files it sent", () => {
|
|
15
|
+
it("drops paths the server made up", () => {
|
|
16
|
+
const sent = [{ path: ".github/workflows/ci.yml" }];
|
|
17
|
+
const r = writableChanges(sent, [
|
|
18
|
+
{ path: ".github/workflows/ci.yml", changed: true, text: "a" },
|
|
19
|
+
{ path: "../../.bashrc", changed: true, text: "evil" },
|
|
20
|
+
{ path: ".github/workflows/other.yml", changed: true, text: "b" },
|
|
21
|
+
{ path: ".github/workflows/ci.yml/../../../x", changed: true, text: "c" },
|
|
22
|
+
]);
|
|
23
|
+
expect(r.changed.map((f) => f.path)).toEqual([".github/workflows/ci.yml"]);
|
|
24
|
+
expect(r.foreign).toEqual(["../../.bashrc", ".github/workflows/other.yml", ".github/workflows/ci.yml/../../../x"]);
|
|
25
|
+
});
|
|
26
|
+
});
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { describe, expect, it } from "vitest";
|
|
2
|
+
import { generateKeyPairSync, sign } from "node:crypto";
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { RELEASE_PUBLIC_KEY, verifyReleaseSignature } from "../../src/lib/updater.js";
|
|
8
|
+
|
|
9
|
+
describe("self-update signatures", () => {
|
|
10
|
+
const { privateKey, publicKey } = generateKeyPairSync("ed25519");
|
|
11
|
+
const pub = publicKey.export({ type: "spki", format: "pem" }).toString();
|
|
12
|
+
const data = Buffer.from("a lizard binary");
|
|
13
|
+
const sig = sign(null, data, privateKey).toString("base64");
|
|
14
|
+
|
|
15
|
+
it("accepts the release key's signature", () => {
|
|
16
|
+
expect(verifyReleaseSignature(data, sig + "\n", pub)).toBe(true);
|
|
17
|
+
});
|
|
18
|
+
|
|
19
|
+
it("refuses changed bytes, another key, and junk", () => {
|
|
20
|
+
expect(verifyReleaseSignature(Buffer.from("a lizard binary!"), sig, pub)).toBe(false);
|
|
21
|
+
expect(verifyReleaseSignature(data, sig)).toBe(false); // the built-in key did not sign this
|
|
22
|
+
expect(verifyReleaseSignature(data, "", pub)).toBe(false);
|
|
23
|
+
expect(verifyReleaseSignature(data, "not base64 at all", pub)).toBe(false);
|
|
24
|
+
expect(verifyReleaseSignature(data, "<html>404</html>", pub)).toBe(false);
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
it("the built-in key is an Ed25519 public key", () => {
|
|
28
|
+
expect(RELEASE_PUBLIC_KEY).toMatch(/^-----BEGIN PUBLIC KEY-----\n[A-Za-z0-9+/=]+\n-----END PUBLIC KEY-----\n$/);
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
it("scripts/sign-release.mjs refuses a key that is not the built-in one", () => {
|
|
32
|
+
const dir = mkdtempSync(join(tmpdir(), "lz-sign-"));
|
|
33
|
+
const f = join(dir, "lizard-linux-x64");
|
|
34
|
+
writeFileSync(f, data);
|
|
35
|
+
const pem = privateKey.export({ type: "pkcs8", format: "pem" }).toString();
|
|
36
|
+
expect(() => execFileSync(process.execPath, ["scripts/sign-release.mjs", f], { env: { ...process.env, LIZARD_RELEASE_SIGNING_KEY: pem }, stdio: "pipe" })).toThrow();
|
|
37
|
+
expect(() => execFileSync(process.execPath, ["scripts/sign-release.mjs", f], { env: { ...process.env, LIZARD_RELEASE_SIGNING_KEY: "" }, stdio: "pipe" })).toThrow();
|
|
38
|
+
});
|
|
39
|
+
});
|