#!/usr/bin/env python3
"""aci_verify – công cụ kiểm chứng ĐỘC LẬP gói bằng chứng của ACI-OS, không cần truy cập ACI-OS và không cần tin ACI-OS.

    python aci_verify.py ART-2026-0001-bang-chung.zip --anchor <dấu vân tay neo tin cậy>
    python aci_verify.py ART-2026-0001-bang-chung.zip --anchor-file anchor.json             # neo, khóa neo gốc, danh sách thu hồi
    python aci_verify.py ART-2026-0001-bang-chung.zip --anchor <…> --engine openssl          # chỉ dùng dòng lệnh OpenSSL ≥ 3.5
    python aci_verify.py ART-2026-0100-bang-chung.zip --anchor-file anchor.json --pl-roots goc.pem   # hồ sơ LAI: kiểm chữ ký pháp lý

Chỉ cần Python 3.10+ (thư viện chuẩn) và dòng lệnh OpenSSL ≥ 3.5; thư viện cryptography ≥ 50 là tùy chọn (--engine cryptography).
Kiểm 10 bước: danh tính, khóa công khai (và trạng thái khóa TẠI THỜI ĐIỂM KÝ theo vòng đời khóa, danh sách thu hồi), chứng thư ủy quyền,
thẩm quyền theo thời gian, quyền, bản ghi hành động, băm hiện vật, chữ ký ML-DSA (FIPS 204) trên manifest, cấu trúc manifest (1.0 KT,
1.1 LAI), chuỗi kiểm toán; hồ sơ LAI thêm bước 11 – chữ ký pháp lý PAdES qua «openssl cms -verify» với kho chứng thư gốc --pl-roots
(không có → INDETERMINATE). Kết quả: VALID / INVALID / INDETERMINATE.
anchor.json tải từ /api/v1/trust/anchor (neo đang dùng, đã xoay vòng, đã thu hồi; khóa neo gốc SLH-DSA và chứng nhận; danh sách thu hồi) –
nên đối chiếu dấu vân tay với kênh công bố độc lập của Nhà trường. Mã nguồn sao từ backend/aci/trust/verifier.py. Bản công bố kèm SHA-256 và
hướng dẫn kiểm tay bằng OpenSSL: <cổng thông tin của Nhà trường>/xac-minh-ngoai-tuyen. Giấy phép phân phối lại: chờ Nhà trường quyết định.
1.10.0 – mức định danh người ký (LIMITED/PUBLISHED/CERTIFIED/LEGALLY-BOUND, tách khỏi kết quả mật mã): --domain <tên miền chính thức bạn
biết> (tải /.well-known/aci-trust.json qua HTTPS, tra DNS TXT _aci-trust.<tên miền>), --anchor/--pin-file/--qr (bản ghi ghim, mã QR trên văn bản
giấy), --key-statement <tuyên bố khóa đã ký pháp lý.pdf> --pl-roots; vòng đời khóa: --revocation-list (danh sách thu hồi có chữ ký),
--tsa-roots (kiểm dấu thời gian RFC 3161 khi khóa bị thu hồi vì lộ), --checkpoints (điểm chốt đã công bố); manifest 1.2 – chữ ký phê duyệt riêng
của người duyệt (bước 3, 5, 6).
1.10.0 – luồng E (kiểm chứng độc lập, fail-closed): --engine noble (noble-post-quantum qua Node, khác nguồn gốc OpenSSL; tệp
noble-post-quantum-0.7.1.js đặt cạnh công cụ hoặc --noble-bundle, mã băm được ghim), --cross cryptography,noble (chạy CÙNG gói với nhiều bộ máy),
--witness-store <thư mục kho của tools/aci_witness.py> (thời điểm nhân chứng thấy điểm chốt → chứng minh thời điểm qua bằng chứng bao hàm Merkle),
--require-hybrid (bắt buộc chữ ký đồng hành cổ điển), --companion-pin. Gói hỏng/giả → INVALID có lý do (không văng lỗi); thiếu bộ máy → INDETERMINATE.
"""
from __future__ import annotations

import base64
import hashlib
import json
import os
import re
import shutil
import subprocess
import tempfile
from datetime import datetime, timezone

VERIFIER_VERSION = "1.2"                # 1.10.0: mức định danh, chữ ký phê duyệt riêng (manifest 1.2), quy tắc khóa bị lộ
STEPS = ["Agent Identity", "Public Key", "Delegation", "Authority", "Permission", "Action", "Document Hash",
         "PQC Signature", "Manifest", "Audit Chain", "Legal Signature"]
GENESIS = "0" * 64
CONTEXT = b"ACI-OS/trust/v1"
_OID = {"ML-DSA-44": "2.16.840.1.101.3.4.3.17", "ML-DSA-65": "2.16.840.1.101.3.4.3.18", "ML-DSA-87": "2.16.840.1.101.3.4.3.19",
        "SLH-DSA-SHA2-128s": "2.16.840.1.101.3.4.3.20", "SLH-DSA-SHA2-192s": "2.16.840.1.101.3.4.3.22"}
_ROOT_ALGS = tuple(a for a in _OID if a.startswith("SLH-"))          # khóa neo gốc (FIPS 205)
MANIFEST_VERSIONS = ("1.0", "1.1", "1.2")
BUNDLE_VERSIONS = ("1.0", "1.1", "1.2")
SIGNING_ENGINE_ORIGIN = "OpenSSL"
SCOPE_KT = ("Chữ ký kỹ thuật hậu lượng tử của hệ thống ACI-OS: chứng minh nguồn gốc và tính toàn vẹn của hiện vật – không phải chữ ký số có giá "
            "trị pháp lý theo Luật Giao dịch điện tử")
SCOPE_LAI = ("Hồ sơ ký lai (LAI): chữ ký số pháp lý của người có thẩm quyền theo chứng thư số của tổ chức cung cấp dịch vụ chứng thực, kèm chữ ký "
             "kỹ thuật hậu lượng tử của hệ thống ACI-OS trên cùng mã băm nội dung; hợp lệ đầy đủ chỉ khi cả hai chữ ký hợp lệ. Chữ ký kỹ thuật "
             "không thay chữ ký pháp lý")
_DIGESTS = {"2.16.840.1.101.3.4.2.1": "sha256", "2.16.840.1.101.3.4.2.2": "sha384", "2.16.840.1.101.3.4.2.3": "sha512",
            "1.3.14.3.2.26": "sha1"}


def _canonical(obj) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, default=str).encode("utf-8")


def _sha(b: bytes) -> str:
    return hashlib.sha256(b).hexdigest()


