From 2cc5135e46c2f8b94a587148b54e7d98dfeeac95 Mon Sep 17 00:00:00 2001 From: diffwireauto <330573775+diffwireauto@users.noreply.github.com> Date: Wed, 25 Nov 2026 23:34:18 -0500 Subject: [PATCH] feat(#1206): one log package for Share, Save and Send LogPackage gathers every log file and the Android exit traces, re-runs the redactor over each line oldest first (so logs written by earlier builds lose their passwords too), and adds manifest.json with the app version, commit, platform, OS and radio model, firmware and caps. Share and Save now hand over these redacted copies, never the files in the log folder. zip() is what Send to Offband will upload. archive moves from transitive to direct at the locked 4.0.9. Co-Authored-By: Claude Opus 5.5 --- lib/services/log_package.dart | 156 +++++++++++++++++++++++ lib/storage/scoping_inventory.dart | 3 + lib/utils/log_export.dart | 29 +++-- pubspec.lock | 2 +- pubspec.yaml | 1 + test/screens/app_only_settings_test.dart | 18 ++- test/services/log_package_test.dart | 114 +++++++++++++++++ 7 files changed, 306 insertions(+), 17 deletions(-) create mode 100644 lib/services/log_package.dart create mode 100644 test/services/log_package_test.dart diff --git a/lib/services/log_package.dart b/lib/services/log_package.dart new file mode 100644 index 00000000..72a7afc8 --- /dev/null +++ b/lib/services/log_package.dart @@ -0,0 +1,156 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:archive/archive.dart'; +import 'package:flutter/foundation.dart'; +import 'package:path_provider/path_provider.dart'; + +import '../connector/meshcore_connector.dart'; +import '../utils/app_logger.dart'; +import '../utils/build_info.dart'; +import '../utils/log_redactor.dart'; +import 'app_exit_info_service.dart'; +import 'file_log_service.dart'; + +/// The log package every send uses (#1192): every log file and Android exit +/// trace, with passwords and PINs removed, plus `manifest.json` naming the +/// build, platform and radio. Share/Save hands over these files; Send to +/// Offband zips them. +/// +/// Lines written before the redactor existed are redacted here too, so an +/// older rotated log cannot carry a password out. +class LogPackage { + LogPackage._(this.directory, this.files); + + static const String manifestName = 'manifest.json'; + static const String tracesDir = 'traces'; + + /// Holds the redacted copies. Delete with [delete] once sent. + final Directory directory; + + /// The manifest first, then the logs oldest first, then the traces. + final List files; + + /// [logs] is newest first, as [FileLogService.flushAndGetAllFiles] returns + /// them. Both lists default to what is on disk now. + static Future build({ + MeshCoreConnector? radio, + List? logs, + List? traces, + Directory? into, + DateTime Function() now = DateTime.now, + }) async { + final logFiles = + logs ?? await FileLogService.instance.flushAndGetAllFiles(); + final traceFiles = + traces ?? + (defaultTargetPlatform == TargetPlatform.android + ? await AppExitInfoService.traceFiles() + : const []); + final dir = into ?? await _freshTempDir(); + final sep = Platform.pathSeparator; + final redactor = LogRedactor(); + final written = []; + + for (final log in logFiles.reversed) { + if (!await log.exists()) continue; + final text = utf8.decode(await log.readAsBytes(), allowMalformed: true); + final redacted = const LineSplitter() + .convert(text) + .map(redactor.line) + .join('\n'); + final out = File('${dir.path}$sep${_name(log)}'); + await out.writeAsString('$redacted\n'); + written.add(out); + } + if (traceFiles.isNotEmpty) { + final traceDir = await Directory('${dir.path}$sep$tracesDir').create(); + for (final trace in traceFiles) { + if (!await trace.exists()) continue; + written.add(await trace.copy('${traceDir.path}$sep${_name(trace)}')); + } + } + + final manifest = File('${dir.path}$sep$manifestName'); + await manifest.writeAsString( + const JsonEncoder.withIndent(' ').convert( + manifestFor( + radio: radio, + createdAt: now(), + files: [for (final f in written) _relative(dir, f)], + ), + ), + ); + return LogPackage._(dir, [manifest, ...written]); + } + + static Map manifestFor({ + MeshCoreConnector? radio, + required DateTime createdAt, + required List files, + }) => { + 'format': 1, + 'createdAt': createdAt.toUtc().toIso8601String(), + 'app': appLogger.appVersion, + 'commit': BuildInfo.gitSha, + 'branch': BuildInfo.gitBranch, + 'buildTime': BuildInfo.buildTime, + 'platform': kIsWeb ? 'web' : defaultTargetPlatform.name, + 'os': kIsWeb ? null : Platform.operatingSystemVersion, + 'radio': radio == null + ? null + : { + 'connected': radio.isConnected, + 'transport': radio.activeTransport.name, + 'model': radio.deviceModel, + 'firmware': radio.firmwareVersion, + 'firmwareVerCode': radio.firmwareVerCode, + 'offbandCaps': radio.offbandCaps, + 'offbandCaps2': radio.offbandCaps2, + }, + 'files': files, + }; + + /// Every file, at its path inside the package, in one zip. + Future zip() async { + final archive = Archive(); + for (final f in files) { + archive.addFile( + ArchiveFile.bytes(_relative(directory, f), await f.readAsBytes()), + ); + } + return ZipEncoder().encodeBytes(archive); + } + + Future delete() async { + try { + await directory.delete(recursive: true); + } catch (e) { + appLogger.warn( + 'Removing ${directory.path} failed: $e', + tag: 'LogPackage', + ); + } + } + + /// A new temp folder, after removing the ones earlier packages left: a + /// share sheet reads its files after `share` returns, so they cannot be + /// removed straight after sending. + static Future _freshTempDir() async { + final temp = await getTemporaryDirectory(); + await for (final old in temp.list()) { + if (old is Directory && _name(old).startsWith(_tempPrefix)) { + await old.delete(recursive: true).catchError((_) => old); + } + } + return temp.createTemp(_tempPrefix); + } + + static const _tempPrefix = 'offband-logs-'; + + static String _name(FileSystemEntity f) => + f.uri.pathSegments.lastWhere((s) => s.isNotEmpty); + + static String _relative(Directory dir, File f) => + f.path.substring(dir.path.length + 1).replaceAll('\\', '/'); +} diff --git a/lib/storage/scoping_inventory.dart b/lib/storage/scoping_inventory.dart index 7235edf6..03032fc0 100644 --- a/lib/storage/scoping_inventory.dart +++ b/lib/storage/scoping_inventory.dart @@ -372,6 +372,9 @@ const List storageSurfaces = [ /// justified, instead of a new key slipping through because nobody looked. const Map nonStorageConstants = { 'offband_store': 'the drift database FILE name, not a key within it', + 'traces': + 'the folder inside a log package that holds Android exit traces ' + '(LogPackage, #1192). A path in a temp folder, not a key', '__all__': 'the sentinel value for "all groups" in the contacts filter ' '(UiViewStateService). A filter VALUE, not a key, and not persisted ' diff --git a/lib/utils/log_export.dart b/lib/utils/log_export.dart index 15961d26..4acede2d 100644 --- a/lib/utils/log_export.dart +++ b/lib/utils/log_export.dart @@ -3,12 +3,14 @@ import 'dart:io' show File; import 'package:file_selector/file_selector.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; import 'package:share_plus/share_plus.dart'; +import '../connector/meshcore_connector.dart'; import '../l10n/l10n.dart'; import '../services/app_debug_log_service.dart'; -import '../services/app_exit_info_service.dart'; import '../services/file_log_service.dart'; +import '../services/log_package.dart'; import 'app_logger.dart'; import 'log_web_download.dart'; @@ -86,6 +88,7 @@ class LogExport { // possibly-deactivated widget after the await. final messenger = ScaffoldMessenger.of(context); final l10n = context.l10n; + final radio = context.read(); final present = []; try { // On mobile, take every log file rather than just the active one, and @@ -94,6 +97,10 @@ class LogExport { // can rotate into `.1.log` before the user exports, which would hand // over a trace with its metadata line missing. Desktop keeps its // single-file Save As: there are no exit records off Android. + // + // Either way the files go through the log package (#1192), so what + // leaves the app has its passwords and PINs removed, including lines + // written by builds before the redactor. final List logs; if (_isMobile) { logs = await FileLogService.instance.flushAndGetAllFiles(); @@ -101,16 +108,16 @@ class LogExport { final active = await FileLogService.instance.flushAndGetActiveFile(); logs = active == null ? const [] : [active]; } - final candidates = [ - ...logs, - if (_isMobile) ...await AppExitInfoService.traceFiles(), - ]; - // Last-moment existence check. Rotation renames files underneath us and - // a trace can be pruned, so a path collected a moment ago may already be - // gone; handing a missing path to the share sheet fails the whole export - // rather than one attachment. - for (final f in candidates) { - if (await f.exists()) present.add(f); + final package = await LogPackage.build( + radio: radio, + logs: logs, + traces: _isMobile ? null : const [], + ); + final hasLog = package.files.length > 1; + if (hasLog) { + present.addAll( + _isMobile ? package.files : package.files.skip(1).take(1), + ); } } catch (e) { appLogger.error('Collecting log files failed: $e', tag: 'LogExport'); diff --git a/pubspec.lock b/pubspec.lock index cb564804..b39e0ebc 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -26,7 +26,7 @@ packages: source: hosted version: "12.1.0" archive: - dependency: transitive + dependency: "direct main" description: name: archive sha256: a96e8b390886ee8abb49b7bd3ac8df6f451c621619f52a26e815fdcf568959ff diff --git a/pubspec.yaml b/pubspec.yaml index fe2e5471..ff9b0571 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -67,6 +67,7 @@ dependencies: path_provider: ^2.1.6 share_plus: ^12.0.1 file_selector: ^1.0.3 # Native Save As dialog for log export on desktop (#433) + archive: ^4.0.9 # Zips the log package for Send to Offband (#1192) build_pipe: ^0.3.1 material_symbols_icons: ^4.2906.0 web: ^1.1.1 diff --git a/test/screens/app_only_settings_test.dart b/test/screens/app_only_settings_test.dart index 3af5e4ce..b98e4469 100644 --- a/test/screens/app_only_settings_test.dart +++ b/test/screens/app_only_settings_test.dart @@ -28,6 +28,7 @@ const _pathProvider = MethodChannel('plugins.flutter.io/path_provider'); const _share = MethodChannel('dev.fluttercommunity.plus/share'); late Directory _supportDir; +late Directory _tempDir; /// Every share the app asked the OS for, as the paths it handed over. final List> _shared = []; @@ -110,12 +111,14 @@ void main() { setUpAll(() async { _supportDir = Directory.systemTemp.createTempSync('offband_693_'); + _tempDir = Directory.systemTemp.createTempSync('offband_693_tmp_'); final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; messenger.setMockMethodCallHandler(_pathProvider, (call) async { if (call.method == 'getApplicationSupportDirectory') { return _supportDir.path; } + if (call.method == 'getTemporaryDirectory') return _tempDir.path; return null; }); messenger.setMockMethodCallHandler(_share, (call) async { @@ -131,6 +134,7 @@ void main() { tearDownAll(() async { await FileLogService.instance.dispose(); if (_supportDir.existsSync()) _supportDir.deleteSync(recursive: true); + if (_tempDir.existsSync()) _tempDir.deleteSync(recursive: true); }); setUp(() async { @@ -211,7 +215,7 @@ void main() { }); group('Share logs with no radio', () { - testWidgets('hands the on-disk log file to the share sheet', ( + testWidgets('hands the on-disk log, redacted, to the share sheet', ( tester, ) async { const marker = 'issue-693 marker line'; @@ -228,12 +232,16 @@ void main() { ); expect(_shared.length, sharesBefore + 1); - final logDir = FileLogService.instance.logDir!.path; final handedOver = _shared.last; - expect(handedOver, isNotEmpty); - expect(handedOver.first, startsWith(logDir)); + expect(handedOver.first, endsWith('manifest.json')); + // The share carries the log package's redacted copies (#1192), never + // the files in the log folder themselves. + final logDir = FileLogService.instance.logDir!.path; + expect(handedOver.where((p) => p.startsWith(logDir)), isEmpty); + final logs = handedOver.where((p) => p.endsWith('.log')).toList(); + expect(logs, isNotEmpty); final text = await tester.runAsync( - () => File(handedOver.first).readAsString(), + () async => [for (final p in logs) await File(p).readAsString()].join(), ); expect(text, contains(marker)); expect(find.text(l10n.debugLog_logUnavailable), findsNothing); diff --git a/test/services/log_package_test.dart b/test/services/log_package_test.dart new file mode 100644 index 00000000..4b291422 --- /dev/null +++ b/test/services/log_package_test.dart @@ -0,0 +1,114 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:archive/archive.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:meshcore_open/connector/cli_command_codec.dart'; +import 'package:meshcore_open/connector/meshcore_protocol.dart'; +import 'package:meshcore_open/services/log_package.dart'; +import 'package:meshcore_open/utils/log_redactor.dart'; + +final _peer = Uint8List.fromList(List.generate(32, (i) => 0xA0 + i)); + +String _hex(Uint8List f) => + f.map((b) => b.toRadixString(16).padLeft(2, '0')).join(' '); + +String _frameLine(String dir, String label, Uint8List f) => + '2026-11-25T10:00:00.000 $dir $label ${_hex(f)}'; + +void main() { + late Directory tmp; + setUp(() async => tmp = await Directory.systemTemp.createTemp('logpkg')); + tearDown(() async => tmp.delete(recursive: true)); + + Future write(String name, List lines) => + File('${tmp.path}/$name').writeAsString('${lines.join('\n')}\n'); + + test('lines written before the redactor lose their passwords', () async { + final login = _frameLine( + 'TX', + 'CMD_SEND_LOGIN', + buildSendLoginFrame(_peer, 'hunter2'), + ); + final get = _frameLine( + 'TX', + 'CODE_66', + buildRunCliCommandFrame('get guest.password', prefix: 'b2|'), + ); + final reply = _frameLine( + 'RX', + 'CODE_29', + Uint8List.fromList([respCodeCliReply, ...latin1.encode('b2|> secret')]), + ); + const late = + '2026-11-25T10:00:01.000 [WARN/RepeaterCommand] Late reply to ' + '"password hunter2" from abcd arrived 900ms after its window closed: ' + 'password now: hunter2'; + const ordinary = '2026-11-25T10:00:02.000 [INFO/App] connected'; + + final older = await write('offband.1.log', [login, get]); + final newer = await write('offband.log', [reply, late, ordinary]); + final out = await Directory('${tmp.path}/out').create(); + final package = await LogPackage.build( + logs: [newer, older], + traces: const [], + into: out, + ); + + final text = [ + for (final f in package.files.skip(1)) await f.readAsString(), + ].join(); + expect(text, isNot(contains(_hex(latin1.encode('hunter2'))))); + expect(text, isNot(contains('hunter2'))); + expect(text, isNot(contains(_hex(latin1.encode('secret'))))); + expect(text, contains(ordinary)); + expect(text, contains('password now: *******')); + expect(package.files.skip(1).map((f) => f.uri.pathSegments.last), [ + 'offband.1.log', + 'offband.log', + ]); + }); + + test('frame lines without secrets come out byte for byte', () { + final r = LogRedactor(); + final psk = Uint8List.fromList(List.generate(16, (i) => i)); + final line = _frameLine( + 'TX', + 'CMD_SET_CHANNEL', + buildSetChannelFrame(2, 'Ops', psk), + ); + expect(r.line(line), line); + final redacted = r.line( + _frameLine('TX', 'CMD_SEND_LOGIN', buildSendLoginFrame(_peer, 'x')), + ); + expect(r.line(redacted), redacted); + }); + + test('the manifest names the files, and the zip holds them all', () async { + final log = await write('offband.log', ['one']); + final trace = await write('anr-1.txt', ['trace']); + final out = await Directory('${tmp.path}/out').create(); + final package = await LogPackage.build( + logs: [log, File('${tmp.path}/gone.log')], + traces: [trace], + into: out, + now: () => DateTime.utc(2026, 11, 25, 12), + ); + + final manifest = + jsonDecode(await package.files.first.readAsString()) + as Map; + expect(manifest['format'], 1); + expect(manifest['createdAt'], '2026-11-25T12:00:00.000Z'); + expect(manifest['files'], ['offband.log', 'traces/anr-1.txt']); + expect(manifest.keys, containsAll(['app', 'commit', 'platform', 'os'])); + + final zip = ZipDecoder().decodeBytes(await package.zip()); + expect(zip.files.map((f) => f.name), [ + LogPackage.manifestName, + 'offband.log', + 'traces/anr-1.txt', + ]); + }); +}