videogen/scripts/sign-desktop-update.py
caelum0x d56639a594
Some checks are pending
build-images / api (push) Waiting to run
build-images / worker-gpu (push) Waiting to run
build-images / web (push) Waiting to run
codeql / Analyze (javascript-typescript) (push) Waiting to run
codeql / Analyze (python) (push) Waiting to run
perf / API hot-path micro-smoke (budgeted) (push) Waiting to run
perf / Desktop engine crates (release build check) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (comfy-workflow-schema) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (effects-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (eventbus-types) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (growth-analytics) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (trends-schema) (push) Waiting to run
vision2026-ci / API phase modules (ruff + pytest) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (provider-adapter-kit) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (publishing-connectors) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (render-core) (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (shot-template-schema) (push) Waiting to run
vision2026-ci / Python SDK resource tests (push) Waiting to run
vision2026-ci / Desktop engine crates (test + clippy + fmt) (push) Waiting to run
vision2026-ci / Alembic upgrade + drift check (push) Waiting to run
vision2026-ci / Shared packages (TS≡Python golden parity) (caption-engine) (push) Waiting to run
Menivor — open source release (MIT), free to use and fork
Paid, hosted product at menivor.com, now retired as a company project.
Fresh squashed history of the cleaned working tree (secret-scanned,
no .env, no customer data, no outreach logs). Built on
MoneyPrinterTurbo (MIT, harry0703) — see NOTICE.
2026-12-04 02:10:26 +03:00

198 lines
6.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""Build a Menivor update manifest and sign its canonical release payload.
The private Ed25519 key is read by OpenSSL and never serialized into the output.
Artifact size and SHA-256 are derived from local release files, not trusted from
the input specification.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import subprocess
import tempfile
from typing import Any
SCHEMA_VERSION = 1
MAX_ARTIFACT_BYTES = 1024 * 1024 * 1024
ED25519_SPKI_PREFIX = bytes.fromhex("302a300506032b6570032100")
def canonical_release(release: dict[str, Any]) -> bytes:
artifacts = sorted(
release["artifacts"],
key=lambda item: (
item["platform"],
item["arch"],
item["kind"],
item["url"],
item["size_bytes"],
item["sha256"],
),
)
canonical = {
"channel": release["channel"],
"version": release["version"],
"published_at": release["published_at"],
"notes_url": release["notes_url"],
"artifacts": artifacts,
}
return json.dumps(
canonical, ensure_ascii=False, separators=(",", ":")
).encode("utf-8")
def sha256_file(path: Path) -> str:
digest = hashlib.sha256()
with path.open("rb") as source:
while chunk := source.read(1024 * 1024):
digest.update(chunk)
return digest.hexdigest()
def build_release(spec: dict[str, Any], spec_dir: Path) -> dict[str, Any]:
channel = str(spec.get("channel", ""))
if channel not in {"stable", "beta"}:
raise ValueError("channel must be stable or beta")
notes_url = str(spec.get("notes_url", ""))
if not notes_url.startswith("https://"):
raise ValueError("notes_url must use HTTPS")
artifacts = []
for raw in spec.get("artifacts", []):
local_path = Path(str(raw["path"])).expanduser()
if not local_path.is_absolute():
local_path = spec_dir / local_path
local_path = local_path.resolve(strict=True)
size = local_path.stat().st_size
if size <= 0 or size > MAX_ARTIFACT_BYTES:
raise ValueError(f"artifact {local_path} is outside the 1 byte–1 GiB limit")
url = str(raw["url"])
if not url.startswith("https://"):
raise ValueError("artifact URLs must use HTTPS")
platform = str(raw["platform"])
kind = str(raw["kind"])
allowed = {
("macos", "pkg"),
("windows", "msi"),
("linux", "appimage"),
}
if (platform, kind) not in allowed:
raise ValueError(f"unsupported artifact kind {platform}/{kind}")
artifacts.append(
{
"platform": platform,
"arch": str(raw["arch"]),
"kind": kind,
"url": url,
"size_bytes": size,
"sha256": sha256_file(local_path),
}
)
if not artifacts:
raise ValueError("at least one artifact is required")
return {
"channel": channel,
"version": str(spec["version"]),
"published_at": str(spec["published_at"]),
"notes_url": notes_url,
"artifacts": artifacts,
}
def openssl_sign(payload: bytes, private_key: Path) -> tuple[bytes, bytes]:
with tempfile.TemporaryDirectory(prefix="menivor-update-sign-") as directory:
root = Path(directory)
payload_path = root / "release.json"
signature_path = root / "release.sig"
public_path = root / "release-public.der"
payload_path.write_bytes(payload)
subprocess.run(
[
"openssl",
"pkeyutl",
"-sign",
"-rawin",
"-inkey",
str(private_key),
"-in",
str(payload_path),
"-out",
str(signature_path),
],
check=True,
)
subprocess.run(
[
"openssl",
"pkey",
"-in",
str(private_key),
"-pubout",
"-outform",
"DER",
"-out",
str(public_path),
],
check=True,
stdout=subprocess.DEVNULL,
)
signature = signature_path.read_bytes()
public_der = public_path.read_bytes()
if len(signature) != 64:
raise ValueError("OpenSSL did not produce a 64-byte Ed25519 signature")
if not public_der.startswith(ED25519_SPKI_PREFIX) or len(public_der) != 44:
raise ValueError("private key is not an Ed25519 key")
return signature, public_der[len(ED25519_SPKI_PREFIX) :]
def write_atomic(path: Path, value: dict[str, Any]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with tempfile.NamedTemporaryFile(
mode="w", encoding="utf-8", dir=path.parent, delete=False
) as output:
json.dump(value, output, ensure_ascii=False, indent=2)
output.write("\n")
temporary = Path(output.name)
output.flush()
os.fsync(output.fileno())
os.replace(temporary, path)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser()
parser.add_argument("--spec", type=Path, required=True)
parser.add_argument("--private-key", type=Path, required=True)
parser.add_argument("--key-id", required=True)
parser.add_argument("--output", type=Path, required=True)
return parser.parse_args()
def main() -> None:
args = parse_args()
spec_path = args.spec.resolve(strict=True)
private_key = args.private_key.resolve(strict=True)
spec = json.loads(spec_path.read_text(encoding="utf-8"))
release = build_release(spec, spec_path.parent)
signature, public_key = openssl_sign(canonical_release(release), private_key)
manifest = {
"schema_version": SCHEMA_VERSION,
"key_id": args.key_id,
"release": release,
"signature_base64": base64.b64encode(signature).decode("ascii"),
}
write_atomic(args.output, manifest)
print(f"wrote {args.output}")
print(
"MENIVOR_UPDATE_PUBLIC_KEY_BASE64="
+ base64.b64encode(public_key).decode("ascii")
)
if __name__ == "__main__":
main()