mirror of
https://git.ugnet.gay/CrossTalk/azul.git
synced 2026-11-25 08:19:55 +00:00
0.6 final
This commit is contained in:
1 parent
7c0581eb97
commit
b89e1932bb
160 files changed
+20534
-4664
No files matched your search
+154
@@ -0,0 +1,154 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
import asyncio, time
|
||||
|
||||
from .models import User, MessageType
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .backend import Backend, BackendSession
|
||||
|
||||
EVIL_DELTA = 100
|
||||
EVIL_DELTA_ANONYMOUS = 30
|
||||
EVIL_DECAY = 50
|
||||
EVIL_DECAY_INTERVAL = 300
|
||||
EVIL_MAX = 999
|
||||
CONVERSATION_WINDOW = 3600
|
||||
|
||||
RATED_MESSAGE_TYPES = frozenset({ MessageType.Chat, MessageType.Nudge, MessageType.Ink })
|
||||
|
||||
RATE_WINDOW = 20
|
||||
RATE_MAX = 6000
|
||||
RATE_LIMIT = 500
|
||||
RATE_CLEAR = 1500
|
||||
RATE_WARNING_SCALE = 250
|
||||
|
||||
class _RateState:
|
||||
__slots__ = ('level', 'last', 'limited')
|
||||
|
||||
level: float
|
||||
last: float
|
||||
limited: bool
|
||||
|
||||
def __init__(self, now: float) -> None:
|
||||
self.level = float(RATE_MAX)
|
||||
self.last = now
|
||||
self.limited = False
|
||||
|
||||
class AbuseService:
|
||||
__slots__ = ('backend', '_conversations', '_warnings', '_warned', '_rates', '_decay_task')
|
||||
|
||||
backend: Backend
|
||||
_conversations: dict[str, dict[str, list[float]]]
|
||||
_warnings: dict[str, dict[str, list[float]]]
|
||||
_warned: dict[str, User]
|
||||
_rates: dict[str, _RateState]
|
||||
_decay_task: asyncio.Task[None] | None
|
||||
|
||||
def __init__(self, backend: Backend) -> None:
|
||||
self.backend = backend
|
||||
self._conversations = {}
|
||||
self._warnings = {}
|
||||
self._warned = {}
|
||||
self._rates = {}
|
||||
self._decay_task = None
|
||||
|
||||
def warning_level(self, user: User) -> int:
|
||||
return max(0, min(EVIL_MAX, int(user.evil_permanent or 0) + int(user.evil_temporary or 0)))
|
||||
|
||||
def track_message(self, sender: User, recipient: User, *, now: float | None = None) -> None:
|
||||
if sender is recipient: return
|
||||
now = (time.time() if now is None else now)
|
||||
times = self._conversations.setdefault(sender.uuid, {}).setdefault(recipient.uuid, [])
|
||||
times.append(now)
|
||||
del times[:-3]
|
||||
|
||||
def may_warn(self, warner: User, warnee: User, *, now: float | None = None) -> bool:
|
||||
if warner is warnee: return False
|
||||
now = (time.time() if now is None else now)
|
||||
received = [t for t in self._conversations.get(warnee.uuid, {}).get(warner.uuid, []) if now - t < CONVERSATION_WINDOW]
|
||||
warns = self._warnings.setdefault(warner.uuid, {}).setdefault(warnee.uuid, [])
|
||||
warns[:] = [t for t in warns if now - t < CONVERSATION_WINDOW]
|
||||
if len(received) <= len(warns):
|
||||
return False
|
||||
warns.append(now)
|
||||
return True
|
||||
|
||||
def warn(self, warner: User, warnee: User, *, anonymous: bool, delta: int | None = None) -> tuple[int, int] | None:
|
||||
level = self.warning_level(warnee)
|
||||
if level >= EVIL_MAX or not self.may_warn(warner, warnee):
|
||||
return None
|
||||
if delta is None:
|
||||
delta = (EVIL_DELTA_ANONYMOUS if anonymous else EVIL_DELTA)
|
||||
delta = min(delta, EVIL_MAX - level)
|
||||
warnee.evil_temporary = int(warnee.evil_temporary or 0) + delta
|
||||
new_level = self.warning_level(warnee)
|
||||
print(f"[Abuse] <Info> {warnee.username} ({warnee.email}) was warned ({'anonymously' if anonymous else 'by ' + warner.username}); their warning level is now {new_level}")
|
||||
self._start_decay(warnee)
|
||||
self.announce(warnee, (None if anonymous else warner))
|
||||
return delta, new_level
|
||||
|
||||
def announce(self, user: User, warner: User | None) -> None:
|
||||
level = self.warning_level(user)
|
||||
sessions: list[BackendSession] = list(self.backend.util_get_sessions_by_user(user))
|
||||
for bs in sessions:
|
||||
try:
|
||||
bs.evt.on_warning_level_changed(level, warner)
|
||||
except Exception:
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
for bs in sessions:
|
||||
if bs.closed: continue
|
||||
bs.me_update({ 'needs_notify': True, 'notify_status': True })
|
||||
break
|
||||
|
||||
def allow_message(self, user: User, *, now: float | None = None) -> bool:
|
||||
now = (time.time() if now is None else now)
|
||||
level = self.warning_level(user)
|
||||
if level >= EVIL_MAX:
|
||||
return False
|
||||
state = self._rates.get(user.uuid)
|
||||
if state is None:
|
||||
state = self._rates[user.uuid] = _RateState(now)
|
||||
return True
|
||||
delta_ms = max(0.0, (now - state.last) * 1000)
|
||||
state.last = now
|
||||
state.level = min(float(RATE_MAX), ((RATE_WINDOW - 1) * state.level + delta_ms) / RATE_WINDOW)
|
||||
scale = 1 + level / RATE_WARNING_SCALE
|
||||
limit = RATE_LIMIT * scale
|
||||
clear = min(RATE_CLEAR * scale, RATE_MAX * 0.95)
|
||||
if state.limited:
|
||||
if state.level < clear:
|
||||
return False
|
||||
state.limited = False
|
||||
if state.level < limit:
|
||||
state.limited = True
|
||||
print(f"[Abuse] <Info> {user.username} ({user.email}) is sending messages too fast and is being rate limited")
|
||||
return False
|
||||
return True
|
||||
|
||||
def is_rate_limited(self, user: User) -> bool:
|
||||
state = self._rates.get(user.uuid)
|
||||
return self.warning_level(user) >= EVIL_MAX or (state is not None and state.limited)
|
||||
|
||||
def _start_decay(self, user: User) -> None:
|
||||
self._warned[user.uuid] = user
|
||||
if self._decay_task is None or self._decay_task.done():
|
||||
try:
|
||||
self._decay_task = self.backend.loop.create_task(self._decay_warnings())
|
||||
except RuntimeError:
|
||||
self._decay_task = None
|
||||
|
||||
async def _decay_warnings(self) -> None:
|
||||
while self._warned:
|
||||
await asyncio.sleep(EVIL_DECAY_INTERVAL)
|
||||
self.decay_once()
|
||||
|
||||
def decay_once(self) -> None:
|
||||
for uuid, user in list(self._warned.items()):
|
||||
temporary = int(user.evil_temporary or 0)
|
||||
user.evil_temporary = max(0, temporary - EVIL_DECAY)
|
||||
if user.evil_temporary == 0:
|
||||
del self._warned[uuid]
|
||||
if user.evil_temporary != temporary and self.backend.util_get_sessions_by_user(user):
|
||||
self.announce(user, None)
|
||||
+243
@@ -0,0 +1,243 @@
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
from urllib.parse import urlsplit
|
||||
from xml.sax.saxutils import escape, quoteattr
|
||||
import itertools, re, time
|
||||
|
||||
import settings
|
||||
|
||||
SITE_IDS = { 'stocks': 0, 'calendar': 1, 'bell': 2 }
|
||||
ALIGNMENTS = ('left', 'center', 'right')
|
||||
AGENTS = ('email', 'messenger', 'mobile')
|
||||
MAX_BODY = 1024
|
||||
MAX_TEXT = 1000
|
||||
MSNP_NOT = 5
|
||||
MSNP_TEXTX = 9
|
||||
|
||||
Run = Tuple[str, bool, bool]
|
||||
Line = List[Run]
|
||||
Paragraph = List[Line]
|
||||
|
||||
_next_id = itertools.count(int(time.time()) % 0xFFFFFFFF)
|
||||
|
||||
def new_alert_id() -> int:
|
||||
return next(_next_id) % 0x100000000
|
||||
|
||||
class AlertError(ValueError):
|
||||
field: str
|
||||
|
||||
def __init__(self, field: str, message: str) -> None:
|
||||
super().__init__(message)
|
||||
self.field = field
|
||||
|
||||
def parse_rich(markup: str) -> List[Paragraph]:
|
||||
paragraphs: list[Paragraph] = []
|
||||
text = markup.replace('\r\n', '\n').replace('\r', '\n').strip()
|
||||
for block in re.split(r'\n[ \t]*\n\s*', text):
|
||||
if not block.strip():
|
||||
continue
|
||||
bold = italic = False
|
||||
lines: list[Line] = []
|
||||
for raw in block.split('\n'):
|
||||
runs: Line = []
|
||||
buf = ''
|
||||
i = 0
|
||||
while i < len(raw):
|
||||
ch = raw[i]
|
||||
if ch == '\\' and i + 1 < len(raw):
|
||||
buf += raw[i + 1]
|
||||
i += 2
|
||||
continue
|
||||
if ch == '*':
|
||||
if buf:
|
||||
runs.append((buf, bold, italic))
|
||||
buf = ''
|
||||
if raw.startswith('**', i):
|
||||
bold = not bold
|
||||
i += 2
|
||||
else:
|
||||
italic = not italic
|
||||
i += 1
|
||||
continue
|
||||
buf += ch
|
||||
i += 1
|
||||
if buf:
|
||||
runs.append((buf, bold, italic))
|
||||
lines.append(runs)
|
||||
paragraphs.append(lines)
|
||||
return paragraphs
|
||||
|
||||
def plain_text(paragraphs: List[Paragraph]) -> str:
|
||||
return '\n\n'.join('\n'.join(''.join(run[0] for run in line) for line in para) for para in paragraphs)
|
||||
|
||||
def textx_document(paragraphs: List[Paragraph], align: str = 'left') -> str:
|
||||
attrs = '' if align == 'left' else ' align="{}"'.format(align)
|
||||
out = []
|
||||
for para in paragraphs:
|
||||
lines = []
|
||||
for line in para:
|
||||
parts = []
|
||||
for text, bold, italic in line:
|
||||
part = escape(text)
|
||||
if italic:
|
||||
part = '<I>' + part + '</I>'
|
||||
if bold:
|
||||
part = '<B>' + part + '</B>'
|
||||
parts.append(part)
|
||||
lines.append(''.join(parts))
|
||||
out.append('<P{}>{}</P>'.format(attrs, '<BR/>'.join(lines)))
|
||||
return ''.join(out)
|
||||
|
||||
def irc_lines(paragraphs: List[Paragraph]) -> List[str]:
|
||||
out = []
|
||||
for para in paragraphs:
|
||||
for line in para:
|
||||
parts = []
|
||||
bold = italic = False
|
||||
for text, run_bold, run_italic in line:
|
||||
if run_bold != bold:
|
||||
parts.append('\x02')
|
||||
bold = run_bold
|
||||
if run_italic != italic:
|
||||
parts.append('\x1d')
|
||||
italic = run_italic
|
||||
parts.append(text)
|
||||
if bold or italic:
|
||||
parts.append('\x0f')
|
||||
if ''.join(parts).strip():
|
||||
out.append(''.join(parts))
|
||||
return out
|
||||
|
||||
def _origin(url: str) -> Optional[str]:
|
||||
parts = urlsplit(url)
|
||||
if parts.scheme not in ('http', 'https') or not parts.netloc:
|
||||
return None
|
||||
return '{}://{}'.format(parts.scheme, parts.netloc)
|
||||
|
||||
def check_url(url: str, field: str) -> str:
|
||||
url = url.strip()
|
||||
if url and _origin(url) is None:
|
||||
raise AlertError(field, 'Links have to be full http:// or https:// addresses.')
|
||||
if len(url) > 500:
|
||||
raise AlertError(field, 'That address is too long.')
|
||||
return url
|
||||
|
||||
@dataclass
|
||||
class Alert:
|
||||
text: str
|
||||
rich: Optional[str] = None
|
||||
align: str = 'left'
|
||||
url: str = ''
|
||||
subscr_url: str = ''
|
||||
icon: str = ''
|
||||
kind: str = 'bell'
|
||||
lang: int = 1033
|
||||
priority: int = 1
|
||||
message_id: int = 0
|
||||
via: Optional[str] = None
|
||||
email_text: Optional[str] = None
|
||||
id: int = field(default_factory = new_alert_id)
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
self.text = (self.text or '').strip()
|
||||
self.rich = (self.rich or '').strip() or None
|
||||
if self.rich and not self.text:
|
||||
self.text = plain_text(parse_rich(self.rich))
|
||||
|
||||
def check(self, *, emailed: bool = False) -> 'Alert':
|
||||
if not self.text:
|
||||
raise AlertError('text', 'Write the alert first.')
|
||||
if len(self.text) > MAX_TEXT:
|
||||
raise AlertError('text', 'Alerts can be at most {} characters.'.format(MAX_TEXT))
|
||||
if self.align not in ALIGNMENTS:
|
||||
raise AlertError('align', 'Alignment is left, center or right.')
|
||||
if self.kind not in SITE_IDS:
|
||||
raise AlertError('kind', 'The icon is bell, stocks or calendar (or a custom icon).')
|
||||
if self.via is not None and self.via not in AGENTS:
|
||||
raise AlertError('via', 'An alert comes from e-mail, messenger or mobile.')
|
||||
if not (0 < self.lang < 0x10000):
|
||||
raise AlertError('lang', 'The language is a Windows LCID, like 1033 for English (United States).')
|
||||
if not (0 <= self.priority <= 0xFFFFFFFF and 0 <= self.message_id <= 0xFFFFFFFF):
|
||||
raise AlertError('priority', 'Priority and message ID are 32-bit numbers.')
|
||||
self.url = check_url(self.url, 'url')
|
||||
self.subscr_url = check_url(self.subscr_url, 'subscr_url')
|
||||
self.icon = check_url(self.icon, 'icon')
|
||||
size = len(self._body(self.locations()[3], MSNP_TEXTX, emailed).replace('\n', '\r\n').encode('utf-8'))
|
||||
if size > MAX_BODY:
|
||||
raise AlertError('rich' if self.rich else 'text', 'That\'s too long for Messenger: an alert\'s body can be at most {} bytes, and this one is {}.'.format(MAX_BODY, size))
|
||||
return self
|
||||
|
||||
@property
|
||||
def paragraphs(self) -> List[Paragraph]:
|
||||
return parse_rich(self.rich) if self.rich else [[[(line, False, False)] for line in para.split('\n')] for para in re.split(r'\n\s*\n', self.text)]
|
||||
|
||||
@property
|
||||
def site_id(self) -> int:
|
||||
return SITE_IDS[self.kind]
|
||||
|
||||
@property
|
||||
def link(self) -> str:
|
||||
return self.url or settings.ALERT_SITE_URL
|
||||
|
||||
def plain(self) -> str:
|
||||
return plain_text(parse_rich(self.rich)) if self.rich else self.text
|
||||
|
||||
def plain_with_link(self) -> str:
|
||||
return self.plain() + ('\n' + self.url if self.url else '')
|
||||
|
||||
def locations(self) -> Tuple[str, str, str, str]:
|
||||
action = self.link
|
||||
subscr = self.subscr_url or action
|
||||
icon = self.icon
|
||||
urls = [u for u in (action, subscr, icon) if u]
|
||||
origins = { _origin(u) for u in urls }
|
||||
if len(origins) == 1 and None not in origins:
|
||||
origin = origins.pop()
|
||||
assert origin is not None
|
||||
rel = lambda u: u[len(origin) + 1:] if u else ''
|
||||
return (origin + '/', rel(action), rel(subscr), rel(icon))
|
||||
return ('', action, subscr, icon)
|
||||
|
||||
def _body(self, icon: str, dialect: int, emailed: bool) -> str:
|
||||
attrs = ' lang="{}"'.format(self.lang)
|
||||
if icon:
|
||||
attrs += ' icon={}'.format(quoteattr(icon))
|
||||
parts = ['<TEXT>{}</TEXT>'.format(escape(self.text))]
|
||||
if emailed and self.email_text:
|
||||
parts.append('<EMAILTEXT>{}</EMAILTEXT>'.format(escape(self.email_text)))
|
||||
if dialect >= MSNP_TEXTX and (self.rich or self.align != 'left'):
|
||||
parts.append('<TEXTX>{}</TEXTX>'.format(escape(textx_document(self.paragraphs, self.align))))
|
||||
return '<BODY{}>\n\t\t\t{}\n\t\t</BODY>'.format(attrs, '\n\t\t\t'.join(parts))
|
||||
|
||||
def notification(self, *, pid: str, name: str, dialect: int, email: Optional[str] = None) -> bytes:
|
||||
siteurl, action, subscr, icon = self.locations()
|
||||
to_attrs = 'pid={} name={}'.format(quoteattr(pid), quoteattr(name))
|
||||
if email:
|
||||
to_attrs += ' email={}'.format(quoteattr(email))
|
||||
if self.via:
|
||||
to = '<TO {}>\n\t\t<VIA agent={} />\n\t</TO>'.format(to_attrs, quoteattr(self.via))
|
||||
else:
|
||||
to = '<TO {} />'.format(to_attrs)
|
||||
doc = (
|
||||
'<NOTIFICATION ver="1" id="{id}" siteid="{siteid}" siteurl={siteurl}>\n'
|
||||
'\t{to}\n'
|
||||
'\t<MSG pri="{pri}" id="{mid}">\n'
|
||||
'\t\t<ACTION url={action} />\n'
|
||||
'\t\t<SUBSCR url={subscr} />\n'
|
||||
'\t\t{body}\n'
|
||||
'\t</MSG>\n'
|
||||
'</NOTIFICATION>'
|
||||
).format(
|
||||
id = self.id, siteid = self.site_id, siteurl = quoteattr(siteurl), to = to, pri = self.priority, mid = self.message_id,
|
||||
action = quoteattr(action), subscr = quoteattr(subscr), body = self._body(icon, dialect, bool(email)),
|
||||
)
|
||||
return doc.replace('\n', '\r\n').encode('utf-8')
|
||||
|
||||
def summary(self) -> Dict[str, Any]:
|
||||
return {
|
||||
'id': self.id, 'text': self.text, 'rich': self.rich, 'align': self.align, 'url': self.url, 'subscr_url': self.subscr_url,
|
||||
'icon': self.icon, 'kind': self.kind, 'lang': self.lang, 'priority': self.priority, 'via': self.via,
|
||||
}
|
||||
|
||||
def puid(high: int, low: int) -> str:
|
||||
return '0x{:08x}:0x{:08x}'.format(high, low)
|
||||
+427
-35
@@ -1,7 +1,8 @@
|
||||
from typing import Dict, List, Set, Any, Tuple, Optional, Iterable
|
||||
from typing import Dict, List, Set, Any, Tuple, Optional, Iterable, Callable
|
||||
from abc import ABCMeta, abstractmethod
|
||||
import asyncio, traceback, settings, smtplib, pprint
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
import asyncio, traceback, settings, smtplib, pprint, re
|
||||
from collections import defaultdict, deque
|
||||
from enum import IntFlag
|
||||
|
||||
from util.misc import gen_uuid, first_in_iterable, run_loop, Runner, server_temp_cleanup
|
||||
@@ -10,11 +11,13 @@ from .user import UserService
|
||||
from .auth import AuthService, LoginAuthService, GenTokenStr
|
||||
from .stats import Stats
|
||||
from .client import Client
|
||||
from .abuse import AbuseService, RATED_MESSAGE_TYPES
|
||||
from .models import (
|
||||
User, UserDetail, Group, ContactList, OIM, Contact, ContactDetail, Circle, CircleRole, CircleState,
|
||||
CircleMembership, Chatroom, UserStatus, TextWithData, MessageData, MessageType, Substatus, LoginOption, _is_blocking,
|
||||
)
|
||||
from . import error, event
|
||||
from .alerts import Alert
|
||||
|
||||
class Ack(IntFlag):
|
||||
Zero = 0
|
||||
@@ -26,7 +29,8 @@ class Backend:
|
||||
__slots__ = (
|
||||
'user_service', 'auth_service', 'login_auth_service', 'loop', 'notify_maintenance', 'maintenance_mode', 'maintenance_mins', '_stats', '_sc',
|
||||
'_chats_by_id', '_cses_by_bs_by_circle_id', '_user_by_uuid', '_worklist_sync_db', '_worklist_sync_circles',
|
||||
'_worklist_notify', '_worklist_notify_self', '_runners', '_linked', '_dev',
|
||||
'_worklist_notify', '_worklist_notify_self', '_runners', '_linked', '_dev', 'recent_alerts', 'on_user_deleted',
|
||||
'_watches', 'abuse',
|
||||
)
|
||||
|
||||
user_service: UserService
|
||||
@@ -48,7 +52,11 @@ class Backend:
|
||||
_runners: List[Runner]
|
||||
_linked: bool
|
||||
_dev: Optional[Any]
|
||||
|
||||
recent_alerts: 'deque[Dict[str, Any]]'
|
||||
on_user_deleted: Optional[Callable[[str, str], None]]
|
||||
_watches: '_WatchRegistry'
|
||||
abuse: AbuseService
|
||||
|
||||
def __init__(self,
|
||||
loop: asyncio.AbstractEventLoop, *,
|
||||
user_service: UserService, login_auth_service: LoginAuthService, auth_service: AuthService, stats_service: Stats,
|
||||
@@ -72,7 +80,11 @@ class Backend:
|
||||
self._runners = []
|
||||
self._linked = False
|
||||
self._dev = None
|
||||
|
||||
self.recent_alerts = deque(maxlen = 50)
|
||||
self.on_user_deleted = None
|
||||
self._watches = _WatchRegistry()
|
||||
self.abuse = AbuseService(self)
|
||||
|
||||
server_temp_cleanup()
|
||||
for circle in self.user_service.get_all_circles():
|
||||
self.chat_create(circle = circle)
|
||||
@@ -85,11 +97,15 @@ class Backend:
|
||||
loop.create_task(self._worker_sync_stats())
|
||||
loop.create_task(self._worker_notify())
|
||||
loop.create_task(self._worker_notify_self())
|
||||
loop.create_task(self._worker_purge_suspended())
|
||||
|
||||
def push_client_alert(self, icon_url: Optional[str], url: Optional[str], message: str = '') -> None:
|
||||
def push_client_alert(self, alert: Alert) -> int:
|
||||
print(f"[Backend] Pushing system alert")
|
||||
delivered = 0
|
||||
for bs in self._sc.iter_sessions():
|
||||
bs.evt.on_client_alert(icon_url, url, message)
|
||||
if bs.evt.on_client_alert(alert):
|
||||
delivered += 1
|
||||
return delivered
|
||||
|
||||
def push_maintenance_message(self, *args: Any, **kwargs: Any) -> None:
|
||||
print(f"[Backend] Server going down for maintenance in {args[1]} minutes. Pushing system alert")
|
||||
@@ -124,6 +140,8 @@ class Backend:
|
||||
old_substatus = user.status.substatus
|
||||
self._stats.on_logout()
|
||||
self._sc.remove_session(sess)
|
||||
# a closed session's client-side buddy list goes with it
|
||||
self._watches.remove_session(sess)
|
||||
print(f"[Presence] <Info> BackendSession {str(id(sess))} belonging to {user.username} ({user.email}) has been closed")
|
||||
if self._sc.get_sessions_by_user(user):
|
||||
# There are still other people logged in as this user,
|
||||
@@ -162,6 +180,7 @@ class Backend:
|
||||
self._stats.on_login()
|
||||
self._stats.on_user_active(user, client)
|
||||
self._sc.add_session(bs)
|
||||
self._stats.on_online(self._sc.session_count())
|
||||
user.detail = self._load_detail(user)
|
||||
print(f"[Presence] <Info> {user.username} ({user.email}) has logged in with BackendSession ID {str(id(bs))}")
|
||||
print(f"[Presence] <Info> They are using {client.program.upper()} {client.version} via {client.via}")
|
||||
@@ -177,6 +196,8 @@ class Backend:
|
||||
|
||||
def _load_detail(self, user: User) -> UserDetail:
|
||||
if user.detail: return user.detail
|
||||
pending = self._worklist_sync_db.get(user)
|
||||
if pending is not None: return pending
|
||||
detail = self.user_service.get_detail(user.uuid)
|
||||
assert detail is not None
|
||||
return detail
|
||||
@@ -239,6 +260,20 @@ class Backend:
|
||||
def _notify_self(self, bs: 'BackendSession', old_substatus: Substatus, *, update_status: bool = True, update_info: bool = True) -> None:
|
||||
self._worklist_notify_self.append((bs, old_substatus, update_status, update_info))
|
||||
|
||||
def notify_whats_new(self, user: User) -> None:
|
||||
# `user` has a new "What's New" activity: their own places and every contact watching them get to refetch it
|
||||
for bs in self._sc.get_sessions_by_user(user):
|
||||
bs.evt.msn_on_whats_new(user)
|
||||
detail = self._load_detail(user)
|
||||
for ctc in detail.contacts.values():
|
||||
if ctc.lists & ContactList.BL: continue
|
||||
for bs_other in self._sc.get_sessions_by_user(ctc.head):
|
||||
detail_other = bs_other.user.detail
|
||||
if detail_other is None: continue
|
||||
ctc_me = detail_other.contacts.get(user.uuid)
|
||||
if ctc_me is None or not ctc_me.lists & ContactList.FL: continue
|
||||
bs_other.evt.msn_on_whats_new(user)
|
||||
|
||||
def _mark_modified(self, user: User, *, detail: Optional[UserDetail] = None) -> None:
|
||||
ud = user.detail or detail
|
||||
if detail: assert ud is detail
|
||||
@@ -263,6 +298,54 @@ class Backend:
|
||||
def util_get_uuid_from_user_id(self, uid: int) -> Optional[str]:
|
||||
return self.user_service.get_uuid_user_id(uid)
|
||||
|
||||
def util_get_uuid_from_uin(self, uin: int) -> Optional[str]:
|
||||
return self.user_service.get_uuid_uin(uin)
|
||||
|
||||
def util_get_uuid_from_screenname(self, name: str) -> Optional[str]:
|
||||
# OSCAR and ICQ name an account by its screen name or by its UIN; an all-digit name is tried as a UIN first,
|
||||
# falling back to a screen name that happens to be all digits
|
||||
name = name.replace(' ', '')
|
||||
if _UIN_RE.match(name) is not None:
|
||||
uuid = self.util_get_uuid_from_uin(int(name))
|
||||
if uuid is not None:
|
||||
return uuid
|
||||
return self.util_get_uuid_from_username(name)
|
||||
|
||||
def util_get_uuids_for_login(self, name: str) -> List[str]:
|
||||
# every account a login name could mean, so a numeric screen name and someone else's UIN can both still sign on
|
||||
name = name.replace(' ', '')
|
||||
uuids = [] # type: List[str]
|
||||
if _UIN_RE.match(name) is not None:
|
||||
uuid = self.util_get_uuid_from_uin(int(name))
|
||||
if uuid is not None:
|
||||
uuids.append(uuid)
|
||||
uuid = self.util_get_uuid_from_username(name)
|
||||
if uuid is not None and uuid not in uuids:
|
||||
uuids.append(uuid)
|
||||
return uuids
|
||||
|
||||
def util_watch(self, bs: 'BackendSession', uuid: str) -> None:
|
||||
# a session-only interest in someone's presence (OSCAR's client-side buddy list), kept out of the stored contact list
|
||||
self._watches.add(bs, uuid)
|
||||
|
||||
def util_unwatch(self, bs: 'BackendSession', uuid: str) -> None:
|
||||
self._watches.remove(bs, uuid)
|
||||
|
||||
def util_unwatch_all(self, bs: 'BackendSession') -> None:
|
||||
self._watches.remove_session(bs)
|
||||
|
||||
def util_get_watched(self, bs: 'BackendSession') -> Set[str]:
|
||||
return self._watches.watched_by(bs)
|
||||
|
||||
def util_get_watchers(self, uuid: str) -> List['BackendSession']:
|
||||
return self._watches.watchers_of(uuid)
|
||||
|
||||
def util_message_allowed(self, user: User, data: MessageData) -> bool:
|
||||
if data.type not in RATED_MESSAGE_TYPES: return True
|
||||
if 'abuse_allowed' not in data.front_cache:
|
||||
data.front_cache['abuse_allowed'] = self.abuse.allow_message(user)
|
||||
return bool(data.front_cache['abuse_allowed'])
|
||||
|
||||
def util_set_sess_token(self, sess: 'BackendSession', token: str) -> None:
|
||||
self._sc.set_nc_by_token(sess, token)
|
||||
|
||||
@@ -272,6 +355,177 @@ class Backend:
|
||||
def util_get_sessions_by_user(self, user: User) -> List['BackendSession']:
|
||||
return self._sc.get_sessions_by_user(user)
|
||||
|
||||
def util_contact_groups(self, user: User) -> List[Group]:
|
||||
detail = self._load_detail(user)
|
||||
return sorted(detail._groups_by_id.values(), key = lambda group: (not group.is_favorite, group.name.lower()))
|
||||
|
||||
def util_add_contact(
|
||||
self, user: User, contact_uuid: str, *, group_id: Optional[str] = None, new_group: Optional[str] = None,
|
||||
) -> Tuple[bool, Optional[Group]]:
|
||||
detail = self._load_detail(user)
|
||||
group = None
|
||||
if group_id is not None:
|
||||
group = detail.get_group_by_id(group_id)
|
||||
if group is None:
|
||||
raise error.GroupDoesNotExist()
|
||||
old_ctc = detail.contacts.get(contact_uuid)
|
||||
already = old_ctc is not None and bool(old_ctc.lists & ContactList.FL) and bool(old_ctc.lists & ContactList.AL)
|
||||
if group is not None and old_ctc is not None and old_ctc.lists & ContactList.FL and old_ctc.group_in_entry(group):
|
||||
group = None
|
||||
if already and group is None and new_group is None:
|
||||
return False, None
|
||||
sessions = self._sc.get_sessions_by_user(user)
|
||||
if sessions:
|
||||
session = sessions[0] # type: Any
|
||||
else:
|
||||
session = _OfflineSessionShim(self, user)
|
||||
user.detail = detail
|
||||
try:
|
||||
if new_group is not None:
|
||||
group = BackendSession.me_group_add(session, new_group)
|
||||
if not already:
|
||||
BackendSession.me_contact_add(session, contact_uuid, ContactList.FL | ContactList.AL, needs_notify = True)
|
||||
if group is not None:
|
||||
BackendSession.me_group_contact_add(session, group.id, contact_uuid)
|
||||
finally:
|
||||
if not sessions:
|
||||
user.detail = None
|
||||
for bs in sessions:
|
||||
bs.evt.msn_on_notify_ab()
|
||||
return not already, group
|
||||
|
||||
def util_add_group(self, user: User, name: str) -> Group:
|
||||
detail = self._load_detail(user)
|
||||
sessions = self._sc.get_sessions_by_user(user)
|
||||
if sessions:
|
||||
session = sessions[0] # type: Any
|
||||
else:
|
||||
session = _OfflineSessionShim(self, user)
|
||||
user.detail = detail
|
||||
try:
|
||||
group = BackendSession.me_group_add(session, name)
|
||||
finally:
|
||||
if not sessions:
|
||||
user.detail = None
|
||||
for bs in sessions:
|
||||
bs.evt.msn_on_notify_ab()
|
||||
return group
|
||||
|
||||
def util_contact_states(self, user: User, uuids: Iterable[str]) -> Dict[str, str]:
|
||||
detail = self._load_detail(user)
|
||||
states: dict[str, str] = {}
|
||||
for uuid in uuids:
|
||||
if uuid == user.uuid:
|
||||
states[uuid] = 'self'
|
||||
continue
|
||||
ctc = detail.contacts.get(uuid)
|
||||
if ctc is None or not ctc.lists & ContactList.FL:
|
||||
states[uuid] = 'none'
|
||||
elif ctc.lists & ContactList.BL:
|
||||
states[uuid] = 'blocked'
|
||||
else:
|
||||
states[uuid] = 'contact'
|
||||
return states
|
||||
|
||||
def util_delete_circle(self, circle: Circle) -> List[User]:
|
||||
members = [membership.head for membership in circle.memberships.values() if membership.state != CircleState.Empty]
|
||||
chat = self.chat_get('persistent', circle.chat_id)
|
||||
if chat is not None:
|
||||
for cs in list(chat.get_roster()):
|
||||
cs.close()
|
||||
for scope, chat_id in list(chat.ids.items()):
|
||||
self._chats_by_id.pop((scope, chat_id), None)
|
||||
self._cses_by_bs_by_circle_id.pop(circle.chat_id, None)
|
||||
self._worklist_sync_circles.pop(circle.chat_id, None)
|
||||
self.user_service.delete_circle(circle.chat_id)
|
||||
for user in members:
|
||||
for bs in self.util_get_sessions_by_user(user):
|
||||
bs.evt.on_left_circle(circle)
|
||||
print(f'[Circle] <Info> {circle.name} (ID: {circle.chat_id}) has been deleted')
|
||||
return members
|
||||
|
||||
def util_delete_user(self, uuid: str) -> Optional[User]:
|
||||
user = self._load_user_record(uuid)
|
||||
if user is None:
|
||||
return None
|
||||
for bs in self.util_get_sessions_by_user(user):
|
||||
try:
|
||||
bs.close()
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
for other in list(self._user_by_uuid.values()):
|
||||
if other is not user and other.detail is not None:
|
||||
other.detail.contacts.pop(uuid, None)
|
||||
for pending in self._worklist_sync_db.values():
|
||||
if pending is not None:
|
||||
pending.contacts.pop(uuid, None)
|
||||
self._worklist_sync_db.pop(user, None)
|
||||
|
||||
new_owners: dict[str, Circle] = {}
|
||||
for circle in self.user_service.get_all_circles():
|
||||
membership = circle.memberships.get(uuid)
|
||||
if membership is None and circle.owner_uuid != uuid:
|
||||
continue
|
||||
others = sorted((
|
||||
m for m in circle.memberships.values()
|
||||
if m.head.uuid != uuid and m.state == CircleState.Accepted and CircleRole.Admin <= m.role <= CircleRole.Member
|
||||
), key = lambda m: int(m.role))
|
||||
admins_left = [m for m in others if m.role == CircleRole.Admin]
|
||||
was_admin = membership is not None and membership.role == CircleRole.Admin and membership.state != CircleState.Empty
|
||||
if circle.owner_uuid == uuid or (was_admin and not admins_left):
|
||||
if not others:
|
||||
self.util_delete_circle(circle)
|
||||
continue
|
||||
successor = others[0]
|
||||
successor.role = CircleRole.Admin
|
||||
if circle.owner_uuid == uuid:
|
||||
circle.owner_id = successor.head.id
|
||||
circle.owner_uuid = successor.head.uuid
|
||||
circle.owner_friendly = successor.head.status.name or successor.head.email
|
||||
new_owners[circle.chat_id] = circle
|
||||
print(f"[Circle] <Info> {successor.head.username} ({successor.head.email}) now runs {circle.name} (ID: {circle.chat_id})")
|
||||
circle.memberships.pop(uuid, None)
|
||||
chat = self.chat_get('persistent', circle.chat_id)
|
||||
if chat is not None:
|
||||
for cs_other in chat.get_roster():
|
||||
if cs_other.user is not user:
|
||||
cs_other.bs.evt.on_circle_updated(circle)
|
||||
self._mark_circle_modified(circle)
|
||||
|
||||
if not self.user_service.delete_user(uuid, new_owners):
|
||||
return None
|
||||
self._user_by_uuid.pop(uuid, None)
|
||||
return user
|
||||
|
||||
def util_purge_suspended(self, now: Optional[datetime] = None) -> List[str]:
|
||||
days = getattr(settings, 'SUSPENDED_ACCOUNT_DAYS', None)
|
||||
if days is None:
|
||||
return []
|
||||
deleted = []
|
||||
for uuid in self.user_service.expired_suspensions(int(days), now):
|
||||
try:
|
||||
user = self.util_delete_user(uuid)
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
continue
|
||||
if user is None:
|
||||
continue
|
||||
print(f"[Backend] <Info> {user.username} ({user.email}) was suspended over {days} days ago and has been deleted")
|
||||
deleted.append(uuid)
|
||||
if self.on_user_deleted is not None:
|
||||
self.on_user_deleted(uuid, 'suspended')
|
||||
return deleted
|
||||
|
||||
def util_contact_state(self, user: User, contact: User) -> str:
|
||||
if user.uuid == contact.uuid:
|
||||
return 'self'
|
||||
ctc = self._load_detail(user).contacts.get(contact.uuid)
|
||||
if ctc is None or not ctc.lists & ContactList.FL:
|
||||
return 'none'
|
||||
if ctc.lists & ContactList.BL:
|
||||
return 'blocked'
|
||||
return 'contact'
|
||||
|
||||
def util_get_circle_memberships_by_role(self, circle: Circle, role: CircleRole) -> Iterable[CircleMembership]:
|
||||
return [membership for membership in circle.memberships.values() if membership.role == role]
|
||||
|
||||
@@ -350,6 +604,7 @@ class Backend:
|
||||
membership.role = CircleRole.Member
|
||||
membership.state = CircleState.Empty
|
||||
|
||||
membership_inviter_email = membership.inviter_email
|
||||
if membership.inviter_uuid is not None:
|
||||
membership.inviter_uuid = None
|
||||
if membership.inviter_email is not None:
|
||||
@@ -361,7 +616,7 @@ class Backend:
|
||||
|
||||
for bs_other in self.util_get_sessions_by_user(user):
|
||||
print(f"[Circle] <Info> {user.username} ({user.email})'s invitation to {circle.name} (ID: {circle.chat_id}) has been revoked")
|
||||
if membership_inviter_email is not None: print(f"[Circle] <Info> It was sent by {membership.inviter_email}")
|
||||
if membership_inviter_email is not None: print(f"[Circle] <Info> It was sent by {membership_inviter_email}")
|
||||
bs_other.evt.on_circle_invite_revoked(circle.chat_id)
|
||||
|
||||
if chat is not None:
|
||||
@@ -483,6 +738,15 @@ class Backend:
|
||||
except:
|
||||
traceback.print_exc()
|
||||
|
||||
async def _worker_purge_suspended(self) -> None:
|
||||
await asyncio.sleep(60)
|
||||
while True:
|
||||
try:
|
||||
self.util_purge_suspended()
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
await asyncio.sleep(3600)
|
||||
|
||||
async def _worker_sync_circles(self) -> None:
|
||||
while True:
|
||||
await asyncio.sleep(0.04)
|
||||
@@ -520,7 +784,7 @@ class Backend:
|
||||
while True:
|
||||
await asyncio.sleep(60)
|
||||
try:
|
||||
self._stats.flush()
|
||||
self._stats.flush(online = self._sc.session_count())
|
||||
except:
|
||||
traceback.print_exc()
|
||||
|
||||
@@ -539,8 +803,7 @@ class Backend:
|
||||
for bs, sess_id, on_contact_add, old_substatus, updated_phone_info, update_status, update_info_other, for_logout in worklist:
|
||||
user = bs.user
|
||||
detail = user.detail
|
||||
assert detail is not None
|
||||
for ctc in detail.contacts.values():
|
||||
for ctc in (detail.contacts.values() if detail is not None else ()):
|
||||
for bs_other in self._sc.get_sessions_by_user(ctc.head):
|
||||
if bs_other.user is user: continue
|
||||
detail_other = bs_other.user.detail
|
||||
@@ -554,6 +817,15 @@ class Backend:
|
||||
ctc_me, on_contact_add, old_substatus, sess_id = sess_id, updated_phone_info = updated_phone_info,
|
||||
update_status = update_status, update_info_other = update_info_other,
|
||||
)
|
||||
# sessions that only watch `user` through a client-side buddy list, and weren't told above
|
||||
for bs_other in self._watches.watchers_of(user.uuid):
|
||||
if bs_other.user is user: continue
|
||||
if detail is not None:
|
||||
if _sees_through_list(user, detail, bs_other.user) or _is_blocking(user, bs_other.user): continue
|
||||
bs_other.evt.on_presence_notification(
|
||||
_watch_contact(user, bs_other.user), on_contact_add, old_substatus, sess_id = sess_id,
|
||||
updated_phone_info = updated_phone_info, update_status = update_status, update_info_other = update_info_other,
|
||||
)
|
||||
for circle in self.user_service.get_circle_batch(user):
|
||||
if circle.chat_id not in self._cses_by_bs_by_circle_id: continue
|
||||
if bs not in self._cses_by_bs_by_circle_id[circle.chat_id]: continue
|
||||
@@ -599,6 +871,19 @@ class Session(metaclass = ABCMeta):
|
||||
@abstractmethod
|
||||
def _on_close(self, **kwargs: Any) -> None: pass
|
||||
|
||||
class _OfflineSessionShim:
|
||||
__slots__ = ('backend', 'user')
|
||||
|
||||
backend: Backend
|
||||
user: User
|
||||
|
||||
def __init__(self, backend: Backend, user: User) -> None:
|
||||
self.backend = backend
|
||||
self.user = user
|
||||
|
||||
def _add_to_list(self, *args: Any, **kwargs: Any) -> Contact:
|
||||
return BackendSession._add_to_list(self, *args, **kwargs) # type: ignore
|
||||
|
||||
class BackendSession(Session):
|
||||
__slots__ = ('backend', 'user', 'client', 'chat_enabled', 'evt', 'front_data')
|
||||
|
||||
@@ -733,7 +1018,44 @@ class BackendSession(Session):
|
||||
)
|
||||
if notify_self:
|
||||
self.backend._notify_self(self, old_substatus, update_status = notify_status, update_info = notify_info_other)
|
||||
|
||||
def me_visibility_snapshot(self) -> Dict[str, bool]:
|
||||
# which of the contacts that have us on their list can currently see us
|
||||
user = self.user
|
||||
detail = user.detail
|
||||
if detail is None: return {}
|
||||
snapshot = {} # type: Dict[str, bool]
|
||||
for ctc in detail.contacts.values():
|
||||
if not ctc.lists & ContactList.RL: continue
|
||||
snapshot[ctc.head.uuid] = not _is_blocking(user, ctc.head)
|
||||
# client-side buddy lists can see us too, without any list linking us
|
||||
for bs_other in self.backend._watches.watchers_of(user.uuid):
|
||||
if bs_other.user is user or bs_other.user.uuid in snapshot: continue
|
||||
snapshot[bs_other.user.uuid] = not _is_blocking(user, bs_other.user)
|
||||
return snapshot
|
||||
|
||||
def me_visibility_changed(self, before: Dict[str, bool]) -> None:
|
||||
# push an arrival/departure to every contact whose view of us changed since `before` was taken
|
||||
backend = self.backend
|
||||
user = self.user
|
||||
detail = user.detail
|
||||
if detail is None or user.status.substatus is Substatus.Offline: return
|
||||
after = self.me_visibility_snapshot()
|
||||
backend._sync_contact_statuses(user)
|
||||
for uuid, visible in after.items():
|
||||
if before.get(uuid) == visible: continue
|
||||
ctc = detail.contacts.get(uuid)
|
||||
if ctc is not None:
|
||||
for sess_other in backend._sc.get_sessions_by_user(ctc.head):
|
||||
detail_other = sess_other.user.detail
|
||||
if detail_other is None: continue
|
||||
ctc_me = detail_other.contacts.get(user.uuid)
|
||||
if ctc_me is None or not ctc_me.lists & ContactList.FL: continue
|
||||
sess_other.evt.on_presence_notification(ctc_me, False, user.status.substatus)
|
||||
for sess_other in backend._watches.watchers_of(user.uuid):
|
||||
if sess_other.user.uuid != uuid or _sees_through_list(user, detail, sess_other.user): continue
|
||||
sess_other.evt.on_presence_notification(_watch_contact(user, sess_other.user), False, user.status.substatus)
|
||||
|
||||
def me_group_add(self, name: str, *, is_favorite: Optional[bool] = None) -> Group:
|
||||
if len(name) > MAX_GROUP_NAME_LENGTH:
|
||||
raise error.GroupNameTooLong()
|
||||
@@ -1043,7 +1365,7 @@ class BackendSession(Session):
|
||||
invite_msg = f"""\
|
||||
Subject: {sender_email} wants to talk to you using CrossTalk!
|
||||
To: {email}
|
||||
From: undergr0und network administration <administration@ugnet.gay>
|
||||
From: CrossTalk network administration <administration@ugnet.xyz>
|
||||
|
||||
This e-mail was sent to you because {sender_info} wants to chat with you using the CrossTalk service, and you don't have an account.
|
||||
|
||||
@@ -1066,7 +1388,7 @@ They've attached this message, as well:
|
||||
with smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT) as server:
|
||||
server.starttls()
|
||||
server.login(settings.SMTP_USERNAME, settings.SMTP_PASSWORD)
|
||||
server.sendmail("administration@ugnet.gay", email, invite_msg)
|
||||
server.sendmail("administration@ugnet.xyz", email, invite_msg)
|
||||
else:
|
||||
print(f"[Mailer] <Info> {sender_email} already has an account. Not sending an invitation e-mail.")
|
||||
|
||||
@@ -1302,6 +1624,9 @@ class _SessionCollection:
|
||||
def iter_sessions(self) -> Iterable[BackendSession]:
|
||||
yield from self._sessions
|
||||
|
||||
def session_count(self) -> int:
|
||||
return len(self._sessions)
|
||||
|
||||
def set_nc_by_token(self, sess: BackendSession, token: str) -> None:
|
||||
self._sess_by_token[token] = sess
|
||||
self._tokens_by_sess[sess].add(token)
|
||||
@@ -1464,13 +1789,6 @@ class Chat:
|
||||
|
||||
last_pop = False
|
||||
|
||||
if len(self._users_by_sess) == 1 and self.circle is None:
|
||||
_, last_user = next(iter(self._users_by_sess.values()))
|
||||
if last_user == su[0]:
|
||||
for scope_id in self.ids:
|
||||
del self.backend._chats_by_id[scope_id]
|
||||
last_pop = True
|
||||
|
||||
sess_others = [sess_other for sess_other in self._users_by_sess.keys() if sess_other.user is su[0]]
|
||||
|
||||
if sess_others:
|
||||
@@ -1481,7 +1799,9 @@ class Chat:
|
||||
break
|
||||
if no_primary_pop:
|
||||
sess_others[-1].primary_pop = True
|
||||
elif last_pop:
|
||||
else:
|
||||
# `sess` was the user's last place in the chat: they've left it (every frontend tells its clients then; with MPoP,
|
||||
# the places before it leaving are only for the clients that show places)
|
||||
last_pop = True
|
||||
|
||||
# Notify others that `sess` has left
|
||||
@@ -1543,37 +1863,57 @@ class ChatSession(Session):
|
||||
if len(ctc_sessions) == len(disabled_sessions): raise error.ContactNotOnline()
|
||||
if len(ctc_sessions) == len(already_invited_sessions): raise error.ContactAlreadyOnContactList()
|
||||
|
||||
def send_message_to_everyone(self, data: MessageData) -> None:
|
||||
def send_message_to_everyone(self, data: MessageData) -> bool:
|
||||
stats = self.chat._stats
|
||||
client = self.bs.client
|
||||
|
||||
if stats and data.type == MessageType.Chat or MessageType.Nudge or MessageType.Emoticon or MessageType.Ink:
|
||||
backend = self.bs.backend
|
||||
|
||||
if client.program not in _UNRATED_PROGRAMS and not backend.util_message_allowed(self.user, data): return False
|
||||
|
||||
if stats and data.type in _STATS_MESSAGE_TYPES:
|
||||
stats.on_message_sent(self.user, client)
|
||||
stats.on_user_active(self.user, client)
|
||||
|
||||
for cs_other in self.chat._users_by_sess.keys():
|
||||
|
||||
tracked: Set[str] = set()
|
||||
for cs_other in list(self.chat._users_by_sess.keys()):
|
||||
if cs_other is self: continue
|
||||
if self.chat.circle is not None and self.chat.circle.memberships[cs_other.user.uuid].blocking: continue
|
||||
cs_other.evt.on_message(data)
|
||||
print(f"[Chat] <Info> {self.user.username} ({self.user.email}) has sent a messasge to {cs_other.user.username} ({cs_other.user.email}) of type {data.type}")
|
||||
if stats:
|
||||
stats.on_message_received(cs_other.user, client)
|
||||
|
||||
def send_message_to_user(self, user_uuid: str, data: MessageData) -> None:
|
||||
if data.type in RATED_MESSAGE_TYPES and cs_other.user.uuid not in tracked and 'abuse_tracked' not in data.front_cache:
|
||||
tracked.add(cs_other.user.uuid)
|
||||
backend.abuse.track_message(self.user, cs_other.user)
|
||||
if tracked:
|
||||
data.front_cache['abuse_tracked'] = True
|
||||
return True
|
||||
|
||||
def send_message_to_user(self, user_uuid: str, data: MessageData) -> bool:
|
||||
stats = self.chat._stats
|
||||
client = self.bs.client
|
||||
|
||||
if stats and data.type == MessageType.Chat or MessageType.Nudge or MessageType.Emoticon or MessageType.Ink:
|
||||
backend = self.bs.backend
|
||||
|
||||
if client.program not in _UNRATED_PROGRAMS and not backend.util_message_allowed(self.user, data): return False
|
||||
|
||||
if stats and data.type in _STATS_MESSAGE_TYPES:
|
||||
stats.on_message_sent(self.user, client)
|
||||
stats.on_user_active(self.user, client)
|
||||
|
||||
for cs_other in self.chat._users_by_sess.keys():
|
||||
|
||||
tracked = False
|
||||
for cs_other in list(self.chat._users_by_sess.keys()):
|
||||
if cs_other is self: continue
|
||||
if cs_other.user.uuid != user_uuid: continue
|
||||
print(f"[Chat] <Info> {self.user.username} ({self.user.email}) has sent a messasge to {cs_other.user.username} ({cs_other.user.email}) of type {data.type}")
|
||||
cs_other.evt.on_message(data)
|
||||
if stats and data.type == MessageType.Chat or MessageType.Nudge or MessageType.Emoticon or MessageType.Ink:
|
||||
if stats and data.type in _STATS_MESSAGE_TYPES:
|
||||
stats.on_message_received(cs_other.user, client)
|
||||
if data.type in RATED_MESSAGE_TYPES and not tracked and 'abuse_tracked' not in data.front_cache:
|
||||
tracked = True
|
||||
backend.abuse.track_message(self.user, cs_other.user)
|
||||
if tracked:
|
||||
data.front_cache['abuse_tracked'] = True
|
||||
return True
|
||||
|
||||
def _gen_group_id(detail: UserDetail) -> str:
|
||||
id = 1
|
||||
@@ -1595,10 +1935,62 @@ def _gen_contact_id(detail: UserDetail) -> str:
|
||||
|
||||
MAX_GROUP_NAME_LENGTH = 61
|
||||
|
||||
_STATS_MESSAGE_TYPES = (MessageType.Chat, MessageType.Nudge, MessageType.Emoticon, MessageType.Ink)
|
||||
|
||||
|
||||
# TODO: PL
|
||||
LST_LIMITS = {
|
||||
ContactList.FL: 1000,
|
||||
ContactList.AL: 1500,
|
||||
ContactList.BL: 1200,
|
||||
ContactList.RL: 1500,
|
||||
}
|
||||
}
|
||||
_UIN_RE = re.compile(r'^[0-9]{1,10}$')
|
||||
|
||||
class _WatchRegistry:
|
||||
__slots__ = ('_watchers_by_uuid', '_watched_by_sess')
|
||||
|
||||
_watchers_by_uuid: Dict[str, Set['BackendSession']]
|
||||
_watched_by_sess: Dict['BackendSession', Set[str]]
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._watchers_by_uuid = {}
|
||||
self._watched_by_sess = {}
|
||||
|
||||
def add(self, bs: 'BackendSession', uuid: str) -> None:
|
||||
self._watchers_by_uuid.setdefault(uuid, set()).add(bs)
|
||||
self._watched_by_sess.setdefault(bs, set()).add(uuid)
|
||||
|
||||
def remove(self, bs: 'BackendSession', uuid: str) -> None:
|
||||
watchers = self._watchers_by_uuid.get(uuid)
|
||||
if watchers is not None:
|
||||
watchers.discard(bs)
|
||||
if not watchers:
|
||||
del self._watchers_by_uuid[uuid]
|
||||
watched = self._watched_by_sess.get(bs)
|
||||
if watched is not None:
|
||||
watched.discard(uuid)
|
||||
if not watched:
|
||||
del self._watched_by_sess[bs]
|
||||
|
||||
def remove_session(self, bs: 'BackendSession') -> None:
|
||||
for uuid in list(self._watched_by_sess.get(bs, ())):
|
||||
self.remove(bs, uuid)
|
||||
|
||||
def watched_by(self, bs: 'BackendSession') -> Set[str]:
|
||||
return set(self._watched_by_sess.get(bs, ()))
|
||||
|
||||
def watchers_of(self, uuid: str) -> List['BackendSession']:
|
||||
return [bs for bs in self._watchers_by_uuid.get(uuid, ()) if not bs.closed]
|
||||
|
||||
def _sees_through_list(user: User, detail: UserDetail, other: User) -> bool:
|
||||
if other.uuid not in detail.contacts: return False
|
||||
detail_other = other.detail
|
||||
if detail_other is None: return False
|
||||
ctc_me = detail_other.contacts.get(user.uuid)
|
||||
return ctc_me is not None and bool(ctc_me.lists & ContactList.FL)
|
||||
|
||||
def _watch_contact(user: User, viewer: User) -> Contact:
|
||||
ctc = Contact(user, set(), ContactList.Empty, UserStatus(user.status.name), ContactDetail('0'))
|
||||
ctc.compute_visible_status(viewer)
|
||||
return ctc
|
||||
+90
-3
@@ -48,9 +48,9 @@ class User(WithFrontData):
|
||||
uuid = Col(sa.String(50), unique = True)
|
||||
email = Col(sa.String(80, collation='utf8mb4_unicode_ci'), nullable=False, unique=True)
|
||||
username = Col(sa.String(40, collation='utf8mb4_unicode_ci'), nullable=False, unique=True)
|
||||
first_name = Col(sa.String(50), default = 'John')
|
||||
first_name = Col(sa.String(50), nullable = True)
|
||||
middle_name = Col(sa.String(50), nullable = True)
|
||||
last_name = Col(sa.String(50), default = 'Doe')
|
||||
last_name = Col(sa.String(50), nullable = True)
|
||||
# specifically used for social features/member directory
|
||||
nickname = Col(sa.String(60), nullable = True)
|
||||
uin = Col(sa.BigInteger, nullable = True)
|
||||
@@ -68,6 +68,7 @@ class User(WithFrontData):
|
||||
groups = Col(JSONType)
|
||||
settings = Col(JSONType)
|
||||
suspended = Col(sa.Boolean)
|
||||
suspended_at = Col(sa.DateTime, nullable = True)
|
||||
is_tester = Col(sa.Boolean)
|
||||
is_mvp = Col(sa.Boolean)
|
||||
show_in_dir = Col(sa.Boolean)
|
||||
@@ -76,6 +77,7 @@ class User(WithFrontData):
|
||||
alias_active = Col(sa.Boolean, default=False)
|
||||
did_firsttime_email_change = Col(sa.Boolean, default=False)
|
||||
account_verified = Col(sa.Boolean, default=False) # for e-mail address verification
|
||||
is_admin = Col(sa.Boolean, default = False, server_default = sa.false())
|
||||
lang = Col(sa.String(10), nullable = True)
|
||||
avatar = Col(sa.String(16), nullable = True)
|
||||
profile = relationship("UserProfile", backref="user", uselist=False, cascade="all, delete-orphan")
|
||||
@@ -131,7 +133,7 @@ class UserProfile(WithFrontData):
|
||||
state = Col(sa.String(80), nullable = True)
|
||||
zip = Col(sa.Integer, nullable = True)
|
||||
country = Col(sa.String(60), nullable = True)
|
||||
language = Col(sa.String(50), nullable = True)
|
||||
language = Col(JSONType, nullable = True)
|
||||
interests = Col(JSONType, nullable = True, default = {})
|
||||
visibility = Col(sa.String(25), default='public')
|
||||
|
||||
@@ -172,6 +174,68 @@ class Sound(Base):
|
||||
is_public = Col(sa.Boolean)
|
||||
hits = Col(sa.Integer, default = 0)
|
||||
|
||||
class Activity(Base):
|
||||
__tablename__ = 'user_activity'
|
||||
|
||||
id = Col(sa.Integer, primary_key = True)
|
||||
# `None` for service announcements
|
||||
user_uuid = Col(sa.String(50), sa.ForeignKey('user.uuid'), nullable = True, index = True)
|
||||
type = Col(sa.Integer)
|
||||
title = Col(sa.String(100), nullable = True)
|
||||
text = Col(sa.String(255), nullable = True)
|
||||
url = Col(sa.String(255), nullable = True)
|
||||
date_created = Col(sa.DateTime, default = datetime.utcnow, index = True)
|
||||
|
||||
class ActivityReaction(Base):
|
||||
__tablename__ = 'user_activity_reaction'
|
||||
__table_args__ = (sa.UniqueConstraint('activity_id', 'user_uuid', 'reaction'),)
|
||||
|
||||
id = Col(sa.Integer, primary_key = True)
|
||||
activity_id = Col(sa.Integer, index = True)
|
||||
user_uuid = Col(sa.String(50), index = True)
|
||||
reaction = Col(sa.String(64))
|
||||
date_created = Col(sa.DateTime, default = datetime.utcnow)
|
||||
|
||||
class ActivityComment(Base):
|
||||
__tablename__ = 'user_activity_comment'
|
||||
|
||||
id = Col(sa.Integer, primary_key = True)
|
||||
activity_id = Col(sa.Integer, index = True)
|
||||
user_uuid = Col(sa.String(50), index = True)
|
||||
text = Col(sa.String(255, collation='utf8mb4_unicode_ci'))
|
||||
date_created = Col(sa.DateTime, default = datetime.utcnow)
|
||||
|
||||
class InsClient(Base):
|
||||
__tablename__ = 'ins_client'
|
||||
|
||||
id = Col(sa.Integer, primary_key = True)
|
||||
identifier = Col(sa.String(64))
|
||||
label = Col(sa.String(100), default = '')
|
||||
transport_public = Col(sa.String(64), unique = True)
|
||||
auth_public = Col(sa.String(64))
|
||||
machine = Col(sa.String(64))
|
||||
addresses = Col(JSONType)
|
||||
date_created = Col(sa.DateTime, default = datetime.utcnow)
|
||||
date_last_seen = Col(sa.DateTime, nullable = True)
|
||||
last_address = Col(sa.String(64), nullable = True)
|
||||
revoked = Col(sa.Boolean, default = False)
|
||||
date_revoked = Col(sa.DateTime, nullable = True)
|
||||
|
||||
class InsEnrollment(Base):
|
||||
__tablename__ = 'ins_enrollment'
|
||||
|
||||
id = Col(sa.Integer, primary_key = True)
|
||||
code_id = Col(sa.String(32), unique = True)
|
||||
secret_hash = Col(sa.String(64))
|
||||
identifier = Col(sa.String(64))
|
||||
label = Col(sa.String(100), default = '')
|
||||
address = Col(sa.String(64), nullable = True)
|
||||
created_by = Col(sa.String(50), nullable = True)
|
||||
date_created = Col(sa.DateTime, default = datetime.utcnow)
|
||||
date_expires = Col(sa.DateTime)
|
||||
date_used = Col(sa.DateTime, nullable = True)
|
||||
client_id = Col(sa.Integer, nullable = True)
|
||||
|
||||
class LoginToken(Base):
|
||||
__tablename__ = 'login_token'
|
||||
|
||||
@@ -195,6 +259,29 @@ def _simplify_json_data(data: Any) -> Any:
|
||||
return [_simplify_json_data(x) for x in data]
|
||||
return data
|
||||
|
||||
def ensure_schema(engine: Any) -> list[str]:
|
||||
changed: list[str] = []
|
||||
inspector = sa.inspect(engine)
|
||||
tables = set(inspector.get_table_names())
|
||||
for table in (InsClient.__table__, InsEnrollment.__table__):
|
||||
if table.name not in tables:
|
||||
table.create(engine)
|
||||
changed.append(table.name)
|
||||
if 'user' in tables:
|
||||
columns = { column['name'] for column in inspector.get_columns('user') }
|
||||
quote = engine.dialect.identifier_preparer.quote
|
||||
if 'is_admin' not in columns:
|
||||
false = str(sa.false().compile(dialect = engine.dialect))
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text('ALTER TABLE {} ADD COLUMN {} BOOLEAN NOT NULL DEFAULT {}'.format(quote('user'), quote('is_admin'), false)))
|
||||
changed.append('user.is_admin')
|
||||
if 'suspended_at' not in columns:
|
||||
kind = sa.DateTime().compile(dialect = engine.dialect)
|
||||
with engine.begin() as conn:
|
||||
conn.execute(sa.text('ALTER TABLE {} ADD COLUMN {} {} NULL'.format(quote('user'), quote('suspended_at'), kind)))
|
||||
changed.append('user.suspended_at')
|
||||
return changed
|
||||
|
||||
engine = sa.create_engine(settings.DB, echo='debug' if settings.DEBUG and settings.DEBUG_FULL and settings.DEBUG_LOG_SQL_QUERIES else None)
|
||||
session_factory = sessionmaker(bind = engine)
|
||||
|
||||
|
||||
+82
-5
@@ -2,6 +2,7 @@ from typing import TYPE_CHECKING, Optional, Dict, Any, List
|
||||
from abc import ABCMeta, abstractmethod
|
||||
|
||||
from .models import User, Contact, OIM, Circle, CircleRole, MessageData, TextWithData, Substatus, LoginOption
|
||||
from .alerts import Alert
|
||||
from util.misc import MultiDict
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -26,12 +27,15 @@ class BackendEventHandler(metaclass = ABCMeta):
|
||||
def on_maintenance_message(self, *args: Any, **kwargs: Any) -> None:
|
||||
pass
|
||||
|
||||
def on_client_alert(self, icon_url: Optional[str], url: Optional[str], message: str = '') -> None:
|
||||
pass
|
||||
def on_client_alert(self, alert: Alert) -> bool:
|
||||
return False
|
||||
|
||||
def on_maintenance_boot(self) -> None:
|
||||
pass
|
||||
|
||||
|
||||
def on_warning_level_changed(self, level: int, warner: Optional[User]) -> None:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def on_presence_notification(
|
||||
self, ctc: Contact, on_contact_add: bool, old_substatus: Substatus, *,
|
||||
@@ -92,17 +96,23 @@ class BackendEventHandler(metaclass = ABCMeta):
|
||||
pass
|
||||
|
||||
def msn_on_uun_sent(
|
||||
self, sender: User, type: int, data: Optional[bytes], *,
|
||||
pop_id_sender: Optional[str] = None, pop_id: Optional[str] = None,
|
||||
self, sender: User, type: Optional[int], data: Optional[bytes], *,
|
||||
pop_id_sender: Optional[str] = None, pop_id: Optional[str] = None, sdg: Optional[bytes] = None,
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
def msn_on_notify_ab(self) -> None:
|
||||
pass
|
||||
|
||||
def msn_on_whats_new(self, publisher: User) -> None:
|
||||
pass
|
||||
|
||||
def msn_on_notify_circle_ab(self, chat_id: str) -> None:
|
||||
pass
|
||||
|
||||
def msn_on_page(self, sender: User, text: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def ymsg_on_p2p_msg_request(self, sess_id: int, yahoo_data: MultiDict[bytes, bytes]) -> None:
|
||||
pass
|
||||
@@ -115,7 +125,74 @@ class BackendEventHandler(metaclass = ABCMeta):
|
||||
|
||||
def ymsg_on_upload_file_ft(self, recipient: str, message: str) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_friend_icon(self, yahoo_id_sender: str, yahoo_id_receiver: str, checksum: bytes) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_friend_icon_download(self, yahoo_id_sender: str, yahoo_id_receiver: str, url: str, checksum: bytes) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_friend_icon_file_transfer(self, yahoo_id_sender: str, yahoo_id_receiver: str, url: str, filename: str, ts: str) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_friend_icon_flag(self, yahoo_id_sender: str, yahoo_id_receiver: str, icon_flag: bytes) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_audible(self, sender: str, receiver: str, audible_id: bytes, text: bytes, checksum: bytes) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_im_panel_feature(self, sender: str, receiver: str, feature: bytes, state: bytes) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_im_session(self, sender: str, receiver: str, flag: bytes) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_message_ack(self, sender: str, receiver: str, msg_id: bytes) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_imvironment(self, sender: str, receiver: str, imv: bytes, state: bytes) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_buddy_response(self, buddy: User, accepted: bool, message: str = '') -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_photo_add(
|
||||
self, sender: str, receiver: str, photo_id: bytes,
|
||||
name: Optional[bytes], thumbnail: Optional[bytes], url: Optional[bytes],
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_photo_ack(self, sender: str, receiver: str, photo_id: bytes) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_photo_select(self, sender: str, receiver: str, photo_id: bytes, action: bytes) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_photo_relay(
|
||||
self, sender: str, receiver: str, photo_id: bytes, token: bytes, *,
|
||||
relay_host: bytes, filesize: Optional[bytes], ack: bool,
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_ft_invite(self, sender: str, receiver: str, cookie: bytes, yahoo_data: MultiDict[bytes, bytes]) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_ft_setup(
|
||||
self, sender: str, receiver: str, cookie: bytes, *,
|
||||
filename: bytes, relay_host: bytes, peer_path: bytes, transfer_type: bytes,
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_ft_init(
|
||||
self, sender: str, receiver: str, cookie: bytes, yahoo_data: MultiDict[bytes, bytes], *, cancelled: bool = False,
|
||||
) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_sip_invite(self, caller: str, callee: str, call_id: str, sdp: str, *, video: bool = False) -> None:
|
||||
pass
|
||||
|
||||
def ymsg_on_sip_bye(self, caller: str, callee: str, call_id: str) -> None:
|
||||
pass
|
||||
class ChatEventHandler(metaclass = ABCMeta):
|
||||
__slots__ = ('cs',)
|
||||
|
||||
|
||||
+20
-5
@@ -25,7 +25,9 @@ def register(loop: asyncio.AbstractEventLoop, backend: Backend, *, devmode: bool
|
||||
backend.add_runner(AIOHTTPRunner(http_host, http_port, app, ssl_context=ssl_context, service='HTTP'))
|
||||
app.router.add_get('/', handle_misc_conns)
|
||||
app.router.add_post('/', handle_blankok)
|
||||
# TODO: migrate to static.ugnet.xyz
|
||||
app.router.add_static('/static', 'core/static')
|
||||
# TODO: move ads / avatars out of azul and into their own svcs
|
||||
app.router.add_get('/ads/txt', handle_textad)
|
||||
app.router.add_get('/ads/banner', handle_bannerad)
|
||||
app.router.add_get('/ads/banner-lg', lambda req: handle_bannerad(req, yuge=True))
|
||||
@@ -34,8 +36,7 @@ def register(loop: asyncio.AbstractEventLoop, backend: Backend, *, devmode: bool
|
||||
app.router.add_get('/svcs/mms/adxml_main.asp', lambda req: handle_bannerad(req, msnxml=True))
|
||||
app.router.add_get('/avatar/{uuid}/static', handle_avatar)
|
||||
app.router.add_get('/avatar/{uuid}/small', lambda req: handle_avatar(req, small=True))
|
||||
app.router.add_get('/avatar/{uuid}/msn', lambda req: handle_avatar(req, msn=True))
|
||||
app.router.add_route('*', '/{path:.*}', handle_notfound)
|
||||
app.router.add_get('/avatar/{uuid}/im', lambda req: handle_avatar(req, im=True))
|
||||
|
||||
return app
|
||||
|
||||
@@ -48,11 +49,18 @@ def create_app(loop: asyncio.AbstractEventLoop, backend: Backend) -> Any:
|
||||
)
|
||||
|
||||
app.on_response_prepare.append(on_response_prepare)
|
||||
app.middlewares.append(notfound_middleware)
|
||||
|
||||
util.misc.add_to_jinja_env(app, 'misc', MISC_TMPL_DIR)
|
||||
|
||||
return app
|
||||
|
||||
@web.middleware
|
||||
async def notfound_middleware(req: web.Request, handler: Any) -> web.StreamResponse:
|
||||
if isinstance(req.match_info.http_exception, web.HTTPNotFound):
|
||||
return await handle_notfound(req)
|
||||
return await handler(req)
|
||||
|
||||
async def on_response_prepare(req: web.Request, res: web.StreamResponse) -> None:
|
||||
res.headers['X-Azul-Version'] = settings.VERSION
|
||||
|
||||
@@ -86,7 +94,7 @@ async def handle_notfound(req: web.Request) -> web.Response:
|
||||
return render(req, 'misc:miscconns.html', {
|
||||
'settings': settings
|
||||
}, status=404)
|
||||
|
||||
|
||||
async def handle_bannerad(req: web.Request, yuge: bool = False, sq: bool = False, msnxml: bool = False) -> web.Response:
|
||||
with open('config/big-bannerimages.json' if yuge else 'config/sq-bannerimages.json' if sq else 'config/bannerimages.json', 'r') as json_file:
|
||||
data = json.load(json_file)
|
||||
@@ -154,14 +162,21 @@ async def handle_blankok(req: web.Request) -> web.Response:
|
||||
# MSN counts the login server as a "key port" by POSTing to the root of the server with no content.
|
||||
return web.Response(status = 200)
|
||||
|
||||
async def handle_avatar(req: web.Request, small: bool = False, msn: bool = False) -> web.Response:
|
||||
async def handle_avatar(req: web.Request, small: bool = False, im: bool = False) -> web.Response:
|
||||
uuid = req.match_info['uuid']
|
||||
backend: Backend = req.app['backend']
|
||||
|
||||
user = backend.user_service.get(uuid)
|
||||
avatar_md5 = user.avatar if user else None
|
||||
|
||||
result = get_avatar_data(uuid, avatar_md5, small=small, msn=msn)
|
||||
md5_query = req.query.get('md5') or ''
|
||||
if user is not None and 8 <= len(md5_query) <= 32 and all(c in '0123456789abcdef' for c in md5_query):
|
||||
result = get_avatar_data(uuid, md5_query, small=small, im=im)
|
||||
if result is not None:
|
||||
data, content_type = result
|
||||
return web.Response(status=200, body=data, content_type=content_type)
|
||||
|
||||
result = get_avatar_data(uuid, avatar_md5, small=small, im=im)
|
||||
if result is not None:
|
||||
data, content_type = result
|
||||
return web.Response(status=200, body=data, content_type=content_type)
|
||||
|
||||
@@ -0,0 +1,547 @@
|
||||
import base64, hashlib, hmac, os, secrets, struct
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable
|
||||
|
||||
from cryptography.exceptions import InvalidSignature, InvalidTag
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
|
||||
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM, ChaCha20Poly1305
|
||||
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
||||
|
||||
try:
|
||||
from cryptography.hazmat.primitives.asymmetric.mlkem import MLKEM768PrivateKey, MLKEM768PublicKey
|
||||
HAS_MLKEM = True
|
||||
except ImportError:
|
||||
HAS_MLKEM = False
|
||||
|
||||
MAGIC = b'KNIT'
|
||||
TRANSPORT_VERSION = 2
|
||||
IV_SIZE = 16
|
||||
KEY_SIZE = 32
|
||||
HELLO_SIZE = len(MAGIC) + 2 + KEY_SIZE
|
||||
WELCOME_SIZE = len(MAGIC) + 2 + KEY_SIZE + 16
|
||||
RECORD_HEADER = struct.Struct('>I')
|
||||
TAG_SIZE = 16
|
||||
MAX_DATA = 32 * 1024
|
||||
MAX_PADDING = 64
|
||||
MAX_RECORD = 1 + MAX_DATA + 2 + MAX_PADDING + 2 * TAG_SIZE + 2048
|
||||
MLKEM_PUBLIC_SIZE = 1184
|
||||
MLKEM_CIPHERTEXT_SIZE = 1088
|
||||
CODE_ID_SIZE = 16
|
||||
CODE_SECRET_SIZE = 32
|
||||
MAX_LABEL = 100
|
||||
|
||||
FLAG_PQ = 0x01
|
||||
FLAG_ENROLL = 0x02
|
||||
|
||||
REC_CLIENT_KEX = 0x01
|
||||
REC_SERVER_KEX = 0x02
|
||||
REC_DATA = 0x03
|
||||
REC_REJECT = 0x04
|
||||
|
||||
CHALLENGE_IDN = b'INS2-IDN'
|
||||
CHALLENGE_CHK = b'INS2-CHK'
|
||||
|
||||
HOST_KEY_FILE = 'host.key'
|
||||
HOST_PUB_FILE = 'host.pub'
|
||||
ENROLLMENT_CODE_PREFIX = 'ins2-'
|
||||
|
||||
class Reject:
|
||||
UnknownKey = 1
|
||||
WrongAddress = 2
|
||||
WrongMachine = 3
|
||||
BadEnrollment = 4
|
||||
Revoked = 5
|
||||
WrongIdentifier = 6
|
||||
TooManyAttempts = 7
|
||||
|
||||
MESSAGES = {
|
||||
UnknownKey: 'this client key is not enrolled on the server',
|
||||
WrongAddress: 'this client key is not allowed from this address',
|
||||
WrongMachine: 'this client key belongs to a different machine or OS install',
|
||||
BadEnrollment: 'the enrollment code is not valid, was already used or has expired',
|
||||
Revoked: 'this client key was revoked',
|
||||
WrongIdentifier: 'this client key is not allowed to use that identifier',
|
||||
TooManyAttempts: 'too many failed attempts from this address, try again later',
|
||||
}
|
||||
|
||||
class INSCryptoError(Exception):
|
||||
pass
|
||||
|
||||
class INSRejected(INSCryptoError):
|
||||
reason: int
|
||||
|
||||
def __init__(self, reason: int, detail: str | None = None) -> None:
|
||||
super().__init__(detail or Reject.MESSAGES.get(reason, 'rejected by the server ({})'.format(reason)))
|
||||
self.reason = reason
|
||||
|
||||
@dataclass(frozen = True)
|
||||
class EnrollmentRequest:
|
||||
code_id: bytes
|
||||
secret: bytes
|
||||
auth_public: bytes
|
||||
identifier: str
|
||||
label: str
|
||||
|
||||
@dataclass(frozen = True)
|
||||
class ClientHello:
|
||||
transport_public: bytes
|
||||
machine: bytes
|
||||
enrollment: EnrollmentRequest | None
|
||||
|
||||
def _nonce(counter: int) -> bytes:
|
||||
return struct.pack('>4xQ', counter)
|
||||
|
||||
def raw_public(key: X25519PublicKey | Ed25519PublicKey) -> bytes:
|
||||
return key.public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
|
||||
|
||||
def _hkdf(ikm: bytes, salt: bytes, info: bytes, length: int = 32) -> bytes:
|
||||
return HKDF(algorithm = hashes.SHA256(), length = length, salt = salt, info = info).derive(ikm)
|
||||
|
||||
def _exchange(private: X25519PrivateKey, public: X25519PublicKey) -> bytes:
|
||||
try:
|
||||
return private.exchange(public)
|
||||
except ValueError as ex:
|
||||
raise INSCryptoError('invalid key exchange') from ex
|
||||
|
||||
def _x25519(raw: bytes) -> X25519PublicKey:
|
||||
try:
|
||||
return X25519PublicKey.from_public_bytes(raw)
|
||||
except ValueError as ex:
|
||||
raise INSCryptoError('invalid X25519 key') from ex
|
||||
|
||||
def _short_string(data: bytes, offset: int, limit: int) -> tuple[str, int]:
|
||||
if offset >= len(data):
|
||||
raise INSCryptoError('truncated enrollment')
|
||||
length = data[offset]
|
||||
end = offset + 1 + length
|
||||
if length > limit or end > len(data):
|
||||
raise INSCryptoError('invalid enrollment')
|
||||
try:
|
||||
return data[offset + 1:end].decode('utf-8'), end
|
||||
except UnicodeDecodeError as ex:
|
||||
raise INSCryptoError('invalid enrollment') from ex
|
||||
|
||||
def _pack_string(value: str, limit: int) -> bytes:
|
||||
data = value.encode('utf-8')[:limit]
|
||||
while data:
|
||||
try:
|
||||
data.decode('utf-8')
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
data = data[:-1]
|
||||
return bytes((len(data),)) + data
|
||||
|
||||
class _Veil:
|
||||
__slots__ = ('_ctx',)
|
||||
|
||||
def __init__(self, server_public: bytes, iv: bytes, direction: bytes) -> None:
|
||||
key = _hkdf(server_public, iv, b'INS2 veil ' + direction)
|
||||
self._ctx = Cipher(algorithms.AES(key), modes.CTR(bytes(16))).encryptor()
|
||||
|
||||
def apply(self, data: bytes) -> bytes:
|
||||
return self._ctx.update(data)
|
||||
|
||||
class SecureChannel:
|
||||
__slots__ = (
|
||||
'_initiator', '_server_public', '_host_key', '_resolver', '_client_key', '_machine', '_enrollment', '_ephemeral',
|
||||
'_peer_ephemeral', '_buffer', '_outbox', '_out_veil', '_in_veil', '_link_send', '_link_recv', '_link_send_ctr',
|
||||
'_link_recv_ctr', '_link_binding', '_kex_x25519', '_kex_mlkem', '_kex_random', '_client_body', '_client_send',
|
||||
'_client_recv', '_client_send_ctr', '_client_recv_ctr', 'binding', 'established', 'post_quantum', 'pq_offer',
|
||||
'identity', 'enrolled', 'rejected',
|
||||
)
|
||||
|
||||
def __init__(self) -> None:
|
||||
raise TypeError('use SecureChannel.client or SecureChannel.server')
|
||||
|
||||
@classmethod
|
||||
def _new(cls, initiator: bool, server_public: bytes, pq_offer: bool) -> 'SecureChannel':
|
||||
self = object.__new__(cls)
|
||||
self._initiator = initiator
|
||||
self._server_public = server_public
|
||||
self._host_key: X25519PrivateKey | None = None
|
||||
self._resolver: Callable[[ClientHello], Any] | None = None
|
||||
self._client_key: X25519PrivateKey | None = None
|
||||
self._machine = b''
|
||||
self._enrollment: EnrollmentRequest | None = None
|
||||
self._ephemeral = X25519PrivateKey.generate()
|
||||
self._peer_ephemeral: X25519PublicKey | None = None
|
||||
self._buffer = bytearray()
|
||||
self._outbox = bytearray()
|
||||
self._out_veil: _Veil | None = None
|
||||
self._in_veil: _Veil | None = None
|
||||
self._link_send: ChaCha20Poly1305 | None = None
|
||||
self._link_recv: ChaCha20Poly1305 | None = None
|
||||
self._link_send_ctr = 0
|
||||
self._link_recv_ctr = 0
|
||||
self._link_binding = b''
|
||||
self._kex_x25519 = X25519PrivateKey.generate()
|
||||
self._kex_mlkem: MLKEM768PrivateKey | None = None
|
||||
self._kex_random = secrets.token_bytes(32)
|
||||
self._client_body = b''
|
||||
self._client_send: AESGCM | None = None
|
||||
self._client_recv: AESGCM | None = None
|
||||
self._client_send_ctr = 0
|
||||
self._client_recv_ctr = 0
|
||||
self.binding = b''
|
||||
self.established = False
|
||||
self.post_quantum = False
|
||||
self.pq_offer = pq_offer and HAS_MLKEM
|
||||
self.identity = None # type: Any
|
||||
self.enrolled = False
|
||||
self.rejected: int | None = None
|
||||
return self
|
||||
|
||||
@classmethod
|
||||
def client(
|
||||
cls, server_public: X25519PublicKey | bytes, client_key: X25519PrivateKey, machine: bytes, *,
|
||||
enrollment: EnrollmentRequest | None = None, pq_offer: bool = True,
|
||||
) -> 'SecureChannel':
|
||||
server_raw = server_public if isinstance(server_public, bytes) else raw_public(server_public)
|
||||
if len(server_raw) != KEY_SIZE or len(machine) != 32:
|
||||
raise INSCryptoError('invalid server key or machine fingerprint')
|
||||
self = cls._new(True, server_raw, pq_offer)
|
||||
self._client_key = client_key
|
||||
self._machine = machine
|
||||
self._enrollment = enrollment
|
||||
self._start_veil()
|
||||
self._write_veiled(MAGIC + bytes((TRANSPORT_VERSION, FLAG_PQ if self.pq_offer else 0)) + raw_public(self._ephemeral.public_key()))
|
||||
return self
|
||||
|
||||
@classmethod
|
||||
def server(cls, host_key: X25519PrivateKey, resolver: Callable[[ClientHello], Any], *, pq_offer: bool = True) -> 'SecureChannel':
|
||||
self = cls._new(False, raw_public(host_key.public_key()), pq_offer)
|
||||
self._host_key = host_key
|
||||
self._resolver = resolver
|
||||
return self
|
||||
|
||||
def _start_veil(self) -> None:
|
||||
iv = secrets.token_bytes(IV_SIZE)
|
||||
self._out_veil = _Veil(self._server_public, iv, b'c2s' if self._initiator else b's2c')
|
||||
self._outbox += iv
|
||||
|
||||
def _write_veiled(self, data: bytes) -> None:
|
||||
assert self._out_veil is not None
|
||||
self._outbox += self._out_veil.apply(data)
|
||||
|
||||
def receive(self, data: bytes) -> list[bytes]:
|
||||
if self.rejected is not None:
|
||||
raise INSRejected(self.rejected)
|
||||
if self._in_veil is None:
|
||||
self._buffer += data
|
||||
if len(self._buffer) < IV_SIZE:
|
||||
return []
|
||||
iv = bytes(self._buffer[:IV_SIZE])
|
||||
rest = bytes(self._buffer[IV_SIZE:])
|
||||
self._buffer.clear()
|
||||
self._in_veil = _Veil(self._server_public, iv, b's2c' if self._initiator else b'c2s')
|
||||
data = rest
|
||||
self._buffer += self._in_veil.apply(data)
|
||||
chunks: list[bytes] = []
|
||||
if self._link_recv is None and not self._link_handshake():
|
||||
return chunks
|
||||
while len(self._buffer) >= RECORD_HEADER.size:
|
||||
(size,) = RECORD_HEADER.unpack_from(self._buffer)
|
||||
if size < TAG_SIZE + 1 or size > MAX_RECORD:
|
||||
raise INSCryptoError('invalid record size {}'.format(size))
|
||||
if len(self._buffer) < RECORD_HEADER.size + size:
|
||||
break
|
||||
header = bytes(self._buffer[:RECORD_HEADER.size])
|
||||
body = bytes(self._buffer[RECORD_HEADER.size:RECORD_HEADER.size + size])
|
||||
del self._buffer[:RECORD_HEADER.size + size]
|
||||
assert self._link_recv is not None
|
||||
try:
|
||||
record = self._link_recv.decrypt(_nonce(self._link_recv_ctr), body, header)
|
||||
except InvalidTag as ex:
|
||||
raise INSCryptoError('link record failed authentication') from ex
|
||||
self._link_recv_ctr += 1
|
||||
chunk = self._on_record(record)
|
||||
if chunk:
|
||||
chunks.append(chunk)
|
||||
return chunks
|
||||
|
||||
def _link_handshake(self) -> bool:
|
||||
expected = (WELCOME_SIZE if self._initiator else HELLO_SIZE)
|
||||
if len(self._buffer) < len(MAGIC):
|
||||
return False
|
||||
if bytes(self._buffer[:len(MAGIC)]) != MAGIC:
|
||||
raise INSCryptoError('unrecognised traffic')
|
||||
if len(self._buffer) < expected:
|
||||
return False
|
||||
message = bytes(self._buffer[:expected])
|
||||
del self._buffer[:expected]
|
||||
if message[4] != TRANSPORT_VERSION:
|
||||
raise INSCryptoError('unsupported transport version {}'.format(message[4]))
|
||||
peer_raw = message[6:38]
|
||||
peer = _x25519(peer_raw)
|
||||
self._peer_ephemeral = peer
|
||||
own_raw = raw_public(self._ephemeral.public_key())
|
||||
client_raw, server_raw = ((own_raw, peer_raw) if self._initiator else (peer_raw, own_raw))
|
||||
self._link_binding = hashlib.sha256(b'INS2 link' + self._server_public + client_raw + server_raw).digest()
|
||||
ee = _exchange(self._ephemeral, peer)
|
||||
if self._initiator:
|
||||
es = _exchange(self._ephemeral, _x25519(self._server_public))
|
||||
else:
|
||||
assert self._host_key is not None
|
||||
es = _exchange(self._host_key, peer)
|
||||
okm = _hkdf(ee + es, self._link_binding, b'INS2 link keys', 64)
|
||||
c2s, s2c = ChaCha20Poly1305(okm[:32]), ChaCha20Poly1305(okm[32:])
|
||||
if self._initiator:
|
||||
self._link_send, self._link_recv = c2s, s2c
|
||||
try:
|
||||
s2c.decrypt(_nonce(0), message[38:], self._link_binding)
|
||||
except InvalidTag as ex:
|
||||
raise INSCryptoError('the server did not prove the host key this client trusts') from ex
|
||||
self._link_recv_ctr = 1
|
||||
self.pq_offer = self.pq_offer and bool(message[5] & FLAG_PQ)
|
||||
self._send_client_kex()
|
||||
else:
|
||||
self._link_send, self._link_recv = s2c, c2s
|
||||
self.pq_offer = self.pq_offer and bool(message[5] & FLAG_PQ)
|
||||
self._start_veil()
|
||||
self._write_veiled(MAGIC + bytes((TRANSPORT_VERSION, FLAG_PQ if self.pq_offer else 0)) + own_raw + s2c.encrypt(_nonce(0), b'', self._link_binding))
|
||||
self._link_send_ctr = 1
|
||||
return True
|
||||
|
||||
def _send_record(self, record: bytes) -> None:
|
||||
assert self._link_send is not None
|
||||
header = RECORD_HEADER.pack(len(record) + TAG_SIZE)
|
||||
self._write_veiled(header + self._link_send.encrypt(_nonce(self._link_send_ctr), record, header))
|
||||
self._link_send_ctr += 1
|
||||
|
||||
def _send_client_kex(self) -> None:
|
||||
assert self._client_key is not None
|
||||
flags = 0
|
||||
body = raw_public(self._client_key.public_key()) + raw_public(self._kex_x25519.public_key()) + self._kex_random + self._machine
|
||||
if self.pq_offer:
|
||||
self._kex_mlkem = MLKEM768PrivateKey.generate()
|
||||
body += self._kex_mlkem.public_key().public_bytes(serialization.Encoding.Raw, serialization.PublicFormat.Raw)
|
||||
flags |= FLAG_PQ
|
||||
enrollment = self._enrollment
|
||||
if enrollment is not None:
|
||||
flags |= FLAG_ENROLL
|
||||
body += (
|
||||
enrollment.code_id + enrollment.secret + enrollment.auth_public
|
||||
+ _pack_string(enrollment.identifier, 64) + _pack_string(enrollment.label, MAX_LABEL)
|
||||
)
|
||||
self._client_body = bytes((flags,)) + body
|
||||
self._send_record(bytes((REC_CLIENT_KEX,)) + self._client_body)
|
||||
|
||||
def _derive_client_key(self, client_body: bytes, server_body: bytes, shared: bytes) -> tuple[bytes, bytes]:
|
||||
self.binding = hashlib.sha256(b'INS2 client' + self._link_binding + client_body + server_body).digest()
|
||||
okm = _hkdf(shared, self.binding, b'INS2 client keys', 64)
|
||||
return okm[:32], okm[32:]
|
||||
|
||||
def _parse_client_kex(self, body: bytes) -> tuple[ClientHello, bytes, bytes, bytes | None]:
|
||||
if len(body) < 1 + 4 * KEY_SIZE:
|
||||
raise INSCryptoError('truncated client KEX')
|
||||
flags = body[0]
|
||||
static_raw = body[1:33]
|
||||
kex_raw = body[33:65]
|
||||
machine = body[97:129]
|
||||
offset = 129
|
||||
mlkem_raw: bytes | None = None
|
||||
if flags & FLAG_PQ:
|
||||
mlkem_raw = body[offset:offset + MLKEM_PUBLIC_SIZE]
|
||||
if len(mlkem_raw) != MLKEM_PUBLIC_SIZE:
|
||||
raise INSCryptoError('truncated ML-KEM key')
|
||||
offset += MLKEM_PUBLIC_SIZE
|
||||
enrollment: EnrollmentRequest | None = None
|
||||
if flags & FLAG_ENROLL:
|
||||
end = offset + CODE_ID_SIZE + CODE_SECRET_SIZE + KEY_SIZE
|
||||
if len(body) < end:
|
||||
raise INSCryptoError('truncated enrollment')
|
||||
code_id = body[offset:offset + CODE_ID_SIZE]
|
||||
secret = body[offset + CODE_ID_SIZE:offset + CODE_ID_SIZE + CODE_SECRET_SIZE]
|
||||
auth_raw = body[end - KEY_SIZE:end]
|
||||
identifier, offset = _short_string(body, end, 64)
|
||||
label, offset = _short_string(body, offset, MAX_LABEL)
|
||||
enrollment = EnrollmentRequest(code_id, secret, auth_raw, identifier, label)
|
||||
if offset != len(body):
|
||||
raise INSCryptoError('unexpected bytes after client KEX')
|
||||
return ClientHello(static_raw, machine, enrollment), static_raw, kex_raw, mlkem_raw
|
||||
|
||||
def reject(self, reason: int) -> None:
|
||||
if self.rejected is None and self._link_send is not None:
|
||||
self._send_record(bytes((REC_REJECT, reason & 0xff)))
|
||||
self.rejected = reason
|
||||
|
||||
def _on_record(self, record: bytes) -> bytes | None:
|
||||
kind = record[0]
|
||||
if kind == REC_DATA and self.established:
|
||||
assert self._client_recv is not None
|
||||
try:
|
||||
inner = self._client_recv.decrypt(_nonce(self._client_recv_ctr), record[1:], b'\x03')
|
||||
except InvalidTag as ex:
|
||||
raise INSCryptoError('client record failed authentication') from ex
|
||||
self._client_recv_ctr += 1
|
||||
(length,) = struct.unpack_from('>H', inner)
|
||||
if length > len(inner) - 2:
|
||||
raise INSCryptoError('invalid data length')
|
||||
return inner[2:2 + length]
|
||||
if kind == REC_CLIENT_KEX and not self._initiator and self._client_send is None:
|
||||
hello, static_raw, kex_raw, mlkem_raw = self._parse_client_kex(record[1:])
|
||||
assert self._resolver is not None
|
||||
try:
|
||||
self.identity = self._resolver(hello)
|
||||
except INSRejected as ex:
|
||||
self.reject(ex.reason)
|
||||
raise
|
||||
self.enrolled = hello.enrollment is not None
|
||||
shared = _exchange(self._kex_x25519, _x25519(kex_raw))
|
||||
shared += _exchange(self._ephemeral, _x25519(static_raw))
|
||||
pq_part = b''
|
||||
used_pq = mlkem_raw is not None and self.pq_offer
|
||||
if used_pq:
|
||||
assert mlkem_raw is not None
|
||||
try:
|
||||
mlkem_pub = MLKEM768PublicKey.from_public_bytes(mlkem_raw)
|
||||
except ValueError as ex:
|
||||
raise INSCryptoError('invalid ML-KEM key') from ex
|
||||
pq_shared, pq_part = mlkem_pub.encapsulate()
|
||||
shared += pq_shared
|
||||
flags = (FLAG_PQ if used_pq else 0) | (FLAG_ENROLL if self.enrolled else 0)
|
||||
server_body = bytes((flags,)) + raw_public(self._kex_x25519.public_key()) + self._kex_random + pq_part
|
||||
client_random = record[66:98]
|
||||
c2s, s2c = self._derive_client_key(record[1:], server_body, shared + client_random + self._kex_random)
|
||||
self._client_send, self._client_recv = AESGCM(s2c), AESGCM(c2s)
|
||||
self._send_record(bytes((REC_SERVER_KEX,)) + server_body + self._client_send.encrypt(_nonce(0), b'', self.binding))
|
||||
self._client_send_ctr = 1
|
||||
self.post_quantum = used_pq
|
||||
self.established = True
|
||||
return None
|
||||
if kind == REC_SERVER_KEX and self._initiator and self._client_recv is None:
|
||||
assert self._client_key is not None and self._peer_ephemeral is not None
|
||||
flags = record[1]
|
||||
used_pq = bool(flags & FLAG_PQ)
|
||||
end = 66 + (MLKEM_CIPHERTEXT_SIZE if used_pq else 0)
|
||||
if len(record) != end + TAG_SIZE:
|
||||
raise INSCryptoError('invalid server KEX')
|
||||
server_body = record[1:end]
|
||||
shared = _exchange(self._kex_x25519, _x25519(record[2:34]))
|
||||
shared += _exchange(self._client_key, self._peer_ephemeral)
|
||||
if used_pq:
|
||||
if self._kex_mlkem is None:
|
||||
raise INSCryptoError('server used ML-KEM that was not offered')
|
||||
try:
|
||||
shared += self._kex_mlkem.decapsulate(record[66:end])
|
||||
except ValueError as ex:
|
||||
raise INSCryptoError('invalid ML-KEM ciphertext') from ex
|
||||
c2s, s2c = self._derive_client_key(self._client_body, server_body, shared + self._kex_random + record[34:66])
|
||||
self._client_send, self._client_recv = AESGCM(c2s), AESGCM(s2c)
|
||||
try:
|
||||
self._client_recv.decrypt(_nonce(0), record[end:], self.binding)
|
||||
except InvalidTag as ex:
|
||||
raise INSCryptoError('server failed client key confirmation') from ex
|
||||
self._client_recv_ctr = 1
|
||||
self.post_quantum = used_pq
|
||||
self.enrolled = bool(flags & FLAG_ENROLL)
|
||||
self.established = True
|
||||
return None
|
||||
if kind == REC_REJECT and self._initiator and len(record) == 2:
|
||||
self.rejected = record[1]
|
||||
raise INSRejected(record[1])
|
||||
raise INSCryptoError('unexpected record type {}'.format(kind))
|
||||
|
||||
def send(self, plaintext: bytes) -> None:
|
||||
if not plaintext:
|
||||
return
|
||||
if not self.established or self._client_send is None:
|
||||
raise INSCryptoError('channel not established')
|
||||
for i in range(0, len(plaintext), MAX_DATA):
|
||||
chunk = plaintext[i:i + MAX_DATA]
|
||||
inner = struct.pack('>H', len(chunk)) + chunk + secrets.token_bytes(secrets.randbelow(MAX_PADDING + 1))
|
||||
self._send_record(bytes((REC_DATA,)) + self._client_send.encrypt(_nonce(self._client_send_ctr), inner, b'\x03'))
|
||||
self._client_send_ctr += 1
|
||||
|
||||
def drain(self) -> bytes:
|
||||
if not self._outbox:
|
||||
return b''
|
||||
data = bytes(self._outbox)
|
||||
self._outbox.clear()
|
||||
return data
|
||||
|
||||
def _challenge_message(purpose: bytes, nonce: bytes, binding: bytes, identifier: str) -> bytes:
|
||||
return purpose + b'\x00' + identifier.encode('utf-8') + b'\x00' + nonce + binding
|
||||
|
||||
def sign_challenge(key: Ed25519PrivateKey, purpose: bytes, nonce: bytes, binding: bytes, identifier: str = '') -> str:
|
||||
return base64.b64encode(key.sign(_challenge_message(purpose, nonce, binding, identifier))).decode('ascii')
|
||||
|
||||
def verify_challenge(key: Ed25519PublicKey, signature: str, purpose: bytes, nonce: bytes, binding: bytes, identifier: str = '') -> bool:
|
||||
try:
|
||||
key.verify(base64.b64decode(signature, validate = True), _challenge_message(purpose, nonce, binding, identifier))
|
||||
except (InvalidSignature, ValueError):
|
||||
return False
|
||||
return True
|
||||
|
||||
def ed25519_public(raw: bytes) -> Ed25519PublicKey:
|
||||
try:
|
||||
return Ed25519PublicKey.from_public_bytes(raw)
|
||||
except ValueError as ex:
|
||||
raise INSCryptoError('invalid Ed25519 key') from ex
|
||||
|
||||
def fingerprint(key: X25519PublicKey | Ed25519PublicKey | bytes) -> str:
|
||||
digest = hashlib.sha256(key if isinstance(key, bytes) else raw_public(key)).hexdigest()
|
||||
return ':'.join(digest[i:i + 4] for i in range(0, 32, 4))
|
||||
|
||||
def b64(data: bytes) -> str:
|
||||
return base64.urlsafe_b64encode(data).decode('ascii').rstrip('=')
|
||||
|
||||
def unb64(text: str) -> bytes:
|
||||
try:
|
||||
return base64.urlsafe_b64decode(text + '=' * (-len(text) % 4))
|
||||
except (ValueError, TypeError) as ex:
|
||||
raise INSCryptoError('invalid base64') from ex
|
||||
|
||||
def make_enrollment_code(server_public: bytes, code_id: bytes, secret: bytes) -> str:
|
||||
body = bytes((1,)) + server_public + code_id + secret
|
||||
return ENROLLMENT_CODE_PREFIX + b64(body + hashlib.sha256(body).digest()[:4])
|
||||
|
||||
def parse_enrollment_code(code: str) -> tuple[bytes, bytes, bytes]:
|
||||
code = ''.join(code.split())
|
||||
if not code.lower().startswith(ENROLLMENT_CODE_PREFIX):
|
||||
raise INSCryptoError('not an INS2 enrollment code')
|
||||
data = unb64(code[len(ENROLLMENT_CODE_PREFIX):])
|
||||
body, check = data[:-4], data[-4:]
|
||||
if len(body) != 1 + KEY_SIZE + CODE_ID_SIZE + CODE_SECRET_SIZE or body[0] != 1 or not hmac.compare_digest(hashlib.sha256(body).digest()[:4], check):
|
||||
raise INSCryptoError('the enrollment code is damaged or incomplete')
|
||||
return body[1:33], body[33:49], body[49:81]
|
||||
|
||||
def _write_new(path: Path, data: bytes, mode: int) -> None:
|
||||
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, mode)
|
||||
with os.fdopen(fd, 'wb') as f:
|
||||
f.write(data)
|
||||
|
||||
def _private_pem(key: X25519PrivateKey) -> bytes:
|
||||
return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8, serialization.NoEncryption())
|
||||
|
||||
def _public_pem(key: X25519PublicKey) -> bytes:
|
||||
return key.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
|
||||
|
||||
@dataclass(frozen = True)
|
||||
class ServerKeys:
|
||||
host: X25519PrivateKey
|
||||
generated: bool
|
||||
|
||||
@property
|
||||
def public_raw(self) -> bytes:
|
||||
return raw_public(self.host.public_key())
|
||||
|
||||
def load_or_generate_server_keys(directory: str | os.PathLike[str]) -> ServerKeys:
|
||||
base = Path(directory)
|
||||
base.mkdir(parents = True, exist_ok = True)
|
||||
key_path = base / HOST_KEY_FILE
|
||||
if key_path.exists():
|
||||
key = serialization.load_pem_private_key(key_path.read_bytes(), password = None)
|
||||
if not isinstance(key, X25519PrivateKey):
|
||||
raise INSCryptoError('{} must be an X25519 private key'.format(key_path))
|
||||
return ServerKeys(key, False)
|
||||
if (base / HOST_PUB_FILE).exists():
|
||||
raise INSCryptoError('{} is missing but {} exists'.format(key_path, base / HOST_PUB_FILE))
|
||||
key = X25519PrivateKey.generate()
|
||||
_write_new(key_path, _private_pem(key), 0o600)
|
||||
_write_new(base / HOST_PUB_FILE, _public_pem(key.public_key()), 0o644)
|
||||
return ServerKeys(key, True)
|
||||
+1648
-624
File diff suppressed because it is too large.
Load diff
@@ -1,44 +1,90 @@
|
||||
from typing import Optional, Callable
|
||||
|
||||
import asyncio
|
||||
import asyncio, ipaddress
|
||||
|
||||
from core.backend import Backend
|
||||
from util.misc import Logger
|
||||
import settings
|
||||
|
||||
from .crypto import load_or_generate_server_keys, fingerprint
|
||||
from .ctrl import INSCtrl
|
||||
from .registry import ClientRegistry
|
||||
|
||||
def register(loop: asyncio.AbstractEventLoop, backend: Backend) -> None:
|
||||
IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network
|
||||
|
||||
def register(loop: asyncio.AbstractEventLoop, backend: Backend) -> ClientRegistry:
|
||||
from util.misc import ProtocolRunner
|
||||
backend.add_runner(ProtocolRunner('0.0.0.0', 4309, ListenerINS, args = ['InterService', backend, INSCtrl], service = 'InterService'))
|
||||
keys = load_or_generate_server_keys(settings.INS_KEY_DIR)
|
||||
if keys.generated:
|
||||
print(f'[InterService] <Info> Generated the InterService host key in {settings.INS_KEY_DIR}')
|
||||
print(f'[InterService] <Info> Host key {fingerprint(keys.host.public_key())}')
|
||||
registry = ClientRegistry(keys.public_raw)
|
||||
active = [record for record in registry.clients() if not record.revoked]
|
||||
if not active:
|
||||
print('[InterService] <Info> No clients are enrolled yet. Make an enrollment code for each one in the admin panel (InterService)')
|
||||
else:
|
||||
print(f'[InterService] <Info> {len(active)} enrolled client(s)')
|
||||
INSCtrl.configure(keys, registry)
|
||||
INSCtrl.attach(backend)
|
||||
allowed = parse_networks(settings.INS_ALLOWED_IPS)
|
||||
backend.add_runner(ProtocolRunner(settings.INS_HOST, settings.INS_PORT, ListenerINS, args = ['InterService', backend, INSCtrl, allowed], service = 'InterService'))
|
||||
return registry
|
||||
|
||||
def parse_networks(entries: list[str]) -> list[IPNetwork]:
|
||||
return [ipaddress.ip_network(str(entry).strip(), strict = False) for entry in entries]
|
||||
|
||||
def is_allowed(host: str, allowed: list[IPNetwork]) -> bool:
|
||||
try:
|
||||
addr = ipaddress.ip_address(host.split('%', 1)[0])
|
||||
except ValueError:
|
||||
return False
|
||||
candidates: list[ipaddress.IPv4Address | ipaddress.IPv6Address] = [addr]
|
||||
if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped is not None:
|
||||
candidates.append(addr.ipv4_mapped)
|
||||
return any(candidate in network for candidate in candidates for network in allowed if candidate.version == network.version)
|
||||
|
||||
class ListenerINS(asyncio.Protocol):
|
||||
logger: Logger
|
||||
backend: Backend
|
||||
controller: INSCtrl
|
||||
transport: Optional[asyncio.WriteTransport]
|
||||
allowed: list[IPNetwork]
|
||||
|
||||
def __init__(self, logger_prefix: str, backend: Backend, controller_factory: Callable[[Logger, str, Backend], INSCtrl]) -> None:
|
||||
def __init__(
|
||||
self, logger_prefix: str, backend: Backend, controller_factory: Callable[[Logger, str, Backend], INSCtrl], allowed: list[IPNetwork],
|
||||
) -> None:
|
||||
super().__init__()
|
||||
self.logger = Logger(logger_prefix, self)
|
||||
self.backend = backend
|
||||
self.controller = controller_factory(self.logger, 'direct', backend)
|
||||
self.controller.close_callback = self._on_close
|
||||
self.transport = None
|
||||
self.allowed = allowed
|
||||
|
||||
def connection_made(self, transport: asyncio.BaseTransport) -> None:
|
||||
assert isinstance(transport, asyncio.WriteTransport)
|
||||
peername = transport.get_extra_info('peername')
|
||||
host = (peername[0] if peername else '')
|
||||
if not is_allowed(host, self.allowed):
|
||||
self.logger.info(f'Refused InterService connection from unauthorized address {host}')
|
||||
self.controller.closed = True
|
||||
transport.abort()
|
||||
return
|
||||
self.transport = transport
|
||||
self.logger.log_connect()
|
||||
self.controller.connection_made(transport)
|
||||
|
||||
def connection_lost(self, exc: Optional[Exception]) -> None:
|
||||
if self.transport is None:
|
||||
return
|
||||
self.controller.close()
|
||||
self.logger.log_disconnect()
|
||||
self.transport = None
|
||||
|
||||
def data_received(self, data: bytes) -> None:
|
||||
transport = self.transport
|
||||
assert transport is not None
|
||||
if transport is None:
|
||||
return
|
||||
if self.backend.maintenance_mode:
|
||||
transport.close()
|
||||
return
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Dict, Optional
|
||||
import asyncio
|
||||
|
||||
from core.backend import Backend
|
||||
from util.misc import Logger
|
||||
import settings
|
||||
|
||||
from .ctrl import INSCtrl, INSFail, JSON_COMMANDS
|
||||
|
||||
class LocalINSError(Exception):
|
||||
code: int
|
||||
detail: Dict[str, Any]
|
||||
|
||||
def __init__(self, code: int, detail: Optional[Dict[str, Any]] = None) -> None:
|
||||
self.code = code
|
||||
self.detail = detail or {}
|
||||
super().__init__('InterService error {:03}{}'.format(code, ': ' + self.message if self.message else ''))
|
||||
|
||||
@property
|
||||
def message(self) -> str:
|
||||
return str(self.detail.get('error') or '')
|
||||
|
||||
class LocalLink(INSCtrl):
|
||||
def __init__(self, backend: Backend, actor: str) -> None:
|
||||
self.logger = Logger('Admin', self)
|
||||
self.backend = backend
|
||||
self.identifier = 'admin'
|
||||
self.authenticated = True
|
||||
self.closed = False
|
||||
self.link_id = 'local'
|
||||
self.client_record = None
|
||||
self.client_info = { 'program': 'admin panel', 'version': settings.VERSION }
|
||||
self.subscriptions = set()
|
||||
self.tasks = set()
|
||||
self.peername = ('127.0.0.1', 0)
|
||||
self.transport = None
|
||||
self.raw_transport = None
|
||||
self.channel = SimpleNamespace(post_quantum = False, binding = b'', enrolled = False)
|
||||
self.privileged = True
|
||||
self.actor = actor
|
||||
self._reply: tuple[str, Any] | None = None
|
||||
|
||||
def send_payload(self, cmd: str, trid: str, obj: Any) -> None:
|
||||
self._reply = (cmd, obj)
|
||||
|
||||
def send_reply(self, *m: str) -> None:
|
||||
self._reply = (m[0] if m else '', list(m[1:]))
|
||||
|
||||
def close(self, reason: Optional[str] = None) -> None:
|
||||
pass
|
||||
|
||||
async def call(self, cmd: str, data: Optional[Dict[str, Any]] = None) -> Any:
|
||||
cmd = cmd.upper()
|
||||
if cmd not in JSON_COMMANDS:
|
||||
raise ValueError('{} is not a JSON command'.format(cmd))
|
||||
handler = getattr(self, '_m_{}'.format(cmd.lower()))
|
||||
self._reply = None
|
||||
self.logger.info(f'{self.actor} ran {cmd}')
|
||||
try:
|
||||
result = handler('1', dict(data or {}))
|
||||
if asyncio.iscoroutine(result):
|
||||
await result
|
||||
except INSFail as ex:
|
||||
raise LocalINSError(ex.code, ex.detail)
|
||||
reply = self._reply
|
||||
if reply is None:
|
||||
return None
|
||||
name, payload = reply
|
||||
if name.isdigit():
|
||||
raise LocalINSError(int(name), payload if isinstance(payload, dict) else None)
|
||||
return payload
|
||||
@@ -0,0 +1,313 @@
|
||||
from collections import deque
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Callable, Deque, Dict, List, Optional, Tuple
|
||||
import hashlib, hmac, ipaddress, secrets, time
|
||||
|
||||
import core.db as db
|
||||
import settings
|
||||
|
||||
from .crypto import (
|
||||
ClientHello, INSRejected, Reject, b64, unb64, ed25519_public, make_enrollment_code, fingerprint, CODE_ID_SIZE, CODE_SECRET_SIZE,
|
||||
)
|
||||
|
||||
MAX_FAILURES = 10
|
||||
FAIL_WINDOW = 600
|
||||
DEFAULT_CODE_HOURS = 24
|
||||
|
||||
IPNetwork = ipaddress.IPv4Network | ipaddress.IPv6Network
|
||||
|
||||
def normalize_address(host: str) -> str:
|
||||
try:
|
||||
addr = ipaddress.ip_address(host.split('%', 1)[0])
|
||||
except ValueError:
|
||||
return host
|
||||
if isinstance(addr, ipaddress.IPv6Address) and addr.ipv4_mapped is not None:
|
||||
addr = addr.ipv4_mapped
|
||||
return str(addr)
|
||||
|
||||
def parse_address_list(entries: List[str]) -> List[str]:
|
||||
result = [] # type: List[str]
|
||||
for entry in entries:
|
||||
entry = entry.strip()
|
||||
if not entry:
|
||||
continue
|
||||
if '/' in entry:
|
||||
value = str(ipaddress.ip_network(entry, strict = False))
|
||||
else:
|
||||
value = normalize_address(str(ipaddress.ip_address(entry)))
|
||||
if value not in result:
|
||||
result.append(value)
|
||||
return result
|
||||
|
||||
def address_allowed(host: str, allowed: List[str]) -> bool:
|
||||
try:
|
||||
addr = ipaddress.ip_address(normalize_address(host))
|
||||
except ValueError:
|
||||
return False
|
||||
for entry in allowed:
|
||||
try:
|
||||
if '/' in entry:
|
||||
if addr in ipaddress.ip_network(entry, strict = False):
|
||||
return True
|
||||
elif addr == ipaddress.ip_address(entry):
|
||||
return True
|
||||
except ValueError:
|
||||
continue
|
||||
return False
|
||||
|
||||
@dataclass
|
||||
class ClientRecord:
|
||||
id: int
|
||||
identifier: str
|
||||
label: str
|
||||
transport_public: bytes
|
||||
auth_public: bytes
|
||||
machine: bytes
|
||||
addresses: List[str]
|
||||
created: datetime
|
||||
last_seen: Optional[datetime]
|
||||
last_address: Optional[str]
|
||||
revoked: bool
|
||||
revoked_at: Optional[datetime]
|
||||
|
||||
@property
|
||||
def fingerprint(self) -> str:
|
||||
return fingerprint(self.transport_public)
|
||||
|
||||
@dataclass
|
||||
class EnrollmentRecord:
|
||||
id: int
|
||||
code_id: str
|
||||
identifier: str
|
||||
label: str
|
||||
address: Optional[str]
|
||||
created_by: Optional[str]
|
||||
created: datetime
|
||||
expires: datetime
|
||||
used: Optional[datetime]
|
||||
client_id: Optional[int]
|
||||
|
||||
@property
|
||||
def state(self) -> str:
|
||||
if self.used is not None:
|
||||
return 'used'
|
||||
if self.expires <= datetime.utcnow():
|
||||
return 'expired'
|
||||
return 'waiting'
|
||||
|
||||
def _client_from_row(row: Any) -> ClientRecord:
|
||||
return ClientRecord(
|
||||
row.id, row.identifier, row.label or '', unb64(row.transport_public), unb64(row.auth_public), bytes.fromhex(row.machine),
|
||||
list(row.addresses or []), row.date_created, row.date_last_seen, row.last_address, bool(row.revoked), row.date_revoked,
|
||||
)
|
||||
|
||||
def _enrollment_from_row(row: Any) -> EnrollmentRecord:
|
||||
return EnrollmentRecord(
|
||||
row.id, row.code_id, row.identifier, row.label or '', row.address, row.created_by, row.date_created, row.date_expires,
|
||||
row.date_used, row.client_id,
|
||||
)
|
||||
|
||||
class ClientRegistry:
|
||||
__slots__ = ('host_public', '_by_key', '_failures', 'on_revoke')
|
||||
|
||||
host_public: bytes
|
||||
_by_key: Dict[bytes, ClientRecord]
|
||||
_failures: Dict[str, Deque[float]]
|
||||
on_revoke: Optional[Callable[[ClientRecord], None]]
|
||||
|
||||
def __init__(self, host_public: bytes) -> None:
|
||||
self.host_public = host_public
|
||||
self._by_key = {}
|
||||
self._failures = {}
|
||||
self.on_revoke = None
|
||||
self.reload()
|
||||
|
||||
def reload(self) -> None:
|
||||
with db.Session() as sess:
|
||||
self._by_key = { record.transport_public: record for record in (_client_from_row(row) for row in sess.query(db.InsClient)) }
|
||||
|
||||
def clients(self) -> List[ClientRecord]:
|
||||
return sorted(self._by_key.values(), key = lambda record: (record.revoked, record.identifier.lower(), record.label.lower(), record.id))
|
||||
|
||||
def get(self, client_id: int) -> Optional[ClientRecord]:
|
||||
for record in self._by_key.values():
|
||||
if record.id == client_id:
|
||||
return record
|
||||
return None
|
||||
|
||||
def _fail(self, address: str, reason: int, logger: Any, detail: str) -> INSRejected:
|
||||
now = time.monotonic()
|
||||
failures = self._failures.setdefault(address, deque())
|
||||
failures.append(now)
|
||||
while failures and now - failures[0] > FAIL_WINDOW:
|
||||
failures.popleft()
|
||||
if logger is not None:
|
||||
logger.info(f'InterService client from {address} turned away: {detail}')
|
||||
return INSRejected(reason)
|
||||
|
||||
def _throttled(self, address: str) -> bool:
|
||||
failures = self._failures.get(address)
|
||||
if not failures:
|
||||
return False
|
||||
now = time.monotonic()
|
||||
while failures and now - failures[0] > FAIL_WINDOW:
|
||||
failures.popleft()
|
||||
return len(failures) >= MAX_FAILURES
|
||||
|
||||
def resolve(self, hello: ClientHello, peer: str, logger: Any = None) -> ClientRecord:
|
||||
address = normalize_address(peer)
|
||||
if self._throttled(address):
|
||||
raise INSRejected(Reject.TooManyAttempts)
|
||||
if hello.enrollment is not None:
|
||||
return self._enroll(hello, address, logger)
|
||||
record = self._by_key.get(hello.transport_public)
|
||||
if record is None:
|
||||
raise self._fail(address, Reject.UnknownKey, logger, 'unknown client key')
|
||||
if record.revoked:
|
||||
raise self._fail(address, Reject.Revoked, logger, f'revoked key of {record.identifier} "{record.label}"')
|
||||
if not address_allowed(address, record.addresses):
|
||||
raise self._fail(address, Reject.WrongAddress, logger, f'key of {record.identifier} "{record.label}" used from an address it is not bound to')
|
||||
if not hmac.compare_digest(record.machine, hello.machine):
|
||||
raise self._fail(address, Reject.WrongMachine, logger, f'key of {record.identifier} "{record.label}" used from a different machine or OS install')
|
||||
return record
|
||||
|
||||
def _enroll(self, hello: ClientHello, address: str, logger: Any) -> ClientRecord:
|
||||
enrollment = hello.enrollment
|
||||
assert enrollment is not None
|
||||
now = datetime.utcnow()
|
||||
if enrollment.identifier not in settings.INS_IDENTIFIERS:
|
||||
raise self._fail(address, Reject.WrongIdentifier, logger, f'enrollment for unknown identifier "{enrollment.identifier}"')
|
||||
if hello.transport_public in self._by_key:
|
||||
raise self._fail(address, Reject.BadEnrollment, logger, 'enrollment with a key that is already enrolled')
|
||||
try:
|
||||
ed25519_public(enrollment.auth_public)
|
||||
except Exception:
|
||||
raise self._fail(address, Reject.BadEnrollment, logger, 'enrollment with an invalid auth key')
|
||||
with db.Session() as sess:
|
||||
row = sess.query(db.InsEnrollment).filter(db.InsEnrollment.code_id == enrollment.code_id.hex()).one_or_none()
|
||||
secret_hash = hashlib.sha256(enrollment.secret).hexdigest()
|
||||
if row is None or not hmac.compare_digest(row.secret_hash, secret_hash):
|
||||
raise self._fail(address, Reject.BadEnrollment, logger, 'unknown enrollment code')
|
||||
if row.date_used is not None:
|
||||
raise self._fail(address, Reject.BadEnrollment, logger, f'enrollment code for {row.identifier} used again')
|
||||
if row.date_expires <= now:
|
||||
raise self._fail(address, Reject.BadEnrollment, logger, f'expired enrollment code for {row.identifier}')
|
||||
if row.identifier != enrollment.identifier:
|
||||
raise self._fail(address, Reject.WrongIdentifier, logger, f'enrollment code for {row.identifier} used for {enrollment.identifier}')
|
||||
if row.address and not address_allowed(address, [row.address]):
|
||||
raise self._fail(address, Reject.WrongAddress, logger, f'enrollment code for {row.identifier} used from an address it was not made for')
|
||||
label = (enrollment.label or row.label or enrollment.identifier)[:100]
|
||||
client_row = db.InsClient(
|
||||
identifier = enrollment.identifier, label = label, transport_public = b64(hello.transport_public),
|
||||
auth_public = b64(enrollment.auth_public), machine = hello.machine.hex(), addresses = [address],
|
||||
date_created = now, revoked = False,
|
||||
)
|
||||
sess.add(client_row)
|
||||
sess.flush()
|
||||
row.date_used = now
|
||||
row.client_id = client_row.id
|
||||
record = _client_from_row(client_row)
|
||||
replaced = [
|
||||
other for other in self._by_key.values()
|
||||
if not other.revoked and other.identifier == record.identifier and hmac.compare_digest(other.machine, record.machine)
|
||||
]
|
||||
for other in replaced:
|
||||
other_row = sess.query(db.InsClient).filter(db.InsClient.id == other.id).one_or_none()
|
||||
if other_row is not None:
|
||||
other_row.revoked = True
|
||||
other_row.date_revoked = now
|
||||
self._by_key[record.transport_public] = record
|
||||
for other in replaced:
|
||||
other.revoked = True
|
||||
other.revoked_at = now
|
||||
if self.on_revoke is not None:
|
||||
self.on_revoke(other)
|
||||
if logger is not None:
|
||||
logger.info(f'InterService client {record.identifier} "{record.label}" enrolled from {address} (key {record.fingerprint})')
|
||||
return record
|
||||
|
||||
def seen(self, record: ClientRecord, peer: str) -> None:
|
||||
now = datetime.utcnow()
|
||||
address = normalize_address(peer)
|
||||
record.last_seen = now
|
||||
record.last_address = address
|
||||
with db.Session() as sess:
|
||||
row = sess.query(db.InsClient).filter(db.InsClient.id == record.id).one_or_none()
|
||||
if row is not None:
|
||||
row.date_last_seen = now
|
||||
row.last_address = address
|
||||
|
||||
def create_code(
|
||||
self, identifier: str, *, label: str = '', address: Optional[str] = None, hours: int = DEFAULT_CODE_HOURS,
|
||||
created_by: Optional[str] = None,
|
||||
) -> Tuple[str, EnrollmentRecord]:
|
||||
if identifier not in settings.INS_IDENTIFIERS:
|
||||
raise ValueError('unknown identifier')
|
||||
if address:
|
||||
address = parse_address_list([address])[0]
|
||||
code_id = secrets.token_bytes(CODE_ID_SIZE)
|
||||
secret = secrets.token_bytes(CODE_SECRET_SIZE)
|
||||
now = datetime.utcnow()
|
||||
with db.Session() as sess:
|
||||
row = db.InsEnrollment(
|
||||
code_id = code_id.hex(), secret_hash = hashlib.sha256(secret).hexdigest(), identifier = identifier, label = label[:100],
|
||||
address = address or None, created_by = created_by, date_created = now,
|
||||
date_expires = now + timedelta(hours = max(1, min(hours, 24 * 30))),
|
||||
)
|
||||
sess.add(row)
|
||||
sess.flush()
|
||||
record = _enrollment_from_row(row)
|
||||
return make_enrollment_code(self.host_public, code_id, secret), record
|
||||
|
||||
def codes(self) -> List[EnrollmentRecord]:
|
||||
with db.Session() as sess:
|
||||
rows = sess.query(db.InsEnrollment).order_by(db.InsEnrollment.date_created.desc()).limit(200).all()
|
||||
return [_enrollment_from_row(row) for row in rows]
|
||||
|
||||
def cancel_code(self, enrollment_id: int) -> bool:
|
||||
with db.Session() as sess:
|
||||
row = sess.query(db.InsEnrollment).filter(db.InsEnrollment.id == enrollment_id).one_or_none()
|
||||
if row is None or row.date_used is not None:
|
||||
return False
|
||||
sess.delete(row)
|
||||
return True
|
||||
|
||||
def revoke(self, client_id: int) -> Optional[ClientRecord]:
|
||||
record = self.get(client_id)
|
||||
if record is None or record.revoked:
|
||||
return record
|
||||
now = datetime.utcnow()
|
||||
with db.Session() as sess:
|
||||
row = sess.query(db.InsClient).filter(db.InsClient.id == client_id).one_or_none()
|
||||
if row is not None:
|
||||
row.revoked = True
|
||||
row.date_revoked = now
|
||||
record.revoked = True
|
||||
record.revoked_at = now
|
||||
if self.on_revoke is not None:
|
||||
self.on_revoke(record)
|
||||
return record
|
||||
|
||||
def delete(self, client_id: int) -> bool:
|
||||
record = self.get(client_id)
|
||||
if record is None or not record.revoked:
|
||||
return False
|
||||
with db.Session() as sess:
|
||||
sess.query(db.InsClient).filter(db.InsClient.id == client_id).delete(synchronize_session = False)
|
||||
self._by_key.pop(record.transport_public, None)
|
||||
return True
|
||||
|
||||
def set_addresses(self, client_id: int, addresses: List[str]) -> ClientRecord:
|
||||
record = self.get(client_id)
|
||||
if record is None:
|
||||
raise KeyError(client_id)
|
||||
parsed = parse_address_list(addresses)
|
||||
if not parsed:
|
||||
raise ValueError('at least one address is needed')
|
||||
with db.Session() as sess:
|
||||
row = sess.query(db.InsClient).filter(db.InsClient.id == client_id).one_or_none()
|
||||
if row is not None:
|
||||
row.addresses = parsed
|
||||
record.addresses = parsed
|
||||
return record
|
||||
@@ -144,11 +144,36 @@ class Contact:
|
||||
if found_group is not None:
|
||||
self._groups.discard(group)
|
||||
|
||||
AIM_PD_KEY = 'AIM_PD'
|
||||
AIM_SSI_KEY = 'AIM_SSI'
|
||||
AIM_CLASS_FREE = 0x0010
|
||||
|
||||
def _aim_pd_mode(user: User) -> Optional[Dict[str, Any]]:
|
||||
pd = user.settings.get(AIM_PD_KEY)
|
||||
if not isinstance(pd, dict) or pd.get('mode') not in (1, 2, 3, 4, 5):
|
||||
return None
|
||||
if user.settings.get('BLP', 'AL') != pd.get('blp'):
|
||||
return None
|
||||
return pd
|
||||
|
||||
def _is_blocking(blocker: User, blockee: User) -> bool:
|
||||
detail = blocker.detail
|
||||
assert detail is not None
|
||||
contact = detail.contacts.get(blockee.uuid)
|
||||
lists = (contact and contact.lists or 0)
|
||||
pd = _aim_pd_mode(blocker)
|
||||
if pd is not None:
|
||||
mask = pd.get('mask')
|
||||
if mask is not None and not (int(mask) & AIM_CLASS_FREE): return True
|
||||
mode = pd['mode']
|
||||
if mode == 1: return False
|
||||
if mode == 2: return True
|
||||
if mode == 4: return bool(lists & ContactList.BL)
|
||||
if mode == 5: return not (lists & ContactList.FL)
|
||||
# mode 3: only explicit permits (AL without FL, or AL entries the client listed itself) get through
|
||||
name = blockee.username.lower()
|
||||
permits = (blocker.settings.get(AIM_SSI_KEY) or {}).get('permits', [])
|
||||
return not (lists & ContactList.AL and (not lists & ContactList.FL or name in permits))
|
||||
if lists & ContactList.BL: return True
|
||||
if lists & ContactList.AL: return False
|
||||
return (blocker.settings.get('BLP', 'AL') == 'BL')
|
||||
@@ -399,6 +424,35 @@ class TextWithData:
|
||||
self.text = text
|
||||
self.yahoo_utf8 = yahoo_utf8
|
||||
|
||||
class ActivityType(IntEnum):
|
||||
StatusMessage = 1
|
||||
Photo = 2
|
||||
DisplayPicture = 3
|
||||
Announcement = 20
|
||||
|
||||
class Activity:
|
||||
__slots__ = ('id', 'user', 'type', 'title', 'text', 'url', 'date_created')
|
||||
|
||||
id: int
|
||||
user: Optional[User]
|
||||
type: ActivityType
|
||||
title: Optional[str]
|
||||
text: Optional[str]
|
||||
url: Optional[str]
|
||||
date_created: datetime
|
||||
|
||||
def __init__(
|
||||
self, id: int, user: Optional[User], type: ActivityType, title: Optional[str], text: Optional[str], url: Optional[str], date_created: datetime,
|
||||
) -> None:
|
||||
self.id = id
|
||||
# `None` for service announcements
|
||||
self.user = user
|
||||
self.type = type
|
||||
self.title = title
|
||||
self.text = text
|
||||
self.url = url
|
||||
self.date_created = date_created
|
||||
|
||||
class RoamingInfo:
|
||||
__slots__ = ('name', 'name_last_modified', 'message', 'message_last_modified')
|
||||
|
||||
|
||||
+293
-8
@@ -1,5 +1,6 @@
|
||||
from typing import Dict, Any, Optional
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any, Optional, List, Iterable, Tuple
|
||||
from datetime import datetime, timedelta
|
||||
import base64, time
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.orm import declarative_base
|
||||
from HLL import HyperLogLog
|
||||
@@ -9,19 +10,43 @@ from core.client import Client
|
||||
from core.models import User
|
||||
from util.json_type import JSONType
|
||||
|
||||
HOURS_KEPT = 48
|
||||
DAYS_KEPT = 35
|
||||
|
||||
class Stats:
|
||||
__slots__ = ('logged_in', 'by_client', '_conn', '_client_id_cache')
|
||||
__slots__ = (
|
||||
'logged_in', 'by_client', '_conn', '_client_id_cache', 'started', '_day', '_day_stats', '_pending_days', '_past_days',
|
||||
'_hours', '_peak_record', '_collect_hour',
|
||||
)
|
||||
|
||||
logged_in: int
|
||||
by_client: Dict[int, Dict[str, Any]]
|
||||
_conn: Conn
|
||||
_client_id_cache: Optional[Dict[Client, int]]
|
||||
started: datetime
|
||||
_day: int
|
||||
_day_stats: Dict[str, Any]
|
||||
_pending_days: Dict[int, Dict[str, Any]]
|
||||
_past_days: Dict[int, bytes]
|
||||
_hours: Dict[int, Dict[str, Any]]
|
||||
_peak_record: Dict[str, Any]
|
||||
_collect_hour: int
|
||||
|
||||
def __init__(self, conn: Conn) -> None:
|
||||
self.logged_in = 0
|
||||
self.by_client = {}
|
||||
self._conn = conn
|
||||
self._client_id_cache = None
|
||||
self.started = datetime.utcnow()
|
||||
self._day = _current_day()
|
||||
self._day_stats = _new_day_stats()
|
||||
self._pending_days = {}
|
||||
self._past_days = {}
|
||||
self._hours = {}
|
||||
self._peak_record = { 'value': 0, 'at': None }
|
||||
self._collect_hour = _current_hour()
|
||||
|
||||
self._load_rollups()
|
||||
|
||||
hour = _current_hour()
|
||||
with self._conn.session() as sess:
|
||||
@@ -35,12 +60,44 @@ class Stats:
|
||||
for client_id, stats in current.value['by_client'].items()
|
||||
}
|
||||
|
||||
def _load_rollups(self) -> None:
|
||||
with self._conn.session() as sess:
|
||||
for row in sess.query(CurrentStats).filter(CurrentStats.key.in_(['hours', 'peak_record'])):
|
||||
if row.key == 'hours' and isinstance(row.value, dict):
|
||||
self._hours = { int(hour): dict(entry) for hour, entry in row.value.items() }
|
||||
elif row.key == 'peak_record' and isinstance(row.value, dict):
|
||||
self._peak_record = { 'value': int(row.value.get('value') or 0), 'at': row.value.get('at') }
|
||||
oldest = _day_key(self._day - DAYS_KEPT)
|
||||
for row in sess.query(CurrentStats).filter(CurrentStats.key.like('day:%'), CurrentStats.key >= oldest):
|
||||
try:
|
||||
day = int(row.key[4:])
|
||||
except ValueError:
|
||||
continue
|
||||
if day == self._day:
|
||||
self._day_stats = _day_from_json(row.value)
|
||||
elif row.value.get('users_active'):
|
||||
self._past_days[day] = base64.b64decode(row.value['users_active'])
|
||||
|
||||
def on_login(self) -> None:
|
||||
self._roll_day()
|
||||
self.logged_in += 1
|
||||
self._day_stats['logins'] += 1
|
||||
|
||||
def on_logout(self) -> None:
|
||||
self.logged_in -= 1
|
||||
|
||||
def on_online(self, online: int) -> None:
|
||||
self._roll_day()
|
||||
now = _iso(datetime.utcnow())
|
||||
if online > self._day_stats['peak']:
|
||||
self._day_stats['peak'] = online
|
||||
self._day_stats['peak_at'] = now
|
||||
hour_entry = self._hour_entry(_current_hour())
|
||||
if online > hour_entry['peak']:
|
||||
hour_entry['peak'] = online
|
||||
if online > self._peak_record['value']:
|
||||
self._peak_record = { 'value': online, 'at': now }
|
||||
|
||||
def on_user_active(self, user: User, client: Client) -> None:
|
||||
self._collect('users_active', user, client)
|
||||
|
||||
@@ -68,17 +125,42 @@ class Stats:
|
||||
if stat not in bhc:
|
||||
bhc[stat] = 0
|
||||
bhc[stat] += 1
|
||||
|
||||
self._roll_day()
|
||||
if stat == 'users_active':
|
||||
self._day_stats['users_active'].add(user.email)
|
||||
else:
|
||||
self._day_stats[stat] += 1
|
||||
|
||||
def flush(self) -> None:
|
||||
def _roll_day(self) -> None:
|
||||
day = _current_day()
|
||||
if day == self._day:
|
||||
return
|
||||
self._pending_days[self._day] = self._day_stats
|
||||
self._past_days[self._day] = bytes(self._day_stats['users_active'].registers())
|
||||
for old in [d for d in self._past_days if d < day - DAYS_KEPT]:
|
||||
del self._past_days[old]
|
||||
self._day = day
|
||||
self._day_stats = _new_day_stats()
|
||||
|
||||
def _hour_entry(self, hour: int) -> Dict[str, Any]:
|
||||
if hour not in self._hours:
|
||||
self._hours[hour] = { 'users_active': 0, 'messages_sent': 0, 'messages_received': 0, 'peak': 0 }
|
||||
return self._hours[hour]
|
||||
|
||||
def flush(self, online: Optional[int] = None) -> None:
|
||||
hour = _current_hour()
|
||||
now = datetime.utcnow()
|
||||
if online is not None:
|
||||
self.on_online(online)
|
||||
self._roll_day()
|
||||
|
||||
with self._conn.session() as sess:
|
||||
current = sess.query(CurrentStats).filter(CurrentStats.key == 'logged_in').one_or_none()
|
||||
if not current:
|
||||
current = CurrentStats(key = 'logged_in')
|
||||
current.date_updated = now
|
||||
current.value = self.logged_in
|
||||
current.value = (online if online is not None else self.logged_in)
|
||||
sess.add(current)
|
||||
sess.flush()
|
||||
|
||||
@@ -88,11 +170,37 @@ class Stats:
|
||||
|
||||
cs_hour = current.value['hour']
|
||||
current.date_updated = now
|
||||
current.value = self._flush_to_hourly(sess, hour)
|
||||
sess.add(current)
|
||||
current.value = self._flush_to_hourly(sess, cs_hour)
|
||||
self._update_hour_totals(cs_hour)
|
||||
|
||||
if cs_hour != hour:
|
||||
self.by_client = {}
|
||||
current.value = { 'hour': hour, 'by_client': {} }
|
||||
self._collect_hour = hour
|
||||
sess.add(current)
|
||||
|
||||
self._flush_rollups(sess, now)
|
||||
|
||||
def _update_hour_totals(self, hour: int) -> None:
|
||||
entry = self._hour_entry(hour)
|
||||
entry['users_active'] = _hll_union(
|
||||
bytes(stats['users_active'].registers()) for stats in self.by_client.values() if 'users_active' in stats
|
||||
)
|
||||
entry['messages_sent'] = sum(int(stats.get('messages_sent') or 0) for stats in self.by_client.values())
|
||||
entry['messages_received'] = sum(int(stats.get('messages_received') or 0) for stats in self.by_client.values())
|
||||
|
||||
def _flush_rollups(self, sess: Any, now: datetime) -> None:
|
||||
hour = _current_hour()
|
||||
for old in [h for h in self._hours if h <= hour - HOURS_KEPT]:
|
||||
del self._hours[old]
|
||||
_put(sess, 'hours', { str(h): entry for h, entry in self._hours.items() }, now)
|
||||
_put(sess, 'peak_record', self._peak_record, now)
|
||||
for day, stats in list(self._pending_days.items()) + [(self._day, self._day_stats)]:
|
||||
_put(sess, _day_key(day), _day_to_json(stats), now)
|
||||
self._pending_days.clear()
|
||||
sess.query(CurrentStats).filter(
|
||||
CurrentStats.key.like('day:%'), CurrentStats.key < _day_key(self._day - DAYS_KEPT),
|
||||
).delete(synchronize_session = False)
|
||||
|
||||
def _flush_to_hourly(self, sess: Any, hour: int) -> Dict[str, Any]:
|
||||
for client_id, stats in self.by_client.items():
|
||||
@@ -116,6 +224,76 @@ class Stats:
|
||||
}
|
||||
}
|
||||
|
||||
def snapshot(self) -> Dict[str, Any]:
|
||||
self._roll_day()
|
||||
hour = _current_hour()
|
||||
self._update_hour_totals(self._collect_hour)
|
||||
today_registers = bytes(self._day_stats['users_active'].registers())
|
||||
|
||||
def active_since(days: int) -> int:
|
||||
return _hll_union([today_registers] + [regs for day, regs in self._past_days.items() if day > self._day - days])
|
||||
|
||||
current = self._hour_entry(hour)
|
||||
hourly = []
|
||||
for h in range(hour - 23, hour + 1):
|
||||
entry = self._hours.get(h) or {}
|
||||
hourly.append({
|
||||
'hour': _iso(datetime.utcfromtimestamp(h * 3600)),
|
||||
'users_active': int(entry.get('users_active') or 0), 'messages_sent': int(entry.get('messages_sent') or 0),
|
||||
'messages_received': int(entry.get('messages_received') or 0), 'peak': int(entry.get('peak') or 0),
|
||||
})
|
||||
return {
|
||||
'active': {
|
||||
'hour': int(current['users_active']),
|
||||
'today': _hll_union([today_registers]),
|
||||
'week': active_since(7),
|
||||
'month': active_since(30),
|
||||
},
|
||||
'messages': {
|
||||
'hour': { 'sent': int(current['messages_sent']), 'received': int(current['messages_received']) },
|
||||
'today': { 'sent': int(self._day_stats['messages_sent']), 'received': int(self._day_stats['messages_received']) },
|
||||
},
|
||||
'logins_today': int(self._day_stats['logins']),
|
||||
'peak_today': { 'value': int(self._day_stats['peak']), 'at': self._day_stats['peak_at'] },
|
||||
'peak_record': dict(self._peak_record),
|
||||
'hourly': hourly,
|
||||
'by_client_hourly': self._by_client_hourly(hour - 23),
|
||||
'started': _iso(self.started),
|
||||
'uptime': int((datetime.utcnow() - self.started).total_seconds()),
|
||||
}
|
||||
|
||||
def _by_client_hourly(self, since_hour: int) -> List[Dict[str, Any]]:
|
||||
clients = { client_id: Client.ToJSON(client) for client, client_id in (self._client_id_cache or {}).items() }
|
||||
by_hour: dict[int, dict[int, dict[str, int]]] = {}
|
||||
with self._conn.session() as sess:
|
||||
if len(clients) < sess.query(sa.func.count(DBClient.id)).scalar():
|
||||
clients = { row.id: row.data for row in sess.query(DBClient).all() }
|
||||
for hcs in sess.query(HourlyClientStats).filter(HourlyClientStats.hour >= since_hour):
|
||||
by_hour.setdefault(int(hcs.hour), {})[int(hcs.client_id)] = {
|
||||
'users_active': int(hcs.users_active), 'messages_sent': int(hcs.messages_sent), 'messages_received': int(hcs.messages_received),
|
||||
}
|
||||
for client_id, stats in self.by_client.items():
|
||||
by_hour.setdefault(self._collect_hour, {})[client_id] = {
|
||||
'users_active': int(stats['users_active'].cardinality()) if 'users_active' in stats else 0,
|
||||
'messages_sent': int(stats.get('messages_sent') or 0), 'messages_received': int(stats.get('messages_received') or 0),
|
||||
}
|
||||
return [
|
||||
{
|
||||
'hour': _iso(datetime.utcfromtimestamp(h * 3600)),
|
||||
'clients': sorted(
|
||||
({ 'client': clients.get(client_id), **values } for client_id, values in by_hour[h].items()),
|
||||
key = lambda entry: -entry['users_active'],
|
||||
),
|
||||
}
|
||||
for h in sorted(by_hour, reverse = True)
|
||||
]
|
||||
|
||||
def snapshot_started(self) -> str:
|
||||
return _iso(self.started)
|
||||
|
||||
def uptime(self) -> int:
|
||||
return int((datetime.utcnow() - self.started).total_seconds())
|
||||
|
||||
def _get_client_id(self, client: Client) -> int:
|
||||
if self._client_id_cache is None:
|
||||
with self._conn.session() as sess:
|
||||
@@ -131,6 +309,110 @@ class Stats:
|
||||
self._client_id_cache[client] = dbobj.id
|
||||
return self._client_id_cache[client]
|
||||
|
||||
def collect_snapshot(backend: Any) -> Dict[str, Any]:
|
||||
sessions = list(backend._sc.iter_sessions())
|
||||
users: set[str] = set()
|
||||
visible: set[str] = set()
|
||||
by_program: dict[str, int] = {}
|
||||
by_client: dict[Client, int] = {}
|
||||
for bs in sessions:
|
||||
users.add(bs.user.uuid)
|
||||
if not bs.user.status.substatus.is_offlineish():
|
||||
visible.add(bs.user.uuid)
|
||||
by_program[bs.client.program] = by_program.get(bs.client.program, 0) + 1
|
||||
by_client[bs.client] = by_client.get(bs.client, 0) + 1
|
||||
snapshot = backend._stats.snapshot()
|
||||
snapshot['online'] = {
|
||||
'sessions': len(sessions),
|
||||
'users': len(users),
|
||||
'visible_users': len(visible),
|
||||
'by_program': [{ 'program': program, 'sessions': count } for program, count in sorted(by_program.items(), key = lambda item: -item[1])],
|
||||
'by_client': [
|
||||
{ **Client.ToJSON(client), 'sessions': count }
|
||||
for client, count in sorted(by_client.items(), key = lambda item: -item[1])[:20]
|
||||
],
|
||||
}
|
||||
snapshot.update(_db_counts())
|
||||
snapshot['generated'] = _iso(datetime.utcnow())
|
||||
return snapshot
|
||||
|
||||
_counts_cache: tuple[float, dict[str, Any]] = (0.0, {})
|
||||
|
||||
def _db_counts() -> Dict[str, Any]:
|
||||
global _counts_cache
|
||||
if time.monotonic() - _counts_cache[0] < 60:
|
||||
return _counts_cache[1]
|
||||
import core.db as db
|
||||
now = datetime.utcnow()
|
||||
day_ago = now - timedelta(days = 1)
|
||||
week_ago = now - timedelta(days = 7)
|
||||
count = sa.func.count
|
||||
with db.Session() as sess:
|
||||
counts = {
|
||||
'accounts': {
|
||||
'total': sess.query(count(db.User.id)).scalar() or 0,
|
||||
'new_today': sess.query(count(db.User.id)).filter(db.User.date_created >= day_ago).scalar() or 0,
|
||||
'new_week': sess.query(count(db.User.id)).filter(db.User.date_created >= week_ago).scalar() or 0,
|
||||
'verified': sess.query(count(db.User.id)).filter(db.User.account_verified == True).scalar() or 0,
|
||||
'in_directory': sess.query(count(db.User.id)).filter(db.User.show_in_dir == True).scalar() or 0,
|
||||
},
|
||||
'circles': sess.query(count(db.Circle.id)).scalar() or 0,
|
||||
'beacon': {
|
||||
'posts_today': sess.query(count(db.Activity.id)).filter(db.Activity.user_uuid.isnot(None), db.Activity.date_created >= day_ago).scalar() or 0,
|
||||
'reactions_today': sess.query(count(db.ActivityReaction.id)).filter(db.ActivityReaction.date_created >= day_ago).scalar() or 0,
|
||||
'comments_today': sess.query(count(db.ActivityComment.id)).filter(db.ActivityComment.date_created >= day_ago).scalar() or 0,
|
||||
},
|
||||
} # type: Dict[str, Any]
|
||||
_counts_cache = (time.monotonic(), counts)
|
||||
return counts
|
||||
|
||||
def _hll_union(register_sets: Iterable[bytes]) -> int:
|
||||
merged: bytearray | None = None
|
||||
for registers in register_sets:
|
||||
if merged is None:
|
||||
merged = bytearray(registers)
|
||||
else:
|
||||
merged = bytearray(map(max, merged, registers))
|
||||
if merged is None:
|
||||
return 0
|
||||
hll = HyperLogLog(12)
|
||||
hll.set_registers(merged)
|
||||
return int(round(hll.cardinality()))
|
||||
|
||||
def _new_day_stats() -> Dict[str, Any]:
|
||||
return { 'users_active': HyperLogLog(12), 'messages_sent': 0, 'messages_received': 0, 'logins': 0, 'peak': 0, 'peak_at': None }
|
||||
|
||||
def _day_to_json(stats: Dict[str, Any]) -> Dict[str, Any]:
|
||||
return {
|
||||
'users_active': base64.b64encode(bytes(stats['users_active'].registers())).decode('ascii'),
|
||||
'users_active_count': int(round(stats['users_active'].cardinality())),
|
||||
'messages_sent': stats['messages_sent'], 'messages_received': stats['messages_received'], 'logins': stats['logins'],
|
||||
'peak': stats['peak'], 'peak_at': stats['peak_at'],
|
||||
}
|
||||
|
||||
def _day_from_json(json: Dict[str, Any]) -> Dict[str, Any]:
|
||||
stats = _new_day_stats()
|
||||
if json.get('users_active'):
|
||||
stats['users_active'].set_registers(bytearray(base64.b64decode(json['users_active'])))
|
||||
for key in ('messages_sent', 'messages_received', 'logins', 'peak'):
|
||||
stats[key] = int(json.get(key) or 0)
|
||||
stats['peak_at'] = json.get('peak_at')
|
||||
return stats
|
||||
|
||||
def _put(sess: Any, key: str, value: Any, now: datetime) -> None:
|
||||
row = sess.query(CurrentStats).filter(CurrentStats.key == key).one_or_none()
|
||||
if row is None:
|
||||
row = CurrentStats(key = key)
|
||||
row.value = value
|
||||
row.date_updated = now
|
||||
sess.add(row)
|
||||
|
||||
def _day_key(day: int) -> str:
|
||||
return 'day:{:06d}'.format(day)
|
||||
|
||||
def _iso(dt: datetime) -> str:
|
||||
return dt.replace(microsecond = 0).isoformat() + 'Z'
|
||||
|
||||
def _stats_to_json(stats: Dict[str, Any]) -> Dict[str, Any]:
|
||||
json = {}
|
||||
if 'messages_sent' in stats:
|
||||
@@ -158,6 +440,9 @@ def _current_hour() -> int:
|
||||
ts = now.timestamp()
|
||||
return int(ts // 3600)
|
||||
|
||||
def _current_day() -> int:
|
||||
return _current_hour() // 24
|
||||
|
||||
class Base(declarative_base()): # type: ignore
|
||||
__abstract__ = True
|
||||
|
||||
@@ -185,4 +470,4 @@ class CurrentStats(Base):
|
||||
|
||||
key = sa.Column(sa.String(255), nullable = False, primary_key = True)
|
||||
date_updated = sa.Column(sa.DateTime, nullable = False, server_default = sa.text('CURRENT_TIMESTAMP'))
|
||||
value = sa.Column(JSONType, nullable = False, default = {})
|
||||
value = sa.Column(JSONType, nullable = False, default = {})
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
from typing import Dict, Tuple, Any, Optional
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import ssl, settings
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.backends import default_backend
|
||||
@@ -48,7 +48,7 @@ class TLSContext:
|
||||
p_key = self.cert_dir / '{}'.format(self.cert_root)
|
||||
|
||||
if not exists_and_valid(p_crt, p_key):
|
||||
raise ssl.CertificateError()
|
||||
if not settings.DEBUG: raise ssl.CertificateError()
|
||||
|
||||
return p_crt, p_key
|
||||
|
||||
|
||||
+265
-16
@@ -1,8 +1,8 @@
|
||||
from typing import Dict, Optional, List, Tuple, Any, TYPE_CHECKING
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
from dateutil import parser as iso_parser
|
||||
from pathlib import Path
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.orm import joinedload
|
||||
import json, traceback
|
||||
|
||||
@@ -13,11 +13,12 @@ from util.avatar import store_avatar_file, get_img_type
|
||||
from .conn import Conn
|
||||
from .db import (
|
||||
User as DBUser, UserContact as DBUserContact, Circle as DBCircle,
|
||||
CircleMembership as DBCircleMembership, UserProfile as DBUserProfile
|
||||
CircleMembership as DBCircleMembership, UserProfile as DBUserProfile, Activity as DBActivity,
|
||||
ActivityReaction as DBActivityReaction, ActivityComment as DBActivityComment
|
||||
)
|
||||
from .models import (
|
||||
User, Contact, ContactDetail, ContactLocation, ContactGroupEntry, UserStatus, UserDetail, Circle,
|
||||
CircleMembership, CircleRole, CircleState, Group, RoamingInfo, OIM, UserProfile
|
||||
CircleMembership, CircleRole, CircleState, Group, RoamingInfo, OIM, UserProfile, Activity, ActivityType
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
@@ -43,11 +44,6 @@ class UserService:
|
||||
status = hasher.verify(pwd, dbuser.password)
|
||||
if status is True:
|
||||
return dbuser.uuid
|
||||
elif status == 'MIGRATEMEPLSTHX':
|
||||
new_hash = hasher.encode(pwd, salt=gen_salt())
|
||||
dbuser.password = new_hash
|
||||
sess.add(dbuser)
|
||||
return dbuser.uuid
|
||||
return None
|
||||
|
||||
def login_with_username(self, username: str, pwd: str) -> Optional[str]:
|
||||
@@ -58,13 +54,25 @@ class UserService:
|
||||
status = hasher.verify(pwd, dbuser.password)
|
||||
if status is True:
|
||||
return dbuser.uuid
|
||||
elif status == 'MIGRATEMEPLSTHX':
|
||||
new_hash = hasher.encode(pwd, salt=gen_salt())
|
||||
dbuser.password = new_hash
|
||||
sess.add(dbuser)
|
||||
return None
|
||||
|
||||
def login_with_uin(self, uin: int, pwd: str) -> Optional[str]:
|
||||
uuid = self.get_uuid_uin(uin)
|
||||
if uuid is None:
|
||||
return None
|
||||
return self.login_with_uuid(uuid, pwd)
|
||||
|
||||
def login_with_uuid(self, uuid: str, pwd: str) -> Optional[str]:
|
||||
# for frontends that already worked out which account a login name points at (screen name or UIN)
|
||||
with self._conn.session() as sess:
|
||||
dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none()
|
||||
if dbuser is None:
|
||||
return None
|
||||
status = hasher.verify(pwd, dbuser.password)
|
||||
if status is True:
|
||||
return dbuser.uuid
|
||||
return None
|
||||
|
||||
|
||||
def msn_login_md5(self, email: str, md5_hash: str) -> Optional[str]:
|
||||
with self._conn.session() as sess:
|
||||
dbuser = sess.query(DBUser).filter(func.lower(DBUser.email) == email.lower()).one_or_none()
|
||||
@@ -118,6 +126,31 @@ class UserService:
|
||||
|
||||
return hasher.extract_salt(pw_md5) if pw_md5 else None
|
||||
|
||||
def aim_get_md5_password_by_uuid(self, uuid: str) -> Optional[bytes]:
|
||||
with self._conn.session() as sess:
|
||||
dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none()
|
||||
if dbuser is None:
|
||||
return None
|
||||
|
||||
return hasher_md5.extract_hash(dbuser.get_front_data('aim', 'pw_md5') or '')
|
||||
|
||||
def aim_get_md5_password_bucp2_by_uuid(self, uuid: str) -> Optional[bytes]:
|
||||
with self._conn.session() as sess:
|
||||
dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none()
|
||||
if dbuser is None:
|
||||
return None
|
||||
|
||||
return hasher_md5.extract_hash(dbuser.get_front_data('aim', 'pw_md5_v5') or '')
|
||||
|
||||
def aim_get_md5_salt_by_uuid(self, uuid: str) -> Optional[str]:
|
||||
with self._conn.session() as sess:
|
||||
dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none()
|
||||
if dbuser is None:
|
||||
return None
|
||||
|
||||
pw_md5 = dbuser.get_front_data('aim', 'pw_md5')
|
||||
|
||||
return hasher.extract_salt(pw_md5) if pw_md5 else None
|
||||
|
||||
def msim_get_sha1_password(self, email: str) -> Optional[bytes]:
|
||||
with self._conn.session() as sess:
|
||||
@@ -152,6 +185,39 @@ class UserService:
|
||||
return None
|
||||
return dbuser.uuid
|
||||
|
||||
def get_uuid_uin(self, uin: int) -> Optional[str]:
|
||||
# a UIN of 0 is what accounts without an ICQ number carry, so it never names anyone
|
||||
if uin <= 0:
|
||||
return None
|
||||
with self._conn.session() as sess:
|
||||
dbuser = sess.query(DBUser).filter(DBUser.uin == uin).first()
|
||||
if dbuser is None:
|
||||
return None
|
||||
return dbuser.uuid
|
||||
|
||||
def search_uuids(
|
||||
self, *, email: Optional[str] = None, first_name: Optional[str] = None, last_name: Optional[str] = None,
|
||||
nickname: Optional[str] = None, limit: int = 20,
|
||||
) -> List[str]:
|
||||
# directory searches (ICQ white pages, AIM ODIR, find-by-email) only ever see people who listed themselves
|
||||
criteria = []
|
||||
if email:
|
||||
criteria.append(func.lower(DBUser.email) == email.lower())
|
||||
if first_name:
|
||||
criteria.append(func.lower(DBUser.first_name) == first_name.lower())
|
||||
if last_name:
|
||||
criteria.append(func.lower(DBUser.last_name) == last_name.lower())
|
||||
if nickname:
|
||||
criteria.append(or_(
|
||||
func.lower(DBUser.nickname) == nickname.lower(), func.lower(DBUser.friendly_name) == nickname.lower(),
|
||||
func.lower(DBUser.username) == nickname.lower(),
|
||||
))
|
||||
if not criteria:
|
||||
return []
|
||||
with self._conn.session() as sess:
|
||||
query = sess.query(DBUser.uuid).filter(DBUser.show_in_dir == True, DBUser.suspended == False, *criteria)
|
||||
return [row.uuid for row in query.limit(limit)]
|
||||
|
||||
def get(self, uuid: str) -> Optional[User]:
|
||||
if uuid not in self._cache_by_uuid:
|
||||
self._cache_by_uuid[uuid] = self._get_uncached(uuid)
|
||||
@@ -218,10 +284,12 @@ class UserService:
|
||||
|
||||
self._cache_by_uuid.pop(user.uuid, None)
|
||||
|
||||
if md5 != user.avatar:
|
||||
self.add_activity(user, ActivityType.DisplayPicture, text = md5)
|
||||
|
||||
user.avatar = md5
|
||||
return md5
|
||||
|
||||
|
||||
def get_detail(self, uuid: str) -> Optional[UserDetail]:
|
||||
with self._conn.session() as sess:
|
||||
dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none()
|
||||
@@ -408,6 +476,49 @@ class UserService:
|
||||
|
||||
return circle
|
||||
|
||||
def delete_user(self, uuid: str, new_owners: Dict[str, Circle]) -> bool:
|
||||
with self._conn.session() as sess:
|
||||
dbuser = sess.query(DBUser).filter(DBUser.uuid == uuid).one_or_none()
|
||||
if dbuser is None:
|
||||
return False
|
||||
for chat_id, circle in new_owners.items():
|
||||
sess.query(DBCircle).filter(DBCircle.chat_id == chat_id).update({
|
||||
DBCircle.owner_id: circle.owner_id, DBCircle.owner_uuid: circle.owner_uuid, DBCircle.owner_friendly: circle.owner_friendly,
|
||||
}, synchronize_session = False)
|
||||
sess.query(DBCircleMembership).filter(or_(
|
||||
DBCircleMembership.member_id == dbuser.id, DBCircleMembership.member_uuid == uuid,
|
||||
)).delete(synchronize_session = False)
|
||||
sess.query(DBUserContact).filter(or_(
|
||||
DBUserContact.user_id == dbuser.id, DBUserContact.contact_id == dbuser.id,
|
||||
DBUserContact.user_uuid == uuid, DBUserContact.uuid == uuid,
|
||||
)).delete(synchronize_session = False)
|
||||
for model in (DBActivityReaction, DBActivityComment):
|
||||
sess.query(model).filter(model.user_uuid == uuid).delete(synchronize_session = False)
|
||||
activity_ids = [activity_id for (activity_id,) in sess.query(DBActivity.id).filter(DBActivity.user_uuid == uuid)]
|
||||
if activity_ids:
|
||||
for model in (DBActivityReaction, DBActivityComment):
|
||||
sess.query(model).filter(model.activity_id.in_(activity_ids)).delete(synchronize_session = False)
|
||||
sess.query(DBActivity).filter(DBActivity.id.in_(activity_ids)).delete(synchronize_session = False)
|
||||
sess.query(DBUserProfile).filter(DBUserProfile.user_id == dbuser.id).delete(synchronize_session = False)
|
||||
sess.expire(dbuser)
|
||||
sess.delete(dbuser)
|
||||
self._cache_by_uuid.pop(uuid, None)
|
||||
return True
|
||||
|
||||
def expired_suspensions(self, days: int, now: Optional[datetime] = None) -> List[str]:
|
||||
cutoff = (now or datetime.utcnow()) - timedelta(days = days)
|
||||
with self._conn.session() as sess:
|
||||
rows = sess.query(DBUser.uuid).filter(
|
||||
DBUser.suspended == True, or_(DBUser.suspended_at == None, DBUser.suspended_at <= cutoff),
|
||||
).all()
|
||||
return [uuid for (uuid,) in rows]
|
||||
|
||||
def delete_circle(self, chat_id: str) -> None:
|
||||
with self._conn.session() as sess:
|
||||
sess.query(DBCircleMembership).filter(DBCircleMembership.chat_id == chat_id).delete(synchronize_session = False)
|
||||
sess.query(DBCircle).filter(DBCircle.chat_id == chat_id).delete(synchronize_session = False)
|
||||
self._circle_cache_by_chat_id.pop(chat_id, None)
|
||||
|
||||
def get_all_circles(self) -> List[Circle]:
|
||||
circles = []
|
||||
|
||||
@@ -548,8 +659,10 @@ class UserService:
|
||||
if dbusercontacts_to_add:
|
||||
sess.add_all(dbusercontacts_to_add)
|
||||
|
||||
def save_single_roaming(self, user: User, to_save: Dict[str, Any]) -> None:
|
||||
def save_single_roaming(self, user: User, to_save: Dict[str, Any]) -> bool:
|
||||
# Returns whether a "What's New" activity was added
|
||||
updated = False
|
||||
activity_added = False
|
||||
|
||||
with self._conn.session() as sess:
|
||||
dbuser = sess.query(DBUser).filter(DBUser.uuid == user.uuid).one()
|
||||
@@ -558,13 +671,149 @@ class UserService:
|
||||
dbuser.name_last_modified = datetime.utcnow()
|
||||
updated = True
|
||||
if 'message' in to_save:
|
||||
# A new status message shows up in contacts' "What's New"
|
||||
if to_save['message'] and to_save['message'] != dbuser.message:
|
||||
activity_added = self.add_activity(user, ActivityType.StatusMessage, text = to_save['message'])
|
||||
dbuser.message = to_save['message']
|
||||
dbuser.message_last_modified = datetime.utcnow()
|
||||
updated = True
|
||||
|
||||
if updated:
|
||||
sess.add(dbuser)
|
||||
|
||||
return activity_added
|
||||
|
||||
def add_activity(
|
||||
self, user: Optional[User], type: ActivityType, *, title: Optional[str] = None, text: Optional[str] = None, url: Optional[str] = None,
|
||||
) -> bool:
|
||||
# Returns whether the activity was added
|
||||
if user is not None and not beacon_enabled(user):
|
||||
return False
|
||||
text = (text[:255] if text else text)
|
||||
title = (title[:100] if title else title)
|
||||
with self._conn.session() as sess:
|
||||
if user is not None:
|
||||
types = ((int(type), int(ActivityType.Photo)) if type is ActivityType.StatusMessage else (int(type),))
|
||||
dbactivity_last = sess.query(DBActivity).filter(
|
||||
DBActivity.user_uuid == user.uuid, DBActivity.type.in_(types),
|
||||
).order_by(DBActivity.date_created.desc()).first()
|
||||
if dbactivity_last is not None and dbactivity_last.text == text and (
|
||||
int(dbactivity_last.type) == int(type) or datetime.utcnow() - dbactivity_last.date_created < PHOTO_STATUS_WINDOW
|
||||
) and (type is not ActivityType.Photo or dbactivity_last.url == url):
|
||||
return False
|
||||
sess.add(DBActivity(
|
||||
user_uuid = (user.uuid if user is not None else None), type = int(type), title = title, text = text, url = url,
|
||||
))
|
||||
return True
|
||||
|
||||
def get_activities(
|
||||
self, uuids: List[str], count: int, *, announcements: bool = False, before_id: int | None = None, after_id: int | None = None,
|
||||
types: list[ActivityType] | None = None,
|
||||
) -> List[Activity]:
|
||||
activities = [] # type: List[Activity]
|
||||
|
||||
with self._conn.session() as sess:
|
||||
condition = DBActivity.user_uuid.in_(uuids)
|
||||
if announcements:
|
||||
condition = condition | DBActivity.user_uuid.is_(None)
|
||||
if before_id is not None:
|
||||
condition = condition & (DBActivity.id < before_id)
|
||||
if after_id is not None:
|
||||
condition = condition & (DBActivity.id > after_id)
|
||||
if types:
|
||||
condition = condition & DBActivity.type.in_([int(t) for t in types])
|
||||
for dbactivity in sess.query(DBActivity).filter(condition).order_by(DBActivity.date_created.desc(), DBActivity.id.desc()).limit(count):
|
||||
user = (self.get(dbactivity.user_uuid) if dbactivity.user_uuid is not None else None)
|
||||
if dbactivity.user_uuid is not None and user is None: continue
|
||||
if user is not None and not beacon_enabled(user): continue
|
||||
activities.append(Activity(
|
||||
dbactivity.id, user, ActivityType(int(dbactivity.type)), dbactivity.title, dbactivity.text, dbactivity.url, dbactivity.date_created,
|
||||
))
|
||||
|
||||
return activities
|
||||
|
||||
def get_activity(self, activity_id: int) -> Activity | None:
|
||||
with self._conn.session() as sess:
|
||||
dbactivity = sess.query(DBActivity).filter(DBActivity.id == activity_id).one_or_none()
|
||||
if dbactivity is None:
|
||||
return None
|
||||
user = (self.get(dbactivity.user_uuid) if dbactivity.user_uuid is not None else None)
|
||||
return Activity(
|
||||
dbactivity.id, user, ActivityType(int(dbactivity.type)), dbactivity.title, dbactivity.text, dbactivity.url, dbactivity.date_created,
|
||||
)
|
||||
|
||||
def delete_activity(self, activity_id: int, user_uuid: str | None) -> bool:
|
||||
with self._conn.session() as sess:
|
||||
if sess.query(DBActivity).filter(DBActivity.id == activity_id).filter(
|
||||
DBActivity.user_uuid.is_(None) if user_uuid is None else DBActivity.user_uuid == user_uuid
|
||||
).count():
|
||||
sess.query(DBActivityReaction).filter(DBActivityReaction.activity_id == activity_id).delete(synchronize_session = False)
|
||||
sess.query(DBActivityComment).filter(DBActivityComment.activity_id == activity_id).delete(synchronize_session = False)
|
||||
query = sess.query(DBActivity).filter(DBActivity.id == activity_id)
|
||||
if user_uuid is None:
|
||||
query = query.filter(DBActivity.user_uuid.is_(None))
|
||||
else:
|
||||
query = query.filter(DBActivity.user_uuid == user_uuid)
|
||||
return query.delete(synchronize_session = False) > 0
|
||||
|
||||
def toggle_reaction(self, activity_id: int, user_uuid: str, reaction: str) -> bool:
|
||||
with self._conn.session() as sess:
|
||||
existing = sess.query(DBActivityReaction).filter(
|
||||
DBActivityReaction.activity_id == activity_id, DBActivityReaction.user_uuid == user_uuid, DBActivityReaction.reaction == reaction,
|
||||
).one_or_none()
|
||||
if existing is not None:
|
||||
sess.delete(existing)
|
||||
return False
|
||||
sess.add(DBActivityReaction(activity_id = activity_id, user_uuid = user_uuid, reaction = reaction))
|
||||
return True
|
||||
|
||||
def get_reactions(self, activity_ids: List[int]) -> Dict[int, Dict[str, List[str]]]:
|
||||
result: dict[int, dict[str, list[str]]] = {}
|
||||
if not activity_ids:
|
||||
return result
|
||||
with self._conn.session() as sess:
|
||||
for row in sess.query(DBActivityReaction).filter(DBActivityReaction.activity_id.in_(activity_ids)).order_by(DBActivityReaction.id):
|
||||
result.setdefault(row.activity_id, {}).setdefault(row.reaction, []).append(row.user_uuid)
|
||||
return result
|
||||
|
||||
def add_comment(self, activity_id: int, user_uuid: str, text: str) -> int:
|
||||
with self._conn.session() as sess:
|
||||
dbcomment = DBActivityComment(activity_id = activity_id, user_uuid = user_uuid, text = text[:255])
|
||||
sess.add(dbcomment)
|
||||
sess.flush()
|
||||
return int(dbcomment.id)
|
||||
|
||||
def delete_comment(self, comment_id: int, user_uuid: str) -> bool:
|
||||
with self._conn.session() as sess:
|
||||
dbcomment = sess.query(DBActivityComment).filter(DBActivityComment.id == comment_id).one_or_none()
|
||||
if dbcomment is None:
|
||||
return False
|
||||
dbactivity = sess.query(DBActivity).filter(DBActivity.id == dbcomment.activity_id).one_or_none()
|
||||
if dbcomment.user_uuid != user_uuid and (dbactivity is None or dbactivity.user_uuid != user_uuid):
|
||||
return False
|
||||
sess.delete(dbcomment)
|
||||
return True
|
||||
|
||||
def get_comments(self, activity_ids: List[int]) -> Dict[int, List[Tuple[int, str, str, datetime]]]:
|
||||
result: dict[int, list[tuple[int, str, str, datetime]]] = {}
|
||||
if not activity_ids:
|
||||
return result
|
||||
with self._conn.session() as sess:
|
||||
for row in sess.query(DBActivityComment).filter(DBActivityComment.activity_id.in_(activity_ids)).order_by(DBActivityComment.id):
|
||||
result.setdefault(row.activity_id, []).append((int(row.id), row.user_uuid, row.text, row.date_created))
|
||||
return result
|
||||
|
||||
def beacon_enabled(user: User) -> bool:
|
||||
if not getattr(user, 'account_verified', False):
|
||||
return False
|
||||
settings_json = user.settings or {}
|
||||
return not (settings_json.get('beacon_off') or settings_json.get('konekt_off'))
|
||||
|
||||
def directory_online_visible(user: User) -> bool:
|
||||
return not (user.settings or {}).get('dir_hide_online')
|
||||
|
||||
# How long after sharing a photo a status message with the same caption still belongs to it
|
||||
PHOTO_STATUS_WINDOW = timedelta(minutes = 10)
|
||||
|
||||
def _get_oim_path(recipient_uuid: str) -> Path:
|
||||
return Path('storage/oim') / recipient_uuid
|
||||
Reference in new issue
Block a user