@sandboxrouter/sdk 0.20.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,158 @@
1
+ import type { FileBox, Mover } from "./move.js";
2
+ import { type RestoreOptions, type RestoreResult, type SaveOptions, type SaveStore } from "./save.js";
3
+ import type { Spawned, SpawnOptions } from "./spawn.js";
4
+ import { type ExecOptions, type ExecResult, type ProviderId, type RouteOptions, type SandboxSpec } from "./types.js";
5
+ /**
6
+ * Who ends a lingering sandbox:
7
+ * - "provider": the provider was told the new lifetime and ends the sandbox itself.
8
+ * - "sandbox": a command left running inside the sandbox ends it (only on providers where that was seen to work).
9
+ * - "create-timeout": nothing could be changed, so the lifetime it was created with (`timeoutMinutes`)
10
+ * still applies, which is not the time asked for. What a provider does when that runs out is its
11
+ * adapter's mapping of `timeoutMinutes` (most delete the sandbox, a few put it to sleep).
12
+ * - "none": nothing known will end it. Call `kill()`.
13
+ */
14
+ export type EnforcedBy = "provider" | "sandbox" | "create-timeout" | "none";
15
+ export interface LingerOptions {
16
+ /**
17
+ * "expire" (default): preview links stop when the linger time is up, even where the sandbox
18
+ * itself lives longer. Gate links are given the new expiry inside the sandbox (never a later one);
19
+ * a provider-issued link made by this sandbox object that would outlive a sandbox nothing ends
20
+ * in time is revoked now. "keep": links are left as they are.
21
+ */
22
+ previews?: "expire" | "keep";
23
+ }
24
+ /** What `linger` arranged: read `endsAt` and `enforcedBy`, they say what will really happen. */
25
+ export interface Lingering {
26
+ /** The seconds asked for. */
27
+ seconds: number;
28
+ /** When the sandbox will end by itself (ISO), or null when nothing known will end it. */
29
+ endsAt: string | null;
30
+ enforcedBy: EnforcedBy;
31
+ /** Why a stronger way was not used, when one was tried or is missing. */
32
+ note?: string;
33
+ /** Preview links dealt with: gates given the new expiry, provider-issued links revoked now. */
34
+ previews: {
35
+ gates: number;
36
+ revoked: number;
37
+ };
38
+ }
39
+ /** A provider-issued preview link the sandbox object knows about. */
40
+ export interface IssuedLink {
41
+ expiresAt: Date;
42
+ revoke(): Promise<void>;
43
+ }
44
+ /** What linger needs from a sandbox. `RoutedSandbox` hands this in. */
45
+ export interface LingerBox {
46
+ readonly provider: string;
47
+ exec(cmd: string, opts?: ExecOptions): Promise<ExecResult>;
48
+ spawn(cmd: string, opts?: SpawnOptions): Promise<Spawned>;
49
+ endAfter?: (seconds: number) => Promise<{
50
+ endsAt: Date;
51
+ }>;
52
+ /** When the lifetime given at create runs out (ISO), when known. */
53
+ createEndsAt?: string;
54
+ links?: IssuedLink[];
55
+ }
56
+ /**
57
+ * Providers where a sandbox ends for good when a command inside it runs this. A provider is listed
58
+ * only after that was seen on a real account (2026-12-04): the sandbox stopped answering and the
59
+ * provider itself then reported it as not found. Tried and left out: Vercel, Maritime, Sail and
60
+ * Tensorlake (the machine stops answering, but the provider reports an error, not an ended
61
+ * sandbox), Freestyle and Agent37 (the sandbox kept running). There linger falls back to the
62
+ * lifetime given at create.
63
+ */
64
+ export declare const SELF_END: Partial<Record<ProviderId, string>>;
65
+ /** Seconds a linger may ask for: up to a day. */
66
+ export declare const MAX_LINGER_SECONDS = 86400;
67
+ /**
68
+ * Keep a sandbox for `seconds` more, then have it end by itself, with no client alive. In order:
69
+ * the provider's own lifetime setting where it can be changed after create, a command inside the
70
+ * sandbox where that is known to end it, else the lifetime it was created with. The result says
71
+ * which, and when: it never claims an end nobody enforces.
72
+ */
73
+ export declare function lingerSandbox(box: LingerBox, seconds: number, opts?: LingerOptions, selfEnd?: string | undefined): Promise<Lingering>;
74
+ /**
75
+ * What `suspend` returns: plain JSON, enough to bring the work back with `router.resume`.
76
+ *
77
+ * `kind` says what was kept, and the two are not the same thing:
78
+ * - "paused": the provider put the sandbox to sleep. Its whole disk is kept, and on most providers
79
+ * its memory and running processes too (on some, pause is a stop: the disk is kept, processes end).
80
+ * Resume wakes that same sandbox.
81
+ * - "saved": the provider has no pause, so the working folder was packed into your store and the
82
+ * sandbox was killed. Only that folder is kept: running processes, memory, env vars, and anything
83
+ * installed outside the folder (system packages) are gone. Resume starts a new sandbox and puts
84
+ * the folder back.
85
+ */
86
+ export type Suspended = PausedSandbox | SavedSandbox;
87
+ export interface PausedSandbox {
88
+ kind: "paused";
89
+ v: 1;
90
+ /** The sandbox's routed id (`provider:nativeId`): `router.resume` wakes it. */
91
+ id: string;
92
+ provider: string;
93
+ /** When it was suspended (ISO). */
94
+ at: string;
95
+ }
96
+ export interface SavedSandbox {
97
+ kind: "saved";
98
+ v: 1;
99
+ /** The provider the sandbox was on: resume tries it first. */
100
+ provider: string;
101
+ /** The id of the sandbox that was killed. */
102
+ sandbox: string;
103
+ at: string;
104
+ /** The save's name in the store. */
105
+ name: string;
106
+ /** The folder that was saved. */
107
+ folder: string;
108
+ /** Size of the packed folder. */
109
+ bytes: number;
110
+ /** The spec the sandbox was created with (image, size, ports, lifetime; empty when this router did not create it), without `env`: env values are often secrets and a handle gets stored and logged. Pass `spec.env` to resume. */
111
+ spec: Omit<SandboxSpec, "env">;
112
+ }
113
+ export interface SuspendOptions extends Omit<SaveOptions, "name"> {
114
+ /** Where the folder goes when the provider has no pause (`folderStore(dir)`, or anything with put/get/delete). Not used for a native pause. */
115
+ store?: SaveStore;
116
+ /** Force one way: "saved" to save the folder even where the provider can pause, "paused" to fail where it can't. */
117
+ kind?: "paused" | "saved";
118
+ /** The save's name in the store. Default: the sandbox's id. */
119
+ name?: string;
120
+ }
121
+ export interface ResumeOptions extends RouteOptions, RestoreOptions {
122
+ /** The store the folder was saved to. Needed for a "saved" handle. */
123
+ store?: SaveStore;
124
+ /** Changes to the saved spec for the new sandbox, e.g. `env`. Not used for a "paused" handle. */
125
+ spec?: SandboxSpec;
126
+ }
127
+ /** How a resume went. */
128
+ export interface Resumed {
129
+ kind: "paused" | "saved";
130
+ /** The provider the suspended sandbox was on. */
131
+ from: string;
132
+ /** Set for "saved": the folder put back into the new sandbox. */
133
+ restored?: RestoreResult;
134
+ }
135
+ /** What suspend needs from a sandbox. */
136
+ export interface SuspendBox extends FileBox {
137
+ readonly canPause: boolean;
138
+ pause(): Promise<void>;
139
+ readonly spec?: SandboxSpec;
140
+ }
141
+ /**
142
+ * Put a sandbox to sleep keeping its work, on any provider. With a native pause the provider keeps
143
+ * the sandbox; without one the working folder is saved to `store` and the sandbox is killed. The
144
+ * handle's `kind` says which happened.
145
+ */
146
+ export declare function suspendSandbox(box: SuspendBox, opts?: SuspendOptions): Promise<Suspended>;
147
+ /** What resume needs from a router. */
148
+ export interface Resumer<B extends FileBox> extends Mover<B> {
149
+ get(id: string): Promise<B>;
150
+ }
151
+ /**
152
+ * Bring a suspended sandbox back from its handle. "paused": the same sandbox, woken. "saved": a new
153
+ * sandbox with the saved folder in it, on the provider it was on when that provider can take it,
154
+ * on another one otherwise.
155
+ */
156
+ export declare function resumeSandbox<B extends FileBox>(router: Resumer<B>, handle: Suspended, opts?: ResumeOptions): Promise<B & {
157
+ resumed: Resumed;
158
+ }>;
@@ -0,0 +1,171 @@
1
+ import { expireGates } from "./preview.js";
2
+ import { recoverSandbox, saveFiles } from "./save.js";
3
+ import { RouterError } from "./types.js";
4
+ /**
5
+ * Run inside the sandbox to end it: power the machine off, as root where that is possible, and if
6
+ * that does nothing end its first process. Each step that works never returns.
7
+ */
8
+ const END_FROM_INSIDE = [
9
+ `s() { if [ "$(id -u)" = 0 ]; then "$@"; elif command -v sudo > /dev/null 2>&1; then sudo -n "$@"; else "$@"; fi; }`,
10
+ "s poweroff -f > /dev/null 2>&1",
11
+ "sleep 3",
12
+ "s sh -c 'echo 1 > /proc/sys/kernel/sysrq; echo o > /proc/sysrq-trigger' > /dev/null 2>&1",
13
+ "sleep 3",
14
+ "s halt -f -p > /dev/null 2>&1",
15
+ "sleep 3",
16
+ "s kill -TERM 1 > /dev/null 2>&1",
17
+ "sleep 3",
18
+ "s kill -KILL 1 > /dev/null 2>&1",
19
+ ].join("\n");
20
+ /**
21
+ * Providers where a sandbox ends for good when a command inside it runs this. A provider is listed
22
+ * only after that was seen on a real account (2026-12-04): the sandbox stopped answering and the
23
+ * provider itself then reported it as not found. Tried and left out: Vercel, Maritime, Sail and
24
+ * Tensorlake (the machine stops answering, but the provider reports an error, not an ended
25
+ * sandbox), Freestyle and Agent37 (the sandbox kept running). There linger falls back to the
26
+ * lifetime given at create.
27
+ */
28
+ export const SELF_END = { modal: END_FROM_INSIDE, cloudflare: END_FROM_INSIDE };
29
+ /** Seconds a linger may ask for: up to a day. */
30
+ export const MAX_LINGER_SECONDS = 86_400;
31
+ /**
32
+ * Keep a sandbox for `seconds` more, then have it end by itself, with no client alive. In order:
33
+ * the provider's own lifetime setting where it can be changed after create, a command inside the
34
+ * sandbox where that is known to end it, else the lifetime it was created with. The result says
35
+ * which, and when: it never claims an end nobody enforces.
36
+ */
37
+ export async function lingerSandbox(box, seconds, opts = {}, selfEnd = SELF_END[box.provider]) {
38
+ if (!Number.isFinite(seconds) || seconds < 1 || seconds > MAX_LINGER_SECONDS)
39
+ throw new RouterError(`linger takes a number of seconds from 1 to ${MAX_LINGER_SECONDS}`, [], "bad_request");
40
+ if (opts.previews !== undefined && opts.previews !== "expire" && opts.previews !== "keep")
41
+ throw new RouterError('previews must be "expire" or "keep"', [], "bad_request");
42
+ const asked = Date.now() + seconds * 1000;
43
+ const notes = [];
44
+ let endsAt = null;
45
+ let enforcedBy = "none";
46
+ if (box.endAfter) {
47
+ try {
48
+ endsAt = (await box.endAfter(seconds)).endsAt.toISOString();
49
+ enforcedBy = "provider";
50
+ }
51
+ catch (error) {
52
+ notes.push(`${box.provider} refused the new lifetime (${error instanceof Error ? error.message : String(error)})`);
53
+ }
54
+ }
55
+ if (enforcedBy === "none" && selfEnd) {
56
+ try {
57
+ // Left running in the sandbox, detached from this process: it needs no client to fire.
58
+ const cmd = await box.spawn(`sleep ${Math.ceil(seconds)}\n${selfEnd}`, { keep: true });
59
+ cmd.detach();
60
+ endsAt = new Date(asked).toISOString();
61
+ enforcedBy = "sandbox";
62
+ }
63
+ catch (error) {
64
+ notes.push(`the command that ends the sandbox from inside could not be started (${error instanceof Error ? error.message : String(error)})`);
65
+ }
66
+ }
67
+ if (enforcedBy === "none") {
68
+ if (!box.endAfter && !selfEnd)
69
+ notes.push(`${box.provider} has no way to change a sandbox's lifetime after create that this SDK knows of`);
70
+ if (box.createEndsAt) {
71
+ endsAt = box.createEndsAt;
72
+ enforcedBy = "create-timeout";
73
+ notes.push(`the lifetime it was created with (timeoutMinutes) still applies and runs out then, not ${Math.ceil(seconds)} s from now: call kill() to end it sooner`);
74
+ }
75
+ else {
76
+ notes.push("its create lifetime is not known here either (it was not created by this router): call kill() to end it");
77
+ }
78
+ }
79
+ const previews = { gates: 0, revoked: 0 };
80
+ if (opts.previews !== "keep") {
81
+ previews.gates = await expireGates(box, seconds).catch(() => 0);
82
+ // A provider-issued link cannot be given a new expiry. It ends with the sandbox when that ends in
83
+ // time; when it would not, it is revoked now.
84
+ const inTime = endsAt !== null && Date.parse(endsAt) <= asked + 60_000;
85
+ for (const link of [...(box.links ?? [])]) {
86
+ if (link.expiresAt.getTime() <= asked || inTime)
87
+ continue;
88
+ await link.revoke().then(() => previews.revoked++, () => { });
89
+ }
90
+ }
91
+ return { seconds, endsAt, enforcedBy, ...(notes.length ? { note: notes.join("; ") } : {}), previews };
92
+ }
93
+ /**
94
+ * Put a sandbox to sleep keeping its work, on any provider. With a native pause the provider keeps
95
+ * the sandbox; without one the working folder is saved to `store` and the sandbox is killed. The
96
+ * handle's `kind` says which happened.
97
+ */
98
+ export async function suspendSandbox(box, opts = {}) {
99
+ const { store, kind: asked, ...save } = opts;
100
+ if (asked !== undefined && asked !== "paused" && asked !== "saved")
101
+ throw new RouterError('kind must be "paused" or "saved"', [], "bad_request");
102
+ const kind = asked ?? (box.canPause ? "paused" : "saved");
103
+ if (kind === "paused") {
104
+ if (!box.canPause)
105
+ throw new RouterError(`${box.provider} does not support pause: suspend without kind saves the working folder to a store`, [], "unsupported");
106
+ // What was just written is on disk before the provider takes its snapshot.
107
+ await box.exec("sync", { timeoutSeconds: 60 }).catch(() => { });
108
+ await box.pause();
109
+ return { kind: "paused", v: 1, id: box.id, provider: box.provider, at: new Date().toISOString() };
110
+ }
111
+ if (!store) {
112
+ throw new RouterError(`${box.canPause ? "a saved suspend" : `${box.provider} has no pause, so suspend saves the working folder and kills the sandbox: it`} needs somewhere to put the folder; pass store (folderStore(dir), or your own put/get/delete)`, [], "bad_request");
113
+ }
114
+ const saved = await saveFiles(box, store, save).catch((error) => {
115
+ // A sandbox whose commands run in / (Modal's stock image) has no working folder to save whole.
116
+ if (save.path === undefined && error instanceof RouterError && /whole filesystem/.test(error.message)) {
117
+ throw new RouterError(`commands on ${box.provider} run in /, which can't be saved whole: pass path, the folder your work is in`, [], "bad_request");
118
+ }
119
+ throw error;
120
+ });
121
+ const { env: _env, ...spec } = box.spec ?? {};
122
+ const handle = {
123
+ kind: "saved",
124
+ v: 1,
125
+ provider: box.provider,
126
+ sandbox: box.id,
127
+ at: saved.at,
128
+ name: saved.name,
129
+ folder: saved.folder,
130
+ bytes: saved.bytes,
131
+ spec,
132
+ };
133
+ try {
134
+ await box.kill();
135
+ }
136
+ catch (error) {
137
+ throw new RouterError(`the folder was saved as "${saved.name}", but ${box.provider} did not kill the sandbox (${error instanceof Error ? error.message : String(error)}): kill it, then resume with ${JSON.stringify(handle)}`, [], "all_failed");
138
+ }
139
+ return handle;
140
+ }
141
+ /**
142
+ * Bring a suspended sandbox back from its handle. "paused": the same sandbox, woken. "saved": a new
143
+ * sandbox with the saved folder in it, on the provider it was on when that provider can take it,
144
+ * on another one otherwise.
145
+ */
146
+ export async function resumeSandbox(router, handle, opts = {}) {
147
+ const h = handle;
148
+ if (!h || typeof h !== "object" || typeof h.provider !== "string" || (h.kind !== "paused" && h.kind !== "saved")) {
149
+ throw new RouterError("not a suspend handle: pass what suspend() returned", [], "bad_request");
150
+ }
151
+ if (h.kind === "paused") {
152
+ if (typeof h.id !== "string")
153
+ throw new RouterError("a paused handle needs the sandbox's id", [], "bad_request");
154
+ const box = await router.get(h.id);
155
+ return Object.assign(box, { resumed: { kind: "paused", from: h.provider } });
156
+ }
157
+ if (typeof h.name !== "string")
158
+ throw new RouterError("a saved handle needs the save's name", [], "bad_request");
159
+ const { store, spec: changes, to, timeoutSeconds, chunkBytes, ...route } = opts;
160
+ if (!store)
161
+ throw new RouterError(`this sandbox was suspended by saving its folder as "${h.name}": pass the store it was saved to`, [], "bad_request");
162
+ const spec = { ...(h.spec ?? {}), ...changes };
163
+ if (route.provider === undefined) {
164
+ // Back where it was when that provider can take it; the others, in the router's usual order, after it.
165
+ const usable = (await router.candidates(spec, route)).filter((c) => !c.skip).map((c) => c.provider);
166
+ if (usable.length > 0)
167
+ route.provider = [...usable.filter((p) => p === h.provider), ...usable.filter((p) => p !== h.provider)];
168
+ }
169
+ const box = await recoverSandbox(router, store, h.name, { ...route, spec, to, timeoutSeconds, chunkBytes });
170
+ return Object.assign(box, { resumed: { kind: "saved", from: h.provider, restored: box.restored } });
171
+ }
@@ -0,0 +1,104 @@
1
+ import type { Spawned, SpawnOptions } from "./spawn.js";
2
+ import { type ExecOptions, type ExecResult } from "./types.js";
3
+ export interface PreviewOptions {
4
+ /** Seconds the link works for (default 3600, 7 days at most). */
5
+ expiresInSeconds?: number;
6
+ /**
7
+ * Default true: only someone holding the link can open the app. `false` asks for a link without
8
+ * a token of ours that still stops at the expiry (the gate lets every request through until
9
+ * then). Where the provider issues the link (`via: "native"`) it is signed either way.
10
+ */
11
+ private?: boolean;
12
+ /**
13
+ * The port the gate listens on. Default: a port named in `spec.ports` at create other than the
14
+ * app's, else any free port. Modal and Vercel only route ports named at create, so there the
15
+ * sandbox needs two: `ports: [3000, 3001]`.
16
+ */
17
+ gatePort?: number;
18
+ /** Use the gate even where the provider issues private links itself. */
19
+ via?: "gate";
20
+ /** Run the gate with this, not the first of node and python3 the image has. */
21
+ runtime?: GateRuntime;
22
+ /**
23
+ * Default true: once the gate is up, ask the provider's plain URL for the app's port once, from
24
+ * this machine, to see whether the app can be reached around the gate (`warnings` says so).
25
+ * `false` skips that request.
26
+ */
27
+ checkExposure?: boolean;
28
+ }
29
+ export type GateRuntime = "node" | "python3";
30
+ /** A link to an app in a sandbox that only its holder can open and that stops working. */
31
+ export interface PreviewLink {
32
+ /** The link to hand out. It carries the access token: treat it as a secret. */
33
+ url: string;
34
+ /**
35
+ * When the link stops working (ISO). For a gate it is counted on the sandbox's clock from the
36
+ * moment the gate started, so it can be a second or two off this machine's.
37
+ */
38
+ expiresAt: string;
39
+ /** "native": the provider issued the link and enforces it. "gate": a proxy this SDK started in the sandbox does. */
40
+ via: "native" | "gate";
41
+ /** The app's port. */
42
+ port: number;
43
+ /** Gate only: the access token in the link (`?sr_token=`). */
44
+ token?: string;
45
+ /** Gate only: the port the gate listens on. */
46
+ gatePort?: number;
47
+ /** Gate only: what runs the gate. */
48
+ runtime?: GateRuntime;
49
+ /** Things to know about this link: the app's port reachable around the gate, nothing listening yet. */
50
+ warnings: string[];
51
+ /** Stop the link now. */
52
+ revoke(): Promise<void>;
53
+ }
54
+ /** What a preview needs from a sandbox. `RoutedSandbox` hands this in. */
55
+ export interface PreviewBox {
56
+ readonly provider: string;
57
+ exec(cmd: string, opts?: ExecOptions): Promise<ExecResult>;
58
+ writeFile(path: string, content: string | Uint8Array): Promise<void>;
59
+ spawn(cmd: string, opts?: SpawnOptions): Promise<Spawned>;
60
+ /** The provider's plain URL for a port. Undefined when it has none. */
61
+ url?: (port: number) => Promise<string>;
62
+ /** The provider's own private, expiring link, where it issues them. */
63
+ privateUrl?: (port: number, expiresInSeconds: number) => Promise<{
64
+ url: string;
65
+ expiresAt: Date;
66
+ reaches?: "interface";
67
+ revoke(): Promise<void>;
68
+ }>;
69
+ /** Ports named when the sandbox was created, when known. */
70
+ ports?: number[];
71
+ }
72
+ export declare const DEFAULT_PREVIEW_SECONDS = 3600;
73
+ export declare const MAX_PREVIEW_SECONDS: number;
74
+ /** Where gates keep their files in the sandbox, one folder each. Removing a folder stops its gate. */
75
+ export declare const GATE_DIRS = "/tmp/sr-gate-";
76
+ /**
77
+ * A link to an app listening on `port` that only its holder can open and that stops working after
78
+ * `expiresInSeconds`.
79
+ *
80
+ * Where the provider issues such links itself (Daytona signed preview URLs, Blaxel private preview
81
+ * tokens) that is what you get. Everywhere else with a public port URL, a small proxy (the gate)
82
+ * is started inside the sandbox on another port: it forwards to 127.0.0.1:`port` only for requests
83
+ * that carry the link's token, and refuses everything after the expiry. The first visit with
84
+ * `?sr_token=` sets an HttpOnly cookie and redirects to the same path without it, so the page's
85
+ * own links, assets, fetches and WebSockets work.
86
+ *
87
+ * The gate guards its own port. The provider's plain URL for the app's port is still there for
88
+ * anyone who guesses it, unless the app listens on 127.0.0.1 only: bind the app to 127.0.0.1.
89
+ * `warnings` says so when it is found listening on every interface.
90
+ */
91
+ export declare function previewLink(box: PreviewBox, port: number, opts?: PreviewOptions): Promise<PreviewLink>;
92
+ /** Stop every gate in a sandbox, whichever process started them. */
93
+ export declare function revokeGates(box: Pick<PreviewBox, "exec">): Promise<void>;
94
+ /**
95
+ * Make every gate in a sandbox expire `seconds` from now by the sandbox's clock, unless it expires
96
+ * sooner already. Returns how many gates were told.
97
+ */
98
+ export declare function expireGates(box: Pick<PreviewBox, "exec">, seconds: number): Promise<number>;
99
+ /**
100
+ * What to know about how the app's port is exposed. Where it is listening is read from the
101
+ * sandbox's own socket table (/proc/net/tcp); `outside`, when given, asks the provider's plain URL
102
+ * for the port. A port that answers there is reachable around the gate.
103
+ */
104
+ export declare function listeningWarnings(box: Pick<PreviewBox, "exec" | "provider" | "url">, port: number, outside?: (box: Pick<PreviewBox, "url">, port: number) => Promise<number | undefined>): Promise<string[]>;
@@ -0,0 +1,209 @@
1
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
2
+ import { GATE_NODE, GATE_PYTHON } from "./gate-scripts.js";
3
+ import { RouterError } from "./types.js";
4
+ import { isPort } from "./validate.js";
5
+ import { shq } from "./util.js";
6
+ export const DEFAULT_PREVIEW_SECONDS = 3600;
7
+ export const MAX_PREVIEW_SECONDS = 7 * 86_400;
8
+ /** Where gates keep their files in the sandbox, one folder each. Removing a folder stops its gate. */
9
+ export const GATE_DIRS = "/tmp/sr-gate-";
10
+ /** Seconds to wait for a started gate to say which port it took. */
11
+ const GATE_START_S = 30;
12
+ const bad = (message) => new RouterError(message, [], "bad_request");
13
+ /**
14
+ * A link to an app listening on `port` that only its holder can open and that stops working after
15
+ * `expiresInSeconds`.
16
+ *
17
+ * Where the provider issues such links itself (Daytona signed preview URLs, Blaxel private preview
18
+ * tokens) that is what you get. Everywhere else with a public port URL, a small proxy (the gate)
19
+ * is started inside the sandbox on another port: it forwards to 127.0.0.1:`port` only for requests
20
+ * that carry the link's token, and refuses everything after the expiry. The first visit with
21
+ * `?sr_token=` sets an HttpOnly cookie and redirects to the same path without it, so the page's
22
+ * own links, assets, fetches and WebSockets work.
23
+ *
24
+ * The gate guards its own port. The provider's plain URL for the app's port is still there for
25
+ * anyone who guesses it, unless the app listens on 127.0.0.1 only: bind the app to 127.0.0.1.
26
+ * `warnings` says so when it is found listening on every interface.
27
+ */
28
+ export async function previewLink(box, port, opts = {}) {
29
+ if (!isPort(port))
30
+ throw bad("port must be an integer from 1 to 65535");
31
+ const seconds = opts.expiresInSeconds ?? DEFAULT_PREVIEW_SECONDS;
32
+ if (!Number.isInteger(seconds) || seconds < 1 || seconds > MAX_PREVIEW_SECONDS)
33
+ throw bad(`expiresInSeconds must be a whole number from 1 to ${MAX_PREVIEW_SECONDS}`);
34
+ if (opts.gatePort !== undefined && (!isPort(opts.gatePort) || opts.gatePort === port))
35
+ throw bad("gatePort must be a port other than the app's");
36
+ if (opts.runtime !== undefined && opts.runtime !== "node" && opts.runtime !== "python3")
37
+ throw bad('runtime must be "node" or "python3"');
38
+ if (box.privateUrl && opts.via !== "gate") {
39
+ const link = await box.privateUrl(port, seconds);
40
+ const warnings = [];
41
+ if (link.reaches === "interface") {
42
+ // The provider connects to the sandbox's network interface: an app on 127.0.0.1 only is not reached.
43
+ const local = await listeners(box, port);
44
+ if (local && local.length > 0 && local.every((a) => loopback4(a) || loopback6(a))) {
45
+ warnings.push(`port ${port} is listening on the loopback interface only, and ${box.provider}'s preview does not reach it there: bind the app to 0.0.0.0 (the provider keeps the preview private)`);
46
+ }
47
+ }
48
+ return { url: link.url, expiresAt: link.expiresAt.toISOString(), via: "native", port, warnings, revoke: () => link.revoke() };
49
+ }
50
+ if (!box.url) {
51
+ throw new RouterError(`${box.provider} gives a sandbox no public URL for its ports, so there is nothing a preview link could point to; create with require: ["ports"]`, [], "unsupported");
52
+ }
53
+ const found = await box.exec("for t in node python3; do command -v $t > /dev/null 2>&1 && echo \"have:$t\"; done; exit 0", { timeoutSeconds: 60 });
54
+ const have = ["node", "python3"].filter((t) => found.stdout.includes(`have:${t}`));
55
+ const runtime = opts.runtime ?? have[0];
56
+ if (!runtime || !have.includes(runtime)) {
57
+ throw new RouterError(`a preview link on ${box.provider} needs ${opts.runtime ?? "node or python3"} in the sandbox to run the gate, and this image has ${have.length ? `only ${have.join(" and ")}` : "neither"}`, [], "unsupported");
58
+ }
59
+ const isPrivate = opts.private !== false;
60
+ // 256 random bits. Only its SHA-256 goes into the sandbox: the gate can check a token, not produce one.
61
+ const token = isPrivate ? randomBytes(32).toString("base64url") : undefined;
62
+ const hash = token ? createHash("sha256").update(token).digest("hex") : "-";
63
+ const dir = `${GATE_DIRS}${randomUUID().replace(/-/g, "").slice(0, 12)}`;
64
+ const file = `${dir}/${runtime === "node" ? "gate.js" : "gate.py"}`;
65
+ const named = (box.ports ?? []).filter((p) => p !== port);
66
+ const listen = opts.gatePort !== undefined ? [opts.gatePort] : [...named, 0];
67
+ const revoke = async () => {
68
+ // The gate leaves within a second of its folder going.
69
+ await box.exec(`rm -rf ${shq(dir)}`, { timeoutSeconds: 60 });
70
+ };
71
+ const made = await box.exec(`mkdir -p ${shq(dir)} && chmod 700 ${shq(dir)}`, { timeoutSeconds: 60 });
72
+ if (made.exitCode !== 0)
73
+ throw new RouterError(`preparing the gate failed on ${box.provider} (exit ${made.exitCode}): ${made.stderr.trim().slice(0, 200)}`, [], "all_failed");
74
+ try {
75
+ await box.writeFile(file, runtime === "node" ? GATE_NODE : GATE_PYTHON);
76
+ let out = "";
77
+ let err = "";
78
+ const cmd = await box.spawn(`exec ${runtime} ${shq(file)} ${listen.join(",")} ${port} ${seconds} ${hash} ${shq(dir)}`, {
79
+ pollMs: 200,
80
+ onStdout: (s) => (out += s),
81
+ onStderr: (s) => (err += s),
82
+ });
83
+ const startedAt = Date.now();
84
+ const ended = cmd.wait().then((r) => `it ended with exit code ${r.exitCode}${(r.stderr || err).trim() ? `: ${(r.stderr || err).trim().split("\n").slice(-2).join(" ").slice(0, 300)}` : ""}`, (e) => (e instanceof Error ? e.message : String(e)));
85
+ let gatePort;
86
+ let why;
87
+ while (gatePort === undefined && why === undefined) {
88
+ const m = /SRGATE port=(\d+)/.exec(out);
89
+ if (m)
90
+ gatePort = Number(m[1]);
91
+ else if (/SRGATE fail/.test(out))
92
+ why = `no port to listen on (tried ${listen.map((p) => p || "any free port").join(", ")})`;
93
+ else if (Date.now() - startedAt > GATE_START_S * 1000)
94
+ why = `it did not start within ${GATE_START_S} s`;
95
+ else
96
+ why = await Promise.race([ended, new Promise((res) => setTimeout(res, 100))]);
97
+ }
98
+ if (gatePort === undefined) {
99
+ await cmd.kill().catch(() => { });
100
+ throw new RouterError(`the preview gate could not start on ${box.provider}: ${why}`, [], "all_failed");
101
+ }
102
+ // From here the gate runs on its own: nothing of this process keeps it alive or reads it.
103
+ cmd.detach();
104
+ let base;
105
+ try {
106
+ base = await box.url(gatePort);
107
+ }
108
+ catch (error) {
109
+ const message = error instanceof Error ? error.message : String(error);
110
+ const unnamed = /not requested when this sandbox was created/.test(message);
111
+ throw new RouterError(`${box.provider} has no public URL for the gate's port ${gatePort} (${message})` +
112
+ (unnamed ? `. This provider only routes ports named when the sandbox is created: create it with a port for the gate, e.g. ports: [${port + 1}], and pass gatePort: ${port + 1}` : ""), [], "unsupported");
113
+ }
114
+ const url = new URL(base);
115
+ if (token)
116
+ url.searchParams.set("sr_token", token);
117
+ return {
118
+ url: url.toString(),
119
+ expiresAt: new Date(startedAt + seconds * 1000).toISOString(),
120
+ via: "gate",
121
+ port,
122
+ ...(token ? { token } : {}),
123
+ gatePort,
124
+ runtime,
125
+ warnings: await listeningWarnings(box, port, opts.checkExposure === false ? undefined : outsideAnswer),
126
+ revoke,
127
+ };
128
+ }
129
+ catch (error) {
130
+ await revoke().catch(() => { });
131
+ throw error;
132
+ }
133
+ }
134
+ /** Stop every gate in a sandbox, whichever process started them. */
135
+ export async function revokeGates(box) {
136
+ await box.exec(`rm -rf ${GATE_DIRS}*`, { timeoutSeconds: 60 });
137
+ }
138
+ /**
139
+ * Make every gate in a sandbox expire `seconds` from now by the sandbox's clock, unless it expires
140
+ * sooner already. Returns how many gates were told.
141
+ */
142
+ export async function expireGates(box, seconds) {
143
+ const r = await box.exec(`e=$(( $(date +%s) + ${Math.max(0, Math.ceil(seconds))} )); n=0; for d in ${GATE_DIRS}*; do [ -d "$d" ] || continue; echo "$e" > "$d/exp.tmp" && mv "$d/exp.tmp" "$d/exp" && n=$((n + 1)); done; echo "gates=$n"`, { timeoutSeconds: 60 });
144
+ return Number(/gates=(\d+)/.exec(r.stdout)?.[1] ?? 0);
145
+ }
146
+ /**
147
+ * Where the app's port is listening, read from the sandbox's own socket table (/proc/net/tcp):
148
+ * a port open on every interface is reachable at the provider's plain URL, around the gate.
149
+ */
150
+ /** What the provider's plain URL for a port answers from this machine: an HTTP status, or undefined when there is no such URL or nothing answers. */
151
+ async function outsideAnswer(box, port) {
152
+ try {
153
+ const plain = await box.url(port);
154
+ const res = await fetch(plain, { method: "GET", redirect: "manual", signal: AbortSignal.timeout(8000) });
155
+ await res.body?.cancel().catch(() => { });
156
+ return res.status;
157
+ }
158
+ catch {
159
+ return undefined;
160
+ }
161
+ }
162
+ /**
163
+ * What to know about how the app's port is exposed. Where it is listening is read from the
164
+ * sandbox's own socket table (/proc/net/tcp); `outside`, when given, asks the provider's plain URL
165
+ * for the port. A port that answers there is reachable around the gate.
166
+ */
167
+ export async function listeningWarnings(box, port, outside) {
168
+ const local = await listeners(box, port);
169
+ if (!local) {
170
+ return [`could not check where port ${port} is listening (no /proc/net/tcp in this sandbox): make sure the app binds 127.0.0.1, or ${box.provider}'s plain URL for port ${port} goes around the gate`];
171
+ }
172
+ if (local.length === 0)
173
+ return [`nothing is listening on port ${port} yet, so how it is exposed could not be checked: the link answers 502 until the app starts (bind it to 127.0.0.1)`];
174
+ const everywhere = local.some((a) => !loopback4(a) && !loopback6(a));
175
+ const warnings = [];
176
+ // An answer that is not a gateway error, on a port where the app is listening: the app, reached directly.
177
+ const status = outside && box.url ? await outside(box, port) : undefined;
178
+ if (status !== undefined && status < 500) {
179
+ warnings.push(`${box.provider}'s own URL for port ${port} answers (HTTP ${status}), and it goes around the gate: the link's token, expiry and revoke() do not apply there. ` +
180
+ (everywhere
181
+ ? `Port ${port} is listening on every interface: bind the app to 127.0.0.1. If it still answers after that, this provider forwards to local ports and the gate cannot close it here`
182
+ : `The app is bound to the loopback interface and is reached anyway: ${box.provider} forwards to local ports. Where ports are named at create, leave ${port} out of spec.ports so it has no URL; where every port has a URL, the gate cannot close this one`));
183
+ }
184
+ else if (everywhere) {
185
+ warnings.push(`port ${port} is listening on every interface (0.0.0.0), so ${box.provider}'s plain URL for it can go around the gate: bind the app to 127.0.0.1`);
186
+ }
187
+ if (local.every(loopback6))
188
+ warnings.push(`port ${port} is listening on ::1 (IPv6) only: the gate forwards to 127.0.0.1, so bind the app to 127.0.0.1`);
189
+ return warnings;
190
+ }
191
+ const loopback4 = (a) => a.length === 8 && a.endsWith("7F");
192
+ const loopback6 = (a) => a.length === 32 && /^0{24}0{6}01$|^0{24}01000000$/.test(a);
193
+ /** The local addresses (hex, as /proc/net/tcp writes them) a port is listening on, or undefined when the sandbox has no socket table to read. */
194
+ async function listeners(box, port) {
195
+ const hex = port.toString(16).toUpperCase().padStart(4, "0");
196
+ const r = await box
197
+ .exec(`if [ -r /proc/net/tcp ]; then echo proc=1; cat /proc/net/tcp /proc/net/tcp6 2> /dev/null | grep -i ':${hex} ' ; fi; exit 0`, { timeoutSeconds: 60 })
198
+ .catch(() => undefined);
199
+ if (!r || !r.stdout.includes("proc=1"))
200
+ return undefined;
201
+ const local = [];
202
+ for (const line of r.stdout.split("\n")) {
203
+ const f = line.trim().split(/\s+/);
204
+ // "<n>: <local addr>:<port> <remote> <state>": 0A is LISTEN.
205
+ if (f.length > 3 && f[3].toUpperCase() === "0A" && f[1].toUpperCase().endsWith(`:${hex}`))
206
+ local.push(f[1].slice(0, f[1].lastIndexOf(":")).toUpperCase());
207
+ }
208
+ return local;
209
+ }