# ---------------------------------------------------------------- bộ máy xác minh ML-DSA, SLH-DSA
def _der_len(n: int) -> bytes:
    if n < 0x80:
        return bytes([n])
    b = n.to_bytes((n.bit_length() + 7) // 8, "big")
    return bytes([0x80 | len(b)]) + b


def spki_pem(alg: str, pk: bytes) -> bytes:
    """Khóa công khai ML-DSA/SLH-DSA thô → PEM SubjectPublicKeyInfo (OID của NIST) cho dòng lệnh OpenSSL."""
    p = [int(x) for x in _OID[alg].split(".")]
    body = bytes([40 * p[0] + p[1]])
    for v in p[2:]:
        enc = [v & 0x7F]
        v >>= 7
        while v:
            enc.append(0x80 | (v & 0x7F))
            v >>= 7
        body += bytes(reversed(enc))
    oid = b"\x06" + _der_len(len(body)) + body
    algid = b"\x30" + _der_len(len(oid)) + oid
    bits = b"\x03" + _der_len(len(pk) + 1) + b"\x00" + pk
    der = b"\x30" + _der_len(len(algid) + len(bits)) + algid + bits
    b64 = base64.b64encode(der).decode()
    lines = [b64[i:i + 64] for i in range(0, len(b64), 64)]
    return ("-----BEGIN PUBLIC KEY-----\n" + "\n".join(lines) + "\n-----END PUBLIC KEY-----\n").encode()


def _mldsa_cryptography():
    try:
        from cryptography.hazmat.primitives.asymmetric import mldsa
    except ImportError:
        return None
    return {"ML-DSA-44": mldsa.MLDSA44PublicKey, "ML-DSA-65": mldsa.MLDSA65PublicKey, "ML-DSA-87": mldsa.MLDSA87PublicKey}


def resolve_engine(engine: str = "auto") -> str:
    if engine == "auto":
        return "cryptography" if _mldsa_cryptography() else "openssl"
    if engine not in ("cryptography", "openssl", "noble"):          # 1.10.0 – luồng E: thêm «noble» (noble-post-quantum qua Node, khác nguồn gốc)
        raise ValueError(f"Bộ máy xác minh không hỗ trợ: {engine}")
    return engine


def _openssl() -> str | None:
    return os.environ.get("ACI_OPENSSL") or shutil.which("openssl")


def engine_info(engine: str = "auto") -> str:
    if resolve_engine(engine) == "noble":
        return noble_info()
    if resolve_engine(engine) == "cryptography":
        import cryptography
        from cryptography.hazmat.backends.openssl import backend
        return f"cryptography {cryptography.__version__} / {backend.openssl_version_text()}"
    exe = _openssl()
    if not exe:
        return "dòng lệnh OpenSSL (không tìm thấy trên máy)"
    return "dòng lệnh " + subprocess.run([exe, "version"], capture_output=True, text=True).stdout.strip()


def _openssl_run(args: list[str], files: dict[str, bytes]) -> tuple[int, bytes]:
    exe = _openssl()
    if not exe:
        raise RuntimeError("Không tìm thấy OpenSSL ≥ 3.5 trên máy")
    with tempfile.TemporaryDirectory() as d:
        paths = {}
        for name, data in files.items():
            paths[name] = os.path.join(d, name)
            with open(paths[name], "wb") as f:
                f.write(data)
        r = subprocess.run([exe] + [paths.get(a, a) for a in args], capture_output=True)
        return r.returncode, r.stdout + r.stderr


def _openssl_verify(alg: str, pk: bytes, msg: bytes, sig: bytes) -> bool:
    code, out = _openssl_run(["pkeyutl", "-verify", "-pubin", "-inkey", "pub.pem", "-rawin", "-in", "msg.bin", "-sigfile", "sig.bin",
                              "-pkeyopt", "context-string:" + CONTEXT.decode()],
                             {"pub.pem": spki_pem(alg, pk), "msg.bin": msg, "sig.bin": sig})
    if b"unsupported" in out.lower() and alg in _ROOT_ALGS:
        raise RuntimeError("OpenSSL trên máy chưa hỗ trợ SLH-DSA (cần ≥ 3.5)")
    return code == 0 and b"Signature Verified Successfully" in out


def _verify_sig(alg: str, pk: bytes, msg: bytes, sig: bytes, engine: str = "auto") -> bool:
    try:
        if alg in _CLASSICAL_OID:                                       # Ed25519, ECDSA-P256: cryptography nếu có, không thì dòng lệnh OpenSSL
            return _classical_verify(alg, pk, msg, sig)
        if alg not in _OID:
            return False
        if alg in _ROOT_ALGS or resolve_engine(engine) == "openssl":   # SLH-DSA (khóa neo gốc): dòng lệnh OpenSSL ≥ 3.5
            return _openssl_verify(alg, pk, msg, sig)
        if resolve_engine(engine) == "noble":                           # 1.10.0 – luồng E: noble-post-quantum (khác nguồn gốc OpenSSL)
            return _noble_verify(alg, pk, msg, sig)
        _mldsa_cryptography()[alg].from_public_bytes(pk).verify(sig, msg, CONTEXT)
        return True
    except RuntimeError:
        raise                                            # thiếu công cụ xác minh – không được báo nhầm là "chữ ký sai"
    except Exception:  # noqa: BLE001 – chữ ký hỏng/giả là "không hợp lệ", không phải lỗi hệ thống
        return False


def _ts(s) -> datetime | None:
    if isinstance(s, datetime):
        return s if s.tzinfo else s.replace(tzinfo=timezone.utc)
    try:
        t = datetime.fromisoformat(s) if s else None
    except (ValueError, TypeError):
        return None
    return t.replace(tzinfo=timezone.utc) if t and t.tzinfo is None else t


def _floor(t: datetime | None) -> datetime | None:
    return t.replace(microsecond=0) if t else None


def _b64(s) -> bytes:
    """Base64 chuẩn, NGHIÊM NGẶT (1.10.0 – luồng E): ký tự ngoài bảng mã, thiếu/thừa đệm, dạng không chuẩn → rỗng (bên gọi kết luận không hợp lệ)."""
    if not s or not isinstance(s, str):
        return b""
    try:
        out = base64.b64decode(s, validate=True)
    except (ValueError, TypeError):
        return b""
    return out if base64.b64encode(out).decode("ascii") == s else b""


# ---------------------------------------------------------------- ASN.1 DER tối giản (thư viện chuẩn) – CMS, TSTInfo, chứng thư
def der_read(buf: bytes, pos: int = 0) -> tuple[int, int, int]:
    """(thẻ, vị trí đầu nội dung, vị trí cuối) của phần tử DER tại pos."""
    tag = buf[pos]
    ln = buf[pos + 1]
    p = pos + 2
    if ln & 0x80:
        n = ln & 0x7F
        if n == 0 or n > 4:
            raise ValueError("Độ dài DER không hỗ trợ")
        ln = int.from_bytes(buf[p:p + n], "big")
        p += n
    if p + ln > len(buf):
        raise ValueError("DER bị cắt cụt")
    return tag, p, p + ln


def der_children(buf: bytes, start: int, end: int) -> list[tuple[int, int, int, int]]:
    """Các phần tử con (thẻ, đầu phần tử, đầu nội dung, cuối) trong [start, end)."""
    out, p = [], start
    while p < end:
        tag, s, e = der_read(buf, p)
        out.append((tag, p, s, e))
        p = e
    return out


def der_oid(body: bytes) -> str:
    vals, v = [], 0
    for b in body:
        v = (v << 7) | (b & 0x7F)
        if not b & 0x80:
            vals.append(v)
            v = 0
    first = 0 if vals[0] < 40 else (1 if vals[0] < 80 else 2)
    return ".".join(str(x) for x in [first, vals[0] - 40 * first] + vals[1:])


def der_time(tag: int, body: bytes) -> datetime | None:
    s = body.decode("ascii", "replace")
    try:
        if tag == 0x17:                               # UTCTime YYMMDDHHMMSSZ
            t = datetime.strptime(s, "%y%m%d%H%M%SZ")
        else:                                         # GeneralizedTime YYYYMMDDHHMMSS[.fff]Z
            t = datetime.strptime(s.split(".")[0].rstrip("Z"), "%Y%m%d%H%M%S")
    except ValueError:
        return None
    return t.replace(tzinfo=timezone.utc)


_ATTR = {"1.2.840.113549.1.9.3": "content_type", "1.2.840.113549.1.9.4": "message_digest", "1.2.840.113549.1.9.5": "signing_time",
         "1.2.840.113549.1.9.16.2.14": "signature_timestamp"}


def cms_parse(der: bytes) -> dict:
    """CMS ContentInfo → SignedData: kiểu nội dung bọc, nội dung bọc (nếu có), chứng thư (DER), người ký đầu tiên (sid, băm, signedAttrs ở
    dạng SET để kiểm chữ ký, thuộc tính messageDigest/signingTime/contentType, thuật toán chữ ký, giá trị chữ ký, thuộc tính không ký)."""
    tag, s, e = der_read(der, 0)
    ci = der_children(der, s, e)
    if der_oid(der[ci[0][2]:ci[0][3]]) != "1.2.840.113549.1.7.2":
        raise ValueError("Không phải CMS SignedData")
    _, s2, e2 = der_read(der, ci[1][2])                         # [0] EXPLICIT → SignedData SEQUENCE
    sd = der_children(der, s2, e2)
    i = 2                                                        # version, digestAlgorithms, encapContentInfo
    enc = der_children(der, sd[i][2], sd[i][3])
    econtent_type = der_oid(der[enc[0][2]:enc[0][3]])
    econtent = None
    if len(enc) > 1:
        _, os_, oe = der_read(der, enc[1][2])                   # [0] EXPLICIT OCTET STRING
        econtent = der[os_:oe]
    i += 1
    certs: list[bytes] = []
    if i < len(sd) and sd[i][0] == 0xA0:
        certs = [der[c[1]:c[3]] for c in der_children(der, sd[i][2], sd[i][3]) if c[0] == 0x30]
        i += 1
    if i < len(sd) and sd[i][0] == 0xA1:                         # crls
        i += 1
    signers = der_children(der, sd[i][2], sd[i][3])
    si = der_children(der, signers[0][2], signers[0][3])
    sid_tag, sid_start, sid_s, sid_e = si[1]
    sid = {"issuer_serial": der[sid_start:sid_e]} if sid_tag == 0x30 else {"ski": der[sid_s:sid_e]}
    if sid_tag == 0x30:
        isn = der_children(der, sid_s, sid_e)
        sid["issuer_der"] = der[isn[0][1]:isn[0][3]]
        sid["serial"] = int.from_bytes(der[isn[1][2]:isn[1][3]], "big")
    digest_oid = der_oid(der[der_children(der, si[2][2], si[2][3])[0][2]:der_children(der, si[2][2], si[2][3])[0][3]])
    j = 3
    attrs, signed_attrs = {}, None
    if si[j][0] == 0xA0:
        raw = der[si[j][1]:si[j][3]]
        signed_attrs = b"\x31" + raw[1:]                         # [0] IMPLICIT → SET OF khi kiểm chữ ký (RFC 5652 mục 5.4)
        for a in der_children(der, si[j][2], si[j][3]):
            parts = der_children(der, a[2], a[3])
            name = _ATTR.get(der_oid(der[parts[0][2]:parts[0][3]]))
            vals = der_children(der, parts[1][2], parts[1][3])
            if name and vals:
                vt, vs, ve = vals[0][0], vals[0][2], vals[0][3]
                attrs[name] = der_time(vt, der[vs:ve]) if name == "signing_time" else (
                    der_oid(der[vs:ve]) if name == "content_type" else der[vs:ve])
        j += 1
    sig_alg = der_oid(der[der_children(der, si[j][2], si[j][3])[0][2]:der_children(der, si[j][2], si[j][3])[0][3]])
    signature = der[si[j + 1][2]:si[j + 1][3]]
    unsigned = {}
    if len(si) > j + 2 and si[j + 2][0] == 0xA1:
        for a in der_children(der, si[j + 2][2], si[j + 2][3]):
            parts = der_children(der, a[2], a[3])
            name = _ATTR.get(der_oid(der[parts[0][2]:parts[0][3]]))
            vals = der_children(der, parts[1][2], parts[1][3])
            if name and vals:
                unsigned[name] = der[vals[0][1]:vals[0][3]]
    return {"econtent_type": econtent_type, "econtent": econtent, "certificates": certs, "sid": sid, "digest_oid": digest_oid,
            "signed_attrs": signed_attrs, "attrs": attrs, "signature_algorithm": sig_alg, "signature": signature, "unsigned": unsigned}


def cert_brief(der: bytes) -> dict:
    """Từ chứng thư DER: số hiệu, tên người cấp (DER), thời hạn, tên chủ thể (CN nếu đọc được) – không kiểm chữ ký."""
    _, s, e = der_read(der, 0)
    tbs = der_children(der, *der_read(der, der_children(der, s, e)[0][1])[1:])
    k = 1 if tbs[0][0] == 0xA0 else 0
    serial = int.from_bytes(der[tbs[k][2]:tbs[k][3]], "big")
    issuer = der[tbs[k + 2][1]:tbs[k + 2][3]]
    validity = der_children(der, tbs[k + 3][2], tbs[k + 3][3])
    nb = der_time(validity[0][0], der[validity[0][2]:validity[0][3]])
    na = der_time(validity[1][0], der[validity[1][2]:validity[1][3]])
    subj = der[tbs[k + 4][1]:tbs[k + 4][3]]
    cn = None
    m = re.search(rb"\x06\x03\x55\x04\x03[\x0c\x13\x14\x16\x1e](.)", subj, re.S)
    if m:
        p = m.end(1)
        cn = subj[p:p + m.group(1)[0]].decode("utf-8", "replace")
    return {"serial": serial, "serial_hex": format(serial, "x"), "issuer_der": issuer, "subject_der": subj, "not_before": nb,
            "not_after": na, "common_name": cn, "fingerprint": _sha(der)}


def pdf_signatures(data: bytes) -> list[dict]:
    """Các chữ ký trong PDF (/ByteRange [a b c d], /Contents <hex>): phần được ký = data[a:a+b] + data[c:c+d], CMS = DER đã cắt phần đệm."""
    out = []
    for m in re.finditer(rb"/ByteRange\s*\[\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s*\]", data):
        a, b, c, d = (int(x) for x in m.groups())
        if a != 0 or a + b > c or c + d > len(data):
            continue
        hexpart = data[a + b:c].strip()
        if hexpart.startswith(b"<") and hexpart.endswith(b">"):
            hexpart = hexpart[1:-1]
        try:
            raw = bytes.fromhex(re.sub(rb"\s", b"", hexpart).decode("ascii"))
            _, _, end = der_read(raw, 0)
        except (ValueError, IndexError):
            continue
        out.append({"byte_range": [a, b, c, d], "cms": raw[:end], "signed": data[a:a + b] + data[c:c + d],
                    "covers_whole_file": c + d == len(data)})
    return out


def _pl_openssl(cms_der: bytes, signed: bytes, roots_pem: bytes, at: datetime | None) -> tuple[bool | None, str]:
    """Kiểm chữ ký PL bằng «openssl cms -verify» (chữ ký trên signedAttrs, messageDigest, chuỗi chứng thư tới kho gốc, hạn chứng thư tại thời
    điểm ký). Trả (True | False | None = không chạy được), chi tiết."""
    args = ["cms", "-verify", "-binary", "-inform", "DER", "-in", "sig.der", "-content", "data.bin", "-CAfile", "roots.pem",
            "-purpose", "any", "-out", os.devnull]
    if at:
        args += ["-attime", str(int(at.timestamp()))]
    try:
        code, out = _openssl_run(args, {"sig.der": cms_der, "data.bin": signed, "roots.pem": roots_pem})
    except RuntimeError as e:
        return None, str(e)
    text = out.decode("utf-8", "replace").strip().splitlines()
    return code == 0, (text[-1] if text else "")[:300]


def legal_check_offline(content: bytes, roots_pem: bytes | None, expected: dict | None = None) -> dict:
    """Bước 11 (hồ sơ LAI) ngoại tuyến: chữ ký PAdES trong tệp hiện vật (hoặc CMS tách rời mô tả trong legal_signature).
    Kết quả: valid | invalid | indeterminate (không có kho chứng thư gốc, không có OpenSSL, định dạng chưa hỗ trợ)."""
    expected = expected or {}
    sigs = pdf_signatures(content) if content.startswith(b"%PDF") else []
    if not sigs:
        return {"result": "invalid", "detail": "Không tìm thấy chữ ký PAdES trong tệp hiện vật"}
    sig = sigs[-1]
    try:
        cms = cms_parse(sig["cms"])
    except (ValueError, IndexError) as e:
        return {"result": "invalid", "detail": f"Không đọc được CMS: {e}"}
    name = _DIGESTS.get(cms["digest_oid"])
    if not name:
        return {"result": "indeterminate", "detail": f"Thuật toán băm {cms['digest_oid']} chưa hỗ trợ"}
    if name == "sha1":
        return {"result": "invalid", "detail": "Chữ ký PL dùng SHA-1 – thuật toán bị cấm (danh mục mật mã)"}
    md_ok = cms["attrs"].get("message_digest") == hashlib.new(name, sig["signed"]).digest()
    if not md_ok:
        return {"result": "invalid", "detail": "Băm vùng ký (ByteRange) không khớp messageDigest"}
    if not sig["covers_whole_file"]:
        return {"result": "invalid", "detail": "Chữ ký pháp lý không bao toàn bộ tệp (có nội dung nối thêm sau khi ký)"}
    signer = None
    for c in cms["certificates"]:
        try:
            cb = cert_brief(c)
        except (ValueError, IndexError):
            continue
        if cms["sid"].get("serial") is not None and cb["serial"] == cms["sid"]["serial"] and cb["issuer_der"] == cms["sid"].get("issuer_der"):
            signer = cb
    if expected.get("signer_serial") and signer and signer["serial_hex"] != expected["signer_serial"]:
        return {"result": "invalid", "detail": "Chứng thư người ký trong tệp khác chứng thư ghi trong manifest đã ký KT"}
    at = cms["attrs"].get("signing_time") or _ts(expected.get("signing_time"))
    if not roots_pem:
        return {"result": "indeterminate", "detail": "Chưa có kho chứng thư gốc (--pl-roots) – không kết luận chữ ký pháp lý",
                "message_digest": "khớp", "signer": (signer or {}).get("common_name")}
    ok, why = _pl_openssl(sig["cms"], sig["signed"], roots_pem, at)
    if ok is None:
        return {"result": "indeterminate", "detail": why}
    return {"result": "valid" if ok else "invalid", "detail": ("openssl cms -verify: " + why) if why else "openssl cms -verify",
            "message_digest": "khớp", "signer": (signer or {}).get("common_name"), "signing_time": at.isoformat() if at else None,
            "covers_whole_file": sig["covers_whole_file"]}


def tst_info(token_der: bytes) -> dict:
    """TimeStampToken (RFC 3161) → TSTInfo: chính sách, thuật toán băm và giá trị message imprint, số hiệu, thời điểm (genTime), nonce."""
    cms = cms_parse(token_der)
    if cms["econtent_type"] != "1.2.840.113549.1.9.16.1.4" or not cms["econtent"]:
        raise ValueError("Không phải dấu thời gian RFC 3161 (TSTInfo)")
    t = cms["econtent"]
    _, s, e = der_read(t, 0)
    f = der_children(t, s, e)
    policy = der_oid(t[f[1][2]:f[1][3]])
    mi = der_children(t, f[2][2], f[2][3])
    alg = der_oid(t[der_children(t, mi[0][2], mi[0][3])[0][2]:der_children(t, mi[0][2], mi[0][3])[0][3]])
    hashed = t[mi[1][2]:mi[1][3]]
    serial = int.from_bytes(t[f[3][2]:f[3][3]], "big")
    gen = der_time(f[4][0], t[f[4][2]:f[4][3]])
    nonce = next((int.from_bytes(t[x[2]:x[3]], "big") for x in f[5:] if x[0] == 0x02), None)
    md = cms["attrs"].get("message_digest")
    hname = _DIGESTS.get(cms["digest_oid"])
    return {"policy": policy, "imprint_alg": alg, "imprint": hashed.hex(), "serial": format(serial, "x"), "gen_time": gen, "nonce": nonce,
            "econtent_digest_ok": bool(md and hname and hashlib.new(hname, t).digest() == md), "cms": cms}


# ---------------------------------------------------------------- vòng đời khóa tại thời điểm ký (bước 2)
def _lifecycle(info: dict, revmap: dict) -> dict:
    """Vòng đời khóa trong gói 1.1, hợp với danh sách thu hồi (của gói và danh sách công bố) – lấy mốc thu hồi, nghi lộ SỚM NHẤT."""
    lc = dict(info.get("lifecycle") or {})
    for r in revmap.get(info.get("fingerprint"), []):
        for f in ("revoked_at", "compromised_since"):
            if r.get(f) and (not lc.get(f) or (_ts(r[f]) and _ts(lc[f]) and _ts(r[f]) < _ts(lc[f]))):
                lc[f] = r[f]
    return lc


def _key_at(lc: dict, t: datetime | None, proven: tuple | None = None) -> tuple[bool | str | None, str]:
    """(hợp lệ tại t?, giải thích). None = không có dữ liệu vòng đời (gói 1.0 không có danh sách thu hồi); "?" = không kết luận được.

    1.10.0 (góp ý PQC số 2 – «khóa có hiệu lực tại thời điểm ký»):
    - xoay vòng (retired) không làm hỏng chữ ký cũ; ký sau khi ngừng → không hợp lệ;
    - khóa bị thu hồi KHÔNG vì lộ (compromised_since trống): chữ ký trước thời điểm thu hồi vẫn hợp lệ;
    - khóa bị thu hồi VÌ LỘ: chữ ký có thời điểm ký sau thời điểm nghi lộ → không hợp lệ; trước thời điểm nghi lộ → hợp lệ kèm cảnh báo CHỈ
      KHI thời điểm ký được chứng minh độc lập (proven = (thời điểm, nguồn): dấu thời gian RFC 3161 đã kiểm chuỗi, điểm chốt đã công bố trước
      thời điểm lộ); chỉ có thời điểm do bên ký tự khai → "?" (INDETERMINATE), không bao giờ VALID – người giữ khóa bị lộ ghi lùi được."""
    if not lc:
        return None, ""
    if t is None:
        return False, "thiếu thời điểm ký"
    created, retired = _ts(lc.get("created_at")), _ts(lc.get("retired_at"))
    revoked, cs = _ts(lc.get("revoked_at")), _ts(lc.get("compromised_since"))
    if created and t < _floor(created):
        return False, "ký trước thời điểm tạo khóa"
    if cs and t > cs:                     # thời điểm ký trong manifest làm tròn xuống giây: ký trong cùng giây trước khi thu hồi vẫn hợp lệ
        return False, f"ký sau thời điểm nghi lộ khóa ({cs.isoformat()})"
    if revoked and t > revoked:
        return False, f"ký sau khi khóa bị thu hồi ({revoked.isoformat()})"
    if retired and t > retired:
        return False, f"ký sau khi khóa đã ngừng ({retired.isoformat()})"
    if cs:
        pt, src = (proven or (None, ""))
        pt = _ts(pt)
        if pt is None:
            return "?", (f"khóa đã bị thu hồi vì nghi lộ từ {cs.isoformat()}; thời điểm ký chỉ do bên ký tự khai, chưa được chứng minh độc lập "
                         "(dấu thời gian RFC 3161, điểm chốt đã công bố) – không kết luận chữ ký có trước thời điểm lộ")
        if pt > cs:
            return False, (f"khóa đã bị thu hồi vì nghi lộ từ {cs.isoformat()}; thời điểm được chứng minh độc lập ({pt.isoformat()}, {src}) "
                           "sau thời điểm nghi lộ")
        return True, (f"khóa hợp lệ tại thời điểm ký; CẢNH BÁO: khóa bị thu hồi vì nghi lộ từ {cs.isoformat()} – chữ ký được chứng minh độc lập "
                      f"có trước thời điểm đó ({pt.isoformat()}, {src})")
    note = "khóa hợp lệ tại thời điểm ký"
    if revoked:
        note += f"; khóa bị thu hồi sau đó ({revoked.isoformat()}, không do nghi lộ) – chữ ký trước thời điểm thu hồi vẫn hợp lệ"
    elif retired:
        note += f"; khóa đã ngừng sau đó ({retired.isoformat()}) – chữ ký cũ vẫn hợp lệ"
    return True, note


def _root_path(bundle: dict, anchor_fp: str | None, trusted: set | None, t: datetime | None, engine: str) -> tuple[bool, str]:
    """Neo vận hành được khóa neo gốc ĐÃ GHIM chứng nhận (chữ ký SLH-DSA hợp lệ, hiệu lực bao thời điểm ký)."""
    if not trusted or not anchor_fp:
        return False, ""
    roots = {r.get("fingerprint"): r for r in bundle.get("root") or [] if r.get("fingerprint") in trusted}
    for c in bundle.get("root_certifications") or []:
        st = c.get("statement") or {}
        r = roots.get(c.get("root_fingerprint"))
        if not r or st.get("type") != "OPERATIONAL_KEY_CERTIFICATION" or (st.get("subject_key") or {}).get("fingerprint") != anchor_fp:
            continue
        pk = _b64(r.get("value"))
        if _sha(pk) != r.get("fingerprint") or r.get("algorithm") not in _ROOT_ALGS:
            continue
        vf, vu = _ts(st.get("valid_from")), _ts(st.get("valid_until"))
        if t and ((vf and t < _floor(vf)) or (vu and t >= vu)):
            continue
        if _verify_sig(r["algorithm"], pk, _canonical(st), _b64(c.get("signature")), engine):
            return True, f"neo vận hành được khóa neo gốc {r['fingerprint'][:16]}… ({r['algorithm']}) chứng nhận"
    return False, ""


# ================================================================ 1.10.0 – thời điểm ký được chứng minh độc lập (góp ý PQC số 2, 3)
def _tsa_openssl(token: bytes, imprint_hex: str, roots_pem: bytes) -> tuple[bool | None, str]:
    """«openssl ts -verify»: chữ ký của TSA trên TSTInfo, chuỗi chứng thư TSA tới kho gốc do người kiểm cung cấp. None = không chạy được."""
    try:
        code, out = _openssl_run(["ts", "-verify", "-digest", imprint_hex, "-in", "tst.der", "-token_in", "-CAfile", "roots.pem"],
                                 {"tst.der": token, "roots.pem": roots_pem})
    except RuntimeError as e:
        return None, str(e)
    text = out.decode("utf-8", "replace")
    return code == 0 and "Verification: OK" in text, (text.strip().splitlines() or [""])[-1][:200]


def _chain_link(start_hash: str, records: list) -> tuple[str | None, int | None]:
    """Nối tiếp chuỗi kiểm toán từ mã băm start_hash qua các bản ghi (seq tăng dần) – trả (mã băm cuối, seq cuối) hoặc (None, None) khi đứt."""
    prev, seq = start_hash, None
    for r in records or []:
        if r.get("previous_hash") != prev or _sha(_canonical(r.get("record")) + prev.encode()) != r.get("record_hash"):
            return None, None
        prev, seq = r["record_hash"], r.get("seq")
    return prev, seq


def independent_time(bundle: dict, signature: bytes, *, tsa_roots_pem: bytes | None = None, time_proofs: list | None = None,
                     published_checkpoints: list | None = None) -> dict:
    """Thời điểm SỚM NHẤT mà chữ ký được chứng minh là đã tồn tại, KHÔNG dựa vào thời điểm bên ký tự khai. Ba nguồn:
    1. dấu thời gian RFC 3161 trong gói (bundle["timestamps"]): message imprint = băm của chữ ký, chữ ký TSA và chuỗi tới kho gốc TSA do người
       kiểm cung cấp (tsa_roots_pem) kiểm bằng «openssl ts -verify»; không có kho gốc TSA → không tính (ghi rõ);
    2. time_proofs: bằng chứng bên gọi ĐÃ kiểm độc lập (máy chủ, nhân chứng ngoài – luồng E) dạng {"time", "source", "covers_signature_sha256"};
       chỉ nhận khi covers_signature_sha256 đúng băm chữ ký này;
    3. điểm chốt đã công bố: bundle["checkpoint_proof"] = {"checkpoint": {"audit_seq", "audit_head"}, "records": [bản ghi nối từ bản ghi của
       hiện vật tới đỉnh điểm chốt]} và published_checkpoints (người kiểm tự lấy từ nguồn độc lập: [{"audit_seq", "audit_head",
       "published_at", "source"}]) – chuỗi nối đúng và điểm chốt có trong danh sách công bố thì chữ ký có trước published_at."""
    sig_sha = _sha(signature)
    found: list[tuple[datetime, str]] = []
    notes: list[str] = []
    for x in bundle.get("timestamps") or []:
        try:
            info = tst_info(_b64(x.get("token")))
        except (ValueError, IndexError, KeyError) as e:
            notes.append(f"dấu thời gian không đọc được: {e}")
            continue
        imprint = hashlib.new(_DIGESTS.get(info["imprint_alg"], "sha256"), signature).hexdigest()
        if info["imprint"] != imprint or not info["econtent_digest_ok"] or not info["gen_time"]:
            notes.append("dấu thời gian không khớp chữ ký này")
            continue
        if not tsa_roots_pem:
            notes.append(f"dấu thời gian RFC 3161 ({info['gen_time'].isoformat()}) chưa kiểm được chuỗi chứng thư TSA – thiếu kho gốc TSA (--tsa-roots)")
            continue
        ok, why = _tsa_openssl(_b64(x.get("token")), info["imprint"], tsa_roots_pem)
        if ok:
            found.append((info["gen_time"], f"dấu thời gian RFC 3161 của {x.get('tsa_url') or 'TSA'}"))
        else:
            notes.append(f"dấu thời gian RFC 3161 không kiểm được: {why}")
    for p in time_proofs or []:
        pt = _ts(p.get("time"))
        if pt and p.get("covers_signature_sha256") == sig_sha:
            found.append((pt, str(p.get("source") or "bằng chứng thời điểm do bên kiểm cung cấp")))
    cp = bundle.get("checkpoint_proof") or {}
    if cp and published_checkpoints is not None:
        recs = bundle.get("audit") or []
        mine = (bundle.get("manifest") or {}).get("audit") or {}
        start = next((r.get("record_hash") for r in recs if r.get("record_id") == mine.get("record_id")), None)
        head, seq = _chain_link(start, cp.get("records")) if start else (None, None)
        c = cp.get("checkpoint") or {}
        if not cp.get("records") and start:
            head, seq = start, next((r.get("seq") for r in recs if r.get("record_id") == mine.get("record_id")), None)
        if head and head == c.get("audit_head") and seq == c.get("audit_seq"):
            pub = next((x for x in published_checkpoints if x.get("audit_head") == head and x.get("audit_seq") == seq and _ts(x.get("published_at"))),
                       None)
            if pub:
                found.append((_ts(pub["published_at"]), f"điểm chốt đã công bố ({pub.get('source') or 'danh sách điểm chốt'})"))
            else:
                notes.append("điểm chốt trong gói không có trong danh sách điểm chốt đã công bố do người kiểm cung cấp")
        else:
            notes.append("chuỗi kiểm toán không nối được từ bản ghi của hiện vật tới điểm chốt")
    if not found:
        return {"proven": None, "source": None, "notes": notes}
    t, src = min(found, key=lambda x: x[0])
    return {"proven": t, "source": src, "notes": notes}


# ================================================================ 1.10.0 – công cụ chính sách phê duyệt (hàm thuần, chạy ngoại tuyến)
AL_ORDER = {"AL-1": 1, "AL-2": 2, "AL-3": 3, "AL-4": 4}
APPROVAL_KINDS = ("grant", "delegation")


def approval_policy_check(policy: dict, action: str, authority: dict, at=None, scope: dict | None = None) -> tuple[bool, str]:
    """Hành động có nằm trong phạm vi thẩm quyền của người duyệt theo chính sách đóng gói (policy["rules"][hành động]) không.
    Quy tắc: {"domains": [mã môi trường | "*" | "$scope"], "min_al", "kinds": ["grant", "delegation"], "resources"?, "verb"?, "decision"?}.
    "$scope" = môi trường ghi trong phạm vi của tuyên bố (ví dụ quy trình thuộc môi trường nào). Không suy quyền từ nhãn vai trò."""
    rule = ((policy or {}).get("rules") or {}).get(action or "")
    if not rule:
        return False, f"hành động «{action}» không có trong chính sách phê duyệt đóng gói"
    a = authority or {}
    kind = a.get("kind")
    if kind not in (rule.get("kinds") or APPROVAL_KINDS):
        return False, f"căn cứ loại «{kind}» không được chính sách chấp nhận cho «{action}»"
    t = _ts(at) if not isinstance(at, datetime) else at
    vf, vu = _ts(a.get("valid_from")), _ts(a.get("valid_until"))
    if t and ((vf and t < _floor(vf)) or (vu and t >= vu)):
        return False, "thẩm quyền không còn hiệu lực tại thời điểm ký"
    doms = set(rule.get("domains") or [])
    if "$scope" in doms:
        doms = (doms - {"$scope"}) | ({(scope or {}).get("domain")} if (scope or {}).get("domain") else set())
    if not doms:
        return False, "chính sách yêu cầu môi trường của phạm vi nhưng tuyên bố không ghi môi trường"
    if kind == "grant":
        if AL_ORDER.get(a.get("al"), 0) < AL_ORDER.get(rule.get("min_al") or "AL-4", 4):
            return False, f"cấp thẩm quyền {a.get('al')} thấp hơn mức chính sách yêu cầu {rule.get('min_al')}"
        d = a.get("domain")
        if not ("*" in doms or d == "*" or d in doms):
            return False, f"thẩm quyền được giao ở môi trường {d}, hành động thuộc {', '.join(sorted(x for x in doms if x))}"
        if a.get("resource") and rule.get("resources") and a["resource"] not in rule["resources"]:
            return False, f"thẩm quyền chỉ cho loại đối tượng {a['resource']}"
        if a.get("action_codes") and rule.get("verb") and rule["verb"] not in a["action_codes"]:
            return False, f"thẩm quyền không gồm hành động «{rule['verb']}»"
        return True, f"thẩm quyền được giao {a.get('al')} ở môi trường {d} bao hành động «{action}»"
    ds = set(a.get("domains") or [])
    if not ("*" in doms or "*" in ds or ds & doms):
        return False, f"ủy quyền ở môi trường {', '.join(sorted(ds))}, hành động thuộc {', '.join(sorted(x for x in doms if x))}"
    dc = a.get("decision_classes") or []
    if dc and rule.get("decision") and rule["decision"] not in dc:
        return False, f"ủy quyền không gồm loại quyết định «{rule['decision']}»"
    return True, f"ủy quyền {a.get('ref') or ''} còn hiệu lực bao hành động «{action}»"


NO_APPROVER_SIGNATURE = ("Không áp dụng – chưa có chữ ký phê duyệt riêng của người duyệt (hiện vật ký trước ACI-OS 1.10.0 hoặc người duyệt "
                         "chưa tạo khóa phê duyệt); phê duyệt chỉ được ghi trong manifest do Nhà trường ký")


def _approval_checks(bundle: dict, m: dict, t: datetime | None, trusted: set | None, revmap: dict, engine: str,
                     proven: tuple | None) -> dict:
    """Bước 3, 5, 6 cho hiện vật Nhà trường ký (manifest 1.2): chuỗi ủy quyền của người duyệt (chứng thư khóa người duyệt do neo ký, thẩm quyền
    có phạm vi, thời hạn, người cấp), hành động thuộc phạm vi thẩm quyền theo chính sách đóng gói, tuyên bố phê duyệt có chữ ký khớp manifest.
    Manifest không khai phê duyệt riêng → N/A kèm lý do (gói cũ); khai mà bằng chứng thiếu/sai → FAIL."""
    authority, action = m.get("authority") or {}, m.get("action") or {}
    decl = authority.get("approval")
    if not decl:
        return {3: (None, NO_APPROVER_SIGNATURE), 5: (None, "Không áp dụng – chưa có chữ ký phê duyệt riêng"),
                6: (None, "Không áp dụng – chưa có tuyên bố phê duyệt có chữ ký của người duyệt")}
    ev = bundle.get("approval") or {}
    if not ev.get("statement") or not ev.get("certificate"):
        why = "manifest khai có chữ ký phê duyệt riêng nhưng gói bằng chứng không mang tuyên bố phê duyệt, chứng thư người duyệt"
        return {3: (False, why), 5: (False, why), 6: (False, why)}
    st, cert, ak, iss, pol = ev["statement"], ev["certificate"], ev.get("approver_key") or {}, ev.get("certificate_issuer") or {}, \
        ev.get("policy") or {}
    auth = decl.get("authority") or {}
    # [3] chứng thư khóa người duyệt + thẩm quyền
    apk, ipk = _b64(ak.get("value")), _b64(iss.get("value"))
    afp, ifp = ak.get("fingerprint"), iss.get("fingerprint")
    subj = cert.get("subject") or {}
    p3 = []
    key_ok = bool(apk) and _sha(apk) == afp == decl.get("approver_key_fingerprint") == subj.get("key_fingerprint")
    p3.append((key_ok, "khóa người duyệt khớp chứng thư và manifest" if key_ok else "khóa người duyệt không khớp chứng thư/manifest"))
    issued = _ts(cert.get("issued_at"))
    iss_ok = bool(ipk) and _sha(ipk) == ifp == (cert.get("issuer") or {}).get("anchor_fingerprint")
    pinned = trusted is None or ifp in trusted
    if iss_ok and not pinned:
        pinned = _root_path({"root": bundle.get("root"), "root_certifications": ev.get("issuer_root_certifications")}, ifp, trusted, issued,
                            engine)[0]
    cert_ok = iss_ok and pinned and cert.get("type") == APPROVER_CERT_TYPE and \
        _verify_sig(iss.get("algorithm", ""), ipk, _canonical(cert), _b64(ev.get("certificate_signature")), engine)
    p3.append((cert_ok, f"chứng thư người duyệt {cert.get('certificate_id')} do neo {str(ifp)[:16]}… ký"
               + ("" if cert_ok else (" – chữ ký không hợp lệ" if iss_ok and pinned else " – neo ký chứng thư không được ghim"))))
    cvf, cvu = _ts(cert.get("valid_from")), _ts(cert.get("valid_until"))
    p3.append((bool(t and cvf and cvu and _floor(cvf) <= t < cvu), f"chứng thư hiệu lực {cert.get('valid_from')} → {cert.get('valid_until')}"))
    i_life, i_note = _key_at(_lifecycle(iss, revmap), issued)
    if i_life is not None:
        p3.append((i_life, "neo ký chứng thư: " + i_note))
    a_life, a_note = _key_at(_lifecycle(ak, revmap), t, proven)
    if a_life is not None:
        p3.append((a_life, "khóa người duyệt: " + a_note))
    actor_ok = subj.get("actor_id") == (st.get("approver") or {}).get("actor_id") == authority.get("approver_actor_id")
    p3.append((actor_ok, "người duyệt trong chứng thư, tuyên bố, manifest là một" if actor_ok else "người duyệt trong chứng thư/tuyên bố/manifest khác nhau"))
    vf, vu = _ts(auth.get("valid_from")), _ts(auth.get("valid_until"))
    a_ok = auth.get("kind") in APPROVAL_KINDS and bool(auth.get("granted_by")) and bool(vf) and \
        bool(auth.get("domain") or auth.get("domains")) and bool(t and _floor(vf) <= t and (vu is None or t < vu))
    p3.append((a_ok, f"thẩm quyền {auth.get('kind')} {auth.get('ref') or ''}: phạm vi {auth.get('domain') or ','.join(auth.get('domains') or [])}"
               f", hiệu lực {auth.get('valid_from')} → {auth.get('valid_until') or 'không đặt hạn'}, người cấp {auth.get('granted_by') or '?'}"))
    s3 = False if any(x[0] is False for x in p3) else ("?" if any(x[0] == "?" for x in p3) else True)
    # [5] chính sách
    pol_ok = bool(pol) and _sha(_canonical(pol)) == decl.get("policy_hash")
    allowed, why = approval_policy_check(pol, action.get("action_type"), auth, t, decl.get("scope")) if pol_ok else (False, "")
    s5 = (pol_ok and allowed, f"{action.get('action_type')} {'AUTHORIZED' if pol_ok and allowed else 'NOT AUTHORIZED'} – "
          + (why if pol_ok else "chính sách trong gói không khớp mã băm chính sách ghi trong manifest")
          + (f" (chính sách {pol.get('version')}, {pol.get('status')})" if pol_ok else ""))
    # [6] tuyên bố phê duyệt
    art, mart, meta = st.get("artifact") or {}, m.get("artifact") or {}, m.get("metadata") or {}
    p6 = []
    sig_ok = ak.get("algorithm") in _OID and ak.get("algorithm") not in _ROOT_ALGS and \
        _verify_sig(ak.get("algorithm", ""), apk, _canonical(st), _b64(ev.get("signature")), engine)
    p6.append((sig_ok, f"chữ ký {ak.get('algorithm')} của người duyệt {'VALID' if sig_ok else 'INVALID'}"))
    p6.append((st.get("type") == APPROVAL_STATEMENT_TYPE and _sha(_canonical(st)) == decl.get("statement_hash"), "băm tuyên bố khớp manifest"))
    if art.get("sha256"):
        tgt = art["sha256"] in (mart.get("sha256"), meta.get("source_sha256"))
    else:
        tgt = bool(art.get("ref")) and art.get("ref") == authority.get("approval_ref")
    p6.append((tgt, "hiện vật trong tuyên bố khớp hiện vật đã ký" if tgt else "tuyên bố phê duyệt cho hiện vật khác"))
    p6.append((st.get("action") == action.get("action_type"), f"hành động {st.get('action')}"))
    sa = st.get("approver") or {}
    p6.append((sa.get("key_fingerprint") == afp and sa.get("certificate_id") == cert.get("certificate_id") == decl.get("certificate_id"),
               "khóa, chứng thư trong tuyên bố khớp"))
    p6.append((st.get("authority") == auth and st.get("scope") == decl.get("scope"), "thẩm quyền, phạm vi người duyệt khai khớp thẩm quyền Nhà trường xác nhận"))
    ts = _ts(st.get("signed_at"))
    p6.append((bool(ts and t and ts.timestamp() <= t.timestamp() + 300 and t.timestamp() - ts.timestamp() <= 86400),
               f"người duyệt ký lúc {st.get('signed_at')}"))
    s6 = all(x[0] for x in p6)
    bad = lambda ps: "; ".join(d for ok, d in ps if ok is not True)                         # noqa: E731
    return {3: (s3, f"Người duyệt {sa.get('name') or authority.get('approved_by')}: " + (bad(p3) if s3 is not True else
                "chứng thư khóa người duyệt hợp lệ; " + p3[-1][1])),
            5: s5,
            6: (s6, f"Tuyên bố phê duyệt {st.get('statement_id')}: " + ("khớp manifest, chữ ký người duyệt hợp lệ" if s6 else bad(p6)))}


# ================================================================ 1.10.0 – mức định danh người ký (góp ý PQC số 1) – không gộp với kết quả mật mã
IDENTITY_LEVELS = ("LIMITED", "PUBLISHED", "CERTIFIED", "LEGALLY-BOUND")
TRUST_DOC_TYPE = "ACI-TRUST-PUBLICATION"
APPROVER_CERT_TYPE = "ACI-APPROVER-CERTIFICATE"
APPROVAL_STATEMENT_TYPE = "ACI-APPROVAL-STATEMENT"
KEY_STATEMENT_TYPE = "ACI-KEY-STATEMENT"
KEY_STATEMENT_MARK = "ACIKEYSTATEMENTV1X"       # + hex(JSON chuẩn hóa) – chỉ chữ, số: không bị thoát ký tự trong chuỗi PDF
DNS_PREFIX = "_aci-trust"


def check_trust_document(env: dict, engine: str = "auto") -> dict:
    """/.well-known/aci-trust.json = {"document": {...}, "signature": {"algorithm", "key_fingerprint", "value"}}: chữ ký của neo đang dùng (có trong
    chính tài liệu) trên JSON chuẩn hóa của «document». Trả {ok, signer, anchors: {dấu vân tay: trạng thái}, roots, institution}."""
    doc, sig = (env or {}).get("document") or {}, (env or {}).get("signature") or {}
    anchors = {a.get("fingerprint"): a for a in doc.get("anchors") or [] if a.get("fingerprint")}
    cur = anchors.get(doc.get("current_anchor_fingerprint")) or {}
    pk = _b64(cur.get("public_key"))
    ok = doc.get("type") == TRUST_DOC_TYPE and bool(pk) and _sha(pk) == cur.get("fingerprint") == sig.get("key_fingerprint") and \
        sig.get("algorithm") == cur.get("algorithm") and _verify_sig(cur.get("algorithm", ""), pk, _canonical(doc), _b64(sig.get("value")), engine)
    return {"ok": ok, "signer": cur.get("fingerprint"), "anchors": {k: v.get("state") for k, v in anchors.items()},
            "roots": {r.get("fingerprint") for r in doc.get("roots") or [] if r.get("fingerprint")},
            "institution": (doc.get("institution") or {}).get("code"), "issued_at": doc.get("issued_at"), "sequence": doc.get("sequence")}


def check_revocation_list(env: dict, trusted: set | None, engine: str = "auto") -> tuple[bool, list, str]:
    """Danh sách thu hồi có chữ ký (/api/v1/trust/revocations.json, tải về dùng ngoại tuyến): chữ ký của neo vận hành ghi trong tài liệu, neo đó
    phải thuộc danh sách ghim (trusted). Trả (hợp lệ?, các mục thu hồi, ghi chú). Không hợp lệ → không dùng (không «gỡ» thu hồi nào)."""
    doc, sig = (env or {}).get("document") or {}, (env or {}).get("signature") or {}
    s = doc.get("signer") or {}
    pk = _b64(s.get("public_key"))
    if doc.get("type") != "ACI-REVOCATION-LIST" or not pk or _sha(pk) != s.get("fingerprint") or sig.get("key_fingerprint") != s.get("fingerprint"):
        return False, [], "danh sách thu hồi không đúng định dạng"
    if trusted is not None and s.get("fingerprint") not in trusted:
        return False, [], "neo ký danh sách thu hồi không thuộc danh sách ghim"
    if not _verify_sig(s.get("algorithm", ""), pk, _canonical(doc), _b64(sig.get("value")), engine):
        return False, [], "chữ ký danh sách thu hồi không hợp lệ"
    return True, list(doc.get("entries") or []), f"danh sách thu hồi số {doc.get('number')} phát hành {doc.get('issued_at')}"


def dns_record_value(institution: str, anchor_fp: str, root_fp: str | None = None) -> str:
    """Giá trị bản ghi TXT «_aci-trust.<tên miền>» (một chuỗi ≤ 255 ký tự)."""
    return f"v=aci-trust1; i={institution}; a={anchor_fp}" + (f"; r={root_fp}" if root_fp else "")


def parse_dns_trust(txts: list) -> dict:
    """Các chuỗi TXT → {"anchors", "roots", "institution"} (bỏ qua bản ghi không đúng «v=aci-trust1»)."""
    out = {"anchors": set(), "roots": set(), "institution": None}
    for s in txts or []:
        kv = dict(p.strip().split("=", 1) for p in str(s).split(";") if "=" in p)
        if kv.get("v") != "aci-trust1":
            continue
        out["institution"] = kv.get("i") or out["institution"]
        for k, dst in (("a", "anchors"), ("r", "roots")):
            for fp in (kv.get(k) or "").split(","):
                if re.fullmatch(r"[0-9a-f]{64}", fp.strip()):
                    out[dst].add(fp.strip())
    return out


def dns_txt(name: str, server: str | None = None, timeout: float = 3.0) -> list[str] | None:
    """Tra bản ghi TXT (thư viện chuẩn): truy vấn UDP tới máy chủ DNS chỉ định / máy chủ trong /etc/resolv.conf, hoặc «nslookup» của hệ điều
    hành. None = không tra được (không có mạng) – kênh DNS khi đó KHÔNG được tính là xác nhận."""
    import socket
    import struct
    if not server:
        try:
            with open("/etc/resolv.conf", encoding="utf-8") as f:
                server = next((ln.split()[1] for ln in f if ln.startswith("nameserver") and len(ln.split()) > 1), None)
        except OSError:
            server = None
    if server:
        try:
            qid = int.from_bytes(os.urandom(2), "big")
            q = struct.pack(">HHHHHH", qid, 0x0100, 1, 0, 0, 0) + b"".join(
                bytes([len(p)]) + p.encode("idna") for p in name.strip(".").split(".")) + b"\x00" + struct.pack(">HH", 16, 1)
            with socket.socket(socket.AF_INET6 if ":" in server else socket.AF_INET, socket.SOCK_DGRAM) as s:
                s.settimeout(timeout)
                s.sendto(q, (server, 53))
                resp = s.recv(4096)
            rid, flags, qd, an = struct.unpack(">HHHH", resp[:8])
            if rid != qid or flags & 0x000F not in (0, 3):
                return None
            p = 12

            def skip(p):
                while resp[p]:
                    if resp[p] & 0xC0 == 0xC0:
                        return p + 2
                    p += resp[p] + 1
                return p + 1
            for _ in range(qd):
                p = skip(p) + 4
            out = []
            for _ in range(an):
                p = skip(p)
                typ, _cls, _ttl, ln = struct.unpack(">HHIH", resp[p:p + 10])
                p += 10
                if typ == 16:
                    q2, txt = p, b""
                    while q2 < p + ln:
                        txt += resp[q2 + 1:q2 + 1 + resp[q2]]
                        q2 += resp[q2] + 1
                    out.append(txt.decode("utf-8", "replace"))
                p += ln
            return out
        except (OSError, struct.error, IndexError, UnicodeError):
            pass
    exe = shutil.which("nslookup")
    if not exe:
        return None
    try:
        r = subprocess.run([exe, "-type=TXT", name], capture_output=True, text=True, timeout=timeout * 3)
    except (OSError, subprocess.SubprocessError):
        return None
    found = re.findall(r'"([^"]*)"', r.stdout)
    return found if found or r.returncode == 0 else None


def _cert_spki_key(der: bytes) -> tuple[str | None, bytes]:
    """Chứng thư X.509 (DER) → (OID thuật toán khóa chủ thể, khóa công khai thô) – thư viện chuẩn."""
    _, s, e = der_read(der, 0)
    tbs = der_children(der, *der_read(der, der_children(der, s, e)[0][1])[1:])
    k = 1 if tbs[0][0] == 0xA0 else 0
    spki = der_children(der, tbs[k + 5][2], tbs[k + 5][3])
    alg = der_children(der, spki[0][2], spki[0][3])
    return der_oid(der[alg[0][2]:alg[0][3]]), der[spki[1][2] + 1:spki[1][3]]


def _pem_der(pem) -> bytes:
    s = pem.decode("ascii", "replace") if isinstance(pem, (bytes, bytearray)) else str(pem or "")
    body = "".join(x for x in s.splitlines() if x and not x.startswith("-----"))
    return _b64(body)


def x509_certified(anchor_pk: bytes, x509: dict | None, trusted: set | None, t: datetime | None) -> tuple[bool | str, str]:
    """CERTIFIED: chứng thư X.509 của khóa vận hành (ML-DSA) do chứng thư gốc của Nhà trường (khóa neo gốc SLH-DSA) cấp: khóa chủ thể đúng khóa
    đã ký, khóa của chứng thư gốc được GHIM (trusted), «openssl verify» chuỗi tại thời điểm ký. Trả (True | False | "?", ghi chú)."""
    x = x509 or {}
    if not x.get("certificate_pem") or not x.get("issuer_pem"):
        return False, "không có chứng thư X.509 cho khóa đã ký"
    try:
        leaf, root = _pem_der(x["certificate_pem"]), _pem_der(x["issuer_pem"])
        _, leaf_pk = _cert_spki_key(leaf)
        _, root_pk = _cert_spki_key(root)
    except (ValueError, IndexError) as e:
        return False, f"chứng thư X.509 không đọc được: {e}"
    if leaf_pk != anchor_pk:
        return False, "chứng thư X.509 cấp cho khóa khác khóa đã ký"
    rfp = _sha(root_pk)
    if not trusted or rfp not in trusted:
        return False, f"khóa của chứng thư gốc {rfp[:16]}… chưa được ghim – không kết luận được chứng nhận"
    try:
        code, out = _openssl_run(["verify", "-CAfile", "root.pem", "-purpose", "any", "leaf.pem"],
                                 {"root.pem": x["issuer_pem"].encode() if isinstance(x["issuer_pem"], str) else x["issuer_pem"],
                                  "leaf.pem": x["certificate_pem"].encode() if isinstance(x["certificate_pem"], str) else x["certificate_pem"]})
    except RuntimeError as e:
        return "?", str(e)
    text = out.decode("utf-8", "replace")
    if code == 0 and ": OK" in text:
        b = cert_brief(leaf)
        at_sign = bool(t and b["not_before"] and b["not_after"] and b["not_before"] <= t <= b["not_after"])
        return True, (f"chứng thư X.509 của khóa đã ký do khóa neo gốc {rfp[:16]}… (đã ghim) cấp, còn hiệu lực"
                      + ("" if at_sign else " (chứng thư cấp sau thời điểm ký – chứng nhận chính khóa đã ký)"))
    return False, "openssl verify: " + (text.strip().splitlines() or [""])[-1][:200]


def key_statement_from_pdf(pdf: bytes) -> dict | None:
    """Tuyên bố khóa của Nhà trường nhúng trong PDF (thông tin tài liệu /Keywords: «ACIKEYSTATEMENTV1X<hex của JSON chuẩn hóa>») – CHỈ tìm trong
    vùng được chữ ký pháp lý bao (ByteRange của chữ ký cuối) để nội dung thêm sau khi ký không được tính."""
    sigs = pdf_signatures(pdf) if pdf.startswith(b"%PDF") else []
    region = sigs[-1]["signed"] if sigs else b""
    m = re.search(re.escape(KEY_STATEMENT_MARK).encode() + rb"((?:[0-9a-f]{2}){20,})", region)
    if not m:
        return None
    try:
        st = json.loads(bytes.fromhex(m.group(1).decode("ascii")).decode("utf-8"))
    except (ValueError, UnicodeDecodeError):
        return None
    return st if isinstance(st, dict) and st.get("type") == KEY_STATEMENT_TYPE else None


def _statement_binds(st: dict | None, anchor_fp: str, bundle: dict, root_ok: set) -> bool:
    if not st:
        return False
    fps = {k.get("fingerprint") for k in st.get("operational_keys") or []}
    roots = {k.get("fingerprint") for k in st.get("root_keys") or []}
    return anchor_fp in fps or bool(roots & root_ok)


def identity_level(bundle: dict, trusted: set | None, t: datetime | None, evidence: dict | None, engine: str = "auto", *,
                   pl_roots_pem: bytes | None = None) -> dict:
    """Mức định danh của bên ký (neo của Nhà trường đã ký hiện vật/chứng thư ủy quyền) – TÁCH khỏi kết luận mật mã, không gắn mức cao hơn bằng
    chứng có thật. evidence: {"channels": [{"channel": "well-known"|"dns"|"pinned", "source", "document"|"txt"|"fingerprints"}],
    "key_statement": {"pdf": bytes} | {"statement", "legal_result"} (máy chủ đã kiểm PL)}.
      LIMITED        – chỉ có neo do bên đưa tệp cung cấp;
      PUBLISHED      – neo khớp ≥ 2 kênh công bố người xác minh tự lấy (HTTPS .well-known có chữ ký, DNS TXT, bản ghi ghim/mã QR);
      CERTIFIED      – có chứng thư X.509 hợp lệ tới khóa gốc đã ghim;
      LEGALLY-BOUND  – có tuyên bố khóa đã ký pháp lý (PL) hợp lệ chứa đúng dấu vân tay."""
    ev = evidence or {}
    anc = bundle.get("anchor") or {}
    fp, apk = anc.get("fingerprint"), _b64(anc.get("value"))
    out = {"level": "LIMITED", "anchor_fingerprint": fp, "channels": [], "criteria": {}}
    if not fp or not apk or _sha(apk) != fp:
        out["note"] = "Gói không mang neo tin cậy hợp lệ"
        return out
    root_ok = set()                         # khóa gốc đã ghim chứng nhận neo này (chứng nhận SLH-DSA hoặc X.509)
    if trusted:
        for r in bundle.get("root") or []:
            if r.get("fingerprint") in trusted and _root_path(bundle, fp, {r.get("fingerprint")}, t, engine)[0]:
                root_ok.add(r["fingerprint"])
    docs = [check_trust_document(c.get("document"), engine) for c in ev.get("channels") or [] if c.get("channel") == "well-known"]
    good_docs = [d for d in docs if d["ok"] and fp in d["anchors"]]
    for c in ev.get("channels") or []:
        kind, ok, why = c.get("channel"), False, ""
        if kind == "well-known":
            d = check_trust_document(c.get("document"), engine)
            ok = d["ok"] and fp in d["anchors"]
            why = ("tài liệu có chữ ký hợp lệ, liệt kê neo này" if ok else
                   "chữ ký tài liệu không hợp lệ" if not d["ok"] else "tài liệu không liệt kê neo này")
        elif kind == "dns":
            p = parse_dns_trust(c.get("txt") or [])
            via_doc = any(d["signer"] in p["anchors"] for d in good_docs)
            ok = fp in p["anchors"] or via_doc or bool(p["roots"] & root_ok)
            why = ("bản ghi TXT có dấu vân tay neo này" if fp in p["anchors"] else
                   "bản ghi TXT có neo đang dùng đã ký tài liệu công bố liệt kê neo này" if via_doc else
                   "bản ghi TXT có khóa gốc đã chứng nhận neo này" if ok else
                   "không tra được bản ghi TXT" if not c.get("txt") else "bản ghi TXT không có dấu vân tay tương ứng")
        elif kind == "pinned":
            pins = set(c.get("fingerprints") or [])
            ok = fp in pins or any(d["signer"] in pins for d in good_docs) or bool(pins & root_ok)
            why = "khớp bản ghi ghim của người xác minh" if ok else "không khớp bản ghi ghim"
        else:
            continue
        out["channels"].append({"channel": kind, "source": c.get("source"), "confirms": ok, "detail": why})
    n = len({c["channel"] for c in out["channels"] if c["confirms"]})
    out["criteria"]["published"] = {"ok": n >= 2, "channels_confirming": n,
                                    "detail": f"{n} kênh công bố độc lập xác nhận neo (cần ít nhất 2)"}
    cert_ok, cert_note = x509_certified(apk, (bundle.get("identity") or {}).get("x509") or ev.get("x509"), trusted, t)
    out["criteria"]["certified"] = {"ok": cert_ok is True, "detail": cert_note}
    if cert_ok is True:
        try:
            root_ok.add(_sha(_cert_spki_key(_pem_der(((bundle.get("identity") or {}).get("x509") or ev.get("x509"))["issuer_pem"]))[1]))
        except (ValueError, IndexError, KeyError, TypeError):
            pass
    ks = ev.get("key_statement") or {}
    lb_ok, lb_note = False, "chưa có tuyên bố khóa đã ký pháp lý"
    if ks.get("pdf"):
        st = key_statement_from_pdf(ks["pdf"])
        lr = ks.get("legal_result") or legal_check_offline(ks["pdf"], pl_roots_pem)
        binds = _statement_binds(st, fp, bundle, root_ok)
        lb_ok = lr.get("result") == "valid" and binds
        lb_note = (f"tuyên bố khóa ký pháp lý bởi {lr.get('signer') or '?'}: {lr.get('result')}" +
                   ("" if binds else " – tuyên bố không chứa dấu vân tay neo này (hoặc khóa gốc đã chứng nhận neo)") +
                   ("" if lr.get("result") == "valid" else f" ({lr.get('detail')})"))
    elif ks.get("statement") and ks.get("legal_result"):
        binds = _statement_binds(ks["statement"], fp, bundle, root_ok)
        lb_ok = ks["legal_result"].get("result") == "valid" and binds and _sha(_canonical(ks["statement"])) == ks.get("statement_hash")
        lb_note = f"tuyên bố khóa {ks.get('code') or ''} ký pháp lý: {ks['legal_result'].get('result')}" + ("" if binds else " – không chứa neo này")
    out["criteria"]["legally_bound"] = {"ok": lb_ok, "detail": lb_note}
    for lv, key in (("LEGALLY-BOUND", "legally_bound"), ("CERTIFIED", "certified"), ("PUBLISHED", "published")):
        if out["criteria"][key]["ok"]:
            out["level"] = lv
            break
    out["note"] = {"LIMITED": "Chỉ có neo do bên đưa tệp cung cấp – nên đối chiếu dấu vân tay qua kênh công bố độc lập của Nhà trường",
                   "PUBLISHED": "Neo khớp các kênh công bố độc lập của Nhà trường",
                   "CERTIFIED": "Khóa đã ký có chứng thư X.509 do khóa neo gốc đã ghim cấp",
                   "LEGALLY-BOUND": "Khóa được gắn với pháp nhân bằng tuyên bố khóa có chữ ký số pháp lý"}[out["level"]]
    return out


# ---------------------------------------------------------------- 10 (11) bước
def verify_bundle(bundle: dict, content: bytes | None, trusted_anchor_fingerprint=None, engine: str = "auto", *,
                  revocations: list | None = None, pl_roots_pem: bytes | None = None, legal_result: dict | None = None,
                  identity_evidence: dict | None = None, time_proofs: list | None = None, tsa_roots_pem: bytes | None = None,
                  published_checkpoints: list | None = None) -> dict:
    """trusted_anchor_fingerprint: một dấu vân tay (có thể nhiều, ngăn bằng dấu phẩy), danh sách (neo đang dùng, neo đã xoay vòng, khóa neo
    gốc), hoặc None (không ghim – chỉ dùng để thử). revocations: danh sách thu hồi công bố (/api/v1/trust/anchor → «revocations»).
    pl_roots_pem: kho chứng thư gốc (PEM) để kiểm chữ ký pháp lý của hồ sơ LAI; legal_result: kết quả kiểm PL do bộ kiểm khác đã chạy
    (máy chủ dùng bộ kiểm trust/legal.py) – khi có thì dùng thay cho bước kiểm bằng dòng lệnh.
    1.10.0: identity_evidence – kênh công bố neo, tuyên bố khóa (mức định danh, xem identity_level); time_proofs, tsa_roots_pem,
    published_checkpoints – chứng minh độc lập thời điểm ký khi khóa bị thu hồi vì lộ (xem independent_time)."""
    if isinstance(trusted_anchor_fingerprint, str):
        trusted = {x.strip() for x in trusted_anchor_fingerprint.split(",") if x.strip()} or None
    else:
        trusted = set(trusted_anchor_fingerprint) if trusted_anchor_fingerprint else None
    m = bundle.get("manifest") or {}
    bver = str(bundle.get("bundle_version") or "1.0")
    mver = str(m.get("manifest_version") or "")
    meta = m.get("metadata") or {}
    profile = meta.get("sig_profile") or "KT"
    checks: list[dict] = []

    def add(i: int, ok, detail: str):
        st = "OK" if ok is True else ("N/A" if ok is None else ("INDETERMINATE" if ok == "?" else "FAIL"))
        checks.append({"step": i + 1, "name": STEPS[i], "status": st, "detail": detail})

    core = {k: v for k, v in m.items() if k not in ("signature", "audit")}
    agent, authority, action = m.get("agent") or {}, m.get("authority") or {}, m.get("action") or {}
    pk_info, anchor, deleg = bundle.get("public_key") or {}, bundle.get("anchor") or {}, bundle.get("delegation")
    institution_signed = agent.get("kind") == "institution"
    pk = _b64(pk_info.get("value"))
    cred = (deleg or {}).get("credential") or {}
    t = _ts(m.get("timestamp"))
    revmap: dict = {}
    for r in list(bundle.get("revocations") or []) + list(revocations or []):
        if r.get("fingerprint"):
            revmap.setdefault(r["fingerprint"], []).append(r)

    # [1] danh tính: agent_id trong manifest khớp chủ thể của chứng thư và chủ khóa
    if institution_signed:
        add(0, agent.get("agent_id") == anchor.get("institution") == pk_info.get("owner_ref"), f"Neo tin cậy của Nhà trường {agent.get('agent_id')}")
    else:
        add(0, bool(cred) and agent.get("agent_id") == cred.get("subject", {}).get("ref") == pk_info.get("owner_ref"),
            f"Agent {agent.get('agent_id')} – chủ thể chứng thư {cred.get('subject', {}).get('ref')}")
    # [2] khóa công khai: dấu vân tay khớp manifest và chứng thư; neo tin cậy thuộc danh sách được ghim (hoặc được khóa neo gốc đã ghim chứng
    #     nhận); Nhà trường ký thì khóa ký chính là neo tin cậy; khóa ký (và neo đã ký chứng thư) hợp lệ TẠI THỜI ĐIỂM KÝ
    fp_ok = bool(pk) and _sha(pk) == pk_info.get("fingerprint") == agent.get("public_key_fingerprint")
    if not institution_signed:
        fp_ok = fp_ok and cred.get("subject", {}).get("key_fingerprint") == agent.get("public_key_fingerprint")
    anchor_pk = _b64(anchor.get("value"))
    if institution_signed:
        fp_ok = fp_ok and pk == anchor_pk
    anchor_fp_ok = bool(anchor_pk) and _sha(anchor_pk) == anchor.get("fingerprint")
    pinned = trusted is None or anchor.get("fingerprint") in trusted
    root_note = ""
    if anchor_fp_ok and trusted is not None and not pinned:
        pinned, root_note = _root_path(bundle, anchor.get("fingerprint"), trusted, t, engine)
    anchor_ok = anchor_fp_ok and pinned
    msig = _b64((m.get("signature") or {}).get("value"))
    tproof = independent_time(bundle, msig, tsa_roots_pem=tsa_roots_pem, time_proofs=time_proofs, published_checkpoints=published_checkpoints)
    proven = (tproof["proven"], tproof["source"]) if tproof["proven"] else None
    life_ok, life_note = _key_at(_lifecycle(pk_info, revmap), t, proven)
    if not institution_signed and anchor.get("fingerprint"):
        a_ok, a_note = _key_at(_lifecycle(anchor, revmap), _ts(cred.get("issued_at")) or t)
        if a_ok is False or (a_ok == "?" and life_ok is not False):
            life_ok, life_note = a_ok, "neo đã ký chứng thư ủy quyền: " + a_note
    detail = ("Dấu vân tay khóa khớp" if fp_ok else "Khóa ký không khớp neo tin cậy hoặc dấu vân tay") \
        + ("" if trusted else " (chưa ghim neo tin cậy – nên truyền --anchor)") \
        + ("" if anchor_ok or not trusted else " · neo tin cậy không thuộc danh sách được ghim") \
        + (f" · {root_note}" if root_note else "") + (f" · {life_note}" if life_note else "") \
        + (" · gói 1.0 không mang vòng đời khóa (đối chiếu danh sách thu hồi công bố)" if life_ok is None and bver == "1.0" else "")
    add(1, False if not (fp_ok and anchor_ok) or life_ok is False else ("?" if life_ok == "?" else True), detail)
    # [3] chứng thư ủy quyền có chữ ký hợp lệ của neo tin cậy; Nhà trường ký (1.10.0): chuỗi ủy quyền của người duyệt có chữ ký phê duyệt riêng
    appr = _approval_checks(bundle, m, t, trusted, revmap, engine, proven) if institution_signed else {}
    if institution_signed:
        add(2, *appr[3])
    else:
        sig = _b64((deleg or {}).get("signature"))
        deleg_ok = bool(cred) and cred.get("issuer", {}).get("anchor_fingerprint") == anchor.get("fingerprint") and \
            _verify_sig(anchor.get("algorithm", ""), anchor_pk, _canonical(cred), sig, engine)
        add(2, deleg_ok, f"Ủy quyền {cred.get('delegation_id')} do {cred.get('owner', {}).get('name')} cấp")
    # [4] thẩm quyền: còn hiệu lực tại thời điểm ký, chưa bị thu hồi trước đó
    if institution_signed:
        ap = (authority.get("approval") or {}).get("authority") or {}
        avf, avu = _ts(ap.get("valid_from")), _ts(ap.get("valid_until"))
        in_time = not ap or bool(t and avf and _floor(avf) <= t and (avu is None or t < avu))
        add(3, bool(authority.get("approved_by")) and in_time, f"Người duyệt: {authority.get('approved_by')}"
            + (f" · thẩm quyền {'còn' if in_time else 'KHÔNG còn'} hiệu lực tại thời điểm ký ({ap.get('valid_from')} → "
               f"{ap.get('valid_until') or 'không đặt hạn'})" if ap else ""))
    else:
        vf, vu = _ts(cred.get("valid_from")), _ts(cred.get("valid_until"))
        revoked = _ts((deleg or {}).get("revoked_at"))
        auth_ok = bool(t and vf and vu and vf <= t < vu) and (revoked is None or revoked > t) and \
            authority.get("delegation_id") == cred.get("delegation_id")
        add(3, auth_ok, f"Hiệu lực {cred.get('valid_from')} → {cred.get('valid_until')}" + (f"; thu hồi {revoked.isoformat()}" if revoked else ""))
    # [5] quyền: hành động và quyền tuyên bố nằm trong quyền được ủy
    if institution_signed:
        add(4, *appr[5])
    else:
        granted = set(cred.get("permissions") or [])
        perm_ok = action.get("action_type") in granted and set(authority.get("permissions") or []) <= granted
        add(4, perm_ok, f"{action.get('action_type')} {'AUTHORIZED' if perm_ok else 'NOT AUTHORIZED'}")
    # [6] hành động: bản ghi cổng cấp quyền khớp manifest
    act = bundle.get("action")
    if institution_signed:
        add(5, *appr[6])
    else:
        act_ok = bool(act) and act.get("action_id") == action.get("action_id") and act.get("action") == action.get("action_type") \
            and act.get("authorization") == "AUTHORIZED" and act.get("subject_ref") == agent.get("agent_id")
        add(5, act_ok, f"{action.get('action_id')} – {(act or {}).get('authorization')}")
    # [7] băm hiện vật
    if content is None:
        add(6, False, "Không có tệp hiện vật để băm")
    else:
        h = _sha(content)
        add(6, h == (m.get("artifact") or {}).get("sha256"), "MATCH" if h == (m.get("artifact") or {}).get("sha256") else f"MISMATCH ({h[:16]}…)")
    # [8] chữ ký hậu lượng tử trên manifest
    sig_info = m.get("signature") or {}
    msig = _b64(sig_info.get("value"))
    # 1.10.0 – luồng E: SLH-DSA được dùng cho khóa ký vận hành khi danh mục chuyển thuật toán (dự phòng khi lưới bị phá); khóa neo gốc vẫn KHÔNG
    # được ký hiện vật trực tiếp (khóa ký trùng khóa neo gốc trong gói → không hợp lệ)
    root_fps = {r.get("fingerprint") for r in bundle.get("root") or [] if isinstance(r, dict)}
    sig_ok = sig_info.get("algorithm") == agent.get("algorithm") == pk_info.get("algorithm") and \
        pk_info.get("fingerprint") not in root_fps and _verify_sig(sig_info.get("algorithm", ""), pk, _canonical(core), msig, engine)
    add(7, sig_ok, f"{sig_info.get('algorithm')} {'VALID' if sig_ok else 'INVALID'}")
    # [9] manifest: cấu trúc theo phiên bản (1.0: KT; 1.1: LAI – bắt buộc hồ sơ ký, phạm vi, mô tả chữ ký pháp lý)
    base_ok = all(k in m for k in ("artifact", "agent", "authority", "action", "timestamp", "signature", "audit"))
    if mver == "1.0":
        man_ok, man_note = base_ok and profile == "KT", "Cấu trúc manifest 1.0 (hồ sơ KT)"
        if profile != "KT":
            man_note += f" – hồ sơ {profile} phải dùng manifest 1.1"
    elif mver == "1.1":
        ls = meta.get("legal_signature") or {}
        man_ok = base_ok and profile == "LAI" and bool(meta.get("scope")) and bool(ls.get("format")) and bool(ls.get("signer_serial"))
        man_note = "Cấu trúc manifest 1.1 (hồ sơ LAI: hồ sơ ký, phạm vi, mô tả chữ ký pháp lý trong phần đã ký)"
    elif mver == "1.2":                    # 1.10.0 – hồ sơ KT có chữ ký phê duyệt riêng của người duyệt (khai trong phần đã ký)
        ad = authority.get("approval") or {}
        man_ok = base_ok and profile == "KT" and institution_signed and all(ad.get(k) for k in (
            "statement_hash", "approver_key_fingerprint", "certificate_id", "policy_hash", "authority"))
        man_note = "Cấu trúc manifest 1.2 (hồ sơ KT có chữ ký phê duyệt riêng của người duyệt trong phần đã ký)"
        if not man_ok:
            man_note += " – thiếu khai báo phê duyệt riêng (authority.approval)"
    else:
        man_ok, man_note = False, f"Phiên bản manifest {mver or '(trống)'} không được bộ kiểm {VERIFIER_VERSION} hỗ trợ"
    if bver not in BUNDLE_VERSIONS:
        man_ok, man_note = False, f"Phiên bản gói bằng chứng {bver} không được hỗ trợ"
    add(8, man_ok, man_note)
    # [10] chuỗi kiểm toán: tái tính từ bản ghi đầu tiên; bản ghi của hiện vật khớp băm, chữ ký, manifest
    recs = bundle.get("audit") or []
    prev, chain_ok, why = GENESIS, True, "Chuỗi hợp lệ"
    for r in recs:
        if r.get("previous_hash") != prev or _sha(_canonical(r.get("record")) + prev.encode()) != r.get("record_hash"):
            chain_ok, why = False, f"Đứt chuỗi tại {r.get('record_id')}"
            break
        prev = r["record_hash"]
    mine = next((r for r in recs if r.get("record_id") == (m.get("audit") or {}).get("record_id")), None)
    if chain_ok:
        rec = (mine or {}).get("record") or {}
        chain_ok = bool(mine) and mine.get("record_hash") == (m.get("audit") or {}).get("record_hash") and \
            rec.get("artifact_hash") == (m.get("artifact") or {}).get("sha256") and \
            rec.get("manifest_core_hash") == _sha(_canonical(core)) and rec.get("signature_hash") == _sha(msig)
        if not chain_ok:
            why = "Bản ghi kiểm toán của hiện vật không khớp manifest/chữ ký"
    add(9, chain_ok, f"{why} ({len(recs)} bản ghi)")
    # [11] hồ sơ LAI: chữ ký pháp lý (PAdES) trên CÙNG tệp – thêm theo SEC-01 mục 11
    pl = None
    if profile == "LAI" or mver == "1.1":
        ls = meta.get("legal_signature") or {}
        if legal_result is not None:
            pl = legal_result
        elif content is None:
            pl = {"result": "invalid", "detail": "Không có tệp hiện vật"}
        else:
            pl = legal_check_offline(content, pl_roots_pem, ls)
        st = {"valid": True, "invalid": False}.get(pl.get("result"), "?")
        add(10, st, f"Chữ ký pháp lý ({ls.get('format') or 'PAdES'}; người ký {ls.get('signer') or pl.get('signer') or '?'}): "
                    f"{pl.get('result')} – {pl.get('detail')}")

    statuses = [c["status"] for c in checks]
    conclusion = "invalid" if "FAIL" in statuses else ("indeterminate" if "INDETERMINATE" in statuses else "valid")
    kt_ok = all(c["status"] in ("OK", "N/A") for c in checks if c["step"] <= 10)
    tsts = []
    for x in bundle.get("timestamps") or []:
        try:
            info = tst_info(_b64(x.get("token")))
            ok = info["imprint"] == hashlib.new(_DIGESTS.get(info["imprint_alg"], "sha256"), msig).hexdigest() and info["econtent_digest_ok"]
            tsts.append({"tsa": x.get("tsa_url"), "gen_time": info["gen_time"].isoformat() if info["gen_time"] else None,
                         "imprint_matches_signature": ok, "serial": info["serial"],
                         "note": "Kiểm khớp dấu băm chữ ký; chữ ký và chuỗi chứng thư của TSA kiểm bằng «openssl ts -verify» với kho gốc của TSA"})
        except (ValueError, IndexError, KeyError) as e:
            tsts.append({"tsa": x.get("tsa_url"), "imprint_matches_signature": False, "note": f"Không đọc được dấu thời gian: {e}"})
    return {"result": conclusion.upper(), "conclusion": conclusion, "verifier_version": VERIFIER_VERSION,
            "bundle_version": bver, "manifest_version": mver, "sig_profile": profile,
            "cryptographic_validity": all(c["status"] == "OK" for c in checks if c["step"] in (2, 7, 8, 10)),
            "authority_validity": all(c["status"] in ("OK", "N/A") for c in checks if c["step"] in (1, 3, 4, 5, 6)),
            "kt_validity": kt_ok, "legal_validity": (pl or {}).get("result") if pl else None,
            "anchor_pinned": trusted is not None,
            "independent": False,
            "independence_note": (f"Bộ máy xác minh ({engine_info(engine)}) cùng nguồn gốc {SIGNING_ENGINE_ORIGIN} với bộ máy ký – đây là bộ kiểm "
                                  "chứng 10 bước, chưa phải «xác minh độc lập» (SEC-01 mục 11b, D-80)"),
            "scope_statement": {"profile": profile, "text": meta.get("scope") or (SCOPE_LAI if profile == "LAI" else SCOPE_KT),
                                "declared_in_manifest": bool(meta.get("scope")),
                                "template_status": "Mẫu tuyên bố DỰ THẢO – chờ ban hành cùng chính sách chữ ký số (D-78)"},
            "timestamps": tsts,
            # 1.10.0 – mức định danh người ký (không gộp với kết luận mật mã) và thời điểm ký được chứng minh độc lập
            "identity": identity_level(bundle, trusted, t, identity_evidence, engine, pl_roots_pem=pl_roots_pem),
            "time_evidence": {"signed_at_declared": m.get("timestamp"),
                              "proven_not_after": tproof["proven"].isoformat() if tproof["proven"] else None,
                              "source": tproof["source"], "notes": tproof["notes"]},
            "approver_signature": bool(authority.get("approval")) if institution_signed else None,
            "artifact": (m.get("artifact") or {}).get("artifact_id"), "engine": engine_info(engine), "checks": checks}


def report(result: dict) -> str:
    lines = ["=" * 40, "AI AGENT TRUST VERIFICATION", "=" * 40]
    for c in result["checks"]:
        mark = {"OK": "OK", "N/A": "--", "FAIL": "X ", "INDETERMINATE": "? "}[c["status"]]
        lines.append(f"[{c['step']}] {c['name']}\n    {mark} {c['detail']}")
    for x in result.get("timestamps") or []:
        lines.append(f"[TSA] {x.get('tsa')} {x.get('gen_time')} – khớp chữ ký: {'có' if x.get('imprint_matches_signature') else 'KHÔNG'}")
    te = result.get("time_evidence") or {}
    if te.get("proven_not_after"):
        lines.append(f"[Thời điểm] chữ ký có trước {te['proven_not_after']} – chứng minh độc lập: {te.get('source')}")
    idn = result.get("identity") or {}
    lines += ["=" * 40, f"TRUST RESULT: {result['result']}",
              f"Signer identity (định danh người ký, tách khỏi kết quả mật mã): {idn.get('level', 'LIMITED')} – {idn.get('note', '')}"]
    for c in idn.get("channels") or []:
        lines.append(f"    kênh {c['channel']}: {'xác nhận' if c['confirms'] else 'không xác nhận'} – {c['detail']}")
    for k in ("certified", "legally_bound"):
        if (idn.get("criteria") or {}).get(k):
            lines.append(f"    {k}: {'có' if idn['criteria'][k]['ok'] else 'không'} – {idn['criteria'][k]['detail']}")
    lines += [
              f"Hồ sơ ký: {result.get('sig_profile', 'KT')} · manifest {result.get('manifest_version')} · gói {result.get('bundle_version')}",
              f"Phạm vi: {(result.get('scope_statement') or {}).get('text', '')}",
              f"Xác minh độc lập (D-80): {'có' if result.get('independent') else 'không – ' + str(result.get('independence_note', ''))}",
              f"Bộ máy xác minh: {result.get('engine', '')}", "=" * 40]
    return "\n".join(lines)


# ================================================================ 1.10.0 – luồng E: kiểm chứng độc lập, fail-closed, chữ ký lai, bằng chứng bao hàm Merkle
# (góp ý PQC 30/10/2026 mục 3, 4, 5, 7 – docs/dac-ta/ACI-OS-trust-v1.md, docs/MO-HINH-DE-DOA-TRUST-V1.md)
# - Bộ máy «noble»: @noble/post-quantum 0.7.1 (JavaScript thuần, MIT – khác nguồn gốc OpenSSL) chạy bằng Node ≥ 20; tệp đóng gói được GHIM mã băm
#   SHA-256 (sai mã băm → không dùng). Tìm tệp theo ACI_NOBLE_BUNDLE, cạnh công cụ, hoặc frontend/public/assets/vendor của kho mã.
# - Fail-closed: mọi ngoại lệ khi đọc gói → INVALID kèm lý do; thiếu bộ máy (OpenSSL, Node) → INDETERMINATE; không bao giờ VALID khi lỗi.
# - Base64 nghiêm ngặt (_b64), JSON nghiêm ngặt (loads_strict: cấm khóa trùng, NaN/Infinity), manifest từ 1.2 có số thực → bước 9 FAIL
#   (manifest 1.0/1.1 đã phát hành giữ nguyên kết luận – 1.11.0).
# - Chữ ký đồng hành cổ điển (ECDSA-P256) trên cùng manifest lõi: báo cáo riêng; require_hybrid=True thì bắt buộc hợp lệ.
# - Bằng chứng bao hàm Merkle (inclusion_proof): sự kiện ký → gốc khối → chuỗi khối → điểm chốt có chữ ký; thời điểm độc lập từ dấu thời gian
#   RFC 3161 của điểm chốt (kiểm chuỗi TSA khi có kho gốc TSA) hoặc từ kho nhân chứng (witness_checkpoints) → đưa vào time_proofs của bước 2.
ENGINES = ("cryptography", "openssl", "noble")
NOBLE_BUNDLE = "noble-post-quantum-0.7.1.js"
NOBLE_SHA256 = "c5dd0a4ff4778dabeba8248b4feeca502cebef16036814804ffed4404ee0c01b"
_NOBLE_JS = r"""
  // thụt lề có chủ ý: dòng trong chuỗi không bắt đầu ở cột 0 (kiểm thử «chỉ thư viện chuẩn» đếm dòng bắt đầu bằng import/from)
  const { pathToFileURL } = await import('node:url');
  let raw = '';
  for await (const c of process.stdin) raw += c;
  const inp = JSON.parse(raw);
  const noble = await import(pathToFileURL(inp.bundle).href);
  const dsa = (a) => noble['ml_dsa' + String(a || '').replace(/^ML-DSA-/, '')];
  const hex = (s) => Uint8Array.from((String(s || '').match(/../g) || []).map((x) => parseInt(x, 16)));
  const out = inp.items.map((it) => { try { return dsa(it.alg).verify(hex(it.sig), hex(it.msg), hex(it.pk), { context: hex(it.ctx) }) === true; }
                                     catch (e) { return false; } });
  process.stdout.write(JSON.stringify(out));
"""
_NOBLE: dict = {}


def noble_bundle_path() -> str | None:
    here = os.path.dirname(os.path.abspath(__file__))
    for p in (os.environ.get("ACI_NOBLE_BUNDLE", ""), os.path.join(here, NOBLE_BUNDLE),
              os.path.join(here, "..", "frontend", "public", "assets", "vendor", NOBLE_BUNDLE),
              os.path.join(here, "..", "..", "..", "frontend", "public", "assets", "vendor", NOBLE_BUNDLE)):
        if p and os.path.isfile(p):
            return os.path.abspath(p)
    return None


def _noble_ready() -> tuple[str, str]:
    node = os.environ.get("ACI_NODE") or shutil.which("node")
    path = noble_bundle_path()
    if not node or not path:
        raise RuntimeError(f"Bộ máy noble cần Node ≥ 20 và tệp {NOBLE_BUNDLE} (ACI_NOBLE_BUNDLE hoặc --noble-bundle)")
    if path not in _NOBLE:
        with open(path, "rb") as f:
            _NOBLE[path] = _sha(f.read())
    if _NOBLE[path] != NOBLE_SHA256:
        raise RuntimeError(f"Tệp {NOBLE_BUNDLE} có SHA-256 {_NOBLE[path][:16]}… khác bản đã ghim {NOBLE_SHA256[:16]}… – không dùng")
    return node, path


def noble_verify_many(items: list[tuple[str, bytes, bytes, bytes, bytes]]) -> list[bool]:
    """items: (thuật toán, khóa công khai, thông điệp, chữ ký, ngữ cảnh) → danh sách kết quả của noble-post-quantum (một tiến trình Node)."""
    node, path = _noble_ready()
    payload = json.dumps({"bundle": path, "items": [{"alg": a, "pk": pk.hex(), "msg": m.hex(), "sig": s.hex(), "ctx": c.hex()}
                                                     for a, pk, m, s, c in items]})
    try:
        r = subprocess.run([node, "--input-type=module", "-e", _NOBLE_JS], input=payload.encode(), capture_output=True, timeout=300)
    except (OSError, subprocess.TimeoutExpired) as e:
        raise RuntimeError(f"Không chạy được Node: {e}") from e
    if r.returncode != 0:
        raise RuntimeError("Node lỗi khi chạy noble-post-quantum: " + r.stderr.decode("utf-8", "replace")[:200])
    out = json.loads(r.stdout)
    if not isinstance(out, list) or len(out) != len(items):
        raise RuntimeError("Kết quả noble-post-quantum không đúng định dạng")
    return [x is True for x in out]


def _noble_verify(alg: str, pk: bytes, msg: bytes, sig: bytes) -> bool:
    return noble_verify_many([(alg, pk, msg, sig, CONTEXT)])[0]


def noble_info() -> str:
    try:
        node, path = _noble_ready()
        v = subprocess.run([node, "--version"], capture_output=True, text=True).stdout.strip()
        return f"noble-post-quantum 0.7.1 (JavaScript, MIT; tệp đã ghim SHA-256 {NOBLE_SHA256[:16]}…) trên Node {v}"
    except (RuntimeError, OSError) as e:
        return f"noble-post-quantum (không dùng được: {e})"


# ---------------------------------------------------------------- chữ ký cổ điển (Ed25519, ECDSA-P256): cryptography nếu có, không thì dòng lệnh OpenSSL
_CLASSICAL_OID = {"Ed25519": ("1.3.101.112", None), "ECDSA-P256": ("1.2.840.10045.2.1", "1.2.840.10045.3.1.7")}


def _oid_tlv(dotted: str) -> bytes:
    p = [int(x) for x in dotted.split(".")]
    body = bytes([40 * p[0] + p[1]])
    for v in p[2:]:
        enc = [v & 0x7F]
        v >>= 7
        while v:
            enc.append(0x80 | (v & 0x7F))
            v >>= 7
        body += bytes(reversed(enc))
    return b"\x06" + _der_len(len(body)) + body


def classical_spki_pem(alg: str, pk: bytes) -> bytes:
    oid, curve = _CLASSICAL_OID[alg]
    algid_body = _oid_tlv(oid) + (_oid_tlv(curve) if curve else b"")
    algid = b"\x30" + _der_len(len(algid_body)) + algid_body
    bits = b"\x03" + _der_len(len(pk) + 1) + b"\x00" + pk
    der = b"\x30" + _der_len(len(algid) + len(bits)) + algid + bits
    b64 = base64.b64encode(der).decode()
    return ("-----BEGIN PUBLIC KEY-----\n" + "\n".join(b64[i:i + 64] for i in range(0, len(b64), 64)) + "\n-----END PUBLIC KEY-----\n").encode()


def _classical_verify(alg: str, pk: bytes, msg: bytes, sig: bytes) -> bool:
    if alg not in _CLASSICAL_OID or not pk or not sig:
        return False
    try:
        from cryptography.exceptions import InvalidSignature
        from cryptography.hazmat.primitives import hashes
        from cryptography.hazmat.primitives.asymmetric import ec
        from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
    except ImportError:
        if alg == "ECDSA-P256":
            code, out = _openssl_run(["dgst", "-sha256", "-verify", "pub.pem", "-signature", "sig.bin", "msg.bin"],
                                     {"pub.pem": classical_spki_pem(alg, pk), "msg.bin": msg, "sig.bin": sig})
            return code == 0 and b"Verified OK" in out
        code, out = _openssl_run(["pkeyutl", "-verify", "-pubin", "-inkey", "pub.pem", "-rawin", "-in", "msg.bin", "-sigfile", "sig.bin"],
                                 {"pub.pem": classical_spki_pem(alg, pk), "msg.bin": msg, "sig.bin": sig})
        return code == 0 and b"Signature Verified Successfully" in out
    try:
        if alg == "Ed25519":
            Ed25519PublicKey.from_public_bytes(pk).verify(sig, msg)
        else:
            ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), pk).verify(sig, msg, ec.ECDSA(hashes.SHA256()))
        return True
    except (InvalidSignature, ValueError, TypeError):
        return False


