Merge pull request #1504 from cypherstack/feat/camera-linux-hook
What changed, and why it matters
This change swaps the Linux QR-code camera backend from OpenCV to a custom V4L2 plugin and, in the Flatpak packaging, widens device access from graphics-only ('dri') to all devices ('all'). The broader Flatpak permission is a security-relevant change: it lets the app reach any USB or system device, not just the GPU, which is normally unnecessary for a wallet app and increases attack surface if the app or a bundled library is compromised. The rest of the patch is a routine refactor of camera initialization and frame handling.
Review whether --device=all is strictly required for V4L2 camera access; prefer the narrowest permission such as --device=video or a portal-based camera approach. Audit the new camera_linux plugin (ref 82e2d82188cc4676a02559118af110c8161b4eed) for memory safety and sandbox interaction, because it now runs native V4L2 code with broader device access. If the permission change is intentional, document the security trade-off in the Flatpak manifest or release notes.
Security signals we found
Flatpak sandbox permission widened from --device=dri to --device=all in three manifests
New camera plugin uses V4L2 directly and exposes frame/error streams to Dart
Removed OpenCV dependency reduces native C/C++ attack surface from a large library
Added explicit error handling for Linux camera lost events
No vendor statement or CVE references present in commit materials
Evidence from the diff
The commit replaces the OpenCV-based camera_linux dependency with a V4L2-based implementation (camera_linux ref ecb41247 -> 82e2d821, version 0.0.8 -> 0.1.0). It updates the QR scanner dialog to use the camera_platform_interface pattern (createCameraWithSettings, initializeCamera, onStreamedFrameAvailable, onCameraError, dispose) instead of polling captureImage(). Build docs and Docker remove libopencv-dev. The three Flatpak manifests change the finish-arg from –device=dri to –device=all, granting the sandbox access to all host devices rather than only direct rendering devices.
Changed components
Flatpak sandbox manifests (com.cypherstack.stackwallet.yaml, com.cypherstack.stackduo.yaml, com.cypherstack.campfire.yaml)lib/widgets/desktop/qr_code_scanner_dialog.dartcamera_linux git dependency (pubspec.lock, pubspec.template.yaml)Dockerfile and docs/building.md build dependency listsInspect captured patch +78 / −68
### Dockerfile
@@ -15,7 +15,6 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
clang libclang-dev llvm \
libgcrypt20-dev libgirepository1.0-dev libgit2-dev libglib2.0-dev libgtk-3-dev \
libjsoncpp-dev liblzma-dev libncurses5-dev libncursesw5-dev \
- libopencv-dev \
libsecret-1-dev libssl-dev libtss2-dev \
ocl-icd-opencl-dev opencl-headers valac zlib1g-dev \
g++-aarch64-linux-gnu gcc-aarch64-linux-gnu \
### docs/building.md
@@ -47,7 +47,7 @@ sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-
### Build dependencies
Install basic dependencies
```
-sudo apt-get install libssl-dev curl unzip automake build-essential file pkg-config git python3 libtool libtinfo6 cmake libgit2-dev clang libncurses5-dev libncursesw5-dev zlib1g-dev llvm lld g++ gcc gperf libopencv-dev python3-typogrify xsltproc valac gobject-introspection meson pipx libgcrypt20-dev libglib2.0-dev libsecret-1-dev
+sudo apt-get install libssl-dev curl unzip automake build-essential file pkg-config git python3 libtool libtinfo6 cmake libgit2-dev clang libncurses5-dev libncursesw5-dev zlib1g-dev llvm lld g++ gcc gperf python3-typogrify xsltproc valac gobject-introspection meson pipx libgcrypt20-dev libglib2.0-dev libsecret-1-dev
pipx install meson==0.64.1 markdown==3.4.1 markupsafe==2.1.1 jinja2==3.1.2 pygments==2.13.0 toml==0.10.2 typogrify==2.0.7 tomli==2.0.1
```
### flatpak/com.cypherstack.campfire.yaml
@@ -9,7 +9,7 @@ finish-args:
- --share=ipc
- --socket=fallback-x11
- --socket=wayland
- - --device=dri
+ - --device=all
- --filesystem=~/.campfire:create
- --talk-name=org.freedesktop.secrets
- --talk-name=org.freedesktop.Notifications
### flatpak/com.cypherstack.stackduo.yaml
@@ -9,7 +9,7 @@ finish-args:
- --share=ipc
- --socket=fallback-x11
- --socket=wayland
- - --device=dri
+ - --device=all
- --filesystem=~/.stackduo:create
- --talk-name=org.freedesktop.secrets
- --talk-name=org.freedesktop.Notifications
### flatpak/com.cypherstack.stackwallet.yaml
@@ -9,7 +9,7 @@ finish-args:
- --share=ipc
- --socket=fallback-x11
- --socket=wayland
- - --device=dri
+ - --device=all
- --filesystem=~/.stackwallet:create
- --talk-name=org.freedesktop.secrets
- --talk-name=org.freedesktop.Notifications
### lib/widgets/desktop/qr_code_scanner_dialog.dart
@@ -1,12 +1,11 @@
import 'dart:async';
-import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:camera_linux/camera_linux.dart';
-import 'package:camera_macos/camera_macos_arguments.dart';
+import 'package:camera_macos/camera_macos_arguments.dart' hide CameraImageData;
import 'package:camera_macos/camera_macos_device.dart';
import 'package:camera_macos/camera_macos_platform_interface.dart';
import 'package:camera_platform_interface/camera_platform_interface.dart';
@@ -36,9 +35,13 @@ class QrCodeScannerDialog extends StatefulWidget {
}
class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
- // Created in _initializeCamera: the constructor loads libcamera_linux.so
- // and throws if it can't.
+ // Created in _initializeCamera. camera_linux implements the camera platform
+ // interface; its image stream delivers JPEG frames and the scan loop takes
+ // the newest one.
CameraLinux? _cameraLinuxPlugin;
+ StreamSubscription<CameraImageData>? _linuxFrameSub;
+ StreamSubscription<CameraErrorEvent>? _linuxErrorSub;
+ Uint8List? _latestLinuxFrame;
final CameraWindows? _cameraWindowsPlugin = Platform.isWindows
? CameraWindows()
: null;
@@ -47,7 +50,7 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
bool _isScanning = false;
int _cameraId = -1;
String? _macOSDeviceId;
- final int _imageDelayInMs = Platform.isLinux ? 500 : 250;
+ final int _imageDelayInMs = 250;
int _consecutiveFailures = 0;
// Time since the last usable frame, to notice a camera that opened but
// stopped (or never started) returning images.
@@ -67,7 +70,7 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
// frame from a repeat; the error event tells us the camera is gone at once.
int? _lastWindowsFrameFingerprint;
bool _loggedRepeatedWindowsFrame = false;
- bool _windowsCameraLost = false;
+ bool _cameraLost = false;
StreamSubscription<CameraErrorEvent>? _windowsErrorSub;
bool _cameraStopped = false;
@@ -98,16 +101,44 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
try {
if (Platform.isLinux) {
final plugin = _cameraLinuxPlugin = CameraLinux();
- // This only starts a capture thread. If OpenCV can't open a camera
- // the thread just exits, and captureImage() keeps returning nothing,
- // so wait for a first frame before calling the camera open.
- await plugin.initializeCamera();
- if (!await _waitForFirstLinuxFrame(plugin)) {
- plugin.stopCamera();
- if (!mounted) return false;
- throw TimeoutException("No image from the camera", _frameTimeout);
+ final List<CameraDescription> cameras = await plugin.availableCameras();
+ if (cameras.isEmpty) {
+ throw CameraException('No cameras available', 'No cameras found.');
+ }
+ Logging.instance.d(
+ "Linux cameras: ${cameras.map((c) => c.name).toList()}",
+ );
+ // 640x480. low is 320x240 on Linux, too small for QR codes.
+ _cameraId = await plugin.createCameraWithSettings(
+ cameras.first,
+ const MediaSettings(
+ resolutionPreset: ResolutionPreset.medium,
+ enableAudio: false,
+ ),
+ );
+ // Throws a CameraException with the driver's reason when the device
+ // can't be opened. A camera that opens but never delivers a frame is
+ // caught by the frame timeout in the scan loop.
+ await plugin.initializeCamera(_cameraId);
+ if (!mounted) {
+ await plugin.dispose(_cameraId);
+ return false;
}
- Logging.instance.d("Linux Camera initialized");
+ _linuxErrorSub = plugin
+ .onCameraError(_cameraId)
+ .listen((e) => _onCameraLost(e.description));
+ // A capture failure is reported on the frame stream as well as
+ // through onCameraError, so it needs a handler here too or it escapes
+ // as an uncaught error. _onCameraLost ignores the second report.
+ _linuxFrameSub = plugin
+ .onStreamedFrameAvailable(_cameraId)
+ .listen(
+ (frame) => _latestLinuxFrame = frame.planes.first.bytes,
+ onError: (Object e) => _onCameraLost(
+ e is CameraException ? (e.description ?? e.code) : "$e",
+ ),
+ );
+ Logging.instance.d("Linux camera initialized with ID: $_cameraId");
} else if (Platform.isWindows && _cameraWindowsPlugin != null) {
final List<CameraDescription> cameras = await _cameraWindowsPlugin
.availableCameras();
@@ -183,7 +214,7 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
// the error event is the one that matters.
_windowsErrorSub = _cameraWindowsPlugin
.onCameraError(_cameraId)
- .listen((e) => _onWindowsCameraLost(e.description));
+ .listen((e) => _onCameraLost(e.description));
Logging.instance.d(
"Windows Camera initialized with ID: $_cameraId, "
"preview $_windowsPreviewSize",
@@ -218,29 +249,6 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
}
}
- /// Polls [plugin] until it returns a frame. Returns false on timeout or if
- /// the dialog closes first.
- Future<bool> _waitForFirstLinuxFrame(CameraLinux plugin) async {
- final stopwatch = Stopwatch()..start();
- Object? lastError;
- while (mounted && stopwatch.elapsed < _frameTimeout) {
- try {
- if ((await plugin.captureImage()).isNotEmpty) {
- return true;
- }
- } catch (e) {
- // captureImage() can throw on the null pointer it gets when there is
- // no frame yet.
- lastError = e;
- }
- await Future<void>.delayed(const Duration(milliseconds: 250));
- }
- if (lastError != null) {
- Logging.instance.w("No frame from Linux camera", error: lastError);
- }
- return false;
- }
-
/// Shows an error once no new frame has arrived for [_frameTimeout].
void _checkFrameTimeout() {
if (_sinceLastFrame.elapsed >= _frameTimeout &&
@@ -254,16 +262,17 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
}
}
- /// The plugin reported a capture engine error. Its preview keeps the last
- /// frame and it never restarts the stream, so stop scanning and say so now
- /// rather than waiting for the frame timeout.
- void _onWindowsCameraLost(String description) {
- // The engine can report one failure several times, and an event already
+ /// The plugin reported a capture error (Windows: the capture engine failed
+ /// and keeps showing the last frame; Linux: the device went away). Neither
+ /// restarts the stream, so stop scanning and say so now rather than waiting
+ /// for the frame timeout.
+ void _onCameraLost(String description) {
+ // An engine can report one failure several times, and an event already
// queued can still arrive after the dialog started closing.
- if (_windowsCameraLost || !_isScanning) return;
- _windowsCameraLost = true;
+ if (_cameraLost || !_isScanning) return;
+ _cameraLost = true;
_isScanning = false;
- Logging.instance.w("Windows camera error: $description");
+ Logging.instance.w("Camera error: $description");
// FormatMessage text ends in ".\r\n", and unknown errors come through
// empty.
final detail = description.trim().replaceFirst(RegExp(r"\.$"), "");
@@ -286,8 +295,12 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
try {
if (Platform.isLinux && _cameraLinuxPlugin != null) {
- _cameraLinuxPlugin!.stopCamera();
- Logging.instance.d("Linux Camera stopped");
+ await _linuxFrameSub?.cancel();
+ _linuxFrameSub = null;
+ await _linuxErrorSub?.cancel();
+ _linuxErrorSub = null;
+ await _cameraLinuxPlugin!.dispose(_cameraId);
+ Logging.instance.d("Linux camera stopped with ID: $_cameraId");
} else if (Platform.isWindows && _cameraWindowsPlugin != null) {
await _windowsErrorSub?.cancel();
_windowsErrorSub = null;
@@ -407,10 +420,12 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
_sinceLastFrame.start();
while (_isScanning) {
try {
- String? base64Image;
+ Uint8List? imageBytes;
img.Image? windowsFrame;
if (Platform.isLinux && _cameraLinuxPlugin != null) {
- base64Image = await _cameraLinuxPlugin!.captureImage();
+ // The newest frame from the image stream, or nothing new yet.
+ imageBytes = _latestLinuxFrame;
+ _latestLinuxFrame = null;
} else if (Platform.isWindows) {
windowsFrame = await _captureWindowsPreviewFrame();
} else if (Platform.isMacOS) {
@@ -428,19 +443,18 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
_checkFrameTimeout();
continue;
}
- base64Image = base64Encode(img.encodePng(image));
+ imageBytes = img.encodePng(image);
}
if (windowsFrame == null &&
- (base64Image == null || base64Image.isEmpty)) {
+ (imageBytes == null || imageBytes.isEmpty)) {
// Logging.instance
// .log("Failed to capture image", level: LogLevel.Error);
// Spammy.
await Future<void>.delayed(Duration(milliseconds: _imageDelayInMs));
_checkFrameTimeout();
continue;
}
- final img.Image? image =
- windowsFrame ?? img.decodeImage(base64Decode(base64Image!));
+ final img.Image? image = windowsFrame ?? img.decodeImage(imageBytes!);
// TODO [prio=low]: Optimize this process. Docs say:
// > WARNING Since this will check the image data against all known
// > decoders, it is much slower than using an explicit decoder
@@ -458,10 +472,7 @@ class _QrCodeScannerDialogState extends State<QrCodeScannerDialog> {
_cameraError = null;
// Windows already shows the live preview.
if (windowsFrame == null) {
- _image = Image.memory(
- base64Decode(base64Image!),
- fit: BoxFit.cover,
- );
+ _image = Image.memory(imageBytes!, fit: BoxFit.cover);
} else {
_hasWindowsFrame = true;
}
### pubspec.lock
@@ -227,11 +227,11 @@ packages:
dependency: "direct main"
description:
path: "."
- ref: ecb412474c5d240347b04ac1eb9f019802ff7034
- resolved-ref: ecb412474c5d240347b04ac1eb9f019802ff7034
+ ref: "82e2d82188cc4676a02559118af110c8161b4eed"
+ resolved-ref: "82e2d82188cc4676a02559118af110c8161b4eed"
url: "https://github.com/cypherstack/camera-linux"
source: git
- version: "0.0.8"
+ version: "0.1.0"
camera_macos:
dependency: "direct main"
description:
### scripts/app_config/templates/pubspec.template.yaml
@@ -243,7 +243,7 @@ dependencies:
camera_linux:
git:
url: https://github.com/cypherstack/camera-linux
- ref: ecb412474c5d240347b04ac1eb9f019802ff7034
+ ref: 82e2d82188cc4676a02559118af110c8161b4eed
zxing2: ^0.2.3
camera_windows: ^0.3.0+1
camera_platform_interface: ^2.8.0Why this scored 38/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.