Skip to content

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

Boat sign-in: a re-sign-in never waits on its own renewal or revokes the working connection; client sessions are not told the account

milind-soni46c66c6ca71b
diff --git a/server/boat-sign-in.test.ts b/server/boat-sign-in.test.ts
index 4d1bb1fd4a..fc78d3d15d 100644
--- a/server/boat-sign-in.test.ts
+++ b/server/boat-sign-in.test.ts
@@ -193,6 +193,52 @@ describe("signing in", () => {
expect(fake.counts.token).toBe(0);
});
+ it("signing in again while the held token is due for renewal: the account check may renew it, and nothing waits on itself", async () => {
+ const { state, persistence } = memory();
+ const checks: number[] = [];
+ const signIn = signInWith(persistence, {
+ // What the server does before a new account replaces the one in use: it asks Boat with the credential held now.
+ beforeConnect: async () => { checks.push((await boatFetch(SIGNED_IN, "/sandboxes?limit=1")).status); return null; },
+ });
+ await connect(signIn);
+ const first = tokensOf(state.value);
+ advance(58 * MINUTE);
+ const { answer } = await connect(signIn);
+ expect(answer.status).toBe(200);
+ expect(checks).toEqual([401, 200]);
+ expect(fake.counts.refresh).toBe(1);
+ expect(tokensOf(state.value).refresh).not.toBe(first.refresh);
+ expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(200);
+ });
+
+ it("a refused or unsaved sign-in over a working one leaves the working one working: nothing is revoked", async () => {
+ const { state, persistence } = memory();
+ let refusal: string | null = null;
+ const signIn = signInWith(persistence, { beforeConnect: async () => refusal });
+ await connect(signIn);
+ const kept = state.value;
+ refusal = "stop active bot work and computer control before changing the Boat account";
+ const refused = await connect(signIn);
+ expect(refused.answer).toMatchObject({ status: 400, text: expect.stringContaining("stop active bot work") });
+ refusal = null;
+ state.fail = true;
+ expect((await connect(signIn)).answer.status).toBe(400);
+ state.fail = false;
+ expect(fake.counts.revoke).toBe(0);
+ expect(state.value).toBe(kept);
+ expect(signIn.status(false, "owner")).toMatchObject({ state: "connected", last: { outcome: "not-saved" } });
+ expect((await boatFetch(SIGNED_IN, "/sandboxes")).status).toBe(200);
+ });
+
+ it("a refused first sign-in gives back what Boat issued", async () => {
+ const { state, persistence } = memory();
+ const signIn = signInWith(persistence, { beforeConnect: async () => "that Boat account cannot access the remembered cloud computers from this installation" });
+ expect((await connect(signIn)).answer.status).toBe(400);
+ expect(fake.counts.revoke).toBe(1);
+ expect(state.value).toBeNull();
+ expect(signIn.status(false, "owner")).toEqual({ available: true, state: "none", keySaved: false, last: { outcome: "refused" } });
+ });
+
it("signing in again does not revoke: a revoke would end the new connection too", async () => {
const signIn = signInWith(memory().persistence);
await connect(signIn);
@@ -293,7 +339,11 @@ describe("renewing", () => {
it("keeps using a token that is still good while Boat cannot be reached, then says so; the connection is kept", async () => {
const { state, persistence } = memory();
let down = false;
- const signIn = signInWith(persistence, { api: () => (down ? "http://127.0.0.1:9/api/v1" : fake.api) });
+ const unreachable: typeof fetch = async (input, init) => {
+ if (down) throw Object.assign(new TypeError("fetch failed"), { cause: { code: "ECONNREFUSED" } });
+ return fetch(input, init);
+ };
+ const signIn = signInWith(persistence, { fetch: unreachable });
await connect(signIn);
advance(56 * MINUTE);
down = true;
diff --git a/server/boat-sign-in.ts b/server/boat-sign-in.ts
index 0596338e1d..85f94f5ced 100644
--- a/server/boat-sign-in.ts
+++ b/server/boat-sign-in.ts
@@ -297,7 +297,8 @@ export class BoatSignIn {
if (!this.enabled || !flow || !state || !sameText(state, flow.state)) return Promise.resolve(invalid);
if (flow.expiresAt <= this.now() || (host ?? "").toLowerCase() !== new URL(flow.redirectUri).host) return Promise.resolve(invalid);
this.flow = null;
- return this.exclusive(() => this.finish(flow, params)).catch((error) => {
+ // Not under the change lock: checking the new account may itself use (and renew) the connection held now.
+ return this.finish(flow, params).catch((error) => {
console.error(`boat sign-in: callback failed: ${error instanceof Error ? error.message : "error"}`);
return this.settle(flow, "failed", "Sign-in did not complete. Return to the app and try again.");
});
@@ -329,7 +330,7 @@ export class BoatSignIn {
const scopes = answer.scopes ?? [...BOAT_SIGN_IN_SCOPES];
const refusal = await this.options.beforeConnect?.(answer.access).catch(() => "The cloud computers this installation remembers could not be checked.");
if (refusal) {
- await this.revoke(answer.refresh);
+ await this.giveBack(answer.refresh);
return this.settle(flow, "refused", `Not signed in: ${refusal}`.slice(0, 400));
}
const account = holds(scopes, "account.read") ? await this.readAccount(answer.access) : undefined;
@@ -337,21 +338,35 @@ export class BoatSignIn {
v: 1, refresh: answer.refresh, access: answer.access, expiresAt: this.now() + answer.expiresIn * 1000, scopes,
...(account ? { account } : {}), prefer: "signIn", connectedAt: this.now(),
};
- try {
- await this.save(next);
- } catch {
- await this.revoke(answer.refresh);
+ // Only the swap is under the change lock, so it never lands in the middle of a renewal.
+ const saved = await this.exclusive(async () => {
+ try {
+ await this.save(next);
+ } catch {
+ return false;
+ }
+ this.document = next;
+ this.unsaved = false;
+ this.retryAfter = 0;
+ this.refreshedAt = this.now();
+ return true;
+ });
+ if (!saved) {
+ await this.giveBack(answer.refresh);
return this.settle(flow, "not-saved", "The sign-in could not be saved on this computer. Return to the app and try again.");
}
- this.document = next;
- this.unsaved = false;
- this.retryAfter = 0;
- this.refreshedAt = this.now();
// The earlier connection's tokens are only dropped, never revoked: a revoke gives up the app's access to the account,
// and the account may be the one just connected.
return this.settle(flow, "connected", "You can close this tab and return to the app.");
}
+ /** Tokens Boat issued for a sign-in that was not kept. Revoking gives up the app's access to the account, so it is done
+ * only when no working connection is held; otherwise they are dropped and run out by themselves. */
+ private async giveBack(refresh: string): Promise<void> {
+ if (this.document && !this.document.needsSignIn) return;
+ await this.revoke(refresh);
+ }
+
private async readAccount(bearer: string): Promise<{ name?: string; email?: string } | undefined> {
try {
const response = await this.fetch(`${this.options.api()}/me`, { headers: { authorization: `Bearer ${bearer}` }, redirect: "error", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
diff --git a/server/index.ts b/server/index.ts
index 31910fc9cb..d7bb1b33b5 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -11627,7 +11627,7 @@ function configForAccess(status: ReturnType<typeof configStatus>, admin: boolean
...withoutKeyHints(status),
edition: { edition: status.edition.edition, features: status.edition.features },
signIn: { admins: [], members: [] }, live: liveSettingsForClient(status.live), everyBotRules: undefined,
- vps: { configured: status.vps.configured, sshAlias: "", servers: [], memoryGb: status.vps.memoryGb, cpus: status.vps.cpus },
+ vps: { configured: status.vps.configured, sshAlias: "", servers: [], memoryGb: status.vps.memoryGb, cpus: status.vps.cpus }, box: { ...withoutKeyHints(status.box), signIn: undefined },
opencodeGo: { configured: status.opencodeGo.configured, providerKeys: [] }, openaiCompat: { configured: status.openaiCompat.configured, url: status.openaiCompat.url, ...(status.openaiCompat.customHeaders ? { customHeaders: { configured: status.openaiCompat.customHeaders.enabled && status.openaiCompat.customHeaders.headers.length > 0 } } : {}) },
...(CLOUD_TEAM ? { onboarding } : {}), profile: CLOUD_TEAM ? profile : { name: profile.name, email: "", ...(profile.avatarUrl ? { avatarUrl: profile.avatarUrl } : {}) },
browserProfiles: status.browserProfiles.map((profile) => Object.fromEntries(Object.entries(profile).filter(([key]) => key !== "partitionId"))),
diff --git a/server/testing/fake-boat-oauth.ts b/server/testing/fake-boat-oauth.ts
index 38e5f2d8f7..d4a22e7032 100644
--- a/server/testing/fake-boat-oauth.ts
+++ b/server/testing/fake-boat-oauth.ts
@@ -44,7 +44,7 @@ const body = (req: IncomingMessage) => new Promise<string>((done) => {
req.on("end", () => done(text));
});
-export async function startFakeBoat(clientId: string, redirectUris: string[]): Promise<FakeBoat> {
+export async function startFakeBoat(clientId: string, redirectUris: string[], apiKeys: string[] = []): Promise<FakeBoat> {
let now = 0;
let nextId = 1;
const codes = new Map<string, { challenge: string; redirectUri: string; scopes: string[]; used: boolean }>();
@@ -116,6 +116,8 @@ export async function startFakeBoat(clientId: string, redirectUris: string[]): P
counts.api += 1;
const bearer = /^Bearer (.+)$/.exec(req.headers.authorization ?? "")?.[1] ?? "";
bearers.push(bearer);
+ // A pasted API key of the same account: every action.
+ if (apiKeys.includes(bearer)) return json(res, 200, url.pathname === "/api/v1/me" ? { ok: true, user: { login: "maya-shah" } } : { ok: true, sandboxes: [] });
const grant = grants.find((one) => one.access === bearer && !one.ended);
if (!grant) return json(res, 401, { ok: false, error: "unauthorized", message: "Invalid token" });
const needs = url.pathname === "/api/v1/me" ? "account.read" : req.method === "POST" ? "sandbox.create" : "sandbox.read";