|
| 1 | +import hashlib |
| 2 | +import io |
| 3 | +import re |
| 4 | +import tarfile |
| 5 | +from typing import Any |
| 6 | + |
| 7 | +import requests |
| 8 | +from flask import Flask, Response, abort, request |
| 9 | + |
| 10 | +app = Flask(__name__) |
| 11 | + |
| 12 | +MAX_OUTPUT_BYTES = 50 * 1024 * 1024 # 50 MB limit for repacked tarball |
| 13 | +_SAFE_PARAM = re.compile(r"^[A-Za-z0-9._-]+$") |
| 14 | + |
| 15 | +_session = requests.Session() |
| 16 | +_session.headers["User-Agent"] = "gitpkg-selfhost/1.0" |
| 17 | + |
| 18 | + |
| 19 | +@app.route("/health") |
| 20 | +def health(): |
| 21 | + return "ok" |
| 22 | + |
| 23 | + |
| 24 | +@app.route("/<user>/<repo>/<path:subdir>") |
| 25 | +@app.route("/https://github.com/<user>/<repo>/tree/<commit>/<path:subdir>") |
| 26 | +def pkg(user: str, repo: str, subdir: str, commit: str | None = None): |
| 27 | + if commit is None: |
| 28 | + qs = request.query_string.decode() |
| 29 | + commit = request.args.get("commit") or (qs if qs and "=" not in qs else "") or "main" |
| 30 | + |
| 31 | + # Validate inputs |
| 32 | + for param in (user, repo, commit): |
| 33 | + if not _SAFE_PARAM.match(param): |
| 34 | + abort(400, "Invalid characters in URL") |
| 35 | + |
| 36 | + subdir = subdir.rstrip("/") + "/" |
| 37 | + |
| 38 | + # Fetch full-repo tarball from GitHub |
| 39 | + codeload_url = f"https://codeload.github.com/{user}/{repo}/tar.gz/{commit}" |
| 40 | + |
| 41 | + # HEAD — skip download, no useful headers to return without repack |
| 42 | + if request.method == "HEAD": |
| 43 | + return Response(mimetype="application/gzip") |
| 44 | + |
| 45 | + upstream = _session.get(codeload_url, stream=True, timeout=(5, 60)) |
| 46 | + if upstream.status_code != 200: |
| 47 | + upstream.close() |
| 48 | + abort(upstream.status_code, f"GitHub returned {upstream.status_code}") |
| 49 | + |
| 50 | + upstream.raw.decode_content = True |
| 51 | + |
| 52 | + # Stream the tarball, filter to subdir, repack with package/ prefix |
| 53 | + try: |
| 54 | + tgz_bytes = _repack(upstream.raw, subdir) |
| 55 | + except ValueError: |
| 56 | + abort(413, "Subdirectory too large to serve") |
| 57 | + finally: |
| 58 | + upstream.close() |
| 59 | + if tgz_bytes is None: |
| 60 | + abort(404, f"Subdirectory '{subdir}' not found in {user}/{repo}@{commit}") |
| 61 | + |
| 62 | + etag = hashlib.sha256(tgz_bytes).hexdigest()[:16] |
| 63 | + if request.headers.get("If-None-Match") == etag: |
| 64 | + return Response(status=304) |
| 65 | + |
| 66 | + safe_subdir = re.sub(r"[^\w.-]", "-", subdir) |
| 67 | + filename = f"{user}-{repo}-{safe_subdir}{commit[:12]}.tgz" |
| 68 | + return Response( |
| 69 | + tgz_bytes, |
| 70 | + mimetype="application/gzip", |
| 71 | + headers={ |
| 72 | + "Content-Disposition": f'attachment; filename="{filename}"', |
| 73 | + "ETag": etag, |
| 74 | + "Cache-Control": "public, immutable, max-age=31536000", |
| 75 | + }, |
| 76 | + ) |
| 77 | + |
| 78 | + |
| 79 | +def _repack(stream: Any, subdir: str) -> bytes | None: |
| 80 | + """Extract subdir from streamed tarball and repack as npm-compatible tgz.""" |
| 81 | + out_buf = io.BytesIO() |
| 82 | + |
| 83 | + found = False |
| 84 | + full_prefix = "" |
| 85 | + |
| 86 | + with tarfile.open(fileobj=stream, mode="r|gz") as src: |
| 87 | + with tarfile.open(fileobj=out_buf, mode="w:gz") as dst: |
| 88 | + for member in src: |
| 89 | + # First entry is the repo root dir, e.g. "wagmi-8fe5291/" |
| 90 | + if not full_prefix: |
| 91 | + full_prefix = member.name.split("/")[0] + "/" + subdir |
| 92 | + continue |
| 93 | + |
| 94 | + # Check if entry is inside the target subdir |
| 95 | + if not member.name.startswith(full_prefix): |
| 96 | + continue |
| 97 | + |
| 98 | + # Only allow regular files and directories |
| 99 | + if not (member.isfile() or member.isdir()): |
| 100 | + continue |
| 101 | + |
| 102 | + found = True |
| 103 | + |
| 104 | + # Copy member info with remapped name |
| 105 | + relative = member.name[len(full_prefix):] |
| 106 | + info = tarfile.TarInfo(name="package/" + relative if relative else "package") |
| 107 | + info.size = member.size if member.isfile() else 0 |
| 108 | + info.mode = member.mode |
| 109 | + info.type = member.type |
| 110 | + info.mtime = member.mtime |
| 111 | + |
| 112 | + fileobj = src.extractfile(member) if member.isfile() else None |
| 113 | + dst.addfile(info, fileobj) |
| 114 | + |
| 115 | + if out_buf.tell() > MAX_OUTPUT_BYTES: |
| 116 | + raise ValueError("Output tarball too large") |
| 117 | + |
| 118 | + if not found: |
| 119 | + return None |
| 120 | + |
| 121 | + return out_buf.getvalue() |
| 122 | + |
| 123 | + |
| 124 | +if __name__ == "__main__": |
| 125 | + app.run(host="0.0.0.0", port=8000) |
0 commit comments