# ---------------------------------------------------------------- JSON, gói bằng chứng nghiêm ngặt
def _no_dup(pairs):
    out = {}
    for k, v in pairs:
        if k in out:
            raise ValueError(f"JSON có khóa trùng «{k}» – hai bộ phân tích có thể hiểu khác nhau")
        out[k] = v
    return out


def _no_const(c):
    raise ValueError(f"JSON có hằng {c} (không thuộc JSON chuẩn)")


def loads_strict(data):
    """JSON nghiêm ngặt: cấm khóa trùng, cấm NaN/Infinity, chuỗi phải mã hóa được UTF-8 (không có nửa cặp thay thế)."""
    if isinstance(data, (bytes, bytearray)):
        data = bytes(data).decode("utf-8")
    obj = json.loads(data, object_pairs_hook=_no_dup, parse_constant=_no_const)
    json.dumps(obj, ensure_ascii=False).encode("utf-8")
    return obj


def _floats(obj, path: str = "$") -> list[str]:
    if isinstance(obj, float):
        return [path]
    if isinstance(obj, dict):
        return [p for k, v in obj.items() for p in _floats(v, f"{path}.{k}")]
    if isinstance(obj, list):
        return [p for i, v in enumerate(obj) for p in _floats(v, f"{path}[{i}]")]
    return []


