← Back to Pull requests

Add bin/op-to-bw: copy a 1Password 7 Login to Bitwarden (Vaultwarden) #644

Merged
memk merged 2 files (536 lines) on Oct 08, 2026 18:33 UTC
View on GitHub
memk memk commented on Oct 08, 2026 16:38 UTC
Author

Summary

op-to-bw QUERY copies a Login from 1Password 7 to Bitwarden (Vaultwarden).

Source (--vault PATH or $OPVAULT):

  • an .opvault vault file. It prompts for the master password (or reads $OPVAULT_PASSWORD). If no path is given, it looks for one with Spotlight.

  • a .1pif export (File > Export > 1PIF, file or folder). This covers iCloud-synced 1Password 7 vaults, which have no vault file. The export is unencrypted, so delete it afterwards.
  • Flow
    1. Searches non-trashed Login names and URLs (case-insensitive substring).
    2. One match continues automatically; several prompt for a choice; none is an error.
    3. Copies name, username, password, URIs, TOTP, notes and every other section field (concealed ones become hidden fields). Empty fields are skipped.
    4. If a Bitwarden Login with the same name exists, it is updated in place. Several same-named entries prompt, with a "create new" option. On update:
    - the folder, favorite and unrelated custom fields are kept
    - URIs are merged, keeping existing ones and their match settings
    - 1Password notes are appended to existing notes
    - custom fields with the same name are overwritten by 1Password

    --dry-run shows the plan without writing anything.

    Notes

  • Only bw (bitwarden-cli, added to osx/Brewfile) is needed. Run bw config server URL and bw login once beforehand. The script syncs before looking up existing entries and prompts to unlock if $BW_SESSION is unset or stale.

  • The OPVault crypto (PBKDF2-SHA512, HMAC-checked AES-256-CBC) is implemented in pure Python, so keys never appear in ps. Secrets are passed to bw over stdin, not argv.

  • Not copied: attachments, password history, web form autofill fields, folders and tags. Unreadable .1pif items are skipped with a warning.
  • Testing

  • Decrypts and maps AgileBits' public sample vault (master password freddy), including a Login with sections and notes. A wrong password is detected.

  • Parses 1Password 6 and 1Password 7 (cloud vault) sample .1pif exports.

  • The AES routine was checked against openssl on random inputs.

  • Fully type-hinted. Passes mypy --strict --scripts-are-modules bin/op-to-bw and pytype (with its strict flags).

  • bw was stubbed (create, update, multi-match, no match, dry-run). It has not been run against a real Vaultwarden, so try --dry-run first.
  • 🤖 Generated with Claude Code

    Diff: 536 lines (+536 / -0) across 2 files Reviewer: parkr Review duration: 114m
    All Vouch review confidence checks passed
    Residual risk 0.06 = Change Risk (0.42) × (1 − Review Confidence (0.86)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.42 · 536 lines diff across 2 files
    0.42
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.81 · 4 substantive comment(s)
    0.81
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    85%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.376
    Real PR Conversation Timeline
    6 items
    parkr parkr approved these changes on Oct 08, 2026 17:04 UTC
    Approved Reviewer

    Approved these changes.

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 08, 2026 17:05 UTC
    Code Review
    bin/op-to-bw:1
    @@ -0,0 +1,430 @@
    +#!/usr/bin/env python3
    +"""Usage: op-to-bw [--vault PATH] [--dry-run] QUERY
    +
    +Copies a Login from 1Password 7 to Bitwarden (Vaultwarden), creating it or
    +updating an existing entry of the same name.
    +
    +QUERY is matched case-insensitively against Login names and URLs. The source
    +is PATH or $OPVAULT: either an .opvault vault file (prompts for the master
    +password; $OPVAULT_PASSWORD skips the prompt) or a 1Password 7 .1pif export
    +(File > Export > 1PIF; unencrypted, so delete it afterwards).
    +
    +Requires: `brew install bitwarden-cli`.
    +Bitwarden must already point at your server (`bw config server URL`) and be
    +logged in (`bw login`); unlocking is prompted for.
    +"""
    +import argparse
    +import base64
    +import datetime
    +import getpass
    +import hashlib
    +import hmac
    +import json
    +import os
    +import pathlib
    +import shutil
    +import struct
    +import subprocess
    +import sys
    +
    +BW_TEXT, BW_HIDDEN = 0, 1
    +
    +
    +def die(msg):
    +    sys.exit(f"error: {msg}")
    +
    +
    +def run(cmd, stdin=None, interactive=False):
    +    """Runs cmd, returns stdout. Interactive keeps the tty for prompts."""
    +    try:
    +        p = subprocess.run(
    +            cmd,
    +            input=stdin,
    +            text=True,
    +            stdout=subprocess.PIPE,
    +            stderr=None if interactive else subprocess.PIPE,
    +        )
    +    except FileNotFoundError:
    +        die(f"`{cmd[0]}` not found; install it with Homebrew")
    +    if p.returncode != 0:
    +        die(f"`{' '.join(cmd[:3])}` failed: {(p.stderr or '').strip()}")
    +    return p.stdout
    +
    +
    +def run_json(cmd, **kw):
    +    return json.loads(run(cmd, **kw))
    +
    +
    +# 1Password (OPVault)
    +
    +
    +class BadMAC(Exception):
    +    pass
    +
    +
    +def _aes_tables():
    +    exp, log, x = [0] * 255, [0] * 256, 1
    +    for i in range(255):
    +        exp[i], log[x] = x, i
    +        x ^= ((x << 1) ^ (0x1B if x & 0x80 else 0)) & 0xFF  # x *= 3
    +    rotl = lambda v, n: ((v << n) | (v >> (8 - n))) & 0xFF
    +    sbox = [0x63] * 256
    +    for i in range(1, 256):
    +        v = exp[(255 - log[i]) % 255]
    +        sbox[i] = v ^ rotl(v, 1) ^ rotl(v, 2) ^ rotl(v, 3) ^ rotl(v, 4) ^ 0x63
    +    inv = [0] * 256
    +    for i, v in enumerate(sbox):
    +        inv[v] = i
    +
    +    def mul(a, b):
    +        return exp[(log[a] + log[b]) % 255] if a and b else 0
    +
    +    td0 = [
    +        mul(v, 14) << 24 | mul(v, 9) << 16 | mul(v, 13) << 8 | mul(v, 11)
    +        for v in inv
    +    ]
    +    ror8 = lambda w: (w >> 8) | ((w & 0xFF) << 24)
    +    td1 = [ror8(w) for w in td0]
    +    td2 = [ror8(w) for w in td1]
    +    td3 = [ror8(w) for w in td2]
    +    return sbox, inv, td0, td1, td2, td3
    +
    +
    +SBOX, ISBOX, TD0, TD1, TD2, TD3 = _aes_tables()
    +
    +
    +def _aes256_decrypt_keys(key):
    +    """Expands a 32-byte key into round keys for the equivalent inverse cipher."""
    +    w = list(struct.unpack(">8I", key))
    +    rcon = 1
    +    for i in range(8, 60):
    +        t = w[i - 1]
    +        if i % 8 == 0:
    +            t = (t << 8 | t >> 24) & 0xFFFFFFFF
    +            t = sum(SBOX[(t >> s) & 0xFF] << s for s in (24, 16, 8, 0)) ^ (rcon << 24)
    +            rcon = ((rcon << 1) ^ (0x1B if rcon & 0x80 else 0)) & 0xFF
    +        elif i % 8 == 4:
    +            t = sum(SBOX[(t >> s) & 0xFF] << s for s in (24, 16, 8, 0))
    +        w.append(w[i - 8] ^ t)
    +    dk = []
    +    for r in range(14, -1, -1):
    +        words = w[4 * r : 4 * r + 4]
    +        if 0 < r < 14:  # InvMixColumns
    +            words = [
    +                TD0[SBOX[x >> 24]] ^ TD1[SBOX[(x >> 16) & 0xFF]] ^ TD2[SBOX[(x >> 8) & 0xFF]] ^ TD3[SBOX[x & 0xFF]]
    +                for x in words
    +            ]
    +        dk += words
    +    return dk
    +
    +
    +def _aes_decrypt_block(dk, block):
    +    s0, s1, s2, s3 = (a ^ b for a, b in zip(struct.unpack(">4I", block), dk))
    +    for r in range(4, 56, 4):
    +        s0, s1, s2, s3 = (
    +            TD0[s0 >> 24] ^ TD1[(s3 >> 16) & 255] ^ TD2[(s2 >> 8) & 255] ^ TD3[s1 & 255] ^ dk[r],
    +            TD0[s1 >> 24] ^ TD1[(s0 >> 16) & 255] ^ TD2[(s3 >> 8) & 255] ^ TD3[s2 & 255] ^ dk[r + 1],
    +            TD0[s2 >> 24] ^ TD1[(s1 >> 16) & 255] ^ TD2[(s0 >> 8) & 255] ^ TD3[s3 & 255] ^ dk[r + 2],
    +            TD0[s3 >> 24] ^ TD1[(s2 >> 16) & 255] ^ TD2[(s1 >> 8) & 255] ^ TD3[s0 & 255] ^ dk[r + 3],
    +        )
    +    return struct.pack(
    +        ">4I",
    +        (ISBOX[s0 >> 24] << 24 | ISBOX[(s3 >> 16) & 255] << 16 | ISBOX[(s2 >> 8) & 255] << 8 | ISBOX[s1 & 255]) ^ dk[56],
    +        (ISBOX[s1 >> 24] << 24 | ISBOX[(s0 >> 16) & 255] << 16 | ISBOX[(s3 >> 8) & 255] << 8 | ISBOX[s2 & 255]) ^ dk[57],
    +        (ISBOX[s2 >> 24] << 24 | ISBOX[(s1 >> 16) & 255] << 16 | ISBOX[(s0 >> 8) & 255] << 8 | ISBOX[s3 & 255]) ^ dk[58],
    +        (ISBOX[s3 >> 24] << 24 | ISBOX[(s2 >> 16) & 255] << 16 | ISBOX[(s1 >> 8) & 255] << 8 | ISBOX[s0 & 255]) ^ dk[59],
    +    )
    +
    +
    +def cbc_decrypt(key, jobs):
    +    """AES-256-CBC-decrypts [(iv, ciphertext)]. Pure Python, so keys never hit argv."""
    +    dk = _aes256_decrypt_keys(key)
    +    out = []
    +    for iv, ct in jobs:
    +        prev, plain = iv, []
    +        for i in range(0, len(ct), 16):
    +            block = ct[i : i + 16]
    +            d = _aes_decrypt_block(dk, block)
    +            plain.append((int.from_bytes(d, "big") ^ int.from_bytes(prev, "big")).to_bytes(16, "big"))
    +            prev = block
    +        out.append(b"".join(plain))
    +    return out
    +
    +
    +def opdata_decrypt(blobs, enc, mac):
    +    """Decrypts "opdata01" blobs (raw or base64): header, length, IV, data, HMAC."""
    +    jobs, sizes = [], []
    +    for blob in blobs:
    +        raw = blob if blob.startswith(b"opdata01") else base64.b64decode(blob)
    +        if not hmac.compare_digest(hmac.digest(mac, raw[:-32], "sha256"), raw[-32:]):
    +            raise BadMAC
    +        jobs.append((raw[16:32], raw[32:-32]))
    +        sizes.append(int.from_bytes(raw[8:16], "little"))
    +    # Plaintext is prefixed with random padding.
    +    return [p[len(p) - n :] for p, n in zip(cbc_decrypt(enc, jobs), sizes)]
    +
    +
    +def split_keys(material):
    +    return material[:32], material[32:]
    +
    +
    +def read_js(path):
    +    """Reads the JSON object out of `var x={...};` / `ld({...});` files."""
    +    text = path.read_text(encoding="utf-8")
    +    return json.loads(text[text.index("{") : text.rindex("}") + 1])
    +
    +
    +def open_source(arg):

    CodeQL / Explicit returns mixed with implicit (fall through) returns

    Mixing implicit and explicit returns may indicate an error, as implicit returns always return None.

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 08, 2026 17:18 UTC
    Code Review
    bin/op-to-bw:1
    @@ -0,0 +1,533 @@
    +#!/usr/bin/env python3
    +"""Usage: op-to-bw [--vault PATH] [--dry-run] QUERY
    +
    +Copies a Login from 1Password 7 to Bitwarden (Vaultwarden), creating it or
    +updating an existing entry of the same name.
    +
    +QUERY is matched case-insensitively against Login names and URLs. The source
    +is PATH or $OPVAULT: either an .opvault vault file (prompts for the master
    +password; $OPVAULT_PASSWORD skips the prompt) or a 1Password 7 .1pif export
    +(File > Export > 1PIF; unencrypted, so delete it afterwards).
    +
    +Requires: `brew install bitwarden-cli`.
    +Bitwarden must already point at your server (`bw config server URL`) and be
    +logged in (`bw login`); unlocking is prompted for.
    +
    +Type-check with: mypy --strict --scripts-are-modules bin/op-to-bw
    +"""
    +from __future__ import annotations
    +
    +import argparse
    +import base64
    +import datetime
    +import getpass
    +import hashlib
    +import hmac
    +import json
    +import os
    +import pathlib
    +import shutil
    +import struct
    +import subprocess
    +import sys
    +from typing import Any, NoReturn, Optional, Protocol, TypedDict
    +
    +BW_TEXT, BW_HIDDEN = 0, 1
    +
    +Json = dict[str, Any]  # JSON we only pass through (Bitwarden items, vault profiles)
    +Keys = tuple[bytes, bytes]  # (encryption key, MAC key)
    +
    +
    +# 1Password: shapes shared by OPVault and 1PIF (all keys optional in the wild).
    +class OverviewUrl(TypedDict, total=False):
    +    u: Optional[str]
    +
    +
    +class Overview(TypedDict, total=False):
    +    title: str
    +    url: Optional[str]
    +    URLs: list[OverviewUrl]
    +    ainfo: Optional[str]
    +
    +
    +class DetailField(TypedDict, total=False):
    +    designation: str
    +    value: Any
    +
    +
    +class SectionField(TypedDict, total=False):
    +    k: str  # kind: string, concealed, totp, date, ...
    +    n: str
    +    t: str
    +    v: Any
    +
    +
    +class Section(TypedDict, total=False):
    +    title: str
    +    fields: list[SectionField]
    +
    +
    +class PifUrl(TypedDict, total=False):
    +    url: str
    +
    +
    +class Details(TypedDict, total=False):
    +    fields: list[DetailField]
    +    sections: list[Section]
    +    notesPlain: str
    +    URLs: list[PifUrl]
    +
    +
    +class OpItem(TypedDict, total=False):
    +    """An OPVault band item; o, d and k are encrypted."""
    +
    +    category: str
    +    trashed: bool
    +    o: str
    +    d: str
    +    k: str
    +
    +
    +class Entry(TypedDict, total=False):
    +    overview: Overview
    +    item: OpItem  # OPVault: details are decrypted on demand
    +    details: Details  # 1PIF: details are already plain
    +
    +
    +class Source(Protocol):
    +    def logins(self) -> list[Entry]: ...

    CodeQL / Statement has no effect

    This statement has no effect.

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 08, 2026 17:18 UTC
    Code Review
    bin/op-to-bw:1
    @@ -0,0 +1,533 @@
    +#!/usr/bin/env python3
    +"""Usage: op-to-bw [--vault PATH] [--dry-run] QUERY
    +
    +Copies a Login from 1Password 7 to Bitwarden (Vaultwarden), creating it or
    +updating an existing entry of the same name.
    +
    +QUERY is matched case-insensitively against Login names and URLs. The source
    +is PATH or $OPVAULT: either an .opvault vault file (prompts for the master
    +password; $OPVAULT_PASSWORD skips the prompt) or a 1Password 7 .1pif export
    +(File > Export > 1PIF; unencrypted, so delete it afterwards).
    +
    +Requires: `brew install bitwarden-cli`.
    +Bitwarden must already point at your server (`bw config server URL`) and be
    +logged in (`bw login`); unlocking is prompted for.
    +
    +Type-check with: mypy --strict --scripts-are-modules bin/op-to-bw
    +"""
    +from __future__ import annotations
    +
    +import argparse
    +import base64
    +import datetime
    +import getpass
    +import hashlib
    +import hmac
    +import json
    +import os
    +import pathlib
    +import shutil
    +import struct
    +import subprocess
    +import sys
    +from typing import Any, NoReturn, Optional, Protocol, TypedDict
    +
    +BW_TEXT, BW_HIDDEN = 0, 1
    +
    +Json = dict[str, Any]  # JSON we only pass through (Bitwarden items, vault profiles)
    +Keys = tuple[bytes, bytes]  # (encryption key, MAC key)
    +
    +
    +# 1Password: shapes shared by OPVault and 1PIF (all keys optional in the wild).
    +class OverviewUrl(TypedDict, total=False):
    +    u: Optional[str]
    +
    +
    +class Overview(TypedDict, total=False):
    +    title: str
    +    url: Optional[str]
    +    URLs: list[OverviewUrl]
    +    ainfo: Optional[str]
    +
    +
    +class DetailField(TypedDict, total=False):
    +    designation: str
    +    value: Any
    +
    +
    +class SectionField(TypedDict, total=False):
    +    k: str  # kind: string, concealed, totp, date, ...
    +    n: str
    +    t: str
    +    v: Any
    +
    +
    +class Section(TypedDict, total=False):
    +    title: str
    +    fields: list[SectionField]
    +
    +
    +class PifUrl(TypedDict, total=False):
    +    url: str
    +
    +
    +class Details(TypedDict, total=False):
    +    fields: list[DetailField]
    +    sections: list[Section]
    +    notesPlain: str
    +    URLs: list[PifUrl]
    +
    +
    +class OpItem(TypedDict, total=False):
    +    """An OPVault band item; o, d and k are encrypted."""
    +
    +    category: str
    +    trashed: bool
    +    o: str
    +    d: str
    +    k: str
    +
    +
    +class Entry(TypedDict, total=False):
    +    overview: Overview
    +    item: OpItem  # OPVault: details are decrypted on demand
    +    details: Details  # 1PIF: details are already plain
    +
    +
    +class Source(Protocol):
    +    def logins(self) -> list[Entry]: ...
    +
    +    def details(self, entry: Entry) -> Details: ...

    CodeQL / Statement has no effect

    This statement has no effect.

    Show more details

    github-advanced-security[bot] github-advanced-security[bot] commented on code on Oct 08, 2026 17:18 UTC
    Code Review
    bin/op-to-bw:1
    @@ -0,0 +1,533 @@
    +#!/usr/bin/env python3
    +"""Usage: op-to-bw [--vault PATH] [--dry-run] QUERY
    +
    +Copies a Login from 1Password 7 to Bitwarden (Vaultwarden), creating it or
    +updating an existing entry of the same name.
    +
    +QUERY is matched case-insensitively against Login names and URLs. The source
    +is PATH or $OPVAULT: either an .opvault vault file (prompts for the master
    +password; $OPVAULT_PASSWORD skips the prompt) or a 1Password 7 .1pif export
    +(File > Export > 1PIF; unencrypted, so delete it afterwards).
    +
    +Requires: `brew install bitwarden-cli`.
    +Bitwarden must already point at your server (`bw config server URL`) and be
    +logged in (`bw login`); unlocking is prompted for.
    +
    +Type-check with: mypy --strict --scripts-are-modules bin/op-to-bw
    +"""
    +from __future__ import annotations
    +
    +import argparse
    +import base64
    +import datetime
    +import getpass
    +import hashlib
    +import hmac
    +import json
    +import os
    +import pathlib
    +import shutil
    +import struct
    +import subprocess
    +import sys
    +from typing import Any, NoReturn, Optional, Protocol, TypedDict
    +
    +BW_TEXT, BW_HIDDEN = 0, 1
    +
    +Json = dict[str, Any]  # JSON we only pass through (Bitwarden items, vault profiles)
    +Keys = tuple[bytes, bytes]  # (encryption key, MAC key)
    +
    +
    +# 1Password: shapes shared by OPVault and 1PIF (all keys optional in the wild).
    +class OverviewUrl(TypedDict, total=False):
    +    u: Optional[str]
    +
    +
    +class Overview(TypedDict, total=False):
    +    title: str
    +    url: Optional[str]
    +    URLs: list[OverviewUrl]
    +    ainfo: Optional[str]
    +
    +
    +class DetailField(TypedDict, total=False):
    +    designation: str
    +    value: Any
    +
    +
    +class SectionField(TypedDict, total=False):
    +    k: str  # kind: string, concealed, totp, date, ...
    +    n: str
    +    t: str
    +    v: Any
    +
    +
    +class Section(TypedDict, total=False):
    +    title: str
    +    fields: list[SectionField]
    +
    +
    +class PifUrl(TypedDict, total=False):
    +    url: str
    +
    +
    +class Details(TypedDict, total=False):
    +    fields: list[DetailField]
    +    sections: list[Section]
    +    notesPlain: str
    +    URLs: list[PifUrl]
    +
    +
    +class OpItem(TypedDict, total=False):
    +    """An OPVault band item; o, d and k are encrypted."""
    +
    +    category: str
    +    trashed: bool
    +    o: str
    +    d: str
    +    k: str
    +
    +
    +class Entry(TypedDict, total=False):
    +    overview: Overview
    +    item: OpItem  # OPVault: details are decrypted on demand
    +    details: Details  # 1PIF: details are already plain
    +
    +
    +class Source(Protocol):
    +    def logins(self) -> list[Entry]: ...
    +
    +    def details(self, entry: Entry) -> Details: ...
    +
    +
    +# Bitwarden: what we build. Existing items from `bw` stay as Json.
    +class BwUri(TypedDict):
    +    match: Optional[int]
    +    uri: str
    +
    +
    +class BwLogin(TypedDict):
    +    username: Optional[str]
    +    password: Optional[str]
    +    totp: Optional[str]
    +    uris: list[BwUri]
    +
    +
    +class BwField(TypedDict):
    +    name: str
    +    value: str
    +    type: int
    +
    +
    +def die(msg: str) -> NoReturn:
    +    sys.exit(f"error: {msg}")
    +
    +
    +def run(cmd: list[str], stdin: Optional[str] = None, interactive: bool = False) -> str:
    +    """Runs cmd, returns stdout. Interactive keeps the tty for prompts."""
    +    try:
    +        p = subprocess.run(
    +            cmd,
    +            input=stdin,
    +            text=True,
    +            stdout=subprocess.PIPE,
    +            stderr=None if interactive else subprocess.PIPE,
    +        )
    +    except FileNotFoundError:
    +        die(f"`{cmd[0]}` not found; install it with Homebrew")
    +    if p.returncode != 0:
    +        die(f"`{' '.join(cmd[:3])}` failed: {(p.stderr or '').strip()}")
    +    return p.stdout
    +
    +
    +def run_json(cmd: list[str]) -> Any:
    +    return json.loads(run(cmd))
    +
    +
    +# 1Password (OPVault)
    +
    +
    +class BadMAC(Exception):
    +    pass
    +
    +
    +def _aes_tables() -> tuple[list[int], list[int], list[int], list[int], list[int], list[int]]:
    +    exp, log, x = [0] * 255, [0] * 256, 1
    +    for i in range(255):
    +        exp[i], log[x] = x, i
    +        x ^= ((x << 1) ^ (0x1B if x & 0x80 else 0)) & 0xFF  # x *= 3
    +
    +    def rotl(v: int, n: int) -> int:
    +        return ((v << n) | (v >> (8 - n))) & 0xFF
    +
    +    sbox = [0x63] * 256
    +    for i in range(1, 256):
    +        v = exp[(255 - log[i]) % 255]
    +        sbox[i] = v ^ rotl(v, 1) ^ rotl(v, 2) ^ rotl(v, 3) ^ rotl(v, 4) ^ 0x63
    +    inv = [0] * 256
    +    for i, v in enumerate(sbox):
    +        inv[v] = i
    +
    +    def mul(a: int, b: int) -> int:
    +        return exp[(log[a] + log[b]) % 255] if a and b else 0
    +
    +    td0 = [
    +        mul(v, 14) << 24 | mul(v, 9) << 16 | mul(v, 13) << 8 | mul(v, 11)
    +        for v in inv
    +    ]
    +
    +    def ror8(w: int) -> int:
    +        return (w >> 8) | ((w & 0xFF) << 24)
    +
    +    td1 = [ror8(w) for w in td0]
    +    td2 = [ror8(w) for w in td1]
    +    td3 = [ror8(w) for w in td2]
    +    return sbox, inv, td0, td1, td2, td3
    +
    +
    +SBOX, ISBOX, TD0, TD1, TD2, TD3 = _aes_tables()
    +
    +
    +def _aes256_decrypt_keys(key: bytes) -> list[int]:
    +    """Expands a 32-byte key into round keys for the equivalent inverse cipher."""
    +    w = list(struct.unpack(">8I", key))
    +    rcon = 1
    +    for i in range(8, 60):
    +        t = w[i - 1]
    +        if i % 8 == 0:
    +            t = (t << 8 | t >> 24) & 0xFFFFFFFF
    +            t = sum(SBOX[(t >> s) & 0xFF] << s for s in (24, 16, 8, 0)) ^ (rcon << 24)
    +            rcon = ((rcon << 1) ^ (0x1B if rcon & 0x80 else 0)) & 0xFF
    +        elif i % 8 == 4:
    +            t = sum(SBOX[(t >> s) & 0xFF] << s for s in (24, 16, 8, 0))
    +        w.append(w[i - 8] ^ t)
    +    dk = []
    +    for r in range(14, -1, -1):
    +        words = w[4 * r : 4 * r + 4]
    +        if 0 < r < 14:  # InvMixColumns
    +            words = [
    +                TD0[SBOX[x >> 24]] ^ TD1[SBOX[(x >> 16) & 0xFF]] ^ TD2[SBOX[(x >> 8) & 0xFF]] ^ TD3[SBOX[x & 0xFF]]
    +                for x in words
    +            ]
    +        dk += words
    +    return dk
    +
    +
    +def _aes_decrypt_block(dk: list[int], block: bytes) -> bytes:
    +    s0, s1, s2, s3 = (a ^ b for a, b in zip(struct.unpack(">4I", block), dk))
    +    for r in range(4, 56, 4):
    +        s0, s1, s2, s3 = (
    +            TD0[s0 >> 24] ^ TD1[(s3 >> 16) & 255] ^ TD2[(s2 >> 8) & 255] ^ TD3[s1 & 255] ^ dk[r],
    +            TD0[s1 >> 24] ^ TD1[(s0 >> 16) & 255] ^ TD2[(s3 >> 8) & 255] ^ TD3[s2 & 255] ^ dk[r + 1],
    +            TD0[s2 >> 24] ^ TD1[(s1 >> 16) & 255] ^ TD2[(s0 >> 8) & 255] ^ TD3[s3 & 255] ^ dk[r + 2],
    +            TD0[s3 >> 24] ^ TD1[(s2 >> 16) & 255] ^ TD2[(s1 >> 8) & 255] ^ TD3[s0 & 255] ^ dk[r + 3],
    +        )
    +    return struct.pack(
    +        ">4I",
    +        (ISBOX[s0 >> 24] << 24 | ISBOX[(s3 >> 16) & 255] << 16 | ISBOX[(s2 >> 8) & 255] << 8 | ISBOX[s1 & 255]) ^ dk[56],
    +        (ISBOX[s1 >> 24] << 24 | ISBOX[(s0 >> 16) & 255] << 16 | ISBOX[(s3 >> 8) & 255] << 8 | ISBOX[s2 & 255]) ^ dk[57],
    +        (ISBOX[s2 >> 24] << 24 | ISBOX[(s1 >> 16) & 255] << 16 | ISBOX[(s0 >> 8) & 255] << 8 | ISBOX[s3 & 255]) ^ dk[58],
    +        (ISBOX[s3 >> 24] << 24 | ISBOX[(s2 >> 16) & 255] << 16 | ISBOX[(s1 >> 8) & 255] << 8 | ISBOX[s0 & 255]) ^ dk[59],
    +    )
    +
    +
    +def cbc_decrypt(key: bytes, jobs: list[tuple[bytes, bytes]]) -> list[bytes]:
    +    """AES-256-CBC-decrypts [(iv, ciphertext)]. Pure Python, so keys never hit argv."""
    +    dk = _aes256_decrypt_keys(key)
    +    out = []
    +    for iv, ct in jobs:
    +        prev, plain = iv, []
    +        for i in range(0, len(ct), 16):
    +            block = ct[i : i + 16]
    +            d = _aes_decrypt_block(dk, block)
    +            plain.append((int.from_bytes(d, "big") ^ int.from_bytes(prev, "big")).to_bytes(16, "big"))
    +            prev = block
    +        out.append(b"".join(plain))
    +    return out
    +
    +
    +def opdata_decrypt(blobs: list[bytes], enc: bytes, mac: bytes) -> list[bytes]:
    +    """Decrypts "opdata01" blobs (raw or base64): header, length, IV, data, HMAC."""
    +    jobs: list[tuple[bytes, bytes]] = []
    +    sizes: list[int] = []
    +    for blob in blobs:
    +        raw = blob if blob.startswith(b"opdata01") else base64.b64decode(blob)
    +        if not hmac.compare_digest(hmac.digest(mac, raw[:-32], "sha256"), raw[-32:]):
    +            raise BadMAC
    +        jobs.append((raw[16:32], raw[32:-32]))
    +        sizes.append(int.from_bytes(raw[8:16], "little"))
    +    # Plaintext is prefixed with random padding.
    +    return [p[len(p) - n :] for p, n in zip(cbc_decrypt(enc, jobs), sizes)]
    +
    +
    +def split_keys(material: bytes) -> Keys:
    +    return material[:32], material[32:]
    +
    +
    +def read_js(path: pathlib.Path) -> Json:
    +    """Reads the JSON object out of `var x={...};` / `ld({...});` files."""
    +    text = path.read_text(encoding="utf-8")
    +    data: Json = json.loads(text[text.index("{") : text.rindex("}") + 1])
    +    return data
    +
    +
    +def open_source(arg: Optional[str]) -> Source:

    CodeQL / Explicit returns mixed with implicit (fall through) returns

    Mixing implicit and explicit returns may indicate an error, as implicit returns always return None.

    Show more details

    Reviewers
    Assignees
    memk memk
    Labels
    risk: low confidence: 85.7% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 42.1% (MEDIUM) · Higher = larger blast radius
    42.1%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 85.7% · Lower = rushed or shallow review
    85.7%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6% · Safe to merge
    6%
    Repository