File size: 5,936 Bytes
05b9f96
 
 
 
 
 
 
3b4f37b
 
 
 
 
 
 
 
 
 
05b9f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b4f37b
 
05b9f96
 
 
 
 
 
3b4f37b
05b9f96
 
 
 
 
 
 
3b4f37b
05b9f96
 
 
 
3b4f37b
05b9f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b4f37b
 
 
05b9f96
3b4f37b
 
05b9f96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3b4f37b
 
05b9f96
3b4f37b
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
#!/usr/bin/env python3
import os
import json
import pathlib
import traceback
import yaml

from verifier.runners.verify_manifest import verify_manifest
from verifier.runners.verify_tweet_thread import verify_tweet_thread
from verifier.core.signer import sign_bundle
from verifier.core.canonical import canonical_json
from verifier.adapters.ipfs_client import pin_bytes_to_ipfs

CONFIG = pathlib.Path("config/targets.yaml")
OUTDIR = pathlib.Path("attestations")
OUTDIR.mkdir(exist_ok=True)

ENABLE_PIN = os.environ.get("ENABLE_IPFS_PIN", "0").strip().lower() in ("1", "true", "yes")


def _safe_subject(s: str) -> str:
    s = (s or "unknown_subject").strip()
    s = s.replace(":", "_").replace("/", "_")
    return s[:180]  # keep filenames sane


def _error_bundle(subject: str, kind: str, err: Exception) -> dict:
    return {
        "subject": subject,
        "ok": False,
        "kind": kind,
        "error": str(err),
        "trace": traceback.format_exc(limit=8),
    }


def write_bundle(subject: str, bundle: dict):
    """
    - signs bundle (if key exists; signer decides)
    - writes attestations/<subject>.json
    - optional IPFS pin (non-fatal)
    """
    subject = _safe_subject(subject)

    # Sign (signer decides what to do if key not present)
    try:
        bundle = sign_bundle(bundle)
    except Exception as e:
        # Never crash just because signing failed
        bundle = bundle or {}
        bundle["sign_error"] = str(e)

    path = OUTDIR / f"{subject}.json"
    path.write_text(json.dumps(bundle, ensure_ascii=False, indent=2), encoding="utf-8")

    # Optional IPFS pin (non-fatal)
    if ENABLE_PIN:
        try:
            data = canonical_json(bundle)
            ipfs_res = pin_bytes_to_ipfs(data)
            if isinstance(ipfs_res, dict) and ipfs_res.get("ok"):
                bundle["evidence_cid"] = ipfs_res.get("cid")
            else:
                bundle["ipfs_error"] = (ipfs_res or {}).get("error", "pin_failed")
        except Exception as e:
            bundle["ipfs_error"] = str(e)

        path.write_text(json.dumps(bundle, ensure_ascii=False, indent=2), encoding="utf-8")

    return {
        "subject": subject,
        "integrity_hash": bundle.get("integrity_hash"),
        "file": str(path),
        "cid": bundle.get("evidence_cid"),
        "ok": bundle.get("ok", True) if isinstance(bundle, dict) else True,
    }


def _load_config() -> dict:
    if not CONFIG.exists():
        # Make it explicit and actionable
        raise FileNotFoundError(f"Missing config file: {CONFIG} (expected: config/targets.yaml)")

    cfg = yaml.safe_load(CONFIG.read_text(encoding="utf-8")) or {}
    if not isinstance(cfg, dict):
        raise TypeError("config/targets.yaml must parse to a YAML mapping/object at top level.")
    return cfg


def _as_list(value) -> list:
    """Treat None/missing as empty list; error only on truly wrong types."""
    if value is None:
        return []
    if isinstance(value, list):
        return value
    raise TypeError(f"Expected a list (or null/omitted), got: {type(value).__name__}")


def main():
    cfg = _load_config()
    index = []

    # -------- GitHub manifests --------
    github_manifests = _as_list(cfg.get("github_manifests"))
    for i, item in enumerate(github_manifests):
        if not isinstance(item, dict):
            # Skip bad entries without killing the run
            b = _error_bundle(
                subject=f"github_manifest_{i}",
                kind="github_manifest",
                err=TypeError("github_manifests entries must be mapping objects"),
            )
            index.append(write_bundle(b["subject"], b))
            continue

        name = (item.get("name") or f"github_manifest_{i}").strip() or f"github_manifest_{i}"

        try:
            b = verify_manifest(
                name=name,
                file=item.get("file", "") or "",
                raw=item.get("raw", "") or "",
                html=item.get("html", "") or "",
                ipfs=item.get("ipfs", "") or "",
            )
        except Exception as e:
            b = _error_bundle(subject=name, kind="github_manifest", err=e)

        # Ensure a subject exists even if runner didn't provide it
        subj = b.get("subject") if isinstance(b, dict) else None
        subj = subj or f"manifest:{name}"
        index.append(write_bundle(subj, b))

    # -------- Tweet threads (optional) --------
    tweet_threads = _as_list(cfg.get("tweet_threads"))
    for i, item in enumerate(tweet_threads):
        if not isinstance(item, dict):
            b = _error_bundle(
                subject=f"tweet_thread_{i}",
                kind="tweet_thread",
                err=TypeError("tweet_threads entries must be mapping objects"),
            )
            index.append(write_bundle(b["subject"], b))
            continue

        name = (item.get("name") or f"tweet_thread_{i}").strip() or f"tweet_thread_{i}"
        status_url = (item.get("status_url") or "").strip()

        if not status_url:
            # Skip invalid entries but record it
            b = _error_bundle(
                subject=f"tweet:{name}",
                kind="tweet_thread",
                err=ValueError("tweet_threads entries require 'status_url'"),
            )
            index.append(write_bundle(b["subject"], b))
            continue

        try:
            b = verify_tweet_thread(name, status_url)
        except Exception as e:
            b = _error_bundle(subject=f"tweet:{name}", kind="tweet_thread", err=e)

        subj = b.get("subject") if isinstance(b, dict) else None
        subj = subj or f"tweet:{name}"
        index.append(write_bundle(subj, b))

    # -------- Write index --------
    (OUTDIR / "index.json").write_text(
        json.dumps(index, ensure_ascii=False, indent=2),
        encoding="utf-8",
    )
    print(json.dumps(index, indent=2))


if __name__ == "__main__":
    main()