Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Cloud browser: the relay token as the _port_auth cookie, the provider's auto-stop pushed ahead while in use, no machine free opens in the home at once

milind-soni5460a44e2bea
diff --git a/server/cloud-browser/cloud-browser.test.ts b/server/cloud-browser/cloud-browser.test.ts
index 598b77fd92..27b69a755f 100644
--- a/server/cloud-browser/cloud-browser.test.ts
+++ b/server/cloud-browser/cloud-browser.test.ts
@@ -11,7 +11,7 @@ import { ComputerIdleTimer } from "../computer-idle.ts";
import { LOCAL_SCHEME_REFUSAL, localSchemeRefusal } from "./guards.ts";
import { SESSION_DOWNLOAD_BYTES, SIGN_IN_SYNC_MS, UPLOAD_MAX_BYTES, type SignInStore } from "./companion.ts";
import { cookieParam } from "./sign-ins.ts";
-import { CLOUD_BROWSER_IDLE_MS, createCloudBrowser, type CloudBrowserDeps } from "./index.ts";
+import { CLOUD_BROWSER_IDLE_MS, createCloudBrowser, SANDBOX_IDLE_TTL_SECONDS, TTL_REFRESH_MS, type CloudBrowserDeps } from "./index.ts";
import { CLOUD_BROWSER_BACKOFF_MS, createCloudBrowserRails } from "./rails.ts";
import { BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, browserSandboxCreateBody, profileKey, providerOps } from "./remote.ts";
import { RELAY_KEY, RELAY_TOKEN, startFakeComputer, type FakeComputer } from "./testing/fake-computer.ts";
@@ -103,6 +103,7 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
expect(upgrade.path).toMatch(new RegExp(`^/${key}/[a-f0-9]{48}$`));
expect(upgrade.host).toBe(new URL(fake.base).host);
expect(upgrade.origin).toBeUndefined();
+ expect(upgrade.query, "the relay's token goes as the _port_auth cookie, never a ?_token= the edge would redirect").toBe("");
}
const before = fake.requests.length;
await act(cdpUrl, 3);
@@ -211,6 +212,40 @@ describe("a personal Cloud's bot browsers in the Cloud's browser sandbox", () =>
expect(cloud.report().resumes).toBe(1);
});
+ it("with no machine free at the provider, opens in the home at once, never as a sandbox failure", async () => {
+ fake.state = "archived";
+ fake.startStatus = 503;
+ fake.startBody = { ok: false, code: "no_ready_machine", message: "No machine is ready." };
+ const cloud = browser();
+ expect(await cloud.open(request())).toEqual({ home: "no-machine" });
+ expect(await cloud.open(request())).toEqual({ home: "no-machine" });
+ expect(await cloud.open(request())).toEqual({ home: "no-machine" });
+ expect(cloud.report().held, "no back-off: the next open may find a machine").toBeNull();
+ expect(fake.resumes()).toBe(3);
+ });
+
+ it("pushes the provider's own auto-stop ahead while a browser is used, at most every 10 minutes, so it stops the sandbox only when unused", async () => {
+ const cloud = browser();
+ const cdpUrl = urlOf(await cloud.open(request()));
+ const patches = () => fake.requests.filter((one) => one.method === "PATCH" && one.body?.ttlSeconds !== undefined).map((one) => one.body);
+ await act(cdpUrl, 1);
+ clock += 60_000;
+ await cloud.closeIdle();
+ expect(patches()).toEqual([{ ttlSeconds: SANDBOX_IDLE_TTL_SECONDS }]);
+ clock += 60_000;
+ await act(cdpUrl, 1);
+ await cloud.closeIdle();
+ expect(patches(), "at most every 10 minutes").toHaveLength(1);
+ clock += TTL_REFRESH_MS;
+ await act(cdpUrl, 1);
+ await cloud.closeIdle();
+ expect(patches()).toHaveLength(2);
+ held = true;
+ clock += TTL_REFRESH_MS;
+ await cloud.closeIdle();
+ expect(patches(), "unused since: the deadline is left to run out").toHaveLength(2);
+ });
+
it("wakes a stopped sandbox with exactly one resume, then reads only", async () => {
fake.state = "archived";
const cloud = browser();
diff --git a/server/cloud-browser/door.ts b/server/cloud-browser/door.ts
index 07c2f92c74..bac7f66de2 100644
--- a/server/cloud-browser/door.ts
+++ b/server/cloud-browser/door.ts
@@ -25,13 +25,15 @@ export function dialable(raw: string): URL | null {
return url.protocol === "http:" && LOOPBACK.has(url.hostname) ? url : null;
}
-/** The request the computer's door gets: its secret path with the relay's token, the relay's host, and the engine's own
- * WebSocket headers. Origin is dropped: Chrome refuses a DevTools connection that names one it was not told to allow. */
+/** The request the sandbox's door gets: its secret path, the relay's host, the relay's access token as the cookie the
+ * provider names for API clients (`_port_auth`; the `?_token=` form answers a browser with a redirect, which a WebSocket
+ * upgrade cannot follow), and the engine's own WebSocket headers. Origin and any cookie of the engine's are dropped:
+ * Chrome refuses a DevTools connection that names an origin it was not told to allow. */
export function rewrittenHead(head: Buffer, target: DoorTarget): Buffer {
const lines = head.toString("latin1").split("\r\n").filter(Boolean);
- const kept = lines.slice(1).filter((line) => !/^(host|origin):/i.test(line));
- const query = target.url.search;
- return Buffer.from([`GET /${target.secret}${query} HTTP/1.1`, `Host: ${target.url.host}`, ...kept, "", ""].join("\r\n"), "latin1");
+ const kept = lines.slice(1).filter((line) => !/^(host|origin|cookie):/i.test(line));
+ const token = target.url.searchParams.get("_token");
+ return Buffer.from([`GET /${target.secret} HTTP/1.1`, `Host: ${target.url.host}`, ...(token ? [`Cookie: _port_auth=${token}`] : []), ...kept, "", ""].join("\r\n"), "latin1");
}
interface Door { server: Server; url: string; token: Buffer; target: DoorTarget; connections: Set<Socket>; lastActivity: number; dialed: number }
diff --git a/server/cloud-browser/index.ts b/server/cloud-browser/index.ts
index 1ea7701640..f94e98c756 100644
--- a/server/cloud-browser/index.ts
+++ b/server/cloud-browser/index.ts
@@ -16,6 +16,10 @@ import { BROWSER_SANDBOX_CHROMES, BROWSER_SANDBOX_OWNER, COMPUTER_DOOR_PORT, Old
export const CLOUD_BROWSER_IDLE_MS = 3 * 60_000;
const SWEEP_MS = 30_000;
const LEVER_CLEANUP_GAP_MS = 60 * 60_000;
+/** While a browser is used, the provider's own auto-stop is pushed to this far ahead, at most every TTL_REFRESH_MS: it then
+ * stops the sandbox by itself when everything here died, and never in the middle of a session in use. */
+export const SANDBOX_IDLE_TTL_SECONDS = 1_200;
+export const TTL_REFRESH_MS = 10 * 60_000;
export const cloudBrowserLever = (env: NodeJS.ProcessEnv = process.env): boolean => env.OMB_CLOUD_BROWSER?.trim() === "home";
@@ -90,6 +94,7 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
/** Woken (or found awake) by an open here and not yet let sleep. */
let awake = false;
let leverCleanupAt = -Infinity;
+ let ttlRefreshedAt = 0;
const home = (request: OpenRequest, reason: HomeReason): Opened => {
rails.home(reason);
@@ -102,6 +107,8 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
function refused(error: unknown): HomeReason {
const failure = cloudFailureOf(error);
const limit = failure.limit;
+ // No machine free right now: the provider answered at once and counted no start. Not the sandbox's failure.
+ if (failure.code === "no_ready_machine") return "no-machine";
if (limit?.reason === "too_many_starts" && (limit.window === "day" || limit.window === undefined)) { rails.accountLimit(limit); return "account-limit"; }
if (limit?.reason === "hours_used") { rails.hoursUsed(limit); return "hours-used"; }
if (limit?.reason === "at_once") { rails.holdOff(); return "at-once"; }
@@ -137,6 +144,8 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
const box = await waking;
boxId = box.id;
awake = true;
+ // Woken now: the deadline the Admin set at the resume is fresh.
+ if (box.started) ttlRefreshedAt = now();
rails.awake();
// On from here: the idle path times it, whatever happens next.
deps.used(BROWSER_SANDBOX_OWNER, CLOUD_BROWSER_IDLE_MS);
@@ -275,8 +284,19 @@ export function createCloudBrowser(deps: CloudBrowserDeps) {
}
}
+ /** The provider's auto-stop pushed ahead while some browser here was used since the last push. */
+ async function refreshTtl(at: number): Promise<void> {
+ const ops = deps.ops();
+ if (!ops || !boxId || at - ttlRefreshedAt < TTL_REFRESH_MS) return;
+ const used = doors.sessions().some((session) => (doors.lastActivity(session) ?? 0) > ttlRefreshedAt);
+ if (!used) return;
+ ttlRefreshedAt = at;
+ await ops.refreshTtl(boxId, SANDBOX_IDLE_TTL_SECONDS).catch(() => undefined);
+ }
+
async function closeIdle(): Promise<void> {
const at = now();
+ await refreshTtl(at);
await Promise.all([...companions.values()].map((companion) => companion.periodic()));
await Promise.all(doors.sessions().map(async (session) => {
const last = doors.lastActivity(session);
diff --git a/server/cloud-browser/rails.ts b/server/cloud-browser/rails.ts
index d6bd605453..609ba8ffc5 100644
--- a/server/cloud-browser/rails.ts
+++ b/server/cloud-browser/rails.ts
@@ -16,7 +16,7 @@ export const CLOUD_BROWSER_BACKOFF_MS = 15 * 60_000;
/** Why a browser session opened in the home instead: names only, for the log and the health report. */
export type HomeReason =
- | "lever" | "team" | "not-eligible" | "own-key" | "sign-ins" | "not-set-up" | "busy" | "lent-connection"
+ | "lever" | "team" | "not-eligible" | "own-key" | "sign-ins" | "no-machine" | "not-set-up" | "busy" | "lent-connection"
| "old-relay" | "unavailable" | "budget" | "minutes-used" | "sandbox-full" | "backoff" | "account-limit" | "hours-used" | "at-once" | "no-route" | "start-failed" | "unreachable";
interface Day {
diff --git a/server/cloud-browser/remote.ts b/server/cloud-browser/remote.ts
index 698cbe28d9..10b295b257 100644
--- a/server/cloud-browser/remote.ts
+++ b/server/cloud-browser/remote.ts
@@ -57,6 +57,8 @@ export interface ComputerOps {
quit(boxId: string, key: string | null): Promise<void>;
/** The door's port on a protected relay URL (one that needs its token); null where it is refused or unprotected. */
host(boxId: string, port: number): Promise<string | null>;
+ /** Moves the provider's own auto-stop to now + `seconds`, so it stops the sandbox only after that long unused. */
+ refreshTtl(boxId: string, seconds: number): Promise<void>;
/** Deletes it, journaled like every deletion (boat-delete-journal.ts), so a failed delete is retried and never leaks. */
remove(boxId: string): Promise<boolean>;
}
@@ -171,6 +173,10 @@ export function providerOps(cfg: () => AppConfig): ComputerOps {
if (!answer.ok || answer.body?.isProtected === false || answer.body?.access === "public") return null;
return protectedUrl(answer.body?.url);
},
+ async refreshTtl(boxId, seconds) {
+ // A refusal (the Admin's maximum session age, say) leaves the deadline as it is: that is the point of it.
+ await json(cfg(), `/sandboxes/${boxId}`, { method: "PATCH", body: JSON.stringify({ ttlSeconds: seconds }) });
+ },
async remove(boxId) {
const name = await boatNameFor(BROWSER_SANDBOX_OWNER);
return (await requestRecordedBoatDeletion(cfg(), { boxId, name, ownerBotId: BROWSER_SANDBOX_OWNER })) === "confirmed";
diff --git a/server/cloud-browser/testing/fake-computer.ts b/server/cloud-browser/testing/fake-computer.ts
index 2aa8b25747..a317d21308 100644
--- a/server/cloud-browser/testing/fake-computer.ts
+++ b/server/cloud-browser/testing/fake-computer.ts
@@ -30,7 +30,7 @@ export interface FakeComputer {
unprotected: boolean;
chromeStarts: boolean;
requests: Request[];
- upgrades: Array<{ path: string; host: string | undefined; origin: string | undefined }>;
+ upgrades: Array<{ path: string; host: string | undefined; origin: string | undefined; query?: string }>;
frames: string[];
boxId: string;
/** Files on the sandbox's disk by path (downloads the page made, uploads the home sent). */
@@ -148,7 +148,10 @@ export async function startFakeComputer(): Promise<FakeComputer> {
const url = new URL(req.url ?? "/", "http://fake");
fake.upgrades.push({ path: url.pathname, host: req.headers.host, origin: req.headers.origin });
const [, key = "", secret = ""] = /^\/([a-f0-9]{16})\/([a-f0-9]+)$/.exec(url.pathname) ?? [];
- if (!key || secrets.get(key) !== secret || url.searchParams.get("_token") !== RELAY_TOKEN) {
+ // The provider's edge takes the token as the `_port_auth` cookie from an API client; a `?_token=` request gets a redirect.
+ const cookie = /(?:^|;\s*)_port_auth=([^;]+)/.exec(String(req.headers.cookie ?? ""))?.[1];
+ fake.upgrades.at(-1)!.query = url.search;
+ if (!key || secrets.get(key) !== secret || cookie !== RELAY_TOKEN || url.search) {
socket.end("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n");
return;
}