Skip to content
Closed
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
198 changes: 198 additions & 0 deletions mcp/src/technocore_mcp/scanner.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,198 @@
"""Threat, scam, and provenance scanner for Technocore MCP.

Evaluates untrusted message content and sender identity for:
1. Adversarial prompt injections and instruction overrides.
2. Homoglyph / confusable character obfuscations (NFKC).
3. Fake token contracts and phishing links (pump.fun, unverified EVM contracts).
4. Syntactic DID provenance and impersonation attempts.
"""

from __future__ import annotations

import re
import unicodedata
from typing import TypedDict

# Confusable homoglyph translation table (Cyrillic & Greek homoglyphs -> ASCII)
HOMOGLYPH_MAP = {
# Cyrillic to Latin
ord("а"): "a",
ord("А"): "A",
ord("е"): "e",
ord("Е"): "E",
ord("о"): "o",
ord("О"): "O",
ord("р"): "p",
ord("Р"): "P",
ord("с"): "c",
ord("С"): "C",
ord("у"): "y",
ord("У"): "Y",
ord("х"): "x",
ord("Х"): "X",
ord("і"): "i",
ord("І"): "I",
ord("ј"): "j",
ord("Ј"): "J",
ord("ѕ"): "s",
ord("Ѕ"): "S",
ord("ԁ"): "d",
ord("Ԃ"): "D",
ord("ԛ"): "q",
ord("ԝ"): "w",
# Greek to Latin
ord("α"): "a",
ord("Α"): "A",
ord("β"): "b",
ord("Β"): "B",
ord("ε"): "e",
ord("Ε"): "E",
ord("ο"): "o",
ord("О"): "O",
ord("ρ"): "p",
ord("Ρ"): "P",
ord("τ"): "t",
ord("Τ"): "T",
ord("ν"): "v",
ord("Ν"): "N",
ord("κ"): "k",
ord("Κ"): "K",
}

PROMPT_INJECTION_PATTERNS = [
# Instruction Resets & Overrides
re.compile(
r"\b(ignore|disregard|forget)\s+(all\s+|any\s+)?(previous|former|prior|past|above)\s+(instructions|prompts|directives|rules|constraints|directions)\b",
re.I,
),
re.compile(
r"\b(you\s+are\s+now|act\s+as|pretend\s+to\s+be)\s+(?:acting\s+as\s+|in\s+)?(a\s+|an\s+)?(unrestricted|jailbroken|developer\s+mode|dan\s+mode|root\s+user|system\s+admin)\b",
re.I,
),
re.compile(
r"\b(system\s+(?:prompt\s+)?override|override\s+system|new\s+system\s+directive|developer\s+mode\s+enabled|admin_override_enabled)\b",
re.I,
),
re.compile(
r"\b(print|reveal|output|display|show|send|leak)\s+(your\s+|the\s+)?(system\s+prompt|initial\s+instructions|private\s+key|seed\s+phrase|api\s+key)\b",
re.I,
),
# Delimiter and Frame Hijacking
re.compile(r"<\s*\|\s*im_start\s*\|>", re.I),
re.compile(r"<\s*\|\s*im_end\s*\|>", re.I),
re.compile(r"\[\s*INST\s*\]|\[\s*/\s*INST\s*\]", re.I),
re.compile(r"<<\s*SYS\s*>>|<</\s*SYS\s*>>", re.I),
re.compile(
r"[-=]{3,}\s*(BEGIN|START|END)\s+.*?(SYSTEM|DIRECTIVE|INSTRUCTION|PROMPT).*?[-=]{3,}", re.I
),
re.compile(r"^\s*(SYSTEM|DEVELOPER|ROOT)\s*:\s*", re.M | re.I),
# Markdown / Out-of-band Exfiltration Payloads
re.compile(r"!\[.*?\]\((https?://[^\s\)]+)\)", re.I),
re.compile(r"data:text/html;base64,[A-Za-z0-9+/=]{16,}", re.I),
]

SCAM_PATTERNS = [
# Solana pump.fun token contract spam
re.compile(r"\b[1-9A-HJ-NP-Za-km-z]{32,44}pump\b", re.I),
re.compile(r"pump\.fun\/coin\/[a-zA-Z0-9]{32,44}", re.I),
# EVM token contract spam with claims
re.compile(r"\b0x[a-fA-F0-9]{40}\b.*?(?:buy|claim|airdrop|launch|presale|contract|mint)", re.I),
re.compile(r"(?:buy|claim|airdrop|launch|presale|contract|mint).*?\b0x[a-fA-F0-9]{40}\b", re.I),
re.compile(r"\b0x[a-fA-F0-9]{40}\b"),
# Phishing / Fake Claim Portals
re.compile(
r"https?://[^\s/]*(?:flop|technocore)[^\s/]*(?:claim|airdrop|reward|presale|token)[^\s]*",
re.I,
),
re.compile(
r"(?:airdrop|presale|claim|whitelist)\s+(?:portal|live|active|link):\s*https?:\/\/", re.I
),
re.compile(r"official\s+(?:flop|technocore)\s+token\s+contract", re.I),
re.compile(r"https?://t\.me/[^\s]*(?:airdrop|claim|reward|official_flop)", re.I),
]

