feat(demo): add fail-closed three-seat desktop launcher (#7628)

This commit is contained in:
ben authored and GitHub committed 2026-11-20 10:03:44 -08:00
1 parent eb0287b00c
commit efb1e2208e
25 files changed
+1029 -27

No files matched your search

+2
View File
@@ -69,6 +69,8 @@
"evals:typecheck": "pnpm --dir evals typecheck",
"evals:pr": "pnpm --dir evals run test:pr",
"world": "node evals/bin/world.mjs",
"demo:desktops": "node scripts/demo/launch.ts",
"test:demo-desktops": "node --test scripts/demo/launch.test.ts",
"release:review": "node scripts/release/review.mjs",
"release:rollback": "node scripts/release/rollback.mjs",
"release:cut": "node scripts/release/cut.mjs",
+10
View File
@@ -18,6 +18,16 @@ export const CHECKS = [
command: ["node", ".github/scripts/typecheck-shipped.mjs", "--all"],
fix: "Fix the type errors above. Do not silence them with `any`, `as` or @ts-ignore.",
},
{
name: "demo-desktops-types",
command: ["pnpm", "exec", "tsc", "-p", "scripts/demo/tsconfig.json"],
fix: "Fix the demo launcher type errors; do not silence or cast them away.",
},
{
name: "demo-desktops",
command: ["node", "--test", "scripts/demo/launch.test.ts"],
fix: "Fix the offline demo snapshot, privacy, lifetime or cleanup regression; never bypass the allowlist.",
},
{
name: "browser-secrets",
command: ["node", "--test", "packages/computer-use/browser-secrets.test.mjs", "packages/computer-use/browser-task-secrets.test.mjs", "packages/computer-use/browser-secrets.review.test.mjs", "packages/computer-use/computer-control-secret-approval.test.mjs", "apps/desktop/electron/session-runner-computer-requests.test.mjs"],
+157
View File
@@ -0,0 +1,157 @@
# Three-seat demo desktops
Operator-only launcher for **demo**, **practice**, and **backup** Daytona Linux
desktops. This is an infrastructure tool, not a new app feature or a replacement
for the workshop fleet. It does not create organizations, seed accounts, grant
models, sign anyone in, or copy credentials. Sign in separately in each desktop
to the same **dedicated sandbox organization**, never a production organization.
## Current state: blocked on a reviewed image
`snapshots.json` is deliberately empty. No clean demo image has been built,
audited, or pinned by this change. `plan` and `up` reject an absent review **before
loading live adapters, reading Daytona credentials, or dispatching a command**.
Do not populate the allowlist with invented IDs, an existing workshop image, an
unreviewed desktop, or a mutable image tag. There is no fallback image or automatic
build/provision path.
The launcher and failure paths have offline tests. The Daytona CLI/REST resource
schema, viewer authentication, Linux desktop, packaged app, and image helpers have
**not** been verified on a live sandbox in this change. No provisioning or remote
image building was authorized. A passing unit test is not a READY demo.
## Commands
Use Node 24.22.1 or newer within Node 24, and pnpm from the repository's
`packageManager`. Run from the checkout:
```sh
pnpm test:demo-desktops
pnpm demo:desktops --help
pnpm demo:desktops plan --snapshot demo-desktop-<reviewed-name>
```
Only after a separately authorized image build, audit, snapshot review and live
pilot, an authorized operator may run:
```sh
pnpm demo:desktops up --stage rehearsal-01 --snapshot demo-desktop-<reviewed-name>
pnpm demo:desktops refresh --stage rehearsal-01
pnpm demo:desktops down --stage rehearsal-01
```
`up` defaults to all three seats, 1440 minutes, `America/Los_Angeles`, and a $30
infrastructure estimate ceiling. A pilot can use `--seats practice --lifetime 60`.
The allowed seat names are fixed, with no duplicates. Lifetimes are 10–1440 minutes.
A stage is never reused or overwritten, including after cleanup. Use a new stage
name for the next run. `refresh` checks desktop/CDP and replaces short-lived viewer
links; it does **not** extend sandbox lifetime or sign a user in.
Live operations require an already-configured Daytona CLI and `DAYTONA_API_URL` /
`DAYTONA_API_KEY` for **the same dedicated team**. The launcher does not fetch,
discover, print, or install credentials. The REST snapshot metadata must match the
reviewed immutable ID, digest-pinned image reference, source sandbox, active state,
and exact 4 CPU / 8 GiB / reviewed disk size (10–40 GiB); otherwise no create runs.
Creation uses the pinned ID, not the reusable snapshot name, and passes the
provider-side `--ttl` at creation. It never passes `--public`, environment mounts,
or secret mounts. Created resources are checked again for identity, privacy and
size. CLI/REST schema drift fails closed; do not weaken checks to make a run pass.
The estimate uses 4 × $0.083/core-hour plus $0.0001/GiB-hour for snapshot disk,
multiplied by seats and maximum lifetime. It is **not a billing cap or current price
quote**: verify provider pricing before authorizing a run. It excludes image builds,
stored snapshots, model usage, backend services, taxes and all other charges.
`--budget-usd` deliberately changes only this local estimate gate.
## Private receipts and recovery
The only public command result is a directory, ready count and estimate (or action).
No signed viewer link is printed, returned as a world output, or written into the
checkout. Outputs live at:
```text
~/.openwork/demos/<stage>/<seat>/control.json
```
Directories must be caller-owned mode `0700`; receipts are atomically replaced
mode `0600`. Git checkout paths, symlink directories and loose permissions are
rejected. If `~/.openwork` already exists with different permissions, review its
ownership and contents before tightening permissions yourself. Bearer viewer URLs
are sensitive even with private permissions: do not attach receipts, logs, browser
profiles, or signed URLs to commits, PRs, screenshots or public evidence.
Each seat journals a random unique sandbox name before create and the resolved ID
immediately afterward. A partial/ambiguous failure attempts cleanup of **all**
journaled owners; no fan-out continues after a failed seat. `down` only acts on
those receipts and verifies private identity before deletion; it never scans or
deletes a fleet. Successfully stopped receipts no longer contain a viewer URL.
Permission, identity, missing-resource, auth and ambiguous delete failures remain
explicitly incomplete, rather than being treated as a successful cleanup.
A `.busy` directory serializes operations on a stage. If a controller is killed,
first confirm no process still owns the stage, inspect the private receipts and
provider state, then remove only the stale empty `.busy` directory and retry
`down`. Do not delete the journal before reconciling resources. A create timeout
can leave a sandbox finishing asynchronously: retry cleanup after creation has
settled. Provider TTL is the final backstop if the process or local journal is
lost; verify its actual behavior in the authorized live pilot. Snapshot storage
is not covered by sandbox TTL.
Viewer links expire at the lesser of one hour and the remaining lifetime. Before
publishing a link privately, the adapter requires private sandbox metadata, denied
unsigned HTTP, denied unsigned WebSocket and a successful signed noVNC HTTP/RFB
probe. Guest CDP remains loopback-only on port 9223; there is no CDP preview or
public port tunnel. `ready` means desktop/CDP/viewer checks passed, **not** that an
organization, account, connectors, models or a demo script are ready.
## Image work preserved, and exactly what remains
`worlds/lib/demo-desktop-files/` preserves the previous worker's **unfinished**
image ingredients:
- `install-tools.sh`: LibreOffice Impress/Calc, fonts and desktop automation tools.
- `package-sha.sh`: package a full pushed SHA in a clean Linux guest, then hash a
deterministic tar stream of the packaged tree. This runs build/install hooks;
review the source first and never run it with production credentials.
- `openwork.sh`, `app-control.sh`: isolated OpenWork state, loopback CDP and a
serialized app start/restart helper.
- `chromium.sh`, desktop/MIME entries: separate employee/admin browser profiles
and the OpenWork deep-link handler.
- `type-file.sh`, `demo-copy.sh`, `prompts.json`: type a fictional prompt into the
focused app without a trailing newline/automatic submit.
These are not an image builder. They are not installed or executed by the launcher.
Before adding any real allowlist entry, a separately authorized follow-up must:
1. Select and pin a clean **x86_64 Linux desktop base by immutable ID/digest**,
configure 4 CPU / 8 GiB / 10–40 GiB disk, and document noVNC/X11 startup, user,
writable disk and provider TTL behavior. No base ID has been selected here.
2. Implement and test image assembly: install these helpers at `/home/daytona/demo`
with executable permissions; install MIME/desktop files in the user's local
applications directory; configure noVNC, X11 and the default browser. The current
files assume user `daytona`, display `:99`, port 6080, and specific package paths.
3. Implement the **release Cloud package download and published digest verification**
path for canonical `release:<version>/cloud`, or authorize a reviewed full pushed
SHA build using the preserved script. Pin dependencies/toolchain, verify Node 24,
verify the real packaging command/output, and record the packaged-tree SHA-256.
No release installer, trusted digest receipt or completed SHA build exists here.
4. Implement a machine-verifiable clean-base audit and a signed-off review receipt.
Require empty OpenWork/browser profiles, no sign-in/session tokens, API keys,
cookies, keychains, copied config, build caches, command histories, private files,
running authenticated apps or residual credential environment. Merely writing
`demo-clean-base-v1: passed` is **not** an audit. The audit is not implemented here.
5. Stop/scrub the guest, create an immutable provider snapshot, wait for active state,
and independently verify the REST metadata fields used by `verifyDemoSnapshot`.
Confirm CLI snapshot-ID support and resource field names without bypassing gates.
6. Review a PR adding the actual snapshot entry, with a non-secret provenance/audit
report and live pilot evidence. Schema per entry: `id` (immutable snapshot UUID),
`image` (`registry/path@sha256:<64 hex>`), `sourceSandboxId` (UUID), canonical
`source`, `packageSha256` (64 hex), `diskGiB` (integer 10–40), and `audit` (exact
`demo-clean-base-v1: passed`). Keep sensitive build receipts outside Git.
7. Run one authorized private pilot: validate packaged app and deep-link sign-in,
independent browser profiles, LibreOffice open/edit/save, fonts, copy helper,
timezone, guest-only CDP, denied unsigned HTTP/WebSocket and signed viewer,
refresh expiry, deliberate partial-failure cleanup, provider expiry, and no
sensitive data in outputs. Only then authorize the three-seat launch.
Until these steps are complete, keep `snapshots.json` empty and this PR in draft.
+208
View File
@@ -0,0 +1,208 @@
import assert from "node:assert/strict";
import { chmod, lstat, mkdtemp, readFile, rm, symlink, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { test } from "node:test";
import { launchDemo, manageDemo } from "../../worlds/lib/demo-launcher.ts";
import type { DemoProvider } from "../../worlds/lib/demo-launcher.ts";
import { demoPrivateDir, readSeatControl, writeDemoJson } from "../../worlds/lib/demo-output.ts";
import { guardDemoBudget, parseDemoOptions, parseDemoSource } from "../../worlds/lib/demo-options.ts";
import { DEMO_AUDIT, parseDemoSnapshot, reviewedDemoSnapshot, verifyDemoSnapshot } from "../../worlds/lib/demo-snapshot.ts";
import type { DemoSnapshot } from "../../worlds/lib/demo-snapshot.ts";
import { main } from "./launch.ts";
import { createDemoSandbox, deleteDemoSandbox, demoCli } from "../../worlds/lib/demo-provider.ts";
import type { DaytonaExec } from "../../evals/packages/hosts/src/daytona.ts";
const id = "11111111-1111-4111-8111-111111111111";
const name = "demo-desktop-fixture";
const entry: DemoSnapshot = { id, sourceSandboxId: id, image: `registry.example.test/demo@sha256:${"a".repeat(64)}`,
source: "release:0.18.71/cloud", packageSha256: "b".repeat(64), diskGiB: 30, audit: DEMO_AUDIT };
const flags = ["--snapshot", name];
const signed = "https://6080-private-fixture.example.test/vnc.html";
function fakeProvider() {
const created: string[] = [], removed: string[] = [];
const provider: DemoProvider = {
async review() { return entry; },
async create(name) { created.push(name); return name; },
async prepare() {},
async viewer() { return { viewer: signed, viewerExpiresAt: new Date(Date.now() + 3600_000).toISOString() }; },
async remove(id) { removed.push(id); },
};
return { provider, created, removed };
}
async function temp() { return mkdtemp(join(tmpdir(), "openwork-demo-test-")); }
test("snapshot gate requires immutable provenance, canonical source, bounded disk and audit", () => {
assert.deepEqual(parseDemoSnapshot(entry), entry);
for (const patch of [{ image: "registry/demo:latest" }, { id: "latest" }, { packageSha256: "x" }, { sourceSandboxId: "" },
{ source: "release:0.18.71" }, { source: "sha:dev" }, { diskGiB: 41 }, { diskGiB: 9 }, { audit: "passed" }]) {
assert.throws(() => parseDemoSnapshot({ ...entry, ...patch }));
}
assert.throws(() => reviewedDemoSnapshot({}, name), /No reviewed entry/);
assert.throws(() => reviewedDemoSnapshot({ [name]: entry }, "../elsewhere"));
assert.throws(() => reviewedDemoSnapshot(Object.create({ [name]: entry }), name));
const actual = { ...entry, name, ref: entry.image, state: "active", cpu: 4, mem: 8, disk: 30 };
verifyDemoSnapshot(name, entry, actual);
for (const patch of [{ id: "other" }, { state: "building" }, { ref: "latest" }, { cpu: 8 }, { mem: 16 }, { disk: 40 }, { sourceSandboxId: "other" }]) {
assert.throws(() => verifyDemoSnapshot(name, entry, { ...actual, ...patch }));
}
});
test("flags cap seats, TTL, spend and shell-safe timezone; duplicate or unknown flags fail", () => {
const options = parseDemoOptions(flags);
assert.deepEqual(options.seats, ["demo", "practice", "backup"]);
assert.equal(options.lifetime, 1440);
assert.ok(guardDemoBudget(options, 30) < 30);
for (const extra of [["--seats", "demo,demo"], ["--seats", "other"], ["--lifetime", "1441"], ["--lifetime", "0"],
["--timezone", "UTC';echo x"], ["--timezone", "Invalid/Zone"], ["--wat", "x"], ["--snapshot", name], ["--seats"]]) {
assert.throws(() => parseDemoOptions([...flags, ...extra]));
}
assert.throws(() => guardDemoBudget(parseDemoOptions([...flags, "--budget-usd", "1"]), 30), /exceeds/);
assert.equal(parseDemoSource(`sha:${"a".repeat(40)}`).kind, "sha");
});
test("private outputs reject loose permissions, checkout descendants and symlinks", async () => {
const root = await temp();
try {
const dir = await demoPrivateDir(join(root, "private"));
await writeDemoJson(join(dir, "receipt.json"), { viewer: signed });
assert.equal((await lstat(join(dir, "receipt.json"))).mode & 0o777, 0o600);
await symlink(dir, join(root, "link"));
await assert.rejects(demoPrivateDir(join(root, "link")), /not a symlink/);
await chmod(dir, 0o755);
await assert.rejects(demoPrivateDir(dir), /0700/);
await writeFile(join(root, ".git"), "gitdir: fixture");
await assert.rejects(demoPrivateDir(join(root, "inside-checkout")), /Git checkout/);
} finally { await rm(root, { recursive: true, force: true }); }
});
test("three seats journal ownership before create, keep bearer links private, refresh and down", async () => {
const root = await temp(), dir = join(root, "stage");
const { provider, created, removed } = fakeProvider();
const create = provider.create;
provider.create = async (name, snapshot, lifetime) => {
const seats = ["demo", "practice", "backup"];
const receipt = await readSeatControl(join(dir, seats[created.length]!), seats[created.length]!);
assert.equal(receipt.sandbox, name, "intent is durable before provider dispatch");
return create(name, snapshot, lifetime);
};
try {
const result = await launchDemo(dir, flags, provider);
assert.equal(result.ready, "3/3");
assert.equal(created.length, 3);
assert.equal(new Set(created).size, 3);
assert.ok(!JSON.stringify(result).includes(signed));
await assert.rejects(launchDemo(dir, flags, provider), /EEXIST/);
assert.equal(created.length, 3);
await manageDemo(dir, "refresh", provider);
for (const seat of ["demo", "practice", "backup"]) {
assert.equal((await readSeatControl(join(dir, seat), seat)).viewer, signed);
}
await manageDemo(dir, "down", provider);
await manageDemo(dir, "down", provider);
assert.deepEqual([...removed].sort(), [...created].sort());
assert.ok(!(await readFile(join(dir, "demo/control.json"), "utf8")).includes(signed));
await chmod(join(dir, "demo/control.json"), 0o644);
await assert.rejects(readSeatControl(join(dir, "demo"), "demo"), /permissions/);
} finally { await rm(root, { recursive: true, force: true }); }
});
test("partial and ambiguous creation failures clean all journaled owners without leaking errors", async () => {
for (const failCreate of [false, true]) {
const root = await temp(), dir = join(root, "stage");
const { provider, created, removed } = fakeProvider();
const create = provider.create;
provider.create = async (...args) => {
const result = await create(...args);
if (failCreate && created.length === 2) throw new Error(signed);
return result;
};
provider.prepare = async () => { if (!failCreate && created.length === 2) throw new Error(signed); };
try {
await assert.rejects(launchDemo(dir, flags, provider), (error: unknown) => error instanceof Error && /owned sandboxes removed/.test(error.message) && !error.message.includes(signed));
assert.deepEqual(removed, created);
assert.equal(created.length, 2);
} finally { await rm(root, { recursive: true, force: true }); }
}
});
test("cleanup failures are explicit, retain recoverable receipts and do not skip other seats", async () => {
const root = await temp(), dir = join(root, "stage");
const { provider, removed } = fakeProvider();
try {
await launchDemo(dir, flags, provider);
const remove = provider.remove;
provider.remove = async (id) => { await remove(id); throw new Error(signed); };
await assert.rejects(manageDemo(dir, "down", provider), /incomplete for 3 seat/);
assert.equal(removed.length, 3);
assert.equal((await readSeatControl(join(dir, "backup"), "backup")).stopped, undefined);
} finally { await rm(root, { recursive: true, force: true }); }
});
test("failed launch cleanup preserves receipts and an explicit incomplete result", async () => {
const root = await temp(), dir = join(root, "stage");
const { provider, removed } = fakeProvider();
provider.prepare = async () => { throw new Error(signed); };
provider.remove = async (id) => { removed.push(id); throw new Error(signed); };
try {
await assert.rejects(launchDemo(dir, flags, provider), /cleanup incomplete/);
assert.equal(removed.length, 1);
assert.equal((await readSeatControl(join(dir, "demo"), "demo")).sandbox, removed[0]);
} finally { await rm(root, { recursive: true, force: true }); }
});
test("expired seats cannot mint a refreshed viewer but remain eligible for cleanup", async () => {
const root = await temp(), dir = join(root, "stage");
const { provider } = fakeProvider();
try {
await launchDemo(dir, [...flags, "--seats", "practice"], provider);
const receipt = await readSeatControl(join(dir, "practice"), "practice");
await writeDemoJson(join(dir, "practice/control.json"), { ...receipt, expiresAt: new Date(0).toISOString() });
provider.viewer = async () => { throw new Error("Must not be called."); };
await assert.rejects(manageDemo(dir, "refresh", provider), /incomplete/);
await manageDemo(dir, "down", provider);
} finally { await rm(root, { recursive: true, force: true }); }
});
test("live adapter passes immutable snapshot and provider TTL, rejects public identity, and redacts errors", async () => {
const calls: string[][] = [];
let isPublic = false;
const exec: DaytonaExec = async (args) => {
calls.push(args);
return { code: 0, stderr: "", stdout: args[0] === "info" ? JSON.stringify({ id, name: id, public: isPublic }) : "sensitive provider output" };
};
assert.equal(await createDemoSandbox(id, entry.id, 60, exec), id);
assert.deepEqual(calls[0], ["create", "--name", id, "--snapshot", entry.id, "--target", "us", "--auto-stop", "0", "--ttl", "60"]);
assert.ok(!calls.flat().includes("--public"));
isPublic = true;
await assert.rejects(createDemoSandbox(id, entry.id, 60, exec), /privacy or identity/);
const before = calls.length;
await assert.rejects(createDemoSandbox(id, "latest", 60, exec), /immutable/);
assert.equal(calls.length, before);
await assert.rejects(deleteDemoSandbox(id, exec), /could not be confirmed/);
assert.ok(!calls.some((args) => args[0] === "delete"));
isPublic = false;
await deleteDemoSandbox(id, exec);
assert.deepEqual(calls.at(-1), ["delete", id]);
await assert.rejects(demoCli(["unused"], "Safe operation", 1, async () => { throw new Error(signed); }),
(error: unknown) => error instanceof Error && error.message === "Safe operation failed; no provider output logged.");
});
test("stage operation lock prevents refresh or deletion during an in-progress launch", async () => {
const root = await temp(), dir = join(root, "stage");
const { provider } = fakeProvider();
provider.prepare = async () => {
await assert.rejects(manageDemo(dir, "down", provider), /EEXIST/);
await assert.rejects(manageDemo(dir, "refresh", provider), /EEXIST/);
};
try { await launchDemo(dir, flags, provider); }
finally { await rm(root, { recursive: true, force: true }); }
});
test("checked-in empty allowlist blocks plan and up before credentials, output or provider access", async () => {
await assert.rejects(main(["plan", ...flags]), /No reviewed entry/);
await assert.rejects(main(["up", "--stage", "offline-test", ...flags]), /No reviewed entry/);
await assert.rejects(main(["down", "--stage", "offline-test", "--public", "true"]), /one value per flag/);
});
+85
View File
@@ -0,0 +1,85 @@
#!/usr/bin/env node
import { join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { demoStage, demoFlags, parseDemoOptions, guardDemoBudget } from "../../worlds/lib/demo-options.ts";
import { demoRootDir } from "../../worlds/lib/demo-output.ts";
import { launchDemo, manageDemo } from "../../worlds/lib/demo-launcher.ts";
import type { DemoProvider } from "../../worlds/lib/demo-launcher.ts";
import { readReviewedDemoSnapshot } from "../../worlds/lib/demo-snapshot.ts";
const usage = `Demo desktops (operator-only; no org seeding or sign-in)
pnpm demo:desktops plan --snapshot demo-desktop-<reviewed-name>
pnpm demo:desktops up --stage <new-name> --snapshot demo-desktop-<reviewed-name> [--seats demo,practice,backup] [--lifetime 1440] [--timezone America/Los_Angeles] [--budget-usd 30]
pnpm demo:desktops refresh --stage <name>
pnpm demo:desktops down --stage <name>
Viewer links are written only to ~/.openwork/demos/<stage>/<seat>/control.json.
plan is offline. up/refresh/down require explicit operator authorization and Daytona credentials.
`;
/** Load live adapters only after local allowlist and budget validation pass. */
async function liveProvider(): Promise<DemoProvider> {
const provider = await import("../../worlds/lib/demo-provider.ts");
const snapshot = await import("../../worlds/lib/demo-snapshot.ts");
return {
async review(name) {
const expected = await readReviewedDemoSnapshot(name);
snapshot.verifyDemoSnapshot(name, expected, await snapshot.getRawDemoSnapshot(snapshot.demoDaytonaApi(), name));
return expected;
},
async create(name, expected, lifetime) {
const id = await provider.createDemoSandbox(name, expected.id, lifetime);
const info: unknown = JSON.parse(await provider.demoCli(["info", id, "-f", "json"], "Verify demo resources"));
if (!snapshot.isRecord(info) || info.id !== id || info.name !== name || info.public !== false
|| info.cpu !== snapshot.DEMO_CPU || info.memory !== snapshot.DEMO_MEMORY || info.disk !== expected.diskGiB) {
throw new Error("Created demo sandbox did not match reviewed resources and identity.");
}
return id;
},
async prepare(id, timezone) {
await provider.demoSandboxInfo(id);
await provider.waitForDemoGuest(id);
if (timezone) await provider.demoGuest(id, `set -eu
zone='/usr/share/zoneinfo/${timezone}'
test -f "$zone"
sudo ln -snf "$zone" /etc/localtime
printf '%s\\n' '${timezone}' | sudo tee /etc/timezone >/dev/null`, "Set demo timezone");
await provider.demoGuest(id, '"$HOME/demo/app-control.sh"', "Start packaged demo desktop");
if (!await provider.demoCdpReachable(id)) throw new Error("Guest CDP is unavailable.");
},
viewer: provider.mintDemoViewer,
remove: provider.deleteDemoSandbox,
};
}
export async function main(argv: readonly string[]) {
const [action, ...rest] = argv;
if (!action || action === "--help") { console.log(usage); return; }
if (action === "plan") {
const options = parseDemoOptions(rest);
const snapshot = await readReviewedDemoSnapshot(options.snapshot);
console.log(JSON.stringify({ seats: options.seats, source: snapshot.source, snapshotId: snapshot.id,
lifetimeMinutes: options.lifetime, infrastructureEstimateUsd: guardDemoBudget(options, snapshot.diskGiB) }, null, 2));
return;
}
if (action !== "up" && action !== "refresh" && action !== "down") throw new Error("Use plan, up, refresh or down.");
const stageIndex = rest.indexOf("--stage");
if (stageIndex < 0 || !rest[stageIndex + 1]) throw new Error("Pass --stage <name>.");
const stage = demoStage(rest[stageIndex + 1]);
const flags = [...rest.slice(0, stageIndex), ...rest.slice(stageIndex + 2)];
if (action === "up") {
const options = parseDemoOptions(flags);
guardDemoBudget(options, (await readReviewedDemoSnapshot(options.snapshot)).diskGiB);
} else { demoFlags(flags, []); }
const dir = join(await demoRootDir(action === "up"), stage);
const provider = await liveProvider();
const result = action === "up" ? await launchDemo(dir, flags, provider) : await manageDemo(dir, action, provider);
console.log(JSON.stringify(result));
}
if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
main(process.argv.slice(2)).catch(() => {
// Errors from libraries or providers can echo bearer URLs or command arguments.
console.error("Demo command failed. No provider diagnostics or viewer links logged. Check scripts/demo/README.md and private receipts; retry down if a launch was attempted.");
process.exitCode = 1;
});
}
+1
View File
@@ -0,0 +1 @@
{}
+17
View File
@@ -0,0 +1,17 @@
{
"compilerOptions": {
"strict": true,
"noEmit": true,
"module": "preserve",
"moduleResolution": "bundler",
"target": "esnext",
"lib": ["esnext", "dom", "dom.iterable"],
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"verbatimModuleSyntax": true,
"skipLibCheck": true,
"types": ["node"],
"paths": { "@openwork/cdp": ["../../evals/packages/cdp/src/index.ts"] }
},
"include": ["./*.ts", "../../evals/packages/cdp/src/browser-globals.d.ts"]
}
@@ -0,0 +1,36 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
state="$HOME/demo/state"
mkdir -p "$state"
exec 9>"$state/app.lock"
flock -x 9
cdp() { curl --noproxy '*' --max-time 2 -fsS http://127.0.0.1:9223/json/list | jq -e 'any(.[]; .type == "page" and (.url | startswith("file://")))' >/dev/null; }
if [[ ${1:-} == restart ]]; then
pid=$(cat "$state/app.pid" 2>/dev/null || true)
if [[ $pid =~ ^[0-9]+$ && $(readlink "/proc/$pid/exe" || true) == "$(readlink -f /opt/openwork-demo/openwork-cloud)" ]]; then
kill -TERM "$pid"
for _ in $(seq 1 30); do
[[ -e /proc/$pid/exe ]] || break
sleep 1
done
[[ ! -e /proc/$pid/exe ]] || { echo 'OpenWork did not exit.' >&2; exit 1; }
fi
fi
if ! cdp 2>/dev/null; then
# Escape the Daytona exec session, and do not let Electron inherit the lock.
python3 - "$HOME/demo/openwork.sh" "$state" <<'PY'
import pathlib, subprocess, sys
state = pathlib.Path(sys.argv[2])
with (state / "app.log").open("wb") as log:
app = subprocess.Popen([sys.argv[1]], stdin=subprocess.DEVNULL, stdout=log,
stderr=subprocess.STDOUT, start_new_session=True, close_fds=True)
(state / "app.pid").write_text(str(app.pid))
PY
fi
for _ in $(seq 1 75); do
if cdp 2>/dev/null; then exit 0; fi
sleep 1
done
echo 'Packaged OpenWork did not expose a renderer on guest CDP.' >&2
exit 1
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
export DISPLAY=${DISPLAY:-:99}
persona=${1:?Usage: chromium.sh employee|admin [URL]}
shift
args=()
case "$persona" in
employee) ;;
admin) args+=(--remote-debugging-port=9224 --remote-debugging-address=127.0.0.1) ;;
*) exit 2 ;;
esac
browser=$(command -v chromium || command -v google-chrome || command -v google-chrome-stable)
mkdir -p "$HOME/demo/state/$persona"
exec "$browser" --no-sandbox --disable-dev-shm-usage --no-first-run \
--user-data-dir="$HOME/demo/state/$persona" "${args[@]}" -- "$@"
@@ -0,0 +1,6 @@
[Desktop Entry]
Type=Application
Name=Demo employee browser
Exec=/home/daytona/demo/chromium.sh employee %U
Terminal=false
MimeType=x-scheme-handler/http;x-scheme-handler/https;text/html;
@@ -0,0 +1,4 @@
#!/usr/bin/env bash
set -euo pipefail
[[ $# == 1 ]] || { echo 'Usage: demo-copy.sh <prompt-name>' >&2; exit 2; }
jq -e -j --arg name "$1" '.[$name] | select(type == "string")' "$HOME/demo/prompts.json" | "$HOME/demo/type-file.sh" -
@@ -0,0 +1,5 @@
[Default Applications]
x-scheme-handler/openwork=demo-openwork.desktop
x-scheme-handler/http=demo-chromium.desktop
x-scheme-handler/https=demo-chromium.desktop
text/html=demo-chromium.desktop
@@ -0,0 +1,6 @@
[Desktop Entry]
Type=Application
Name=OpenWork Cloud
Exec=/home/daytona/demo/openwork.sh %U
Terminal=false
MimeType=x-scheme-handler/openwork;
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
set -euo pipefail
test "$(id -un)" = daytona && test "$HOME" = /home/daytona
test "$(uname -m)" = x86_64
packages=(libreoffice-impress libreoffice-calc fonts-liberation xdotool wmctrl jq)
command -v ffmpeg >/dev/null || packages+=(ffmpeg)
sudo apt-get update
if ! command -v chromium && ! command -v google-chrome && ! command -v google-chrome-stable; then
packages+=(chromium)
fi
sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends "${packages[@]}"
sudo apt-get clean
sudo rm -rf /var/lib/apt/lists/*
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env bash
set -euo pipefail
umask 077
export DISPLAY=${DISPLAY:-:99}
state="$HOME/demo/state/openwork"
export XDG_CONFIG_HOME="$state/config" XDG_DATA_HOME="$state/data"
export XDG_CACHE_HOME="$state/cache" XDG_STATE_HOME="$state/state"
export XDG_DATA_DIRS="$HOME/.local/share:${XDG_DATA_DIRS:-/usr/local/share:/usr/share}"
export OPENWORK_ELECTRON_USERDATA="$state/electron"
export OPENWORK_AUTOMATION_RUNNER=off
mkdir -p "$XDG_CONFIG_HOME" "$XDG_DATA_HOME" "$XDG_CACHE_HOME" "$XDG_STATE_HOME" "$OPENWORK_ELECTRON_USERDATA"
# Internal sign-in uses the same employee browser and returns via openwork://.
cp "$HOME/.local/share/applications/demo-mimeapps.list" "$XDG_CONFIG_HOME/mimeapps.list"
cd "$HOME"
exec /opt/openwork-demo/openwork-cloud --no-sandbox --disable-gpu --disable-dev-shm-usage \
--remote-debugging-port=9223 --remote-debugging-address=127.0.0.1 "$@"
@@ -0,0 +1,26 @@
#!/usr/bin/env bash
set -euo pipefail
sha=${1:?Usage: package-sha.sh <full-pushed-sha>}
[[ $# == 1 && $sha =~ ^[a-f0-9]{40}$ ]] || { echo 'Expected one full lowercase pushed SHA.' >&2; exit 2; }
export PATH=/usr/local/share/nvm/current/bin:$PATH
export XDG_CACHE_HOME=/tmp/demo-build/cache
export ELECTRON_CACHE=$XDG_CACHE_HOME/electron ELECTRON_BUILDER_CACHE=$XDG_CACHE_HOME/electron-builder
export TARGET=x86_64-unknown-linux-gnu CI=true
sudo apt-get update
sudo env DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends build-essential python3 pkg-config libsecret-1-dev
mkdir -p /tmp/demo-build/src
cd /tmp/demo-build/src
git init -q
git fetch -q --depth=1 https://github.com/different-ai/openwork.git "$sha"
git checkout -q --detach FETCH_HEAD
test "$(git rev-parse HEAD)" = "$sha"
pnpm install --frozen-lockfile --store-dir /tmp/demo-build/store
pnpm --filter @openwork/desktop package:electron:cloud --linux --x64 --dir --publish never
app=apps/desktop/dist-electron/linux-unpacked
test -x "$app/openwork-cloud"
# Record the digest of a deterministic tar stream of exactly the packaged tree.
tar --sort=name --mtime=@0 --owner=0 --group=0 --numeric-owner -C "$app" -cf - . | sha256sum | cut -d' ' -f1 > "$HOME/demo/package.sha256"
sudo mv "$app" /opt/openwork-demo
rm -rf /tmp/demo-build
sudo apt-get clean
sudo rm -rf /var/lib/apt/lists/*
@@ -0,0 +1,3 @@
{
"example": "Draft a three-bullet update for the fictional Harbor Robotics team."
}
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
[[ $# == 1 ]] || { echo 'Usage: type-file.sh <file or ->' >&2; exit 2; }
export DISPLAY=${DISPLAY:-:99}
# Remove trailing CR/LF so the prompt is never submitted. Keep internal newlines.
input=$1
[[ $input != - ]] || input=/dev/stdin
python3 -c 'import sys; sys.stdout.buffer.write(sys.stdin.buffer.read().rstrip(b"\r\n"))' < "$input" | xdotool type --clearmodifiers --file -
+81
View File
@@ -0,0 +1,81 @@
import { randomUUID } from "node:crypto";
import { mkdir, readdir, rm } from "node:fs/promises";
import { join } from "node:path";
import { guardDemoBudget, parseDemoOptions } from "./demo-options.ts";
import { demoPrivateDir, readSeatControl, writeSeatControl } from "./demo-output.ts";
import type { SeatControl } from "./demo-output.ts";
import type { DemoSnapshot } from "./demo-snapshot.ts";
export interface DemoProvider {
review(name: string): Promise<DemoSnapshot>;
create(name: string, snapshot: DemoSnapshot, lifetime: number): Promise<string>;
prepare(id: string, timezone: string): Promise<void>;
viewer(id: string, expiresAt: string): Promise<{ viewer: string; viewerExpiresAt: string }>;
remove(idOrName: string): Promise<void>;
}
/** A fresh stage is a journal: record the unique name before dispatching create. */
export async function launchDemo(dir: string, argv: readonly string[], provider: DemoProvider) {
const options = parseDemoOptions(argv);
const snapshot = await provider.review(options.snapshot);
const estimate = guardDemoBudget(options, snapshot.diskGiB);
// Do not overwrite a previous run, even if its resources were stopped.
await demoPrivateDir(dir, true, true);
const lock = join(dir, ".busy");
await mkdir(lock, { mode: 0o700 });
const owned: SeatControl[] = [];
try {
for (const seat of options.seats) {
const seatDir = await demoPrivateDir(join(dir, seat));
const control: SeatControl = { seat, sandbox: randomUUID(), expiresAt: new Date(Date.now() + options.lifetime * 60_000).toISOString(), cdpReachable: false };
await writeSeatControl(seatDir, control);
owned.push(control);
control.sandbox = await provider.create(control.sandbox, snapshot, options.lifetime);
await writeSeatControl(seatDir, control);
await provider.prepare(control.sandbox, options.timezone);
control.cdpReachable = true;
Object.assign(control, await provider.viewer(control.sandbox, control.expiresAt));
await writeSeatControl(seatDir, control);
}
return { directory: dir, ready: `${owned.length}/${options.seats.length}`, infrastructureEstimateUsd: estimate };
} catch {
const cleanup = await Promise.allSettled(owned.map(async (control) => {
await provider.remove(control.sandbox);
await writeSeatControl(join(dir, control.seat), { ...control, viewer: undefined, viewerExpiresAt: undefined, stopped: true, cdpReachable: false });
}));
throw new Error(cleanup.some((result) => result.status === "rejected")
? "Demo launch failed; cleanup incomplete. Retry down using the private receipts; provider TTL remains the backstop."
: "Demo launch failed; owned sandboxes removed. Start a new stage to retry.");
} finally { await rm(lock, { recursive: true }); }
}
/** Refresh and cleanup use only the selected stage's receipts, never a fleet query. */
export async function manageDemo(dir: string, action: "refresh" | "down", provider: DemoProvider) {
await demoPrivateDir(dir, false);
const lock = join(dir, ".busy");
await mkdir(lock, { mode: 0o700 });
try { return await manageLockedDemo(dir, action, provider); }
finally { await rm(lock, { recursive: true }); }
}
async function manageLockedDemo(dir: string, action: "refresh" | "down", provider: DemoProvider) {
const seats = (await readdir(dir)).filter((name) => name !== ".busy");
const failed: string[] = [];
for (const seat of seats) {
try {
const seatDir = await demoPrivateDir(join(dir, seat), false);
const control = await readSeatControl(seatDir, seat);
if (control.stopped) continue;
if (action === "down") {
await provider.remove(control.sandbox);
await writeSeatControl(seatDir, { ...control, viewer: undefined, viewerExpiresAt: undefined, stopped: true, cdpReachable: false });
} else {
if (Date.parse(control.expiresAt) <= Date.now()) throw new Error("Expired seat.");
await provider.prepare(control.sandbox, "");
await writeSeatControl(seatDir, { ...control, ...await provider.viewer(control.sandbox, control.expiresAt), cdpReachable: true });
}
} catch { failed.push(seat); }
}
if (failed.length) throw new Error(`Demo ${action} incomplete for ${failed.length} seat(s); inspect private receipts and retry. No links logged.`);
return { directory: dir, action };
}
+70
View File
@@ -0,0 +1,70 @@
export const DEMO_SEATS = ["demo", "practice", "backup"];
export const DEFAULT_DEMO_SOURCE = "release:0.18.71/cloud";
export const DEFAULT_DEMO_BUDGET = 30;
export const MAX_DEMO_LIFETIME = 1440;
export const MAX_DEMO_DISK = 40;
export function demoFlags(argv: readonly string[], known: readonly string[]) {
const flags = new Map<string, string>();
for (let i = 0; i < argv.length; i += 2) {
const flag = argv[i], value = argv[i + 1];
if (!flag || !known.includes(flag) || flags.has(flag) || !value || value.startsWith("--")) {
throw new Error(`Use one value per flag, with no duplicates: ${known.join(", ")}.`);
}
flags.set(flag, value);
}
return flags;
}
export function demoSnapshotName(value: string | undefined): string {
if (!value || !/^demo-desktop-[a-z0-9][a-z0-9-]{0,47}$/.test(value)) {
throw new Error("Pass --snapshot demo-desktop-<lowercase-name> (letters, digits and dashes).");
}
return value;
}
export function demoSeat(value: string): string {
if (!DEMO_SEATS.includes(value)) throw new Error("Demo seats are demo, practice and backup.");
return value;
}
export function demoStage(value = "default"): string {
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,31}$/.test(value)) throw new Error("Invalid demo stage.");
return value;
}
export type DemoSource = { kind: "release"; version: string; source: string } | { kind: "sha"; sha: string; source: string };
export function parseDemoSource(value: string): DemoSource {
const release = /^release:(\d+\.\d+\.\d+)(?:\/(cloud))?$/.exec(value);
if (release?.[1]) return { kind: "release", version: release[1], source: `release:${release[1]}/cloud` };
const sha = /^sha:([a-f0-9]{40})$/.exec(value)?.[1];
if (sha) return { kind: "sha", sha, source: `sha:${sha}` };
throw new Error("Use --source release:<version>/cloud or sha:<full lowercase pushed SHA>.");
}
export function parseDemoOptions(argv: readonly string[]) {
const flags = demoFlags(argv, ["--snapshot", "--seats", "--lifetime", "--timezone", "--budget-usd"]);
const seats = flags.get("--seats")?.split(",").map(demoSeat) ?? [...DEMO_SEATS];
if (new Set(seats).size !== seats.length) throw new Error("Do not repeat a demo seat.");
const lifetime = flags.get("--lifetime") ?? "1440";
if (!/^\d+$/.test(lifetime) || Number(lifetime) < 10 || Number(lifetime) > MAX_DEMO_LIFETIME) {
throw new Error("--lifetime must be 10–1440 minutes.");
}
const timezone = flags.get("--timezone") ?? "America/Los_Angeles";
if (!/^[A-Za-z]+(?:\/[A-Za-z0-9_+-]+){1,2}$/.test(timezone)) throw new Error("Invalid IANA timezone.");
new Intl.DateTimeFormat("en", { timeZone: timezone });
const budget = flags.get("--budget-usd") ?? String(DEFAULT_DEMO_BUDGET);
if (!/^\d+(?:\.\d{1,2})?$/.test(budget) || !Number.isFinite(Number(budget))) throw new Error("Invalid --budget-usd.");
return { snapshot: demoSnapshotName(flags.get("--snapshot")), seats, lifetime: Number(lifetime), timezone, budget: Number(budget) };
}
export function demoInfrastructureUsd(seats: number, lifetime: number, diskGiB: number): number {
return seats * (4 * 0.083 * lifetime / 60 + diskGiB * 0.0001 * lifetime / 60);
}
export function guardDemoBudget(options: ReturnType<typeof parseDemoOptions>, diskGiB: number): number {
const estimate = demoInfrastructureUsd(options.seats.length, options.lifetime, diskGiB);
if (estimate > options.budget) throw new Error(`Estimated infrastructure $${estimate.toFixed(2)} exceeds --budget-usd ${options.budget}; shorten the lifetime or raise the budget deliberately.`);
return estimate;
}
+88
View File
@@ -0,0 +1,88 @@
import { randomUUID } from "node:crypto";
import { lstat, mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { output } from "../../packages/world/src/outputs.ts";
import { demoSeat, demoStage } from "./demo-options.ts";
import { idPattern, isRecord } from "./demo-snapshot.ts";
export interface SeatControl {
seat: string;
sandbox: string;
expiresAt: string;
cdpReachable: boolean;
viewer?: string;
viewerExpiresAt?: string;
stopped?: boolean;
}
async function outsideCheckout(path: string) {
for (let dir = path; dir !== dirname(dir); dir = dirname(dir)) {
const git = await lstat(join(dir, ".git")).catch((error: unknown) => {
if (isRecord(error) && error.code === "ENOENT") return null;
throw error;
});
if (git) throw new Error("Demo output must not be inside a Git checkout.");
}
}
export async function demoPrivateDir(path: string, create = true, exclusive = false) {
// Reject checkout paths before writing, including paths through symlinks.
const parent = await realpath(dirname(path));
await outsideCheckout(parent);
if (create) await mkdir(path, { mode: 0o700 }).catch((error: unknown) => {
if (exclusive || !isRecord(error) || error.code !== "EEXIST") throw error;
});
const stat = await lstat(path);
if (!stat.isDirectory() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o700 || await realpath(path) !== join(parent, path.split("/").at(-1) ?? "")) {
throw new Error("Demo output directory must be caller-owned, mode 0700, and not a symlink.");
}
await outsideCheckout(await realpath(path));
return path;
}
export async function demoRootDir(create = true) {
const parent = join(homedir(), ".openwork");
if (create) {
await outsideCheckout(await realpath(homedir()));
await mkdir(parent, { mode: 0o700, recursive: true });
}
await demoPrivateDir(parent, false);
return demoPrivateDir(join(parent, "demos"), create);
}
export async function demoStageDir(stage: string, create = true) {
demoStage(stage);
return demoPrivateDir(join(await demoRootDir(create), stage), create);
}
export async function writeDemoJson(path: string, value: unknown) {
const tmp = `${path}.${randomUUID()}.tmp`;
try {
await writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: "wx" });
await rename(tmp, path);
} finally { await rm(tmp, { force: true }); }
}
export async function writeSeatControl(dir: string, control: SeatControl) {
await writeDemoJson(join(dir, "control.json"), control);
}
export async function readSeatControl(dir: string, seat: string): Promise<SeatControl> {
const path = join(dir, "control.json");
const stat = await lstat(path);
if (!stat.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o777) !== 0o600) throw new Error("Invalid private seat receipt permissions.");
const data: unknown = JSON.parse(await readFile(path, "utf8"));
if (!isRecord(data) || data.seat !== demoSeat(seat) || typeof data.sandbox !== "string" || !idPattern.test(data.sandbox)
|| typeof data.expiresAt !== "string" || !Number.isFinite(Date.parse(data.expiresAt)) || typeof data.cdpReachable !== "boolean") {
throw new Error("Invalid demo seat receipt.");
}
return { seat, sandbox: data.sandbox, expiresAt: data.expiresAt, cdpReachable: data.cdpReachable,
...(data.stopped === true ? { stopped: true } : {}),
...(typeof data.viewer === "string" && typeof data.viewerExpiresAt === "string" ? { viewer: data.viewer, viewerExpiresAt: data.viewerExpiresAt } : {}) };
}
/** Never pass links to world outputs/events/logs, even as secret output values. */
export function demoWorldOutputs(dir: string, controls: readonly SeatControl[], total: number) {
return { directory: output(dir), ready: output(`${controls.filter((seat) => seat.viewer && seat.cdpReachable).length}/${total}`) };
}
+75
View File
@@ -0,0 +1,75 @@
import { setTimeout as delay } from "node:timers/promises";
import { daytonaSandboxLimitArgs, defaultDaytonaExec } from "../../evals/packages/hosts/src/daytona.ts";
import type { DaytonaExec } from "../../evals/packages/hosts/src/daytona.ts";
import { deleteSandboxes, execInSandbox } from "../../evals/packages/hosts/src/provision.ts";
import { privateSandboxId, privateWebPreview } from "../../evals/packages/hosts/src/private-web-preview.ts";
import { verifyViewer } from "./private-viewer.ts";
import { idPattern, isRecord } from "./demo-snapshot.ts";
export async function demoCli(args: string[], context: string, timeoutMs = 30_000, exec: DaytonaExec = defaultDaytonaExec): Promise<string> {
try {
const result = await exec(args, { timeoutMs });
if (result.code === 0) return result.stdout;
} catch { /* Do not log provider output or command arguments. */ }
throw new Error(`${context} failed; no provider output logged.`);
}
export async function demoGuest(id: string, script: string, context: string, timeoutMs = 90_000): Promise<string> {
try {
return (await execInSandbox(defaultDaytonaExec, id, `printf %s ${Buffer.from(script).toString("base64")} | base64 -d | bash`, { context, timeoutMs })).stdout;
} catch { throw new Error(`${context} failed; no guest output logged.`); }
}
/** Use the reviewed immutable ID, not the reusable name. No env or secrets mounts. */
export async function createDemoSandbox(name: string, snapshot: string, ttlMinutes: number, exec: DaytonaExec = defaultDaytonaExec) {
if (!idPattern.test(snapshot) || !idPattern.test(name)) throw new Error("Missing immutable snapshot ID or unique sandbox name.");
await demoCli(["create", "--name", name, "--snapshot", snapshot, "--target", "us", "--auto-stop", "0",
...daytonaSandboxLimitArgs({ ttlMinutes })], "Create private Daytona sandbox", 300_000, exec);
let id: string;
try { id = await privateSandboxId(name, exec); }
catch { throw new Error("Could not confirm sandbox privacy or identity."); }
if (!idPattern.test(id)) throw new Error("Could not confirm sandbox UUID.");
return id;
}
export async function deleteDemoSandbox(id: string, exec: DaytonaExec = defaultDaytonaExec) {
try {
if (!idPattern.test(id)) throw new Error("Invalid sandbox receipt.");
// A pending create has only its random name journaled. Resolve it before delete.
const info: unknown = JSON.parse(await demoCli(["info", id, "-f", "json"], "Resolve owned sandbox", 30_000, exec));
if (!isRecord(info) || (info.id !== id && info.name !== id) || info.public !== false
|| typeof info.id !== "string" || !idPattern.test(info.id)) throw new Error("Invalid identity.");
await deleteSandboxes([info.id], { exec, log: () => {} });
} catch { throw new Error("Daytona deletion could not be confirmed; retry cleanup or rely on the provider TTL."); }
}
export async function demoSandboxInfo(id: string): Promise<{ state: string; createdAt: string }> {
const data: unknown = JSON.parse(await demoCli(["info", id, "-f", "json"], "Read sandbox status"));
if (!isRecord(data) || data.id !== id || data.public !== false || typeof data.state !== "string"
|| typeof data.createdAt !== "string" || !Number.isFinite(Date.parse(data.createdAt))) throw new Error("Invalid private sandbox status.");
return { state: data.state, createdAt: data.createdAt };
}
export async function waitForDemoGuest(id: string) {
for (let attempt = 0; attempt < 20; attempt++) {
if (await demoGuest(id, "test \"$(id -un)\" = daytona && DISPLAY=:99 xset q >/dev/null", "Wait for desktop", 8_000).then(() => true, () => false)) return;
await delay(1_500);
}
throw new Error("The Daytona desktop was not ready.");
}
export async function demoCdpReachable(id: string): Promise<boolean> {
return demoGuest(id, "curl --noproxy '*' -fsS --max-time 3 http://127.0.0.1:9223/json/version >/dev/null", "Check guest CDP", 8_000).then(() => true, () => false);
}
export async function mintDemoViewer(id: string, expiresAt: string) {
const now = Date.now();
const seconds = Math.min(3600, Math.floor((Date.parse(expiresAt) - now) / 1000));
if (seconds < 1) throw new Error("Sandbox lifetime has expired; launch a new stage.");
try {
const { browserOrigin } = await privateWebPreview(id, 6080, defaultDaytonaExec, seconds);
const viewer = `${browserOrigin}/vnc.html?autoconnect=1&resize=scale&view_only=0&reconnect=1&reconnect_delay=2000`;
await verifyViewer(viewer, id);
return { viewer, viewerExpiresAt: new Date(now + seconds * 1000).toISOString() };
} catch { throw new Error("Could not verify the signed private noVNC viewer. No URL published."); }
}
+64
View File
@@ -0,0 +1,64 @@
import { readFile } from "node:fs/promises";
import { DaytonaApi, DaytonaApiError, daytonaConfig } from "../../packages/daytona-evidence/src/api.ts";
import { demoSnapshotName, MAX_DEMO_DISK, parseDemoSource } from "./demo-options.ts";
export const DEMO_CPU = 4;
export const DEMO_MEMORY = 8;
export const DEMO_AUDIT = "demo-clean-base-v1: passed";
export const demoManifest = new URL("../../scripts/demo/snapshots.json", import.meta.url);
export const idPattern = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i;
export interface DemoSnapshot {
id: string;
image: string;
sourceSandboxId: string;
source: string;
packageSha256: string;
diskGiB: number;
audit: typeof DEMO_AUDIT;
}
export function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
export function parseDemoSnapshot(value: unknown): DemoSnapshot {
if (!isRecord(value) || typeof value.id !== "string" || !idPattern.test(value.id)
|| typeof value.sourceSandboxId !== "string" || !idPattern.test(value.sourceSandboxId)
|| typeof value.image !== "string" || !/^[\w./:-]+@sha256:[a-f0-9]{64}$/.test(value.image)
|| typeof value.packageSha256 !== "string" || !/^[a-f0-9]{64}$/.test(value.packageSha256)
|| typeof value.diskGiB !== "number" || !Number.isInteger(value.diskGiB) || value.diskGiB < 10 || value.diskGiB > MAX_DEMO_DISK
|| value.audit !== DEMO_AUDIT || typeof value.source !== "string" || parseDemoSource(value.source).source !== value.source) {
throw new Error("Invalid demo snapshot review entry (identity, source, package digest, disk or audit missing).");
}
return { id: value.id, image: value.image, sourceSandboxId: value.sourceSandboxId, source: value.source,
packageSha256: value.packageSha256, diskGiB: value.diskGiB, audit: value.audit };
}
export function reviewedDemoSnapshot(manifest: unknown, name: string): DemoSnapshot {
demoSnapshotName(name);
if (!isRecord(manifest) || !Object.hasOwn(manifest, name)) throw new Error(`No reviewed entry for ${name} in scripts/demo/snapshots.json.`);
return parseDemoSnapshot(manifest[name]);
}
export function verifyDemoSnapshot(name: string, expected: DemoSnapshot, actual: unknown): void {
if (!isRecord(actual) || actual.state !== "active" || actual.name !== name || actual.id !== expected.id
|| actual.ref !== expected.image || actual.sourceSandboxId !== expected.sourceSandboxId
|| actual.cpu !== DEMO_CPU || actual.mem !== DEMO_MEMORY || actual.disk !== expected.diskGiB) {
throw new Error(`Daytona snapshot ${name} does not match the reviewed provenance or resources.`);
}
}
export async function readReviewedDemoSnapshot(name: string): Promise<DemoSnapshot> {
return reviewedDemoSnapshot(JSON.parse(await readFile(demoManifest, "utf8")), name);
}
export function demoDaytonaApi() {
if (!process.env.DAYTONA_API_URL?.trim()) throw new Error("Set DAYTONA_API_URL and DAYTONA_API_KEY for the same Daytona team (CLI and REST).");
return new DaytonaApi(daytonaConfig());
}
export async function getRawDemoSnapshot(api: DaytonaApi, name: string): Promise<unknown> {
try { return await api.call("GET", `/snapshots/${encodeURIComponent(name)}`); }
catch (error) { if (error instanceof DaytonaApiError && error.status === 404) return null; throw new Error("Could not inspect Daytona snapshot metadata."); }
}
+29
View File
@@ -0,0 +1,29 @@
import { parsePrivatePreview } from "../../evals/packages/hosts/src/private-web-preview.ts";
async function rfb(url: string, expectOpen: boolean): Promise<void> {
const endpoint = new URL("/websockify", url);
endpoint.protocol = "wss:";
await new Promise<void>((resolve, reject) => {
const socket = new WebSocket(endpoint, ["binary"]);
socket.binaryType = "arraybuffer";
const timer = setTimeout(() => finish(new Error("Viewer WebSocket probe timed out.")), 15_000);
const finish = (error?: Error) => { clearTimeout(timer); socket.close(); error ? reject(error) : resolve(); };
socket.onmessage = (event) => {
const text = typeof event.data === "string" ? event.data : new TextDecoder().decode(event.data);
finish(expectOpen && text.startsWith("RFB 003.") ? undefined : new Error("Viewer RFB authentication check failed."));
};
socket.onopen = () => { if (!expectOpen) finish(new Error("Unsigned viewer WebSocket unexpectedly opened.")); };
socket.onerror = () => finish(expectOpen ? new Error("Signed viewer WebSocket failed.") : undefined);
});
}
export async function verifyViewer(signed: string, sandboxId: string): Promise<void> {
const origins = parsePrivatePreview(new URL(signed).origin, sandboxId, 6080);
const get = (url: string) => fetch(url, { redirect: "error", headers: { "X-Daytona-Skip-Preview-Warning": "true" }, signal: AbortSignal.timeout(30_000) });
const unsigned = await get(origins.unsignedOrigin);
if (![401, 403].includes(unsigned.status)) throw new Error("Unsigned viewer HTTP access was not denied.");
const response = await get(signed);
if (!response.ok || !/novnc|vnc/i.test(await response.text())) throw new Error("Signed noVNC viewer unavailable.");
await rfb(origins.unsignedOrigin, false);
await rfb(signed, true);
}
+3 -27
View File
@@ -1,4 +1,5 @@
import { randomBytes } from "node:crypto";
import { verifyViewer } from "./lib/private-viewer.ts";
import { assertTrustedWorkshopRef } from "./lib/workshop-trust.ts";
import { chmod, lstat, mkdir, realpath, writeFile } from "node:fs/promises";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
@@ -29,6 +30,8 @@ import { unlockWorkshopDesktop } from "./lib/workshop-unlock.ts";
import { readWorkshopAudit, validateAuditedPilotRead } from "./lib/workshop-pilot-audit.ts";
import { connectWorkshopBrowser, foregroundWorkshopDesktop, installWorkshopBrowser, verifyWorkshopBrowserHandoff, WORKSHOP_BROWSER_LAUNCHER, WORKSHOP_BROWSER_PROFILE } from "./lib/workshop-browser.ts";
export { verifyViewer } from "./lib/private-viewer.ts";
export const summary = "Private shared Den/Gateway and isolated workshop Linux desktops; pilot must pass before fan-out.";
export const supportedTargets = ["daytona/linux"];
const REPO_ROOT = fileURLToPath(new URL("..", import.meta.url));
@@ -122,33 +125,6 @@ export async function verifySandbox(sandbox: string) {
return validateSandboxInfo(JSON.parse(result.stdout));
}
async function rfb(url: string, expectOpen: boolean): Promise<void> {
const endpoint = new URL("/websockify", url);
endpoint.protocol = "wss:";
await new Promise<void>((resolve, reject) => {
const socket = new WebSocket(endpoint, ["binary"]);
socket.binaryType = "arraybuffer";
const timer = setTimeout(() => finish(new Error("Viewer WebSocket probe timed out.")), 15_000);
const finish = (error?: Error) => { clearTimeout(timer); socket.close(); error ? reject(error) : resolve(); };
socket.onmessage = (event) => {
const text = typeof event.data === "string" ? event.data : new TextDecoder().decode(event.data);
finish(expectOpen && text.startsWith("RFB 003.") ? undefined : new Error("Viewer RFB authentication check failed."));
};
socket.onopen = () => { if (!expectOpen) finish(new Error("Unsigned viewer WebSocket unexpectedly opened.")); };
socket.onerror = () => finish(expectOpen ? new Error("Signed viewer WebSocket failed.") : undefined);
});
}
export async function verifyViewer(signed: string, sandboxId: string): Promise<void> {
const origins = parsePrivatePreview(new URL(signed).origin, sandboxId, 6080);
const get = (url: string) => fetch(url, { redirect: "error", headers: { "X-Daytona-Skip-Preview-Warning": "true" }, signal: AbortSignal.timeout(30_000) });
const unsigned = await get(origins.unsignedOrigin);
if (![401, 403].includes(unsigned.status)) throw new Error("Unsigned viewer HTTP access was not denied.");
const response = await get(signed);
if (!response.ok || !/novnc|vnc/i.test(await response.text())) throw new Error("Signed noVNC viewer unavailable.");
await rfb(origins.unsignedOrigin, false);
await rfb(signed, true);
}
async function memberGet(member: DenSession, orgId: string, path: string): Promise<unknown> {
const result = await denFetch(member, path, { headers: { authorization: `Bearer ${member.token}`, "x-openwork-org-id": orgId } });
if (!result.response.ok) throw new Error(`Workshop member verification failed: HTTP ${result.response.status}.`);