iterate.com / cloud

git clone https://git.iterate.com/repos/cloud

cloud / core / lib / src / node.tsmain at aacbc74

// node.ts — ONE NODE CLIENT FOR A MIND, addressed by its control-plane hostname (iterate/mind-api): what
// the `iterate` CLI and scripts use, and the token a home lab dials with (`mindToken`).
// `connectMind` answers the mind's root `itx` over capnweb at `https://<address>/api`: the `mind`
// of the session that the root answers to `authenticate(token)` (iterate/api `ControlPlaneApi`). A
// sign-in finds the mind's issuer by discovery (iterate/oauth `discoverMind`), runs once (the
// loopback code flow with PKCE, or the device flow when the issuer offers it and there is no browser
// here), keeps the session per resource in the CLI's config directory (cli/config.ts, mode 600) and
// refreshes it. A token handed in, or ITERATE_MIND_TOKEN, replaces all of that and is used as it
// stands.
import { hostname } from "node:os";
import { newWebSocketRpcSession, type RpcStub } from "capnweb";
import { ResponseBodyError } from "oauth4webapi";
import WebSocket, { type ClientOptions } from "ws";
import type { ControlPlaneApi, IterateContextApi } from "./api.ts";
import { connectedMind } from "./client/connected-mind.ts";
import { type DiscoveredMind, discoverMind } from "./client/oauth.ts";
import { startHeartbeat } from "./client/heartbeat.ts";
import { isCodingAgent } from "./cli/coding-agent.ts";
import {
  readSession,
  removeSession,
  withSessionsLock,
  writeSession,
  type StoredSession,
} from "./cli/config.ts";
import { loginFlowFor, type LoginFlow } from "./cli/device-login/flow.ts";
import { deviceLogin, showsColors } from "./cli/device-login/index.ts";
import { oauthLogin, refreshOAuthSession } from "./cli/oauth.ts";
import { openPageCommand } from "./cli/open-page.ts";
import { withTimeout } from "./lib.ts";
import {
  mindAddressOf,
  mindApiUrlOf,
  ownSandboxOf,
  SANDBOX_SESSION_REFUSED_HEADER,
  sandboxSessionRefusal,
} from "./mind-api.ts";

/** What `iterate provide --json` prints, one per line: parse each line with it. */
export { ProvideState } from "./cli/provide-state.ts";

/** Where a line for the person goes: stderr, so stdout stays a command's answer. */
const printToStderr = (line: string) => console.error(line);

/** A TYPED ADDRESS AS A MIND'S (iterate/mind-api `mindAddressOf`: lowercased, a scheme, a
 *  path and a trailing dot dropped, `example.com` read as `iterate.example.com`), or an error
 *  that says why it is none. A command, a script and the home lab read what a person typed
 *  here, ONCE. Every other function of this file takes the address that this answers, as it is:
 *  a session is stored and found under it, and a bearer is sent to it and to no other host. */
export function addressOf(typed: string): string {
  const parsed = mindAddressOf(typed);
  if ("error" in parsed) throw new Error(parsed.error);
  return parsed.address;
}

/** THE MIND AT `address`, as discovery finds it (iterate/oauth `discoverMind`), or an error that
 *  says why it found none. The address is taken as it is: `addressOf` reads what a person typed. */
export async function discoveredMind(address: string): Promise<DiscoveredMind> {
  const found = await discoverMind(address);
  if ("error" in found) throw new Error(found.error);
  return found;
}

/** How a sign-in reaches the person: the flow (cli/device-login/flow.ts `loginFlowFor` when not
 *  given), where its lines go, and how a browser opens the authorization URL. */
export type SignInOptions = {
  flow?: LoginFlow;
  print?: (line: string) => void;
  openBrowser?: (url: URL) => void | Promise<void>;
  /** A page that leads to the issuer's own page (cli/oauth.ts `oauthLogin`, cli/device-login
   *  `deviceLogin`): a new mind's first sign-in, which adds the owner's first passkey on the way. */
  through?: (issuerPage: string) => string;
  /** The browser flow: where the browser goes on after the sign-in, and how long it may take. */
  then?: string;
  waitMs?: number;
};

/** SIGN IN to `mind`'s issuer for `resource` and store the session. The device flow when it is
 *  the flow for this process and the issuer offers it; else the loopback flow, whose URL is printed
 *  (an agent, or `ITERATE_SKIP_BROWSER_OPEN=1`, opens it itself). */
