1package com.peachpasswords.sync23import kotlinx.serialization.builtins.serializer4import kotlinx.serialization.json.Json5import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters678const val DEVICE_MANIFEST_VERSION = 0x049const val MAX_VOUCH_DEPTH = 310private const val DEVICE_MANIFEST_FRESHNESS_MS = 5 * 60_000L111213141516171819private const val MAX_MANIFEST_DEVICES = 25620private const val MAX_MANIFEST_REVOCATIONS = 50021private const val MAX_MANIFEST_STRING = 2562223242526272829internal const val MAX_DEVICE_NAME_CHARS = 64303132internal fun capDeviceName(name: String): String =33 if (name.length > MAX_DEVICE_NAME_CHARS) name.take(MAX_DEVICE_NAME_CHARS) else name34internal const val NO_KEY_SENTINEL = "0000000000000000000000000000000000000000000000000000000000000000"35363738394041data class DeviceManifestRegistryBatch(42 val incomingRevocations: List<DeviceRevocation>,43 val removals: Set<String>,44 val upserts: List<PairedDevice>,45)4647interface PairedDeviceRegistry {48 fun getAll(): List<PairedDevice>49 fun get(id: String): PairedDevice?50 fun getByPubkey(pubkeyHex: String): PairedDevice? =51 getAll().firstOrNull {52 it.longTermPublicKeyHex?.let { key -> CryptoCompare.hex(key, pubkeyHex) } == true53 }54 fun upsert(device: PairedDevice)55 fun remove(deviceId: String) {}56 fun listRevocations(): List<DeviceRevocation> = emptyList()5758 59 fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean6061 62 fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> = emptyList()6364 6566676869707172 fun isRevoked(deviceId: String, longTermPublicKeyHex: String? = null): Boolean {73 val key = longTermPublicKeyHex?.lowercase()?.takeIf { it != NO_KEY_SENTINEL }74 return listRevocations().any {75 it.deviceId == deviceId || (key != null && it.longTermPublicKeyHex.lowercase() == key)76 }77 }7879 80 fun clearRevocation(deviceId: String) {}81}8283fun buildSignedDeviceManifest(84 issuerDeviceId: String,85 devices: List<ManifestDeviceEntry>,86 signingPrivateKey: Ed25519PrivateKeyParameters,87 nowMs: Long = System.currentTimeMillis(),88 revoked: List<DeviceRevocation> = emptyList(),89): SignedDeviceManifest {90 require(issuerDeviceId.isNotBlank()) { "issuerDeviceId is required" }91 val body = DeviceManifestBody(92 manifestVersion = DEVICE_MANIFEST_VERSION,93 issuerDeviceId = issuerDeviceId,94 issuedAt = nowMs,95 96 97 98 devices = devices.map { normaliseManifestEntry(it) ?: it },99 revoked = revoked.map(::normaliseRevocation),100 )101 val signature = signEd25519(signingPrivateKey, canonicalDeviceManifestBody(body).toByteArray(Charsets.UTF_8))102 return SignedDeviceManifest(body, pubkeyToHex(signature))103}104105fun verifyDeviceManifest(106 manifest: SignedDeviceManifest,107 issuerSigningPublicKey: ByteArray,108 nowMs: Long = System.currentTimeMillis(),109 freshnessMs: Long = DEVICE_MANIFEST_FRESHNESS_MS,110): DeviceManifestBody? {111 val body = manifest.body112 if (body.manifestVersion != DEVICE_MANIFEST_VERSION) return null113 114 115 116 117 if (body.issuedAt < 0L) return null118 if (body.issuedAt < nowMs - freshnessMs || body.issuedAt > nowMs + freshnessMs) return null119 if (body.issuerDeviceId.isBlank() || body.issuerDeviceId.length > MAX_MANIFEST_STRING) return null120 if (body.devices.size > MAX_MANIFEST_DEVICES) return null121 if (body.revoked.size > MAX_MANIFEST_REVOCATIONS) return null122 if (!isHex(manifest.signatureHex, 128)) return null123 if (!body.devices.all { normaliseManifestEntry(it) != null }) return null124 if (!body.revoked.all { isValidRevocation(it) }) return null125 val signature = runCatching { hexToBytes(manifest.signatureHex) }.getOrNull() ?: return null126 val canonical = canonicalDeviceManifestBody(body).toByteArray(Charsets.UTF_8)127 if (!verifyEd25519(issuerSigningPublicKey, canonical, signature)) return null128 129 130 131 return body.copy(devices = body.devices.map { normaliseManifestEntry(it)!! })132}133134fun canonicalDeviceManifestBody(body: DeviceManifestBody): String =135 canonicalise(136 mapOf(137 "devices" to body.devices.map { manifestEntryMap(it) },138 "issuedAt" to body.issuedAt,139 "issuerDeviceId" to body.issuerDeviceId,140 "manifestVersion" to body.manifestVersion,141 "revoked" to body.revoked.map { revocationMap(it) },142 ),143 )144145fun PairedDevice.toManifestEntry(): ManifestDeviceEntry? {146 val id = deviceId.takeIf { it.isNotBlank() } ?: return null147 val name = deviceName?.takeIf { it.isNotBlank() }?.let(::capDeviceName) ?: return null148 val type = deviceType?.takeIf { it in setOf("extension", "android", "ios") } ?: return null149 val longTerm = longTermPublicKeyHex?.lowercase()?.takeIf { isHex(it, 64) } ?: return null150 val signing = signingPublicKeyHex?.lowercase()?.takeIf { isHex(it, 64) } ?: return null151 return ManifestDeviceEntry(152 deviceId = id,153 deviceName = name,154 deviceType = type,155 longTermPublicKeyHex = longTerm,156 signingPublicKeyHex = signing,157 wsPort = wsPort,158 relayUrl = relayUrl,159 pairedAt = pairedAt,160 vouchDepth = 0,161 )162}163164private fun normaliseManifestEntry(entry: ManifestDeviceEntry): ManifestDeviceEntry? {165 if (entry.deviceId.isBlank() || entry.deviceName.isBlank()) return null166 167 168 169 170 if (entry.deviceId.length > MAX_MANIFEST_STRING) return null171 if (entry.deviceType !in setOf("extension", "android", "ios")) return null172 if (!isHex(entry.longTermPublicKeyHex, 64) || !isHex(entry.signingPublicKeyHex, 64)) return null173 if (entry.wsPort != null && entry.wsPort !in 1..65_535) return null174 if (entry.pairedAt < 0L || entry.vouchDepth !in 0..MAX_VOUCH_DEPTH) return null175 if (176 entry.relayUrl != null && (177 entry.relayUrl.length > MAX_MANIFEST_STRING ||178 runCatching { Rendezvous.normalizeRelayUrl(entry.relayUrl) }.isFailure179 )180 ) return null181 return entry.copy(182 deviceName = capDeviceName(entry.deviceName),183 longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),184 signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),185 )186}187188private fun normaliseRevocation(r: DeviceRevocation): DeviceRevocation =189 r.copy(longTermPublicKeyHex = r.longTermPublicKeyHex.lowercase())190191private fun isValidRevocation(r: DeviceRevocation): Boolean =192 r.deviceId.isNotBlank() && r.deviceId.length <= MAX_MANIFEST_STRING &&193 isHex(r.longTermPublicKeyHex.lowercase(), 64) &&194 r.revokedByDeviceId.isNotBlank() && r.revokedByDeviceId.length <= MAX_MANIFEST_STRING &&195 r.revokedAt >= 0L196197private fun revocationMap(r: DeviceRevocation): Map<String, Any> = linkedMapOf(198 "deviceId" to r.deviceId,199 "longTermPublicKeyHex" to r.longTermPublicKeyHex.lowercase(),200 "revokedAt" to r.revokedAt,201 "revokedByDeviceId" to r.revokedByDeviceId,202)203204private fun manifestEntryMap(entry: ManifestDeviceEntry): Map<String, Any> {205 val normalised = normaliseManifestEntry(entry) ?: entry206 val map = linkedMapOf<String, Any>(207 "deviceId" to normalised.deviceId,208 "deviceName" to normalised.deviceName,209 "deviceType" to normalised.deviceType,210 "longTermPublicKeyHex" to normalised.longTermPublicKeyHex.lowercase(),211 "pairedAt" to normalised.pairedAt,212 "signingPublicKeyHex" to normalised.signingPublicKeyHex.lowercase(),213 "vouchDepth" to normalised.vouchDepth,214 )215 normalised.wsPort?.let { map["wsPort"] = it }216 normalised.relayUrl?.let { map["relayUrl"] = it }217 return map218}219220private fun canonicalise(value: Any?): String = when (value) {221 null -> "null"222 is Number -> {223 val d = value.toDouble()224 require(d.isFinite()) { "non-finite number" }225 if (d % 1.0 == 0.0) value.toLong().toString() else value.toString()226 }227 is String -> Json.encodeToString(String.serializer(), value)228 is Boolean -> if (value) "true" else "false"229 is List<*> -> value.joinToString(prefix = "[", postfix = "]", separator = ",") { canonicalise(it) }230 is Map<*, *> -> value.entries231 .map { (k, v) -> k.toString() to v }232 .sortedBy { it.first }233 .joinToString(prefix = "{", postfix = "}", separator = ",") { (k, v) ->234 Json.encodeToString(String.serializer(), k) + ":" + canonicalise(v)235 }236 else -> error("cannot canonicalise ${value::class.simpleName}")237}238239private fun isHex(value: String, length: Int): Boolean =240 value.length == length && value.all { it in '0'..'9' || it in 'a'..'f' }