Skip to content

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

28.2 KB
Raw Blame
// "Sign in with Boat": the person's own Boat account through Boat's OAuth (https://docs.boat.dev/oauth-apps), next to the
// pasted API key. Every call to Boat is made here on the server; the page gets a status and never a token.
//
// One connection per installation. Boat rotates the refresh token on every refresh and ends the connection when it sees
// an old one again after a minute, so: one refresh at a time in this process (the data folder's lease allows one live
// server), the new tokens are saved before the new access token is handed to any caller, a lost answer is repeated once
// while the minute lasts, and `invalid_grant` ends in "sign in again", never in another try.
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
import { z } from "zod";

import { addHeldSecretScrubber, HELD_SECRET_MASK } from "../shared/redact.ts";
import { BOAT_SIGN_IN_PORTS, type BoatSignInOutcome, type BoatSignInStatus } from "../shared/boat-sign-in.ts";

/** Public: a device app has no secret. */
export const BOAT_SIGN_IN_CLIENT_ID = "boatapp_GNp1v9O9qZ8aYw9g9cyHyID2";
export const BOAT_SIGN_IN_CALLBACK_PATH = "/api/boat/oauth/callback";
// The redirect addresses registered with Boat, matched exactly, are this path on each of BOAT_SIGN_IN_PORTS.
export { BOAT_SIGN_IN_PORTS };

/** The least the cloud computer features call (server/boat*.ts, server/cloud-computer-*.ts); one line each in SCOPE_USE. */
export const BOAT_SIGN_IN_SCOPES = [
  "account.read", "sandbox.read", "sandbox.create", "sandbox.resume", "sandbox.stop", "sandbox.update",
  "sandbox.delete", "exec", "file.read", "file.write", "desktop",
] as const;
export type BoatScope = (typeof BOAT_SIGN_IN_SCOPES)[number];

const FLOW_LIFETIME_MS = 10 * 60_000;
const REFRESH_MARGIN_MS = 5 * 60_000;
const REQUEST_TIMEOUT_MS = 15_000;
/** Boat repeats a lost refresh answer for one minute; a second send must start well inside it. */
const REPEAT_WINDOW_MS = 40_000;
/** After a refresh got no usable answer, the next one waits this long. */
const RETRY_PAUSE_MS = 15_000;
/** A token Boat refused right after a refresh is not an expired one. */
const REFUSED_REFRESH_MS = 60_000;
const DEFAULT_LIFETIME_S = 3600;

const documentSchema = z.object({
  v: z.literal(1),
  refresh: z.string(),
  access: z.string(),
  expiresAt: z.number(),
  scopes: z.array(z.string()),
  account: z.object({ name: z.string().optional(), email: z.string().optional() }).optional(),
  /** Which credential the cloud computers use while a pasted key is saved too: the one set last. */
  prefer: z.enum(["signIn", "key"]),
  needsSignIn: z.boolean().optional(),
  connectedAt: z.number(),
});
export type BoatSignInDocument = z.infer<typeof documentSchema>;

/** Where the connection is kept: the same place as the pasted key (see boat-sign-in-store.ts). `write` resolves only
 * once the value is durable there. */
export interface BoatSignInPersistence {
  /** What this process was started with. */
  read(): string | null;
  /** What is saved now: another process sharing the store may have renewed it. */
  latest(): Promise<string | null>;
  write(value: string | null): Promise<void>;
}

export type BoatSignInProblem = "signed-out" | "needs-sign-in" | "unreachable" | "not-saved";

export class BoatSignInError extends Error {
  readonly problem: BoatSignInProblem;
  constructor(problem: BoatSignInProblem) {
    super(BOAT_SIGN_IN_PROBLEM[problem]);
    this.name = "BoatSignInError";
    this.problem = problem;
  }
}

const SETTINGS = "Settings → AI → Other services";
export const BOAT_SIGN_IN_PROBLEM: Record<BoatSignInProblem, string> = {
  "signed-out": `Boat is not signed in — sign in to Boat or paste an API key in ${SETTINGS}`,
  "needs-sign-in": `Your Boat sign-in has ended — sign in to Boat again in ${SETTINGS}`,
  unreachable: "Couldn't reach boat.dev to renew your Boat sign-in — check your connection and try again",
  "not-saved": "Your renewed Boat sign-in could not be saved on this computer — try again in a moment",
};

