Speakr is a personal, self-hosted web application designed for transcribing audio recordings
Python
Share target limited per account, 20 files per hour by default (#435)
Murtaza Nasird8bc59b969b0
diff --git a/config/env.transcription.example b/config/env.transcription.exampleindex a839484c..fe14c6bd 100644--- a/config/env.transcription.example+++ b/config/env.transcription.example@@ -546,6 +546,10 @@ MAX_CONCURRENT_UPLOADS=3# API_TOKEN_RATE_LIMIT_WRITE=30 per minute# API_TOKEN_RATE_LIMIT_PROCESS=10 per minute+# Files one account can send through the phone's share sheet (installed PWA).+# Default: 20 per hour.+# SHARE_TARGET_RATE_LIMIT=20 per hour+# Set to true only when the text, chat and embedding models all run on machines# you control. API clients read it from /api/v1/capabilities (models_local).# Default: false.diff --git a/docs/user-guide/pwa.md b/docs/user-guide/pwa.mdindex 874592f5..47ab6896 100644--- a/docs/user-guide/pwa.md+++ b/docs/user-guide/pwa.md@@ -76,6 +76,8 @@ Once the PWA is installed, Speakr appears in your phone's native share sheet. FrAccepted file types are the common audio formats plus the following video containers: `mp4`, `mov` (QuickTime), `mkv`, and `webm`.+Each account can share up to 20 files per hour this way (`SHARE_TARGET_RATE_LIMIT`, for example `50 per hour`). Uploads from the app are not counted.+!!! warning "Installed PWA only"Share-to-Speakr works only for the **installed PWA**, not a browser tab. If you installed the PWA before this feature shipped, reopen the app, then uninstall and reinstall it so Android registers the new share entry.diff --git a/src/api/recordings.py b/src/api/recordings.pyindex 6ccc06a6..890ac93e 100644--- a/src/api/recordings.py+++ b/src/api/recordings.py@@ -2114,6 +2114,21 @@ def delete_recording_audio(recording_id):return jsonify({'error': 'An unexpected error occurred.'}), 500+# Shares per signed-in user (#435): a forced share from another page cannot+# fill an account or queue paid transcriptions without bound.+try:+ from limits import parse as _parse_limit+ SHARE_TARGET_LIMIT = _parse_limit(os.environ.get('SHARE_TARGET_RATE_LIMIT', '20 per hour'))+except Exception:+ SHARE_TARGET_LIMIT = None+++def _share_target_allowed(user_id):+ if SHARE_TARGET_LIMIT is None or limiter is None or not getattr(limiter, 'enabled', True):+ return True+ return limiter.limiter.hit(SHARE_TARGET_LIMIT, 'share_target', str(user_id))++@recordings_bp.route('/share-target', methods=['POST', 'GET'])@login_requireddef share_target():@@ -2151,6 +2166,10 @@ def share_target():f"share-target POST from another site refused for user {current_user.id}")return redirect(url_for('recordings.index') + '?share_target_error=cross_site')+ if not _share_target_allowed(current_user.id):+ current_app.logger.warning(f"share-target rate limit reached for user {current_user.id}")+ return redirect(url_for('recordings.index') + '?share_target_error=rate_limited')+shared = request.files.get('shared_audio') or request.files.get('file')if not shared or not getattr(shared, 'filename', ''):return redirect(url_for('recordings.index') + '?share_target_error=missing_file')diff --git a/static/locales/de.json b/static/locales/de.jsonindex 35fa7225..ff239595 100644--- a/static/locales/de.json+++ b/static/locales/de.json@@ -945,7 +945,8 @@"validationError": "Validierungsfehler","waitAndRetryGuidance": "Einige Minuten warten und erneut versuchen","shareTarget_storage_quota": "Die geteilte Datei wurde nicht gespeichert, weil Ihr Speicher voll ist.",- "technicalDetails": "Technische Details"+ "technicalDetails": "Technische Details",+ "shareTarget_rate_limited": "In kurzer Zeit wurden zu viele Dateien geteilt. Bitte warten Sie, bevor Sie weitere teilen."},"eventExtraction": {"description": "Wenn aktiviert, identifiziert die KI Meetings, Termine und Fristen in Ihren Aufnahmen und erstellt herunterladbare Kalenderereignisse.",diff --git a/static/locales/en.json b/static/locales/en.jsonindex e7960240..7d6ec08a 100644--- a/static/locales/en.json+++ b/static/locales/en.json@@ -945,7 +945,8 @@"validationError": "Validation error","waitAndRetryGuidance": "Wait a few minutes and try again","shareTarget_storage_quota": "The shared file was not saved because your storage is full.",- "technicalDetails": "Technical details"+ "technicalDetails": "Technical details",+ "shareTarget_rate_limited": "Too many files were shared in a short time. Please wait before sharing more."},"eventExtraction": {"description": "When enabled, the AI will identify meetings, appointments, and deadlines mentioned in your recordings and create downloadable calendar events.",diff --git a/static/locales/es.json b/static/locales/es.jsonindex 4a5a3c4e..77992f29 100644--- a/static/locales/es.json+++ b/static/locales/es.json@@ -945,7 +945,8 @@"validationError": "Error de validación","waitAndRetryGuidance": "Espere unos minutos y vuelva a intentarlo","shareTarget_storage_quota": "El archivo compartido no se guardó porque su almacenamiento está lleno.",- "technicalDetails": "Detalles técnicos"+ "technicalDetails": "Detalles técnicos",+ "shareTarget_rate_limited": "Se compartieron demasiados archivos en poco tiempo. Espere antes de compartir más."},"eventExtraction": {"description": "Cuando está habilitado, la IA identificará reuniones, citas y plazos mencionados en tus grabaciones y creará eventos de calendario descargables.",diff --git a/static/locales/fr.json b/static/locales/fr.jsonindex 3addcf89..2c981ca4 100644--- a/static/locales/fr.json+++ b/static/locales/fr.json@@ -945,7 +945,8 @@"validationError": "Erreur de validation","waitAndRetryGuidance": "Patientez quelques minutes et réessayez","shareTarget_storage_quota": "Le fichier partagé n'a pas été enregistré, car votre stockage est plein.",- "technicalDetails": "Détails techniques"+ "technicalDetails": "Détails techniques",+ "shareTarget_rate_limited": "Trop de fichiers ont été partagés en peu de temps. Veuillez patienter avant d'en partager d'autres."},"eventExtraction": {"description": "Lorsqu'activé, l'IA identifiera les réunions, rendez-vous et échéances mentionnés dans vos enregistrements et créera des événements de calendrier téléchargeables.",diff --git a/static/locales/pt-BR.json b/static/locales/pt-BR.jsonindex ff621dbe..a86ffeaf 100644--- a/static/locales/pt-BR.json+++ b/static/locales/pt-BR.json@@ -945,7 +945,8 @@"validationError": "Erro de validação","waitAndRetryGuidance": "Aguarde alguns minutos e tente novamente","shareTarget_storage_quota": "O arquivo compartilhado não foi salvo porque seu armazenamento está cheio.",- "technicalDetails": "Detalhes técnicos"+ "technicalDetails": "Detalhes técnicos",+ "shareTarget_rate_limited": "Muitos arquivos foram compartilhados em pouco tempo. Aguarde antes de compartilhar mais."},"eventExtraction": {"description": "Quando ativado, a IA identificará reuniões, compromissos e prazos mencionados em suas gravações e criará eventos de calendário para inserir na agenda.",diff --git a/static/locales/ru.json b/static/locales/ru.jsonindex 7ace3c2f..eaac92d0 100644--- a/static/locales/ru.json+++ b/static/locales/ru.json@@ -945,7 +945,8 @@"validationError": "Ошибка проверки","waitAndRetryGuidance": "Подождите несколько минут и повторите","shareTarget_storage_quota": "Файл не сохранён, потому что хранилище заполнено.",- "technicalDetails": "Технические подробности"+ "technicalDetails": "Технические подробности",+ "shareTarget_rate_limited": "За короткое время отправлено слишком много файлов. Подождите, прежде чем отправлять ещё."},"eventExtraction": {"description": "При включении ИИ будет определять встречи, назначения и дедлайны, упомянутые в ваших записях, и создавать загружаемые календарные события.",diff --git a/static/locales/zh.json b/static/locales/zh.jsonindex 6b505b58..d90fc579 100644--- a/static/locales/zh.json+++ b/static/locales/zh.json@@ -945,7 +945,8 @@"validationError": "验证错误","waitAndRetryGuidance": "请等待几分钟后再重试","shareTarget_storage_quota": "由于存储已满,共享的文件未保存。",- "technicalDetails": "技术详情"+ "technicalDetails": "技术详情",+ "shareTarget_rate_limited": "短时间内分享的文件过多。请稍后再分享。"},"eventExtraction": {"description": "启用后,AI将识别录音中提到的会议、约会和截止日期,并创建可下载的日历事件。",diff --git a/tests/test_share_target.py b/tests/test_share_target.pyindex 37e0de6a..df3cbc5f 100644--- a/tests/test_share_target.py+++ b/tests/test_share_target.py@@ -258,3 +258,37 @@ if __name__ == "__main__":test_share_target_requires_login()test_share_target_is_csrf_exempt()print("All share-target tests passed.")+++def test_share_target_is_limited_per_user():+ """#435: shares are counted per signed-in user; another user is not affected."""+ from types import SimpleNamespace+ from limits import parse+ from limits.storage import MemoryStorage+ from limits.strategies import FixedWindowRateLimiter+ from src.api import recordings as rec_module+ with app.app_context():+ ids = [_setup_user(p).id for p in ("rl_first", "rl_second")]+ clients = []+ for uid in ids:+ client = app.test_client()+ with client.session_transaction() as sess:+ sess["_user_id"] = str(uid)+ sess["_fresh"] = True+ clients.append(client)+ # The suite runs with rate limiting off, so Flask-Limiter has no storage;+ # an enabled limiter with its own memory storage stands in for it.+ old_limiter, old_limit = rec_module.limiter, rec_module.SHARE_TARGET_LIMIT+ rec_module.limiter = SimpleNamespace(enabled=True, limiter=FixedWindowRateLimiter(MemoryStorage()))+ rec_module.SHARE_TARGET_LIMIT = parse("2 per hour")+ try:+ places = [clients[0].post("/share-target", data={}).headers["Location"] for _ in range(3)]+ assert "missing_file" in places[0] and "missing_file" in places[1]+ assert "share_target_error=rate_limited" in places[2]+ assert "missing_file" in clients[1].post("/share-target", data={}).headers["Location"]+ finally:+ rec_module.limiter, rec_module.SHARE_TARGET_LIMIT = old_limiter, old_limit+ with app.app_context():+ for uid in ids:+ db.session.delete(db.session.get(User, uid))+ db.session.commit()