336 lines
13 KiB
Python
336 lines
13 KiB
Python
"""Bounded registry metadata and ZIP directory/necessary-text Range reads only."""
|
|
|
|
import base64
|
|
import datetime as dt
|
|
import hashlib
|
|
import json
|
|
import re
|
|
import struct
|
|
import urllib.error
|
|
import urllib.request
|
|
import zlib
|
|
from pathlib import Path
|
|
|
|
HERE = Path(__file__).resolve().parent
|
|
REGISTRY = "https://api.comfy.org/nodes/comfyui_controlnet_aux"
|
|
CDN = "https://cdn.comfy.org/fannovel16/comfyui_controlnet_aux/1.1.5/node.zip"
|
|
CORE = "https://api.github.com/repos/Comfy-Org/ComfyUI/"
|
|
|
|
|
|
def now():
|
|
return dt.datetime.now(dt.timezone.utc).isoformat()
|
|
|
|
|
|
def sha(raw):
|
|
return hashlib.sha256(raw).hexdigest()
|
|
|
|
|
|
def save(name, value):
|
|
with (HERE / name).open("x", encoding="utf-8") as stream:
|
|
json.dump(value, stream, ensure_ascii=False, indent=2)
|
|
stream.write("\n")
|
|
|
|
|
|
def request(key, url, limit, byte_range=None):
|
|
assert url.startswith((REGISTRY, CDN, CORE))
|
|
record = dict(
|
|
key=key,
|
|
requested_url=url,
|
|
started_at=now(),
|
|
range=byte_range,
|
|
maximum_body_bytes=limit,
|
|
acquisition="new HTTP read; not historical retrieval",
|
|
)
|
|
headers = {"User-Agent": "HEL-892-bounded-static-provenance", "Accept-Encoding": "identity"}
|
|
if byte_range:
|
|
headers["Range"] = byte_range
|
|
raw = b""
|
|
try:
|
|
with urllib.request.urlopen(
|
|
urllib.request.Request(url, headers=headers), timeout=20
|
|
) as response:
|
|
record.update(
|
|
status=response.status, final_url=response.url, headers=dict(response.headers)
|
|
)
|
|
if byte_range:
|
|
assert response.status == 206, (
|
|
"server ignored Range; body deliberately not downloaded"
|
|
)
|
|
raw = response.read(limit + 1)
|
|
assert len(raw) <= limit, "response exceeds bounded cap"
|
|
record["ok"] = True
|
|
except (OSError, ValueError, AssertionError) as exc:
|
|
record.update(ok=False, error=type(exc).__name__ + ": " + str(exc))
|
|
if isinstance(exc, urllib.error.HTTPError):
|
|
record.update(status=exc.code, headers=dict(exc.headers))
|
|
raw = exc.read(min(limit, 4096))
|
|
finally:
|
|
record.update(finished_at=now(), actual_body_bytes=len(raw), sha256=sha(raw))
|
|
with (HERE / "network" / f"{key}.body").open("xb") as stream:
|
|
stream.write(raw)
|
|
save(f"network/{key}.json", record)
|
|
assert record["ok"], record
|
|
return raw, record
|
|
|
|
|
|
def range_read(key, start, end):
|
|
raw, rec = request(key, CDN, end - start + 1, f"bytes={start}-{end}")
|
|
expected = f"bytes {start}-{end}/"
|
|
content_range = next(v for k, v in rec["headers"].items() if k.lower() == "content-range")
|
|
assert content_range.startswith(expected) and len(raw) == end - start + 1
|
|
tail_record = json.loads((HERE / "network/release-tail.json").read_text())
|
|
|
|
def header(r, k):
|
|
return next((v for n, v in r["headers"].items() if n.lower() == k), None)
|
|
|
|
assert header(rec, "etag") == header(tail_record, "etag")
|
|
assert content_range.rsplit("/", 1)[1] == header(tail_record, "content-range").rsplit("/", 1)[1]
|
|
return raw, rec
|
|
|
|
|
|
def parse_directory(raw, expected_count):
|
|
entries, pos = [], 0
|
|
while pos < len(raw):
|
|
h = struct.unpack_from("<4s6H3L5H2L", raw, pos)
|
|
assert h[0] == b"PK\x01\x02"
|
|
flags, method, crc, compressed, size = h[3], h[4], h[7], h[8], h[9]
|
|
nlen, elen, clen, offset = h[10], h[11], h[12], h[16]
|
|
name = raw[pos + 46 : pos + 46 + nlen].decode("utf-8" if flags & 2048 else "cp437")
|
|
assert not name.startswith("/") and ".." not in name.split("/")
|
|
entries.append(
|
|
dict(
|
|
name=name,
|
|
flags=flags,
|
|
method=method,
|
|
crc32=crc,
|
|
compressed_bytes=compressed,
|
|
bytes=size,
|
|
local_offset=offset,
|
|
)
|
|
)
|
|
pos += 46 + nlen + elen + clen
|
|
assert len(entries) == expected_count
|
|
assert len({e["name"] for e in entries}) == len(entries)
|
|
return entries
|
|
|
|
|
|
def unpack_member(entry, local_header, payload):
|
|
h = struct.unpack_from("<4s5H3L2H", local_header)
|
|
assert h[0] == b"PK\x03\x04" and h[3] == entry["method"]
|
|
assert h[2] == entry["flags"]
|
|
assert not h[2] & 1, "encrypted member"
|
|
if not h[2] & 8:
|
|
assert (h[6], h[7], h[8]) == (entry["crc32"], entry["compressed_bytes"], entry["bytes"])
|
|
assert len(payload) == entry["compressed_bytes"]
|
|
if entry["method"] == 8:
|
|
decoder = zlib.decompressobj(-15)
|
|
raw = decoder.decompress(payload, entry["bytes"] + 1)
|
|
assert decoder.eof and not decoder.unused_data and not decoder.unconsumed_tail
|
|
else:
|
|
assert entry["method"] == 0
|
|
raw = payload
|
|
assert len(raw) == entry["bytes"]
|
|
assert zlib.crc32(raw) & 0xFFFFFFFF == entry["crc32"]
|
|
raw.decode("utf-8") # Necessary text only; never import it.
|
|
return raw
|
|
|
|
|
|
def metadata():
|
|
request("registry-node", REGISTRY, 131072)
|
|
raw, _ = request("registry-version", REGISTRY + "/versions/1.1.5", 131072)
|
|
version = json.loads(raw)
|
|
assert version["version"] == "1.1.5" and version["node_id"] == "comfyui_controlnet_aux"
|
|
assert version["downloadUrl"] == CDN
|
|
tail, rec = request("release-tail", CDN, 65557, "bytes=-65557")
|
|
cr = next(v for k, v in rec["headers"].items() if k.lower() == "content-range")
|
|
match = re.fullmatch(r"bytes (\d+)-(\d+)/(\d+)", cr)
|
|
assert match
|
|
start, end, total = map(int, match.groups())
|
|
assert end == total - 1 and len(tail) == end - start + 1
|
|
pos = tail.rfind(b"PK\x05\x06")
|
|
h = struct.unpack_from("<4s4H2LH", tail, pos)
|
|
assert pos >= 0 and h[1] == h[2] == 0 and h[3] == h[4]
|
|
assert pos + 22 + h[7] == len(tail) and h[4] < 65535
|
|
count, cd_size, cd_offset = h[4], h[5], h[6]
|
|
assert cd_size <= 2_000_000
|
|
if cd_offset >= start:
|
|
directory = tail[cd_offset - start : cd_offset - start + cd_size]
|
|
else:
|
|
directory, _ = range_read("release-directory", cd_offset, cd_offset + cd_size - 1)
|
|
entries = parse_directory(directory, count)
|
|
save(
|
|
"release-directory.json",
|
|
dict(
|
|
artifact_url=CDN,
|
|
version="1.1.5",
|
|
total_artifact_bytes=total,
|
|
whole_artifact_sha256=None,
|
|
git_release_commit=None,
|
|
central_directory_sha256=sha(directory),
|
|
entries=entries,
|
|
),
|
|
)
|
|
print(count, "central directory entries; only metadata downloaded")
|
|
|
|
|
|
def members(plan, calls=False):
|
|
index = json.loads((HERE / "release-directory.json").read_text())
|
|
entries = {e["name"]: e for e in index["entries"]}
|
|
proofs = []
|
|
for i, name in enumerate(plan):
|
|
entry = entries[name]
|
|
assert name.endswith((".py", ".toml", ".txt", ".md", "LICENSE"))
|
|
assert entry["bytes"] <= 512000 and entry["compressed_bytes"] <= 256000
|
|
offset = entry["local_offset"]
|
|
prefix = "call-member" if calls else "member"
|
|
header, hr = range_read(f"{prefix}-{i:02}-header", offset, offset + 29)
|
|
h = struct.unpack("<4s5H3L2H", header)
|
|
nlen, extra = h[9], h[10]
|
|
named, nr = range_read(f"{prefix}-{i:02}-name", offset + 30, offset + 29 + nlen + extra)
|
|
assert named[:nlen].decode("utf-8") == name
|
|
payload_start = offset + 30 + nlen + extra
|
|
payload, pr = range_read(
|
|
f"{prefix}-{i:02}-data", payload_start, payload_start + entry["compressed_bytes"] - 1
|
|
)
|
|
raw = unpack_member(entry, header, payload)
|
|
output = name.replace("/", "__")
|
|
with (HERE / "release-members" / output).open("xb") as stream:
|
|
stream.write(raw)
|
|
proofs.append(
|
|
dict(
|
|
**entry,
|
|
sha256=sha(raw),
|
|
file=f"release-members/{output}",
|
|
retrieved_at=pr["finished_at"],
|
|
header_request=hr["key"],
|
|
name_request=nr["key"],
|
|
data_request=pr["key"],
|
|
whole_artifact_sha256=None,
|
|
git_release_commit=None,
|
|
)
|
|
)
|
|
save("release-call-proofs.json" if calls else "release-member-proofs.json", proofs)
|
|
print(len(proofs), "necessary release text members, CRC/SHA checked")
|
|
|
|
|
|
def core():
|
|
results = []
|
|
declarations = [
|
|
(
|
|
"0.21.1",
|
|
"26515acd23fa291a8f5ab53c5997258598de0701",
|
|
[
|
|
("nodes.py", "corev0.21.1__nodes.py"),
|
|
("comfy_extras/nodes_canny.py", "corev0.21.1__comfy_extras__nodes_canny.py"),
|
|
],
|
|
),
|
|
(
|
|
"0.17.0",
|
|
"63d1bbdb407c69370d407ce5ced6ca3f917528a8",
|
|
[("comfy_extras/nodes_images.py", "corev0.17.0__comfy_extras__nodes_images.py")],
|
|
),
|
|
]
|
|
for version, expected, paths in declarations:
|
|
prefix = "core-" + version.replace(".", "-")
|
|
ref, _ = request(prefix + "-tag", CORE + "git/ref/tags/v" + version, 131072)
|
|
obj = json.loads(ref)["object"]
|
|
if obj["type"] == "tag":
|
|
tag, _ = request(prefix + "-annotated", CORE + "git/tags/" + obj["sha"], 131072)
|
|
obj = json.loads(tag)["object"]
|
|
assert obj["type"] == "commit" and obj["sha"] == expected
|
|
commit, _ = request(prefix + "-commit", CORE + "git/commits/" + expected, 131072)
|
|
tree_sha = json.loads(commit)["tree"]["sha"]
|
|
root, _ = request(prefix + "-root", CORE + "git/trees/" + tree_sha, 262144)
|
|
trees = {"": json.loads(root)}
|
|
for filepath, retained in paths:
|
|
parent, _, filename = filepath.rpartition("/")
|
|
if parent not in trees:
|
|
parent_sha = next(e["sha"] for e in trees[""]["tree"] if e["path"] == parent)
|
|
body, _ = request(prefix + "-" + parent, CORE + "git/trees/" + parent_sha, 262144)
|
|
trees[parent] = json.loads(body)
|
|
entry = next(e for e in trees[parent]["tree"] if e["path"] == filename)
|
|
local = HERE.parent / "serialization-evidence" / retained
|
|
raw = local.read_bytes()
|
|
blob = hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest()
|
|
assert entry["type"] == "blob" and entry["sha"] == blob
|
|
results.append(
|
|
dict(
|
|
version=version,
|
|
tag="v" + version,
|
|
commit=expected,
|
|
repository="https://github.com/Comfy-Org/ComfyUI",
|
|
path=filepath,
|
|
retained_path=str(local.relative_to(HERE.parents[2])),
|
|
git_blob_sha1=blob,
|
|
sha256=sha(raw),
|
|
tag_commit_tree_blob_verified=True,
|
|
rechecked_at=now(),
|
|
target_installed=False,
|
|
)
|
|
)
|
|
save("core-bindings.json", results)
|
|
print("three retained core files bound by exact tag/commit/tree/blob")
|
|
|
|
|
|
def core_support(public=False):
|
|
proofs = []
|
|
for version, commit in (
|
|
("0.21.1", "26515acd23fa291a8f5ab53c5997258598de0701"),
|
|
("0.17.0", "63d1bbdb407c69370d407ce5ced6ca3f917528a8"),
|
|
):
|
|
paths = (
|
|
("comfy_api/latest/_io_public.py",)
|
|
if public
|
|
else ("comfy_api/latest/__init__.py", "comfy_api/latest/_io.py", "LICENSE")
|
|
)
|
|
for i, path in enumerate(paths):
|
|
key = (
|
|
("core-public-" if public else "core-support-")
|
|
+ version.replace(".", "-")
|
|
+ "-"
|
|
+ str(i)
|
|
)
|
|
body, record = request(key, CORE + "contents/" + path + "?ref=" + commit, 512000)
|
|
item = json.loads(body)
|
|
assert item["path"] == path and item["type"] == "file" and item["encoding"] == "base64"
|
|
raw = base64.b64decode(item["content"], validate=False)
|
|
assert len(raw) == item["size"]
|
|
blob = hashlib.sha1(b"blob " + str(len(raw)).encode() + b"\0" + raw).hexdigest()
|
|
assert blob == item["sha"]
|
|
raw.decode("utf-8")
|
|
output = "core-" + version + "__" + path.replace("/", "__") + ".txt"
|
|
with (HERE / "release-members" / output).open("xb") as stream:
|
|
stream.write(raw)
|
|
proofs.append(
|
|
dict(
|
|
repository="https://github.com/Comfy-Org/ComfyUI",
|
|
version=version,
|
|
commit=commit,
|
|
path=path,
|
|
git_blob_sha1=blob,
|
|
sha256=sha(raw),
|
|
retrieved_at=record["finished_at"],
|
|
request_key=key,
|
|
file="release-members/" + output,
|
|
)
|
|
)
|
|
save("core-public-proofs.json" if public else "core-support-proofs.json", proofs)
|
|
print(len(proofs), "exact core base/schema/license texts; not imported")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import sys
|
|
|
|
if sys.argv[1] == "metadata":
|
|
metadata()
|
|
elif sys.argv[1] == "core":
|
|
core()
|
|
elif sys.argv[1] == "core-support":
|
|
core_support()
|
|
elif sys.argv[1] == "core-public":
|
|
core_support(public=True)
|
|
elif sys.argv[1] == "calls":
|
|
members(json.loads((HERE / "call-member-plan.json").read_text()), calls=True)
|
|
else:
|
|
members(json.loads((HERE / "member-plan.json").read_text()))
|