1package com.peachpasswords.sync23import kotlinx.serialization.builtins.serializer4import kotlinx.serialization.json.Json5import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters678const val DEVICE_MANIFEST_VERSION = 0x059const val MAX_VOUCH_DEPTH = 310private const val DEVICE_MANIFEST_FRESHNESS_MS = 5 * 60_000L111213141516171819private const val MAX_MANIFEST_DEVICES = 25620internal const val MAX_MANIFEST_REVOCATIONS = 50021internal 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"3536data class DeviceManifestIssuerBinding(37 val deviceId: String,38 val longTermPublicKeyHex: String,39 val signingPublicKeyHex: String,40)41424344454647data class DeviceManifestRegistryBatch(48 val incomingRevocations: List<DeviceRevocation>,49 val removals: Set<String>,50 val upserts: List<PairedDevice>,51 val issuerSigningKeys: Map<String, Set<String>> = emptyMap(),52 val authenticatedIssuer: DeviceManifestIssuerBinding,53 val expectedSnapshot: DeviceManifestRegistrySnapshot,54)5556data class DeviceManifestRegistrySnapshot(57 val devices: List<PairedDevice>,58 val revocations: List<DeviceRevocation>,59 val issuerSigningKeys: Map<String, Set<String>>,60)6162interface PairedDeviceRegistry {63 fun getAll(): List<PairedDevice>64 fun get(id: String): PairedDevice?65 fun getByPubkey(pubkeyHex: String): PairedDevice? =66 getAll().firstOrNull {67 it.longTermPublicKeyHex?.let { key -> CryptoCompare.hex(key, pubkeyHex) } == true68 }69 fun upsert(device: PairedDevice)70 fun remove(deviceId: String) {}71 fun listRevocations(): List<DeviceRevocation> = emptyList()7273 74757677 fun issuerSigningKeys(issuerDeviceId: String): Set<String> = emptySet()78 fun appendIssuerSigningKey(issuerDeviceId: String, signingKeyHex: String): Boolean = true7980 81 fun manifestSnapshot(requestedIssuerIds: Set<String>): DeviceManifestRegistrySnapshot {82 val devices = getAll()83 val revocations = listRevocations()84 val issuers = requestedIssuerIds + devices.map { it.deviceId } + revocations.map { it.revokedByDeviceId }85 return DeviceManifestRegistrySnapshot(86 devices,87 revocations,88 issuers.associateWith { issuerSigningKeys(it).toSet() },89 )90 }9192 93 fun applyManifestBatch(batch: DeviceManifestRegistryBatch): Boolean9495 96 fun mergeRevocations(incoming: List<DeviceRevocation>): List<String> = emptyList()9798 99100101102103104105106 fun isRevoked(deviceId: String, longTermPublicKeyHex: String? = null): Boolean {107 val key = longTermPublicKeyHex?.lowercase()?.takeIf { it != NO_KEY_SENTINEL }108 return listRevocations().any {109 it.deviceId == deviceId || (key != null && it.longTermPublicKeyHex.lowercase() == key)110 }111 }112113 114 fun clearRevocation(deviceId: String) {}115}116117fun buildSignedDeviceManifest(118 issuerDeviceId: String,119 devices: List<ManifestDeviceEntry>,120 signingPrivateKey: Ed25519PrivateKeyParameters,121 nowMs: Long = System.currentTimeMillis(),122 revoked: List<DeviceRevocation> = emptyList(),123): SignedDeviceManifest {124 require(issuerDeviceId.isNotBlank()) { "issuerDeviceId is required" }125 val body = DeviceManifestBody(126 manifestVersion = DEVICE_MANIFEST_VERSION,127 issuerDeviceId = issuerDeviceId,128 issuedAt = nowMs,129 devices = devices.map { normaliseManifestEntry(it) ?: it },130 revoked = revoked.map { record ->131 132 133 134 if (record.signatureHex.isNotBlank()) record else signDeviceRevocation(record, signingPrivateKey)135 },136 )137 val signature = signEd25519(signingPrivateKey, canonicalDeviceManifestBody(body).toByteArray(Charsets.UTF_8))138 return SignedDeviceManifest(body, pubkeyToHex(signature))139}140141142fun signDeviceRevocation(143 record: DeviceRevocation,144 signingPrivateKey: Ed25519PrivateKeyParameters,145): DeviceRevocation {146 val unsigned = record.copy(signatureHex = "")147 val signature = signEd25519(148 signingPrivateKey,149 canonicalDeviceRevocation(unsigned).toByteArray(Charsets.UTF_8),150 )151 return unsigned.copy(signatureHex = pubkeyToHex(signature))152}153154155fun canonicalDeviceRevocation(record: DeviceRevocation): String =156 canonicalise(157 mapOf(158 "deviceId" to record.deviceId,159 "longTermPublicKeyHex" to record.longTermPublicKeyHex.lowercase(),160 "recordVersion" to record.recordVersion,161 "revokedAt" to record.revokedAt,162 "revokedByDeviceId" to record.revokedByDeviceId,163 ),164 )165166fun verifyDeviceRevocation(record: DeviceRevocation, issuerSigningPublicKey: ByteArray): Boolean {167 if (!isHex(record.signatureHex, 128)) return false168 val signature = runCatching { hexToBytes(record.signatureHex) }.getOrNull() ?: return false169 return verifyEd25519(170 issuerSigningPublicKey,171 canonicalDeviceRevocation(record.copy(signatureHex = "")).toByteArray(Charsets.UTF_8),172 signature,173 )174}175176177178179180181182183184185186187private fun isAuthorisedRevocation(188 record: DeviceRevocation,189 resolveIssuerSigningKeys: (String) -> Set<String>,190): Boolean {191 val signature = runCatching { hexToBytes(record.signatureHex) }.getOrNull() ?: return false192 val payload = canonicalDeviceRevocation(record.copy(signatureHex = "")).toByteArray(Charsets.UTF_8)193 val trusted = resolveIssuerSigningKeys(record.revokedByDeviceId)194 if (trusted.isEmpty()) return false195 return trusted.any { key ->196 val hex = key.lowercase()197 isHex(hex, 64) && verifyEd25519(hexToPubkey(hex), payload, signature)198 }199}200201fun verifyDeviceManifest(202 manifest: SignedDeviceManifest,203 issuerSigningPublicKey: ByteArray,204 resolveIssuerSigningKeys: (String) -> Set<String>,205 nowMs: Long = System.currentTimeMillis(),206 freshnessMs: Long = DEVICE_MANIFEST_FRESHNESS_MS,207): DeviceManifestBody? {208 val body = manifest.body209 if (body.manifestVersion != DEVICE_MANIFEST_VERSION) return null210 211 212 213 214 if (body.issuedAt < 0L) return null215 if (body.issuedAt < nowMs - freshnessMs || body.issuedAt > nowMs + freshnessMs) return null216 if (body.issuerDeviceId.isBlank() || body.issuerDeviceId.length > MAX_MANIFEST_STRING) return null217 if (body.devices.size > MAX_MANIFEST_DEVICES) return null218 if (body.revoked.size > MAX_MANIFEST_REVOCATIONS) return null219 220 221 222 if (body.devices.any { normaliseManifestEntry(it) == null }) return null223 if (!isHex(manifest.signatureHex, 128)) return null224 if (!body.revoked.all { isValidRevocation(it) }) return null225 val signature = runCatching { hexToBytes(manifest.signatureHex) }.getOrNull() ?: return null226 val canonical = canonicalDeviceManifestBody(body).toByteArray(Charsets.UTF_8)227 if (!verifyEd25519(issuerSigningPublicKey, canonical, signature)) return null228 229 230 231 232 233 234 if (!body.revoked.all { record -> isAuthorisedRevocation(record, resolveIssuerSigningKeys) }) return null235 236 237 238 return body.copy(devices = body.devices.map { normaliseManifestEntry(it)!! })239}240241fun canonicalDeviceManifestBody(body: DeviceManifestBody): String =242 canonicalise(243 mapOf(244 "devices" to body.devices.map { manifestEntryMap(it) },245 "issuedAt" to body.issuedAt,246 "issuerDeviceId" to body.issuerDeviceId,247 "manifestVersion" to body.manifestVersion,248 "revoked" to body.revoked.map { revocationMap(it) },249 ),250 )251252fun PairedDevice.toManifestEntry(): ManifestDeviceEntry? {253 val id = deviceId.takeIf { it.isNotBlank() } ?: return null254 val name = deviceName?.takeIf { it.isNotBlank() }?.let(::capDeviceName) ?: return null255 val type = deviceType?.takeIf { it in setOf("extension", "android", "ios") } ?: return null256 val longTerm = longTermPublicKeyHex?.lowercase()?.takeIf { isHex(it, 64) } ?: return null257 val signing = signingPublicKeyHex?.lowercase()?.takeIf { isHex(it, 64) } ?: return null258 return ManifestDeviceEntry(259 deviceId = id,260 deviceName = name,261 deviceType = type,262 longTermPublicKeyHex = longTerm,263 signingPublicKeyHex = signing,264 wsPort = wsPort,265 relayUrl = relayUrl,266 pairedAt = pairedAt,267 vouchDepth = 0,268 )269}270271private fun normaliseManifestEntry(entry: ManifestDeviceEntry): ManifestDeviceEntry? {272 if (entry.deviceId.isBlank() || entry.deviceName.isBlank()) return null273 if (entry.deviceId.length > MAX_MANIFEST_STRING) return null274 if (entry.deviceType !in setOf("extension", "android", "ios")) return null275 if (!isHex(entry.longTermPublicKeyHex, 64) || !isHex(entry.signingPublicKeyHex, 64)) return null276 if (entry.wsPort != null && entry.wsPort !in 1..65_535) return null277 if (entry.pairedAt < 0L || entry.vouchDepth !in 0..MAX_VOUCH_DEPTH) return null278 if (279 entry.relayUrl != null && (280 entry.relayUrl.length > MAX_MANIFEST_STRING ||281 runCatching { Rendezvous.normalizeRelayUrl(entry.relayUrl) }.isFailure282 )283 ) return null284 return entry.copy(285 deviceName = capDeviceName(entry.deviceName),286 longTermPublicKeyHex = entry.longTermPublicKeyHex.lowercase(),287 signingPublicKeyHex = entry.signingPublicKeyHex.lowercase(),288 )289}290291private fun normaliseRevocation(r: DeviceRevocation): DeviceRevocation =292 r.copy(longTermPublicKeyHex = r.longTermPublicKeyHex.lowercase())293294private fun isValidRevocation(r: DeviceRevocation): Boolean =295 r.recordVersion == DEVICE_REVOCATION_RECORD_VERSION &&296 r.deviceId.isNotBlank() && r.deviceId.length <= MAX_MANIFEST_STRING &&297 isHex(r.longTermPublicKeyHex.lowercase(), 64) &&298 r.revokedByDeviceId.isNotBlank() && r.revokedByDeviceId.length <= MAX_MANIFEST_STRING &&299 isHex(r.signatureHex, 128) &&300 r.revokedAt >= 0L301 302303private fun revocationMap(r: DeviceRevocation): Map<String, Any> = linkedMapOf(304 "deviceId" to r.deviceId,305 "longTermPublicKeyHex" to r.longTermPublicKeyHex.lowercase(),306 "recordVersion" to r.recordVersion,307 "revokedAt" to r.revokedAt,308 "revokedByDeviceId" to r.revokedByDeviceId,309 "signatureHex" to r.signatureHex.lowercase(),310)311312private fun manifestEntryMap(entry: ManifestDeviceEntry): Map<String, Any> {313 val normalised = normaliseManifestEntry(entry) ?: entry314 val map = linkedMapOf<String, Any>(315 "deviceId" to normalised.deviceId,316 "deviceName" to normalised.deviceName,317 "deviceType" to normalised.deviceType,318 "longTermPublicKeyHex" to normalised.longTermPublicKeyHex.lowercase(),319 "pairedAt" to normalised.pairedAt,320 "signingPublicKeyHex" to normalised.signingPublicKeyHex.lowercase(),321 "vouchDepth" to normalised.vouchDepth,322 )323 normalised.wsPort?.let { map["wsPort"] = it }324 normalised.relayUrl?.let { map["relayUrl"] = it }325 return map326}327328private fun canonicalise(value: Any?): String = when (value) {329 null -> "null"330 is Number -> {331 val d = value.toDouble()332 require(d.isFinite()) { "non-finite number" }333 if (d % 1.0 == 0.0) value.toLong().toString() else value.toString()334 }335 is String -> Json.encodeToString(String.serializer(), value)336 is Boolean -> if (value) "true" else "false"337 is List<*> -> value.joinToString(prefix = "[", postfix = "]", separator = ",") { canonicalise(it) }338 is Map<*, *> -> value.entries339 .map { (k, v) -> k.toString() to v }340 .sortedBy { it.first }341 .joinToString(prefix = "{", postfix = "}", separator = ",") { (k, v) ->342 Json.encodeToString(String.serializer(), k) + ":" + canonicalise(v)343 }344 else -> error("cannot canonicalise ${value::class.simpleName}")345}346347private fun isHex(value: String, length: Int): Boolean =348 value.length == length && value.all { it in '0'..'9' || it in 'a'..'f' }