indieward 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
indieward/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """IndieWard: prove you made it, spot clones, draft takedowns. Runs on your machine; never sends anything."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,202 @@
1
+ """Signed, timestamped proof-of-ownership certificates (IndieWard certificate v1).
2
+
3
+ A certificate lists the project's verified store links, every registered
4
+ asset (SHA-256, size, registration time, watermark ID) and every build (its
5
+ trap commitment, not the traps themselves). The body is canonical JSON signed
6
+ with the creator's Ed25519 key; the digest of the signed body is then
7
+ timestamped by an RFC 3161 authority and OpenTimestamps.
8
+
9
+ What it proves: these exact files existed and were held by the holder of this
10
+ key by the timestamp's date, and that key holder had shown control of the
11
+ listed store pages. It does not prove authorship. A US copyright
12
+ registration is stronger evidence of that.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ from pathlib import Path
18
+
19
+ from cryptography.exceptions import InvalidSignature
20
+ from cryptography.hazmat.primitives import serialization
21
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
22
+
23
+ from . import payload as pl, timestamp, util
24
+ from .vault import Vault
25
+
26
+ STATEMENT = (
27
+ "This certificate shows that the listed files (identified by SHA-256) were held by the holder of the "
28
+ "signing key by the time of the attached third-party timestamps, and that this key holder showed control "
29
+ "of the listed store pages. It is evidence of possession at a point in time, not proof of authorship. It "
30
+ "is not a copyright registration and not legal advice."
31
+ )
32
+
33
+
34
+ def build_body(vault: Vault) -> dict:
35
+ proj = vault.project()
36
+ pub_raw = util.unb64(proj["public_key"])
37
+ ver = [
38
+ {"store": r["store"], "url": r["url"], "method": r["method"], "verified_at": r["verified_at"],
39
+ "evidence_sha256": r["evidence_sha256"], "detail": json.loads(r["detail"] or "{}")}
40
+ for r in vault.verifications() if r["status"] == "verified"
41
+ ]
42
+ assets = []
43
+ for r in vault.db.execute("SELECT * FROM assets ORDER BY id").fetchall():
44
+ a = {"record": pl.fmt(r["record_id"]), "kind": r["kind"], "category": r["category"], "name": r["name"],
45
+ "sha256": r["sha256"], "size": r["size"], "registered_at": r["registered_at"]}
46
+ if r["wm_payload"]:
47
+ a["watermark"] = {"format": "IW-Mark v1", "backend": r["wm_backend"],
48
+ "marked_file_sha256": r["wm_output_sha256"]}
49
+ assets.append(a)
50
+ builds = [
51
+ {"build_id": r["id"], "label": r["label"], "engine": r["engine"], "registered_at": r["registered_at"],
52
+ "manifest_sha256": r["manifest_sha256"], "trap_commitment": r["trap_commitment"]}
53
+ for r in vault.db.execute("SELECT * FROM builds ORDER BY registered_at").fetchall()
54
+ ]
55
+ docs = [{"kind": r["kind"], "title": r["title"], "sha256": r["sha256"], "added_at": r["added_at"]}
56
+ for r in vault.db.execute("SELECT * FROM docs ORDER BY id").fetchall()]
57
+ return {
58
+ "format": "IndieWard certificate v1",
59
+ "issued_at": util.now_iso(),
60
+ "creator": {"name": proj["creator"], "contact": proj["contact_email"],
61
+ "public_key_ed25519": proj["public_key"],
62
+ "key_fingerprint": util.sha256_bytes(pub_raw)[:32]},
63
+ "project": {"id": proj["id"], "name": proj["name"], "first_published": proj["first_published"],
64
+ "verification_code": proj["verify_code"]},
65
+ "verified_store_links": ver,
66
+ "assets": assets,
67
+ "builds": builds,
68
+ "documents": docs,
69
+ "statement": STATEMENT,
70
+ }
71
+
72
+
73
+ def issue(vault: Vault, out_dir=None, do_stamp: bool = True, passphrase: str | None = None) -> dict:
74
+ vault.require_verified("issue certificates")
75
+ body = build_body(vault)
76
+ canon = util.canonical_json(body)
77
+ sig = vault.signing_key(passphrase).sign(canon)
78
+ digest = util.sha256_bytes(canon + sig)
79
+ cert = {**body, "signature": {"alg": "Ed25519", "value": util.b64(sig)}, "digest_sha256": digest}
80
+ if do_stamp:
81
+ ts = timestamp.stamp(vault, f"certificate {digest[:12]}", digest)
82
+ cert["timestamps"] = {k: {kk: vv for kk, vv in v.items() if kk != "error"} | (
83
+ {"error": v["error"]} if v.get("error") else {}) for k, v in ts.items()}
84
+ for k, v in ts.items():
85
+ tok = v.get("token")
86
+ if tok:
87
+ cert["timestamps"][k]["token_b64"] = util.b64(vault.path("certs", "timestamps", tok).read_bytes())
88
+ out_dir = Path(out_dir) if out_dir else vault.path("certs")
89
+ out_dir.mkdir(parents=True, exist_ok=True)
90
+ jpath = out_dir / f"certificate_{digest[:12]}.json"
91
+ jpath.write_text(json.dumps(cert, indent=2, ensure_ascii=False))
92
+ pdf = out_dir / f"certificate_{digest[:12]}.pdf"
93
+ render_pdf(cert, pdf)
94
+ return {"json": str(jpath), "pdf": str(pdf), "digest": digest,
95
+ "timestamps": {k: v.get("status") for k, v in cert.get("timestamps", {}).items()}}
96
+
97
+
98
+ def summary(cert: dict, json_path=None, pdf_path=None) -> dict:
99
+ ts = cert.get("timestamps", {})
100
+ r = ts.get("rfc3161", {})
101
+ if r.get("status") == "stamped":
102
+ stamp = f"independently timestamped by {r.get('service')} at {r.get('time')} (RFC 3161)"
103
+ else:
104
+ stamp = "independent timestamp still pending, so the issue date above is self-reported"
105
+ return {"digest": cert["digest_sha256"], "issued_at": cert["issued_at"], "json": json_path, "pdf": pdf_path,
106
+ "timestamps": {k: v.get("status") for k, v in ts.items()}, "stamp_sentence": stamp,
107
+ "builds": {b["build_id"] for b in cert.get("builds", [])}, "n_assets": len(cert.get("assets", []))}
108
+
109
+
110
+ def earliest_covering(vault: Vault, build_ids: set[str]) -> dict | None:
111
+ """Earliest stamped certificate in the vault that lists these builds and at least one asset."""
112
+ found = []
113
+ for p in sorted(vault.path("certs").glob("certificate_*.json")):
114
+ try:
115
+ c = json.loads(p.read_text())
116
+ except Exception:
117
+ continue
118
+ if not verify(c)["valid"]:
119
+ continue
120
+ s = summary(c, str(p), str(p.with_suffix(".pdf")))
121
+ if s["n_assets"] and build_ids <= s["builds"] and Path(s["pdf"]).exists():
122
+ found.append(s)
123
+ stamped = [s for s in found if s["timestamps"].get("rfc3161") == "stamped"]
124
+ pool = stamped or found
125
+ return min(pool, key=lambda s: s["issued_at"]) if pool else None
126
+
127
+
128
+ def verify(cert_or_path, tsa_ca=None) -> dict:
129
+ cert = json.loads(Path(cert_or_path).read_text()) if not isinstance(cert_or_path, dict) else cert_or_path
130
+ body = {k: v for k, v in cert.items() if k not in ("signature", "digest_sha256", "timestamps")}
131
+ canon = util.canonical_json(body)
132
+ sig = util.unb64(cert["signature"]["value"])
133
+ pub = Ed25519PublicKey.from_public_bytes(util.unb64(cert["creator"]["public_key_ed25519"]))
134
+ try:
135
+ pub.verify(sig, canon)
136
+ sig_ok = True
137
+ except InvalidSignature:
138
+ sig_ok = False
139
+ digest_ok = util.sha256_bytes(canon + sig) == cert.get("digest_sha256")
140
+ out = {"signature_valid": sig_ok, "digest_matches": digest_ok, "valid": sig_ok and digest_ok,
141
+ "timestamps": {k: v.get("status") for k, v in cert.get("timestamps", {}).items()}}
142
+ tok = cert.get("timestamps", {}).get("rfc3161", {}).get("token_b64")
143
+ if tok:
144
+ out["rfc3161_token"] = timestamp.check_token(util.unb64(tok), cert.get("digest_sha256", ""), tsa_ca)
145
+ return out
146
+
147
+
148
+ def render_pdf(cert: dict, path) -> None:
149
+ from reportlab.lib import colors
150
+ from reportlab.lib.pagesizes import letter
151
+ from reportlab.lib.styles import getSampleStyleSheet
152
+ from reportlab.lib.units import inch
153
+ from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle
154
+
155
+ styles = getSampleStyleSheet()
156
+ small = styles["BodyText"].clone("small", fontSize=7.5, leading=9)
157
+ body = styles["BodyText"].clone("b", fontSize=9.5, leading=12)
158
+ story = [Paragraph("Proof-of-ownership certificate", styles["Title"]),
159
+ Paragraph(f"<b>Project:</b> {cert['project']['name']} &nbsp; <b>Creator:</b> {cert['creator']['name']}", body),
160
+ Paragraph(f"<b>Issued:</b> {cert['issued_at']} &nbsp; <b>Certificate digest:</b> {cert['digest_sha256']}", small),
161
+ Paragraph(f"<b>Signing key fingerprint:</b> {cert['creator']['key_fingerprint']}", small),
162
+ Spacer(1, 8)]
163
+ ts = cert.get("timestamps", {})
164
+ rows = [["Timestamp", "Status", "Service", "Time"]]
165
+ for k, v in ts.items():
166
+ rows.append([k, v.get("status", ""), v.get("service", "") or "", v.get("time", "") or ""])
167
+ if len(rows) > 1:
168
+ story += [Paragraph("<b>Independent timestamps</b>", body), _tbl(rows, small, Table, TableStyle, colors),
169
+ Spacer(1, 8)]
170
+ vrows = [["Store", "URL", "Method", "Verified at"]] + [
171
+ [v["store"], Paragraph(v["url"], small), v["method"], v["verified_at"]] for v in cert["verified_store_links"]]
172
+ story += [Paragraph("<b>Verified store links</b>", body), _tbl(vrows, small, Table, TableStyle, colors),
173
+ Spacer(1, 8)]
174
+ arows = [["Record", "Category", "File", "SHA-256", "Registered"]] + [
175
+ [a["record"], a["category"], Paragraph(a["name"], small), Paragraph(a["sha256"], small), a["registered_at"]]
176
+ for a in cert["assets"]]
177
+ story += [Paragraph(f"<b>Registered assets ({len(cert['assets'])})</b>", body),
178
+ _tbl(arows, small, Table, TableStyle, colors, widths=[1.0, 0.6, 1.4, 2.6, 1.2]), Spacer(1, 8)]
179
+ if cert["builds"]:
180
+ brows = [["Build", "Label", "Engine", "Trap commitment", "Registered"]] + [
181
+ [b["build_id"], b["label"], b["engine"], Paragraph(b["trap_commitment"], small), b["registered_at"]]
182
+ for b in cert["builds"]]
183
+ story += [Paragraph("<b>Builds with trap markers</b>", body), _tbl(brows, small, Table, TableStyle, colors),
184
+ Spacer(1, 8)]
185
+ story += [Paragraph("<b>What this shows</b>", body), Paragraph(cert["statement"], small), Spacer(1, 6),
186
+ Paragraph("Verify the signature and digest with <font face='Courier'>indieward cert verify "
187
+ "certificate.json</font>, or any Ed25519 tool over the canonical JSON body. The RFC 3161 "
188
+ "token and OpenTimestamps proof are embedded in the JSON file.", small)]
189
+ SimpleDocTemplate(str(path), pagesize=letter, leftMargin=0.6 * inch, rightMargin=0.6 * inch,
190
+ topMargin=0.6 * inch, bottomMargin=0.6 * inch, title="IndieWard certificate").build(story)
191
+
192
+
193
+ def _tbl(rows, style, Table, TableStyle, colors, widths=None):
194
+ from reportlab.lib.units import inch
195
+ from reportlab.platypus import Paragraph
196
+
197
+ data = [[c if not isinstance(c, str) else Paragraph(c, style) for c in r] for r in rows]
198
+ t = Table(data, colWidths=[w * inch for w in widths] if widths else None, repeatRows=1)
199
+ t.setStyle(TableStyle([("GRID", (0, 0), (-1, -1), 0.4, colors.grey),
200
+ ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#eeeeee")),
201
+ ("VALIGN", (0, 0), (-1, -1), "TOP")]))
202
+ return t