export interface BoatSignInOptions {
  persistence: BoatSignInPersistence;
  /** Boat's API base (`…/api/v1`); the OAuth endpoints live on the same origin. */
  api: () => string;
  /** False wherever sign-in is not offered: nothing is read, used or started. */
  enabled?: boolean;
  /** Before a new sign-in replaces the credential in use: a refusal in words, or null. `bearer` is the new access token. */
  beforeConnect?: (bearer: string) => Promise<string | null>;
  onChange?: () => void;
  fetch?: typeof fetch;
  now?: () => number;
  /** How long a refresh may wait to be repeated; tests shorten nothing else. */
  pause?: (ms: number) => Promise<void>;
}

interface Flow {
  owner: string;
  state: string;
  verifier: string;
  redirectUri: string;
  expiresAt: number;
}

export interface BoatCallbackAnswer {
  status: number;
  title: string;
  text: string;
}

type TokenAnswer =
  | { kind: "tokens"; access: string; refresh: string; expiresIn: number; scopes: string[] | null }
  | { kind: "invalid-grant" }
  | { kind: "refused"; status: number }
  | { kind: "lost"; sent: boolean };

const single = (params: URLSearchParams, name: string): string | null => {
  const all = params.getAll(name);
  return all.length === 1 && all[0]!.length <= 4096 ? all[0]! : null;
};

const sameText = (left: string, right: string): boolean => {
  const a = createHash("sha256").update(left).digest(), b = createHash("sha256").update(right).digest();
  return timingSafeEqual(a, b);
};

/** Boat's authorization server, as its own metadata document (boat.dev/.well-known/oauth-authorization-server) names it:
 * `/api/box/oauth2/{authorize,token,revoke}` on the API's origin. https, or a loopback stand-in in development and tests. */
export function boatOAuthBase(api: string): string | null {
  try {
    const parsed = new URL(api);
    const loopback = parsed.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(parsed.hostname);
    return parsed.protocol === "https:" || loopback ? `${parsed.origin}/api/box/oauth2` : null;
  } catch {
    return null;
  }
}

/** The scope a Boat API call needs, by Boat's action table (docs.boat.dev/api-keys/scopes); null where none is known. */
export function boatScopeFor(method: string, path: string): BoatScope | null {
  const verb = method.toUpperCase();
  const route = path.split("?")[0]!;
  if (route === "/me" || route === "/orgs") return "account.read";
  const sandbox = /^\/sandboxes(?:\/([^/]+)(\/.*)?)?$/.exec(route);
  if (!sandbox) return null;
  const [, id, rest = ""] = sandbox;
  if (!id) return verb === "POST" ? "sandbox.create" : "sandbox.read";
  if (!rest) return verb === "DELETE" ? "sandbox.delete" : verb === "PATCH" ? "sandbox.update" : "sandbox.read";
  if (rest === "/resume") return "sandbox.resume";
  if (rest === "/stop") return "sandbox.stop";
  if (rest.startsWith("/commands")) return "exec";
  if (rest.startsWith("/desktop")) return "desktop";
  if (rest === "/artifacts" || rest === "/files/download-url") return "file.read";
  if (rest === "/files/upload-url") return "file.write";
  if (rest === "/files") return verb === "GET" ? "file.read" : "file.write";
  return null;
}

const holds = (granted: readonly string[], scope: string): boolean =>
  // A sign-in made while the app asked only for "sandbox.delete-own" keeps working: it is not asked to sign in again,
  // and Boat itself says so if it is asked to delete a computer it did not create.
  granted.includes(scope) || (scope === "sandbox.delete" && granted.includes("sandbox.delete-own"));

export class BoatSignIn {
  private readonly options: BoatSignInOptions;
  private readonly fetch: typeof fetch;
  private readonly now: () => number;
  private readonly pause: (ms: number) => Promise<void>;
  private document: BoatSignInDocument | null = null;
  /** The document in memory is newer than the saved one: no token from it is handed out until a save succeeds. */
  private unsaved = false;
  private flow: Flow | null = null;
  private last: { owner: string; outcome: BoatSignInOutcome } | null = null;
  private refreshing: Promise<string> | null = null;
  private retryAfter = 0;
  private refreshedAt = 0;
  private changing: Promise<unknown> = Promise.resolve();

