iterate.com / kernel

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

kernel / core / lib / src / cli / device-login / index.tsmain at 949894f

// THE DEVICE SIGN-IN (RFC 8628) on oauth4webapi, for an issuer that offers it
// (`device_authorization_endpoint` in its metadata): no listener, no browser on this computer.
import * as oauth from "oauth4webapi";
import { authorizationServerOf, type DiscoveredMind } from "../../client/oauth.ts";
import type { StoredSession } from "../config.ts";
import { registerClient, requestOptions, sessionFromTokens } from "../oauth.ts";
import { pollUntilAnswered, type PollAnswer } from "./poll.ts";
import { terminalQrCode, type TerminalScreen } from "./qr.ts";

/** Sign in to `mind`'s issuer from a browser on any device, for `resource`: the person opens the
 *  printed page, checks the code, and approves. `deviceName` is the registration's `client_name`,
 *  which that page shows. `print` writes a line for the person, or the agent that relays it;
 *  `colors` says whether the person sees its colors (`showsColors`), and `screen` how large their
 *  terminal is: a QR code that does not fit it is left out, and the link stands alone. `through`
 *  makes the page to print from the approval page with its code filled in: a page that leads
 *  there (a new mind's first sign-in, which adds the owner's first passkey on the way). */
export async function deviceLogin(input: {
  mind: DiscoveredMind;
  resource: string;
  deviceName: string;
  print: (line: string) => void;
  colors: boolean;
  screen?: TerminalScreen;
  through?: (approvalPage: string) => string;
}): Promise<StoredSession> {
  const { mind, resource } = input;
  const issuer = mind.issuer;
  if (!mind.endpoints.deviceAuthorization)
    throw new Error(`${new URL(issuer).host} does not offer the device sign-in.`);
  const as = authorizationServerOf(mind);
  const client = await registerClient(mind, {
    client_name: input.deviceName,
    token_endpoint_auth_method: "none",
    grant_types: ["urn:ietf:params:oauth:grant-type:device_code", "refresh_token"],
  });
  const device = await oauth.processDeviceAuthorizationResponse(
    as,
    client,
    await oauth.deviceAuthorizationRequest(
      as,
      client,
      oauth.None(),
      { scope: "iterate", resource },
      requestOptions(issuer),
    ),
  );
  const expiresInSeconds = Math.min(device.expires_in, 300);
  const waiting = `The code expires in ${Math.round(expiresInSeconds / 60)} minutes. Waiting for approval...`;
  // the page and the link on lines of their own, so a terminal or an agent's transcript copies them
  const through = input.through?.(device.verification_uri_complete || device.verification_uri);
  if (through) {
    input.print("\nTo sign in, open this page in a browser on any device:\n");
    input.print(`  ${through}\n`);
    input.print(`It ends at the code:  ${device.user_code}\n`);
    const qrCode = terminalQrCode(through, input.colors, input.screen, ["", waiting]);
    if (qrCode) {
      input.print("Or scan this QR code. It opens the same page:\n");
      input.print(`${qrCode}\n`);
    }
  } else {
    input.print("\nTo sign in, open this page in a browser on any device:\n");
    input.print(`  ${device.verification_uri}\n`);
    input.print(`and enter the code:  ${device.user_code}\n`);
  }
  if (!through && device.verification_uri_complete) {
    const link = `  ${device.verification_uri_complete}`;
    const qrCode = terminalQrCode(device.verification_uri_complete, input.colors, input.screen, [
      "",
      link,
      "",
      waiting,
    ]);
    if (qrCode) {
      input.print("Or scan this QR code, or open the link under it. Both fill in the code:\n");
      input.print(`${qrCode}\n`);
    } else input.print("Or open this link. It fills in the code:\n");
    input.print(`${link}\n`);
  }
  input.print(waiting);
  const answer = await pollUntilAnswered({
    intervalSeconds: device.interval || 5,
    deadline: Date.now() + expiresInSeconds * 1000,
    poll: () => pollOnce(as, client, issuer, device.device_code, resource),
    onRetry: (reason, waitMs) =>
      input.print(`Could not reach ${issuer} (${reason}); trying again in ${waitMs / 1000} s.`),
  });
  return sessionFromTokens(answer.tokens, mind, client.client_id, answer.started);
}

/** Whether the person sees the colors written to a stream: a terminal (`isTTY`) that is not
 *  `TERM=dumb`, and no `NO_COLOR` (https://no-color.org). `FORCE_COLOR` decides first, as in Node:
 *  `0` or `false` is no colors, any other value is colors. */
export function showsColors(isTTY: boolean | undefined, env: Record<string, string | undefined>) {
  if (env.FORCE_COLOR) return env.FORCE_COLOR !== "0" && env.FORCE_COLOR !== "false";
  return isTTY === true && !env.NO_COLOR && env.TERM !== "dumb";
}

/** One poll, read for `pollUntilAnswered`: no answer at all, or a 5xx, is worth trying again. */
async function pollOnce(
  as: oauth.AuthorizationServer,
  client: oauth.Client,
  issuer: string,
  deviceCode: string,
  resource: string,
): Promise<PollAnswer<{ tokens: oauth.TokenEndpointResponse; started: number }>> {
  const started = Date.now();
  try {
    const tokens = await oauth.processDeviceCodeResponse(
      as,
      client,
      await oauth.deviceCodeGrantRequest(as, client, oauth.None(), deviceCode, {
        ...requestOptions(issuer),
        additionalParameters: { resource },
      }),
    );
    return { kind: "tokens", value: { tokens, started } };
  } catch (error) {
    if (error instanceof oauth.ResponseBodyError) {
      if (error.status >= 500)
        return { kind: "transient", reason: `${error.status} ${error.error}` };
      if (error.error === "authorization_pending") return { kind: "pending" };
      if (error.error === "slow_down") return { kind: "slow-down" };
      return { kind: "refused", error: error.error, description: error.error_description };
    }
    // a 5xx whose body is no OAuth error (the edge's 503) is no conform answer to oauth4webapi
    if (
      error instanceof oauth.OperationProcessingError &&
      error.cause instanceof Response &&
      error.cause.status >= 500
    )
      return { kind: "transient", reason: String(error.cause.status) };
    // fetch's network failure (a TypeError; oauth4webapi's own TypeErrors carry a `code`), or the
    // request's own timeout (`requestOptions`)
    const networkFailure = error instanceof TypeError && !("code" in error);
    if (networkFailure || (error instanceof Error && error.name === "TimeoutError"))
      return { kind: "transient", reason: error.message };
    throw error;
  }
}