def load_bundle_zip(data: bytes, max_total: int = 512 * 1024 * 1024) -> tuple[dict, bytes]:
    """Đọc gói .zip (manifest.json, evidence.json, tệp hiện vật) – nghiêm ngặt: tên tệp không trùng, JSON nghiêm ngặt, tổng dung lượng giải nén có
    giới hạn, tệp hiện vật đúng tên ghi trong manifest. Lỗi → ValueError (bên gọi kết luận INVALID)."""
    import io
    import zipfile
    try:
        z = zipfile.ZipFile(io.BytesIO(data))
    except zipfile.BadZipFile as e:
        raise ValueError(f"Không phải tệp zip hợp lệ: {e}") from e
    with z:
        infos = z.infolist()
        names = [i.filename for i in infos]
        if len(names) != len(set(names)):
            raise ValueError("Gói có hai tệp trùng tên")
        if sum(i.file_size for i in infos) > max_total:
            raise ValueError("Gói vượt dung lượng giải nén cho phép")
        if "manifest.json" not in names or "evidence.json" not in names:
            raise ValueError("Gói thiếu manifest.json hoặc evidence.json")
        manifest, evidence = loads_strict(z.read("manifest.json")), loads_strict(z.read("evidence.json"))
        if not isinstance(manifest, dict) or not isinstance(evidence, dict):
            raise ValueError("manifest.json, evidence.json phải là đối tượng JSON")
        fn = (manifest.get("artifact") or {}).get("filename") if isinstance(manifest.get("artifact"), dict) else None
        if not isinstance(fn, str) or fn in ("manifest.json", "evidence.json") or fn not in names:
            raise ValueError("Không tìm thấy tệp hiện vật đúng tên ghi trong manifest")
        content = z.read(fn)
    return {**evidence, "manifest": manifest}, content


