diff --git a/docs/USER.md b/docs/USER.md index f324e5e..7936c0a 100644 --- a/docs/USER.md +++ b/docs/USER.md @@ -30,10 +30,12 @@ A főmenü "Beállítások" opciójában az alábbi funkciók érhetők el: - Git-alapú jegytörténet: Lokális Git tárolóba mentés (`Pala_Jegyek_Git`). - **Profilkezelés**: Váltás a mentett fiókok között. - **Háttér-értesítések**: Windowson a Feladatütemezőbe kerül (`PalaDaemon`): a háttérben óránként és bejelentkezéskor ellenőrzi az új jegyeket, majd értesítést küld. Linuxon és macOS-en a `pala --daemon` parancsot magad ütemezheted (például cronnal), az értesítést a rendszer saját értesítési rendszere jeleníti meg. -- **Slack-értesítések**: a `pala --daemon` minden értesítést egy Slack csatornába is elküld, ha megadsz egy Incoming Webhook címet. Tedd a `PALA_SLACK_WEBHOOK` környezeti változóba, vagy írd a `~/.config/pala/slack_webhook` fájlba (`chmod 600`). Csak `https://hooks.slack.com/services/...` címet fogad el. Értesít az új jegyekről (tantárggyal és értékkel), az új házi feladatokról, minden új számonkérésről egyszer, a holnapi számonkérésről egyszer, valamint az elmaradt és helyettesített órákról. Az első futás csak megjegyzi a meglévő dolgozatokat, nem küldi el őket. Egy futás összes értesítése egyetlen Slack üzenetben érkezik. -- **Gemini összefoglaló**: ha megadsz egy Gemini API kulcsot (`PALA_GEMINI_API_KEY` vagy `~/.config/pala/gemini_key`), az új adatot tartalmazó Slack üzenet végére rövid magyar összefoglaló kerül. Új adat nélkül nincs üzenet és nincs API hívás. A modell a `PALA_GEMINI_MODEL` változóval állítható. A kérés csak a tantárgyakat, jegyeket, témákat, dátumokat, valamint a Moodle kurzusok és határidők nevét tartalmazza. A helyettesítő tanár neve és a Moodle értesítések szövege csak a Slack üzenetbe kerül, a Geminihez nem. Az ingyenes szint tartalmát a Google felhasználhatja a termékei fejlesztéséhez. -- **Moodle**: ha a `PALA_MOODLE_URL` be van állítva (például `https://moodle.iskolam.hu`), a futás az olvasatlan Moodle értesítéseket és a következő 14 nap határidejeit is ellenőrzi. Az első futás a `PALA_MOODLE_USER` és `PALA_MOODLE_PASSWORD` értékkel belép, és csak a tokent menti el. Csak jelszavas belépéssel működik (SSO nélkül), és a Moodle mobil szolgáltatásnak engedélyezettnek kell lennie. -- **Futtatás számítógép nélkül**: a `pala --daemon` egyetlen ellenőrzés után kilép, ezért ütemezett feladatból futtatható, például GitHub Actionsből. Sikertelen Kréta belépésnél Slack hibaüzenetet küld, és hibakóddal lép ki. +- **Slack-értesítések**: a `pala --daemon` minden értesítést egy Slack csatornába is elküld, ha megadsz egy Incoming Webhook címet. Tedd a `PALA_SLACK_WEBHOOK` környezeti változóba, vagy írd a `~/.config/pala/slack_webhook` fájlba (`chmod 600`). Csak `https://hooks.slack.com/services/...` címet fogad el. Értesít az új jegyekről (tantárggyal és értékkel), az új házi feladatokról, minden új számonkérésről egyszer, a holnapi számonkérésről egyszer, valamint az elmaradt és helyettesített órákról. Az első futás csak megjegyzi a meglévő dolgozatokat, nem küldi el őket. Egy futás összes értesítése egyetlen üzenetben érkezik. +- **Discord-értesítések**: ugyanez Discordra is működik. Tedd a webhook címet a `PALA_DISCORD_WEBHOOK` környezeti változóba, vagy a `~/.config/pala/discord_webhook` fájlba (`chmod 600`). Csak `https://discord.com/api/webhooks//` alakú címet fogad el (a `discordapp.com`, `ptb.discord.com` és `canary.discord.com` is megfelel). A Slack és a Discord egyszerre is be lehet kapcsolva, így az átállás megszakítás nélkül megy. Az üzenet soha nem pingel senkit (`@everyone`, `@here` és említések nem működnek). A Discord 2000 karakteres korlátja miatt a hosszabb üzenet több részre oszlik, sortörésnél vágva. Ha a Discord lassításra kéri a küldést (429), egyszer vár, aztán egyszer újrapróbálja. +- **Webhook titkosság**: a webhook cím és a token titok. A Pala hibakeresési naplóba (`PALA_DEBUG=1`) sem írja ki, sikertelen küldésnél is csak a hiba típusát naplózza. +- **Gemini összefoglaló**: ha megadsz egy Gemini API kulcsot (`PALA_GEMINI_API_KEY` vagy `~/.config/pala/gemini_key`), az új adatot tartalmazó üzenetek végére rövid magyar összefoglaló kerül (Slacken és Discordon is). Új adat nélkül nincs üzenet és nincs API hívás. A modell a `PALA_GEMINI_MODEL` változóval állítható. A kérés csak a tantárgyakat, jegyeket, témákat, dátumokat, valamint a Moodle kurzusok és határidők nevét tartalmazza. A helyettesítő tanár neve és a Moodle értesítések szövege csak a chat üzenetbe kerül, a Geminihez nem. Az ingyenes szint tartalmát a Google felhasználhatja a termékei fejlesztéséhez. +- **Moodle**: ha a `PALA_MOODLE_URL` be van állítva (például `https://moodle.iskolam.hu`), a futás az olvasatlan Moodle értesítéseket és a következő 14 nap határidejeit is ellenőrzi. Az első futás a `PALA_MOODLE_USER` és `PALA_MOODLE_PASSWORD` értékkel belép, és csak a tokent menti el. Csak jelszavas belépéssel működik (SSO nélkül), és a Moodle mobil szolgáltatásnak engedélyezettnek kell lennie. Hibás felhasználónév vagy jelszó esetén a Pala egyszer jelzi a hibát, utána nem próbálkozik újra, amíg a felhasználónevet vagy a jelszót meg nem változtatod. Ehhez a jelszó sózott hash-ét menti, magát a jelszót nem. Időtúllépés vagy szerverhiba nem zárolja a belépést. A meglévő értesítéseket és határidőket akkor jegyzi meg csendben, amikor a Moodle először sikeresen visszaadta a listát, ezért egy elmaradt első lekérés után sem érkezik egyszerre az összes olvasatlan elem. +- **Futtatás számítógép nélkül**: a `pala --daemon` egyetlen ellenőrzés után kilép, ezért ütemezett feladatból futtatható, például GitHub Actionsből. Sikertelen Kréta belépésnél hibaüzenetet küld minden beállított csatornára, és hibakóddal lép ki. ## 4. Komponensek, Rendszerintegráció & Eltávolítás A Pala teljes komponenskezelési támogatással rendelkezik a parancssorból és a grafikus beállításokból is: diff --git a/lib/api/moodle_client.dart b/lib/api/moodle_client.dart index 54903b2..df91616 100644 --- a/lib/api/moodle_client.dart +++ b/lib/api/moodle_client.dart @@ -25,7 +25,15 @@ class MoodleEvent { class MoodleLoginException implements Exception { final String reason; - const MoodleLoginException(this.reason); + + /// Moodle's own error code (`invalidlogin`, `invalidtoken`, ...), when the + /// server sent one. + final String? errorCode; + const MoodleLoginException(this.reason, {this.errorCode}); + + /// The server answered and refused the username or password. Trying the same + /// credentials again cannot work and can lock the account. + bool get isBadCredentials => errorCode == 'invalidlogin'; @override String toString() => 'Moodle bejelentkezés sikertelen: $reason'; } @@ -76,7 +84,7 @@ class MoodleClient { return; } final reason = data is Map ? (data['error'] ?? data['errorcode'] ?? 'ismeretlen hiba') : 'ismeretlen válasz'; - throw MoodleLoginException(reason.toString()); + throw MoodleLoginException(reason.toString(), errorCode: data is Map ? data['errorcode']?.toString() : null); } Future _call(String function, Map params) async { diff --git a/lib/api/moodle_tracking.dart b/lib/api/moodle_tracking.dart new file mode 100644 index 0000000..9cd1495 --- /dev/null +++ b/lib/api/moodle_tracking.dart @@ -0,0 +1,105 @@ +import 'dart:convert'; +import 'dart:math'; + +import 'package:crypto/crypto.dart'; +import 'package:pala/api/moodle_client.dart'; + +/// Remembers a refused Moodle login, so a scheduled run does not retry (and +/// report) the same wrong password every time. +/// +/// The auth data holds `moodleLoginFailed: true` and a salted SHA-256 of the +/// username and password that were refused. The login is skipped while the +/// credentials still produce that hash, and tried again as soon as either one +/// changes. Only an `invalidlogin` answer counts: a timeout or an HTTP error +/// is not a refusal and never locks anything. +class MoodleLoginGuard { + static const flagKey = 'moodleLoginFailed'; + static const hashKey = 'moodleFailedHash'; + + static String _digest(String salt, String user, String password) => + sha256.convert(utf8.encode('$salt\n$user\n$password')).toString(); + + static String _newSalt() { + final random = Random.secure(); + return List.generate(16, (_) => random.nextInt(256).toRadixString(16).padLeft(2, '0')).join(); + } + + /// True when the last login with exactly these credentials was refused. + static bool shouldSkip(Map auth, String user, String password) { + if (auth[flagKey] != true) return false; + final stored = auth[hashKey]; + if (stored is! String) return false; + final split = stored.indexOf(':'); + if (split <= 0) return false; + final salt = stored.substring(0, split); + return stored.substring(split + 1) == _digest(salt, user, password); + } + + static void recordFailure(Map auth, String user, String password, {String? salt}) { + final s = salt ?? _newSalt(); + auth[flagKey] = true; + auth[hashKey] = '$s:${_digest(s, user, password)}'; + } + + static void clear(Map auth) { + auth.remove(flagKey); + auth.remove(hashKey); + } +} + +/// Logs in with [user] and [password] unless the guard says the same +/// credentials were refused before. On success the token goes into [auth] and +/// the failure flag is cleared. A refused login is recorded in [auth] and then +/// rethrown, so the caller reports it once. [auth] is changed in place; the +/// caller saves it, also when this throws. +/// +/// Returns false when the login was skipped, true after a successful login. +Future moodleLoginWithGuard( + MoodleClient moodle, + Map auth, + String user, + String password, +) async { + if (MoodleLoginGuard.shouldSkip(auth, user, password)) return false; + try { + await moodle.login(user, password); + } on MoodleLoginException catch (e) { + if (e.isBadCredentials) MoodleLoginGuard.recordFailure(auth, user, password); + rethrow; + } + MoodleLoginGuard.clear(auth); + auth['moodleToken'] = moodle.token; + return true; +} + +/// Tells which Moodle items are new since the last run. +/// +/// A list counts as seen only after the server returned it. A failed fetch +/// (null) changes nothing, so the next run still treats the list as not yet +/// recorded and does not announce every existing item. The first successful +/// fetch records the items silently. +class MoodleSeenIds { + /// [stored] is the saved id list (null when nothing was recorded yet). + /// Returns the items to announce and the id list to save, which is null when + /// there is nothing new to save. + static ({List fresh, List? next}) update( + List? items, + String Function(T) idOf, + Object? stored, + ) { + if (items == null) return (fresh: [], next: null); + final ids = []; + final seenNow = {}; + final unique = []; + for (final item in items) { + final id = idOf(item); + if (seenNow.add(id)) { + ids.add(id); + unique.add(item); + } + } + if (stored is! List) return (fresh: [], next: ids); + final known = stored.map((e) => e.toString()).toSet(); + return (fresh: unique.where((i) => !known.contains(idOf(i))).toList(), next: ids); + } +} diff --git a/lib/app/cli_app.dart b/lib/app/cli_app.dart index d47840d..f2eab88 100644 --- a/lib/app/cli_app.dart +++ b/lib/app/cli_app.dart @@ -10,6 +10,7 @@ import 'package:pala/api/api.dart'; import 'package:pala/api/client.dart'; import 'package:pala/api/demo_client.dart'; import 'package:pala/api/moodle_client.dart'; +import 'package:pala/api/moodle_tracking.dart'; import 'package:pala/models/models.dart'; import 'package:pala/rules/absence_rules.dart'; import 'package:pala/rules/grade_rules.dart'; @@ -29,8 +30,8 @@ import 'package:pala/app/tui/screen_buffer.dart'; import 'package:pala/app/tui/tui_state.dart'; import 'package:pala/app/tui/tui_views.dart'; import 'package:pala/utils/logger.dart'; +import 'package:pala/utils/alert_digest.dart'; import 'package:pala/utils/gemini_summarizer.dart'; -import 'package:pala/utils/slack_notifier.dart'; import 'package:pala/utils/win32_console.dart'; import 'package:pala/version.dart'; import 'package:path/path.dart' as p; @@ -67,11 +68,10 @@ class PalaApp { KretaClient? _client; - /// Alert lines of the current daemon run. While it is non-null, Slack gets - /// one combined message at the end (with the optional Gemini summary) - /// instead of one message per alert. [gemini] is the same alert without - /// names or free text, the only form that goes to the Gemini prompt. - List<({String slack, String gemini})>? _runAlerts; + /// Alerts of the current daemon run. While it is non-null, the chat sinks + /// (Slack, Discord) get one combined message at the end (with the optional + /// Gemini summary) instead of one message per alert. + List? _runAlerts; String? studentUid; File _getAuthFile() { @@ -153,10 +153,10 @@ class PalaApp { Future runDaemon() async { if (!await _tryAutoLogin()) { - // A scheduled run has no one watching it, so say on Slack that the + // A scheduled run has no one watching it, so say in chat that the // login failed instead of failing silently. - await SlackNotifier.fromConfig(AppState.instance.configDir) - .send('Pala (hiba)', 'A Kréta bejelentkezés nem sikerült. Jelentkezz be újra a Palában.'); + await sendToAllSinks(configuredAlertSinks(AppState.instance.configDir), 'Pala (hiba)', + 'A Kréta bejelentkezés nem sikerült. Jelentkezz be újra a Palában.'); exitCode = 1; return; } @@ -167,7 +167,7 @@ class PalaApp { } finally { final alerts = _runAlerts!; _runAlerts = null; - await _flushAlertsToSlack(alerts); + await _flushAlerts(alerts); } } diff --git a/lib/app/daemon/daemon_logic.dart b/lib/app/daemon/daemon_logic.dart index 860e062..ae286b7 100644 --- a/lib/app/daemon/daemon_logic.dart +++ b/lib/app/daemon/daemon_logic.dart @@ -143,14 +143,14 @@ extension PalaAppDaemonLogic on PalaApp { // (a teacher, a Moodle notification), so only subjects, grades, dates and // course or deadline titles reach Gemini. Future _showToast(String title, String message, {String? geminiText}) async { - // Slack goes first: it is the channel that reaches the phone, and a + // Chat goes first: it is the channel that reaches the phone, and a // missing desktop notifier (no notify-send on a server or in Termux) // must not block it. final collecting = _runAlerts; if (collecting != null) { - collecting.add((slack: message, gemini: geminiText ?? message)); + collecting.add((text: message, gemini: geminiText ?? message)); } else { - await SlackNotifier.fromConfig(AppState.instance.configDir).send(title, message); + await sendToAllSinks(configuredAlertSinks(AppState.instance.configDir), title, message); } if (Platform.isWindows) { @@ -182,20 +182,11 @@ extension PalaAppDaemonLogic on PalaApp { } } - /// Sends the alerts of one run as a single Slack message. The Gemini - /// summary is added only when there is at least one alert, so a run without - /// news posts nothing and costs no API call. - Future _flushAlertsToSlack(List<({String slack, String gemini})> alerts) async { - if (alerts.isEmpty) return; + /// Sends the alerts of one run as a single message to every configured chat + /// sink. See [sendAlertDigest]. + Future _flushAlerts(List alerts) async { final configDir = AppState.instance.configDir; - final slack = SlackNotifier.fromConfig(configDir); - if (!slack.isEnabled) return; - final summary = await GeminiSummarizer.fromConfig(configDir).summarize(alerts.map((a) => a.gemini).toList()); - final body = StringBuffer(alerts.map((a) => '• ${a.slack}').join('\n')); - if (summary != null) { - body.write('\n\nÖsszefoglaló: $summary'); - } - await slack.send('Pala', body.toString()); + await sendAlertDigest(alerts, configuredAlertSinks(configDir), GeminiSummarizer.fromConfig(configDir)); } // Moodle is optional: it runs only when PALA_MOODLE_URL is set. The first run @@ -218,54 +209,51 @@ extension PalaAppDaemonLogic on PalaApp { final user = Platform.environment['PALA_MOODLE_USER']; final password = Platform.environment['PALA_MOODLE_PASSWORD']; if (user == null || password == null) return; - await moodle.login(user, password); + // The guard remembers a refused login, so a wrong password is reported + // once and not on every scheduled run. authData = state.getAuthData(); - authData['moodleToken'] = moodle.token; - state.saveAuthData(authData); + try { + if (!await moodleLoginWithGuard(moodle, authData, user, password)) { + PalaLogger.debug('Moodle login skipped: these credentials were refused before.'); + return; + } + } finally { + state.saveAuthData(authData); + } } - final firstRun = authData['moodleNotifiedIds'] == null; - final seenNotifications = - ((authData['moodleNotifiedIds'] as List?)?.map((e) => e.toString()) ?? const []).toSet(); - final seenEvents = - ((authData['moodleEventIds'] as List?)?.map((e) => e.toString()) ?? const []).toSet(); - + // Each list is recorded only after the server returned it. If a fetch + // fails, the next run still counts that list as unrecorded, instead of + // announcing every item that was already there. final notifications = await moodle.getNotifications(); - if (notifications != null) { - for (final n in notifications) { - if (seenNotifications.add('${n.id}') && !firstRun) { - // Notification subjects often name the sender or the poster. - await _showToast('Pala (Moodle)', 'Moodle: ${n.subject}', geminiText: 'Új Moodle értesítés'); - } - } - seenNotifications.retainWhere(notifications.map((n) => '${n.id}').toSet().contains); + final seenNotifications = MoodleSeenIds.update(notifications, (n) => '${n.id}', authData['moodleNotifiedIds']); + for (final n in seenNotifications.fresh) { + // Notification subjects often name the sender or the poster. + await _showToast('Pala (Moodle)', 'Moodle: ${n.subject}', geminiText: 'Új Moodle értesítés'); } final events = await moodle.getUpcomingEvents(); - if (events != null) { - for (final e in events) { - if (seenEvents.add('${e.id}') && !firstRun) { - final due = e.due; - final dueLabel = due == null - ? '' - : ', határidő: ${due.year}.${due.month.toString().padLeft(2, '0')}.${due.day.toString().padLeft(2, '0')}.'; - final course = e.course != null ? ' (${e.course})' : ''; - await _showToast('Pala (Moodle)', 'Új Moodle esemény: ${e.name}$course$dueLabel'); - } - } - seenEvents.retainWhere(events.map((e) => '${e.id}').toSet().contains); + final seenEvents = MoodleSeenIds.update(events, (e) => '${e.id}', authData['moodleEventIds']); + for (final e in seenEvents.fresh) { + final due = e.due; + final dueLabel = due == null + ? '' + : ', határidő: ${due.year}.${due.month.toString().padLeft(2, '0')}.${due.day.toString().padLeft(2, '0')}.'; + final course = e.course != null ? ' (${e.course})' : ''; + await _showToast('Pala (Moodle)', 'Új Moodle esemény: ${e.name}$course$dueLabel'); } authData = state.getAuthData(); - authData['moodleNotifiedIds'] = seenNotifications.toList(); - authData['moodleEventIds'] = seenEvents.toList(); + if (seenNotifications.next != null) authData['moodleNotifiedIds'] = seenNotifications.next; + if (seenEvents.next != null) authData['moodleEventIds'] = seenEvents.next; state.saveAuthData(authData); } on MoodleLoginException catch (e) { // Drop a dead token so the next run logs in again. authData = state.getAuthData(); authData.remove('moodleToken'); state.saveAuthData(authData); - await _showToast('Pala (Moodle)', '$e'); + final hint = e.isBadCredentials ? ' Új próbálkozás csak a felhasználónév vagy a jelszó módosítása után.' : ''; + await _showToast('Pala (Moodle)', '$e.$hint'); } catch (e) { PalaLogger.debug('Moodle ellenőrzés sikertelen: $e'); } diff --git a/lib/utils/alert_digest.dart b/lib/utils/alert_digest.dart new file mode 100644 index 0000000..01c096e --- /dev/null +++ b/lib/utils/alert_digest.dart @@ -0,0 +1,50 @@ +import 'package:pala/utils/alert_sink.dart'; +import 'package:pala/utils/discord_notifier.dart'; +import 'package:pala/utils/gemini_summarizer.dart'; +import 'package:pala/utils/logger.dart'; +import 'package:pala/utils/slack_notifier.dart'; + +/// One alert of a daemon run. [text] is the full line for the chat channels. +/// [gemini] is the same alert without names or free text (a teacher, a Moodle +/// notification subject), and is the only form that goes to the Gemini prompt. +typedef RunAlert = ({String text, String gemini}); + +/// Every chat channel that has a valid webhook. Slack and Discord work at the +/// same time, so a move from one to the other needs no gap. +List configuredAlertSinks(String configDir) { + return [ + SlackNotifier.fromConfig(configDir), + DiscordNotifier.fromConfig(configDir), + ].where((sink) => sink.isEnabled).toList(); +} + +/// Sends one message to every sink. A failing sink never stops the others. +Future sendToAllSinks(List sinks, String title, String message) async { + for (final sink in sinks) { + try { + await sink.send(title, message); + } catch (e) { + // Sinks are written not to throw; this is only a safety net, and it logs + // the type because a message could hold a webhook URL. + PalaLogger.debug('Alert sink failed: ${e.runtimeType}'); + } + } +} + +/// Sends the alerts of one run as a single message per sink. The Gemini +/// summary is added only when there is at least one alert and at least one +/// sink, so a run without news posts nothing and costs no API call. Bold +/// markup is each sink's own (`*x*` for Slack, `**x**` for Discord). +Future sendAlertDigest( + List alerts, + List sinks, + GeminiSummarizer gemini, +) async { + if (alerts.isEmpty || sinks.isEmpty) return; + final summary = await gemini.summarize(alerts.map((a) => a.gemini).toList()); + final lines = alerts.map((a) => '• ${a.text}').join('\n'); + for (final sink in sinks) { + final body = summary == null ? lines : '$lines\n\n${sink.bold('Összefoglaló:')} $summary'; + await sendToAllSinks([sink], 'Pala', body); + } +} diff --git a/lib/utils/alert_sink.dart b/lib/utils/alert_sink.dart new file mode 100644 index 0000000..ed6a13f --- /dev/null +++ b/lib/utils/alert_sink.dart @@ -0,0 +1,15 @@ +/// A chat channel the daemon posts its alerts to (Slack, Discord). +/// +/// Each sink formats text its own way, so callers never build channel markup +/// themselves: bold goes through [bold], and [send] adds the bold title. +abstract class AlertSink { + /// True when a valid webhook is configured. + bool get isEnabled; + + /// Wraps [text] in this channel's bold markup. + String bold(String text); + + /// Posts one message. Returns false when disabled or when the channel + /// rejects it. Never throws and never logs the webhook URL. + Future send(String title, String message); +} diff --git a/lib/utils/discord_notifier.dart b/lib/utils/discord_notifier.dart new file mode 100644 index 0000000..e3a42da --- /dev/null +++ b/lib/utils/discord_notifier.dart @@ -0,0 +1,187 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:http/http.dart' as http; +import 'package:pala/utils/alert_sink.dart'; +import 'package:pala/utils/logger.dart'; + +/// Posts daemon notifications to a Discord channel through a webhook. +/// +/// The webhook URL holds a secret token (anyone with it can post to the +/// channel), so it is read from the `PALA_DISCORD_WEBHOOK` environment +/// variable or from the owner-only `discord_webhook` file in the config +/// directory, never from argv, and it is never written to a log. +class DiscordNotifier implements AlertSink { + /// Discord rejects a message whose content is longer than this. + static const maxContentLength = 2000; + + static const _hosts = { + 'discord.com', + 'discordapp.com', + 'ptb.discord.com', + 'canary.discord.com', + }; + static final _pathPattern = RegExp(r'^/api/webhooks/\d+/[A-Za-z0-9_-]+$'); + static const _requestTimeout = Duration(seconds: 15); + static const _maxRetryWait = Duration(seconds: 30); + + final String? webhookUrl; + final http.Client _client; + final Future Function(Duration) _delay; + + /// [delay] is how a rate-limit wait happens; tests pass a recorder so they + /// do not sleep. + DiscordNotifier( + this.webhookUrl, { + http.Client? client, + Future Function(Duration)? delay, + }) : _client = client ?? http.Client(), + _delay = delay ?? Future.delayed; + + /// Builds a notifier from the environment, falling back to + /// `/discord_webhook`. Returns a disabled notifier when neither + /// is set. + factory DiscordNotifier.fromConfig(String configDir, {http.Client? client}) { + final fromEnv = Platform.environment['PALA_DISCORD_WEBHOOK']?.trim(); + if (fromEnv != null && fromEnv.isNotEmpty) { + return DiscordNotifier(fromEnv, client: client); + } + final file = File('$configDir/discord_webhook'); + if (file.existsSync()) { + final value = file.readAsStringSync().trim(); + if (value.isNotEmpty) return DiscordNotifier(value, client: client); + } + return DiscordNotifier(null, client: client); + } + + @override + bool get isEnabled => isValidWebhook(webhookUrl); + + @override + String bold(String text) => '**$text**'; + + /// Only Discord's own webhook hosts are accepted, so a typo or a tampered + /// config file cannot send Kréta data to an arbitrary server. A port, user + /// info, query or fragment makes the address invalid. + static bool isValidWebhook(String? url) { + if (url == null) return false; + final uri = Uri.tryParse(url); + return uri != null && + uri.scheme == 'https' && + _hosts.contains(uri.host) && + !uri.hasPort && + uri.userInfo.isEmpty && + !uri.hasQuery && + !uri.hasFragment && + _pathPattern.hasMatch(uri.path); + } + + /// The request body. `allowed_mentions.parse` is empty, so text that came + /// from Kréta or Moodle (`@everyone`, `<@123>`) can never ping anyone. + static Map buildPayload(String content) { + return { + 'content': content, + 'allowed_mentions': {'parse': []}, + }; + } + + /// Splits [text] into pieces of at most [limit] characters, cutting at line + /// boundaries. A single line longer than [limit] is cut at the limit, never + /// in the middle of a surrogate pair. + static List splitMessage(String text, {int limit = maxContentLength}) { + if (text.length <= limit) return [text]; + final chunks = []; + var current = StringBuffer(); + var length = 0; + + void flush() { + if (length > 0) { + chunks.add(current.toString()); + current = StringBuffer(); + length = 0; + } + } + + for (final line in text.split('\n')) { + var rest = line; + while (rest.length > limit) { + flush(); + var cut = limit; + final last = rest.codeUnitAt(cut - 1); + if (last >= 0xD800 && last <= 0xDBFF) cut--; + chunks.add(rest.substring(0, cut)); + rest = rest.substring(cut); + } + final needed = rest.length + (length > 0 ? 1 : 0); + if (length + needed > limit) flush(); + if (length > 0) { + current.write('\n'); + length++; + } + current.write(rest); + length += rest.length; + } + flush(); + return chunks; + } + + /// Sends one message, split into several posts when it is over the limit. + /// Returns false when disabled or when Discord rejects a part. Errors are + /// logged by type only, never thrown, so a Discord outage does not stop the + /// rest of the daemon run. + @override + Future send(String title, String message) async { + if (!isEnabled) return false; + for (final chunk in splitMessage('${bold(title)}\n$message')) { + if (chunk.trim().isEmpty) continue; + if (!await _post(chunk)) return false; + } + return true; + } + + Future _post(String content) async { + final body = jsonEncode(buildPayload(content)); + for (var attempt = 0; attempt < 2; attempt++) { + try { + final response = await _client + .post( + Uri.parse(webhookUrl!), + headers: {'Content-Type': 'application/json; charset=utf-8'}, + body: body, + ) + .timeout(_requestTimeout); + if (response.statusCode == 204) return true; + if (response.statusCode == 429 && attempt == 0) { + await _delay(_retryAfter(response)); + continue; + } + PalaLogger.debug('Discord webhook HTTP ${response.statusCode}'); + return false; + } catch (e) { + // ClientException messages carry the request URI, which holds the + // secret token, so only the exception type is logged. + PalaLogger.debug('Discord webhook failed: ${e.runtimeType}'); + return false; + } + } + return false; + } + + /// How long a 429 asks to wait: `retry_after` (seconds, may be fractional) + /// in the JSON body, else the `Retry-After` header, else one second. Capped + /// so a scheduled run cannot hang on a huge value. + static Duration _retryAfter(http.Response response) { + num? seconds; + try { + final data = jsonDecode(response.body); + if (data is Map && data['retry_after'] is num) { + seconds = data['retry_after'] as num; + } + } catch (_) {} + seconds ??= num.tryParse(response.headers['retry-after'] ?? ''); + seconds ??= 1; + final wait = Duration(milliseconds: (seconds * 1000).round()); + if (wait.isNegative) return Duration.zero; + return wait > _maxRetryWait ? _maxRetryWait : wait; + } +} diff --git a/lib/utils/slack_notifier.dart b/lib/utils/slack_notifier.dart index 60fdfde..062efbb 100644 --- a/lib/utils/slack_notifier.dart +++ b/lib/utils/slack_notifier.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; +import 'package:pala/utils/alert_sink.dart'; import 'package:pala/utils/logger.dart'; /// Posts daemon notifications to a Slack channel through an Incoming Webhook. @@ -9,7 +10,7 @@ import 'package:pala/utils/logger.dart'; /// The webhook URL is a secret (anyone holding it can post to the channel), so /// it is read from the `PALA_SLACK_WEBHOOK` environment variable or from the /// owner-only `slack_webhook` file in the config directory, never from argv. -class SlackNotifier { +class SlackNotifier implements AlertSink { final String? webhookUrl; final http.Client _client; @@ -31,8 +32,12 @@ class SlackNotifier { return SlackNotifier(null, client: client); } + @override bool get isEnabled => isValidWebhook(webhookUrl); + @override + String bold(String text) => '*$text*'; + /// Only Slack's own webhook host is accepted, so a typo or a tampered config /// file cannot send Kréta data to an arbitrary server. static bool isValidWebhook(String? url) { @@ -62,6 +67,7 @@ class SlackNotifier { /// Sends one message. Returns false when disabled or when Slack rejects it. /// Errors are logged, never thrown, so a Slack outage does not stop the /// desktop notification or the rest of the daemon run. + @override Future send(String title, String message) async { if (!isEnabled) return false; try { @@ -78,7 +84,9 @@ class SlackNotifier { } return true; } catch (e) { - PalaLogger.debug('Slack webhook failed: $e'); + // The http package puts the request URI (the secret webhook) into + // ClientException messages, so only the exception type is logged. + PalaLogger.debug('Slack webhook failed: ${e.runtimeType}'); return false; } } diff --git a/pubspec.lock b/pubspec.lock index cb698c6..73007c0 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -90,7 +90,7 @@ packages: source: hosted version: "1.15.1" crypto: - dependency: transitive + dependency: "direct main" description: name: crypto sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf diff --git a/pubspec.yaml b/pubspec.yaml index fb43e0c..9826427 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -15,6 +15,7 @@ dependencies: interact: ^2.1.1 args: ^2.7.0 encrypt: ^5.0.3 + crypto: ^3.0.0 dart_console: '>=1.0.0 <6.0.0' path: ^1.9.1 diff --git a/test/alert_digest_test.dart b/test/alert_digest_test.dart new file mode 100644 index 0000000..6eaeda8 --- /dev/null +++ b/test/alert_digest_test.dart @@ -0,0 +1,146 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:pala/utils/alert_digest.dart'; +import 'package:pala/utils/alert_sink.dart'; +import 'package:pala/utils/discord_notifier.dart'; +import 'package:pala/utils/gemini_summarizer.dart'; +import 'package:pala/utils/slack_notifier.dart'; +import 'package:test/test.dart'; + +class _FakeSink implements AlertSink { + final String name; + final bool throws; + final sent = <({String title, String message})>[]; + + _FakeSink(this.name, {this.throws = false}); + + @override + bool get isEnabled => true; + + @override + String bold(String text) => '<$name>$text'; + + @override + Future send(String title, String message) async { + if (throws) throw StateError('boom'); + sent.add((title: title, message: message)); + return true; + } +} + +void main() { + const geminiReply = '{"candidates":[{"content":{"parts":[{"text":"Holnap dolgozat van."}]}}]}'; + + // A summarizer whose requests are recorded, so a test can read the prompt. + ({GeminiSummarizer summarizer, List prompts}) gemini({String? key = 'fake-key', int status = 200}) { + final prompts = []; + final client = MockClient((req) async { + final body = jsonDecode(req.body) as Map; + prompts.add(body['contents'][0]['parts'][0]['text'] as String); + return http.Response(geminiReply, status); + }); + return (summarizer: GeminiSummarizer(key, client: client), prompts: prompts); + } + + group('sendAlertDigest', () { + test('sends one message per sink with its own bold summary label', () async { + final slack = _FakeSink('s'); + final discord = _FakeSink('d'); + final g = gemini(); + await sendAlertDigest( + [(text: 'Új jegy: Matek 5', gemini: 'Új jegy: Matek 5'), (text: 'Holnap dolgozat: Töri', gemini: 'Holnap dolgozat: Töri')], + [slack, discord], + g.summarizer, + ); + expect(slack.sent.length, 1); + expect(discord.sent.length, 1); + expect(slack.sent.single.title, 'Pala'); + expect(slack.sent.single.message, startsWith('• Új jegy: Matek 5\n• Holnap dolgozat: Töri\n\nÖsszefoglaló: Holnap dolgozat van.')); + expect(discord.sent.single.message, contains('Összefoglaló: Holnap dolgozat van.')); + expect(g.prompts.length, 1, reason: 'one Gemini call for all sinks'); + }); + + test('the Gemini prompt holds the gemini form, never the chat text', () async { + final sink = _FakeSink('s'); + final g = gemini(); + await sendAlertDigest( + [ + (text: 'Holnap helyettesítés: Matek — Kovács Anna', gemini: 'Holnap helyettesítés: Matek'), + (text: 'Moodle: Szabó Béla írt a fórumba', gemini: 'Új Moodle értesítés'), + ], + [sink], + g.summarizer, + ); + expect(g.prompts.single, 'Holnap helyettesítés: Matek\nÚj Moodle értesítés'); + expect(g.prompts.single, isNot(contains('Kovács'))); + expect(g.prompts.single, isNot(contains('Szabó'))); + // The chat message still has the full text. + expect(sink.sent.single.message, contains('Kovács Anna')); + expect(sink.sent.single.message, contains('Szabó Béla')); + }); + + test('makes no Gemini call and posts nothing without alerts', () async { + final sink = _FakeSink('s'); + final g = gemini(); + await sendAlertDigest([], [sink], g.summarizer); + expect(sink.sent, isEmpty); + expect(g.prompts, isEmpty); + }); + + test('makes no Gemini call when no sink is configured', () async { + final g = gemini(); + await sendAlertDigest([(text: 'a', gemini: 'a')], [], g.summarizer); + expect(g.prompts, isEmpty); + }); + + test('still posts the alerts when Gemini fails or is off', () async { + final failing = _FakeSink('s'); + await sendAlertDigest([(text: 'Új jegy', gemini: 'Új jegy')], [failing], gemini(status: 500).summarizer); + expect(failing.sent.single.message, '• Új jegy'); + + final off = _FakeSink('s'); + await sendAlertDigest([(text: 'Új jegy', gemini: 'Új jegy')], [off], gemini(key: null).summarizer); + expect(off.sent.single.message, '• Új jegy'); + }); + + test('a failing sink does not stop the next one', () async { + final broken = _FakeSink('b', throws: true); + final ok = _FakeSink('o'); + await sendAlertDigest([(text: 'x', gemini: 'x')], [broken, ok], gemini(key: null).summarizer); + expect(ok.sent.single.message, '• x'); + }); + }); + + test('sendToAllSinks reaches every sink', () async { + final a = _FakeSink('a'); + final b = _FakeSink('b'); + await sendToAllSinks([a, b], 'Pala (hiba)', 'bejelentkezés'); + expect(a.sent.single.title, 'Pala (hiba)'); + expect(b.sent.single.message, 'bejelentkezés'); + }); + + group('real sinks side by side', () { + test('Slack and Discord both get the digest, each in its own markup', () async { + const slackHook = 'https://hooks.slack.com/services/T000/B000/XXXX'; + const discordHook = 'https://discord.com/api/webhooks/123456789012345678/FAKE-test_token'; + final posts = {}; + final client = MockClient((req) async { + posts[req.url.host] = req.body; + return req.url.host == 'discord.com' ? http.Response('', 204) : http.Response('ok', 200); + }); + await sendAlertDigest( + [(text: 'Új jegy: Matek 5', gemini: 'Új jegy: Matek 5')], + [SlackNotifier(slackHook, client: client), DiscordNotifier(discordHook, client: client)], + gemini().summarizer, + ); + expect((jsonDecode(posts['hooks.slack.com']!) as Map)['text'], startsWith('*Pala*\n')); + expect((jsonDecode(posts['hooks.slack.com']!) as Map)['text'], contains('*Összefoglaló:*')); + final discord = jsonDecode(posts['discord.com']!) as Map; + expect(discord['content'], startsWith('**Pala**\n')); + expect(discord['content'], contains('**Összefoglaló:**')); + expect(discord['allowed_mentions'], {'parse': []}); + }); + }); +} diff --git a/test/discord_notifier_test.dart b/test/discord_notifier_test.dart new file mode 100644 index 0000000..259e731 --- /dev/null +++ b/test/discord_notifier_test.dart @@ -0,0 +1,250 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:pala/utils/discord_notifier.dart'; +import 'package:test/test.dart'; + +import 'support/log_capture.dart'; + +void main() { + // Obviously fake: the id and the token are made up for these tests. + const hook = 'https://discord.com/api/webhooks/123456789012345678/FAKE-test_token'; + const token = 'FAKE-test_token'; + + group('isValidWebhook', () { + test('accepts every Discord host', () { + for (final host in ['discord.com', 'discordapp.com', 'ptb.discord.com', 'canary.discord.com']) { + expect(DiscordNotifier.isValidWebhook('https://$host/api/webhooks/123/FAKE-test_token'), isTrue, reason: host); + } + }); + + test('rejects other hosts, plain http, odd paths and empty values', () { + const bad = [ + '', + 'http://discord.com/api/webhooks/123/FAKE-test_token', + 'https://evil.example/api/webhooks/123/FAKE-test_token', + 'https://discord.com.evil.example/api/webhooks/123/FAKE-test_token', + 'https://evil.example/discord.com/api/webhooks/123/FAKE-test_token', + 'https://user@discord.com/api/webhooks/123/FAKE-test_token', + 'https://discord.com:8443/api/webhooks/123/FAKE-test_token', + 'https://discord.com/api/webhooks/123/FAKE-test_token?wait=true', + 'https://discord.com/api/webhooks/123/FAKE-test_token#x', + 'https://discord.com/api/webhooks/abc/FAKE-test_token', + 'https://discord.com/api/webhooks/123', + 'https://discord.com/api/webhooks/123/', + 'https://discord.com/api/webhooks/123/FAKE/test', + 'https://discord.com/api/v10/webhooks/123/FAKE-test_token', + 'https://hooks.slack.com/services/T000/B000/XXXX', + ]; + expect(DiscordNotifier.isValidWebhook(null), isFalse); + for (final url in bad) { + expect(DiscordNotifier.isValidWebhook(url), isFalse, reason: url); + } + }); + }); + + group('payload', () { + test('blocks every kind of mention', () { + final payload = DiscordNotifier.buildPayload('Matek @everyone <@123>'); + expect(payload['content'], 'Matek @everyone <@123>'); + expect(payload['allowed_mentions'], {'parse': []}); + }); + + test('the posted body carries the mention block and bold title', () async { + late http.Request captured; + final client = MockClient((req) async { + captured = req; + return http.Response('', 204); + }); + final ok = await DiscordNotifier(hook, client: client).send('Pala', '@here Holnap dolgozat'); + expect(ok, isTrue); + expect(captured.url.toString(), hook); + expect(captured.headers['Content-Type'], startsWith('application/json')); + final body = jsonDecode(captured.body) as Map; + expect(body['content'], '**Pala**\n@here Holnap dolgozat'); + expect(body['allowed_mentions'], {'parse': []}); + }); + + test('bold uses Discord markup', () { + expect(DiscordNotifier(null).bold('x'), '**x**'); + }); + }); + + group('splitMessage', () { + test('keeps a short message in one piece', () { + expect(DiscordNotifier.splitMessage('a\nb'), ['a\nb']); + }); + + test('splits at line boundaries and no piece is over the limit', () { + final lines = List.generate(100, (i) => 'sor ${i.toString().padLeft(3, '0')} ${'x' * 40}'); + final chunks = DiscordNotifier.splitMessage(lines.join('\n'), limit: 500); + expect(chunks.length, greaterThan(1)); + for (final chunk in chunks) { + expect(chunk.length, lessThanOrEqualTo(500)); + // Every line is whole: none starts or ends in the middle of a line. + for (final line in chunk.split('\n')) { + expect(lines, contains(line)); + } + } + expect(chunks.join('\n'), lines.join('\n')); + }); + + test('cuts a single over-long line at the limit', () { + final chunks = DiscordNotifier.splitMessage('a\n${'b' * 25}\nc', limit: 10); + expect(chunks.every((c) => c.length <= 10), isTrue); + expect(chunks.join(), contains('b' * 25)); + expect(chunks.first, 'a'); + }); + + test('does not split a surrogate pair', () { + // The emoji is two UTF-16 units; a cut after the first would corrupt it. + final text = '${'a' * 9}\u{1F600}${'b' * 5}'; + final chunks = DiscordNotifier.splitMessage(text, limit: 10); + for (final chunk in chunks) { + expect(chunk.length, lessThanOrEqualTo(10)); + for (var i = 0; i < chunk.length; i++) { + final unit = chunk.codeUnitAt(i); + if (unit >= 0xD800 && unit <= 0xDBFF) { + expect(i + 1, lessThan(chunk.length), reason: 'high surrogate at the end'); + } + } + } + expect(chunks.join(), text); + }); + + test('send posts each piece of a long message and all are within 2000', () async { + final posted = []; + final client = MockClient((req) async { + posted.add((jsonDecode(req.body) as Map)['content'] as String); + return http.Response('', 204); + }); + final message = List.generate(150, (i) => '• sor $i ${'y' * 30}').join('\n'); + expect(await DiscordNotifier(hook, client: client).send('Pala', message), isTrue); + expect(posted.length, greaterThan(1)); + expect(posted.every((c) => c.length <= DiscordNotifier.maxContentLength), isTrue); + expect(posted.first, startsWith('**Pala**\n')); + }); + }); + + group('send', () { + test('disabled notifier sends nothing', () async { + var called = false; + final client = MockClient((_) async { + called = true; + return http.Response('', 204); + }); + expect(await DiscordNotifier(null, client: client).send('a', 'b'), isFalse); + expect(await DiscordNotifier('https://evil.example/x', client: client).send('a', 'b'), isFalse); + expect(called, isFalse); + }); + + test('only 204 is success', () async { + final client = MockClient((_) async => http.Response('{"id":"1"}', 200)); + expect(await DiscordNotifier(hook, client: client).send('a', 'b'), isFalse); + final unauthorized = MockClient((_) async => http.Response('{"message":"Unknown Webhook"}', 404)); + expect(await DiscordNotifier(hook, client: unauthorized).send('a', 'b'), isFalse); + }); + + test('waits retry_after once after a 429, then retries and succeeds', () async { + var calls = 0; + final client = MockClient((_) async { + calls++; + return calls == 1 ? http.Response('{"retry_after": 1.5, "global": false}', 429) : http.Response('', 204); + }); + final waits = []; + final notifier = DiscordNotifier(hook, client: client, delay: (d) async => waits.add(d)); + expect(await notifier.send('a', 'b'), isTrue); + expect(calls, 2); + expect(waits, [const Duration(milliseconds: 1500)]); + }); + + test('gives up after a second 429 and never waits twice', () async { + var calls = 0; + final client = MockClient((_) async { + calls++; + return http.Response('{"retry_after": 1}', 429); + }); + final waits = []; + final notifier = DiscordNotifier(hook, client: client, delay: (d) async => waits.add(d)); + expect(await notifier.send('a', 'b'), isFalse); + expect(calls, 2); + expect(waits.length, 1); + }); + + test('falls back to the Retry-After header and caps a huge wait', () async { + var calls = 0; + final client = MockClient((_) async { + calls++; + return calls == 1 ? http.Response('not json', 429, headers: {'retry-after': '3600'}) : http.Response('', 204); + }); + final waits = []; + final notifier = DiscordNotifier(hook, client: client, delay: (d) async => waits.add(d)); + expect(await notifier.send('a', 'b'), isTrue); + expect(waits, [const Duration(seconds: 30)]); + }); + + test('never throws on network errors', () async { + final failing = MockClient((_) async => throw const SocketException('offline')); + expect(await DiscordNotifier(hook, client: failing).send('a', 'b'), isFalse); + }); + }); + + group('logging', () { + test('a failed send never logs the webhook URL or token', () async { + // The http package puts the request URI into ClientException messages. + final failing = MockClient((req) async => throw http.ClientException('connection closed', req.url)); + final log = await captureDebugLog(() async { + expect(await DiscordNotifier(hook, client: failing).send('a', 'b'), isFalse); + }); + expect(log, contains('Discord webhook failed: ClientException')); + expect(log, isNot(contains(hook))); + expect(log, isNot(contains(token))); + expect(log, isNot(contains('123456789012345678'))); + }); + + test('an error status and a rate limit log only the status', () async { + final rejected = MockClient((_) async => http.Response('{"message":"$token"}', 401)); + final limited = MockClient((_) async => http.Response('{"retry_after": 0}', 429)); + final log = await captureDebugLog(() async { + await DiscordNotifier(hook, client: rejected).send('a', 'b'); + await DiscordNotifier(hook, client: limited, delay: (_) async {}).send('a', 'b'); + }); + expect(log, contains('Discord webhook HTTP 401')); + expect(log, contains('Discord webhook HTTP 429')); + expect(log, isNot(contains(token))); + expect(log, isNot(contains('discord.com'))); + }); + + test('an exception with the URL in its message logs only its type', () async { + final slow = MockClient((_) async => throw LeakyException(hook)); + final log = await captureDebugLog(() async { + expect(await DiscordNotifier(hook, client: slow).send('a', 'b'), isFalse); + }); + expect(log, contains('Discord webhook failed: LeakyException')); + expect(log, isNot(contains(token))); + }); + }); + + test('fromConfig reads the owner-only file', () { + final dir = Directory.systemTemp.createTempSync('pala_discord'); + addTearDown(() => dir.deleteSync(recursive: true)); + File('${dir.path}/discord_webhook').writeAsStringSync('$hook\n'); + // The environment variable wins when set, so only check the file path + // when the test runner does not have one. + if ((Platform.environment['PALA_DISCORD_WEBHOOK'] ?? '').isEmpty) { + final notifier = DiscordNotifier.fromConfig(dir.path); + expect(notifier.webhookUrl, hook); + expect(notifier.isEnabled, isTrue); + } + }); +} + +/// An exception whose message holds the URL, to prove the message is not logged. +class LeakyException implements Exception { + final String message; + LeakyException(this.message); + @override + String toString() => 'LeakyException: $message'; +} diff --git a/test/moodle_tracking_test.dart b/test/moodle_tracking_test.dart new file mode 100644 index 0000000..c389736 --- /dev/null +++ b/test/moodle_tracking_test.dart @@ -0,0 +1,191 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:pala/api/moodle_client.dart'; +import 'package:pala/api/moodle_tracking.dart'; +import 'package:test/test.dart'; + +void main() { + const badLogin = '{"error":"Invalid login, please try again","errorcode":"invalidlogin"}'; + + // A client whose login endpoint answers [body] with [status], counting the + // requests so a test can prove that a skipped login makes none. + ({MoodleClient client, List requests}) moodle(String body, {int status = 200}) { + final requests = []; + final client = MockClient((req) async { + requests.add(req); + return http.Response(body, status); + }); + return (client: MoodleClient('https://moodle.example.test', client: client), requests: requests); + } + + group('MoodleLoginGuard', () { + test('skips only when the flag is set and the credentials are the same', () { + final auth = {}; + expect(MoodleLoginGuard.shouldSkip(auth, 'diak', 'rossz'), isFalse); + MoodleLoginGuard.recordFailure(auth, 'diak', 'rossz'); + expect(auth[MoodleLoginGuard.flagKey], isTrue); + expect(MoodleLoginGuard.shouldSkip(auth, 'diak', 'rossz'), isTrue); + expect(MoodleLoginGuard.shouldSkip(auth, 'diak', 'masik'), isFalse, reason: 'password changed'); + expect(MoodleLoginGuard.shouldSkip(auth, 'masik', 'rossz'), isFalse, reason: 'username changed'); + }); + + test('stores no password, only a salted hash', () { + final auth = {}; + MoodleLoginGuard.recordFailure(auth, 'diak', 'titok-jelszo'); + final stored = jsonEncode(auth); + expect(stored, isNot(contains('titok-jelszo'))); + expect(stored, isNot(contains('diak'))); + // The same credentials get a different hash with another salt. + final other = {}; + MoodleLoginGuard.recordFailure(other, 'diak', 'titok-jelszo'); + expect(other[MoodleLoginGuard.hashKey], isNot(auth[MoodleLoginGuard.hashKey])); + expect(MoodleLoginGuard.shouldSkip(other, 'diak', 'titok-jelszo'), isTrue); + }); + + test('a flag without a usable hash never blocks a login', () { + for (final hash in [null, 5, '', 'nincs-kettospont', ':abc']) { + final auth = {MoodleLoginGuard.flagKey: true, MoodleLoginGuard.hashKey: hash}; + expect(MoodleLoginGuard.shouldSkip(auth, 'diak', 'rossz'), isFalse, reason: '$hash'); + } + }); + + test('clear removes both keys', () { + final auth = {'moodleToken': 't'}; + MoodleLoginGuard.recordFailure(auth, 'diak', 'rossz'); + MoodleLoginGuard.clear(auth); + expect(auth, {'moodleToken': 't'}); + }); + }); + + group('moodleLoginWithGuard', () { + test('a wrong password reports once, then the next runs make no request', () async { + final auth = {}; + final m = moodle(badLogin); + + // Run 1: the server refuses, the failure is recorded and rethrown. + await expectLater( + moodleLoginWithGuard(m.client, auth, 'diak', 'rossz'), + throwsA(isA().having((e) => e.isBadCredentials, 'isBadCredentials', isTrue)), + ); + expect(m.requests.length, 1); + expect(auth[MoodleLoginGuard.flagKey], isTrue); + expect(auth.containsKey('moodleToken'), isFalse); + + // Runs 2 and 3 with the same credentials: skipped, no request, no throw. + expect(await moodleLoginWithGuard(m.client, auth, 'diak', 'rossz'), isFalse); + expect(await moodleLoginWithGuard(m.client, auth, 'diak', 'rossz'), isFalse); + expect(m.requests.length, 1); + }); + + test('a changed password is tried again, and success clears the flag and keeps the token', () async { + final auth = {}; + MoodleLoginGuard.recordFailure(auth, 'diak', 'rossz'); + final m = moodle('{"token":"fake-token"}'); + + expect(await moodleLoginWithGuard(m.client, auth, 'diak', 'jo'), isTrue); + expect(m.requests.length, 1); + expect(auth['moodleToken'], 'fake-token'); + expect(auth.containsKey(MoodleLoginGuard.flagKey), isFalse); + expect(auth.containsKey(MoodleLoginGuard.hashKey), isFalse); + }); + + test('the password is posted in the body and never kept in the auth data', () async { + final auth = {}; + final m = moodle('{"token":"fake-token"}'); + await moodleLoginWithGuard(m.client, auth, 'diak', 'titok-jelszo'); + expect(m.requests.single.body, contains('password=titok-jelszo')); + expect(m.requests.single.url.toString(), isNot(contains('titok-jelszo'))); + expect(jsonEncode(auth), isNot(contains('titok-jelszo'))); + }); + + test('an HTTP error or a network failure does not lock the login', () async { + final auth = {}; + final server = moodle('oops', status: 503); + await expectLater(moodleLoginWithGuard(server.client, auth, 'diak', 'jo'), throwsA(isA())); + expect(auth.containsKey(MoodleLoginGuard.flagKey), isFalse); + + final offline = MoodleClient('https://moodle.example.test', client: MockClient((_) async => throw http.ClientException('offline'))); + await expectLater(moodleLoginWithGuard(offline, auth, 'diak', 'jo'), throwsA(isA())); + expect(auth.containsKey(MoodleLoginGuard.flagKey), isFalse); + }); + + test('another server error is reported but does not lock the login', () async { + final auth = {}; + final m = moodle('{"error":"Web services are not enabled","errorcode":"enablewsdescription"}'); + await expectLater( + moodleLoginWithGuard(m.client, auth, 'diak', 'jo'), + throwsA(isA().having((e) => e.isBadCredentials, 'isBadCredentials', isFalse)), + ); + expect(auth.containsKey(MoodleLoginGuard.flagKey), isFalse); + }); + }); + + group('MoodleSeenIds', () { + String id(int n) => '$n'; + + test('a failed fetch records nothing, so the list is still unrecorded', () { + final r = MoodleSeenIds.update(null, id, null); + expect(r.fresh, isEmpty); + expect(r.next, isNull); + }); + + test('the first successful fetch records the items and announces none', () { + final r = MoodleSeenIds.update([1, 2, 3], id, null); + expect(r.fresh, isEmpty); + expect(r.next, ['1', '2', '3']); + }); + + test('an empty first list still counts as recorded', () { + final r = MoodleSeenIds.update([], id, null); + expect(r.fresh, isEmpty); + expect(r.next, []); + }); + + test('a failed first fetch followed by a good one does not announce the backlog', () { + var stored = null as Object?; + final failed = MoodleSeenIds.update(null, id, stored); + if (failed.next != null) stored = failed.next; + expect(stored, isNull, reason: 'nothing saved after the failed run'); + + final second = MoodleSeenIds.update([1, 2, 3], id, stored); + expect(second.fresh, isEmpty, reason: 'first successful fetch is silent'); + stored = second.next; + + final third = MoodleSeenIds.update([1, 2, 3, 4], id, stored); + expect(third.fresh, [4]); + }); + + test('later runs announce only new ids and drop ids that went away', () { + final r = MoodleSeenIds.update([2, 3, 4], id, ['1', '2', '3']); + expect(r.fresh, [4]); + expect(r.next, ['2', '3', '4']); + }); + + test('a failed fetch after a recorded list leaves the saved ids alone', () { + final r = MoodleSeenIds.update(null, id, ['1', '2']); + expect(r.fresh, isEmpty); + expect(r.next, isNull); + }); + + test('numbers in the saved list are read as ids', () { + final r = MoodleSeenIds.update([1, 2], id, [1, 2]); + expect(r.fresh, isEmpty); + }); + + test('duplicate ids in one fetch are announced once', () { + final r = MoodleSeenIds.update([5, 5, 6], id, ['1']); + expect(r.fresh, [5, 6]); + expect(r.next, ['5', '6']); + }); + + test('notifications and events are tracked separately', () { + // Notifications were recorded, events were not (their fetch failed). + final events = MoodleSeenIds.update([10, 11], id, null); + expect(events.fresh, isEmpty, reason: 'events are still on their first run'); + final notifications = MoodleSeenIds.update([1, 2], id, ['1']); + expect(notifications.fresh, [2]); + }); + }); +} diff --git a/test/slack_notifier_test.dart b/test/slack_notifier_test.dart index 7e447a0..81ffc09 100644 --- a/test/slack_notifier_test.dart +++ b/test/slack_notifier_test.dart @@ -6,6 +6,8 @@ import 'package:http/testing.dart'; import 'package:pala/utils/slack_notifier.dart'; import 'package:test/test.dart'; +import 'support/log_capture.dart'; + void main() { const hook = 'https://hooks.slack.com/services/T000/B000/XXXX'; @@ -48,6 +50,22 @@ void main() { expect(await SlackNotifier(hook, client: failing).send('a', 'b'), isFalse); }); + test('a failed send never logs the webhook URL', () async { + // The http package puts the request URI into ClientException messages. + final failing = MockClient((req) async => throw http.ClientException('connection closed', req.url)); + final log = await captureDebugLog(() async { + expect(await SlackNotifier(hook, client: failing).send('a', 'b'), isFalse); + }); + expect(log, contains('Slack webhook failed: ClientException')); + expect(log, isNot(contains(hook))); + expect(log, isNot(contains('XXXX'))); + expect(log, isNot(contains('hooks.slack.com'))); + }); + + test('bold uses Slack markup', () { + expect(SlackNotifier(null).bold('x'), '*x*'); + }); + test('disabled notifier sends nothing', () async { var called = false; final client = MockClient((_) async { diff --git a/test/support/log_capture.dart b/test/support/log_capture.dart new file mode 100644 index 0000000..8f05695 --- /dev/null +++ b/test/support/log_capture.dart @@ -0,0 +1,34 @@ +import 'dart:io'; + +import 'package:pala/utils/logger.dart'; + +class _CapturingStdout implements Stdout { + final lines = []; + + @override + void writeln([Object? object = '']) => lines.add('$object'); + + @override + void write(Object? object) => lines.add('$object'); + + @override + dynamic noSuchMethod(Invocation invocation) => null; +} + +/// Runs [body] with debug logging on and returns everything written to stderr. +/// Lets a test check that a log line never holds a webhook URL or token. +Future captureDebugLog(Future Function() body) async { + final capture = _CapturingStdout(); + await IOOverrides.runZoned( + () async { + PalaLogger.init(enabled: true); + try { + await body(); + } finally { + PalaLogger.init(enabled: false); + } + }, + stderr: () => capture, + ); + return capture.lines.join('\n'); +}