mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-07-25 20:45:19 +00:00
* Add capability bits to announce TLV Announces now carry an optional capabilities TLV (0x05): a little-endian bitfield with named bits for upcoming features (prekeys, wifiBulk, gateway, groups, board, vouch, meshDiagnostics). Old clients skip the unknown TLV; peers without it decode as nil so features can distinguish "legacy peer" from "advertises nothing". PeerCapabilities lives in BitFoundation with a minimal-length encoding that preserves unknown bits for forward compatibility. Peer capabilities are stored in the BLE peer registry on verified announce and exposed via BLEService.peerCapabilities(_:). The local advertisement set is empty until each feature ships its bit. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Transitive verification: vouch for verified peers over Noise When a Noise session establishes with a peer I verified and that peer advertises the .vouch capability, send signed attestations (up to 16, most recently verified first, at most once per peer per 24h) for the OTHER fingerprints I verified. Receivers accept vouches only from senders they verified themselves, verify the Ed25519 signature against the sender's announce-bound signing key, and surface the result as a new derived trust tier: vouched (unfilled seal) between casual and trusted. Protocol: - NoisePayloadType.vouch = 0x12 carries a batch of TLV attestations: voucheeFingerprint (32B), voucheeSigningKey (32B), timestamp (uint64 ms BE), Ed25519 signature over "bitchat-vouch-v1" | fingerprint | signingKey | timestamp. The voucher is implicit in the authenticated session. - PeerCapabilities.localSupported now advertises .vouch. Storage (SecureIdentityStateManager / IdentityCache): - vouches keyed by vouchee, capped at 8 vouchers each; validity is recomputed on read (voucher still verified-by-me, < 30 days old), so unverifying a voucher retires their vouches without cascade deletes. - New IdentityCache fields are Optional so pre-existing encrypted caches decode cleanly; TrustLevel.vouched is inserted mid-ladder but raw values are strings, so persisted values are unaffected (and vouched itself is never persisted). - Panic wipe clears vouch state with the rest of the identity cache. UI: unfilled checkmark.seal badge in the mesh peer list (filled seal stays exclusive to verified) and a "vouched for by N people you verified" section with voucher names in FingerprintView; VoiceOver labels and xcstrings entries included. Tests: attestation encode/decode + signature (forged/tampered/expired), accept-policy gates, batch cap, trust-level derivation incl. voucher invalidation, persistence compat, and coordinator exchange/accept policies. Full macOS suite: 1088 tests passing. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Fix CI deadlock in vouch tests and live-refresh the fingerprint sheet on vouch acceptance Two fixes for PR #1380 review findings: 1. CI "Run Swift Tests (app)" hang (exit 137): the new SecureIdentityStateManagerVouchTests suite was nonisolated, so Swift Testing ran its tests in parallel on the Swift Concurrency cooperative pool. Each test enqueues a queue.async(.barrier) write (setVerified) and immediately blocks in queue.sync / queue.sync(.barrier) (recordVouch / effectiveTrustLevel). On CI's few-core runners every cooperative-pool thread ended up parked behind a pending barrier that never got a dispatch worker, deadlocking the whole test process until the watchdog SIGKILLed it. The suite is now @MainActor, matching the production isolation of the vouch API (ChatVouchCoordinator is @MainActor) and keeping blocking syncs off the cooperative pool. 2. Codex P2: an open fingerprint sheet did not refresh its vouched badge when a vouch batch was accepted - VerificationModel.bind() never observed the trust-change signal. It now subscribes to the "peerStatusUpdated" notification that ChatVouchCoordinator.notifyPeerTrustChanged() posts (same source PeerListModel uses) and forwards it to objectWillChange. Added a regression test that pins VerificationModel's own subscription (verified to fail without the fix). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Skip media-wipe detached tasks under tests (shared-filesystem race) panicClearAllData and clearCurrentPublicTimeline delete the real ~/Library/Application Support/files tree in detached utility-priority tasks. The SPM test process shares that tree and ChatViewModelTests invoke both methods, so under parallel scheduling the wipe lands at a nondeterministic time — deleting media a concurrently running test just wrote (and the developer's real app data with it). Guard both with the existing TestEnvironment.isRunningTests pattern, mirroring the same fix on feat/mesh-diagnostics (#1377). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * Port vouch capability-race fix to feat/vouching (ports b8adcbe9) Ports the on-device-confirmed fix from the integration test branch (commit b8adcbe9) onto feat/vouching so PR #1380 is actually correct. On-device testing confirmed the transitive vouch propagated once the send was triggered on verify / announce arrival rather than auth alone. Vouch attestations only ever sent from peerAuthenticated, gated on the peer's .vouch capability. That capability arrives via the peer's announce, processed independently of the Noise handshake, so at auth time the set was usually empty -> gate failed -> vouch silently skipped and never retried. - Refactor the send path into a reusable attemptVouch(to:fingerprint:now:). - Trigger on peer-list updates (peersUpdated): fired after every verified announce, so the batch goes out once the .vouch bit actually arrives. - Trigger on local verification (vouchToConnectedVerifiedPeers): verifying a peer runs a vouch pass over connected verified peers, covering the verify-while-connected case and propagating the new identity onward. - Relax the capability gate: treat an empty/unknown set as eligible (the Noise 0x12 payload is ignored by non-supporting peers); only skip when a non-empty set explicitly lacks .vouch. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: jack <jackjackbits@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
226 lines
9.1 KiB
Swift
226 lines
9.1 KiB
Swift
//
|
|
// VouchAttestation.swift
|
|
// bitchat
|
|
//
|
|
// This is free and unencumbered software released into the public domain.
|
|
// For more information, see <https://unlicense.org>
|
|
//
|
|
|
|
import CryptoKit
|
|
import Foundation
|
|
|
|
/// A signed statement that the *sender of the enclosing Noise payload* has
|
|
/// verified the identity described here ("transitive verification").
|
|
///
|
|
/// The voucher's identity is deliberately implicit: attestations only travel
|
|
/// inside an authenticated Noise session (`NoisePayloadType.vouch`), so the
|
|
/// receiver verifies the Ed25519 signature against the session peer's
|
|
/// announce-bound signing key and stores the vouch keyed by that peer's
|
|
/// fingerprint. Nothing in the attestation names the voucher, so a captured
|
|
/// attestation cannot be replayed by a third party whose signing key doesn't
|
|
/// match.
|
|
///
|
|
/// Wire format — single attestation (TLV, 1-byte type + 1-byte length):
|
|
/// - `0x01` voucheeFingerprint: 32 bytes, SHA-256 of the vouchee's Noise static key
|
|
/// - `0x02` voucheeSigningKey: 32 bytes, Ed25519; anchors the vouch to a concrete identity
|
|
/// - `0x03` timestamp: 8 bytes big-endian, milliseconds since 1970
|
|
/// - `0x04` signature: 64 bytes, Ed25519 by the VOUCHER's signing key over
|
|
/// `"bitchat-vouch-v1" | voucheeFingerprint | voucheeSigningKey | timestamp`
|
|
///
|
|
/// Unknown TLV types are skipped for forward compatibility.
|
|
///
|
|
/// Batch format (the `vouch` Noise payload body):
|
|
/// `[count: UInt8]` then per attestation `[length: UInt16 BE][attestation TLV]`.
|
|
struct VouchAttestation: Equatable {
|
|
static let signingContext = "bitchat-vouch-v1"
|
|
/// Receiver-side expiry for attestations.
|
|
static let maxAge: TimeInterval = 30 * 24 * 60 * 60
|
|
/// Tolerated clock skew for attestations timestamped in the future.
|
|
static let maxClockSkew: TimeInterval = 60 * 60
|
|
/// Upper bound of attestations carried/accepted in one batch payload.
|
|
static let maxBatchCount = 16
|
|
|
|
static let fingerprintSize = 32
|
|
static let signingKeySize = 32
|
|
static let signatureSize = 64
|
|
|
|
let voucheeFingerprint: Data // 32 bytes
|
|
let voucheeSigningKey: Data // 32 bytes
|
|
let timestampMs: UInt64
|
|
let signature: Data // 64 bytes
|
|
|
|
private enum TLVType: UInt8 {
|
|
case voucheeFingerprint = 0x01
|
|
case voucheeSigningKey = 0x02
|
|
case timestamp = 0x03
|
|
case signature = 0x04
|
|
}
|
|
|
|
var voucheeFingerprintHex: String { voucheeFingerprint.hexEncodedString() }
|
|
|
|
var timestamp: Date { Date(timeIntervalSince1970: TimeInterval(timestampMs) / 1000) }
|
|
|
|
/// The exact bytes the voucher signs.
|
|
static func signableBytes(
|
|
voucheeFingerprint: Data,
|
|
voucheeSigningKey: Data,
|
|
timestampMs: UInt64
|
|
) -> Data {
|
|
var message = Data(signingContext.utf8)
|
|
message.append(voucheeFingerprint)
|
|
message.append(voucheeSigningKey)
|
|
var timestampBE = timestampMs.bigEndian
|
|
withUnsafeBytes(of: ×tampBE) { message.append(contentsOf: $0) }
|
|
return message
|
|
}
|
|
|
|
var signableBytes: Data {
|
|
Self.signableBytes(
|
|
voucheeFingerprint: voucheeFingerprint,
|
|
voucheeSigningKey: voucheeSigningKey,
|
|
timestampMs: timestampMs
|
|
)
|
|
}
|
|
|
|
/// Builds and signs an attestation. `sign` is the voucher's Ed25519
|
|
/// signing primitive (e.g. `Transport.noiseSignData`).
|
|
static func build(
|
|
voucheeFingerprint: Data,
|
|
voucheeSigningKey: Data,
|
|
timestampMs: UInt64 = UInt64(Date().timeIntervalSince1970 * 1000),
|
|
sign: (Data) -> Data?
|
|
) -> VouchAttestation? {
|
|
guard voucheeFingerprint.count == fingerprintSize,
|
|
voucheeSigningKey.count == signingKeySize else { return nil }
|
|
let message = signableBytes(
|
|
voucheeFingerprint: voucheeFingerprint,
|
|
voucheeSigningKey: voucheeSigningKey,
|
|
timestampMs: timestampMs
|
|
)
|
|
guard let signature = sign(message), signature.count == signatureSize else { return nil }
|
|
return VouchAttestation(
|
|
voucheeFingerprint: voucheeFingerprint,
|
|
voucheeSigningKey: voucheeSigningKey,
|
|
timestampMs: timestampMs,
|
|
signature: signature
|
|
)
|
|
}
|
|
|
|
/// Verifies the Ed25519 signature against the voucher's announce-bound
|
|
/// signing key.
|
|
func verifySignature(voucherSigningKey: Data) -> Bool {
|
|
guard let publicKey = try? Curve25519.Signing.PublicKey(rawRepresentation: voucherSigningKey) else {
|
|
return false
|
|
}
|
|
return publicKey.isValidSignature(signature, for: signableBytes)
|
|
}
|
|
|
|
/// Whether the attestation is outside its validity window (older than
|
|
/// `maxAge`, or timestamped implausibly far in the future).
|
|
func isExpired(now: Date = Date()) -> Bool {
|
|
let age = now.timeIntervalSince(timestamp)
|
|
return age > Self.maxAge || age < -Self.maxClockSkew
|
|
}
|
|
|
|
// MARK: - Encoding
|
|
|
|
func encode() -> Data? {
|
|
guard voucheeFingerprint.count == Self.fingerprintSize,
|
|
voucheeSigningKey.count == Self.signingKeySize,
|
|
signature.count == Self.signatureSize else { return nil }
|
|
var data = Data()
|
|
func appendTLV(_ type: TLVType, _ value: Data) {
|
|
data.append(type.rawValue)
|
|
data.append(UInt8(value.count))
|
|
data.append(value)
|
|
}
|
|
appendTLV(.voucheeFingerprint, voucheeFingerprint)
|
|
appendTLV(.voucheeSigningKey, voucheeSigningKey)
|
|
var timestampBE = timestampMs.bigEndian
|
|
appendTLV(.timestamp, withUnsafeBytes(of: ×tampBE) { Data($0) })
|
|
appendTLV(.signature, signature)
|
|
return data
|
|
}
|
|
|
|
static func decode(from data: Data) -> VouchAttestation? {
|
|
var fingerprint: Data?
|
|
var signingKey: Data?
|
|
var timestampMs: UInt64?
|
|
var signature: Data?
|
|
|
|
var offset = data.startIndex
|
|
while offset < data.endIndex {
|
|
guard data.index(offset, offsetBy: 2, limitedBy: data.endIndex) != nil,
|
|
offset + 1 < data.endIndex else { return nil }
|
|
let type = data[offset]
|
|
let length = Int(data[offset + 1])
|
|
let valueStart = offset + 2
|
|
guard let valueEnd = data.index(valueStart, offsetBy: length, limitedBy: data.endIndex) else {
|
|
return nil
|
|
}
|
|
let value = Data(data[valueStart..<valueEnd])
|
|
switch TLVType(rawValue: type) {
|
|
case .voucheeFingerprint:
|
|
guard value.count == fingerprintSize else { return nil }
|
|
fingerprint = value
|
|
case .voucheeSigningKey:
|
|
guard value.count == signingKeySize else { return nil }
|
|
signingKey = value
|
|
case .timestamp:
|
|
guard value.count == 8 else { return nil }
|
|
timestampMs = value.reduce(UInt64(0)) { ($0 << 8) | UInt64($1) }
|
|
case .signature:
|
|
guard value.count == signatureSize else { return nil }
|
|
signature = value
|
|
case nil:
|
|
break // Unknown TLV: skip for forward compatibility.
|
|
}
|
|
offset = valueEnd
|
|
}
|
|
|
|
guard let fingerprint, let signingKey, let timestampMs, let signature else { return nil }
|
|
return VouchAttestation(
|
|
voucheeFingerprint: fingerprint,
|
|
voucheeSigningKey: signingKey,
|
|
timestampMs: timestampMs,
|
|
signature: signature
|
|
)
|
|
}
|
|
|
|
// MARK: - Batch encoding
|
|
|
|
/// Encodes up to `maxBatchCount` attestations into one payload body.
|
|
static func encodeList(_ attestations: [VouchAttestation]) -> Data? {
|
|
guard !attestations.isEmpty, attestations.count <= maxBatchCount else { return nil }
|
|
var data = Data()
|
|
data.append(UInt8(attestations.count))
|
|
for attestation in attestations {
|
|
guard let encoded = attestation.encode(), encoded.count <= Int(UInt16.max) else { return nil }
|
|
var lengthBE = UInt16(encoded.count).bigEndian
|
|
withUnsafeBytes(of: &lengthBE) { data.append(contentsOf: $0) }
|
|
data.append(encoded)
|
|
}
|
|
return data
|
|
}
|
|
|
|
/// Decodes a batch payload, dropping malformed entries and ignoring
|
|
/// anything beyond `maxBatchCount` (sender-declared count is not trusted).
|
|
static func decodeList(from data: Data) -> [VouchAttestation] {
|
|
guard data.count > 1 else { return [] }
|
|
let declaredCount = Int(data[data.startIndex])
|
|
let limit = min(declaredCount, maxBatchCount)
|
|
var attestations: [VouchAttestation] = []
|
|
var offset = data.startIndex + 1
|
|
while attestations.count < limit, offset < data.endIndex {
|
|
guard let lengthEnd = data.index(offset, offsetBy: 2, limitedBy: data.endIndex) else { break }
|
|
let length = Int(data[offset]) << 8 | Int(data[offset + 1])
|
|
guard let entryEnd = data.index(lengthEnd, offsetBy: length, limitedBy: data.endIndex) else { break }
|
|
if let attestation = decode(from: Data(data[lengthEnd..<entryEnd])) {
|
|
attestations.append(attestation)
|
|
}
|
|
offset = entryEnd
|
|
}
|
|
return attestations
|
|
}
|
|
}
|