# ---------------------------------------------------------------- chữ ký đồng hành (chữ ký lai)
COMPANION_CERT_TYPE = "COMPANION_KEY_CERTIFICATION"


def check_companions(bundle: dict, core_bytes: bytes, trusted: set | None, companion_pins: set | None, engine: str = "auto") -> dict:
    """Chữ ký cổ điển đồng hành trên manifest lõi chuẩn hóa. Khóa đồng hành được tin khi người kiểm ghim dấu vân tay của nó, hoặc tuyên bố
    «COMPANION_KEY_CERTIFICATION» có chữ ký hợp lệ của một neo được ghim. Kết quả: valid | invalid | unverified (khóa chưa được tin) | absent."""
    items = []
    anchors = {}
    ba = bundle.get("anchor") or {}
    if isinstance(ba, dict) and ba.get("fingerprint"):
        anchors[ba["fingerprint"]] = ba
    for c in bundle.get("companion_signatures") or []:
        alg, pk, sig = c.get("algorithm"), _b64(c.get("public_key")), _b64(c.get("signature"))
        fp_ok = bool(pk) and _sha(pk) == c.get("key_fingerprint")
        sig_ok = fp_ok and alg in _CLASSICAL_OID and _classical_verify(alg, pk, core_bytes, sig)
        cert = c.get("certification") or {}
        st = cert.get("statement") or {}
        trusted_key, why = False, "khóa đồng hành chưa được tin (không ghim, không có chứng nhận của neo được ghim)"
        if companion_pins and c.get("key_fingerprint") in companion_pins:
            trusted_key, why = True, "dấu vân tay khóa đồng hành được ghim"
        else:
            afp = cert.get("anchor_fingerprint")
            a = cert.get("anchor_public_key") or anchors.get(afp) or {}     # neo đã chứng nhận (có thể là neo trước khi xoay vòng)
            apk = _b64(a.get("value"))
            if st.get("type") == COMPANION_CERT_TYPE and (st.get("companion_key") or {}).get("fingerprint") == c.get("key_fingerprint") and \
                    st.get("anchor_fingerprint") == afp and apk and _sha(apk) == afp and (trusted is None or afp in trusted) and \
                    _verify_sig(a.get("algorithm", ""), apk, _canonical(st), _b64(cert.get("signature")), engine):
                trusted_key = True
                why = f"neo {afp[:16]}… chứng nhận khóa đồng hành" + ("" if trusted else " (neo chưa được ghim)")
        status = "invalid" if not sig_ok else ("valid" if trusted_key else "unverified")
        items.append({"algorithm": alg, "key_fingerprint": c.get("key_fingerprint"), "status": status,
                      "detail": (f"chữ ký {alg} {'VALID' if sig_ok else 'INVALID'} trên manifest lõi; {why}")})
    if not items:
        return {"status": "absent", "items": [], "detail": "Gói không có chữ ký đồng hành (hiện vật ký trước 1.10.0 hoặc chính sách lai tắt)"}
    st = "invalid" if any(i["status"] == "invalid" for i in items) else ("valid" if any(i["status"] == "valid" for i in items) else "unverified")
    return {"status": st, "items": items, "detail": "; ".join(i["detail"] for i in items)}