  constructor(options: BoatSignInOptions) {
    this.options = options;
    this.fetch = options.fetch ?? fetch;
    this.now = options.now ?? Date.now;
    this.pause = options.pause ?? ((ms) => new Promise((done) => setTimeout(done, ms)));
    if (this.enabled) this.document = this.load();
    // The tokens are held here for the life of the process: none may reach a log or a transcript.
    addHeldSecretScrubber((text) => {
      let out = text;
      for (const secret of [this.document?.access, this.document?.refresh]) {
        if (secret && secret.length >= 12 && out.includes(secret)) out = out.split(secret).join(HELD_SECRET_MASK);
      }
      return out;
    });
  }

  get enabled(): boolean {
    return this.options.enabled !== false;
  }

  private parse(raw: string | null): BoatSignInDocument | null {
    try {
      if (!raw) return null;
      const parsed = documentSchema.safeParse(JSON.parse(raw));
      return parsed.success ? parsed.data : null;
    } catch {
      return null;
    }
  }

  private load(): BoatSignInDocument | null {
    try { return this.parse(this.options.persistence.read()); } catch { return null; }
  }

  private async save(next: BoatSignInDocument | null): Promise<void> {
    await this.options.persistence.write(next ? JSON.stringify(next) : null);
  }

  private changed(): void {
    try { this.options.onChange?.(); } catch (error) { console.error(`boat sign-in: a listener failed: ${error instanceof Error ? error.message : "error"}`); }
  }

  /** One change to the connection at a time: a callback, a disconnect and a preference never interleave. */
  private exclusive<T>(run: () => Promise<T>): Promise<T> {
    const next = this.changing.then(run, run);
    this.changing = next.catch(() => undefined);
    return next;
  }

  /** A sign-in is kept here, working or ended. */
  connected(): boolean {
    return this.enabled && this.document !== null;
  }

  /** The sign-in is the credential the cloud computers use: alone, or set after the pasted key. */
  used(keySaved: boolean): boolean {
    return this.connected() && (!keySaved || this.document!.prefer === "signIn");
  }

  status(keySaved: boolean, owner?: string): BoatSignInStatus {
    if (!this.enabled) return { available: false, state: "none", keySaved };
    const document = this.document;
    const last = this.last && (owner === undefined || this.last.owner === owner) ? this.last : null;
    const pending = Boolean(this.flow && this.flow.expiresAt > this.now() && (owner === undefined || this.flow.owner === owner));
    const tail = { keySaved, ...(pending ? { pending: true as const } : {}), ...(last ? { last: { outcome: last.outcome } } : {}) };
    if (!document) return { available: true, state: "none", ...tail };
    const account = document.account?.email?.trim() || document.account?.name?.trim();
    return {
      available: true,
      state: document.needsSignIn ? "needs-sign-in" : "connected",
      ...(account ? { account } : {}),
      missingScopes: document.needsSignIn ? [] : BOAT_SIGN_IN_SCOPES.filter((scope) => !holds(document.scopes, scope)),
      used: this.used(keySaved),
      ...tail,
    };
  }

  scopeOf(method: string, path: string): BoatScope | null {
    return boatScopeFor(method, path);
  }

  /** The scope this call needs and the person unticked; null when it may go ahead. */
  missingScope(method: string, path: string): BoatScope | null {
    const needed = boatScopeFor(method, path);
    return needed && this.document && !this.document.needsSignIn && !holds(this.document.scopes, needed) ? needed : null;
  }

  /** The address to open in the person's browser. A newer start replaces an older one: its state stops working. */
  start(owner: string, port: number): { url: string } {
    const base = boatOAuthBase(this.options.api());
    if (!this.enabled || !base || !BOAT_SIGN_IN_PORTS.includes(port)) throw new Error("Sign in with Boat is not available here.");
    const state = randomBytes(32).toString("base64url");
    const verifier = randomBytes(48).toString("base64url");
    const redirectUri = `http://127.0.0.1:${port}${BOAT_SIGN_IN_CALLBACK_PATH}`;
    this.flow = { owner, state, verifier, redirectUri, expiresAt: this.now() + FLOW_LIFETIME_MS };
    this.last = null;
    const url = new URL(`${base}/authorize`);
    url.searchParams.set("response_type", "code");
    url.searchParams.set("client_id", BOAT_SIGN_IN_CLIENT_ID);
    url.searchParams.set("redirect_uri", redirectUri);
    url.searchParams.set("scope", BOAT_SIGN_IN_SCOPES.join(" "));
    url.searchParams.set("state", state);
    url.searchParams.set("code_challenge", createHash("sha256").update(verifier).digest("base64url"));
    url.searchParams.set("code_challenge_method", "S256");
    this.changed();
    return { url: url.href };
  }

