proof-engine-registry 1.33.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.
@@ -0,0 +1,4 @@
1
+ """proof-engine-registry — Proof Registry protocol implementation."""
2
+
3
+ __version__ = "1.33.0"
4
+ __protocol_version__ = "0.1"
@@ -0,0 +1,141 @@
1
+ """Proof badge: compact certificate for claim verification.
2
+
3
+ Two artifacts per proof:
4
+ - badge.json — machine-readable payload
5
+ - badge.svg — shields-style inline SVG for direct <img> embedding
6
+
7
+ The SVG uses a fixed sans-serif stack and estimated text widths. It won't be
8
+ pixel-perfect at all zoom levels, but it renders without external fonts and
9
+ is byte-identical across builds (important so git diffs stay clean).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from typing import Optional
15
+
16
+ from proof_engine_registry.emit import (
17
+ claim_text, verdict_string, confidence_from_proof,
18
+ )
19
+ from proof_engine_registry.hashing import hash_claim
20
+
21
+
22
+ # Locked color map — see test_build_badge_pinned_colors.
23
+ VERDICT_COLORS: dict[str, str] = {
24
+ "PROVED": "#2d8f5f",
25
+ "SUPPORTED": "#5eb88a",
26
+ "PARTIALLY VERIFIED": "#d4a017",
27
+ "UNDETERMINED": "#888888",
28
+ "DISPROVED": "#c75450",
29
+ }
30
+
31
+ BADGE_SCHEMA_VERSION = "1.0"
32
+
33
+
34
+ def _color_for(verdict: str) -> str:
35
+ """Pick a color by the leading verdict family (ignoring any qualifier)."""
36
+ for family, color in VERDICT_COLORS.items():
37
+ if verdict.startswith(family):
38
+ return color
39
+ return VERDICT_COLORS["UNDETERMINED"]
40
+
41
+
42
+ def build_badge(proof: dict, slug: str, doi: Optional[str],
43
+ base_url: str) -> dict:
44
+ """Build the badge payload from a v3 proof.json dict.
45
+
46
+ `slug` and `doi` are passed explicitly because they live outside
47
+ proof.json (slug is the dir name; DOI is in a sibling doi.json).
48
+ """
49
+ base = base_url.rstrip("/")
50
+ claim = claim_text(proof)
51
+ verdict = verdict_string(proof)
52
+ gen = proof.get("generator") or {}
53
+ return {
54
+ "schema_version": BADGE_SCHEMA_VERSION,
55
+ "slug": slug,
56
+ "claim": claim,
57
+ "claim_hash": hash_claim(claim),
58
+ "verdict": verdict,
59
+ "confidence": confidence_from_proof(proof),
60
+ "doi": doi,
61
+ "proof_url": f"{base}/proofs/{slug}/",
62
+ "badge_svg_url": f"{base}/proofs/{slug}/badge.svg",
63
+ "generated_at": gen.get("generated_at", ""),
64
+ "colors": {
65
+ "verdict_bg": _color_for(verdict),
66
+ "verdict_fg": "#ffffff",
67
+ },
68
+ }
69
+
70
+
71
+ # SVG layout constants — keep in one place for easy theming.
72
+ _FONT_STACK = (
73
+ "-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica,Arial,sans-serif"
74
+ )
75
+ _LABEL_BG = "#555555"
76
+ _LABEL_FG = "#ffffff"
77
+ _CHAR_WIDTH = 6.5 # px, estimated for 11px sans-serif
78
+ _PADDING = 10
79
+ _HEIGHT = 20
80
+
81
+
82
+ def _text_width(text: str) -> int:
83
+ return int(len(text) * _CHAR_WIDTH) + 2 * _PADDING
84
+
85
+
86
+ def render_badge_svg(badge: dict) -> str:
87
+ label = "proof"
88
+ value = badge["verdict"]
89
+ label_w = _text_width(label)
90
+ value_w = _text_width(value)
91
+ total_w = label_w + value_w
92
+ value_bg = badge["colors"]["verdict_bg"]
93
+ # Defense-in-depth: verdict is a controlled enum today, but escape on
94
+ # the way into XML attributes and text nodes so a future qualifier
95
+ # string with `<` / `&` / `"` cannot break the SVG.
96
+ value_esc = _escape_html(value)
97
+ label_esc = _escape_html(label)
98
+
99
+ svg = (
100
+ f'<svg xmlns="http://www.w3.org/2000/svg" '
101
+ f'width="{total_w}" height="{_HEIGHT}" role="img" '
102
+ f'aria-label="proof: {value_esc}">'
103
+ f'<title>proof: {value_esc}</title>'
104
+ f'<linearGradient id="s" x2="0" y2="100%">'
105
+ f'<stop offset="0" stop-color="#bbb" stop-opacity=".1"/>'
106
+ f'<stop offset="1" stop-opacity=".1"/>'
107
+ f'</linearGradient>'
108
+ f'<rect width="{total_w}" height="{_HEIGHT}" rx="3" fill="{_LABEL_BG}"/>'
109
+ f'<rect x="{label_w}" width="{value_w}" height="{_HEIGHT}" rx="3" fill="{value_bg}"/>'
110
+ f'<rect width="{total_w}" height="{_HEIGHT}" rx="3" fill="url(#s)"/>'
111
+ f'<g fill="{_LABEL_FG}" text-anchor="middle" '
112
+ f'font-family="{_FONT_STACK}" font-size="11">'
113
+ f'<text x="{label_w // 2}" y="14">{label_esc}</text>'
114
+ f'<text x="{label_w + value_w // 2}" y="14">{value_esc}</text>'
115
+ f'</g></svg>'
116
+ )
117
+ return svg
118
+
119
+
120
+ def render_embed_snippets(badge: dict) -> dict[str, str]:
121
+ """Return the three copy-paste-ready embeds."""
122
+ proof_url = badge["proof_url"]
123
+ svg_url = badge["badge_svg_url"]
124
+ claim = badge["claim"]
125
+ return {
126
+ "html": (
127
+ f'<a href="{proof_url}" title="{_escape_html(claim)}">'
128
+ f'<img src="{svg_url}" alt="proof: {badge["verdict"]}"/></a>'
129
+ ),
130
+ "markdown": f'[![proof]({svg_url})]({proof_url})',
131
+ "url": svg_url,
132
+ }
133
+
134
+
135
+ def _escape_html(s: str) -> str:
136
+ return (
137
+ s.replace("&", "&amp;")
138
+ .replace("<", "&lt;")
139
+ .replace(">", "&gt;")
140
+ .replace('"', "&quot;")
141
+ )
@@ -0,0 +1,163 @@
1
+ """proof-registry CLI: serve | lookup | publish | emit."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sys
9
+ from dataclasses import asdict
10
+ from pathlib import Path
11
+
12
+ from proof_engine_registry import __version__
13
+ from proof_engine_registry.client import RegistryClient
14
+ from proof_engine_registry.config import load_registries, Registry
15
+ from proof_engine_registry.emit import emit_registry_files
16
+ from proof_engine_registry.server import RegistryServer
17
+
18
+
19
+ def _cmd_serve(args) -> int:
20
+ token = os.environ.get(args.token_env) if args.token_env else None
21
+ srv = RegistryServer(
22
+ proofs_dir=Path(args.proofs_dir),
23
+ name=args.name,
24
+ base_url=args.base_url or f"http://{args.bind}:{args.port}",
25
+ bind=args.bind, port=args.port,
26
+ auth_token=token,
27
+ cors_origin=args.cors_origin,
28
+ log_json=args.log_json,
29
+ )
30
+ if args.print_port_to:
31
+ Path(args.print_port_to).write_text(str(srv.port))
32
+ print(f"proof-registry serving {args.proofs_dir} on http://{args.bind}:{srv.port}",
33
+ file=sys.stderr)
34
+ try:
35
+ srv.serve_forever()
36
+ except KeyboardInterrupt:
37
+ srv.shutdown()
38
+ return 0
39
+
40
+
41
+ def _cmd_emit(args) -> int:
42
+ emit_registry_files(
43
+ proofs_dir=Path(args.proofs_dir),
44
+ output_dir=Path(args.output_dir),
45
+ base_url=args.base_url,
46
+ registry_name=args.name,
47
+ publishes_supported=False,
48
+ )
49
+ print(f"emitted registry to {args.output_dir}", file=sys.stderr)
50
+ return 0
51
+
52
+
53
+ def _cmd_lookup(args) -> int:
54
+ registries = load_registries()
55
+ if not registries:
56
+ print("error: no registries configured (expected ~/.config/proof-engine/registries.toml)",
57
+ file=sys.stderr)
58
+ return 2
59
+ client = RegistryClient(registries)
60
+ hit = client.lookup(args.claim)
61
+ if hit is None:
62
+ if args.json:
63
+ sys.stdout.write(json.dumps({"hit": False}) + "\n")
64
+ else:
65
+ sys.stdout.write("no hit\n")
66
+ return 1
67
+ payload = asdict(hit.entry) | {"registry_name": hit.registry_name}
68
+ if args.json:
69
+ sys.stdout.write(json.dumps(payload, indent=2 if args.pretty else None) + "\n")
70
+ else:
71
+ sys.stdout.write(f"{hit.registry_name}: {hit.slug} → {hit.proof_url}\n")
72
+ return 0
73
+
74
+
75
+ def _cmd_publish(args) -> int:
76
+ # Find the one publish target.
77
+ registries = [r for r in load_registries() if r.publish]
78
+ if not registries:
79
+ print("error: no registry has publish = true", file=sys.stderr)
80
+ return 2
81
+ if len(registries) > 1:
82
+ print("error: more than one registry has publish = true (blocked by config loader)",
83
+ file=sys.stderr)
84
+ return 2
85
+ target = registries[0]
86
+ body = json.loads(Path(args.proof_json).read_text())
87
+ import requests
88
+ r = requests.post(
89
+ f"{target.url}/proofs",
90
+ json={"slug": body["slug"], "claim": body["claim"], "proof_json": body},
91
+ headers={"Authorization": f"Bearer {target.token}"} if target.token else {},
92
+ timeout=30,
93
+ )
94
+ if r.status_code == 201:
95
+ print(f"published {body['slug']} to {target.name}", file=sys.stderr)
96
+ return 0
97
+ print(f"publish failed: HTTP {r.status_code} {r.text}", file=sys.stderr)
98
+ return 1
99
+
100
+
101
+ def build_parser() -> argparse.ArgumentParser:
102
+ p = argparse.ArgumentParser(prog="proof-registry")
103
+ p.add_argument("--version", action="version", version=__version__)
104
+ sub = p.add_subparsers(dest="cmd", required=True)
105
+
106
+ s = sub.add_parser(
107
+ "serve",
108
+ help="Run a self-hosted registry server.",
109
+ description=(
110
+ "Stdlib HTTP server. Suitable for development and local team "
111
+ "deployments. For public deployment over the open internet, "
112
+ "front this with a TLS-terminating reverse proxy (nginx, Caddy, "
113
+ "Cloudflare, etc.) — bearer tokens travel in the Authorization "
114
+ "header and MUST NOT cross the network in cleartext."
115
+ ),
116
+ )
117
+ s.add_argument("proofs_dir")
118
+ s.add_argument("--name", default="Self-Hosted Proof Registry")
119
+ s.add_argument("--base-url", default=None)
120
+ s.add_argument("--bind", default="127.0.0.1")
121
+ s.add_argument("--port", type=int, default=8080)
122
+ s.add_argument("--token-env", default=None,
123
+ help="Env var holding the bearer token required for publishing.")
124
+ s.add_argument("--cors-origin", default="*",
125
+ help=("Value for Access-Control-Allow-Origin on read responses. "
126
+ "Default '*' for public registries; pass a specific origin "
127
+ "to restrict cross-origin browser access."))
128
+ s.add_argument("--log-json", action="store_true",
129
+ help=("Emit one structured JSON access log line per request to "
130
+ "stderr. Off by default; useful for compliance/audit. "
131
+ "Authorization headers are NEVER logged."))
132
+ s.add_argument("--print-port-to", default=None,
133
+ help="Write the bound port to this file (for test orchestration).")
134
+ s.set_defaults(func=_cmd_serve)
135
+
136
+ e = sub.add_parser("emit", help="Emit static registry JSON from a proofs dir.")
137
+ e.add_argument("proofs_dir")
138
+ e.add_argument("output_dir")
139
+ e.add_argument("--base-url", required=True)
140
+ e.add_argument("--name", default="Proof Registry")
141
+ e.set_defaults(func=_cmd_emit)
142
+
143
+ l = sub.add_parser("lookup", help="Look up a claim across configured registries.")
144
+ l.add_argument("claim")
145
+ l.add_argument("--json", action="store_true")
146
+ l.add_argument("--pretty", action="store_true")
147
+ l.set_defaults(func=_cmd_lookup)
148
+
149
+ pub = sub.add_parser("publish", help="Publish a proof.json to the publish-target registry.")
150
+ pub.add_argument("proof_json")
151
+ pub.set_defaults(func=_cmd_publish)
152
+
153
+ return p
154
+
155
+
156
+ def main(argv=None) -> int:
157
+ parser = build_parser()
158
+ args = parser.parse_args(argv)
159
+ return args.func(args)
160
+
161
+
162
+ if __name__ == "__main__":
163
+ raise SystemExit(main())
@@ -0,0 +1,100 @@
1
+ """Registry client. Talks the Registry Protocol v0.1.
2
+
3
+ Respects configured registry order. Never performs implicit fallback — the
4
+ caller must set fallback=True on a registry to permit querying it after a
5
+ miss on the previous registry.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from dataclasses import dataclass
11
+ from typing import Optional
12
+
13
+ import requests
14
+
15
+ from proof_engine_registry import __protocol_version__
16
+ from proof_engine_registry.config import Registry
17
+ from proof_engine_registry.hashing import hash_claim
18
+ from proof_engine_registry.schema import Discovery, IndexEntry, from_json
19
+
20
+
21
+ class ProtocolVersionMismatch(Exception):
22
+ """Registry speaks a higher major protocol version than the client."""
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class LookupHit:
27
+ registry_name: str
28
+ entry: IndexEntry
29
+
30
+ # Convenience accessors mirror IndexEntry fields.
31
+ @property
32
+ def slug(self) -> str: return self.entry.slug
33
+ @property
34
+ def claim(self) -> str: return self.entry.claim
35
+ @property
36
+ def verdict(self) -> str: return self.entry.verdict
37
+ @property
38
+ def confidence(self) -> float: return self.entry.confidence
39
+ @property
40
+ def doi(self) -> Optional[str]: return self.entry.doi
41
+ @property
42
+ def proof_url(self) -> str: return self.entry.proof_url
43
+ @property
44
+ def badge_url(self) -> str: return self.entry.badge_url
45
+
46
+
47
+ class RegistryClient:
48
+ def __init__(self, registries: list[Registry], timeout: float = 10.0):
49
+ self.registries = registries
50
+ self.timeout = timeout
51
+ self._client_major, self._client_minor = (
52
+ int(x) for x in __protocol_version__.split(".")
53
+ )
54
+
55
+ def _headers(self, registry: Registry) -> dict:
56
+ if registry.token:
57
+ return {"Authorization": f"Bearer {registry.token}"}
58
+ return {}
59
+
60
+ def _get(self, registry: Registry, path: str) -> Optional[dict]:
61
+ url = f"{registry.url}{path}"
62
+ resp = requests.get(url, headers=self._headers(registry),
63
+ timeout=self.timeout)
64
+ if resp.status_code == 404:
65
+ return None
66
+ resp.raise_for_status()
67
+ return resp.json()
68
+
69
+ def discovery(self, registry: Registry) -> Discovery:
70
+ data = self._get(registry, "/.well-known/proof-registry.json")
71
+ if data is None:
72
+ raise RuntimeError(f"Registry {registry.name} has no discovery doc")
73
+ disco = from_json(Discovery, data)
74
+ major = int(disco.protocol_version.split(".")[0])
75
+ if major > self._client_major:
76
+ raise ProtocolVersionMismatch(
77
+ f"Registry {registry.name} speaks v{disco.protocol_version}, "
78
+ f"client supports v{__protocol_version__}"
79
+ )
80
+ return disco
81
+
82
+ def lookup(self, claim: str) -> Optional[LookupHit]:
83
+ """Return the first registry hit for the claim, or None.
84
+
85
+ Walks registries in order. If a registry returns 404, continues
86
+ only if the NEXT registry has fallback=True.
87
+ """
88
+ claim_hash_hex = hash_claim(claim)
89
+ previous_was_miss = False
90
+ for i, registry in enumerate(self.registries):
91
+ if i > 0 and previous_was_miss and not registry.fallback:
92
+ break # explicit no-fallback boundary
93
+ data = self._get(registry, f"/claims/{claim_hash_hex}.json")
94
+ if data is not None:
95
+ return LookupHit(
96
+ registry_name=registry.name,
97
+ entry=from_json(IndexEntry, data),
98
+ )
99
+ previous_was_miss = True
100
+ return None
@@ -0,0 +1,68 @@
1
+ """Load registry configuration from ~/.config/proof-engine/registries.toml.
2
+
3
+ Tokens are never stored in the config file — only the NAME of the env var
4
+ that holds the token.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import tomllib
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+ from typing import Optional
14
+
15
+
16
+ class DuplicatePublishError(Exception):
17
+ """More than one registry configured with publish = true."""
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Registry:
22
+ name: str
23
+ url: str
24
+ token: Optional[str] = None
25
+ publish: bool = False
26
+ fallback: bool = False # implicit fallback from prior registry
27
+
28
+
29
+ def default_config_path() -> Path:
30
+ xdg = os.environ.get("XDG_CONFIG_HOME")
31
+ base = Path(xdg) if xdg else Path.home() / ".config"
32
+ return base / "proof-engine" / "registries.toml"
33
+
34
+
35
+ def load_registries() -> list[Registry]:
36
+ return load_registries_from_path(default_config_path())
37
+
38
+
39
+ def load_registries_from_path(path: Path) -> list[Registry]:
40
+ if not path.exists():
41
+ return []
42
+ data = tomllib.loads(path.read_text())
43
+ raw_list = data.get("registry", [])
44
+ regs: list[Registry] = []
45
+ for raw in raw_list:
46
+ token = None
47
+ if "token_env" in raw:
48
+ env_name = raw["token_env"]
49
+ token = os.environ.get(env_name)
50
+ if token is None:
51
+ raise RuntimeError(
52
+ f"Registry {raw.get('name', '?')!r} expects env var "
53
+ f"{env_name!r} but it is not set."
54
+ )
55
+ regs.append(Registry(
56
+ name=raw["name"],
57
+ url=raw["url"].rstrip("/"),
58
+ token=token,
59
+ publish=bool(raw.get("publish", False)),
60
+ fallback=bool(raw.get("fallback", False)),
61
+ ))
62
+ publish_targets = [r for r in regs if r.publish]
63
+ if len(publish_targets) > 1:
64
+ raise DuplicatePublishError(
65
+ f"Multiple publish targets configured: "
66
+ f"{[r.name for r in publish_targets]}"
67
+ )
68
+ return regs