Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Harden incognito privacy: keep PRESERVE_TEMP_AUDIO debug copies out of the incognito path, log/name incognito temp files by extension only (no user filenames), and carry the incognito flag through crash recovery so recovered recordings stay incognito

Murtaza Nasir8aa9b201f77a
diff --git a/src/api/recordings.py b/src/api/recordings.py
index b9a635d5..032859f6 100644
--- a/src/api/recordings.py
+++ b/src/api/recordings.py
@@ -2957,8 +2957,11 @@ def upload_incognito():
'max_size_mb': float(effective_limit_mb),
}), 413
- # Save to temp file - use secure temp directory
- with tempfile.NamedTemporaryFile(delete=False, suffix=f'_{safe_filename}') as tmp:
+ # Save to temp file - use secure temp directory. Suffix carries only
+ # the extension, not the user's filename: the temp path is logged and
+ # filenames can themselves be sensitive (no PHI in logs or paths).
+ _ext = os.path.splitext(safe_filename)[1].lower() or '.audio'
+ with tempfile.NamedTemporaryFile(delete=False, suffix=_ext) as tmp:
temp_filepath = tmp.name
file.save(temp_filepath)
current_app.logger.info(f"[Incognito] Temp file saved: {temp_filepath}")
@@ -2982,9 +2985,11 @@ def upload_incognito():
except (ValueError, TypeError):
max_speakers = None
- # Log only metadata - NEVER log content for HIPAA compliance
+ # Log only metadata - NEVER log content for HIPAA compliance. The
+ # user's filename is deliberately excluded too (extension only):
+ # filenames routinely contain names/dates and count as PHI.
current_app.logger.info(f"[Incognito] Processing request from user {current_user.id}: "
- f"filename={original_filename}, size={file_size/1024/1024:.2f}MB, "
+ f"ext={_ext}, size={file_size/1024/1024:.2f}MB, "
f"language={language}, auto_summarize={auto_summarize}")
# Perform transcription synchronously (no database operations)
diff --git a/src/tasks/processing.py b/src/tasks/processing.py
index c44bcc98..23fea348 100644
--- a/src/tasks/processing.py
+++ b/src/tasks/processing.py
@@ -2428,12 +2428,18 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speaker
connector_name = type(connector).__name__
current_app.logger.info(f"[Incognito] Using transcription connector: {connector_name}")
- # Determine mime type
+ # Determine mime type from the real filename, but use an anonymized
+ # name (extension only) everywhere downstream: the shared conversion
+ # utilities and connectors log the filename they are given, and user
+ # filenames can themselves be sensitive (HIPAA guidance: no PHI in
+ # logs — "jane-doe-session-3.mp3" is PHI even if the audio never is).
mime_type = mimetypes.guess_type(original_filename)[0] or 'audio/mpeg'
+ _anon_ext = os.path.splitext(original_filename)[1].lower() or '.audio'
+ anon_filename = f"incognito{_anon_ext}"
# Handle video extraction if needed
actual_filepath = filepath
- actual_filename = original_filename
+ actual_filename = anon_filename
actual_content_type = mime_type
# Check if file is video and needs audio extraction
@@ -2454,7 +2460,10 @@ def transcribe_incognito(filepath, original_filename, language=None, min_speaker
else:
current_app.logger.info(f"[Incognito] Video detected, extracting audio...")
try:
- audio_filepath, audio_mime_type = extract_audio_from_video(filepath, cleanup_original=False)
+ # allow_debug_copy=False: the PRESERVE_TEMP_AUDIO debug copy
+ # is untracked by incognito cleanup and would retain audio.
+ audio_filepath, audio_mime_type = extract_audio_from_video(
+ filepath, cleanup_original=False, allow_debug_copy=False)
actual_filepath = audio_filepath
actual_content_type = audio_mime_type
actual_filename = os.path.basename(audio_filepath)
diff --git a/src/utils/ffmpeg_utils.py b/src/utils/ffmpeg_utils.py
index 01f70c8e..c904df33 100644
--- a/src/utils/ffmpeg_utils.py
+++ b/src/utils/ffmpeg_utils.py
@@ -85,11 +85,12 @@ def extract_audio_from_video(
output_format: str = 'mp3',
bitrate: str = DEFAULT_MP3_BITRATE,
cleanup_original: bool = True,
- copy_stream: bool = False
+ copy_stream: bool = False,
+ allow_debug_copy: bool = True
) -> Tuple[str, str]:
"""
Extract audio track from video file.
-
+
Args:
video_path: Path to video file
output_format: Audio format ('mp3', 'wav', 'flac', 'copy')
@@ -97,10 +98,14 @@ def extract_audio_from_video(
cleanup_original: Whether to delete the original video file
copy_stream: If True, copy audio stream without re-encoding (fast, preserves quality)
If False, re-encode to specified format
-
+ allow_debug_copy: Whether the PRESERVE_TEMP_AUDIO debug copy is permitted.
+ Incognito processing passes False — that debug copy is not
+ tracked by any cleanup and would silently retain audio from
+ a flow that promises zero retention.
+
Returns:
Tuple of (audio_filepath, mime_type)
-
+
Raises:
FFmpegNotFoundError: If FFmpeg is not installed
FFmpegError: If extraction fails
@@ -230,7 +235,7 @@ def extract_audio_from_video(
_run_ffmpeg_command(cmd, f"Audio extraction from {os.path.basename(video_path)}")
# Optionally preserve temp file for debugging
- if os.getenv('PRESERVE_TEMP_AUDIO', 'false').lower() == 'true':
+ if allow_debug_copy and os.getenv('PRESERVE_TEMP_AUDIO', 'false').lower() == 'true':
import shutil
debug_path = temp_audio_path.replace('_temp', '_debug')
shutil.copy2(temp_audio_path, debug_path)
diff --git a/static/js/modules/composables/audio.js b/static/js/modules/composables/audio.js
index ee4e4693..12c72b61 100644
--- a/static/js/modules/composables/audio.js
+++ b/static/js/modules/composables/audio.js
@@ -717,7 +717,8 @@ export function useAudio(state, utils) {
min_speakers: asrMinSpeakers.value || '',
max_speakers: asrMaxSpeakers.value || ''
},
- mimeType
+ mimeType,
+ incognito: !!(incognitoMode && incognitoMode.value)
});
} catch (dbError) {
console.warn('[Recording] IndexedDB persistence failed, continuing without persistence:', dbError);
@@ -1530,6 +1531,13 @@ export function useAudio(state, utils) {
asrMaxSpeakers.value = recovered.metadata.asrOptions.max_speakers || '';
}
+ // Restore the incognito state the recording was left in, so a
+ // crashed incognito recording is offered back as incognito instead
+ // of silently becoming a normal (permanently stored) one.
+ if (incognitoMode && enableIncognitoMode && enableIncognitoMode.value) {
+ incognitoMode.value = !!recovered.metadata.incognito;
+ }
+
console.log('[Recording] Successfully recovered recording from IndexedDB');
return recovered.metadata;
} catch (error) {
@@ -1543,6 +1551,17 @@ export function useAudio(state, utils) {
// Placeholder for future initialization if needed
};
+ // Keep the crash-recovery session's incognito flag in sync with the
+ // toggle. It can be flipped in the review pane after recording stops
+ // (and the modal toggle can flip it with no session — then this is a
+ // harmless no-op), so a crash after the flip still recovers into the
+ // mode the user last chose.
+ if (typeof Vue !== 'undefined' && Vue.watch && incognitoMode) {
+ Vue.watch(incognitoMode, (v) => {
+ RecordingDB.updateRecordingMetadata({ incognito: !!v });
+ });
+ }
+
return {
startRecording,
stopRecording,
diff --git a/static/js/modules/db/recording-persistence.js b/static/js/modules/db/recording-persistence.js
index 8cd81c8e..6b315078 100644
--- a/static/js/modules/db/recording-persistence.js
+++ b/static/js/modules/db/recording-persistence.js
@@ -74,7 +74,11 @@ export const startRecordingSession = async (recordingData) => {
asrOptions: recordingData.asrOptions || {},
chunks: [],
mimeType: recordingData.mimeType || 'audio/webm',
- duration: 0
+ duration: 0,
+ // Incognito state travels with the crash-recovery copy so a
+ // recovered recording reopens in the same mode instead of
+ // silently becoming a normal (permanently stored) one.
+ incognito: !!recordingData.incognito
};
await promisifyRequest(objectStore.put(session));
@@ -250,7 +254,8 @@ export const recoverRecording = async () => {
asrOptions: session.asrOptions,
mimeType: session.mimeType,
duration: session.duration || (session.chunks.length * 5),
- startTime: session.startTime
+ startTime: session.startTime,
+ incognito: !!session.incognito
}
};
} catch (error) {
diff --git a/tests/test_video_passthrough.py b/tests/test_video_passthrough.py
index 1f317427..1e4ebce9 100644
--- a/tests/test_video_passthrough.py
+++ b/tests/test_video_passthrough.py
@@ -275,8 +275,11 @@ class TestIncognitoPassthrough(unittest.TestCase):
self.assertNotIn('VIDEO_RETENTION', PROCESSING_INCOGNITO)
def test_incognito_still_extracts_without_passthrough(self):
- """Without passthrough, incognito still extracts audio from video."""
- self.assertIn('extract_audio_from_video(filepath, cleanup_original=False)',
+ """Without passthrough, incognito still extracts audio from video.
+ allow_debug_copy=False keeps the PRESERVE_TEMP_AUDIO debug copy out
+ of the zero-retention incognito path."""
+ self.assertIn('extract_audio_from_video(', PROCESSING_INCOGNITO)
+ self.assertIn('filepath, cleanup_original=False, allow_debug_copy=False)',
PROCESSING_INCOGNITO)
def test_incognito_still_converts_without_passthrough(self):