snareline 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.
- snareline/__init__.py +31 -0
- snareline/__main__.py +5 -0
- snareline/_util.py +109 -0
- snareline/_version.py +1 -0
- snareline/alerts.py +181 -0
- snareline/attribution.py +132 -0
- snareline/cli.py +437 -0
- snareline/config.py +169 -0
- snareline/decoys.py +319 -0
- snareline/demo.py +153 -0
- snareline/detect.py +128 -0
- snareline/errors.py +32 -0
- snareline/hooks.py +229 -0
- snareline/keys.py +89 -0
- snareline/ledger.py +254 -0
- snareline/mcp_proxy.py +172 -0
- snareline/monitor.py +453 -0
- snareline/py.typed +0 -0
- snareline/redact.py +76 -0
- snareline/report.py +167 -0
- snareline-0.1.0.dist-info/METADATA +276 -0
- snareline-0.1.0.dist-info/RECORD +26 -0
- snareline-0.1.0.dist-info/WHEEL +4 -0
- snareline-0.1.0.dist-info/entry_points.txt +2 -0
- snareline-0.1.0.dist-info/licenses/LICENSE +202 -0
- snareline-0.1.0.dist-info/licenses/NOTICE +4 -0
snareline/__init__.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""Snareline: intrusion detection for AI agents.
|
|
2
|
+
|
|
3
|
+
Plant decoys an honest agent never touches, record every action in a signed
|
|
4
|
+
tamper-evident ledger, and raise an alert, with the suspected trigger, the
|
|
5
|
+
moment a hijacked agent takes the bait.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from ._version import __version__
|
|
9
|
+
from .alerts import Alert, MemorySink
|
|
10
|
+
from .config import Config, State
|
|
11
|
+
from .decoys import Decoy, DecoyRegistry
|
|
12
|
+
from .detect import Detector
|
|
13
|
+
from .errors import ConfigError, LedgerError, SnarelineError, SnareTriggered
|
|
14
|
+
from .monitor import Monitor, Session
|
|
15
|
+
|
|
16
|
+
__all__ = [
|
|
17
|
+
"__version__",
|
|
18
|
+
"Alert",
|
|
19
|
+
"Config",
|
|
20
|
+
"ConfigError",
|
|
21
|
+
"Decoy",
|
|
22
|
+
"DecoyRegistry",
|
|
23
|
+
"Detector",
|
|
24
|
+
"LedgerError",
|
|
25
|
+
"MemorySink",
|
|
26
|
+
"Monitor",
|
|
27
|
+
"Session",
|
|
28
|
+
"SnarelineError",
|
|
29
|
+
"SnareTriggered",
|
|
30
|
+
"State",
|
|
31
|
+
]
|
snareline/__main__.py
ADDED
snareline/_util.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Small internal helpers shared across modules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import secrets
|
|
9
|
+
import tempfile
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
# Crockford-style base32 without ambiguous characters. Used for decoy markers
|
|
15
|
+
# and identifiers so they survive case changes and are easy to read aloud.
|
|
16
|
+
_ALPHABET = "abcdefghjkmnpqrstvwxyz23456789"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def random_token(length: int, alphabet: str = _ALPHABET) -> str:
|
|
20
|
+
"""Return a cryptographically random token drawn from ``alphabet``."""
|
|
21
|
+
return "".join(secrets.choice(alphabet) for _ in range(length))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def new_id(prefix: str, length: int = 12) -> str:
|
|
25
|
+
return f"{prefix}_{random_token(length)}"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def utc_now() -> str:
|
|
29
|
+
"""ISO-8601 UTC timestamp with millisecond precision."""
|
|
30
|
+
return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def canonical_json(obj: Any) -> bytes:
|
|
34
|
+
"""Deterministic JSON encoding used for hashing and signing."""
|
|
35
|
+
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode("utf-8")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def to_jsonable(value: Any, max_depth: int = 8) -> Any:
|
|
39
|
+
"""Convert arbitrary Python values into JSON-safe structures.
|
|
40
|
+
|
|
41
|
+
Unknown objects are converted with ``repr`` so recording never fails just
|
|
42
|
+
because a tool returned something exotic.
|
|
43
|
+
"""
|
|
44
|
+
if max_depth <= 0:
|
|
45
|
+
return repr(value)
|
|
46
|
+
if value is None or isinstance(value, (bool, int, str)):
|
|
47
|
+
return value
|
|
48
|
+
if isinstance(value, float):
|
|
49
|
+
return value if value == value and value not in (float("inf"), float("-inf")) else repr(value)
|
|
50
|
+
if isinstance(value, bytes):
|
|
51
|
+
return value.decode("utf-8", errors="replace")
|
|
52
|
+
if isinstance(value, dict):
|
|
53
|
+
return {str(k): to_jsonable(v, max_depth - 1) for k, v in value.items()}
|
|
54
|
+
if isinstance(value, (list, tuple, set, frozenset)):
|
|
55
|
+
return [to_jsonable(v, max_depth - 1) for v in value]
|
|
56
|
+
return repr(value)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def flatten_text(value: Any) -> str:
|
|
60
|
+
"""Flatten any JSON-like value into one string for scanning."""
|
|
61
|
+
if isinstance(value, str):
|
|
62
|
+
return value
|
|
63
|
+
try:
|
|
64
|
+
return json.dumps(to_jsonable(value), ensure_ascii=False)
|
|
65
|
+
except (TypeError, ValueError):
|
|
66
|
+
return repr(value)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def atomic_write(path: Path, data: bytes, mode: int = 0o600) -> None:
|
|
70
|
+
"""Write ``data`` to ``path`` atomically with restrictive permissions."""
|
|
71
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
72
|
+
fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=".tmp-", suffix=path.suffix)
|
|
73
|
+
try:
|
|
74
|
+
with os.fdopen(fd, "wb") as fh:
|
|
75
|
+
fh.write(data)
|
|
76
|
+
fh.flush()
|
|
77
|
+
os.fsync(fh.fileno())
|
|
78
|
+
try:
|
|
79
|
+
os.chmod(tmp, mode)
|
|
80
|
+
except OSError: # pragma: no cover - permissions are advisory on Windows
|
|
81
|
+
pass
|
|
82
|
+
os.replace(tmp, path)
|
|
83
|
+
except BaseException:
|
|
84
|
+
try:
|
|
85
|
+
os.unlink(tmp)
|
|
86
|
+
except OSError:
|
|
87
|
+
pass
|
|
88
|
+
raise
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
_CONTROL = re.compile(r"[\x00-\x08\x0b-\x1f\x7f-\x9f\u202a-\u202e\u2066-\u2069]")
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def safe_term(value: object, limit: int = 500) -> str:
|
|
95
|
+
"""Neutralise control characters before printing attacker-influenced text.
|
|
96
|
+
|
|
97
|
+
Without this, a tool name or source containing ANSI escape sequences could
|
|
98
|
+
rewrite or hide lines in the operator's terminal (including our alerts),
|
|
99
|
+
and bidi overrides could make text read differently from what it is.
|
|
100
|
+
"""
|
|
101
|
+
text = str(value).replace(chr(10), " ")
|
|
102
|
+
text = _CONTROL.sub(lambda m: f"\\x{ord(m.group(0)):02x}", text)
|
|
103
|
+
return truncate(text, limit)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def truncate(text: str, limit: int) -> str:
|
|
107
|
+
if limit <= 0 or len(text) <= limit:
|
|
108
|
+
return text
|
|
109
|
+
return text[:limit] + f"... [truncated {len(text) - limit} chars]"
|
snareline/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
snareline/alerts.py
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"""Alerts and the sinks that deliver them."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ipaddress
|
|
6
|
+
import json
|
|
7
|
+
import queue
|
|
8
|
+
import sys
|
|
9
|
+
import threading
|
|
10
|
+
import urllib.request
|
|
11
|
+
from dataclasses import asdict, dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any, Protocol
|
|
14
|
+
from urllib.parse import urlsplit
|
|
15
|
+
|
|
16
|
+
from ._util import new_id, safe_term, utc_now
|
|
17
|
+
from .config import SEVERITIES
|
|
18
|
+
from .errors import ConfigError
|
|
19
|
+
|
|
20
|
+
SEVERITY_RANK = {s: i for i, s in enumerate(SEVERITIES)}
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class Alert:
|
|
25
|
+
rule: str
|
|
26
|
+
severity: str
|
|
27
|
+
title: str
|
|
28
|
+
detail: str
|
|
29
|
+
session: str
|
|
30
|
+
agent: str
|
|
31
|
+
event_seq: int
|
|
32
|
+
decoy_id: str | None = None
|
|
33
|
+
decoy_kind: str | None = None
|
|
34
|
+
decoy_label: str | None = None
|
|
35
|
+
decoy_hint: str | None = None
|
|
36
|
+
encoding: str | None = None
|
|
37
|
+
blocked: bool = False
|
|
38
|
+
suspected_triggers: list[dict[str, Any]] = field(default_factory=list)
|
|
39
|
+
decoys: list[dict[str, Any]] = field(default_factory=list)
|
|
40
|
+
id: str = field(default_factory=lambda: new_id("alr"))
|
|
41
|
+
ts: str = field(default_factory=utc_now)
|
|
42
|
+
|
|
43
|
+
def to_dict(self) -> dict[str, Any]:
|
|
44
|
+
return asdict(self)
|
|
45
|
+
|
|
46
|
+
def summary(self) -> str:
|
|
47
|
+
action = "BLOCKED" if self.blocked else "detected"
|
|
48
|
+
return f"[{self.severity.upper()}] {self.title} ({action}; agent={self.agent}, session={self.session}, event #{self.event_seq})"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class Sink(Protocol):
|
|
52
|
+
def send(self, alert: Alert) -> None: ...
|
|
53
|
+
def close(self) -> None: ...
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
class ConsoleSink:
|
|
57
|
+
_COLORS = {"low": "36", "medium": "33", "high": "31", "critical": "1;37;41"}
|
|
58
|
+
|
|
59
|
+
def __init__(self, stream=None) -> None:
|
|
60
|
+
self.stream = stream or sys.stderr
|
|
61
|
+
|
|
62
|
+
def send(self, alert: Alert) -> None:
|
|
63
|
+
line = "snareline: " + safe_term(alert.summary())
|
|
64
|
+
if getattr(self.stream, "isatty", lambda: False)():
|
|
65
|
+
line = f"\x1b[{self._COLORS.get(alert.severity, '0')}m{line}\x1b[0m"
|
|
66
|
+
print(line, file=self.stream)
|
|
67
|
+
if alert.suspected_triggers:
|
|
68
|
+
top = alert.suspected_triggers[0]
|
|
69
|
+
print(
|
|
70
|
+
f"snareline: suspected trigger: event #{top['seq']} from {safe_term(top['source'], 120)}",
|
|
71
|
+
file=self.stream,
|
|
72
|
+
)
|
|
73
|
+
self.stream.flush()
|
|
74
|
+
|
|
75
|
+
def close(self) -> None:
|
|
76
|
+
pass
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class FileSink:
|
|
80
|
+
"""Append-only JSONL alert log (``alerts.jsonl``)."""
|
|
81
|
+
|
|
82
|
+
def __init__(self, path: Path) -> None:
|
|
83
|
+
self.path = path
|
|
84
|
+
self._lock = threading.Lock()
|
|
85
|
+
|
|
86
|
+
def send(self, alert: Alert) -> None:
|
|
87
|
+
line = json.dumps(alert.to_dict(), ensure_ascii=False) + "\n"
|
|
88
|
+
with self._lock, open(self.path, "a", encoding="utf-8") as fh:
|
|
89
|
+
fh.write(line)
|
|
90
|
+
|
|
91
|
+
def close(self) -> None:
|
|
92
|
+
pass
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
96
|
+
def redirect_request(self, *args, **kwargs): # noqa: D401 - urllib hook
|
|
97
|
+
return None
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def validate_webhook_url(url: str, *, allow_http_localhost: bool = False) -> str:
|
|
101
|
+
parts = urlsplit(url)
|
|
102
|
+
if parts.username or parts.password:
|
|
103
|
+
raise ConfigError("webhook URL must not embed credentials")
|
|
104
|
+
if parts.scheme == "https" and parts.hostname:
|
|
105
|
+
return url
|
|
106
|
+
if parts.scheme == "http" and allow_http_localhost and parts.hostname:
|
|
107
|
+
host = parts.hostname
|
|
108
|
+
try:
|
|
109
|
+
loopback = ipaddress.ip_address(host).is_loopback
|
|
110
|
+
except ValueError:
|
|
111
|
+
loopback = host == "localhost"
|
|
112
|
+
if loopback:
|
|
113
|
+
return url
|
|
114
|
+
raise ConfigError("webhook URL must use https:// (http is only allowed for localhost when enabled)")
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
class WebhookSink:
|
|
118
|
+
"""POST alerts as JSON to a webhook, off the agent's critical path.
|
|
119
|
+
|
|
120
|
+
Slack incoming-webhook URLs get a Slack-formatted message; everything
|
|
121
|
+
else receives the alert object. Redirects are refused and requests time
|
|
122
|
+
out after a few seconds so a slow receiver cannot stall the agent.
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
def __init__(self, url: str, *, allow_http_localhost: bool = False, timeout: float = 5.0) -> None:
|
|
126
|
+
self.url = validate_webhook_url(url, allow_http_localhost=allow_http_localhost)
|
|
127
|
+
self.timeout = timeout
|
|
128
|
+
self._slack = (urlsplit(url).hostname or "").endswith("hooks.slack.com")
|
|
129
|
+
self._opener = urllib.request.build_opener(_NoRedirect)
|
|
130
|
+
self._q: queue.Queue[Alert | None] = queue.Queue(maxsize=1000)
|
|
131
|
+
self._thread = threading.Thread(target=self._run, name="snareline-webhook", daemon=True)
|
|
132
|
+
self.failures = 0
|
|
133
|
+
self._thread.start()
|
|
134
|
+
|
|
135
|
+
def send(self, alert: Alert) -> None:
|
|
136
|
+
try:
|
|
137
|
+
self._q.put_nowait(alert)
|
|
138
|
+
except queue.Full: # an alert storm must not exhaust memory
|
|
139
|
+
self.failures += 1
|
|
140
|
+
|
|
141
|
+
def _payload(self, alert: Alert) -> bytes:
|
|
142
|
+
if self._slack:
|
|
143
|
+
text = f":rotating_light: *Snareline* {alert.summary()}\n{alert.detail}"
|
|
144
|
+
return json.dumps({"text": text}).encode("utf-8")
|
|
145
|
+
return json.dumps({"source": "snareline", "alert": alert.to_dict()}).encode("utf-8")
|
|
146
|
+
|
|
147
|
+
def _run(self) -> None:
|
|
148
|
+
while True:
|
|
149
|
+
alert = self._q.get()
|
|
150
|
+
if alert is None:
|
|
151
|
+
return
|
|
152
|
+
# Scheme is restricted to https (or loopback http) by validate_webhook_url.
|
|
153
|
+
req = urllib.request.Request( # noqa: S310
|
|
154
|
+
self.url,
|
|
155
|
+
data=self._payload(alert),
|
|
156
|
+
headers={"Content-Type": "application/json", "User-Agent": "snareline-alerts"},
|
|
157
|
+
method="POST",
|
|
158
|
+
)
|
|
159
|
+
try:
|
|
160
|
+
with self._opener.open(req, timeout=self.timeout) as resp:
|
|
161
|
+
resp.read(1024)
|
|
162
|
+
except Exception as exc: # noqa: BLE001 - never crash the agent over a webhook
|
|
163
|
+
self.failures += 1
|
|
164
|
+
print(f"snareline: webhook delivery failed: {type(exc).__name__}", file=sys.stderr)
|
|
165
|
+
|
|
166
|
+
def close(self, timeout: float = 10.0) -> None:
|
|
167
|
+
self._q.put(None)
|
|
168
|
+
self._thread.join(timeout)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
class MemorySink:
|
|
172
|
+
"""Collects alerts in memory. Handy in tests and notebooks."""
|
|
173
|
+
|
|
174
|
+
def __init__(self) -> None:
|
|
175
|
+
self.alerts: list[Alert] = []
|
|
176
|
+
|
|
177
|
+
def send(self, alert: Alert) -> None:
|
|
178
|
+
self.alerts.append(alert)
|
|
179
|
+
|
|
180
|
+
def close(self) -> None:
|
|
181
|
+
pass
|
snareline/attribution.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
"""Suspected-trigger attribution.
|
|
2
|
+
|
|
3
|
+
When a decoy fires, the useful question is *what made the agent do that?*
|
|
4
|
+
Snareline keeps an index of every piece of untrusted content that entered the
|
|
5
|
+
session (web pages, tool outputs, retrieved documents, emails) and ranks it
|
|
6
|
+
by injection signals and by links to the alert, such as the exfiltration
|
|
7
|
+
destination appearing in that content.
|
|
8
|
+
|
|
9
|
+
This is a ranking heuristic, not proof. Reports label results "suspected".
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from urllib.parse import urlsplit
|
|
17
|
+
|
|
18
|
+
_SIGNALS: list[tuple[str, re.Pattern[str], int]] = [
|
|
19
|
+
(
|
|
20
|
+
"override instruction",
|
|
21
|
+
re.compile(
|
|
22
|
+
r"(?i)\b(ignore|disregard|forget|override)\b.{0,40}\b(previous|prior|above|earlier|all|system)\b.{0,20}\b(instructions?|rules?|prompts?|guidelines?)"
|
|
23
|
+
),
|
|
24
|
+
5,
|
|
25
|
+
),
|
|
26
|
+
("role hijack", re.compile(r"(?i)\b(you are now|new instructions|system prompt|developer mode|act as)\b"), 3),
|
|
27
|
+
(
|
|
28
|
+
"addresses the agent",
|
|
29
|
+
re.compile(
|
|
30
|
+
r"(?i)\b(ai|assistant|agent|llm|language model)\b.{0,30}\b(must|should|need to|are required|please)\b"
|
|
31
|
+
),
|
|
32
|
+
2,
|
|
33
|
+
),
|
|
34
|
+
(
|
|
35
|
+
"secrecy request",
|
|
36
|
+
re.compile(
|
|
37
|
+
r"(?i)\b(do not|don't|never)\b.{0,20}\b(tell|mention|inform|reveal|show)\b.{0,20}\b(user|human|anyone)\b"
|
|
38
|
+
),
|
|
39
|
+
3,
|
|
40
|
+
),
|
|
41
|
+
(
|
|
42
|
+
"asks for secrets",
|
|
43
|
+
re.compile(
|
|
44
|
+
r"(?i)(api[_ -]?keys?|credentials?|passwords?|secrets?|tokens?|\.env\b|id_rsa|id_ed25519|private key)"
|
|
45
|
+
),
|
|
46
|
+
2,
|
|
47
|
+
),
|
|
48
|
+
(
|
|
49
|
+
"asks to send data out",
|
|
50
|
+
re.compile(
|
|
51
|
+
r"(?i)\b(send|post|upload|forward|exfiltrate|transmit|email|curl|webhook)\b.{0,60}(https?://|\b(to|at)\b)"
|
|
52
|
+
),
|
|
53
|
+
3,
|
|
54
|
+
),
|
|
55
|
+
("encoding request", re.compile(r"(?i)\b(base64|hex[- ]?encode|rot13|url[- ]?encode|reverse the)\b"), 2),
|
|
56
|
+
(
|
|
57
|
+
"hidden markup",
|
|
58
|
+
re.compile(r"(?i)<!--|display\s*:\s*none|font-size\s*:\s*0|color\s*:\s*(#fff\b|#ffffff|white)"),
|
|
59
|
+
2,
|
|
60
|
+
),
|
|
61
|
+
("invisible characters", re.compile("[\u200b\u200c\u200d\u2060\ufeff\U000e0000-\U000e007f]"), 3),
|
|
62
|
+
]
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@dataclass
|
|
66
|
+
class _Source:
|
|
67
|
+
seq: int
|
|
68
|
+
source: str
|
|
69
|
+
text: str
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class Attributor:
|
|
73
|
+
def __init__(self, keep: int = 200, max_chars: int = 200_000) -> None:
|
|
74
|
+
self._items: list[_Source] = []
|
|
75
|
+
self.keep = keep
|
|
76
|
+
self.max_chars = max_chars
|
|
77
|
+
|
|
78
|
+
def add(self, seq: int, source: str, text: str) -> None:
|
|
79
|
+
self._items.append(_Source(seq, source, text[: self.max_chars]))
|
|
80
|
+
if len(self._items) > self.keep:
|
|
81
|
+
self._items = self._items[-self.keep :]
|
|
82
|
+
|
|
83
|
+
def rank(self, *, before_seq: int, alert_text: str = "", limit: int = 3) -> list[dict]:
|
|
84
|
+
candidates = [s for s in self._items if s.seq < before_seq]
|
|
85
|
+
if not candidates:
|
|
86
|
+
return []
|
|
87
|
+
hosts = {h for h in (_host(u) for u in re.findall(r"https?://[^\s\"'<>)]+", alert_text)) if h}
|
|
88
|
+
n = len(candidates)
|
|
89
|
+
scored = []
|
|
90
|
+
for idx, src in enumerate(candidates):
|
|
91
|
+
reasons: list[str] = []
|
|
92
|
+
score = 0
|
|
93
|
+
for name, pattern, weight in _SIGNALS:
|
|
94
|
+
if pattern.search(src.text):
|
|
95
|
+
score += weight
|
|
96
|
+
reasons.append(name)
|
|
97
|
+
low = src.text.lower()
|
|
98
|
+
for h in hosts:
|
|
99
|
+
if h in low:
|
|
100
|
+
score += 8
|
|
101
|
+
reasons.append(f"mentions destination {h}")
|
|
102
|
+
if score == 0:
|
|
103
|
+
continue
|
|
104
|
+
score += round(2 * (idx + 1) / n, 2) # mild recency bonus
|
|
105
|
+
scored.append(
|
|
106
|
+
{
|
|
107
|
+
"seq": src.seq,
|
|
108
|
+
"source": src.source,
|
|
109
|
+
"score": round(score, 2),
|
|
110
|
+
"reasons": reasons,
|
|
111
|
+
"snippet": _snippet(src.text),
|
|
112
|
+
}
|
|
113
|
+
)
|
|
114
|
+
scored.sort(key=lambda s: s["score"], reverse=True)
|
|
115
|
+
return scored[:limit]
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _host(url: str) -> str | None:
|
|
119
|
+
try:
|
|
120
|
+
host = urlsplit(url).hostname
|
|
121
|
+
except ValueError:
|
|
122
|
+
return None
|
|
123
|
+
return host.lower() if host else None
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _snippet(text: str, limit: int = 400) -> str:
|
|
127
|
+
for _, pattern, _ in _SIGNALS:
|
|
128
|
+
m = pattern.search(text)
|
|
129
|
+
if m:
|
|
130
|
+
start = max(0, m.start() - 120)
|
|
131
|
+
return ("…" if start else "") + text[start : start + limit] + ("…" if start + limit < len(text) else "")
|
|
132
|
+
return text[:limit] + ("…" if len(text) > limit else "")
|