export async function signInToMind(
  mind: DiscoveredMind,
  resource: string,
  options: SignInOptions = {},
): Promise<StoredSession> {
  const print = options.print || printToStderr;
  const flow = options.flow || loginFlowFor({ env: process.env, platform: process.platform });
  const device = flow === "device" && Boolean(mind.endpoints.deviceAuthorization);
  print(`Signing in to ${mind.address} at ${new URL(mind.issuer).host}...`);
  const session = device
    ? await deviceLogin({
        mind,
        resource,
        deviceName: `iterate CLI on ${hostname()}`,
        print,
        colors: showsColors(process.stderr.isTTY, process.env),
        screen: process.stderr,
        through: options.through,
      })
    : await oauthLogin({
        mind,
        resource,
        openBrowser: options.openBrowser || ((url) => openForSignIn(url, print)),
        through: options.through,
        then: options.then,
        waitMs: options.waitMs,
      });
  writeSession(resource, session);
  return session;
}

/** The authorization URL, printed, and opened in this computer's browser unless a coding agent
 *  runs this process or `ITERATE_SKIP_BROWSER_OPEN=1`. */
export async function openForSignIn(url: URL, print: (line: string) => void) {
  // checked first: a page that is refused is neither opened nor offered to the person to open
  const { command, args } = openPageCommand(url, process.platform);
  print(`\nOpen this page to sign in:\n\n  ${url.href}\n`);
  if (isCodingAgent(process.env) || process.env.ITERATE_SKIP_BROWSER_OPEN === "1") return;
  const { execFile } = await import("node:child_process");
  execFile(command, args, (error) => {
    if (error) print(`Could not open a browser (${error.message}): open the URL above yourself.`);
  });
}

/** A LIVE BEARER FOR `resource` of the mind at `address` (as it is: `addressOf` reads what a
 *  person typed): `token`, else ITERATE_MIND_TOKEN,
 *  else the stored session, refreshed when it ends within the minute, or within `leastLeftMs`
 *  for a caller that needs more of it (cli/git.ts). With none, or one the issuer
 *  refuses to refresh, a sign-in when `signIn` allows it; else an error that says how to sign in. */
export async function mindToken(input: {
  address: string;
  resource: string;
  token?: string;
  /** false: never sign in, fail instead (a script, the smoke check) */
  signIn?: SignInOptions | false;
  leastLeftMs?: number;
}): Promise<string> {
  const fixed = input.token || process.env.ITERATE_MIND_TOKEN?.trim();
  if (fixed) return fixed;
  const { resource } = input;
  const endsSoon = (session: StoredSession) => endsWithin(session, input.leastLeftMs ?? 60_000);
  const stored = readSession(resource);
  if (stored && !endsSoon(stored)) return stored.token;
  if (stored?.refreshToken) {
    // ONE AT A TIME (cli/config.ts `withSessionsLock`), and the file is read again inside: a
    // process that waited finds the sign-in that the first one renewed, or finds none that can
    // be renewed (null: the sign-in below).
    const token = await withSessionsLock(async () => {
      const now = readSession(resource);
      if (now && !endsSoon(now)) return now.token;
      if (!now?.refreshToken) return null;
      try {
        const refreshed = await refreshOAuthSession({ resource, session: now });
        writeSession(resource, refreshed);
        return refreshed.token;
      } catch (error) {
        // Only the issuer's `invalid_grant` or `invalid_client` says the stored sign-in is gone
        // (the grant ended, or the mind was reinstalled and no longer knows this OAuth client),
        // and then nothing stored is worth keeping (cli/oauth.ts `tokenResponse` carries the
        // issuer's error as the cause). A timeout or a 5xx is passing: the session stays, and the
        // caller hears of the failure. Still under the lock, so the session removed is the one
        // whose refresh was refused, never one that another process stored since.
        const refusal = error instanceof Error ? error.cause : undefined;
        const ended =
          refusal instanceof ResponseBodyError &&
          (refusal.error === "invalid_grant" || refusal.error === "invalid_client");
        if (!ended) throw error;
        removeSession(resource);
        if (input.signIn === false) throw error;
        return null;
      }
    });
    if (token) return token;
  }
  if (input.signIn === false)
    throw new Error(`Not signed in to ${input.address}. Run \`iterate login ${input.address}\`.`);
  const mind = await discoveredMind(input.address);
  return (await signInToMind(mind, resource, input.signIn)).token;
}

