CLI: the device sign-in's QR code is half the width and half the height, and is left out of a terminal that it does not fit (#15)
jonas, 2026-11-26 22:22 UTC ยท ca5d72a51c4447512af828687fc947a3ae0653f3 ยท parent d1d06c4
4 files changed
- M core/lib/src/cli/device-login/index.ts
- A core/lib/src/cli/device-login/qr.test.ts
- A core/lib/src/cli/device-login/qr.ts
- M core/lib/src/node.ts
M core/lib/src/cli/device-login/index.ts
@@ -1,24 +1,26 @@ // 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 { encode, renderUnicodeCompact } from "uqr"; 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`). `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). */ + * `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; @@ -43,27 +45,38 @@ ), ); 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`); - input.print("Or scan this QR code. It opens the same page:\n"); - input.print(`${terminalQrCode(through, input.colors)}\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) { - input.print("Or scan this QR code, or open the link under it. Both fill in the code:\n"); - input.print(`${terminalQrCode(device.verification_uri_complete, input.colors)}\n`); - input.print(` ${device.verification_uri_complete}\n`); + 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( - `The code expires in ${Math.round(expiresInSeconds / 60)} minutes. Waiting for approval...`, - ); + input.print(waiting); const answer = await pollUntilAnswered({ intervalSeconds: device.interval || 5, deadline: Date.now() + expiresInSeconds * 1000, @@ -72,36 +85,6 @@ input.print(`Could not reach ${issuer} (${reason}); trying again in ${waitMs / 1000} s.`), }); return sessionFromTokens(answer.tokens, mind, client.client_id, answer.started); -} - -/** `text` as a QR code for a phone's camera (uqr, https://github.com/unjs/uqr, error correction L), - * indented two spaces. - * - * With `colors`, as `qrencode -t ANSI` draws it: a module is two spaces on a background color, - * black (40) or bright white (107; 47 first, for a terminal without bright colors). So dark is - * dark and light is light in any theme, and the colors fill each line to the next, whatever the - * line height. The quiet zone is two modules: the spec's four would take 84 columns. - * - * Without colors (a pipe, an agent's transcript): Unicode half blocks in the text color, two - * modules a character, with a four-module quiet zone. They scan in a dark terminal whose lines - * touch; space between lines cuts through them, so the link under the code is the fallback. */ -function terminalQrCode(text: string, colors: boolean) { - if (!colors) - return renderUnicodeCompact(text, { ecc: "L", border: 4 }) - .split("\n") - .map((line) => ` ${line}`) - .join("\n"); - return encode(text, { ecc: "L", border: 2 }) - .data.map((row) => row.map((dark) => (dark ? "1" : "0")).join("")) - .map((row) => { - const cells = row.replace( - /1+|0+/g, - (run) => `\u001b[${run[0] === "1" ? "40" : "47;107"}m${" ".repeat(run.length)}`, - ); - // a reset at the end of every line, so a line that wraps or is cut never colors the next - return ` ${cells}\u001b[0m`; - }) - .join("\n"); } /** Whether the person sees the colors written to a stream: a terminal (`isTTY`) that is not
A core/lib/src/cli/device-login/qr.test.ts
@@ -0,0 +1,66 @@ +import { encode } from "uqr"; +import { expect, test } from "vitest"; +import { terminalQrCode } from "./qr.ts"; + +// synthetic: no mind answers at this address, and the code is no code of a sign-in +const LINK = "https://iterate.example.com/device?user_code=BCDF-GHJK"; + +/** The dark modules that a camera sees in a code `drawn` with colors: a row for each half line, + * read from the background that the escape codes set and from the black half blocks on it. */ +function modulesOf(drawn: string) { + const rows: boolean[][] = []; + for (const line of drawn.split("\n")) { + const top: boolean[] = []; + const bottom: boolean[] = []; + let blackBackground = false; + for (const [, code, char] of line.slice(2).matchAll(/\u001b\[([\d;]*)m|(.)/gu)) { + if (code !== undefined) blackBackground = code === "40"; + else { + top.push(blackBackground || char === "โ"); + bottom.push(blackBackground || char === "โ"); + } + } + rows.push(top, bottom); + } + return rows; +} + +test("with colors, a character is one module wide and two high, and the modules are the code's", () => { + const { data, size } = encode(LINK, { ecc: "L", border: 2 }); + const drawn = terminalQrCode(LINK, true)!; + const lines = drawn.split("\n"); + expect(lines).toHaveLength(Math.ceil(size / 2)); + // every line ends with a reset, and is the indent and one character for each module + for (const line of lines) { + expect(line.endsWith("\u001b[0m")).toBe(true); + expect(line.replace(/\u001b\[[\d;]*m/g, "")).toHaveLength(2 + size); + } + // the half line under an odd code is light + const expected = [...data, ...(size % 2 ? [Array<boolean>(size).fill(false)] : [])]; + expect(modulesOf(drawn)).toEqual(expected); +}); + +// what the sign-in prints under the code (index.ts `deviceLogin`) +const UNDER = ["", ` ${LINK}`, "", "The code expires in 5 minutes. Waiting for approval..."]; + +// 19 lines of code with colors (21 without, whose quiet zone is four modules), then the lines +// under it and the cursor's line: 5 rows when no line wraps, 7 when the link and the last line do +test.for([ + { colors: true, columns: 80, rows: 24, fits: true }, + { colors: true, columns: 40, rows: 26, fits: true }, + { colors: true, columns: 40, rows: 25, fits: false }, + { colors: true, columns: 38, rows: 50, fits: false }, + { colors: false, columns: 80, rows: 26, fits: true }, + { colors: false, columns: 44, rows: 28, fits: true }, + { colors: false, columns: 44, rows: 27, fits: false }, + { colors: false, columns: 42, rows: 50, fits: false }, +])("$columns columns and $rows rows, colors $colors: fits $fits", (terminal) => { + const drawn = terminalQrCode(LINK, terminal.colors, terminal, UNDER); + if (!terminal.fits) return expect(drawn).toBeNull(); + const lines = drawn!.replace(/\u001b\[[\d;]*m/g, "").split("\n"); + expect(Math.max(...lines.map((line) => line.length))).toBeLessThanOrEqual(terminal.columns); +}); + +test("a stream that is no terminal has no size, and gets the code", () => { + expect(terminalQrCode(LINK, false, { columns: undefined, rows: undefined })).toContain("โ"); +});
A core/lib/src/cli/device-login/qr.ts
@@ -0,0 +1,61 @@ +// A QR code for a phone's camera, drawn in a terminal. +import { encode, renderUnicodeCompact } from "uqr"; + +/** The terminal that the code is drawn in: `process.stderr` is one. No `columns` or `rows` (a + * pipe, an agent's transcript) is no limit. */ +export type TerminalScreen = { columns?: number; rows?: number }; + +/** `text` as a QR code (uqr, https://github.com/unjs/uqr, error correction L), indented two + * spaces: a character is one module wide and two modules high. Or null when `screen` is too small + * for it: a code whose lines wrap, or whose top has scrolled away, does not scan, so the caller + * prints the link alone. `under` is the lines that the caller prints under the code: they, and + * the line that the cursor then waits on, push the code up. + * + * With `colors`, a character is a half block in black (30) on a background color, black (40) or + * bright white (107; 47 first, for a terminal without bright colors). So dark is dark and light + * is light in any theme, and the background fills each line to the next, whatever the line + * height. The quiet zone is two modules. + * + * Without colors (a pipe, an agent's transcript): Unicode half blocks in the text color, with a + * four-module quiet zone. They scan in a dark terminal whose lines touch; space between lines + * cuts through them, so the link is the fallback. */ +export function terminalQrCode( + text: string, + colors: boolean, + screen: TerminalScreen = {}, + under: string[] = [], +) { + const lines = colors + ? colorLines(text) + : renderUnicodeCompact(text, { ecc: "L", border: 4 }).split("\n"); + const width = 2 + encode(text, { ecc: "L", border: colors ? 2 : 4 }).size; + const { columns = Infinity, rows = Infinity } = screen; + // a line that is wider than the screen takes more than one of its rows + const rowsUnder = under.reduce( + (sum, line) => sum + Math.max(1, Math.ceil(line.length / columns)), + 1, + ); + if (width > columns || lines.length + rowsUnder > rows) return null; + return lines.map((line) => ` ${line}`).join("\n"); +} + +function colorLines(text: string) { + const { data, size } = encode(text, { ecc: "L", border: 2 }); + const lines: string[] = []; + for (let y = 0; y < size; y += 2) { + let line = ""; + let style = ""; + for (let x = 0; x < size; x++) { + const top = data[y]![x]!; + // under the last line of an odd code is the quiet zone + const bottom = y + 1 < size && data[y + 1]![x]!; + // a cell of one color is its background alone, which fills the whole line height + const next = top && bottom ? "40" : "30;47;107"; + if (next !== style) line += `\u001b[${(style = next)}m`; + line += top === bottom ? " " : top ? "โ" : "โ"; + } + // a reset at the end of every line, so a line that is cut never colors the next + lines.push(`${line}\u001b[0m`); + } + return lines; +}
M core/lib/src/node.ts
@@ -94,6 +94,7 @@ deviceName: `iterate CLI on ${hostname()}`, print, colors: showsColors(process.stderr.isTTY, process.env), + screen: process.stderr, through: options.through, }) : await oauthLogin({