# ---------------------------------------------------------------- bằng chứng bao hàm Merkle (sự kiện ký → khối → điểm chốt)
def _merkle_sides(index: int, count: int) -> list[tuple[str, bool]]:
    """(bên của nút anh em, có phải nhân đôi chính nó) từ lá tới gốc theo quy tắc lẻ thì nhân đôi phần tử cuối."""
    out, i, n = [], index, count
    while n > 1:
        dup = n % 2 == 1 and i == n - 1
        if n % 2:
            n += 1
        out.append(("L" if (i ^ 1) < i else "R", dup))
        i //= 2
        n //= 2
    return out


def verify_inclusion(proof, manifest: dict, trusted: set | None, engine: str = "auto", *, anchor_ok_fp: str | None = None,
                     tsa_roots_pem: bytes | None = None, witness_checkpoints: dict | None = None) -> dict:
    """Kiểm bằng chứng bao hàm. Trả {status: valid | invalid | pending | absent, binding: signature | content, checkpoint_seq, proven_not_after,
    time_source, problems}. Thời điểm độc lập: dấu thời gian RFC 3161 của điểm chốt (cần kho gốc TSA) hoặc thời điểm nhân chứng thấy điểm chốt."""
    if not proof:
        return {"status": "absent", "detail": "Gói không mang bằng chứng bao hàm (gói trước 1.10.0)"}
    if not isinstance(proof, dict):
        return {"status": "invalid", "problems": ["bằng chứng bao hàm không đúng định dạng"]}
    if proof.get("status") != "complete":
        return {"status": "pending" if str(proof.get("status", "")).startswith("pending") else "absent",
                "detail": str(proof.get("detail") or proof.get("status"))}
    try:
        return _verify_inclusion(proof, manifest, trusted, engine, anchor_ok_fp, tsa_roots_pem, witness_checkpoints)
    except RuntimeError:
        raise
    except Exception as e:  # noqa: BLE001 – bằng chứng hỏng là KHÔNG HỢP LỆ, không văng lỗi
        return {"status": "invalid", "problems": [f"bằng chứng bao hàm không đúng định dạng: {type(e).__name__}: {str(e)[:150]}"]}


