rssa 0.1.1__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.
- rssa/__init__.py +11 -0
- rssa/__main__.py +93 -0
- rssa/agent.py +260 -0
- rssa/canonical.py +125 -0
- rssa/feed.py +331 -0
- rssa/integrations/__init__.py +1 -0
- rssa/integrations/crewai.py +51 -0
- rssa/integrations/langchain.py +32 -0
- rssa/keys.py +176 -0
- rssa/policy.py +124 -0
- rssa/sign.py +105 -0
- rssa/tools.py +69 -0
- rssa-0.1.1.dist-info/METADATA +39 -0
- rssa-0.1.1.dist-info/RECORD +18 -0
- rssa-0.1.1.dist-info/WHEEL +5 -0
- rssa-0.1.1.dist-info/entry_points.txt +2 -0
- rssa-0.1.1.dist-info/licenses/LICENSE +202 -0
- rssa-0.1.1.dist-info/top_level.txt +1 -0
rssa/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""RSS-A (RSS for Agents): publish, sign, read and verify agent feeds and groups."""
|
|
2
|
+
|
|
3
|
+
from .agent import (EXT_URI, MEDIA_TYPES, FeedRead, ReadEntry, build_feed, card_extension, card_modules, entry, find_rssa, local_filter,
|
|
4
|
+
now, ping_hub, read_feed, read_group, GroupRead, sign_card, with_rssa)
|
|
5
|
+
from .canonical import CanonicalError, canonicalize, strict_parse
|
|
6
|
+
from .feed import Entry, ParsedFeed, atom_xml, json_feed, parse_feed, rss_xml
|
|
7
|
+
from .keys import Key, generate_key, key_from_jwk, key_from_seed, load_key, resolve_keys, sign_detached, thumbprint, verify_detached
|
|
8
|
+
from .policy import CORE_TYPES, PRESETS, check_entry, effective_settings, roster_opml, sign_policy, verify_policy
|
|
9
|
+
from .sign import content_hash, content_hash_input, entry_payload, sign_entry, verify_entry
|
|
10
|
+
|
|
11
|
+
__version__ = "0.1.1"
|
rssa/__main__.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""python -m rssa — keygen, add-to-card, verify, sign-policy."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from . import generate_key, load_key, read_feed, roster_opml, sign_card, sign_policy, with_rssa
|
|
9
|
+
from .canonical import strict_parse
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def main(argv=None) -> int:
|
|
13
|
+
ap = argparse.ArgumentParser(prog="rssa", description="RSS-A (RSS for Agents). Full validation: rssa validate <url> (the Node CLI, bin/rssa in the repo)")
|
|
14
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
15
|
+
k = sub.add_parser("keygen", help="create an Ed25519 key; prints the public JWKS for your card")
|
|
16
|
+
k.add_argument("--out", default="rssa-key.json")
|
|
17
|
+
a = sub.add_parser("add-to-card", help="add the RSSA extension line to an Agent Card file, in place")
|
|
18
|
+
a.add_argument("card")
|
|
19
|
+
a.add_argument("--feed", required=True)
|
|
20
|
+
a.add_argument("--key")
|
|
21
|
+
a.add_argument("--modules")
|
|
22
|
+
sc = sub.add_parser("sign-card", help="sign an Agent Card (A2A native signatures field), in place")
|
|
23
|
+
sc.add_argument("card")
|
|
24
|
+
sc.add_argument("--key", required=True)
|
|
25
|
+
v = sub.add_parser("verify", help="fetch a feed and verify every signed entry")
|
|
26
|
+
v.add_argument("url")
|
|
27
|
+
p = sub.add_parser("sign-policy", help="sign a group policy.json in place and write roster.opml beside it")
|
|
28
|
+
p.add_argument("policy")
|
|
29
|
+
p.add_argument("--key", required=True)
|
|
30
|
+
args = ap.parse_args(argv)
|
|
31
|
+
|
|
32
|
+
if args.cmd == "keygen":
|
|
33
|
+
if os.path.exists(args.out):
|
|
34
|
+
print(f"rssa: {args.out} exists; refusing to overwrite a key", file=sys.stderr)
|
|
35
|
+
return 2
|
|
36
|
+
key = generate_key()
|
|
37
|
+
fd = os.open(args.out, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
38
|
+
with os.fdopen(fd, "w") as f:
|
|
39
|
+
json.dump(key.private_jwk, f, indent=2)
|
|
40
|
+
print(f"Private key written to {args.out}. Keep it secret; load it at runtime with rssa.load_key() or RSSA_KEY.", file=sys.stderr)
|
|
41
|
+
print("Paste this into your Agent Card's RSSA params as \"keys\":", file=sys.stderr)
|
|
42
|
+
print(json.dumps(key.public_jwks(), indent=2))
|
|
43
|
+
return 0
|
|
44
|
+
if args.cmd == "add-to-card":
|
|
45
|
+
with open(args.card, encoding="utf-8") as f:
|
|
46
|
+
card = json.load(f)
|
|
47
|
+
key = load_key(args.key) if args.key else None
|
|
48
|
+
modules = args.modules.split(",") if args.modules else (["sign"] if key else None)
|
|
49
|
+
card = with_rssa(card, feed=args.feed, modules=modules, keys=key.public_jwks() if key else None)
|
|
50
|
+
with open(args.card, "w", encoding="utf-8") as f:
|
|
51
|
+
json.dump(card, f, indent=2, ensure_ascii=False)
|
|
52
|
+
f.write("\n")
|
|
53
|
+
print(f"Added the RSSA extension to {args.card}. Next: publish {args.feed}, then sign the card (rssa sign-card) and run: rssa validate <your agent URL>")
|
|
54
|
+
return 0
|
|
55
|
+
if args.cmd == "sign-card":
|
|
56
|
+
with open(args.card, encoding="utf-8") as f:
|
|
57
|
+
card = json.load(f)
|
|
58
|
+
signed = sign_card(card, load_key(args.key)) # before opening for write, so a bad key can't truncate the card
|
|
59
|
+
with open(args.card, "w", encoding="utf-8") as f:
|
|
60
|
+
json.dump(signed, f, indent=2, ensure_ascii=False)
|
|
61
|
+
f.write("\n")
|
|
62
|
+
print(f"Signed {args.card}. Re-sign after every change to the card.")
|
|
63
|
+
return 0
|
|
64
|
+
if args.cmd == "verify":
|
|
65
|
+
r = read_feed(args.url, require_signatures=False)
|
|
66
|
+
bad = 0
|
|
67
|
+
for e in r.entries:
|
|
68
|
+
mark = "OK " if e.verified else ("- " if not e.entry.sig else "BAD")
|
|
69
|
+
bad += bool(e.entry.sig and not e.verified)
|
|
70
|
+
print(f"{mark} {e.entry.id} {e.entry.type or ''}")
|
|
71
|
+
for c in e.checks:
|
|
72
|
+
if not c.ok:
|
|
73
|
+
print(f" {c.message}")
|
|
74
|
+
for msg in r.problems:
|
|
75
|
+
print(f"WARN {msg}")
|
|
76
|
+
return 1 if bad or r.problems else 0
|
|
77
|
+
if args.cmd == "sign-policy":
|
|
78
|
+
with open(args.policy, encoding="utf-8") as f:
|
|
79
|
+
policy = strict_parse(f.read())
|
|
80
|
+
signed = sign_policy(policy, load_key(args.key))
|
|
81
|
+
with open(args.policy, "w", encoding="utf-8") as f:
|
|
82
|
+
json.dump(signed, f, indent=2, ensure_ascii=False)
|
|
83
|
+
f.write("\n")
|
|
84
|
+
opml = os.path.join(os.path.dirname(args.policy) or ".", "roster.opml")
|
|
85
|
+
with open(opml, "w", encoding="utf-8") as f:
|
|
86
|
+
f.write(roster_opml(signed))
|
|
87
|
+
print(f"Signed {args.policy} (version {signed['version']}) and wrote {opml}. Bump version on every change.")
|
|
88
|
+
return 0
|
|
89
|
+
return 2
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
if __name__ == "__main__":
|
|
93
|
+
sys.exit(main())
|
rssa/agent.py
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
"""High-level helpers: the Agent Card line, publishing, reading and local filtering."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import uuid
|
|
6
|
+
from dataclasses import dataclass, field, replace
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from typing import Any, Optional
|
|
9
|
+
|
|
10
|
+
from .feed import Entry, ParsedFeed, atom_xml, json_feed, parse_feed, rss_xml
|
|
11
|
+
from .keys import Fetch, Key, get_json, http_get, resolve_keys
|
|
12
|
+
from .sign import Check, sign_entry, verify_entry
|
|
13
|
+
|
|
14
|
+
EXT_URI = "https://rssa.getvda.ai/ext/v0.1"
|
|
15
|
+
EXT_PREFIX = "https://rssa.getvda.ai/ext/"
|
|
16
|
+
USER_AGENT = "rssa-sdk-py/0.1 (+https://rssa.getvda.ai)"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def card_extension(feed: str, modules: Optional[list[str]] = None, hub: Optional[str] = None,
|
|
20
|
+
groups: Optional[list[str]] = None, keys: Any = None) -> dict:
|
|
21
|
+
"""The one Agent Card line. Put it in card["capabilities"]["extensions"]."""
|
|
22
|
+
params: dict = {"feed": feed}
|
|
23
|
+
if modules:
|
|
24
|
+
params["modules"] = modules
|
|
25
|
+
if hub:
|
|
26
|
+
params["hub"] = hub
|
|
27
|
+
if groups:
|
|
28
|
+
params["groups"] = groups
|
|
29
|
+
if keys:
|
|
30
|
+
params["keys"] = keys
|
|
31
|
+
return {"uri": EXT_URI, "description": "RSSA: this agent's feed and modules", "required": False, "params": params}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def with_rssa(card: dict, **params) -> dict:
|
|
35
|
+
"""Returns a copy of an Agent Card with the RSSA extension added or replaced."""
|
|
36
|
+
caps = dict(card.get("capabilities") or {})
|
|
37
|
+
exts = [e for e in caps.get("extensions", []) if not str(e.get("uri", "")).startswith(EXT_PREFIX)]
|
|
38
|
+
caps["extensions"] = exts + [card_extension(**params)]
|
|
39
|
+
return {**card, "capabilities": caps}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def find_rssa(card: Any) -> Optional[dict]:
|
|
43
|
+
for e in ((card or {}).get("capabilities") or {}).get("extensions", []):
|
|
44
|
+
if str(e.get("uri", "")).startswith(EXT_PREFIX):
|
|
45
|
+
return e
|
|
46
|
+
return None
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def card_modules(card: Any) -> list[str]:
|
|
50
|
+
ext = find_rssa(card)
|
|
51
|
+
return [str(m).split("@")[0] for m in ((ext or {}).get("params") or {}).get("modules", [])]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def sign_card(card: dict, key: Key) -> dict:
|
|
55
|
+
"""Signs an Agent Card with A2A's native `signatures` field (JWS over the RFC 8785 canonical card).
|
|
56
|
+
Re-sign after every change to the card."""
|
|
57
|
+
from .canonical import canonicalize
|
|
58
|
+
from .keys import sign_detached
|
|
59
|
+
|
|
60
|
+
body = {k: v for k, v in card.items() if k != "signatures"}
|
|
61
|
+
protected, _, signature = sign_detached(canonicalize(body).encode("utf-8"), key).split(".")
|
|
62
|
+
return {**body, "signatures": [{"protected": protected, "signature": signature}]}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def now() -> str:
|
|
66
|
+
return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def entry(title: Optional[str] = None, summary: Optional[str] = None, content: Optional[str] = None, *,
|
|
70
|
+
type: Optional[str] = None, to: Optional[str] = None, source: Optional[str] = None,
|
|
71
|
+
in_reply_to: Optional[str] = None, reaction: Optional[str] = None, id: Optional[str] = None,
|
|
72
|
+
updated: Optional[str] = None, link: Optional[str] = None, content_type: Optional[str] = None) -> Entry:
|
|
73
|
+
"""A new entry with a urn:uuid id and the current time (whole seconds) unless given."""
|
|
74
|
+
return Entry(id=id or f"urn:uuid:{uuid.uuid4()}", updated=updated or now(), title=title, summary=summary, content=content,
|
|
75
|
+
content_type=content_type, link=link, type=type, to=to, source=source, in_reply_to=in_reply_to, reaction=reaction)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# Content-Type to serve each format with.
|
|
79
|
+
MEDIA_TYPES = {"atom": "application/atom+xml", "rss": "application/rss+xml", "json": "application/feed+json"}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def build_feed(feed_url: str, title: str, entries: list[Entry], key: Optional[Key] = None, card_url: Optional[str] = None,
|
|
83
|
+
hub_url: Optional[str] = None, author: Optional[str] = None, format: str = "atom") -> str:
|
|
84
|
+
"""Builds a complete feed: format "atom" (default), "rss" (RSS 2.0) or "json" (JSON Feed 1.1).
|
|
85
|
+
With a key every entry is signed. Returns a string: store it wherever your platform keeps
|
|
86
|
+
files (disk, GCS, S3, a route handler) and serve it with MEDIA_TYPES[format]."""
|
|
87
|
+
if format not in MEDIA_TYPES:
|
|
88
|
+
raise ValueError(f"format must be one of {sorted(MEDIA_TYPES)}")
|
|
89
|
+
seen = set()
|
|
90
|
+
for e in entries:
|
|
91
|
+
if e.id in seen:
|
|
92
|
+
raise ValueError(f"duplicate entry id {e.id}")
|
|
93
|
+
seen.add(e.id)
|
|
94
|
+
ordered = sorted(entries, key=lambda e: e.updated, reverse=True)
|
|
95
|
+
if key:
|
|
96
|
+
ordered = [sign_entry(e, feed_url, key) for e in ordered]
|
|
97
|
+
if format == "rss":
|
|
98
|
+
return rss_xml(feed_url, title, ordered, card_url=card_url, hub_url=hub_url)
|
|
99
|
+
if format == "json":
|
|
100
|
+
return json_feed(feed_url, title, ordered, card_url=card_url, hub_url=hub_url)
|
|
101
|
+
return atom_xml(feed_url, title, ordered, card_url=card_url, hub_url=hub_url, author=author)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def ping_hub(hub_url: str, feed_url: str) -> int:
|
|
105
|
+
"""Tells a WebSub hub the feed changed. Never raises; returns the HTTP status (0 on network error)."""
|
|
106
|
+
import urllib.parse
|
|
107
|
+
import urllib.request
|
|
108
|
+
|
|
109
|
+
data = urllib.parse.urlencode({"hub.mode": "publish", "hub.url": feed_url}).encode()
|
|
110
|
+
try:
|
|
111
|
+
with urllib.request.urlopen(urllib.request.Request(hub_url, data=data, headers={"User-Agent": USER_AGENT}), timeout=10) as r:
|
|
112
|
+
return r.status
|
|
113
|
+
except Exception as e: # noqa: BLE001
|
|
114
|
+
return getattr(e, "code", 0)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass
|
|
118
|
+
class ReadEntry:
|
|
119
|
+
entry: Entry
|
|
120
|
+
verified: bool
|
|
121
|
+
source: str # the feed the entry is attributed to
|
|
122
|
+
checks: list[Check] = field(default_factory=list)
|
|
123
|
+
|
|
124
|
+
def __getattr__(self, name): # entry fields read through: r.type, r.summary …
|
|
125
|
+
return getattr(self.entry, name)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@dataclass
|
|
129
|
+
class FeedRead:
|
|
130
|
+
feed: ParsedFeed
|
|
131
|
+
card: Optional[dict]
|
|
132
|
+
keys: list[dict]
|
|
133
|
+
entries: list[ReadEntry]
|
|
134
|
+
problems: list[str]
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def read_feed(url: str, fetch: Optional[Fetch] = None, require_signatures: Optional[bool] = None, reader_card: Optional[str] = None) -> FeedRead:
|
|
138
|
+
"""Fetches a feed, follows rel=describedby to the card, checks it points back, verifies signatures.
|
|
139
|
+
Pass reader_card (your own Agent Card URL) so publishers and hubs can count real subscribers."""
|
|
140
|
+
ua = f"{USER_AGENT} reader={reader_card}" if reader_card else USER_AGENT
|
|
141
|
+
fetch = fetch or (lambda u: http_get(u, accept="application/atom+xml, application/rss+xml, application/feed+json, application/json", user_agent=ua))
|
|
142
|
+
status, text = fetch(url)
|
|
143
|
+
if status != 200:
|
|
144
|
+
raise ValueError(f"GET {url} returned {status}")
|
|
145
|
+
feed = parse_feed(text)
|
|
146
|
+
problems = list(feed.problems)
|
|
147
|
+
feed_url = feed.self_url or url
|
|
148
|
+
card, keys = None, []
|
|
149
|
+
no_keys_reason = None if feed.card_url else "the feed has no rel=describedby link to an Agent Card, so there are no keys to check against"
|
|
150
|
+
if feed.card_url:
|
|
151
|
+
try:
|
|
152
|
+
card = get_json(feed.card_url, fetch)
|
|
153
|
+
ext = find_rssa(card)
|
|
154
|
+
if not ext:
|
|
155
|
+
problems.append(f"card {feed.card_url} has no RSSA extension")
|
|
156
|
+
no_keys_reason = f"the Agent Card {feed.card_url} has no RSS-A line yet, so it does not vouch for this feed or publish keys"
|
|
157
|
+
elif ext["params"].get("feed") != feed_url:
|
|
158
|
+
problems.append(f"card names feed {ext['params'].get('feed')}, not {feed_url} — it does not vouch for this feed")
|
|
159
|
+
no_keys_reason = f"the Agent Card names feed {ext['params'].get('feed')}, not this one, so its keys do not apply here"
|
|
160
|
+
elif ext["params"].get("keys"):
|
|
161
|
+
keys = resolve_keys(ext["params"]["keys"], fetch)
|
|
162
|
+
except Exception as e: # noqa: BLE001
|
|
163
|
+
problems.append(f"card: {e}")
|
|
164
|
+
if require_signatures is None:
|
|
165
|
+
require_signatures = "sign" in card_modules(card)
|
|
166
|
+
out = []
|
|
167
|
+
for e in feed.entries:
|
|
168
|
+
attributed = e.source_feed or feed_url
|
|
169
|
+
if not e.sig:
|
|
170
|
+
if require_signatures:
|
|
171
|
+
problems.append(f"dropped unsigned entry {e.id}")
|
|
172
|
+
else:
|
|
173
|
+
out.append(ReadEntry(e, False, attributed))
|
|
174
|
+
continue
|
|
175
|
+
k = keys
|
|
176
|
+
if e.source_feed and e.source_feed != feed_url and e.source_card:
|
|
177
|
+
try:
|
|
178
|
+
c = get_json(e.source_card, fetch)
|
|
179
|
+
x = find_rssa(c)
|
|
180
|
+
k = resolve_keys(x["params"]["keys"], fetch) if x and x["params"].get("feed") == e.source_feed and x["params"].get("keys") else []
|
|
181
|
+
except Exception: # noqa: BLE001
|
|
182
|
+
k = []
|
|
183
|
+
v = verify_entry(e, attributed, k)
|
|
184
|
+
if not k and attributed == feed_url and no_keys_reason:
|
|
185
|
+
# Say why there is nothing to verify against, instead of a bare key-id error.
|
|
186
|
+
v.checks = [c for c in v.checks if c.code != "signature"] + [Check(False, "signature", f"cannot verify: {no_keys_reason}")]
|
|
187
|
+
if v.ok or not require_signatures:
|
|
188
|
+
out.append(ReadEntry(e, v.ok, attributed, v.checks))
|
|
189
|
+
else:
|
|
190
|
+
problems.append(f"dropped entry {e.id}: " + "; ".join(c.message for c in v.checks if not c.ok))
|
|
191
|
+
return FeedRead(feed, card, keys, out, problems)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def local_filter(entries: list[ReadEntry], signed_only: bool = False, types: Optional[list[str]] = None,
|
|
195
|
+
to: Optional[list[str]] = None, sources: Optional[list[str]] = None) -> list[ReadEntry]:
|
|
196
|
+
"""Consumer-side guardrail, applied with plain code before any model reads an entry.
|
|
197
|
+
Type patterns ending in "." match prefixes ("exception."). Entries without rssa:to count as "group"."""
|
|
198
|
+
def type_ok(t):
|
|
199
|
+
return types is None or (t is not None and any(t == p or (p.endswith(".") and t.startswith(p)) for p in types))
|
|
200
|
+
return [r for r in entries
|
|
201
|
+
if (not signed_only or r.verified) and type_ok(r.entry.type)
|
|
202
|
+
and (to is None or (r.entry.to or "group") in to) and (sources is None or r.source in sources)]
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
@dataclass
|
|
206
|
+
class GroupRead:
|
|
207
|
+
policy: dict
|
|
208
|
+
policy_verified: bool
|
|
209
|
+
entries: list[ReadEntry] # newest first
|
|
210
|
+
problems: list[str]
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def read_group(policy_url: str, fetch: Optional[Fetch] = None, reader_card: Optional[str] = None) -> GroupRead:
|
|
214
|
+
"""Hubless group reading (open groups, two-party links, or checking a hub): fetches and
|
|
215
|
+
verifies the policy, reads every member feed, checks two-way membership, then applies
|
|
216
|
+
the group's policy in time order. Dropped entries are listed in `problems` with the reason."""
|
|
217
|
+
from datetime import datetime as _dt
|
|
218
|
+
|
|
219
|
+
from .policy import check_entry, effective_settings, verify_policy
|
|
220
|
+
|
|
221
|
+
ua = f"{USER_AGENT} reader={reader_card}" if reader_card else USER_AGENT
|
|
222
|
+
fetch = fetch or (lambda u: http_get(u, accept="application/atom+xml, application/rss+xml, application/feed+json, application/json", user_agent=ua))
|
|
223
|
+
policy = get_json(policy_url, fetch)
|
|
224
|
+
problems: list[str] = []
|
|
225
|
+
pok, perr = verify_policy(policy, fetch)
|
|
226
|
+
if not pok:
|
|
227
|
+
problems.append(f"policy signature: {perr}")
|
|
228
|
+
s = effective_settings(policy)
|
|
229
|
+
refs = {policy.get("group"), policy_url}
|
|
230
|
+
every: list[ReadEntry] = []
|
|
231
|
+
for m in policy.get("members", []):
|
|
232
|
+
try:
|
|
233
|
+
fr = read_feed(m["feed"], fetch=fetch, require_signatures=s["signatures"] == "required" or None)
|
|
234
|
+
except Exception as e: # noqa: BLE001
|
|
235
|
+
problems.append(f"{m['feed']}: {e}")
|
|
236
|
+
continue
|
|
237
|
+
groups = (((find_rssa(fr.card) or {}).get("params")) or {}).get("groups") or []
|
|
238
|
+
if not refs & set(groups):
|
|
239
|
+
problems.append(f"{m['feed']}: its Agent Card does not list this group — not a member (two-way membership)")
|
|
240
|
+
continue
|
|
241
|
+
problems += [f"{m['feed']}: {p}" for p in fr.problems]
|
|
242
|
+
every += fr.entries
|
|
243
|
+
ts = lambda r: _dt.fromisoformat(r.entry.updated.replace("Z", "+00:00")).timestamp()
|
|
244
|
+
every.sort(key=ts)
|
|
245
|
+
depth: dict[str, int] = {}
|
|
246
|
+
root: dict[str, str] = {}
|
|
247
|
+
last: dict[str, float] = {}
|
|
248
|
+
kept: list[ReadEntry] = []
|
|
249
|
+
for r in every:
|
|
250
|
+
e = r.entry
|
|
251
|
+
v = check_entry(e, r.source, s, depth_of=depth.get, root_of=root.get, last_post=lambda f, rt: last.get(f"{f} {rt}"))
|
|
252
|
+
if v:
|
|
253
|
+
problems.append(f"dropped {e.id}: " + "; ".join(m for _, m in v))
|
|
254
|
+
continue
|
|
255
|
+
d = depth.get(e.in_reply_to, 0) + 1 if e.in_reply_to else 0
|
|
256
|
+
rt = root.get(e.in_reply_to, e.in_reply_to) if e.in_reply_to else e.id
|
|
257
|
+
depth[e.id], root[e.id] = d, rt
|
|
258
|
+
last[f"{r.source} {rt}"] = ts(r)
|
|
259
|
+
kept.append(r)
|
|
260
|
+
return GroupRead(policy, pok, list(reversed(kept)), problems)
|
rssa/canonical.py
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""RSSA canonical JSON: RFC 8785 (JCS) restricted to the RSSA signable subset.
|
|
2
|
+
|
|
3
|
+
Signable values are strings, booleans, safe integers (|n| <= 2**53 - 1), None, lists and
|
|
4
|
+
dicts of those. No floats, no exponents, no duplicate keys, no lone surrogates. Inside that
|
|
5
|
+
subset JCS has exactly one correct output, so Python and JavaScript produce identical bytes.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import re
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
MAX_SAFE = 2**53 - 1
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class CanonicalError(ValueError):
|
|
18
|
+
def __init__(self, code: str, message: str, path: str = "$"):
|
|
19
|
+
super().__init__(f"{message} (at {path})")
|
|
20
|
+
self.code = code
|
|
21
|
+
self.path = path
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
_NUMBER = re.compile(r"-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def strict_parse(text: str) -> Any:
|
|
28
|
+
"""Parses JSON, rejecting floats, exponents, unsafe integers, duplicate keys and lone surrogates."""
|
|
29
|
+
|
|
30
|
+
def pairs(items):
|
|
31
|
+
out = {}
|
|
32
|
+
for k, v in items:
|
|
33
|
+
if k in out:
|
|
34
|
+
raise CanonicalError("duplicate-key", f"duplicate key {json.dumps(k)}")
|
|
35
|
+
out[k] = v
|
|
36
|
+
return out
|
|
37
|
+
|
|
38
|
+
def bad_float(s):
|
|
39
|
+
raise CanonicalError("float", f"number {s} is not an integer — send amounts and measurements as strings, e.g. \"12.50\"")
|
|
40
|
+
|
|
41
|
+
def check_int(s):
|
|
42
|
+
n = int(s)
|
|
43
|
+
if abs(n) > MAX_SAFE:
|
|
44
|
+
raise CanonicalError("unsafe-integer", f"integer {s} is outside ±(2^53-1) — send it as a string")
|
|
45
|
+
return n
|
|
46
|
+
|
|
47
|
+
def bad_constant(s):
|
|
48
|
+
raise CanonicalError("syntax", f"{s} is not JSON")
|
|
49
|
+
|
|
50
|
+
try:
|
|
51
|
+
value = json.loads(text, object_pairs_hook=pairs, parse_float=bad_float, parse_int=check_int, parse_constant=bad_constant)
|
|
52
|
+
except CanonicalError:
|
|
53
|
+
raise
|
|
54
|
+
except json.JSONDecodeError as e:
|
|
55
|
+
code = "syntax"
|
|
56
|
+
raise CanonicalError(code, e.msg + f" at offset {e.pos}") from None
|
|
57
|
+
_check_strings(value, "$")
|
|
58
|
+
return value
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _check_strings(v: Any, path: str) -> None:
|
|
62
|
+
if isinstance(v, str):
|
|
63
|
+
_assert_well_formed(v, path)
|
|
64
|
+
elif isinstance(v, list):
|
|
65
|
+
for i, x in enumerate(v):
|
|
66
|
+
_check_strings(x, f"{path}[{i}]")
|
|
67
|
+
elif isinstance(v, dict):
|
|
68
|
+
for k, x in v.items():
|
|
69
|
+
_assert_well_formed(k, path)
|
|
70
|
+
_check_strings(x, f"{path}.{k}")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _assert_well_formed(s: str, path: str) -> None:
|
|
74
|
+
for ch in s:
|
|
75
|
+
if 0xD800 <= ord(ch) <= 0xDFFF:
|
|
76
|
+
raise CanonicalError("lone-surrogate", "string contains a lone surrogate", path)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
_SHORT = {'"': '\\"', "\\": "\\\\", "\b": "\\b", "\f": "\\f", "\n": "\\n", "\r": "\\r", "\t": "\\t"}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _quote(s: str) -> str:
|
|
83
|
+
out = ['"']
|
|
84
|
+
for ch in s:
|
|
85
|
+
if ch in _SHORT:
|
|
86
|
+
out.append(_SHORT[ch])
|
|
87
|
+
elif ord(ch) < 0x20:
|
|
88
|
+
out.append("\\u%04x" % ord(ch))
|
|
89
|
+
else:
|
|
90
|
+
out.append(ch)
|
|
91
|
+
out.append('"')
|
|
92
|
+
return "".join(out)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _utf16_key(k: str) -> bytes:
|
|
96
|
+
# JCS sorts keys by UTF-16 code units; big-endian UTF-16 bytes compare the same way.
|
|
97
|
+
return k.encode("utf-16-be")
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def canonicalize(v: Any, path: str = "$") -> str:
|
|
101
|
+
"""Canonical JSON text of a value in the RSSA signable subset. Raises CanonicalError otherwise."""
|
|
102
|
+
if v is None:
|
|
103
|
+
return "null"
|
|
104
|
+
if v is True:
|
|
105
|
+
return "true"
|
|
106
|
+
if v is False:
|
|
107
|
+
return "false"
|
|
108
|
+
if isinstance(v, str):
|
|
109
|
+
_assert_well_formed(v, path)
|
|
110
|
+
return _quote(v)
|
|
111
|
+
if isinstance(v, int):
|
|
112
|
+
if abs(v) > MAX_SAFE:
|
|
113
|
+
raise CanonicalError("unsafe-integer", f"integer {v} is outside ±(2^53-1)", path)
|
|
114
|
+
return str(v)
|
|
115
|
+
if isinstance(v, float):
|
|
116
|
+
raise CanonicalError("float", f"number {v} is not an integer — send it as a string", path)
|
|
117
|
+
if isinstance(v, (list, tuple)):
|
|
118
|
+
return "[" + ",".join(canonicalize(x, f"{path}[{i}]") for i, x in enumerate(v)) + "]"
|
|
119
|
+
if isinstance(v, dict):
|
|
120
|
+
for k in v:
|
|
121
|
+
if not isinstance(k, str):
|
|
122
|
+
raise CanonicalError("type", "object keys must be strings", path)
|
|
123
|
+
_assert_well_formed(k, path)
|
|
124
|
+
return "{" + ",".join(_quote(k) + ":" + canonicalize(v[k], f"{path}.{k}") for k in sorted(v, key=_utf16_key)) + "}"
|
|
125
|
+
raise CanonicalError("type", f"type {type(v).__name__} cannot be signed", path)
|