Replace .log w/ explicit .debug/.error functions

This would make the intention more explicit so we can overload different logging types as well like keychain, security events, etc…

Search/Replace Strategies:

1.
Search regex: `SecureLogger\.log\(\s*(.*?),\s*category:\s*(.*?),\s*level:\s*\.(\w+)\s*\)`
Replace regex: `SecureLogger.$3($1, category: $2)`

Sample input:
```
SecureLogger.log(
    "🔄 Found favorite for '\(peerInfo.nickname)' by nickname, updating noise key",
    category: .session,
    level: .debug
)
```

Sample output:
`SecureLogger.debug("🔄 Found favorite for '\(peerInfo.nickname)' by nickname, updating noise key", category: .session)`

---

2.
Search regex: `SecureLogger\.log\((.*?)\)`
Replace regex: `SecureLogger.debug($1)` (as it’s the default level)

Sample input:
`SecureLogger.log("some text")`

Sample output:
`SecureLogger.debug("some text")`

---

3
Manual changes:
ChatViewModel line 5393 (commented code)
NostrRelayManager line 196 (commented code)
NostrRelayManager lines 346-350 (if/else logic)
NostrRelayManager line 371 (commented code)
This commit is contained in:
islam
2025-09-11 19:03:08 +01:00
parent 5ca9222fc2
commit 5d6aecfc83
20 changed files with 362 additions and 487 deletions
+16 -28
View File
@@ -68,8 +68,7 @@ final class NoiseHandshakeCoordinator {
switch state {
case .initiating(_, let lastAttempt):
if Date().timeIntervalSince(lastAttempt) > handshakeTimeout {
SecureLogger.log("Forcing new handshake with \(remotePeerID) - previous stuck in initiating",
category: .handshake, level: .warning)
SecureLogger.warning("Forcing new handshake with \(remotePeerID) - previous stuck in initiating", category: .handshake)
return true
}
default:
@@ -77,8 +76,7 @@ final class NoiseHandshakeCoordinator {
}
}
SecureLogger.log("Already in active handshake with \(remotePeerID), state: \(state)",
category: .handshake, level: .debug)
SecureLogger.debug("Already in active handshake with \(remotePeerID), state: \(state)", category: .handshake)
return false
}
@@ -107,8 +105,7 @@ final class NoiseHandshakeCoordinator {
handshakeQueue.async(flags: .barrier) {
let attempt = self.getCurrentAttempt(for: peerID) + 1
self.handshakeStates[peerID] = .initiating(attempt: attempt, lastAttempt: Date())
SecureLogger.log("Recording handshake initiation with \(peerID), attempt \(attempt)",
category: .handshake, level: .info)
SecureLogger.info("Recording handshake initiation with \(peerID), attempt \(attempt)", category: .handshake)
}
}
@@ -116,8 +113,7 @@ final class NoiseHandshakeCoordinator {
func recordHandshakeResponse(peerID: String) {
handshakeQueue.async(flags: .barrier) {
self.handshakeStates[peerID] = .responding(since: Date())
SecureLogger.log("Recording handshake response to \(peerID)",
category: .handshake, level: .info)
SecureLogger.info("Recording handshake response to \(peerID)", category: .handshake)
}
}
@@ -125,8 +121,7 @@ final class NoiseHandshakeCoordinator {
func recordHandshakeSuccess(peerID: String) {
handshakeQueue.async(flags: .barrier) {
self.handshakeStates[peerID] = .established(since: Date())
SecureLogger.log("Handshake successfully established with \(peerID)",
category: .handshake, level: .info)
SecureLogger.info("Handshake successfully established with \(peerID)", category: .handshake)
}
}
@@ -136,8 +131,7 @@ final class NoiseHandshakeCoordinator {
let attempts = self.getCurrentAttempt(for: peerID)
let canRetry = attempts < self.maxHandshakeAttempts
self.handshakeStates[peerID] = .failed(reason: reason, canRetry: canRetry, lastAttempt: Date())
SecureLogger.log("Handshake failed with \(peerID): \(reason), canRetry: \(canRetry)",
category: .handshake, level: .warning)
SecureLogger.warning("Handshake failed with \(peerID): \(reason), canRetry: \(canRetry)", category: .handshake)
}
}
@@ -146,8 +140,7 @@ final class NoiseHandshakeCoordinator {
return handshakeQueue.sync {
// If we're already established, reject new handshakes
if case .established = handshakeStates[remotePeerID] {
SecureLogger.log("Rejecting handshake from \(remotePeerID) - already established",
category: .handshake, level: .debug)
SecureLogger.debug("Rejecting handshake from \(remotePeerID) - already established", category: .handshake)
return false
}
@@ -157,8 +150,7 @@ final class NoiseHandshakeCoordinator {
if role == .initiator {
if case .initiating = handshakeStates[remotePeerID] {
// They shouldn't be initiating, but accept it to recover from race condition
SecureLogger.log("Accepting handshake from \(remotePeerID) despite being initiator (race condition recovery)",
category: .handshake, level: .warning)
SecureLogger.warning("Accepting handshake from \(remotePeerID) despite being initiator (race condition recovery)", category: .handshake)
return true
}
}
@@ -215,8 +207,7 @@ final class NoiseHandshakeCoordinator {
func resetHandshakeState(for peerID: String) {
handshakeQueue.async(flags: .barrier) {
self.handshakeStates.removeValue(forKey: peerID)
SecureLogger.log("Reset handshake state for \(peerID)",
category: .handshake, level: .debug)
SecureLogger.debug("Reset handshake state for \(peerID)", category: .handshake)
}
}
@@ -256,8 +247,7 @@ final class NoiseHandshakeCoordinator {
if isStale {
stalePeerIDs.append(peerID)
SecureLogger.log("Found stale handshake state for \(peerID): \(state)",
category: .handshake, level: .warning)
SecureLogger.warning("Found stale handshake state for \(peerID): \(state)", category: .handshake)
}
}
@@ -270,8 +260,7 @@ final class NoiseHandshakeCoordinator {
for i in 0..<sessionsToRemove {
let peerID = sortedSessions[i].peerID
stalePeerIDs.append(peerID)
SecureLogger.log("Removing old established session for \(peerID) to maintain session limit",
category: .handshake, level: .info)
SecureLogger.info("Removing old established session for \(peerID) to maintain session limit", category: .handshake)
}
}
@@ -281,8 +270,7 @@ final class NoiseHandshakeCoordinator {
}
if !stalePeerIDs.isEmpty {
SecureLogger.log("Cleaned up \(stalePeerIDs.count) stale handshake states",
category: .handshake, level: .info)
SecureLogger.info("Cleaned up \(stalePeerIDs.count) stale handshake states", category: .handshake)
}
return stalePeerIDs
@@ -333,7 +321,7 @@ final class NoiseHandshakeCoordinator {
/// Log current handshake states for debugging
func logHandshakeStates() {
handshakeQueue.sync {
SecureLogger.log("=== Handshake States ===", category: .handshake, level: .debug)
SecureLogger.debug("=== Handshake States ===", category: .handshake)
for (peerID, state) in handshakeStates {
let stateDesc: String
switch state {
@@ -352,16 +340,16 @@ final class NoiseHandshakeCoordinator {
case .failed(let reason, let canRetry, let lastAttempt):
stateDesc = "failed: \(reason) (canRetry: \(canRetry), last: \(lastAttempt))"
}
SecureLogger.log(" \(peerID): \(stateDesc)", category: .handshake, level: .debug)
SecureLogger.debug(" \(peerID): \(stateDesc)", category: .handshake)
}
SecureLogger.log("========================", category: .handshake, level: .debug)
SecureLogger.debug("========================", category: .handshake)
}
}
/// Clear all handshake states - used during panic mode
func clearAllHandshakeStates() {
handshakeQueue.async(flags: .barrier) {
SecureLogger.log("Clearing all handshake states for panic mode", category: .handshake, level: .warning)
SecureLogger.warning("Clearing all handshake states for panic mode", category: .handshake)
self.handshakeStates.removeAll()
self.processedHandshakeMessages.removeAll()
}
+9 -9
View File
@@ -285,7 +285,7 @@ final class NoiseCipherState {
// Log high nonce values that might indicate issues
if currentNonce > Self.HIGH_NONCE_WARNING_THRESHOLD {
SecureLogger.log("High nonce value detected: \(currentNonce) - consider rekeying", category: .encryption, level: .warning)
SecureLogger.warning("High nonce value detected: \(currentNonce) - consider rekeying", category: .encryption)
}
return combinedPayload
@@ -307,13 +307,13 @@ final class NoiseCipherState {
if useExtractedNonce {
// Extract nonce and ciphertext from combined payload
guard let (extractedNonce, actualCiphertext) = try extractNonceFromCiphertextPayload(ciphertext) else {
SecureLogger.log("Decrypt failed: Could not extract nonce from payload")
SecureLogger.debug("Decrypt failed: Could not extract nonce from payload")
throw NoiseError.invalidCiphertext
}
// Validate nonce with sliding window replay protection
guard isValidNonce(extractedNonce) else {
SecureLogger.log("Replay attack detected: nonce \(extractedNonce) rejected")
SecureLogger.debug("Replay attack detected: nonce \(extractedNonce) rejected")
throw NoiseError.replayDetected
}
@@ -342,7 +342,7 @@ final class NoiseCipherState {
// Log high nonce values that might indicate issues
if decryptionNonce > Self.HIGH_NONCE_WARNING_THRESHOLD {
SecureLogger.log("High nonce value detected: \(decryptionNonce) - consider rekeying", category: .encryption, level: .warning)
SecureLogger.warning("High nonce value detected: \(decryptionNonce) - consider rekeying", category: .encryption)
}
do {
@@ -355,9 +355,9 @@ final class NoiseCipherState {
nonce += 1
return plaintext
} catch {
SecureLogger.log("Decrypt failed: \(error) for nonce \(decryptionNonce)")
SecureLogger.debug("Decrypt failed: \(error) for nonce \(decryptionNonce)")
// Log authentication failures with nonce info
SecureLogger.log("Decryption failed at nonce \(decryptionNonce)", category: .encryption, level: .error)
SecureLogger.error("Decryption failed at nonce \(decryptionNonce)", category: .encryption)
throw error
}
}
@@ -661,7 +661,7 @@ final class NoiseHandshakeState {
do {
remoteEphemeralPublic = try NoiseHandshakeState.validatePublicKey(ephemeralData)
} catch {
SecureLogger.log("Invalid ephemeral public key received", category: .security, level: .warning)
SecureLogger.warning("Invalid ephemeral public key received", category: .security)
throw NoiseError.invalidMessage
}
symmetricState.mixHash(ephemeralData)
@@ -877,7 +877,7 @@ extension NoiseHandshakeState {
// Check against known bad points
if lowOrderPoints.contains(keyData) {
SecureLogger.log("Low-order point detected", category: .security, level: .warning)
SecureLogger.warning("Low-order point detected", category: .security)
throw NoiseError.invalidPublicKey
}
@@ -887,7 +887,7 @@ extension NoiseHandshakeState {
return publicKey
} catch {
// If CryptoKit rejects it, it's invalid
SecureLogger.log("CryptoKit validation failed", category: .security, level: .warning)
SecureLogger.warning("CryptoKit validation failed", category: .security)
throw NoiseError.invalidPublicKey
}
}
@@ -153,7 +153,7 @@ final class NoiseRateLimiter {
// Check global rate limit first
globalHandshakeTimestamps = globalHandshakeTimestamps.filter { $0 > oneMinuteAgo }
if globalHandshakeTimestamps.count >= NoiseSecurityConstants.maxGlobalHandshakesPerMinute {
SecureLogger.log("Global handshake rate limit exceeded: \(globalHandshakeTimestamps.count)/\(NoiseSecurityConstants.maxGlobalHandshakesPerMinute) per minute", category: .security, level: .warning)
SecureLogger.warning("Global handshake rate limit exceeded: \(globalHandshakeTimestamps.count)/\(NoiseSecurityConstants.maxGlobalHandshakesPerMinute) per minute", category: .security)
return false
}
@@ -162,7 +162,7 @@ final class NoiseRateLimiter {
timestamps = timestamps.filter { $0 > oneMinuteAgo }
if timestamps.count >= NoiseSecurityConstants.maxHandshakesPerMinute {
SecureLogger.log("Per-peer handshake rate limit exceeded for \(peerID): \(timestamps.count)/\(NoiseSecurityConstants.maxHandshakesPerMinute) per minute", category: .security, level: .warning)
SecureLogger.warning("Per-peer handshake rate limit exceeded for \(peerID): \(timestamps.count)/\(NoiseSecurityConstants.maxHandshakesPerMinute) per minute", category: .security)
return false
}
@@ -182,7 +182,7 @@ final class NoiseRateLimiter {
// Check global rate limit first
globalMessageTimestamps = globalMessageTimestamps.filter { $0 > oneSecondAgo }
if globalMessageTimestamps.count >= NoiseSecurityConstants.maxGlobalMessagesPerSecond {
SecureLogger.log("Global message rate limit exceeded: \(globalMessageTimestamps.count)/\(NoiseSecurityConstants.maxGlobalMessagesPerSecond) per second", category: .security, level: .warning)
SecureLogger.warning("Global message rate limit exceeded: \(globalMessageTimestamps.count)/\(NoiseSecurityConstants.maxGlobalMessagesPerSecond) per second", category: .security)
return false
}
@@ -191,7 +191,7 @@ final class NoiseRateLimiter {
timestamps = timestamps.filter { $0 > oneSecondAgo }
if timestamps.count >= NoiseSecurityConstants.maxMessagesPerSecond {
SecureLogger.log("Per-peer message rate limit exceeded for \(peerID): \(timestamps.count)/\(NoiseSecurityConstants.maxMessagesPerSecond) per second", category: .security, level: .warning)
SecureLogger.warning("Per-peer message rate limit exceeded for \(peerID): \(timestamps.count)/\(NoiseSecurityConstants.maxMessagesPerSecond) per second", category: .security)
return false
}
+7 -8
View File
@@ -92,7 +92,7 @@ class NoiseSession {
func processHandshakeMessage(_ message: Data) throws -> Data? {
return try sessionQueue.sync(flags: .barrier) {
SecureLogger.log("NoiseSession[\(peerID)]: Processing handshake message, current state: \(state), role: \(role)", category: .noise, level: .debug)
SecureLogger.debug("NoiseSession[\(peerID)]: Processing handshake message, current state: \(state), role: \(role)", category: .noise)
// Initialize handshake state if needed (for responders)
if state == .uninitialized && role == .responder {
@@ -103,7 +103,7 @@ class NoiseSession {
remoteStaticKey: nil
)
state = .handshaking
SecureLogger.log("NoiseSession[\(peerID)]: Initialized handshake state for responder", category: .noise, level: .debug)
SecureLogger.debug("NoiseSession[\(peerID)]: Initialized handshake state for responder", category: .noise)
}
guard case .handshaking = state, let handshake = handshakeState else {
@@ -112,7 +112,7 @@ class NoiseSession {
// Process incoming message
_ = try handshake.readMessage(message)
SecureLogger.log("NoiseSession[\(peerID)]: Read handshake message, checking if complete", category: .noise, level: .debug)
SecureLogger.debug("NoiseSession[\(peerID)]: Read handshake message, checking if complete", category: .noise)
// Check if handshake is complete
if handshake.isHandshakeComplete() {
@@ -130,7 +130,7 @@ class NoiseSession {
state = .established
handshakeState = nil // Clear handshake state
SecureLogger.log("NoiseSession[\(peerID)]: Handshake complete (no response needed), transitioning to established", category: .noise, level: .debug)
SecureLogger.debug("NoiseSession[\(peerID)]: Handshake complete (no response needed), transitioning to established", category: .noise)
SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))
return nil
@@ -138,7 +138,7 @@ class NoiseSession {
// Generate response
let response = try handshake.writeMessage()
sentHandshakeMessages.append(response)
SecureLogger.log("NoiseSession[\(peerID)]: Generated handshake response of size \(response.count)", category: .noise, level: .debug)
SecureLogger.debug("NoiseSession[\(peerID)]: Generated handshake response of size \(response.count)", category: .noise)
// Check if handshake is complete after writing
if handshake.isHandshakeComplete() {
@@ -156,7 +156,7 @@ class NoiseSession {
state = .established
handshakeState = nil // Clear handshake state
SecureLogger.log("NoiseSession[\(peerID)]: Handshake complete after writing response, transitioning to established", category: .noise, level: .debug)
SecureLogger.debug("NoiseSession[\(peerID)]: Handshake complete after writing response, transitioning to established", category: .noise)
SecureLogger.logSecurityEvent(.handshakeCompleted(peerID: peerID))
}
@@ -348,8 +348,7 @@ final class NoiseSessionManager {
// for a good reason (e.g., decryption failure, restart, etc.)
// We should accept the new handshake to re-establish encryption
if existing.isEstablished() {
SecureLogger.log("Accepting handshake from \(peerID) despite existing session - peer likely cleared their session",
category: .session, level: .info)
SecureLogger.info("Accepting handshake from \(peerID) despite existing session - peer likely cleared their session", category: .session)
_ = sessions.removeValue(forKey: peerID)
shouldCreateNew = true
} else {