const endsWithin = (session: StoredSession, ms: number) => {
  if (!session.expiresAt) return false;
  const expiresAt = Date.parse(session.expiresAt);
  return Number.isFinite(expiresAt) && expiresAt <= Date.now() + ms;
};

/** The mind's root context, as capnweb hands it: pipelined, and disposable. */
export type MindItx = RpcStub<IterateContextApi>;

/** One connection to a mind's API. Dispose it to close every capability and its socket.
 *  Operations are never retried: replaying a script could duplicate its effects. */
export type MindConnection = Disposable & {
  /** the mind's address */
  address: string;
  itx: MindItx;
  closed: Promise<{ code: number; reason: string }>;
};

/** CONNECT TO THE MIND AT `address`, its control-plane hostname as it is (`addressOf` reads what a
 *  person typed, before this): a bearer for its API (`mindToken`), a WebSocket to
 *  `https://<address>/api`, and on its root `authenticate(token).mind`, the mind's `itx` as the
 *  token's member. The token goes in that call and in no header: the boundary ends the session
 *  and checks it there. A refused token fails the first call, before this answers. A heartbeat
 *  ends a connection whose peer stopped answering. */
// Explicit return type keeps declaration emit from expanding capnweb's recursive mapped types.
export async function connectMind(input: {
  address: string;
  token?: string;
  signIn?: SignInOptions | false;
  /** the heartbeat's timing — a test's, client/heartbeat.ts `HEARTBEAT` otherwise */
  heartbeat?: { intervalMs: number; deadAfterMs: number };
  /** how the socket is opened — a test's, which sees where the socket goes; `ws` otherwise */
  openSocket?: (url: string, options: ClientOptions) => WebSocket;
}): Promise<MindConnection> {
  const { address } = input;
  const resource = mindApiUrlOf(address);
  // In a sandbox of this mind, with no token named, no token goes: the sandbox's egress serves the
  // API as the sandbox's own context (iterate/mind-api `ownSandboxOf`). No sign-in is tried there.
  const sandbox = input.token ? null : ownSandboxOf(process.env, address);
  const token = sandbox
    ? undefined
    : await mindToken({ address, resource, token: input.token, signIn: input.signIn });
  const openSocket = input.openSocket || ((url, options) => new WebSocket(url, options));
  const socket = openSocket(resource.replace(/^http/, "ws"), { handshakeTimeout: 15_000 });
  // A sandbox's refused upgrade says why: its 401 is no call to sign in.
  let refused = "";
  if (sandbox)
    socket.once("unexpected-response", (_request, response) => {
      refused = sandboxSessionRefusal({
        sandbox,
        address,
        status: response.statusCode,
        why: response.headers[SANDBOX_SESSION_REFUSED_HEADER],
      });
      socket.terminate();
    });
  // ws implements the DOM event/send/close interface consumed by capnweb.
  const api = newWebSocketRpcSession<ControlPlaneApi>(socket as unknown as globalThis.WebSocket);
  const itx = connectedMind(api, token);
  let dead = "";
  const closed = new Promise<{ code: number; reason: string }>((resolve) => {
    socket.once("close", (code, reason) => resolve({ code, reason: dead || reason.toString() }));
  });
  // The transport surfaces failures through RPC and `closed`; ws also emits an EventEmitter error.
  socket.on("error", () => {});
  try {
    // the first call proves the socket and the token: it goes with `authenticate`, in one round trip
    await withTimeout(Promise.resolve(itx.whoami()), 20_000, `Connecting to ${address}`);
    const heartbeat = startHeartbeat({
      beat: () => itx.whoami(),
      onDead: (reason) => {
        dead = reason;
        socket.terminate();
      },
      timing: input.heartbeat,
    });
    void closed.then(() => heartbeat.stop());
    return {
      address,
      itx,
      closed,
      [Symbol.dispose]() {
        try {
          itx[Symbol.dispose]();
          api[Symbol.dispose]();
        } finally {
          socket.close();
        }
      },
    };
  } catch (error) {
    try {
      itx[Symbol.dispose]();
      api[Symbol.dispose]();
    } finally {
      socket.terminate();
    }
    throw refused ? new Error(refused, { cause: error }) : error;
  }
}