mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-24 21:45:20 +00:00
* Quality pass on the 1.7.0 batch: fix confirmed bugs, bump to 1.7.1 Post-merge review of PRs #1400–#1417 (push-to-talk, mesh bridging, DM store-and-forward, empty-mesh liveliness, geo-notes). Fixes the confirmed, well-scoped findings; deeper architectural/security items are tracked separately. - PTT hot-mic leak: releasing the mic during VoiceCaptureSession.start()'s 150ms retry pause left the mic live and streaming for up to 120s, because cancel() no-op'd once `completed` was set. Bail after the sleep if the hold was released, and make cancel() always tear down a late-started capture. - Bridge courier depositDrop reported success and burned the dedup slot before the drop was actually published (evicted/compose-fail = lying 📦 "carried" with no retry). Only consume publishedDropKeys on durable accept; add BoundedIDSet.remove() to release evicted/failed slots (uses the dead dedupKey). - Blocked senders resurfaced via archived "heard here earlier" echoes, the one path that bypassed the live block filter — filter at seed time. - A late optimistic .sent clobbered the router's .carried state; extend ConversationStore.shouldSkipStatusUpdate to a full precedence guard (sending < sent < carried < delivered < read). - Read receipts were permanently burned when the router dropped them (marked sent then dropped). sendReadReceipt/routeReadReceipt now return Bool; only record as sent on a successful route, else retry on the next read scan. - MessageRouter.cleanupExpiredMessages() had no production caller, so DMs to a peer that never reconnects sat on .sending until relaunch — run it in the 120s bridge sweep. - Sightings tally now rolls over at midnight while idle; wave notification action localized across all 29 locales; bridged anon#tag uses suffix(4) like everything else; makeThrowawayIdentity delegates to NostrIdentity.generate(); .swiftlint.yml excludes .claude worktrees. - Add regression tests: carried→sent no-downgrade, carried→delivered upgrade, evicted pending drop stays retryable. - Bump MARKETING_VERSION to 1.7.1. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * Fix CI: adjust delivery-status benchmark and drop now-dead addSystemMessage The stricter no-downgrade guard (delivered/carried never regress to sent) broke two things the earlier commit didn't catch locally (perf tests are skipped in the default run, and Periphery runs only in CI): - PerformanceBaselineTests delivery benchmarks alternated sent <-> delivered assuming both directions apply; the delivered -> sent half is now correctly skipped, so the pass measured 0 updates. Alternate two delivered timestamps instead — every update is real, no downgrade. - Routing the geoDM "not in a location channel" error into the thread removed the only caller of ChatPrivateConversationContext.addSystemMessage, leaving it (and its mock) dead per Periphery. Drop the protocol requirement, the mock impl, and the now-vacuous systemMessages.isEmpty assertions (the invariant is compile-time enforced: the context can no longer emit a public system line). Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * Address review findings: read-receipt dedup, carried-vs-sending, block-time echo purge - Read receipts: claim the receipt in sentReadReceipts synchronously before spawning the routing task (chat open runs two read scans in one MainActor stretch, so the async insert let every unread message route twice), and release the claim when the route fails so the retry-on-failed-route behavior is preserved. - Delivery status: extend the no-downgrade guard so the `.sending` stamp a pre-handshake resend emits can no longer clobber carried/delivered/read (the 📦 indicator survived `.sent` but not `.sending`). - Archived echoes: blocking a peer now purges their carried public messages from the gossip archive at block time (UnifiedPeerService and /block), while the fingerprint-to-peerID mapping is still known — the seed-time filter can't resolve offline non-favorite strangers and stays only as defense-in-depth. New Transport hook (default no-op) + GossipSyncManager.removePublicMessages with immediate persist. - Bridge courier: an envelope that can't encode within the drop size caps fails identically on every attempt; consume the dedup slot so the 120s retry sweep stops re-running Noise sealing on it. - MeshSightingsTracker: cache the day-key DateFormatter instead of building one per call. Tests: double-markAsRead dedup + failed-route retry, carried→sending no-downgrade matrix, block-time purge (manager + service wiring), oversize-drop slot consumption. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Also skip the sent→sending downgrade in the delivery-status guard Codex review follow-up: sendPrivateMessage without an established Noise session emits `.sending` asynchronously, so it can land after the message already reached `.sent` and visibly walk "Sent" back to "Sending...". Treat `.sending` as weaker than `.sent` too — the status was already truthful. `.failed` → `.sending` stays allowed so a retry after a real failure remains visible. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Retain Codable properties in Periphery scan (same fix as #1421) The noiseKey assign-only false positive fired persistently on this branch (twice, including a rerun) despite the baselined USR. Byte-identical to the fix on fix/announce-replay-link-steal so the branches merge cleanly in either order. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
278 lines
10 KiB
Swift
278 lines
10 KiB
Swift
//
|
|
// SecureLogger.swift
|
|
// BitLogger
|
|
//
|
|
// This is free and unencumbered software released into the public domain.
|
|
// For more information, see <https://unlicense.org>
|
|
//
|
|
|
|
import Foundation
|
|
#if canImport(os.log)
|
|
import os.log
|
|
#else
|
|
public struct OSLog {
|
|
public let subsystem: String
|
|
public let category: String
|
|
|
|
public init(subsystem: String, category: String) {
|
|
self.subsystem = subsystem
|
|
self.category = category
|
|
}
|
|
}
|
|
|
|
public struct OSLogType: CustomStringConvertible {
|
|
private let label: String
|
|
|
|
private init(_ label: String) {
|
|
self.label = label
|
|
}
|
|
|
|
public var description: String { label }
|
|
|
|
public static let debug = OSLogType("debug")
|
|
public static let info = OSLogType("info")
|
|
public static let `default` = OSLogType("default")
|
|
public static let error = OSLogType("error")
|
|
public static let fault = OSLogType("fault")
|
|
}
|
|
|
|
@usableFromInline
|
|
let secureLoggerFallbackFormatter: ISO8601DateFormatter = {
|
|
let formatter = ISO8601DateFormatter()
|
|
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
|
return formatter
|
|
}()
|
|
|
|
@usableFromInline
|
|
func os_log(_ message: StaticString, log: OSLog, type: OSLogType, _ args: CVarArg...) {
|
|
let rawFormat = String(describing: message)
|
|
let format = rawFormat
|
|
.replacingOccurrences(of: "%{public}@", with: "%@")
|
|
.replacingOccurrences(of: "%{private}@", with: "%@")
|
|
let formatted = String(format: format, arguments: args)
|
|
let timestamp = secureLoggerFallbackFormatter.string(from: Date())
|
|
print("[\(timestamp)] [\(log.subsystem)::\(log.category)] [\(type.description)] \(formatted)")
|
|
}
|
|
#endif
|
|
|
|
/// Centralized security-aware logging framework
|
|
/// Provides safe logging that filters sensitive data and security events
|
|
public final class SecureLogger {
|
|
|
|
// MARK: - Timestamp Formatter
|
|
|
|
private static let timestampFormatter: DateFormatter = {
|
|
let formatter = DateFormatter()
|
|
formatter.dateFormat = "HH:mm:ss.SSS"
|
|
formatter.timeZone = TimeZone.current
|
|
return formatter
|
|
}()
|
|
|
|
// MARK: - Log Levels
|
|
|
|
enum LogLevel {
|
|
case debug
|
|
case info
|
|
case warning
|
|
case error
|
|
case fault
|
|
|
|
fileprivate var order: Int {
|
|
switch self {
|
|
case .debug: return 0
|
|
case .info: return 1
|
|
case .warning: return 2
|
|
case .error: return 3
|
|
case .fault: return 4
|
|
}
|
|
}
|
|
|
|
var osLogType: OSLogType {
|
|
switch self {
|
|
case .debug: return .debug
|
|
case .info: return .info
|
|
case .warning: return .default
|
|
case .error: return .error
|
|
case .fault: return .fault
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Global Threshold
|
|
|
|
/// Minimum level that will be logged. Defaults to .info. Override via env BITCHAT_LOG_LEVEL.
|
|
/// Internal-settable so tests can verify level filtering; app code should not mutate it.
|
|
internal static var minimumLevel: LogLevel = {
|
|
let env = ProcessInfo.processInfo.environment["BITCHAT_LOG_LEVEL"]?.lowercased()
|
|
switch env {
|
|
case "debug": return .debug
|
|
case "warning": return .warning
|
|
case "error": return .error
|
|
case "fault": return .fault
|
|
default: return .info
|
|
}
|
|
}()
|
|
|
|
private static func shouldLog(_ level: LogLevel) -> Bool {
|
|
return level.order >= minimumLevel.order
|
|
}
|
|
}
|
|
|
|
// MARK: - Public Logging Methods
|
|
|
|
public extension SecureLogger {
|
|
|
|
// Each wrapper checks the level BEFORE evaluating the autoclosure so
|
|
// filtered messages never pay for string interpolation — this matters on
|
|
// hot paths that log per packet/event. Debug compiles out of release
|
|
// builds entirely (the core log() drops .debug there anyway).
|
|
static func debug(_ message: @autoclosure () -> String, category: OSLog = .noise,
|
|
file: String = #file, line: Int = #line, function: String = #function) {
|
|
#if DEBUG
|
|
guard shouldLog(.debug) else { return }
|
|
log(message(), category: category, level: .debug, file: file, line: line, function: function)
|
|
#endif
|
|
}
|
|
|
|
static func info(_ message: @autoclosure () -> String, category: OSLog = .noise,
|
|
file: String = #file, line: Int = #line, function: String = #function) {
|
|
#if DEBUG
|
|
guard shouldLog(.info) else { return }
|
|
log(message(), category: category, level: .info, file: file, line: line, function: function)
|
|
#endif
|
|
}
|
|
|
|
static func warning(_ message: @autoclosure () -> String, category: OSLog = .noise,
|
|
file: String = #file, line: Int = #line, function: String = #function) {
|
|
#if DEBUG
|
|
guard shouldLog(.warning) else { return }
|
|
log(message(), category: category, level: .warning, file: file, line: line, function: function)
|
|
#endif
|
|
}
|
|
|
|
static func error(_ message: @autoclosure () -> String, category: OSLog = .noise,
|
|
file: String = #file, line: Int = #line, function: String = #function) {
|
|
#if DEBUG
|
|
guard shouldLog(.error) else { return }
|
|
log(message(), category: category, level: .error, file: file, line: line, function: function)
|
|
#endif
|
|
}
|
|
|
|
/// Log errors with context
|
|
static func error(_ error: Error, context: @autoclosure () -> String, category: OSLog = .noise,
|
|
file: String = #file, line: Int = #line, function: String = #function) {
|
|
#if DEBUG
|
|
let location = formatLocation(file: file, line: line, function: function)
|
|
let sanitized = context().sanitized()
|
|
let errorDesc = error.localizedDescription.sanitized()
|
|
|
|
#if DEBUG
|
|
os_log("%{public}@ Error in %{public}@: %{public}@", log: category, type: .error, location, sanitized, errorDesc)
|
|
#else
|
|
os_log("%{private}@ Error in %{private}@: %{private}@", log: category, type: .error, location, sanitized, errorDesc)
|
|
#endif
|
|
#endif
|
|
}
|
|
}
|
|
|
|
// MARK: Security Event Logging
|
|
|
|
public extension SecureLogger {
|
|
|
|
enum SecurityEvent {
|
|
case handshakeStarted(peerID: String)
|
|
case handshakeCompleted(peerID: String)
|
|
case handshakeFailed(peerID: String, error: String)
|
|
case sessionExpired(peerID: String)
|
|
case authenticationFailed(peerID: String)
|
|
|
|
var message: String {
|
|
switch self {
|
|
case .handshakeStarted(let peerID):
|
|
return "Handshake started with peer: \(peerID.sanitized())"
|
|
case .handshakeCompleted(let peerID):
|
|
return "Handshake completed with peer: \(peerID.sanitized())"
|
|
case .handshakeFailed(let peerID, let error):
|
|
return "Handshake failed with peer: \(peerID.sanitized()), error: \(error)"
|
|
case .sessionExpired(let peerID):
|
|
return "Session expired for peer: \(peerID.sanitized())"
|
|
case .authenticationFailed(let peerID):
|
|
return "Authentication failed for peer: \(peerID.sanitized())"
|
|
}
|
|
}
|
|
}
|
|
|
|
static func info(_ event: SecurityEvent, file: String = #file, line: Int = #line, function: String = #function) {
|
|
logSecurityEvent(event, level: .info, file: file, line: line, function: function)
|
|
}
|
|
|
|
static func warning(_ event: SecurityEvent, file: String = #file, line: Int = #line, function: String = #function) {
|
|
logSecurityEvent(event, level: .warning, file: file, line: line, function: function)
|
|
}
|
|
|
|
static func error(_ event: SecurityEvent, file: String = #file, line: Int = #line, function: String = #function) {
|
|
logSecurityEvent(event, level: .error, file: file, line: line, function: function)
|
|
}
|
|
}
|
|
|
|
// MARK: - Convenience Extensions
|
|
|
|
public extension SecureLogger {
|
|
|
|
enum KeyOperation: String, CustomStringConvertible {
|
|
case load
|
|
case create
|
|
case generate
|
|
case delete
|
|
case save
|
|
|
|
public var description: String { rawValue }
|
|
}
|
|
|
|
/// Log key management operations
|
|
static func logKeyOperation(_ operation: KeyOperation, keyType: String, success: Bool = true,
|
|
file: String = #file, line: Int = #line, function: String = #function) {
|
|
if success {
|
|
debug("Key operation '\(operation)' for \(keyType) succeeded", category: .keychain, file: file, line: line, function: function)
|
|
} else {
|
|
error("Key operation '\(operation)' for \(keyType) failed", category: .keychain, file: file, line: line, function: function)
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Private Helpers
|
|
|
|
private extension SecureLogger {
|
|
/// Log general messages with automatic sensitive data filtering
|
|
static func log(_ message: @autoclosure () -> String, category: OSLog, level: LogLevel,
|
|
file: String, line: Int, function: String) {
|
|
// All public wrappers are compiled out of release builds; this core
|
|
// is gated too so no future call path can reintroduce production
|
|
// logging. bitchat is privacy-first: release builds emit nothing.
|
|
#if DEBUG
|
|
guard shouldLog(level) else { return }
|
|
let location = formatLocation(file: file, line: line, function: function)
|
|
let sanitized = "\(location) \(message())".sanitized()
|
|
os_log("%{public}@", log: category, type: level.osLogType, sanitized)
|
|
#endif
|
|
}
|
|
|
|
/// Log a security event
|
|
static func logSecurityEvent(_ event: SecurityEvent, level: LogLevel = .info,
|
|
file: String, line: Int, function: String) {
|
|
#if DEBUG
|
|
guard shouldLog(level) else { return }
|
|
let location = formatLocation(file: file, line: line, function: function)
|
|
let message = "\(location) \(event.message)"
|
|
os_log("%{public}@", log: .security, type: level.osLogType, message)
|
|
#endif
|
|
}
|
|
|
|
/// Format location information for logging
|
|
static func formatLocation(file: String, line: Int, function: String) -> String {
|
|
let fileName = (file as NSString).lastPathComponent
|
|
let timestamp = timestampFormatter.string(from: Date())
|
|
return "[\(timestamp)] [\(fileName):\(line) \(function)]"
|
|
}
|
|
}
|