  /** The person gave up before Boat answered. */
  cancel(owner: string): void {
    if (this.flow?.owner !== owner) return;
    this.flow = null;
    this.changed();
  }

  /** Boat sent the browser back. The state is the only credential: it is single-valued, compared in constant time and
   * spent before the code is exchanged, and the code is exchanged once. The answer is fixed words, never a redirect. */
  callback(host: string | undefined, search: string): Promise<BoatCallbackAnswer> {
    const invalid: BoatCallbackAnswer = { status: 400, title: "Sign-in link not valid", text: "This sign-in link is not valid or has expired. Return to the app and start again." };
    const params = new URLSearchParams(search);
    const state = single(params, "state");
    const flow = this.flow;
    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;
    // 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.");
    });
  }

  private settle(flow: Flow, outcome: BoatSignInOutcome, text: string): BoatCallbackAnswer {
    this.last = { owner: flow.owner, outcome };
    this.changed();
    if (outcome === "connected") return { status: 200, title: "Signed in to Boat", text };
    if (outcome === "cancelled") return { status: 200, title: "Sign-in cancelled", text };
    return { status: 400, title: "Sign-in did not complete", text };
  }

  private async finish(flow: Flow, params: URLSearchParams): Promise<BoatCallbackAnswer> {
    const base = boatOAuthBase(this.options.api());
    const error = params.has("error") ? single(params, "error") ?? "error" : null;
    if (error === "access_denied") return this.settle(flow, "cancelled", "Nothing was connected. You can close this tab.");
    const iss = params.has("iss") ? single(params, "iss") : undefined;
    const code = single(params, "code");
    if (error || !code || !base || iss === null || (iss !== undefined && iss.replace(/\/$/, "") !== new URL(base).origin)) {
      return this.settle(flow, "failed", "Boat did not complete the sign-in. Return to the app and try again.");
    }
    const answer = await this.token({ grant_type: "authorization_code", code, redirect_uri: flow.redirectUri, code_verifier: flow.verifier, client_id: BOAT_SIGN_IN_CLIENT_ID });
    if (answer.kind !== "tokens") {
      return answer.kind === "lost"
        ? this.settle(flow, "unreachable", "Couldn't reach Boat to complete the sign-in. Return to the app and try again.")
        : this.settle(flow, "failed", "Boat did not accept this sign-in. Return to the app and try again.");
    }
    const scopes = answer.scopes ?? [...BOAT_SIGN_IN_SCOPES];
    const refusal = await this.unusable(answer.access, scopes)
      ?? await this.options.beforeConnect?.(answer.access).catch(() => "The cloud computers this installation remembers could not be checked.");
    if (refusal) {
      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;
    const next: BoatSignInDocument = {
      v: 1, refresh: answer.refresh, access: answer.access, expiresAt: this.now() + answer.expiresIn * 1000, scopes,
      ...(account ? { account } : {}), prefer: "signIn", connectedAt: this.now(),
    };
    // 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.");
    }
    // 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.");
  }

  /** Why a sign-in just made cannot run cloud computers at all, in the person's words; null when it can. Asked before the
   * account check, whose own words are about API keys. */
  private async unusable(bearer: string, scopes: readonly string[]): Promise<string | null> {
    const SEE = "the app must be allowed to see your sandboxes. Sign in again and keep \"sandbox.read\" ticked on Boat's screen.";
    if (!holds(scopes, "sandbox.read")) return SEE;
    try {
      const response = await this.fetch(`${this.options.api()}/sandboxes?limit=1`, { headers: { authorization: `Bearer ${bearer}` }, redirect: "error", signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) });
      if (response.ok) return null;
      const body: any = await response.json().catch(() => null);
      const code = typeof body?.error === "string" ? body.error : body?.error?.code ?? body?.code;
      if (response.status === 400 && code === "org_required") {
        return "you ticked several organizations and none of them is your default. Sign in again and tick one organization only on Boat's screen, or set a default organization in boat.dev.";
      }
      if (response.status === 403) return code === "api_key_action_forbidden" ? SEE : "boat.dev did not let this sign-in see your sandboxes. Sign in again and tick the organization and environments your cloud computers are in.";
      return null;
    } catch {
      return null;
    }
  }

  /** 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) });
      if (!response.ok) return undefined;
      const body: any = await response.json();
      // Boat's MeResponse: `user.login` and `user.email`.
      const text = (value: unknown) => (typeof value === "string" && value.trim() && value.length <= 200 ? value.trim() : undefined);
      const name = text(body?.user?.login);
      const email = text(body?.user?.email);
      return name || email ? { ...(name ? { name } : {}), ...(email ? { email } : {}) } : undefined;
    } catch {
      return undefined;
    }
  }

  private async token(form: Record<string, string>): Promise<TokenAnswer> {
    const base = boatOAuthBase(this.options.api());
    if (!base) return { kind: "lost", sent: false };
    let response: Response;
    try {
      response = await this.fetch(`${base}/token`, {
        method: "POST",
        headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
        body: new URLSearchParams(form).toString(),
        redirect: "error",
        signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
      });
    } catch (error) {
      const code = (error as { cause?: { code?: string } })?.cause?.code;
      return { kind: "lost", sent: !(code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "EAI_AGAIN") };
    }
    let body: any = null;
    try { body = await response.json(); } catch { /* an answer with no JSON is read by its status */ }
    if (response.ok && typeof body?.access_token === "string" && body.access_token && typeof body?.refresh_token === "string" && body.refresh_token) {
      const expiresIn = typeof body.expires_in === "number" && body.expires_in > 0 ? body.expires_in : DEFAULT_LIFETIME_S;
      return { kind: "tokens", access: body.access_token, refresh: body.refresh_token, expiresIn, scopes: typeof body.scope === "string" ? body.scope.split(/\s+/).filter(Boolean) : null };
    }
    // An answer in the 200s without tokens may still have rotated them: it is read as lost, not as a refusal.
    if (response.ok) return { kind: "lost", sent: true };
    if (response.status === 400 && body?.error === "invalid_grant") return { kind: "invalid-grant" };
    return { kind: "refused", status: response.status };
  }

  private async revoke(token: string): Promise<boolean> {
    const base = boatOAuthBase(this.options.api());
    if (!base || !token) return false;
    try {
      const response = await this.fetch(`${base}/revoke`, {
        method: "POST",
        headers: { "content-type": "application/x-www-form-urlencoded" },
        body: new URLSearchParams({ token, client_id: BOAT_SIGN_IN_CLIENT_ID }).toString(),
        redirect: "error",
        signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
      });
      return response.ok;
    } catch {
      return false;
    }
  }

  /** A bearer for one Boat call: the saved access token, renewed when it is near its end. Every caller in the process
   * shares one renewal. Throws BoatSignInError where there is none to give. */
  async accessToken(): Promise<string> {
    const document = this.document;
    if (!this.enabled || !document) throw new BoatSignInError("signed-out");
    if (document.needsSignIn) throw new BoatSignInError("needs-sign-in");
    if (this.refreshing) return this.refreshing;
    if (!this.unsaved && document.expiresAt - this.now() > REFRESH_MARGIN_MS) return document.access;
    return this.renew();
  }

  /** Boat answered 401 to `used`. A token renewed since is tried instead; else one renewal, at most once a minute. Null:
   * nothing newer to try. */
  async afterRefusal(used: string): Promise<string | null> {
    const document = this.document;
    if (!this.enabled || !document || document.needsSignIn) return null;
    if (this.refreshing) return this.refreshing.catch(() => null);
    if (!this.unsaved && document.access !== used) return document.access;
    if (this.now() - this.refreshedAt < REFUSED_REFRESH_MS) return null;
    return this.renew().then((token) => (token === used ? null : token), () => null);
  }

  private renew(): Promise<string> {
    this.refreshing ??= this.exclusive(() => this.refresh()).finally(() => { this.refreshing = null; });
    return this.refreshing;
  }

  private async refresh(): Promise<string> {
    let document = this.document;
    if (!document) throw new BoatSignInError("signed-out");
    if (document.needsSignIn) throw new BoatSignInError("needs-sign-in");
    if (!this.unsaved) {
      // Another process on the same store (a desktop restart's overlap) may have renewed already: its tokens are taken,
      // and the refresh token it spent is never sent again from here.
      let stored: BoatSignInDocument | null | undefined;
      try { stored = this.parse(await this.options.persistence.latest()); } catch { stored = undefined; }
      if (stored === null) {
        this.document = null;
        this.changed();
        throw new BoatSignInError("signed-out");
      }
      if (stored && stored.refresh !== document.refresh) {
        this.document = document = stored;
        this.changed();
        if (stored.needsSignIn) throw new BoatSignInError("needs-sign-in");
        if (stored.expiresAt - this.now() > REFRESH_MARGIN_MS) return stored.access;
      }
    }
    if (this.unsaved) {
      // Boat already rotated: the tokens in memory are the only good ones, so the save is tried again, not the refresh.
      try { await this.save(document); } catch { throw new BoatSignInError("not-saved"); }
      this.unsaved = false;
      this.changed();
      return document.access;
    }
    const stillGood = () => (document!.expiresAt > this.now() ? document!.access : null);
    if (this.now() < this.retryAfter) {
      const kept = stillGood();
      if (kept) return kept;
      throw new BoatSignInError("unreachable");
    }
    const sent = document.refresh;
    const form = { grant_type: "refresh_token", refresh_token: sent, client_id: BOAT_SIGN_IN_CLIENT_ID };
    const began = this.now();
    let answer = await this.token(form);
    // A lost answer may have rotated the token at Boat, which repeats that answer for a minute: asked once more, in time.
    if (answer.kind === "lost" && answer.sent && this.now() - began < REPEAT_WINDOW_MS) {
      await this.pause(1_000);
      answer = await this.token(form);
    }
    if (answer.kind === "invalid-grant") {
      document = { ...document, access: "", refresh: "", needsSignIn: true };
      this.document = document;
      try { await this.save(document); } catch { this.unsaved = true; }
      this.changed();
      throw new BoatSignInError("needs-sign-in");
    }
    if (answer.kind !== "tokens") {
      this.retryAfter = this.now() + RETRY_PAUSE_MS;
      const kept = stillGood();
      if (kept) return kept;
      throw new BoatSignInError("unreachable");
    }
    const next: BoatSignInDocument = {
      ...document, refresh: answer.refresh, access: answer.access, expiresAt: this.now() + answer.expiresIn * 1000,
      scopes: answer.scopes ?? document.scopes, prefer: this.document?.prefer ?? document.prefer,
    };
    // From here the old refresh token is dead at Boat. The new one is saved before its access token goes to any caller.
    this.document = next;
    this.refreshedAt = this.now();
    try {
      await this.save(next);
    } catch {
      this.unsaved = true;
      throw new BoatSignInError("not-saved");
    }
    if (next.scopes.join(" ") !== document.scopes.join(" ")) this.changed();
    return next.access;
  }

  /** A pasted key was saved after the sign-in: it is the one used from now on. The switch is made here at once; the
   * returned promise is its save, which the caller must not wait for inside anything the store itself waits on (the
   * packaged app saves a key and this connection through one queue). */
  preferKey(): Promise<void> {
    const document = this.document;
    if (!this.enabled || !document || document.prefer === "key") return Promise.resolve();
    this.document = { ...document, prefer: "key" };
    this.changed();
    return this.exclusive(async () => {
      if (this.document) await this.save(this.document);
    });
  }

  /** The next Boat call would first renew the token (and save it). */
  renewalDue(): boolean {
    const document = this.document;
    return Boolean(this.enabled && document && !document.needsSignIn && (this.unsaved || document.expiresAt - this.now() <= REFRESH_MARGIN_MS));
  }

  /** Disconnect: Boat is told first, then the connection is forgotten here whatever Boat answered. */
  signOut(): Promise<{ revoked: boolean }> {
    return this.exclusive(async () => {
      const document = this.document;
      this.flow = null;
      this.last = null;
      if (!this.enabled || !document) return { revoked: true };
      const revoked = document.refresh ? await this.revoke(document.refresh) : true;
      await this.save(null);
      this.document = null;
      this.unsaved = false;
      this.retryAfter = 0;
      this.changed();
      return { revoked };
    });
  }
}