def _verify_inclusion(proof: dict, manifest: dict, trusted, engine, anchor_ok_fp, tsa_roots_pem, witness_checkpoints) -> dict:
    probs: list[str] = []
    m = manifest or {}
    core = {k: v for k, v in m.items() if k not in ("signature", "audit")}
    msig = _b64((m.get("signature") or {}).get("value"))
    leaf, mk, blocks, env = proof.get("leaf") or {}, proof.get("merkle") or {}, proof.get("blocks") or [], proof.get("checkpoint") or {}
    # [a] lá = băm sự kiện ký; nội dung sự kiện gắn với hiện vật
    raw = f"{leaf.get('payload_text')}|{leaf.get('type')}|{leaf.get('stream_id')}|{leaf.get('stream_version')}".encode("utf-8")
    if not isinstance(leaf.get("payload_text"), str) or _sha(raw) != leaf.get("digest"):
        probs.append("băm sự kiện ký không khớp nội dung sự kiện")
    payload = loads_strict(leaf.get("payload_text") or "{}")
    art = m.get("artifact") or {}
    if leaf.get("type") != "trust.artifact.signed" or leaf.get("stream_id") != f"trust/artifact/{art.get('artifact_id')}":
        probs.append("sự kiện không phải sự kiện ký của hiện vật này")
    if payload.get("sha256") != art.get("sha256"):
        probs.append("sự kiện ghi mã băm hiện vật khác")
    binding = "content"
    if payload.get("signature_hash") or payload.get("manifest_core_hash"):
        if payload.get("signature_hash") != _sha(msig) or payload.get("manifest_core_hash") != _sha(_canonical(core)):
            probs.append("sự kiện ghi băm chữ ký/manifest lõi khác")
        else:
            binding = "signature"
    # [b] đường đi Merkle tới gốc khối
    h, path = bytes.fromhex(str(leaf.get("digest") or "00")), mk.get("path") or []
    try:
        sides = _merkle_sides(int(mk.get("index")), int(mk.get("leaf_count")))
    except (TypeError, ValueError):
        sides = None
    if mk.get("algorithm") != "sha256-merkle/dup-last/1" or sides is None or len(sides) != len(path):
        probs.append("đường đi Merkle sai độ dài hoặc thuật toán")
    else:
        for (side, dup), step in zip(sides, path):
            sib = bytes.fromhex(str(step.get("hash")))
            if step.get("side") != side or (dup and sib != h):
                probs.append("đường đi Merkle sai vị trí nút")
                break
            h = hashlib.sha256(sib + h).digest() if side == "L" else hashlib.sha256(h + sib).digest()
        if h.hex() != mk.get("root"):
            probs.append("gốc Merkle tính lại không khớp")
    # [c] chuỗi khối từ khối chứa sự kiện tới khối điểm chốt ghi
    if not blocks or blocks[0].get("root_digest") != mk.get("root") or blocks[0].get("member_count") != mk.get("leaf_count"):
        probs.append("khối đầu không chứa gốc Merkle này")
    for j, b in enumerate(blocks):
        bh = _sha(f"{b.get('block_no')}|{b.get('prior_block_hash')}|{b.get('root_digest')}|{b.get('member_count')}".encode())
        if bh != b.get("block_hash"):
            probs.append(f"băm khối #{b.get('block_no')} không khớp")
            break
        if j and (b.get("prior_block_hash") != blocks[j - 1].get("block_hash") or b.get("block_no") != blocks[j - 1].get("block_no") + 1):
            probs.append(f"khối #{b.get('block_no')} không nối khối trước")
            break
    # [d] điểm chốt có chữ ký ghi khối cuối
    doc, cm = env.get("checkpoint") or {}, env.get("manifest") or {}
    sb = ((doc.get("ledger") or {}).get("sealed_block") or {})
    if not blocks or sb.get("block_hash") != blocks[-1].get("block_hash") or sb.get("block_no") != blocks[-1].get("block_no"):
        probs.append("điểm chốt không ghi khối cuối của chuỗi")
    if doc.get("type") != "ACI-SV11-CHECKPOINT" or _sha(_canonical(doc)) != env.get("sha256") or env.get("sha256") != (cm.get("artifact") or {}).get("sha256"):
        probs.append("nội dung điểm chốt không khớp mã băm đã ký")
    cpk = env.get("public_key") or {}
    ck = _b64(cpk.get("value"))
    ccore = {k: v for k, v in cm.items() if k not in ("signature", "audit")}
    csig = _b64((cm.get("signature") or {}).get("value"))
    sig_ok = bool(ck) and _sha(ck) == cpk.get("fingerprint") == (cm.get("agent") or {}).get("public_key_fingerprint") and \
        (cm.get("signature") or {}).get("algorithm") == cpk.get("algorithm") and _verify_sig(cpk.get("algorithm", ""), ck, _canonical(ccore), csig, engine)
    if not sig_ok:
        probs.append("chữ ký của điểm chốt không hợp lệ")
    pinned = cpk.get("fingerprint") in (trusted or set()) or (cpk.get("fingerprint") == anchor_ok_fp and anchor_ok_fp is not None)
    out = {"binding": binding, "checkpoint_seq": env.get("seq"), "checkpoint_day": env.get("day"), "checkpoint_sha256": env.get("sha256"),
           "checkpoint_key": cpk.get("fingerprint"), "blocks": len(blocks), "proven_not_after": None, "time_source": None}
    if probs:
        return {**out, "status": "invalid", "problems": probs}
    if not pinned:
        return {**out, "status": "unverified", "problems": ["khóa ký điểm chốt không thuộc neo được ghim"]}
    times: list[tuple[datetime, str]] = []
    for x in env.get("timestamps") or []:
        try:
            info = tst_info(_b64(x.get("token")))
        except (ValueError, IndexError, KeyError, TypeError):
            continue
        if info["imprint"] != hashlib.new(_DIGESTS.get(info["imprint_alg"], "sha256"), csig).hexdigest() or not info["gen_time"]:
            continue
        if tsa_roots_pem:
            ok, _why = _tsa_openssl(_b64(x.get("token")), info["imprint"], tsa_roots_pem)
            if ok:
                times.append((info["gen_time"], f"dấu thời gian RFC 3161 của điểm chốt #{env.get('seq')} ({x.get('tsa_url') or 'TSA'})"))
    w = (witness_checkpoints or {}).get(env.get("seq")) or (witness_checkpoints or {}).get(str(env.get("seq")))
    if w and w.get("sha256") == env.get("sha256") and _ts(w.get("first_seen")):
        times.append((_ts(w["first_seen"]), f"nhân chứng {w.get('source') or 'bên ngoài'} thấy điểm chốt #{env.get('seq')}"))
    if times:
        t, src = min(times, key=lambda x: x[0])
        out.update(proven_not_after=t.isoformat(), time_source=src)
    return {**out, "status": "valid", "problems": [],
            "detail": f"hiện vật nằm trong sổ cái SV-11 trước điểm chốt #{env.get('seq')} ({env.get('day')})" +
                      (f"; có trước {out['proven_not_after']} ({out['time_source']})" if out["proven_not_after"] else
                       "; chưa có thời điểm độc lập (cần kho gốc TSA hoặc kho nhân chứng)")}


# ---------------------------------------------------------------- bộ kiểm fail-closed (bọc verify_bundle ở trên)
_verify_bundle_core = verify_bundle


def _fail_result(conclusion: str, why: str, engine: str) -> dict:
    st = "INDETERMINATE" if conclusion == "indeterminate" else "FAIL"
    try:
        eng = engine_info(engine)
    except Exception:  # noqa: BLE001
        eng = str(engine)
    return {"result": conclusion.upper(), "conclusion": conclusion, "verifier_version": VERIFIER_VERSION, "bundle_version": None,
            "manifest_version": None, "sig_profile": None, "cryptographic_validity": False, "authority_validity": False, "kt_validity": False,
            "legal_validity": None, "anchor_pinned": None, "independent": False, "independence_note": "", "scope_statement": {},
            "timestamps": [], "artifact": None, "engine": eng, "error": why,
            "checks": [{"step": 9, "name": STEPS[8], "status": st, "detail": why}]}


def _engine_str(engine: str) -> str:
    return noble_info() if engine == "noble" else engine_info(engine)


def verify_bundle(bundle, content, trusted_anchor_fingerprint=None, engine: str = "auto", *, require_hybrid: bool = False,
                  companion_pins=None, witness_checkpoints: dict | None = None, **kw) -> dict:
    """Bộ kiểm 10 (11) bước, FAIL-CLOSED (1.10.0 – luồng E). Tham số thêm: require_hybrid – bắt buộc chữ ký đồng hành cổ điển hợp lệ (chính sách
    lai «require» đã phê duyệt); companion_pins – dấu vân tay khóa đồng hành được ghim; witness_checkpoints – {seq: {sha256, first_seen, source}}
    từ kho nhân chứng của người kiểm (tools/aci_witness.py) để chứng minh thời điểm qua bằng chứng bao hàm Merkle."""
    resolve_engine(engine)                                 # bộ máy không hỗ trợ là lỗi của bên gọi – ném ValueError
    try:
        if not isinstance(bundle, dict):
            raise ValueError("gói bằng chứng phải là đối tượng JSON")
        m = bundle.get("manifest")
        if not isinstance(m, dict):
            raise ValueError("thiếu manifest")
        if isinstance(trusted_anchor_fingerprint, str):
            trusted = {x.strip() for x in trusted_anchor_fingerprint.split(",") if x.strip()} or None
        else:
            trusted = set(trusted_anchor_fingerprint) if trusted_anchor_fingerprint else None
        anchor = bundle.get("anchor") if isinstance(bundle.get("anchor"), dict) else {}
        a_fp = anchor.get("fingerprint") if (trusted is not None and anchor.get("fingerprint") in trusted) else None
        inc = verify_inclusion(bundle.get("inclusion_proof"), m, trusted, engine, anchor_ok_fp=a_fp, tsa_roots_pem=kw.get("tsa_roots_pem"),
                               witness_checkpoints=witness_checkpoints)
        tp = list(kw.pop("time_proofs", None) or [])
        if inc.get("status") == "valid" and inc.get("binding") == "signature" and inc.get("proven_not_after"):
            tp.append({"time": inc["proven_not_after"], "source": "bằng chứng bao hàm Merkle – " + str(inc.get("time_source")),
                       "covers_signature_sha256": _sha(_b64((m.get("signature") or {}).get("value")))})
        r = _verify_bundle_core(bundle, content, trusted_anchor_fingerprint, engine, time_proofs=tp or None, **kw)
        core = {k: v for k, v in m.items() if k not in ("signature", "audit")}
        # 1.11.0: quy tắc «không số thực» của trust/v1 chỉ áp cho manifest từ 1.2 – manifest 1.0/1.1 đã phát hành (ví dụ vị trí chữ ký văn
        # thư 1.8.0 ghi tọa độ thập phân) vẫn tái lập được JSON chuẩn hóa ở máy chủ, không được hồi tố thành «không hợp lệ».
        fl = _floats(m) if str(m.get("manifest_version") or "") not in ("1.0", "1.1") else []
        sig_b, aud_b = m.get("signature"), m.get("audit")
        extra = [] if isinstance(sig_b, dict) and isinstance(aud_b, dict) else ["khối signature/audit không phải đối tượng"]
        if not extra:
            extra += [f"signature.{k}" for k in sig_b if k not in ("algorithm", "value")]
            extra += [f"audit.{k}" for k in aud_b if k not in ("record_id", "previous_hash", "record_hash")]
        for c in r["checks"]:
            if c["step"] == 9 and fl:
                c["status"], c["detail"] = "FAIL", c["detail"] + f" – có số thực trong manifest ({', '.join(fl[:3])}): định dạng trust/v1 cấm"
            if c["step"] == 9 and extra:
                c["status"], c["detail"] = "FAIL", c["detail"] + f" – trường lạ ngoài phần đã ký ({', '.join(extra[:3])}): định dạng trust/v1 cấm"
            if c["step"] == 10 and c["status"] == "OK" and isinstance(aud_b, dict):
                recs = bundle.get("audit") or []
                mine = next((x for x in recs if isinstance(x, dict) and x.get("record_id") == aud_b.get("record_id")), {})
                if mine.get("previous_hash") != aud_b.get("previous_hash"):
                    c["status"], c["detail"] = "FAIL", "Mã băm bản ghi trước ghi trong manifest khác bản ghi kiểm toán của hiện vật"
                # trường ngoài phần được băm của từng bản ghi (số thứ tự, mã bản ghi) phải khớp – không để sửa im lặng
                elif any(not isinstance(x, dict) or set(x) - {"seq", "record_id", "previous_hash", "record", "record_hash"} or
                         x.get("record_id") != (x.get("record") or {}).get("record_id") or x.get("seq") != i + 1
                         for i, x in enumerate(recs)):
                    c["status"], c["detail"] = "FAIL", "Bản ghi kiểm toán có số thứ tự/mã bản ghi ngoài phần băm không khớp nội dung đã băm"
        comp = check_companions(bundle, _canonical(core), trusted, set(companion_pins or []), engine)
        r["hybrid"] = {**comp, "required": bool(require_hybrid)}
        if require_hybrid:
            r["checks"].append({"step": 12, "name": "Hybrid Signature", "status": "OK" if comp["status"] == "valid" else "FAIL",
                                "detail": "Chữ ký đồng hành cổ điển (bắt buộc theo chính sách lai): " + comp["detail"]})
        if inc.get("status") == "invalid":
            r["checks"].append({"step": 13, "name": "Inclusion Proof", "status": "FAIL",
                                "detail": "Bằng chứng bao hàm Merkle trong gói không hợp lệ: " + "; ".join(inc.get("problems") or [])})
        r["inclusion"] = inc
        st = [c["status"] for c in r["checks"]]
        r["conclusion"] = "invalid" if "FAIL" in st else ("indeterminate" if "INDETERMINATE" in st else "valid")
        r["result"] = r["conclusion"].upper()
        r["kt_validity"] = r["kt_validity"] and "FAIL" not in st
        r["cryptographic_validity"] = r["cryptographic_validity"] and "FAIL" not in st
        if resolve_engine(engine) == "noble":
            r["engine"] = noble_info()
            r["engine_origin"] = "noble-post-quantum (JavaScript) – khác nguồn gốc OpenSSL của bộ máy ký; SHA-256 vẫn qua hashlib của Python"
            r["independence_note"] = ("Chữ ký ML-DSA kiểm bằng noble-post-quantum – khác nguồn gốc OpenSSL của bộ máy ký; bộ máy này chưa qua kiểm định "
                                      "D-80 và SHA-256 vẫn qua hashlib của Python – chưa gọi là «xác minh độc lập» (SEC-01 mục 11b)")
        return r
    except RuntimeError as e:
        return _fail_result("indeterminate", f"Không xác minh được – thiếu bộ máy: {e}", engine)
    except Exception as e:  # noqa: BLE001 – fail-closed: gói hỏng/giả là KHÔNG HỢP LỆ có lý do, không văng lỗi, không bao giờ VALID
        return _fail_result("invalid", f"Gói bằng chứng không đúng định dạng: {type(e).__name__}: {str(e)[:200]}", engine)


