Skip to content

An open-source, faster Devin alternative

TypeScript

add preview url auth

Brian Reardon8b2ae8d87888
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 0aafc639..ce50f80e 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -286,6 +286,31 @@ function parsePreviewHost(hostname: string): { sandboxID: string; port: number }
return { sandboxID: m[1], port };
}
+// generatePreviewToken produces a 32-byte random token, URL-safe base64
+// encoded. The output is ~43 chars, no padding, 256 bits of entropy — more
+// than enough that a SHA-256 of it is fine for the at-rest hash (we don't
+// need PBKDF2/scrypt because there's no low-entropy input to stretch).
+function generatePreviewToken(): string {
+ const bytes = new Uint8Array(32);
+ crypto.getRandomValues(bytes);
+ let bin = "";
+ for (const b of bytes) bin += String.fromCharCode(b);
+ return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
+}
+
+// extractPreviewToken pulls the bearer token from one of two accepted
+// headers. Returns null when neither is present or the Authorization header
+// uses a non-Bearer scheme. Tokens-in-querystring are deliberately not
+// supported — they leak into logs and browser history.
+function extractPreviewToken(req: Request): string | null {
+ const x = req.headers.get("X-OC-Preview-Token");
+ if (x) return x.trim();
+ const auth = req.headers.get("Authorization");
+ if (!auth) return null;
+ const m = auth.match(/^Bearer\s+(.+)$/i);
+ return m ? m[1].trim() : null;
+}
+
// handlePreviewURL is the edge-routed equivalent of the cell-local
// ControlPlaneProxy.Middleware: resolve the sandbox to its owning cell via
// D1, then forward the request through that cell's Tunnel to its CP's
@@ -301,13 +326,13 @@ async function handlePreviewURL(
m: { sandboxID: string; port: number },
): Promise<Response> {
const row = await env.OPENCOMPUTER_DB.prepare(
- `SELECT s.cell_id, s.status, c.base_url
+ `SELECT s.cell_id, s.status, s.preview_auth_hash, s.preview_auth_scheme, c.base_url
FROM sandboxes_index s
JOIN cells c ON s.cell_id = c.cell_id
WHERE s.id = ?1`,
)
.bind(m.sandboxID)
- .first<{ cell_id: string; status: string; base_url: string }>();
+ .first<{ cell_id: string; status: string; preview_auth_hash: string | null; preview_auth_scheme: string | null; base_url: string }>();
if (!row) return new Response(`sandbox ${m.sandboxID} not found`, { status: 404 });
if (row.status === "stopped" || row.status === "error") {
@@ -315,6 +340,26 @@ async function handlePreviewURL(
}
// status="hibernated" is fine — CP's doProxy will wake-on-request.
+ // Bearer auth gate. When preview_auth_hash is NULL the URL is open (legacy
+ // default). With a hash set, require a matching token in either
+ // `Authorization: Bearer <t>` or `X-OC-Preview-Token: <t>`. We never accept
+ // the token in the query string — that would leak into browser history and
+ // server logs. Check happens before forwarding so a brute-force run hits
+ // the edge worker, not the customer's VM.
+ if (row.preview_auth_hash) {
+ const presented = extractPreviewToken(req);
+ if (!presented) {
+ return new Response("preview URL requires authentication", {
+ status: 401,
+ headers: { "WWW-Authenticate": 'Bearer realm="preview"' },
+ });
+ }
+ const presentedHash = await sha256Hex(presented);
+ if (!constantTimeEqual(presentedHash, row.preview_auth_hash)) {
+ return new Response("invalid preview token", { status: 401 });
+ }
+ }
+
const url = new URL(req.url);
const base = row.base_url.replace(/\/$/, "");
const target = `${base}/internal/preview/${m.sandboxID}/${m.port}${url.pathname}${url.search}`;
@@ -445,13 +490,41 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {
let bodyCpuCount = 0;
let bodyMemoryMB = 0;
let bodyDiskMB = 0;
+ // Preview-URL bearer auth (opt-in). Caller sends `previewAuth: { scheme,
+ // token }`. `token: "auto"` (or omitted) → we generate a random one.
+ // An explicit string lets the caller bring its own (e.g. so its gateway
+ // can mint and share a token with both ends in one round-trip).
+ // The plaintext is returned exactly once in the create response; only
+ // the SHA-256 hex lives in D1.
+ let previewAuthScheme: string | null = null;
+ let previewAuthHash: string | null = null;
+ let previewAuthPlaintext: string | null = null;
try {
if (bodyText) {
- const parsed = JSON.parse(bodyText) as { cellId?: unknown; cpuCount?: unknown; memoryMB?: unknown; diskMB?: unknown };
+ const parsed = JSON.parse(bodyText) as {
+ cellId?: unknown; cpuCount?: unknown; memoryMB?: unknown; diskMB?: unknown;
+ previewAuth?: { scheme?: unknown; token?: unknown };
+ };
if (typeof parsed.cellId === "string") requestedCellID = parsed.cellId;
if (typeof parsed.cpuCount === "number") bodyCpuCount = parsed.cpuCount;
if (typeof parsed.memoryMB === "number") bodyMemoryMB = parsed.memoryMB;
if (typeof parsed.diskMB === "number") bodyDiskMB = parsed.diskMB;
+ if (parsed.previewAuth && typeof parsed.previewAuth === "object") {
+ const scheme = typeof parsed.previewAuth.scheme === "string" ? parsed.previewAuth.scheme : "bearer";
+ if (scheme !== "bearer") {
+ return json({ error: `previewAuth.scheme must be "bearer" (got ${JSON.stringify(scheme)})` }, 400);
+ }
+ const t = parsed.previewAuth.token;
+ if (t === undefined || t === "auto" || t === null) {
+ previewAuthPlaintext = generatePreviewToken();
+ } else if (typeof t === "string" && t.length >= 16) {
+ previewAuthPlaintext = t;
+ } else {
+ return json({ error: "previewAuth.token must be omitted, \"auto\", or a string of at least 16 characters" }, 400);
+ }
+ previewAuthScheme = "bearer";
+ previewAuthHash = await sha256Hex(previewAuthPlaintext);
+ }
}
} catch {
/* malformed JSON — let the CP reject with a proper 400 */
@@ -523,8 +596,8 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {
if (parsed.sandboxID) {
await env.OPENCOMPUTER_DB.prepare(
`INSERT OR REPLACE INTO sandboxes_index
- (id, org_id, user_id, cell_id, worker_id, status, cpu_count, memory_mb, created_at, last_event_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9)`,
+ (id, org_id, user_id, cell_id, worker_id, status, cpu_count, memory_mb, created_at, last_event_at, preview_auth_hash, preview_auth_scheme)
+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9, ?10, ?11)`,
)
.bind(
parsed.sandboxID,
@@ -536,9 +609,23 @@ async function createSandbox(req: Request, env: Env): Promise<Response> {
bodyCpuCount,
parsed.memoryMB ?? bodyMemoryMB,
Math.floor(Date.now() / 1000),
+ previewAuthHash,
+ previewAuthScheme,
)
.run();
}
+ // Overlay the plaintext preview-auth token onto the CP's response body so
+ // the caller gets `previewAuthToken` alongside `sandboxID` in one round
+ // trip. We do this only on success and only when one was generated/set.
+ // The token is never persisted at the edge in plaintext and never
+ // returned again — rotation issues a new one.
+ if (previewAuthPlaintext) {
+ const merged = { ...parsed, previewAuthToken: previewAuthPlaintext };
+ return new Response(JSON.stringify(merged), {
+ status: cpResp.status,
+ headers: { "content-type": "application/json" },
+ });
+ }
}
// Pass the CP's response through verbatim (status + body).
return new Response(cpText, {
@@ -592,6 +679,29 @@ function sandboxRowToJSON(r: SandboxRow): Record<string, unknown> {
};
}
+// rotatePreviewAuth issues a new bearer token, swaps the hash on
+// sandboxes_index, and returns the plaintext exactly once. Idempotent in the
+// sense that calling it again produces a fresh token and invalidates the
+// previous one — there is no zero-downtime dual-token mode yet, so the
+// gateway should be able to absorb a brief window of 401s during rollover.
+async function rotatePreviewAuth(req: Request, env: Env, id: string): Promise<Response> {
+ const caller = await authenticate(req, env);
+ if (!caller) return json({ error: "missing or invalid API key" }, 401);
+ const row = await env.OPENCOMPUTER_DB.prepare(
+ "SELECT org_id, status FROM sandboxes_index WHERE id = ?1",
+ ).bind(id).first<{ org_id: string; status: string }>();
+ if (!row || row.org_id !== caller.orgID) return json({ error: "sandbox not found" }, 404);
+ if (row.status === "stopped" || row.status === "error") {
+ return json({ error: `sandbox is ${row.status}` }, 410);
+ }
+ const token = generatePreviewToken();
+ const hash = await sha256Hex(token);
+ await env.OPENCOMPUTER_DB.prepare(
+ "UPDATE sandboxes_index SET preview_auth_hash = ?1, preview_auth_scheme = 'bearer' WHERE id = ?2",
+ ).bind(hash, id).run();
+ return json({ previewAuthToken: token, scheme: "bearer" });
+}
+
async function listSandboxes(req: Request, env: Env): Promise<Response> {
const caller = await authenticate(req, env);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
@@ -1692,6 +1802,11 @@ export default {
}
return json({ error: "method not allowed" }, 405);
}
+ // Preview-URL auth lives purely at the edge — the cell never sees the
+ // hash. Intercept the rotate before the cell-proxy fallback catches it.
+ if (rest === "/preview/rotate" && req.method === "POST") {
+ return rotatePreviewAuth(req, env, id);
+ }
// Anything under /:id/* (exec, files, pty, hibernate, …) lives on the
// cell — proxy with an edge-minted IdentityToken (the cell's existing
// API-key middleware accepts that JWT shape) so we don't depend on the
diff --git a/cloudflare-workers/schema.sql b/cloudflare-workers/schema.sql
index 20f11441..0e707618 100644
--- a/cloudflare-workers/schema.sql
+++ b/cloudflare-workers/schema.sql
@@ -132,16 +132,18 @@ CREATE TABLE IF NOT EXISTS cells (
-- Global sandbox index (cross-region routing and listing) -----------------
CREATE TABLE IF NOT EXISTS sandboxes_index (
- id TEXT PRIMARY KEY, -- sandbox_id
- org_id TEXT NOT NULL,
- user_id TEXT,
- cell_id TEXT NOT NULL,
- worker_id TEXT,
- status TEXT NOT NULL, -- running | hibernated | stopped | error
- template_id TEXT,
- created_at INTEGER NOT NULL,
- last_event_at INTEGER,
- stopped_at INTEGER
+ id TEXT PRIMARY KEY, -- sandbox_id
+ org_id TEXT NOT NULL,
+ user_id TEXT,
+ cell_id TEXT NOT NULL,
+ worker_id TEXT,
+ status TEXT NOT NULL, -- running | hibernated | stopped | error
+ template_id TEXT,
+ created_at INTEGER NOT NULL,
+ last_event_at INTEGER,
+ stopped_at INTEGER,
+ preview_auth_hash TEXT, -- SHA-256 hex of the bearer token (NULL = open)
+ preview_auth_scheme TEXT -- "bearer" today; reserved for HMAC/JWT later
);
CREATE INDEX IF NOT EXISTS idx_sandboxes_org_status ON sandboxes_index(org_id, status);
CREATE INDEX IF NOT EXISTS idx_sandboxes_cell ON sandboxes_index(cell_id, status);
diff --git a/cloudflare-workers/schema_phase5_preview_auth.sql b/cloudflare-workers/schema_phase5_preview_auth.sql
new file mode 100644
index 00000000..2675c415
--- /dev/null
+++ b/cloudflare-workers/schema_phase5_preview_auth.sql
@@ -0,0 +1,12 @@
+-- Phase 5: preview URL authentication.
+--
+-- Adds a per-sandbox bearer token check enforced at the edge. The plaintext
+-- token is shown once on sandbox create (or rotate); only its SHA-256 hex
+-- digest lands here. When preview_auth_hash IS NULL the preview URL is open
+-- (current behavior — backwards compatible).
+--
+-- Scheme is split into its own column so we can add HMAC / JWT verification
+-- later without another migration. Today only "bearer" is supported.
+
+ALTER TABLE sandboxes_index ADD COLUMN preview_auth_hash TEXT;
+ALTER TABLE sandboxes_index ADD COLUMN preview_auth_scheme TEXT;
diff --git a/cmd/oc/internal/commands/preview.go b/cmd/oc/internal/commands/preview.go
index 57efc739..7bbf5bc0 100644
--- a/cmd/oc/internal/commands/preview.go
+++ b/cmd/oc/internal/commands/preview.go
@@ -113,6 +113,29 @@ var previewDeleteCmd = &cobra.Command{
},
}
+// previewRotateAuthCmd issues a fresh bearer token for the sandbox's
+// edge-enforced preview-URL auth gate. The old token stops working
+// immediately — no dual-token grace period in v1.
+var previewRotateAuthCmd = &cobra.Command{
+ Use: "rotate-auth <sandbox-id>",
+ Short: "Rotate the sandbox's preview-URL bearer token",
+ Args: cobra.ExactArgs(1),
+ RunE: func(cmd *cobra.Command, args []string) error {
+ c := client.FromContext(cmd.Context())
+ var resp struct {
+ PreviewAuthToken string `json:"previewAuthToken"`
+ Scheme string `json:"scheme"`
+ }
+ if err := c.Post(cmd.Context(), fmt.Sprintf("/sandboxes/%s/preview/rotate", args[0]), nil, &resp); err != nil {
+ return err
+ }
+ printer.Print(resp, func() {
+ fmt.Printf("New preview auth token (shown once): %s\n", resp.PreviewAuthToken)
+ })
+ return nil
+ },
+}
+
func init() {
previewCreateCmd.Flags().Int("port", 0, "Container port to expose (required)")
previewCreateCmd.Flags().String("domain", "", "Custom domain")
@@ -121,4 +144,5 @@ func init() {
previewCmd.AddCommand(previewCreateCmd)
previewCmd.AddCommand(previewListCmd)
previewCmd.AddCommand(previewDeleteCmd)
+ previewCmd.AddCommand(previewRotateAuthCmd)
}
diff --git a/cmd/oc/internal/commands/sandbox.go b/cmd/oc/internal/commands/sandbox.go
index e263c108..330a86fc 100644
--- a/cmd/oc/internal/commands/sandbox.go
+++ b/cmd/oc/internal/commands/sandbox.go
@@ -27,6 +27,8 @@ var sandboxCreateCmd = &cobra.Command{
envSlice, _ := cmd.Flags().GetStringSlice("env")
metaSlice, _ := cmd.Flags().GetStringSlice("metadata")
secretStore, _ := cmd.Flags().GetString("secret-store")
+ previewAuth, _ := cmd.Flags().GetBool("preview-auth")
+ previewAuthToken, _ := cmd.Flags().GetString("preview-auth-token")
config := types.SandboxConfig{
Timeout: timeout,
@@ -55,6 +57,20 @@ var sandboxCreateCmd = &cobra.Command{
if secretStore != "" {
body["secretStore"] = secretStore
}
+ // --preview-auth-token implies --preview-auth. Either flag attaches the
+ // previewAuth block to the create payload; only the token-having flag
+ // supplies a caller-chosen secret. The plaintext is returned exactly
+ // once via the sandbox response's PreviewAuthToken field; print it
+ // prominently so a piped/scripted caller can capture it.
+ if previewAuth || previewAuthToken != "" {
+ pa := map[string]string{"scheme": "bearer"}
+ if previewAuthToken != "" {
+ pa["token"] = previewAuthToken
+ } else {
+ pa["token"] = "auto"
+ }
+ body["previewAuth"] = pa
+ }
var sandbox types.Sandbox
if err := c.Post(cmd.Context(), "/sandboxes", body, &sandbox); err != nil {
@@ -63,6 +79,9 @@ var sandboxCreateCmd = &cobra.Command{
printer.Print(sandbox, func() {
fmt.Printf("Created sandbox %s (status: %s)\n", sandbox.ID, sandbox.Status)
+ if sandbox.PreviewAuthToken != "" {
+ fmt.Printf("Preview auth token (shown once): %s\n", sandbox.PreviewAuthToken)
+ }
})
return nil
},
@@ -274,6 +293,8 @@ func init() {
cmd.Flags().StringSlice("env", nil, "Environment variables (KEY=VALUE)")
cmd.Flags().StringSlice("metadata", nil, "Metadata (KEY=VALUE)")
cmd.Flags().String("secret-store", "", "Secret store name (injects encrypted secrets)")
+ cmd.Flags().Bool("preview-auth", false, "Require a bearer token on the sandbox's preview URLs (server generates a 256-bit token, printed once)")
+ cmd.Flags().String("preview-auth-token", "", "Bring your own preview-URL bearer token (>=16 chars); implies --preview-auth")
}
// sandbox wake flags
diff --git a/pkg/types/sandbox.go b/pkg/types/sandbox.go
index 9919dd47..c2790ab7 100644
--- a/pkg/types/sandbox.go
+++ b/pkg/types/sandbox.go
@@ -35,6 +35,10 @@ type Sandbox struct {
ConnectURL string `json:"connectURL,omitempty"`
Token string `json:"token,omitempty"`
HostPort int `json:"hostPort,omitempty"` // Mapped host port for the sandbox's container port
+ // PreviewAuthToken is the plaintext bearer token for the sandbox's
+ // preview URL, returned exactly once on create when previewAuth was
+ // requested. Empty otherwise. Mirrors the SDK field by the same name.
+ PreviewAuthToken string `json:"previewAuthToken,omitempty"`
}
// SandboxConfig is the request body for creating a sandbox.
diff --git a/sdks/python/opencomputer/sandbox.py b/sdks/python/opencomputer/sandbox.py
index 61b4f18e..c6da5433 100644
--- a/sdks/python/opencomputer/sandbox.py
+++ b/sdks/python/opencomputer/sandbox.py
@@ -60,6 +60,12 @@ class Sandbox:
sandbox_id: str
status: str = "running"
template: str = ""
+ #: Plaintext preview-URL bearer token, available immediately after a
+ #: ``Sandbox.create(preview_auth=...)`` call. Read it once and store
+ #: it somewhere durable — the server will not return it again. After
+ #: a successful ``rotate_preview_auth_token()`` this value is replaced
+ #: with the new token. Empty string when not enabled or when reconnecting.
+ preview_auth_token: str = ""
_api_url: str = ""
_api_key: str = ""
_connect_url: str = ""
@@ -82,6 +88,7 @@ class Sandbox:
image: Image | None = None,
snapshot: str | None = None,
on_build_log: Callable[[str], None] | None = None,
+ preview_auth: dict[str, str] | None = None,
) -> Sandbox:
"""Create a new sandbox instance.
@@ -105,6 +112,15 @@ class Sandbox:
image: Declarative Image definition. The server builds and caches it as a checkpoint.
snapshot: Name of a pre-built snapshot to create the sandbox from.
on_build_log: Callback for build log streaming when using image/snapshot.
+ preview_auth: Require a bearer token on the sandbox's preview URLs.
+ When set, every request to ``https://sb-{id}-p{port}.<domain>``
+ must include the token in an ``Authorization: Bearer <token>``
+ or ``X-OC-Preview-Token`` header. The check happens at the edge
+ before traffic reaches the VM. Pass ``{"token": "auto"}`` (or
+ omit the key) to have the server generate a 256-bit random
+ token; pass an explicit string (>=16 chars) to bring your own.
+ The plaintext is returned exactly once and assigned to
+ ``sandbox.preview_auth_token``.
"""
url = api_url or os.environ.get("OPENCOMPUTER_API_URL", "https://app.opencomputer.dev")
url = url.rstrip("/")
@@ -145,6 +161,11 @@ class Sandbox:
body["image"] = image.to_dict()
if snapshot is not None:
body["snapshot"] = snapshot
+ if preview_auth is not None:
+ body["previewAuth"] = {
+ "scheme": preview_auth.get("scheme", "bearer"),
+ "token": preview_auth.get("token", "auto"),
+ }
if use_sse:
data = await cls._create_with_sse(client, body, on_build_log)
@@ -169,6 +190,7 @@ class Sandbox:
sandbox_id=data["sandboxID"],
status=data.get("status", "running"),
template=template,
+ preview_auth_token=data.get("previewAuthToken", ""),
_api_url=url,
_api_key=key,
_connect_url=connect_url,
@@ -789,6 +811,25 @@ class Sandbox:
if resp.status_code != 404:
resp.raise_for_status()
+ async def rotate_preview_auth_token(self) -> str:
+ """Issue a new preview-URL bearer token; invalidate the previous one.
+
+ The old token stops working immediately — there is no zero-downtime
+ dual-token mode in v1, so coordinate the rollover with whoever is
+ calling your preview URL. If the sandbox was created without
+ ``preview_auth``, calling this enables the auth gate from now on.
+
+ Returns the new plaintext token (also written to
+ ``self.preview_auth_token``).
+ """
+ resp = await self._client.post(
+ f"/sandboxes/{self.sandbox_id}/preview/rotate",
+ )
+ resp.raise_for_status()
+ data = resp.json()
+ self.preview_auth_token = data["previewAuthToken"]
+ return self.preview_auth_token
+
async def create_preview_url(self, port: int, domain: str | None = None, auth_config: dict | None = None) -> dict:
"""Create a preview URL targeting a specific container port.
diff --git a/sdks/typescript/src/sandbox.ts b/sdks/typescript/src/sandbox.ts
index 4098d261..b484bc25 100644
--- a/sdks/typescript/src/sandbox.ts
+++ b/sdks/typescript/src/sandbox.ts
@@ -41,6 +41,21 @@ export interface SandboxOpts {
snapshot?: string;
/** Callback for build log streaming when using `image`. Called with each build step message. */
onBuildLog?: (log: string) => void;
+ /**
+ * Require a bearer token on the sandbox's preview URLs.
+ *
+ * When set, every request to `https://sb-{id}-p{port}.<domain>` must include
+ * the token in an `Authorization: Bearer <token>` or `X-OC-Preview-Token`
+ * header. The check happens at the edge before traffic reaches the VM —
+ * bad tokens never touch your sandbox.
+ *
+ * Pass `{ token: "auto" }` (or omit `token`) to have the server generate a
+ * 256-bit random token; pass an explicit string (≥16 chars) to bring your
+ * own. The plaintext is returned exactly once on the create response as
+ * `previewAuthToken`. Use `Sandbox.rotatePreviewAuthToken()` to issue a new
+ * one (the old one stops working immediately).
+ */
+ previewAuth?: { scheme?: "bearer"; token?: "auto" | string };
}
interface SandboxData {
@@ -50,6 +65,9 @@ interface SandboxData {
connectURL?: string;
token?: string;
sandboxDomain?: string;
+ /** Plaintext preview-URL bearer token. Returned exactly once on the create
+ * or rotate response when `previewAuth` was requested. */
+ previewAuthToken?: string;
}
export interface CheckpointInfo {
@@ -202,6 +220,19 @@ export class Sandbox {
private token: string;
private _status: string;
private _sandboxDomain: string;
+ /**
+ * Plaintext preview-URL bearer token, available immediately after a
+ * `Sandbox.create({ previewAuth: ... })` call. Read it once and store
+ * it somewhere durable — the server will not return it again. After
+ * a successful `rotatePreviewAuthToken()` this value is replaced
+ * with the new token.
+ *
+ * Empty string when the sandbox was created without `previewAuth`,
+ * or when reconnecting via `Sandbox.connect()` (the server-side hash
+ * is still in effect; only the plaintext is gone). In that case use
+ * `rotatePreviewAuthToken()` to mint a new one.
+ */
+ previewAuthToken: string;
private constructor(data: SandboxData, apiUrl: string, apiKey: string) {
this.sandboxId = data.sandboxID;
@@ -210,6 +241,7 @@ export class Sandbox {
this.apiKey = apiKey;
this.connectUrl = data.connectURL || "";
this.token = data.token || "";
+ this.previewAuthToken = data.previewAuthToken || "";
this._sandboxDomain = data.sandboxDomain || "";
// Always route through the CP — it handles readiness waiting and proxies to workers.
@@ -254,6 +286,12 @@ export class Sandbox {
if (opts.secretStore) body.secretStore = opts.secretStore;
if (opts.image) body.image = opts.image.toJSON();
if (opts.snapshot) body.snapshot = opts.snapshot;
+ if (opts.previewAuth) {
+ body.previewAuth = {
+ scheme: opts.previewAuth.scheme ?? "bearer",
+ token: opts.previewAuth.token ?? "auto",
+ };
+ }
// Always use SSE for image/snapshot creation to keep the connection alive
// through proxies (Cloudflare has a 100s idle timeout).
@@ -304,6 +342,31 @@ export class Sandbox {
return new Sandbox(data, apiUrl, apiKey);
}
+ /**
+ * Issue a new preview-URL bearer token and invalidate the previous one.
+ *
+ * Returns the new plaintext token (also written to `sandbox.previewAuthToken`).
+ * The old token stops working immediately — there is no zero-downtime
+ * dual-token mode in v1, so coordinate the rollover with whoever is calling
+ * your preview URL.
+ *
+ * If the sandbox was created without `previewAuth`, calling this enables the
+ * auth gate from that point on.
+ */
+ async rotatePreviewAuthToken(): Promise<string> {
+ const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}/preview/rotate`, {
+ method: "POST",
+ headers: this.apiKey ? { "X-API-Key": this.apiKey } : {},
+ });
+ if (!resp.ok) {
+ const text = await resp.text();
+ throw new Error(`Failed to rotate preview auth token: ${resp.status} ${text}`);
+ }
+ const data = await resp.json() as { previewAuthToken: string };
+ this.previewAuthToken = data.previewAuthToken;
+ return this.previewAuthToken;
+ }
+
async kill(): Promise<void> {
const resp = await fetch(`${this.apiUrl}/sandboxes/${this.sandboxId}`, {
method: "DELETE",