Skip to content

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

4.2 KB
Raw Blame
// Where a "Sign in with Boat" connection is kept: wherever the pasted Boat key is.
//  - Packaged desktop app: the operating system's encrypted credential document, owned by the app's main process
//    (electron/boat-sign-in-store.mjs). It arrives in OMB_BOAT_SIGN_IN at start, as the key arrives in BOX_TOKEN, and is
//    dropped from the environment at once; later reads and writes go over the private parent port and a write counts
//    only when the main process says it is saved.
//  - Anywhere else (the app run from source): boat-sign-in.json in the data folder, owner-only like config.json.
// Neither is in a backup or a move: backups carry no credential (server/workspace-backup-policy.ts).
import { randomUUID } from "node:crypto";
import { readFileSync, rmSync } from "node:fs";
import { join } from "node:path";

import { writeFileAtomic } from "./atomic.ts";
import type { BoatSignInPersistence } from "./boat-sign-in.ts";

export const BOAT_SIGN_IN_FILE = "boat-sign-in.json";
export const BOAT_SIGN_IN_ENV = "OMB_BOAT_SIGN_IN";
const REQUEST = "openmausbot:boat-sign-in-store";
const RESULT = "openmausbot:boat-sign-in-store-result";
const ANSWER_TIMEOUT_MS = 20_000;

export interface BoatSignInStoreRequest {
  type: typeof REQUEST;
  requestId: string;
  op: "read" | "write";
  value?: string | null;
}

export interface BoatSignInStore {
  persistence: BoatSignInPersistence;
  /** True when the message was the main process's answer to a request made here. */
  receive(message: unknown): boolean;
}

export function createBoatSignInStore(options: {
  dataDir: string;
  env?: NodeJS.ProcessEnv;
  /** Sends to the desktop main process; false when there is none. */
  post: (message: BoatSignInStoreRequest) => boolean;
}): BoatSignInStore {
  const env = options.env ?? process.env;
  const fromEnv = env[BOAT_SIGN_IN_ENV];
  // Nothing this server starts may inherit it.
  delete env[BOAT_SIGN_IN_ENV];
  const file = join(options.dataDir, BOAT_SIGN_IN_FILE);
  const waiting = new Map<string, { settle: (answer: { ok: boolean; value?: string | null }) => void; timer: ReturnType<typeof setTimeout> }>();

  const ask = (op: "read" | "write", value?: string | null) => new Promise<{ ok: boolean; value?: string | null }>((settle) => {
    const requestId = randomUUID();
    const timer = setTimeout(() => { waiting.delete(requestId); settle({ ok: false }); }, ANSWER_TIMEOUT_MS);
    timer.unref?.();
    waiting.set(requestId, { settle, timer });
    if (!options.post({ type: REQUEST, requestId, op, ...(op === "write" ? { value: value ?? null } : {}) })) {
      clearTimeout(timer);
      waiting.delete(requestId);
      settle({ ok: false });
    }
  });

  const receive = (raw: unknown): boolean => {
    if (!raw || typeof raw !== "object" || (raw as { type?: unknown }).type !== RESULT) return false;
    const { requestId, ok, value } = raw as { requestId?: unknown; ok?: unknown; value?: unknown };
    const pending = typeof requestId === "string" ? waiting.get(requestId) : undefined;
    if (pending) {
      clearTimeout(pending.timer);
      waiting.delete(requestId as string);
      pending.settle({ ok: ok === true, value: typeof value === "string" && value ? value : null });
    }
    return true;
  };

  if (fromEnv !== undefined) {
    return {
      receive,
      persistence: {
        read: () => fromEnv || null,
        async latest() {
          const answer = await ask("read");
          if (!answer.ok) throw new Error("the credential store did not answer");
          return answer.value ?? null;
        },
        async write(value) {
          if (!(await ask("write", value)).ok) throw new Error("the credential store did not save");
        },
      },
    };
  }

  const readFile = (): string | null => {
    try {
      return readFileSync(file, "utf8") || null;
    } catch (error) {
      if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
      throw error;
    }
  };
  return {
    receive,
    persistence: {
      read: () => { try { return readFile(); } catch { return null; } },
      latest: async () => readFile(),
      async write(value) {
        if (value === null) rmSync(file, { force: true });
        else writeFileAtomic(file, value, { mode: 0o600 });
      },
    },
  };
}