feat(gateway): 'decline' unauthorized-DM behavior — one-time polite decline instead of pairing code

Port from qwibitai/nanoclaw#3260: adds a third unauthorized_dm_behavior
option, 'decline'. Instead of replying with a pairing code (pair) or
staying silent (ignore), the gateway sends one short, polite decline to
the unknown sender, then stays silent toward that sender for 24 hours.

- gateway/config.py: accept 'decline' in the normalizer; new
  unauthorized_dm_decline_message for custom decline text (round-trips
  through to_dict/from_dict).
- gateway/pairing.py: persisted decline stamps (_declined.json) on
  PairingStore with has_recent_decline/record_decline; stamps are
  pruned on write and recorded BEFORE delivery so a send failure can't
  become a decline storm (nanoclaw's stamp-first pattern).
- gateway/run.py: decline branch in the unauthorized-sender path;
  groups still always silently ignore.
- docs: security.md + configuration.md updated.

Adapted from TypeScript (NanoClaw's pending_sender_approvals 'decline:'
stamp rows) to Hermes' existing PairingStore JSON persistence; the
owner-FYI half of nanoclaw's flow is intentionally not ported — Hermes
logs the unauthorized attempt, and pairing remains the owner-visible
grant path.

Rebase onto the decomposed gateway (salvage, #88028):
- The unauthorized-sender path moved from gateway/run.py to
  gateway/run_inbound.py::_hm_admit_event; the decline branch is a sibling
  helper _hm_send_unauthorized_decline next to _hm_offer_pairing_code.
- gateway/config.py now validates the enum via _normalize_choice; the
  accepted set is the module constant UNAUTHORIZED_DM_BEHAVIORS (used by
  both from_dict and get_unauthorized_dm_behavior so a per-platform
  `extra.unauthorized_dm_behavior: decline` is honoured too). The default
  decline text lives in config as DEFAULT_UNAUTHORIZED_DM_DECLINE_MESSAGE.
- Tests trimmed from 5 to 2 invariant tests (send-once-then-silent through
  the real inbound path; config round-trip + real PairingStore stamp
  lifecycle with a patched clock instead of rewriting the JSON file).
This commit is contained in:
Teknium
2026-08-16 17:12:48 -07:00
parent 134ef6454d
commit a6e934e0fd
7 changed files with 139 additions and 12 deletions
@@ -1,3 +1,4 @@
import time
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
@@ -413,3 +414,62 @@ def test_qqbot_with_allowlist_ignores_unauthorized_dm(monkeypatch):
behavior = runner._get_unauthorized_dm_behavior(Platform.QQBOT)
assert behavior == "ignore"
# ---------------------------------------------------------------------------
# "decline" behavior: one-time polite decline instead of a pairing code
# (ported from qwibitai/nanoclaw#3260, #88028)
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_unauthorized_dm_decline_sends_once_then_stays_silent(monkeypatch):
"""First DM: stamp recorded BEFORE the send, custom text delivered, no pairing code. A sender
with a recent stamp gets nothing."""
_clear_auth_env(monkeypatch)
config = GatewayConfig(
platforms={Platform.WHATSAPP: PlatformConfig(enabled=True, extra={"unauthorized_dm_behavior": "decline"})},
)
config.unauthorized_dm_decline_message = "Sorry, this assistant is private."
runner, adapter = _make_runner(Platform.WHATSAPP, config)
jid = "15551234567@s.whatsapp.net"
runner.pairing_store.has_recent_decline.return_value = False
assert await runner._handle_message(_make_event(Platform.WHATSAPP, jid, jid)) is None
runner.pairing_store.generate_code.assert_not_called()
runner.pairing_store.record_decline.assert_called_once_with("whatsapp", jid)
adapter.send.assert_awaited_once_with(jid, "Sorry, this assistant is private.")
runner.pairing_store.has_recent_decline.return_value = True
adapter.send.reset_mock()
runner.pairing_store.record_decline.reset_mock()
assert await runner._handle_message(_make_event(Platform.WHATSAPP, jid, jid)) is None
runner.pairing_store.record_decline.assert_not_called()
adapter.send.assert_not_awaited()
def test_decline_config_and_stamp_roundtrip(monkeypatch, tmp_path):
"""Config accepts 'decline' (case-insensitive) and round-trips the custom text; a real
PairingStore persists the stamp, scopes it per sender, and expires it after the window."""
from unittest.mock import patch as _patch
import gateway.pairing as pairing_mod
config = GatewayConfig.from_dict(
{"unauthorized_dm_behavior": "DECLINE", "unauthorized_dm_decline_message": " custom text "}
)
assert config.unauthorized_dm_behavior == "decline"
assert config.get_unauthorized_dm_behavior(Platform.TELEGRAM) == "decline"
assert config.to_dict()["unauthorized_dm_behavior"] == "decline"
assert GatewayConfig.from_dict(config.to_dict()).unauthorized_dm_decline_message == "custom text"
with _patch("gateway.pairing.PAIRING_DIR", tmp_path):
store = pairing_mod.PairingStore()
assert store.has_recent_decline("telegram", "12345") is False
store.record_decline("telegram", "12345")
assert store.has_recent_decline("telegram", "12345") is True
assert store.has_recent_decline("telegram", "67890") is False
with _patch("gateway.pairing.time.time", return_value=time.time() + pairing_mod.DECLINE_DEDUPE_SECONDS + 1):
assert store.has_recent_decline("telegram", "12345") is False