From 8a93b4f49ab88c7ad7e6cad3d14684e33cae1436 Mon Sep 17 00:00:00 2001 From: imSp4rky Date: Fri, 27 Nov 2026 12:40:41 -0700 Subject: [PATCH] feat(console): read a QR code from a PNG with a pure decoder --- docs/dev/creating-a-service.md | 21 +- docs/dev/service-architecture.md | 2 + tests/core/test_read_qr_image.py | 241 ++++++++++++++++++++++ tests/fixtures/qr/qrcode_pillow_rgba.png | Bin 0 -> 15172 bytes tests/fixtures/qr/qrcode_pypng.png | Bin 0 -> 443 bytes unshackle/core/console.py | 8 + unshackle/core/utils/qr_read.py | 247 +++++++++++++++++++++++ unshackle/services/EXAMPLE/__init__.py | 2 +- 8 files changed, 519 insertions(+), 2 deletions(-) create mode 100644 tests/core/test_read_qr_image.py create mode 100644 tests/fixtures/qr/qrcode_pillow_rgba.png create mode 100644 tests/fixtures/qr/qrcode_pypng.png create mode 100644 unshackle/core/utils/qr_read.py diff --git a/docs/dev/creating-a-service.md b/docs/dev/creating-a-service.md index eef05a01..2cafbe00 100644 --- a/docs/dev/creating-a-service.md +++ b/docs/dev/creating-a-service.md @@ -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. diff --git a/docs/dev/service-architecture.md b/docs/dev/service-architecture.md index 3d324ebf..bb53f93a 100644 --- a/docs/dev/service-architecture.md +++ b/docs/dev/service-architecture.md @@ -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. diff --git a/tests/core/test_read_qr_image.py b/tests/core/test_read_qr_image.py new file mode 100644 index 00000000..cee96672 --- /dev/null +++ b/tests/core/test_read_qr_image.py @@ -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)) diff --git a/tests/fixtures/qr/qrcode_pillow_rgba.png b/tests/fixtures/qr/qrcode_pillow_rgba.png new file mode 100644 index 0000000000000000000000000000000000000000..da1757271067256bf2f7158b0093f462dd6b8b03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FOAavsj+7Vqk-ZXxchP_4T{ z^C!w1t+LYFeR^`$GsGzsj*9Q?Ch=cM@@cyUVGCjHZIs)T$cKM`eTTUXm9S2bvSoSG zah=$h)a4r~&Nx6_JnGE1DA%bS!)MEeX@|K-&4w#dEIo7^;zdhrdAJ7_J5g@Ux_rm| zp7SEab@vUt=^S6899t^)rjLPy`RFLgzRl+DEH78AJs;F(V^J*S?dvM|4&TUND= z?|BF%xer?MmSgNYzbNP2*bZAhbzOcN 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", diff --git a/unshackle/core/utils/qr_read.py b/unshackle/core/utils/qr_read.py new file mode 100644 index 00000000..2ae2cd4e --- /dev/null +++ b/unshackle/core/utils/qr_read.py @@ -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 diff --git a/unshackle/services/EXAMPLE/__init__.py b/unshackle/services/EXAMPLE/__init__.py index 0041f26d..cf61f0df 100644 --- a/unshackle/services/EXAMPLE/__init__.py +++ b/unshackle/services/EXAMPLE/__init__.py @@ -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.