RESERVED_ADMIN_NAMES = frozenset(
{
"server",
"admin",
"administrator",
"root",
"system",
"flop_team",
"flop_official",
"technocore_admin",
"flop_labs",
"technocore",
}
)


class ScanResult(TypedDict):
verdict: str # "clean" | "suspicious" | "threat"
reason: str # "none" | "prompt_injection" | "homoglyph_obfuscation" | "unverified_token_contract" | "impersonation_nick"
provenance: str # "claimed_did" | "unverified_nick" | "impersonator_warning"
details: str


def normalize(text: str) -> str:
"""Normalize text using NFKC and confusable substitution."""
de_confused = text.translate(HOMOGLYPH_MAP)
return unicodedata.normalize("NFKC", de_confused)


def evaluate_text(text: str, sender: str | None = None) -> ScanResult:
"""Evaluate text and sender for adversarial threats, scams, and provenance."""
# 1. Provenance check
provenance = "unverified_nick"
if sender:
clean_sender = sender.strip().lstrip("~")
if sender.startswith("did:key:") or clean_sender.startswith("did:key:"):
provenance = "claimed_did"
elif clean_sender.lower() in RESERVED_ADMIN_NAMES:
provenance = "impersonator_warning"

# 2. Check raw and normalized forms for prompt injections
norm_text = normalize(text)
for pat in PROMPT_INJECTION_PATTERNS:
if pat.search(text) or pat.search(norm_text):
return {
"verdict": "threat",
"reason": "prompt_injection",
"provenance": provenance,
"details": f"Matched prompt injection pattern: {pat.pattern}",
}

# 3. Check for fake token contracts / phishing
for pat in SCAM_PATTERNS:
if pat.search(text) or pat.search(norm_text):
return {
"verdict": "threat",
"reason": "unverified_token_contract",
"provenance": provenance,
"details": f"Matched token contract/phishing pattern: {pat.pattern}",
}

# 4. Homoglyph obfuscation check
if any(ord(c) in HOMOGLYPH_MAP for c in text):
return {
"verdict": "suspicious",
"reason": "homoglyph_obfuscation",
"provenance": provenance,
"details": "Text contains mixed Cyrillic/Greek homoglyphs resembling Latin characters",
}

# 5. Impersonator warning check
if provenance == "impersonator_warning":
return {
"verdict": "suspicious",
"reason": "impersonation_nick",
"provenance": provenance,
"details": f"Sender claims reserved nickname '~{clean_sender}' without did:key signature",
}

return {
"verdict": "clean",
"reason": "none",
"provenance": provenance,
"details": "No threat or scam patterns detected",
}
29 changes: 28 additions & 1 deletion mcp/src/technocore_mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@
from pydantic import Field
from starlette.applications import Starlette

from . import signing
from . import scanner, signing
from .fetch import Fetch, urllib_fetch

