1package com.peachpasswords.sync23import org.bouncycastle.crypto.digests.SHA256Digest4import org.bouncycastle.crypto.generators.HKDFBytesGenerator5import org.bouncycastle.crypto.params.HKDFParameters6import java.net.URI7import java.nio.ByteBuffer8import java.security.MessageDigest9import java.security.SecureRandom10import java.util.Base641112object Rendezvous {13 const val DEFAULT_RELAY_URL = "wss://relay.peachpasswords.com"14 const val WINDOW_SECONDS = 3600L15 const val PAIRING_TOKEN_BYTES = 161617 private val secretInfo = "peach-rendezvous-secret-v1".encodeToByteArray()18 private val meshSecretInfo = "peach-mesh-rendezvous-v2".encodeToByteArray()19 private val windowInfo = "peach-rendezvous-v1".encodeToByteArray()2021 fun deriveSecret(handshakeHash: ByteArray): ByteArray {22 require(handshakeHash.size == 32) { "handshake hash must be exactly 32 bytes" }23 return hkdf(handshakeHash, secretInfo)24 }2526 27282930 fun deriveMeshSecret(31 ourPrivateKey: ByteArray,32 ourPublicKey: ByteArray,33 peerPublicKey: ByteArray,34 ): ByteArray {35 require(ourPrivateKey.size == 32 && ourPublicKey.size == 32 && peerPublicKey.size == 32)36 require(compareUnsigned(ourPublicKey, peerPublicKey) != 0)37 val shared = ByteArray(32)38 try {39 org.bouncycastle.crypto.params.X25519PrivateKeyParameters(ourPrivateKey, 0)40 .generateSecret(org.bouncycastle.crypto.params.X25519PublicKeyParameters(peerPublicKey, 0), shared, 0)41 require(shared.any { it.toInt() != 0 }) { "mesh low-order point rejected" }42 val low = if (compareUnsigned(ourPublicKey, peerPublicKey) < 0) ourPublicKey else peerPublicKey43 val high = if (low === ourPublicKey) peerPublicKey else ourPublicKey44 return hkdf(shared, meshSecretInfo + low + high)45 } finally {46 shared.fill(0)47 }48 }49 5051525354 fun deriveId(secret: ByteArray, windowIndex: Long): String {55 require(secret.size == 32) { "rendezvous secret must be exactly 32 bytes" }56 require(windowIndex >= 0) { "window index must be non-negative" }57 val info = windowInfo + ByteBuffer.allocate(Long.SIZE_BYTES).putLong(windowIndex).array()58 return Base64.getUrlEncoder().withoutPadding().encodeToString(hkdf(secret, info))59 }6061 fun windowIndex(unixSeconds: Long, windowSeconds: Long = WINDOW_SECONDS): Long {62 require(unixSeconds >= 0) { "unixSeconds must be non-negative" }63 require(windowSeconds > 0) { "windowSeconds must be positive" }64 return unixSeconds / windowSeconds65 }6667 fun waitingIds(secret: ByteArray, unixSeconds: Long): List<String> {68 val current = windowIndex(unixSeconds)69 return listOf(current, (current - 1).coerceAtLeast(0)).map { deriveId(secret, it) }70 }7172 fun dialingIds(secret: ByteArray, unixSeconds: Long): List<String> {73 val current = windowIndex(unixSeconds)74 return listOf(current, (current - 1).coerceAtLeast(0), current + 1).map {75 deriveId(secret, it)76 }77 }7879 8081828384 fun resolvePeer(85 devices: List<PairedDevice>,86 rendezvousId: String,87 unixSeconds: Long = System.currentTimeMillis() / 1000L,88 ): PairedDevice? {89 if (!rendezvousId.matches(Regex("^[A-Za-z0-9_-]{22,128}$"))) return null90 val presented = rendezvousId.toByteArray(Charsets.US_ASCII)91 var match: PairedDevice? = null92 for (device in devices) {93 val secret = device.rendezvousSecretHex94 ?.takeIf { it.matches(Regex("^[0-9a-f]{64}$")) }95 ?.let(::secretFromHex)96 ?: continue97 for (candidate in waitingIds(secret, unixSeconds)) {98 if (MessageDigest.isEqual(candidate.toByteArray(Charsets.US_ASCII), presented)) {99 match = device100 }101 }102 }103 return match104 }105106 fun newPairingToken(random: SecureRandom = SecureRandom()): String {107 val bytes = ByteArray(PAIRING_TOKEN_BYTES)108 random.nextBytes(bytes)109 return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes)110 }111112 fun normalizeRelayUrl(input: String): String {113 val uri = URI(input.trim())114 require(uri.scheme == "wss") { "relay URL must use wss://" }115 require(!uri.host.isNullOrBlank()) { "relay URL host missing" }116 require(uri.userInfo == null && uri.rawQuery == null && uri.rawFragment == null) {117 "relay URL must not contain credentials, query, or fragment"118 }119 val path = uri.path.orEmpty().trimEnd('/')120 return URI("wss", null, uri.host, uri.port, path, null, null).toString().trimEnd('/')121 }122123 fun buildUrl(relayUrl: String, rendezvousId: String): String {124 require(rendezvousId.matches(Regex("^[A-Za-z0-9_-]{22,128}$"))) {125 "invalid rendezvous id"126 }127 return "${normalizeRelayUrl(relayUrl)}/r/$rendezvousId"128 }129130 fun bytesToHex(bytes: ByteArray): String =131 bytes.joinToString("") { "%02x".format(it) }132133 fun secretFromHex(hex: String): ByteArray {134 require(hex.matches(Regex("^[0-9a-f]{64}$"))) {135 "rendezvous secret must be 32-byte lowercase hex"136 }137 return ByteArray(32) { index -> hex.substring(index * 2, index * 2 + 2).toInt(16).toByte() }138 }139140 fun bindPairState(141 device: PairedDevice,142 handshakeHash: ByteArray,143 relayUrl: String,144 ): PairedDevice = device.copy(145 rendezvousSecretHex = bytesToHex(deriveSecret(handshakeHash)),146 relayUrl = normalizeRelayUrl(relayUrl),147 )148149 private fun hkdf(ikm: ByteArray, info: ByteArray): ByteArray {150 val generator = HKDFBytesGenerator(SHA256Digest())151 generator.init(HKDFParameters(ikm, ByteArray(0), info))152 return ByteArray(32).also { generator.generateBytes(it, 0, it.size) }153 }154155 private fun compareUnsigned(a: ByteArray, b: ByteArray): Int {156 for (index in a.indices) {157 val left = a[index].toInt() and 0xff158 val right = b[index].toInt() and 0xff159 if (left != right) return left.compareTo(right)160 }161 return 0162 }163}164165166167168169170171const val PAIRING_WINDOW_MS = 5L * 60 * 1000