feat(console): read a QR code from a PNG with a pure decoder

This commit is contained in:
imSp4rky
2026-11-27 12:40:41 -07:00
parent cfe6685dfc
commit 8a93b4f49a
8 changed files with 519 additions and 2 deletions
+20 -1
View File
@@ -279,7 +279,7 @@ session shows it. A REST download job shows it in its `notice` field until the w
For a login that the user scans with a phone, give the text of the QR code as `qr`. Both
`wait_for_approval` and `request_input` take it. The terminal that shows the message draws
the code under it, on the client for a remote session. Give the text that the login API puts in
the code, such as the login URL, not an image. Keep the URL or code in the message too: a
the code, such as the login URL. Keep the URL or code in the message too: a
terminal that cannot draw the code, or a phone that cannot read it, still shows the text.
`EXAMPLE.scan_login` in `unshackle/services/EXAMPLE/` shows the whole flow.
@@ -292,6 +292,25 @@ token = self.wait_for_approval(
)
```
When the login API gives only a PNG of the QR code, read the text from the image with
`read_qr_image` from `unshackle.core.console`, and give that text as `qr`. It reads a clean,
axis-aligned code, dark on a light background, as a login API renders it. Decode a base64 data URI
to bytes first. It does no error correction, so a code with a logo or other mark over it does not
read. It returns `None` for such a code, for an interlaced PNG or another image format, and for a
photo of a code. The terminal then shows only the message.
```python
from unshackle.core.console import read_qr_image
png = self.session.get(login["qr_image_url"]).content
token = self.wait_for_approval(
f"Scan the code with the app, or open {login_url}",
check=lambda: self.poll_login(session_id),
timeout=expires_in,
qr=read_qr_image(png),
)
```
The wait sees a cancel only between two `check` calls, so `check` must return within a few
seconds. A `check` that reads a socket keeps the socket open across calls and returns `None`
after each short idle wait.
+2
View File
@@ -96,6 +96,8 @@ These are abstract. A service will not load unless it defines all three:
another device, such as a pair code. A remote-dl session shows the message as a log
line, and a REST download job shows it as the job's `notice`. Both methods take `qr`, the
text of a QR code to scan, and the terminal or UI that shows the user the message draws it.
When the login API gives only a PNG, `read_qr_image(data)` in `unshackle.core.console`
gives the text.
- **Event callbacks**: `on_segment_downloaded`, `on_track_downloaded`,
`on_track_decrypted`, `on_track_repacked`, `on_track_multiplex` let a service react to
pipeline events.
+241
View File
@@ -0,0 +1,241 @@
import io
import random
import struct
import zlib
from pathlib import Path
import pytest
import segno
from unshackle.core.console import read_qr_image
URL = "https://login.example/scan?session=EXAMPLE&code=0123456789abcdef"
FIXTURES = Path(__file__).parent.parent / "fixtures" / "qr"
INK, PAPER = (20, 40, 120), (250, 240, 200)
def segno_png(data: str = URL, **options) -> bytes:
make = {k: options.pop(k) for k in ("version", "error", "mask", "eci") if k in options}
buf = io.BytesIO()
segno.make_qr(data, **make).save(buf, kind="png", **options)
return buf.getvalue()
def chunk(kind: bytes, body: bytes) -> bytes:
return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body))
def png_file(header: bytes, raw: bytes, extra: bytes = b"") -> bytes:
sig = b"\x89PNG\r\n\x1a\n"
return sig + chunk(b"IHDR", header) + extra + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")
def paeth(a: int, b: int, c: int) -> int:
p = a + b - c
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
return a if pa <= pb and pa <= pc else b if pb <= pc else c
def filtered(kind: int, line: bytes, prev: bytes, bpp: int) -> bytes:
out = bytearray()
for i, x in enumerate(line):
a, b, c = (line[i - bpp], prev[i], prev[i - bpp]) if i >= bpp else (0, prev[i], 0)
out.append((x - (0, a, b, (a + b) // 2, paeth(a, b, c))[kind]) & 255)
return bytes(out)
def encode_png(
dark_px: tuple,
light_px: tuple,
colour: int,
depth: int = 8,
scale: float = 3,
border: int = 4,
flip: tuple = (),
caption: bool = False,
**chunks: bytes,
) -> bytes:
"""A PNG of URL in any colour type and bit depth, each row with the next of the five filters.
*flip* lists symbol modules (row, column) to invert; *caption* adds a dark bar under the code.
"""
matrix = [list(row) for row in segno.make_qr(URL).matrix_iter(border=border)]
for r, c in flip:
matrix[r + border][c + border] ^= 1
if caption:
width = len(matrix[0])
matrix += (
[[0] * width] * 2 + [[int(width // 3 < x < 2 * width // 3) for x in range(width)]] * 2 + [[0] * width] * 2
)
side = int(len(matrix[0]) * scale)
channels = len(dark_px)
bpp = max(1, channels * depth // 8)
raw, prev = bytearray(), b""
for y in range(int(len(matrix) * scale)):
samples = [v for x in range(side) for v in (dark_px if matrix[int(y / scale)][int(x / scale)] else light_px)]
if depth == 16:
line = b"".join(v.to_bytes(2, "big") for v in samples)
elif depth == 8:
line = bytes(samples)
else:
bits = "".join(format(v, f"0{depth}b") for v in samples)
line = int(bits.ljust(-(-len(bits) // 8) * 8, "0"), 2).to_bytes(-(-len(bits) // 8), "big")
prev = prev or bytes(len(line))
raw += bytes([y % 5]) + filtered(y % 5, line, prev, bpp)
prev = line
header = struct.pack(">IIBBBBB", side, int(len(matrix) * scale), depth, colour, 0, 0, 0)
extra = b"".join(chunk(kind.encode(), body) for kind, body in chunks.items())
return png_file(header, bytes(raw), extra)
@pytest.mark.parametrize("version", [1, 2, 7, 10, 25, 40])
def test_each_version_gives_its_text(version: int) -> None:
assert read_qr_image(segno_png("LOGIN-EXAMPLE", version=version, scale=2)) == "LOGIN-EXAMPLE"
@pytest.mark.parametrize("error", ["L", "M", "Q", "H"])
def test_each_error_correction_level_gives_its_text(error: str) -> None:
assert read_qr_image(segno_png(error=error)) == URL
@pytest.mark.parametrize("mask", range(8))
def test_each_mask_gives_its_text(mask: int) -> None:
assert read_qr_image(segno_png(mask=mask)) == URL
@pytest.mark.parametrize("scale", [1, 3, 8])
@pytest.mark.parametrize("border", [0, 4])
def test_each_scale_and_border_gives_its_text(scale: int, border: int) -> None:
assert read_qr_image(segno_png(scale=scale, border=border)) == URL
@pytest.mark.parametrize("scale", [1.37, 2.6, 4.5])
def test_a_resize_by_a_fraction_gives_its_text(scale: float) -> None:
assert read_qr_image(encode_png((0,), (255,), colour=0, scale=scale)) == URL
@pytest.mark.parametrize(
"png",
[
pytest.param(lambda: segno_png(), id="grey-1bit"),
pytest.param(lambda: encode_png((0,), (3,), colour=0, depth=2), id="grey-2bit"),
pytest.param(lambda: encode_png((0,), (255,), colour=0), id="grey-8bit"),
pytest.param(lambda: encode_png((0x00FF,), (0xFF00,), colour=0, depth=16), id="grey-16bit"),
pytest.param(lambda: encode_png((128,), (0,), colour=0, tRNS=struct.pack(">H", 0)), id="grey-key-clear-black"),
pytest.param(lambda: segno_png(dark="darkblue", light="#ffff99"), id="palette-coloured"),
pytest.param(lambda: segno_png(light=None), id="palette-transparent"),
pytest.param(
lambda: encode_png((1,), (0,), colour=3, depth=4, PLTE=bytes((0, 0, 0) + INK), tRNS=b"\x00"),
id="palette-4bit-clear-black",
),
pytest.param(lambda: encode_png(INK, PAPER, colour=2), id="rgb-coloured"),
pytest.param(
lambda: encode_png(INK, (0, 0, 0), colour=2, tRNS=struct.pack(">3H", 0, 0, 0)), id="rgb-key-clear-black"
),
pytest.param(lambda: encode_png((5000, 9000, 30000), (65535,) * 3, colour=2, depth=16), id="rgb-16bit"),
pytest.param(lambda: encode_png((0, 255), (0, 0), colour=4), id="grey-alpha-clear-black"),
pytest.param(lambda: encode_png((0, 0, 0, 255), (255, 255, 255, 255), colour=6), id="rgba-black-on-white"),
pytest.param(lambda: encode_png((*INK, 255), (0, 0, 0, 0), colour=6), id="rgba-coloured-on-clear-black"),
],
)
def test_each_png_colour_type_gives_its_text(png) -> None:
assert read_qr_image(png()) == URL
@pytest.mark.parametrize(
"text",
[
"0123456789012",
"HELLO WORLD $%*+-./:",
"caf\u00e9 latin-1",
"\u20ac utf-8 \U0001f511",
"\u6f22\u5b57\u30c6\u30b9\u30c8\u4e55\u500f\u51dc",
],
ids=["numeric", "alphanumeric", "latin-1", "utf-8", "kanji"],
)
def test_each_data_mode_gives_its_text(text: str) -> None:
assert read_qr_image(segno_png(text)) == text
def test_an_eci_header_is_skipped() -> None:
assert read_qr_image(segno_png("\u20ac utf-8", eci=True)) == "\u20ac utf-8"
@pytest.mark.parametrize("name", ["qrcode_pypng.png", "qrcode_pillow_rgba.png"])
def test_png_from_another_encoder_gives_its_text(name: str) -> None:
"""One 1-bit PNG from a pure encoder; one coloured RGBA PNG resized 1.37x with bilinear smoothing."""
assert (
read_qr_image((FIXTURES / name).read_bytes())
== "https://login.example/activate?session=EXAMPLE&code=QRCODE-1234"
)
def test_a_damaged_payload_module_gives_none_not_wrong_text() -> None:
size = segno.make_qr(URL).symbol_size(border=0)[0]
assert read_qr_image(encode_png((0,), (255,), colour=0, flip=[(size - 11, size - 1)])) is None
def test_a_damaged_top_left_format_copy_reads_from_the_other_copy() -> None:
assert read_qr_image(encode_png((0,), (255,), colour=0, flip=[(8, c) for c in range(6)])) == URL
def test_format_information_reads_with_two_wrong_bits_in_each_copy() -> None:
size = segno.make_qr(URL).symbol_size(border=0)[0]
flip = [(8, 0), (8, 2), (8, size - 1), (8, size - 3)]
assert read_qr_image(encode_png((0,), (255,), colour=0, flip=flip)) == URL
def test_a_caption_under_the_code_is_ignored() -> None:
assert read_qr_image(encode_png((0,), (255,), colour=0, caption=True)) == URL
def test_an_image_over_the_size_limit_is_not_decoded(monkeypatch) -> None:
from unshackle.core.utils import qr_read
def no_unfilter(*args: object) -> None:
raise AssertionError("decoded an image over the limit")
monkeypatch.setattr(qr_read, "_unfilter", no_unfilter)
side = 2100
header = struct.pack(">IIBBBBB", side, side, 8, 6, 0, 0, 0)
assert read_qr_image(png_file(header, bytes((side * 4 + 1) * side))) is None
def interlaced(png: bytes) -> bytes:
return png[:28] + b"\x01" + png[29:]
@pytest.mark.parametrize(
"data",
[
pytest.param(b"", id="empty"),
pytest.param(None, id="none"),
pytest.param(b"not an image", id="text"),
pytest.param(segno_png()[:60], id="truncated"),
pytest.param(interlaced(segno_png()), id="interlaced"),
pytest.param(encode_png((255,), (255,), colour=0), id="blank"),
pytest.param(
encode_png((0,), (255,), colour=0)[:16] + struct.pack(">II", 100000, 100000) + b"\x08\x00", id="huge"
),
pytest.param(segno.make_micro("12345").png_data_uri().encode(), id="data-uri"),
],
)
def test_bytes_that_hold_no_readable_code_give_none(data: bytes) -> None:
assert read_qr_image(data) is None
def test_a_dark_square_with_no_code_gives_none() -> None:
side = 40
raw = b"".join(b"\x00" + bytes(0 if 5 <= x < 35 and 5 <= y < 35 else 255 for x in range(side)) for y in range(side))
header = struct.pack(">IIBBBBB", side, side, 8, 0, 0, 0, 0)
assert read_qr_image(png_file(header, raw)) is None
def test_corrupted_bytes_never_raise() -> None:
rng = random.Random(187)
png = encode_png((0,), (255,), colour=0, scale=1)
for _ in range(300):
data = bytearray(png)
for _ in range(rng.randint(1, 8)):
data[rng.randrange(len(data))] = rng.randrange(256)
read_qr_image(bytes(data))
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 443 B

+8
View File
@@ -539,6 +539,13 @@ def qr_text(data: str, indent: int = 5) -> Text:
return text
def read_qr_image(data: bytes) -> str | None:
"""Give the text of the QR code in a PNG image, to pass as ``qr=``. None when the image holds no code that reads."""
from unshackle.core.utils.qr_read import read_qr_image
return read_qr_image(data)
def show_qr(data: str) -> None:
"""Draw *data* as a QR code on the shared console, unless a prompt handler stands in for the terminal.
@@ -597,6 +604,7 @@ __all__ = (
"print_listing",
"print_wide",
"prompt_user",
"read_qr_image",
"set_notice_handler",
"set_prompt_handler",
"show_notice",
+247
View File
@@ -0,0 +1,247 @@
"""Read the text of a QR code from a PNG image, with the standard library and the QR tables of segno."""
import struct
import zlib
from segno import consts, encoder
MAX_RAW_BYTES = 1 << 24
CHANNELS = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}
def read_qr_image(data: bytes) -> str | None:
"""Give the text of the QR code in a PNG image, or None when the bytes hold no QR code that reads.
The code must be axis-aligned and dark on a light background, as an API renders it. Transparency counts
as white. An interlaced PNG gives None, and so does a damaged code: there is no error correction.
"""
try:
dark = _dark_rows(_grey_rows(data))
box = _bounding_box(dark)
size = _symbol_size(dark, *box)
return _decode(_sample(dark, *box, size))
except (ValueError, IndexError, KeyError, TypeError, struct.error, zlib.error):
return None
def _grey_rows(data: bytes) -> list[bytes]:
"""The luminance of each pixel, row by row, with alpha composited over white."""
if data[:8] != b"\x89PNG\r\n\x1a\n":
raise ValueError("not a PNG")
pos, header, palette, trns, idat = 8, b"", b"", b"", []
while pos + 8 <= len(data):
length, kind = struct.unpack(">I4s", data[pos : pos + 8])
body = data[pos + 8 : pos + 8 + length]
pos += 12 + length
if kind == b"IHDR":
header = body
elif kind == b"PLTE":
palette = body
elif kind == b"tRNS":
trns = body
elif kind == b"IDAT":
idat.append(body)
elif kind == b"IEND":
break
width, height, depth, colour, _, _, interlace = struct.unpack(">IIBBBBB", header)
channels = CHANNELS[colour]
bpp = max(1, channels * depth // 8)
stride = (width * channels * depth + 7) // 8
if interlace or depth not in (1, 2, 4, 8, 16) or not width or not 0 < (stride + 1) * height <= MAX_RAW_BYTES:
raise ValueError("unsupported PNG")
raw = zlib.decompressobj().decompress(b"".join(idat), (stride + 1) * height)
if len(raw) < (stride + 1) * height:
raise ValueError("PNG data ends early")
if colour == 3:
alpha = trns.ljust(len(palette) // 3, b"\xff")
lut = bytes(_over(_luma(*palette[i * 3 : i * 3 + 3]), alpha[i]) for i in range(len(palette) // 3))
else:
lut = bytes(v * 255 // ((1 << depth) - 1) for v in range(1 << depth)) if depth < 8 else bytes(range(256))
key = (
tuple(v >> 8 if depth == 16 else v for v in struct.unpack(f">{len(trns) // 2}H", trns))
if colour in (0, 2)
else ()
)
if colour == 0 and key:
lut = lut[: key[0]] + b"\xff" + lut[key[0] + 1 :]
lut = lut.ljust(256, b"\x00")
per, mask = max(1, 8 // depth), (1 << depth) - 1
rows, prev = [], bytes(stride)
for y in range(height):
line = _unfilter(
raw[y * (stride + 1)], bytearray(raw[y * (stride + 1) + 1 : (y + 1) * (stride + 1)]), prev, bpp
)
prev = line
s = bytes(line[::2] if depth == 16 else line)
if depth < 8:
s = bytes(s[i // per] >> (8 - depth * (i % per + 1)) & mask for i in range(width))
if colour in (0, 3):
rows.append(s.translate(lut))
elif colour == 2:
rows.append(bytes(255 if px == key else _luma(*px) for px in zip(s[0::3], s[1::3], s[2::3], strict=True)))
elif colour == 4:
rows.append(bytes(map(_over, s[0::2], s[1::2])))
else:
rows.append(bytes(map(_over, map(_luma, s[0::4], s[1::4], s[2::4]), s[3::4])))
return rows
def _unfilter(kind: int, line: bytearray, prev: bytes, bpp: int) -> bytearray:
"""Undo one of the five PNG scanline filters."""
if kind == 1:
for i in range(bpp, len(line)):
line[i] = (line[i] + line[i - bpp]) & 255
elif kind == 2:
for i in range(len(line)):
line[i] = (line[i] + prev[i]) & 255
elif kind == 3:
for i in range(len(line)):
line[i] = (line[i] + ((line[i - bpp] if i >= bpp else 0) + prev[i]) // 2) & 255
elif kind == 4:
for i in range(len(line)):
a, b, c = (line[i - bpp], prev[i], prev[i - bpp]) if i >= bpp else (0, prev[i], 0)
pa, pb, pc = abs(b - c), abs(a - c), abs(a + b - 2 * c)
line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 255
elif kind:
raise ValueError("unknown PNG filter")
return line
def _luma(r: int, g: int, b: int) -> int:
return (299 * r + 587 * g + 114 * b) // 1000
def _over(grey: int, alpha: int) -> int:
return (grey * alpha + 255 * (255 - alpha)) // 255
def _dark_rows(rows: list[bytes]) -> list[bytes]:
"""Each pixel as 1 for dark or 0 for light, split at the middle of the darkest and lightest grey."""
low, high = min(map(min, rows)), max(map(max, rows))
if high - low < 32:
raise ValueError("no contrast")
table = bytes(int(v < (low + high + 1) // 2) for v in range(256))
return [row.translate(table) for row in rows]
def _bounding_box(dark: list[bytes]) -> tuple[int, int, int, int]:
"""Left, top, width and height of the symbol, from the top edges of its two upper finder patterns.
The width comes from the top dark row and the height from the left edge, so a caption under the code does not count.
"""
top = min(y for y, row in enumerate(dark) if 1 in row)
left, right = dark[top].find(1), dark[top].rfind(1)
bottom = bytes(row[left] for row in dark).rfind(1)
return left, top, right - left + 1, bottom - top + 1
def _symbol_size(dark: list[bytes], left: int, top: int, width: int, height: int) -> int:
"""Modules per side: the size whose row 6 and column 6 sample as finder, timing pattern and finder."""
for size in range(21, 178, 4):
line = bytes(1 if c < 7 or c >= size - 7 else 0 if c in (7, size - 8) else (c + 1) % 2 for c in range(size))
row = dark[top + 13 * height // (2 * size)]
x6 = left + 13 * width // (2 * size)
if _sample_line(row, left, width, size) == line == _sample_line(bytes(r[x6] for r in dark), top, height, size):
return size
raise ValueError("no QR timing pattern")
def _sample_line(pixels: bytes, start: int, length: int, size: int) -> bytes:
"""The *size* module centres of a line of pixels."""
return bytes(pixels[start + (2 * i + 1) * length // (2 * size)] for i in range(size))
def _sample(dark: list[bytes], left: int, top: int, width: int, height: int, size: int) -> list[bytes]:
"""The module grid, read at the centre of each module."""
return [_sample_line(dark[top + (2 * r + 1) * height // (2 * size)], left, width, size) for r in range(size)]
def _decode(matrix: list[bytes]) -> str | None:
"""The text of a sampled module grid; None for a symbol with no data."""
size = len(matrix)
version = (size - 17) // 4
top_left = [(i, 8) for i in range(6)] + [(7, 8), (8, 8), (8, 7)] + [(8, 14 - i) for i in range(9, 15)]
other = [(8, size - 1 - i) for i in range(8)] + [(size - 15 + i, 8) for i in range(8, 15)]
formats = [sum(matrix[r][c] << i for i, (r, c) in enumerate(cells)) for cells in (top_left, other)]
distance, index = min(((v ^ code).bit_count(), i) for v in formats for i, code in enumerate(consts.FORMAT_INFO))
if distance > 3:
raise ValueError("unreadable format information")
level, mask = divmod(index, 8)
layout = encoder.make_matrix(size, size)
encoder.add_finder_patterns(layout, size, size)
encoder.add_alignment_patterns(layout, size, size)
masked = encoder.get_data_mask_functions(False)[mask]
bits, upward = [], True
for right in [*range(size - 1, 7, -2), *range(5, 0, -2)]:
for r in range(size - 1, -1, -1) if upward else range(size):
bits += [matrix[r][c] ^ masked(r, c) for c in (right, right - 1) if layout[r][c] == 0x2]
upward = not upward
codewords = int("".join(map(str, bits[: len(bits) // 8 * 8])), 2).to_bytes(len(bits) // 8, "big")
groups = consts.ECC[version][level] # type: ignore[index]
blocks = [(ec.num_data, ec.num_total - ec.num_data) for ec in groups for _ in range(ec.num_blocks)]
data = [bytearray() for _ in blocks]
ecc = [bytearray() for _ in blocks]
pos = 0
for i in range(max(d for d, _ in blocks)):
for block, (d, _) in zip(data, blocks, strict=True):
if i < d:
block.append(codewords[pos])
pos += 1
for _ in range(blocks[0][1]):
for block in ecc:
block.append(codewords[pos])
pos += 1
message = encoder.Buffer()
for byte in b"".join(data):
message.append_bits(byte, 8)
if encoder.make_blocks(groups, message)[1] != ecc:
raise ValueError("QR error correction check failed")
return _parse(b"".join(data), version)
def _parse(data: bytes, version: int) -> str | None:
"""The text of the data bit stream: numeric, alphanumeric, byte and kanji segments, ECI skipped."""
value, left = int.from_bytes(data, "big"), len(data) * 8
def read(n: int) -> int:
nonlocal left
if n > left:
raise ValueError("QR data ends early")
left -= n
return (value >> left) & ((1 << n) - 1)
chars = consts.ALPHANUMERIC_CHARS.decode()
text = []
while left >= 4 and (mode := read(4)):
if mode == consts.MODE_ECI:
first = read(8)
read(0 if first < 0x80 else 8 if first < 0xC0 else 16)
continue
if mode == consts.MODE_STRUCTURED_APPEND:
read(16)
continue
count = read(consts.CHAR_COUNT_INDICATOR_LENGTH[mode][encoder.version_range(version)])
if mode == consts.MODE_NUMERIC:
groups = [3] * (count // 3) + [count % 3] * bool(count % 3)
text += [f"{read(3 * k + 1):0{k}d}" for k in groups]
elif mode == consts.MODE_ALPHANUMERIC:
for _ in range(count // 2):
pair = read(11)
text.append(chars[pair // 45] + chars[pair % 45])
if count % 2:
text.append(chars[read(6)])
elif mode == consts.MODE_BYTE:
raw = bytes(read(8) for _ in range(count))
try:
text.append(raw.decode("utf-8"))
except UnicodeDecodeError:
text.append(raw.decode("latin-1"))
elif mode == consts.MODE_KANJI:
pairs = [divmod(read(13), 0xC0) for _ in range(count)]
words = [(a << 8 | b) + (0x8140 if (a << 8 | b) < 0x1F00 else 0xC140) for a, b in pairs]
text.append(b"".join(w.to_bytes(2, "big") for w in words).decode(consts.KANJI_ENCODING))
else:
raise ValueError("unsupported QR mode")
return "".join(text) or None
+1 -1
View File
@@ -210,7 +210,7 @@ class EXAMPLE(Service):
def scan_login(self) -> dict[str, Any]:
"""Log in with a QR code the user scans in the app, for a run with no cookies or credentials."""
device = self.session.post(url=self.config["endpoints"]["device_code"]).json()
# Pass the QR code's TEXT as qr= (the URL the app encodes), never an image. The local
# Pass the QR code's TEXT as qr= (the URL the app encodes); for a PNG, read_qr_image(png). The local
# terminal draws it, and over `serve` a --remote client or the REST job's UI draws it.
# Keep the URL and code in the message too, for a terminal that cannot draw the code.
# `request_input(prompt, qr=...)` takes the same argument when the user must type an answer.