def cross_verify(bundle, content, trusted_anchor_fingerprint=None, engines=("cryptography", "noble"), **kw) -> dict:
    """Chạy CÙNG gói với nhiều bộ máy (mặc định OpenSSL qua cryptography và noble-post-quantum). VALID chỉ khi mọi bộ máy cùng VALID và từng bước
    trùng nhau; có bộ máy INVALID → INVALID; còn lại INDETERMINATE (ví dụ thiếu Node)."""
    runs = []
    for e in engines:
        r = verify_bundle(bundle, content, trusted_anchor_fingerprint, e, **kw)
        runs.append({"engine": e, "engine_info": r.get("engine"), "result": r["result"],
                     "steps": {c["step"]: c["status"] for c in r["checks"]}, "verification": r})
    agree = len({x["result"] for x in runs}) == 1 and all(x["steps"] == runs[0]["steps"] for x in runs)
    res = [x["result"] for x in runs]
    final = "VALID" if agree and set(res) == {"VALID"} else ("INVALID" if "INVALID" in res else "INDETERMINATE")
    return {"result": final, "agree": agree, "engines": list(engines), "runs": runs}


_report_core = report


def report(result: dict) -> str:
    text = _report_core(result)
    extra = []
    if result.get("error"):
        extra.append(f"[Lỗi đọc gói] {result['error']}")
    hy = result.get("hybrid") or {}
    if hy:
        extra.append(f"[Chữ ký lai] {hy.get('status')}{' (bắt buộc)' if hy.get('required') else ' (chỉ ghi nhận)'} – {hy.get('detail', '')}")
    inc = result.get("inclusion") or {}
    if inc:
        extra.append(f"[Bao hàm Merkle] {inc.get('status')} – {inc.get('detail') or '; '.join(inc.get('problems') or [])}")
    if result.get("engine_origin"):
        extra.append(f"[Bộ máy] {result['engine_origin']}")
    return text + ("\n" + "\n".join(extra) if extra else "")


# ---------------------------------------------------------------- dòng lệnh
def _read_zip(path: str):
    with open(path, "rb") as f:                    # 1.10.0 – luồng E: đọc nghiêm ngặt (tên trùng, JSON khóa trùng/NaN → ValueError)
        return load_bundle_zip(f.read())


def witness_from_store(path: str) -> tuple[dict, list]:
    """Kho nhân chứng (tools/aci_witness.py) → ({seq: {sha256, first_seen, source}}, [điểm chốt đã công bố cho bước 2])."""
    import glob
    wc, pub = {}, []
    for st in glob.glob(os.path.join(path, "**", "state.json"), recursive=True):
        with open(st, encoding="utf-8") as f:
            s = json.load(f)
        for k, x in (s.get("seen") or {}).items():
            src = f"{s.get('witness') or 'nhân chứng'} ({s.get('origin')})"
            wc[int(k)] = {"sha256": x.get("sha256"), "first_seen": x.get("first_seen"), "source": src}
            if x.get("audit_head"):
                pub.append({"audit_seq": x.get("audit_seq"), "audit_head": x.get("audit_head"), "published_at": x.get("first_seen"), "source": src})
    return wc, pub


def anchors_from_file(path: str) -> tuple[list[str], list[dict]]:
    """anchor.json (/api/v1/trust/anchor) → (dấu vân tay để ghim: neo đang dùng, đã xoay vòng, đã thu hồi, khóa neo gốc; danh sách thu hồi)."""
    with open(path, encoding="utf-8") as f:
        a = json.load(f)
    fps = [a.get("fingerprint")] + [h.get("fingerprint") for h in (a.get("history") or []) + (a.get("revoked_anchors") or [])] + \
        [r.get("fingerprint") for r in a.get("root") or []]
    return [x for x in fps if x], list(a.get("revocations") or [])


def _fetch(src: str, timeout: float = 10.0) -> bytes:
    """Tệp cục bộ hoặc địa chỉ https:// (người xác minh TỰ lấy – không dùng địa chỉ do gói gợi ý)."""
    if src.startswith(("https://", "http://")):
        import urllib.request
        req = urllib.request.Request(src, headers={"User-Agent": "aci_verify/" + VERIFIER_VERSION})
        with urllib.request.urlopen(req, timeout=timeout) as r:          # noqa: S310 – địa chỉ do người xác minh nhập
            return r.read()
    with open(src, "rb") as f:
        return f.read()


def _qr_fingerprints(values: list[str]) -> list[str]:
    """Nội dung mã QR in trên văn bản («…/xac-minh/ART-…#neo=sha256:<dấu vân tay>») hoặc dấu vân tay trần."""
    out = []
    for v in values or []:
        m = re.search(r"([0-9a-f]{64})", v.lower())
        if m:
            out.append(m.group(1))
    return out


def main(argv=None) -> int:
    import argparse
    p = argparse.ArgumentParser(description="Kiểm chứng độc lập gói bằng chứng ACI-OS (chữ ký hậu lượng tử ML-DSA, chuỗi kiểm toán, LAI, "
                                            "định danh người ký, chữ ký phê duyệt riêng).")
    p.add_argument("bundle", help="Tệp .zip tải từ ACI-OS (Gói bằng chứng)")
    p.add_argument("--anchor", help="Dấu vân tay SHA-256 của neo tin cậy (nhiều: ngăn bằng dấu phẩy); có thể gồm khóa neo gốc – tính là kênh "
                                    "«bản ghi ghim» của người xác minh")
    p.add_argument("--anchor-file", help="Tệp anchor.json tải từ /api/v1/trust/anchor: neo tin cậy, khóa neo gốc, danh sách thu hồi")
    p.add_argument("--pl-roots", help="Kho chứng thư gốc (PEM) để kiểm chữ ký pháp lý của hồ sơ LAI – lấy từ nguồn chính thức của tổ chức chứng thực")
    p.add_argument("--engine", choices=("auto", "cryptography", "openssl", "noble"), default="auto",
                   help="Bộ máy xác minh ML-DSA: cryptography (OpenSSL qua Python), openssl (dòng lệnh OpenSSL ≥ 3.5) hoặc noble "
                        "(noble-post-quantum qua Node ≥ 20 – khác nguồn gốc OpenSSL)")
    # 1.10.0 – luồng E: chạy chéo nhiều bộ máy, kho nhân chứng, chữ ký lai
    p.add_argument("--cross", help="Chạy CÙNG gói với nhiều bộ máy, ví dụ cryptography,noble hoặc openssl,noble – VALID khi mọi bộ máy cùng VALID")
    p.add_argument("--noble-bundle", help="Đường dẫn tệp noble-post-quantum-0.7.1.js (mã băm phải đúng bản đã ghim)")
    p.add_argument("--witness-store", help="Thư mục kho của tools/aci_witness.py: thời điểm nhân chứng thấy điểm chốt chứng minh thời điểm ký")
    p.add_argument("--require-hybrid", action="store_true", help="Bắt buộc chữ ký đồng hành cổ điển (ECDSA-P256) hợp lệ")
    p.add_argument("--companion-pin", help="Dấu vân tay khóa đồng hành được ghim (nhiều: ngăn bằng dấu phẩy)")
    # 1.10.0 – định danh người ký (kênh công bố độc lập), vòng đời khóa
    p.add_argument("--domain", help="Tên miền chính thức của Nhà trường mà BẠN biết (ví dụ aci.nute.edu.vn): tải https://<tên miền>"
                                    "/.well-known/aci-trust.json và tra DNS TXT _aci-trust.<tên miền>")
    p.add_argument("--well-known", help="Tài liệu công bố đã tải (tệp hoặc địa chỉ https://…/.well-known/aci-trust.json)")
    p.add_argument("--dns-server", help="Máy chủ DNS dùng tra bản ghi TXT (mặc định: của hệ điều hành)")
    p.add_argument("--pin-file", help="Bản ghi ghim của bạn (JSON danh sách dấu vân tay, hoặc anchor.json đã lưu từ trước)")
    p.add_argument("--qr", action="append", default=[], help="Nội dung mã QR in trên văn bản giấy (đường dẫn có #neo=sha256:…)")
    p.add_argument("--key-statement", help="Tuyên bố khóa của Nhà trường đã ký số pháp lý (PDF) – cần --pl-roots để kiểm chữ ký pháp lý")
    p.add_argument("--revocation-list", help="Danh sách thu hồi có chữ ký (/api/v1/trust/revocations.json) – tệp hoặc địa chỉ https://")
    p.add_argument("--tsa-roots", help="Kho chứng thư gốc của TSA (PEM) để kiểm dấu thời gian RFC 3161 bằng «openssl ts -verify»")
    p.add_argument("--checkpoints", help="Danh sách điểm chốt đã công bố lấy từ nguồn độc lập (JSON: [{audit_seq, audit_head, published_at}])")
    p.add_argument("--json", action="store_true", help="In kết quả dạng JSON")
    a = p.parse_args(argv)
    import sys
    try:
        sys.stdout.reconfigure(encoding="utf-8")       # cửa sổ lệnh Windows mặc định không phải UTF-8
    except (AttributeError, ValueError):
        pass
    if a.noble_bundle:
        os.environ["ACI_NOBLE_BUNDLE"] = a.noble_bundle
    try:
        bundle, content = _read_zip(a.bundle)
    except (OSError, ValueError, KeyError) as e:
        print(f"TRUST RESULT: INVALID\nKhông đọc được gói bằng chứng: {e}")
        return 1
    pins = [x.strip() for x in (a.anchor or "").split(",") if x.strip()]
    own_pins = list(pins) + _qr_fingerprints(a.qr)
    revs: list = []
    if a.anchor_file:
        fps, revs = anchors_from_file(a.anchor_file)
        pins += fps
    if a.pin_file:
        with open(a.pin_file, encoding="utf-8") as f:
            pf = json.load(f)
        own_pins += [x for x in (pf if isinstance(pf, list) else anchors_from_file(a.pin_file)[0]) if isinstance(x, str)]
    pins += own_pins
    channels, notes = [], []
    if own_pins:
        channels.append({"channel": "pinned", "source": "--anchor/--pin-file/--qr", "fingerprints": own_pins})
    wk_src = a.well_known or (f"https://{a.domain}/.well-known/aci-trust.json" if a.domain else None)
    if wk_src:
        try:
            channels.append({"channel": "well-known", "source": wk_src, "document": json.loads(_fetch(wk_src))})
        except (OSError, ValueError) as e:
            notes.append(f"Không tải được tài liệu công bố {wk_src}: {e}")
    if a.domain:
        name = f"{DNS_PREFIX}.{a.domain.strip('.')}"
        txt = dns_txt(name, a.dns_server)
        if txt is None:
            notes.append(f"Không tra được DNS TXT {name} (không có mạng?) – kênh DNS không được tính")
        else:
            channels.append({"channel": "dns", "source": name, "txt": txt})
    ev = {"channels": channels}
    if a.key_statement:
        ev["key_statement"] = {"pdf": _fetch(a.key_statement)}
    if a.revocation_list:
        ok, entries, why = check_revocation_list(json.loads(_fetch(a.revocation_list)), set(pins) or None, a.engine)
        notes.append(("Đã dùng " if ok else "KHÔNG dùng ") + why)
        if ok:
            revs += entries
    roots = None
    if a.pl_roots:
        with open(a.pl_roots, "rb") as f:
            roots = f.read()
    tsa_roots = _fetch(a.tsa_roots) if a.tsa_roots else None
    cps = json.loads(_fetch(a.checkpoints)) if a.checkpoints else None
    if isinstance(cps, dict):
        cps = cps.get("items") or []
    kw = {"revocations": revs, "pl_roots_pem": roots, "identity_evidence": ev, "tsa_roots_pem": tsa_roots, "published_checkpoints": cps,
          "require_hybrid": a.require_hybrid, "companion_pins": [x.strip() for x in (a.companion_pin or "").split(",") if x.strip()]}
    if a.witness_store:
        wc, pub = witness_from_store(a.witness_store)
        kw["witness_checkpoints"] = wc
        kw["published_checkpoints"] = (cps or []) + pub
        notes.append(f"Kho nhân chứng {a.witness_store}: {len(wc)} điểm chốt đã lưu")
    if a.cross:
        engines = [x.strip() for x in a.cross.split(",") if x.strip()]
        x = cross_verify(bundle, content, pins or None, engines, **kw)
        result = x["runs"][0]["verification"]
        result["cross_engine"] = {"result": x["result"], "agree": x["agree"],
                                  "runs": [{k: r[k] for k in ("engine", "engine_info", "result", "steps")} for r in x["runs"]]}
        notes += [f"Bộ máy {r['engine']} ({r['engine_info']}): {r['result']}" for r in x["runs"]]
        notes.append(f"Chạy chéo {', '.join(engines)}: {'TRÙNG KẾT QUẢ' if x['agree'] else 'KHÁC KẾT QUẢ'} → {x['result']}")
        result["result"] = x["result"]
    else:
        try:
            result = verify_bundle(bundle, content, pins or None, a.engine, **kw)
        except RuntimeError as e:
            print(f"Không xác minh được: {e}")
            return 2
    result["notes"] = notes
    out = json.dumps(result, ensure_ascii=False, indent=2, default=str) if a.json else report(result) + "".join(f"\n- {n}" for n in notes)
    print(out)
    return {"VALID": 0, "INVALID": 1}.get(result["result"], 3)


if __name__ == "__main__":
    raise SystemExit(main())