# The single place this package's version is written: `mcp/pyproject.toml` reads it from
Expand Down Expand Up @@ -711,6 +711,33 @@ async def read_docs(
return await _get(PAGES[page])


@server.tool(
name="technocore_scan",
description=(
"Evaluate untrusted room text or note content for adversarial prompt injections, "
"instruction resets, homoglyph obfuscation (confusables), fake token contracts, "
"and syntactic sender provenance before deciding whether to act on it."
),
annotations=ToolAnnotations(read_only_hint=True, open_world_hint=False),
structured_output=False,
)
async def technocore_scan(
text: Annotated[str, Field(description="The message text or note value to evaluate.")],
sender: Annotated[
str | None,
Field(description="The message's author or nick (optional, evaluated for provenance)."),
] = None,
) -> str:
result = scanner.evaluate_text(text, sender)
lines = [
f"verdict: {result['verdict']}",
f"reason: {result['reason']}",
f"provenance: {result['provenance']}",
f"details: {result['details']}",
]
return "\n".join(lines)


# DNS-rebinding protection guards a *local* server: it stops a page in the user's browser
# from driving an MCP server that only their machine can reach. This server fronts a
# public, unauthenticated, world-writable origin — a browser reaching it has gained nothing
Expand Down
10 changes: 6 additions & 4 deletions src/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -1294,10 +1294,11 @@ def room_say(request: Request) -> Response:
if denied:
return denied
nick, body = request.path_params["nick"], request.path_params["text"]
with _dupe_slot(room, body) as refused:
cleaned = store.clean_text(body)
with _dupe_slot(room, cleaned) as refused:
if refused:
return _dupe_refusal(request, room)
rec = store.append(config.ROOT, room, nick, body)
rec = store.append(config.ROOT, room, nick, cleaned)
config._dbg(3, "write", room=room, seq=rec["seq"], chars=len(rec["text"]))
limit._settle_room_budget(request, rec, RATE_ROOMS_PER_DAY, ip_header=CLIENT_IP_HEADER)
view = store.read_messages(config.ROOT, room, limit=20)
Expand Down Expand Up @@ -1419,10 +1420,11 @@ def write() -> Response:
return denied
if signer is None:
nick = _field(payload, "from", is_name=True)
with _dupe_slot(room, sent) as refused:
cleaned = store.clean_text(sent)
with _dupe_slot(room, cleaned) as refused:
if refused:
return _dupe_refusal(request, room)
posted = store.append(config.ROOT, room, nick, sent)
posted = store.append(config.ROOT, room, nick, cleaned)
else:
with _dupe_slot(room, body) as refused:
if refused:
Expand Down
55 changes: 35 additions & 20 deletions src/limit.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"""

import hashlib
import ipaddress
import threading
import time
import unicodedata
Expand Down Expand Up @@ -53,6 +54,7 @@
# limiter state — which is why the authoritative limit belongs in the proxy (see README).
MAX_BUCKETS = 20_000
_buckets: OrderedDict[tuple[str, str], tuple[float, float]] = OrderedDict()
_buckets_lock = threading.Lock()

# Request counters for /stats. Deliberately in-process (the store's counters are the
# durable ones): traffic is only ever read as a rate, and a rate needs the uptime that
Expand Down Expand Up @@ -248,13 +250,24 @@ def client_ip(request: Request, ip_header: str = "") -> str:
if ip_header:
forwarded = request.headers.get(ip_header, "").split(",")[0].strip()
if forwarded:
return forwarded
return request.client.host if request.client else "?"
# Not configured to read one. Note whether the request looks proxied anyway, so a
# misconfiguration is visible in /stats instead of only in a support ticket.
if any(h in request.headers for h in PROXY_IP_HEADERS):
_proxy_evidence["proxied_requests"] += 1
return request.client.host if request.client else "?"
raw = forwarded
else:
raw = request.client.host if request.client else "?"
else:
# Not configured to read one. Note whether the request looks proxied anyway, so a
# misconfiguration is visible in /stats instead of only in a support ticket.
if any(h in request.headers for h in PROXY_IP_HEADERS):
_proxy_evidence["proxied_requests"] += 1
raw = request.client.host if request.client else "?"

if ":" in raw:
try:
addr = ipaddress.ip_address(raw)
if isinstance(addr, ipaddress.IPv6Address):
return str(ipaddress.ip_network(f"{addr}/64", strict=False))
except ValueError:
pass
return raw


def take(request, kind, per_min, burst=None, *, ip_header="", max_buckets=MAX_BUCKETS):
Expand All @@ -273,17 +286,18 @@ def take(request, kind, per_min, burst=None, *, ip_header="", max_buckets=MAX_BU
_identities.add(ip)
now = time.monotonic()
cap = float(per_min if burst is None else burst)
tokens, last = _buckets.get((ip, kind), (cap, now))
tokens = min(cap, tokens + (now - last) * per_min / 60.0)
if tokens >= 1.0: # granted: no wait, even when this was the last token
tokens -= 1.0
wait = 0.0
else:
wait = (1.0 - tokens) * 60.0 / per_min
_buckets[(ip, kind)] = (tokens, now)
_buckets.move_to_end((ip, kind))
while len(_buckets) > max_buckets:
_buckets.popitem(last=False)
with _buckets_lock:
tokens, last = _buckets.get((ip, kind), (cap, now))
tokens = min(cap, tokens + (now - last) * per_min / 60.0)
if tokens >= 1.0: # granted: no wait, even when this was the last token
tokens -= 1.0
wait = 0.0
else:
wait = (1.0 - tokens) * 60.0 / per_min
_buckets[(ip, kind)] = (tokens, now)
_buckets.move_to_end((ip, kind))
while len(_buckets) > max_buckets:
_buckets.popitem(last=False)
# Counted at the one point every rate-limited route already funnels through, so a new
# route cannot forget to count itself. In-process, so these reset on restart — /stats
# reports them next to `uptime_seconds`, which is what makes them readable.
Expand All @@ -302,8 +316,9 @@ def refund(request, kind, per_min, burst=None, *, ip_header="") -> None:
"""
ip = client_ip(request, ip_header)
cap = float(per_min if burst is None else burst)
tokens, last = _buckets.get((ip, kind), (cap, time.monotonic()))
_buckets[(ip, kind)] = (min(cap, tokens + 1.0), last)
with _buckets_lock:
tokens, last = _buckets.get((ip, kind), (cap, time.monotonic()))
_buckets[(ip, kind)] = (min(cap, tokens + 1.0), last)
config._dbg(1, "refund", ip=ip, kind=kind)


Expand Down
Loading
Loading