()
+ private val captured = AtomicBoolean(false)
+ private val closed = AtomicBoolean(false)
+
+ init {
+ scope.launch { acceptLoop() }
+ }
+
+ /**
+ * Runs [open] (the browser launch) while waiting for the validated code. A launch that fails before
+ * any code arrived ends the wait with [HermesException.Kind.BrowserAuthenticationUnavailable]; one that
+ * fails or is cancelled later cannot erase a captured code. Returns the code after the success page
+ * has been flushed.
+ */
+ suspend fun awaitCode(open: suspend () -> Unit): String {
+ try {
+ return coroutineScope {
+ val opener = launch {
+ try {
+ open()
+ } catch (e: CancellationException) {
+ throw e
+ } catch (_: Exception) {
+ if (!captured.get()) result.completeExceptionally(HermesException(HermesException.Kind.BrowserAuthenticationUnavailable))
+ }
+ }
+ try {
+ withTimeout(timings.browserSignInMillis) { result.await() }
+ } catch (_: TimeoutCancellationException) {
+ throw HermesException(HermesException.Kind.TimedOut)
+ } finally {
+ opener.cancel()
+ }
+ }
+ } finally {
+ close()
+ }
+ }
+
+ override fun close() {
+ if (!closed.compareAndSet(false, true)) return
+ result.completeExceptionally(HermesException(HermesException.Kind.Cancelled))
+ closeQuietly(server)
+ connections.forEach(::closeQuietly)
+ scope.cancel()
+ }
+
+ private fun acceptLoop() {
+ while (!closed.get() && !captured.get()) {
+ val socket = try {
+ server.accept()
+ } catch (_: IOException) {
+ return
+ }
+ if (captured.get() || connections.size >= MAXIMUM_CONNECTIONS) {
+ closeQuietly(socket)
+ continue
+ }
+ connections.add(socket)
+ scope.launch { handle(socket) }
+ }
+ }
+
+ private suspend fun handle(socket: Socket) {
+ val deadline = scope.launch { delay(timings.callbackRequestMillis); closeQuietly(socket) }
+ try {
+ socket.soTimeout = timings.callbackRequestMillis.toInt()
+ val request = readRequest(socket) ?: return
+ val code = try {
+ validate(request, port, path, state)
+ } catch (_: HermesException) {
+ return
+ }
+ if (!captured.compareAndSet(false, true)) return
+ deadline.cancel()
+ // Other readers stop; a static page is flushed before the code is handed over.
+ connections.filter { it !== socket }.forEach(::closeQuietly)
+ closeQuietly(server)
+ val flushDeadline = scope.launch { delay(timings.callbackResponseFlushMillis); closeQuietly(socket) }
+ try {
+ socket.getOutputStream().apply { write(SUCCESS_RESPONSE); flush() }
+ socket.shutdownOutput()
+ } catch (_: IOException) {
+ // The code is already ours; a browser that went away early changes nothing.
+ }
+ flushDeadline.cancel()
+ result.complete(code)
+ } catch (_: IOException) {
+ // A reset or timed-out connection never consumes the sign-in.
+ } finally {
+ deadline.cancel()
+ connections.remove(socket)
+ closeQuietly(socket)
+ }
+ }
+
+ /** Reads up to the header terminator; refuses oversize input and anything after the terminator. */
+ private fun readRequest(socket: Socket): ByteArray? {
+ val input = socket.getInputStream()
+ val buffer = ByteArrayOutputStream()
+ val chunk = ByteArray(4_096)
+ while (true) {
+ val count = input.read(chunk)
+ if (count <= 0 || count > MAXIMUM_REQUEST_BYTES - buffer.size()) return null
+ buffer.write(chunk, 0, count)
+ val bytes = buffer.toByteArray()
+ val end = indexOfTerminator(bytes)
+ if (end >= 0) return if (end + 4 == bytes.size) bytes else null
+ }
+ }
+
+ companion object {
+ const val MAXIMUM_REQUEST_BYTES = 16_384
+ private const val MAXIMUM_CONNECTIONS = 4
+ private const val MAXIMUM_TOKEN_BYTES = 4_096
+
+ private val SUCCESS_RESPONSE: ByteArray = run {
+ val body = "bighelp" +
+ "Sign-in received. Return to bighelp.
"
+ ("HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: ${body.toByteArray().size}\r\n" +
+ "Cache-Control: no-store\r\nPragma: no-cache\r\nReferrer-Policy: no-referrer\r\n" +
+ "Content-Security-Policy: default-src 'none'; frame-ancestors 'none'\r\nX-Content-Type-Options: nosniff\r\n" +
+ "Connection: close\r\n\r\n$body").toByteArray(Charsets.US_ASCII)
+ }
+
+ /** Binds `127.0.0.1` on an OS-chosen port; never a wildcard address. */
+ fun bind(callbackPath: String, state: String, timings: AuthTimings): LoopbackCallbackListener {
+ require(isValidPath(callbackPath) && isUrlToken(state)) { "Invalid callback" }
+ val server = try {
+ ServerSocket(0, 4, InetAddress.getByAddress(byteArrayOf(127, 0, 0, 1)))
+ } catch (_: IOException) {
+ throw HermesException(HermesException.Kind.BrowserAuthenticationUnavailable)
+ }
+ return LoopbackCallbackListener(server, callbackPath, state, timings)
+ }
+
+ /**
+ * Exactly one `GET ?state=&code= HTTP/1.1` with strict CRLF framing, the exact
+ * `Host: 127.0.0.1:`, unique headers, no body or upgrade, and two token-valued query fields.
+ * @return the code
+ * @throws HermesException InvalidResponse (or MessageTooLarge) for anything else.
+ */
+ fun validate(request: ByteArray, port: Int, path: String, state: String): String {
+ fun invalid(): Nothing = throw HermesException(HermesException.Kind.InvalidResponse)
+ if (request.size > MAXIMUM_REQUEST_BYTES) throw HermesException(HermesException.Kind.MessageTooLarge)
+ if (!request.all { val b = it.toInt() and 0xff; b in 32..126 || b == 9 || b == 10 || b == 13 }) invalid()
+ val text = String(request, Charsets.US_ASCII)
+ if (!text.endsWith("\r\n\r\n")) invalid()
+ val lines = text.split("\r\n")
+ if (lines.size !in 4..68 || lines.takeLast(2).any { it.isNotEmpty() } ||
+ lines.dropLast(2).any { it.isEmpty() || '\r' in it || '\n' in it }
+ ) invalid()
+ val requestLine = lines[0].split(' ')
+ if (requestLine.size != 3 || requestLine[0] != "GET" || requestLine[2] != "HTTP/1.1") invalid()
+
+ val headers = HashMap()
+ for (line in lines.subList(1, lines.size - 2)) {
+ val colon = line.indexOf(':')
+ if (colon < 0) invalid()
+ val name = line.substring(0, colon)
+ if (name.isEmpty() || !name.all(::isHeaderToken)) invalid()
+ if (headers.putIfAbsent(name.lowercase(), line.substring(colon + 1).trim(' ', '\t')) != null) invalid()
+ }
+ if (headers["host"] != "127.0.0.1:$port" || "transfer-encoding" in headers || "expect" in headers ||
+ "upgrade" in headers || "trailer" in headers || headers["content-length"]?.let { it != "0" } == true
+ ) invalid()
+
+ val target = requestLine[1].split('?')
+ if (target.size != 2 || target[0] != path) invalid()
+ val fields = target[1].split('&')
+ if (fields.size != 2) invalid()
+ val query = HashMap()
+ for (field in fields) {
+ val pair = field.split('=')
+ if (pair.size != 2) invalid()
+ val key = decodeToken(pair[0])
+ val value = decodeToken(pair[1])
+ if ((key != "state" && key != "code") || query.put(key, value) != null) invalid()
+ }
+ val code = query["code"]
+ if (code == null || !MessageDigest.isEqual((query["state"] ?: invalid()).toByteArray(), state.toByteArray())) invalid()
+ return code
+ }
+
+ /** Strict percent-decoding: `+` is not a space, and every decoded byte must be a URL-safe token character. */
+ private fun decodeToken(encoded: String): String {
+ val result = StringBuilder()
+ var index = 0
+ while (index < encoded.length) {
+ val byte: Int
+ if (encoded[index] == '%') {
+ if (index + 2 >= encoded.length) throw HermesException(HermesException.Kind.InvalidResponse)
+ val high = Character.digit(encoded[index + 1], 16)
+ val low = Character.digit(encoded[index + 2], 16)
+ if (high < 0 || low < 0) throw HermesException(HermesException.Kind.InvalidResponse)
+ byte = high * 16 + low
+ index += 3
+ } else {
+ byte = encoded[index].code
+ index += 1
+ }
+ if (byte > 0x7f || !isUrlToken(byte.toChar()) || result.length >= MAXIMUM_TOKEN_BYTES) {
+ throw HermesException(HermesException.Kind.InvalidResponse)
+ }
+ result.append(byte.toChar())
+ }
+ if (result.isEmpty()) throw HermesException(HermesException.Kind.InvalidResponse)
+ return result.toString()
+ }
+
+ private fun isUrlToken(c: Char) = c in 'A'..'Z' || c in 'a'..'z' || c in '0'..'9' || c == '-' || c == '_'
+ private fun isUrlToken(text: String) = text.isNotEmpty() && text.length <= MAXIMUM_TOKEN_BYTES && text.all(::isUrlToken)
+ private fun isHeaderToken(c: Char) = isUrlToken(c) || c in "!#$%&'*+.^`|~"
+
+ private fun isValidPath(path: String) = path.startsWith("/") && !path.startsWith("//") && path.length <= 1_024 &&
+ "//" !in path && path.all { isUrlToken(it) || it == '/' || it == '.' } &&
+ path.split('/').none { it == "." || it == ".." }
+
+ private fun indexOfTerminator(bytes: ByteArray): Int {
+ for (i in 0..bytes.size - 4) {
+ if (bytes[i] == 13.toByte() && bytes[i + 1] == 10.toByte() && bytes[i + 2] == 13.toByte() && bytes[i + 3] == 10.toByte()) return i
+ }
+ return -1
+ }
+
+ private fun closeQuietly(socket: Socket) {
+ try { socket.close() } catch (_: IOException) { }
+ }
+
+ private fun closeQuietly(server: ServerSocket) {
+ try { server.close() } catch (_: IOException) { }
+ }
+ }
+}
diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt
new file mode 100644
index 00000000..1a8130fd
--- /dev/null
+++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt
@@ -0,0 +1,939 @@
+package app.bighelp.hermes
+
+import java.util.UUID
+import java.util.concurrent.ConcurrentHashMap
+import kotlin.coroutines.cancellation.CancellationException
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.CoroutineDispatcher
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Deferred
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.NonCancellable
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.async
+import kotlinx.coroutines.channels.Channel
+import kotlinx.coroutines.channels.trySendBlocking
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.put
+
+/**
+ * The ordered Hermes gateway: one authenticated WebSocket at a time, a single ordered reader and a single
+ * ordered writer, and nothing written before `gateway.ready`.
+ *
+ * **Connect.** `connect()` mints credentials through the [HermesAuthenticator] (a fresh single-use ticket
+ * for every socket of a gated host), waits up to [GatewayTimings.readyMillis] for `gateway.ready`, then, in
+ * order: advertises `client.capabilities {server_requests:true}` **only if handlers are registered**,
+ * checks authenticated `GET /api/health`, and asks `gateway.capabilities`. Only then is the state
+ * [GatewayConnection.Connected]. The advertisement repeats on every ready socket, so register handlers
+ * before connecting.
+ *
+ * **Never silent about uncertainty.** A frame is marked `sendStarted` before it is handed to the socket. If
+ * the connection ends while a mutation is pending, that request fails with
+ * [HermesException.outcomeUnknown]; the client does not reconnect on its own, and no request is ever
+ * resent on any socket. Reads and controls fail plainly and the automatic same-owner recovery (delays 0, 1
+ * and 3 seconds) replaces the socket, advertises again and rediscovers capabilities, for the owner to
+ * reconcile with session recovery.
+ *
+ * **Server requests.** Handlers answer the host's `approval`, `clarify`, `secret` and `sudo` requests. IDs
+ * are opaque and live in a table separate from the client's own RPC IDs (64 at most; duplicates and an
+ * over-capacity request are ignored). An unknown method gets `-32601`. A matching `request.cancel` (ID
+ * **and** method) cancels the handler and removes a queued response.
+ *
+ * **Ordering and atomicity.** Every received message is decoded whole by [HermesWire] before any entry is
+ * applied; entries are applied and published in wire order. Everything mutable lives on one
+ * single-threaded dispatcher, so no result or event of an older socket can publish after a newer one starts.
+ *
+ * **Inbound bounds.** The socket (see `GatewayWebSocket.kt`) refuses a frame by its declared length before
+ * allocating for it, caps the sum of fragments at 4 MiB, rejects malformed UTF-8 in a TEXT message instead of
+ * repairing it, bounds the upgrade response headers, offers no extensions, and keeps the platform's default
+ * TLS certificate and hostname checks.
+ *
+ * **Outbound bounds.** Frames reach the socket one at a time: the writer stops while the socket still holds
+ * unwritten data, so a stalled peer fills this client's own bounded queues (8 MiB of ordinary requests, one
+ * attachment of up to 12 MiB counted apart, 4 MiB of server replies) and then refuses new requests with
+ * [HermesException.Kind.TooManyRequests] instead of growing without limit.
+ */
+@OptIn(ExperimentalCoroutinesApi::class)
+class GatewayClient internal constructor(
+ private val authenticator: HermesAuthenticator,
+ private val scope: CoroutineScope,
+ private val timings: GatewayTimings,
+ private val transports: GatewayTransportFactory,
+) {
+ constructor(
+ authenticator: HermesAuthenticator,
+ scope: CoroutineScope,
+ timings: GatewayTimings = GatewayTimings(),
+ ) : this(authenticator, scope, timings, GatewayWebSockets)
+
+ private val serial: CoroutineDispatcher = Dispatchers.Default.limitedParallelism(1)
+
+ /** Owns only the one-second hard-close timers, so they outlive the caller's scope; each ends by itself. */
+ private val fallbackClose = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+
+ // Everything below is touched only on [serial], except the concurrent collections.
+ private var terminal = false
+ private var link: Link? = null
+ private var generation = 0L
+ private var owners = OwnerState.none
+ private var lastFailure: HermesException? = null
+ private var opening: Deferred? = null
+ private var openingWaiters = 0
+ private var recovery: Job? = null
+ private val handlers = ConcurrentHashMap()
+ private val subscribers = ConcurrentHashMap.newKeySet>()
+ private val mutableState = MutableStateFlow(GatewayState(GatewayConnection.Idle, 0, null, null, null, false, null))
+
+ val state: StateFlow = mutableState.asStateFlow()
+
+ /**
+ * Every event of every socket, in wire order, each with its socket generation. A collector sees events
+ * from the moment it starts collecting, plus the retained first `gateway.ready` of a socket that is
+ * already ready; start collecting before [connect] to see everything. A collector too slow to keep up
+ * ([EVENT_BUFFER] events behind) fails with [HermesException.Kind.TooManyRequests] and must resynchronize.
+ */
+ val events: Flow = flow {
+ val channel = Channel(EVENT_BUFFER)
+ withContext(serial) {
+ subscribers += channel
+ link?.let { l ->
+ val ready = l.socket.ready
+ if (l.socket.phase == SocketPhase.Ready && ready != null) channel.trySend(GatewayEvent(l.generation, ready))
+ }
+ }
+ try {
+ for (event in channel) emit(event)
+ } finally {
+ withContext(NonCancellable + serial) { subscribers -= channel }
+ }
+ }
+
+ internal val subscriberCount: Int get() = subscribers.size
+
+ /** The bytes waiting in each bounded queue of the current socket (a test seam). */
+ internal class QueueSnapshot(val ordinary: Int, val attachment: Int, val server: Int, val frames: Int)
+
+ internal suspend fun queueSnapshot(): QueueSnapshot = withContext(serial) {
+ link?.let { QueueSnapshot(it.queuedBytes, it.queuedAttachmentBytes, it.queuedServerBytes, it.outbox.size) } ?: QueueSnapshot(0, 0, 0, 0)
+ }
+
+ private class Pending(
+ val id: String,
+ val method: String,
+ val result: CompletableDeferred,
+ val readOnly: Boolean,
+ val isAttachment: Boolean,
+ ) {
+ var sendStarted = false
+ var timeout: Job? = null
+ }
+
+ /** [kind] decides which of the three bounded queues counts it. */
+ private class Outbound(val id: String, val serverMethod: String?, val text: String, val bytes: Int, val attachment: Boolean = false)
+ private class ServerTask(val token: Any, val job: Job)
+
+ private sealed interface Inbound {
+ class Opened(val subprotocol: String?) : Inbound
+ class Message(val bytes: ByteArray) : Inbound
+ class Failed(val error: HermesException) : Inbound
+ }
+
+ private inner class Link(val generation: Long, val owner: ConnectionOwner, val request: SocketRequest) {
+ var socket: GatewaySocket = GatewaySocket.opening(owner)
+ var transport: GatewayTransport? = null
+ val inbound = Channel(INBOUND_BUFFER)
+ var reader: Job? = null
+ var heartbeat: Job? = null
+ var readyDeadline: Job? = null
+ val readyGate = CompletableDeferred()
+ val pending = LinkedHashMap()
+ val outbox = ArrayDeque()
+ var queuedBytes = 0
+ var queuedAttachmentBytes = 0
+ var queuedServerBytes = 0
+ var attachmentId: String? = null
+ var draining = false
+ val serverRequests = ServerRequestTable()
+ val serverTasks = HashMap()
+ var closed = false
+ var wasReady = false
+ var connected = false
+ var advertised = false
+ }
+
+ // Connecting
+
+ /** Opens the socket, waits for readiness and runs the startup sequence. Joins a connect already running. */
+ suspend fun connect(): GatewayState = open(verify = false)
+
+ /**
+ * Like [connect] but first rediscovers the host's authentication mode and rechecks the identity (what
+ * the automatic recovery does). Returns at once if already connected. It never resends anything.
+ */
+ suspend fun reconnect(): GatewayState = open(verify = true)
+
+ private suspend fun open(verify: Boolean): GatewayState {
+ val flight = withContext(serial) {
+ if (terminal) throw notConnected()
+ val current = link
+ if (current != null && current.connected) return@withContext CompletableDeferred(mutableState.value)
+ opening?.let { openingWaiters++; return@withContext it }
+ val created = scope.async(serial) {
+ try {
+ establish(verify)
+ } finally {
+ opening = null
+ }
+ }
+ opening = created
+ openingWaiters = 1
+ created
+ }
+ try {
+ return flight.await()
+ } catch (e: CancellationException) {
+ // Nobody is left waiting for this attempt: end it, closing its socket.
+ withContext(NonCancellable + serial) { if (--openingWaiters <= 0 && opening === flight) flight.cancel() }
+ throw e
+ }
+ }
+
+ private suspend fun establish(verify: Boolean): GatewayState {
+ if (verify) authenticator.verifyModeAndSession()
+ val request = authenticator.socketRequest()
+ val opened = startLink(request)
+ try {
+ opened.readyGate.await()
+ handshake(opened)
+ } catch (e: Throwable) {
+ val error = if (e is CancellationException) HermesException(HermesException.Kind.Cancelled) else asHermes(e)
+ closeLink(opened, error, notify = false)
+ throw if (e is CancellationException) e else error
+ }
+ return mutableState.value
+ }
+
+ private fun startLink(request: SocketRequest): Link {
+ if (terminal) throw notConnected()
+ link?.let { closeLink(it, HermesException(HermesException.Kind.Disconnected), notify = false) }
+ generation += 1
+ owners = owners.connect(authenticator.endpoint, authenticator.savedConnection?.principal.orEmpty())
+ val created = Link(generation, owners.current!!, request)
+ link = created
+ publish()
+
+ try {
+ created.transport = transports.open(request, listenerFor(created))
+ } catch (e: HermesException) {
+ closeLink(created, e, notify = false)
+ throw e
+ }
+ created.reader = scope.launch(serial) { readLoop(created) }
+ created.readyDeadline = scope.launch(serial) {
+ delay(timings.readyMillis)
+ if (!created.wasReady) closeLink(created, HermesException(HermesException.Kind.TimedOut), notify = false)
+ }
+ return created
+ }
+
+ /** Socket callbacks arrive on the socket's reader thread; a full buffer blocks it, which is TCP backpressure. */
+ private fun listenerFor(owner: Link) = object : GatewayTransportListener {
+ override fun opened(negotiatedSubprotocol: String?) {
+ owner.inbound.trySendBlocking(Inbound.Opened(negotiatedSubprotocol))
+ }
+
+ override fun message(bytes: ByteArray) {
+ owner.inbound.trySendBlocking(Inbound.Message(bytes))
+ }
+
+ override fun failed(error: HermesException) {
+ owner.inbound.trySendBlocking(Inbound.Failed(error))
+ }
+ }
+
+ /** The single ordered reader: one inbound item at a time, each fully applied before the next is read. */
+ private suspend fun readLoop(owner: Link) {
+ for (item in owner.inbound) {
+ if (owner.closed) return
+ when (item) {
+ is Inbound.Opened -> {
+ val required = owner.request.requiredSubprotocol
+ if (required != null && item.subprotocol != required) {
+ closeLink(owner, HermesException(HermesException.Kind.InvalidResponse), notify = false)
+ return
+ }
+ owner.socket = owner.socket.upgraded()
+ }
+ is Inbound.Message -> {
+ val decoded = try {
+ withContext(Dispatchers.Default) { HermesWire.decode(item.bytes) }
+ } catch (e: WireException) {
+ closeLink(owner, HermesException(
+ if (e.kind == WireException.Kind.MessageTooLarge) HermesException.Kind.MessageTooLarge else HermesException.Kind.InvalidResponse,
+ ), notify = true)
+ return
+ }
+ if (owner.closed) return
+ accept(owner, decoded)
+ }
+ is Inbound.Failed -> {
+ closeLink(owner, item.error, notify = true)
+ return
+ }
+ }
+ }
+ }
+
+ private fun accept(owner: Link, messages: List) {
+ for (message in messages) {
+ if (owner.closed) return
+ when (message) {
+ is WireMessage.Event -> {
+ if (message.type == "request.cancel") retireServerRequest(owner, HermesWire.cancellation(message))
+ if (message.type == GatewaySocket.GATEWAY_READY) {
+ val next = owner.socket.receive(message)
+ if (next.phase == SocketPhase.Closed || next.phase != SocketPhase.Ready) {
+ // A second ready on a ready socket, or one that arrives at the wrong time.
+ closeLink(owner, HermesException(HermesException.Kind.InvalidResponse), notify = true)
+ return
+ }
+ owner.socket = next
+ owner.wasReady = true
+ owner.readyDeadline?.cancel()
+ owner.readyGate.complete(Unit)
+ startHeartbeat(owner)
+ pump(owner)
+ publish()
+ }
+ publishEvent(owner, message)
+ }
+ is WireMessage.Request -> acceptServerRequest(owner, message.id, message.method, message.params)
+ is WireMessage.Result -> finish(owner, message.id, Result.success(message.value))
+ is WireMessage.Failure -> finish(owner, message.id, Result.failure(rpcFailure(message)))
+ }
+ }
+ }
+
+ private fun rpcFailure(failure: WireMessage.Failure): HermesException {
+ val kind = if (failure.code == 4090L && failure.reason == "MAX_CONCURRENT_SESSIONS") {
+ HermesException.Kind.ActiveSessionLimit
+ } else {
+ HermesException.Kind.RpcRejected
+ }
+ return HermesException(kind, code = failure.code, reason = failure.reason, refusal = failure.message)
+ }
+
+ private fun publishEvent(owner: Link, event: WireMessage.Event) {
+ val published = GatewayEvent(owner.generation, event)
+ for (channel in subscribers) {
+ if (channel.trySend(published).isFailure) {
+ channel.close(HermesException(HermesException.Kind.TooManyRequests))
+ subscribers -= channel
+ }
+ }
+ }
+
+ // Startup sequence
+
+ private suspend fun handshake(owner: Link) {
+ if (claimAdvertisement(owner)) {
+ try {
+ requestOn(owner, "client.capabilities", buildJsonObject { put("server_requests", true) }, timings.advertiseMillis)
+ } catch (e: HermesException) {
+ // An older host that has no such method needs none; a lost socket is retried by the next one.
+ if (e.kind != HermesException.Kind.RpcRejected) {
+ owner.advertised = false
+ throw e
+ }
+ }
+ }
+ authenticator.requireHealth()
+ val result = requestOn(owner, "gateway.capabilities", JsonObject(emptyMap()), timings.requestMillis)
+ val capabilities = try {
+ GatewayCapabilities.decode(result)
+ } catch (_: WireException) {
+ throw HermesException(HermesException.Kind.InvalidResponse)
+ }
+ withContext(serial) {
+ if (owner.closed) throw notConnected()
+ owner.socket = owner.socket.discovered(capabilities)
+ owner.connected = true
+ publish()
+ }
+ }
+
+ /** True exactly once per socket, and only when real handlers exist: advertising promises to answer. */
+ private fun claimAdvertisement(owner: Link): Boolean {
+ if (owner.advertised || owner.closed || handlers.isEmpty()) return false
+ owner.advertised = true
+ return true
+ }
+
+ /**
+ * Registers (or, with null, removes) the handler for one server-request [method]. Only methods the
+ * app can really fulfill belong here; everything else is refused with `-32601`. Registration alone
+ * advertises nothing; the client advertises after `gateway.ready`, once per socket, as soon as it has
+ * any handler. Handlers survive an automatic same-owner recovery and are forgotten when a connection
+ * ends without one (an uncertain mutation, exhausted attempts, [disconnect]).
+ */
+ fun setServerRequestHandler(method: String, handler: ServerRequestHandler?) {
+ require(HermesWire.isValidMethod(method) && method != "event") { "Invalid method" }
+ if (handler == null) {
+ handlers.remove(method)
+ return
+ }
+ handlers[method] = handler
+ scope.launch(serial) {
+ val live = link ?: return@launch
+ if (live.socket.phase != SocketPhase.Ready || !claimAdvertisement(live)) return@launch
+ try {
+ requestOn(live, "client.capabilities", buildJsonObject { put("server_requests", true) }, timings.advertiseMillis)
+ } catch (e: HermesException) {
+ if (e.kind != HermesException.Kind.RpcRejected) live.advertised = false
+ }
+ }
+ }
+
+ // Requests
+
+ /**
+ * One JSON-RPC call. [operation] defaults from the method: reads, controls, and the three submission
+ * methods (`prompt.submit`, `slash.exec`, `command.dispatch`), which need the host's
+ * `per_session_exclusive_submit` guarantee. A refused admission sends nothing.
+ *
+ * Failures are [HermesException]s; [HermesException.outcomeUnknown] marks a mutation that may have been
+ * accepted. Cancelling the caller throws [RequestCancelledException] (a `CancellationException`) saying
+ * whether the frame had been handed to the socket; it never stops the host and is never resent.
+ *
+ * [generation] fences a call that names something only one socket knows (a runtime ID): it is compared with
+ * the current socket's generation in the same serial section that reads the socket, and a mismatch is
+ * [HermesException.Kind.NotConnected] before anything is queued. [requestOn] then enqueues on exactly that
+ * socket object, so the frame can only ever leave on the generation that was named.
+ */
+ suspend fun request(
+ method: String,
+ params: JsonObject = JsonObject(emptyMap()),
+ timeoutMillis: Long = timings.requestMillis,
+ operation: GatewayOperation? = null,
+ maximumFrameBytes: Int = DEFAULT_FRAME_BYTES,
+ generation: Long? = null,
+ ): JsonElement {
+ val live = withContext(serial) { link?.takeIf { generation == null || it.generation == generation } } ?: throw notConnected()
+ return requestOn(live, method, params, timeoutMillis, operation, maximumFrameBytes)
+ }
+
+ private suspend fun requestOn(
+ owner: Link,
+ method: String,
+ params: JsonObject,
+ timeoutMillis: Long,
+ operation: GatewayOperation? = null,
+ maximumFrameBytes: Int = DEFAULT_FRAME_BYTES,
+ ): JsonElement {
+ if (!HermesWire.isValidMethod(method)) throw HermesException(HermesException.Kind.InvalidResponse)
+ val isAttachment = method == "file.attach" || method == "image.attach_bytes"
+ val ceiling = if (isAttachment) ATTACHMENT_FRAME_BYTES else maximumOutboundBytes(method)
+ if (maximumFrameBytes > ceiling) throw HermesException(HermesException.Kind.MessageTooLarge)
+ val id = UUID.randomUUID().toString()
+ val text = buildJsonObject {
+ put("jsonrpc", "2.0"); put("id", id); put("method", method); put("params", params)
+ }.toString()
+ val bytes = utf8Length(text)
+ if (bytes > maximumFrameBytes || exceedsNesting(text)) throw HermesException(HermesException.Kind.MessageTooLarge)
+ val op = operation ?: when {
+ DispatchPolicy.isReadOnly(method) -> GatewayOperation.Read
+ method in SUBMISSION_METHODS -> GatewayOperation.Submission
+ else -> GatewayOperation.Control
+ }
+
+ try {
+ // Cancellation can land while the frame is already on its way out of enqueue; the cleanup and the
+ // dispatch outcome below must cover that window too, or a sent request would be forgotten.
+ val pending = withContext(serial) { enqueue(owner, id, method, op, text, bytes, timeoutMillis, isAttachment) }
+ return pending.result.await()
+ } catch (e: CancellationException) {
+ // Returning from withContext into an already cancelled caller rethrows its cancellation, even for
+ // NonCancellable work, so the outcome is captured inside the block where the cleanup runs.
+ var dispatch = DispatchOutcome.NotSent
+ try {
+ withContext(NonCancellable + serial) { dispatch = cancelPending(owner, id) }
+ } catch (_: CancellationException) {
+ // The cleanup above already ran.
+ }
+ throw RequestCancelledException(dispatch).also { it.initCause(e) }
+ }
+ }
+
+ private fun maximumOutboundBytes(method: String) = if (method == "profiles.set_asset") 2_800_000 else DEFAULT_FRAME_BYTES
+
+ private fun enqueue(
+ owner: Link, id: String, method: String, operation: GatewayOperation, text: String, bytes: Int,
+ timeoutMillis: Long, isAttachment: Boolean,
+ ): Pending {
+ if (owner.closed || owner !== link) throw notConnected()
+ when (val admission = owner.socket.admit(operation, owners)) {
+ Admission.Admitted -> Unit
+ is Admission.Refused -> throw HermesException(
+ if (admission.reason == Refusal.ExclusiveSubmitUnavailable) HermesException.Kind.ExclusiveSubmitUnavailable
+ else HermesException.Kind.NotConnected,
+ )
+ }
+ if (owner.pending.size >= MAXIMUM_PENDING) throw HermesException(HermesException.Kind.TooManyRequests)
+ // Three separate queues, so a flood of ordinary requests can never refuse the one attachment frame the
+ // contract allows (up to 12 MiB), nor the other way round, and neither starves a server reply.
+ if (isAttachment) {
+ if (owner.attachmentId != null || owner.queuedAttachmentBytes + bytes > ATTACHMENT_FRAME_BYTES) {
+ throw HermesException(HermesException.Kind.TooManyRequests)
+ }
+ } else if (owner.queuedBytes + bytes > MAXIMUM_QUEUED_BYTES) {
+ throw HermesException(HermesException.Kind.TooManyRequests)
+ }
+
+ val pending = Pending(id, method, CompletableDeferred(), DispatchPolicy.isReadOnly(method), isAttachment)
+ owner.pending[id] = pending
+ if (isAttachment) owner.attachmentId = id
+ pending.timeout = scope.launch(serial) {
+ delay(timeoutMillis)
+ expire(owner, id)
+ }
+ owner.outbox.addLast(Outbound(id, null, text, bytes, isAttachment))
+ if (isAttachment) owner.queuedAttachmentBytes += bytes else owner.queuedBytes += bytes
+ pump(owner)
+ return pending
+ }
+
+ /** Removes a cancelled request and reports how far it got. The frame, if sent, is not recalled. */
+ private fun cancelPending(owner: Link, id: String): DispatchOutcome {
+ val pending = owner.pending[id] ?: return DispatchOutcome.NotSent
+ val outcome = if (pending.sendStarted) DispatchOutcome.MayHaveBeenSent else DispatchOutcome.NotSent
+ removePending(owner, id)
+ return outcome
+ }
+
+ private fun removePending(owner: Link, id: String): Pending? {
+ val pending = owner.pending.remove(id) ?: return null
+ pending.timeout?.cancel()
+ if (owner.attachmentId == id) owner.attachmentId = null
+ val index = owner.outbox.indexOfFirst { it.id == id && it.serverMethod == null }
+ if (index >= 0) uncount(owner, owner.outbox.removeAt(index))
+ return pending
+ }
+
+ private fun finish(owner: Link, id: String, result: Result) {
+ val pending = removePending(owner, id) ?: return
+ result.fold({ pending.result.complete(it) }, { pending.result.completeExceptionally(it) })
+ }
+
+ private fun expire(owner: Link, id: String) {
+ val pending = owner.pending[id] ?: return
+ finish(owner, id, Result.failure(HermesException(HermesException.Kind.TimedOut, outcomeUnknown = pending.sendStarted && !pending.readOnly)))
+ // A stalled send is unparked before anything queued behind it could go out.
+ if (pending.sendStarted) closeLink(owner, HermesException(HermesException.Kind.TimedOut), notify = true)
+ }
+
+ /** Takes [item] out of whichever bounded queue counted it. */
+ private fun uncount(owner: Link, item: Outbound) {
+ when {
+ item.serverMethod != null -> owner.queuedServerBytes -= item.bytes
+ item.attachment -> owner.queuedAttachmentBytes -= item.bytes
+ else -> owner.queuedBytes -= item.bytes
+ }
+ }
+
+ /**
+ * The single ordered writer. Nothing leaves before ready; each frame is marked sent before the socket call.
+ * Frames go out one at a time, only while the socket holds no unwritten data: a peer that stops reading
+ * leaves the rest here, where it is bounded and a queued server reply can still be cancelled.
+ */
+ private fun pump(owner: Link) {
+ if (owner.closed || owner.socket.phase != SocketPhase.Ready) return
+ val transport = owner.transport ?: return
+ while (owner.outbox.isNotEmpty()) {
+ if (transport.hasBufferedData) {
+ drainLater(owner)
+ return
+ }
+ val item = owner.outbox.removeFirst()
+ uncount(owner, item)
+ if (item.serverMethod != null) {
+ if (!owner.serverRequests.beginSendingResponse(item.id, item.serverMethod)) continue
+ } else {
+ val pending = owner.pending[item.id] ?: continue
+ pending.sendStarted = true
+ }
+ if (!transport.send(item.text)) {
+ closeLink(owner, HermesException(HermesException.Kind.Disconnected), notify = true)
+ return
+ }
+ }
+ }
+
+ /**
+ * Resumes the writer once the socket has taken what it was given. The library offers no "written" callback, so the
+ * wait polls, but backs off while the peer stays stalled (a stalled socket may last until the request timeout) and
+ * starts fast again at the next stall.
+ */
+ private fun drainLater(owner: Link) {
+ if (owner.draining) return
+ owner.draining = true
+ scope.launch(serial) {
+ try {
+ var wait = DRAIN_POLL_MILLIS
+ while (!owner.closed && owner.outbox.isNotEmpty()) {
+ if (owner.transport?.hasBufferedData == true) {
+ delay(wait)
+ wait = minOf(wait * 2, DRAIN_POLL_MAX_MILLIS)
+ } else {
+ pump(owner)
+ wait = DRAIN_POLL_MILLIS
+ }
+ }
+ } finally {
+ owner.draining = false
+ }
+ }
+ }
+
+ // Keepalive
+
+ private fun startHeartbeat(owner: Link) {
+ val hinted = (owner.socket.ready?.payload?.get("heartbeat") as? JsonPrimitive)?.takeIf { !it.isString }?.content == "true"
+ val interval = if (hinted) timings.heartbeatMillis else timings.pingMillis
+ owner.heartbeat?.cancel()
+ owner.heartbeat = scope.launch(serial) {
+ while (isActive && !owner.closed) {
+ delay(interval)
+ if (owner.closed) return@launch
+ try {
+ requestOn(owner, "gateway.ping", JsonObject(emptyMap()), timings.pingReplyMillis)
+ } catch (e: HermesException) {
+ // Any RPC answer proves the socket; this host just has no ping.
+ if (e.kind == HermesException.Kind.RpcRejected) return@launch
+ closeLink(owner, e, notify = true)
+ return@launch
+ } catch (e: RequestCancelledException) {
+ return@launch
+ }
+ }
+ }
+ }
+
+ /** A quick check after the app returns or the network changes; a silent socket is replaced at once. */
+ suspend fun verifyLiveness() {
+ val live = withContext(serial) { link?.takeIf { it.connected } } ?: return
+ try {
+ requestOn(live, "gateway.ping", JsonObject(emptyMap()), timings.livenessMillis)
+ } catch (e: HermesException) {
+ if (e.kind == HermesException.Kind.RpcRejected) return
+ withContext(serial) { closeLink(live, e, notify = true) }
+ }
+ }
+
+ /**
+ * Proves the socket just before a prompt admission (a ping within [GatewayTimings.admissionMillis]); on
+ * failure it waits for the automatic recovery and pings the replacement once. Nothing is constructed or
+ * sent for the caller until the proof succeeds.
+ * @throws HermesException [HermesException.Kind.NotConnected] when there is no socket to prove.
+ */
+ suspend fun prepareForAdmission() {
+ withContext(serial) { recovery }?.join()
+ pingForAdmission(first = true)
+ }
+
+ private suspend fun pingForAdmission(first: Boolean) {
+ val live = withContext(serial) { if (terminal) null else link?.takeIf { it.connected } } ?: throw notConnected()
+ try {
+ requestOn(live, "gateway.ping", JsonObject(emptyMap()), timings.admissionMillis)
+ } catch (e: HermesException) {
+ if (!first) throw e
+ withContext(serial) { recovery }?.join()
+ pingForAdmission(first = false)
+ }
+ }
+
+ // Server requests
+
+ private fun acceptServerRequest(owner: Link, id: String, method: String, params: JsonObject) {
+ when (owner.serverRequests.register(id, method)) {
+ // The existing request stays authoritative and bounded: no second decision or response.
+ ServerRequestTable.Registration.Duplicate, ServerRequestTable.Registration.AtCapacity -> return
+ ServerRequestTable.Registration.Accepted -> Unit
+ }
+ val handler = handlers[method]
+ if (handler == null) {
+ queueServerResponse(owner, id, method, ServerResponse.Failure(-32601, "Method not supported by this client"))
+ return
+ }
+ val token = Any()
+ val job = scope.launch(Dispatchers.Default) {
+ val response = try {
+ handler.handle(IncomingServerRequest(owner.generation, id, method, params))
+ } catch (e: CancellationException) {
+ throw e
+ } catch (_: Exception) {
+ ServerResponse.Failure(-32603, "Client could not handle the request")
+ }
+ withContext(serial + NonCancellable) { completeHandler(owner, id, method, token, response) }
+ }
+ owner.serverTasks[id] = ServerTask(token, job)
+ }
+
+ private fun completeHandler(owner: Link, id: String, method: String, token: Any, response: ServerResponse) {
+ if (owner.serverTasks[id]?.token !== token) return
+ owner.serverTasks.remove(id)
+ if (owner.closed || owner !== link) return
+ queueServerResponse(owner, id, method, response)
+ }
+
+ private fun queueServerResponse(owner: Link, id: String, method: String, response: ServerResponse) {
+ var text = encodeResponse(id, response)
+ ?: encodeResponse(id, ServerResponse.Failure(-32603, "Client could not encode the response"))
+ ?: run { owner.serverRequests.retire(id, method); return }
+ var bytes = utf8Length(text)
+ if (owner.queuedServerBytes + bytes > MAXIMUM_QUEUED_SERVER_BYTES) {
+ text = encodeResponse(id, ServerResponse.Failure(-32603, "Client response queue is full"))
+ ?: run { owner.serverRequests.retire(id, method); return }
+ bytes = utf8Length(text)
+ if (owner.queuedServerBytes + bytes > MAXIMUM_QUEUED_SERVER_BYTES) {
+ owner.serverRequests.retire(id, method)
+ return
+ }
+ }
+ if (!owner.serverRequests.stageResponse(id, method)) return
+ owner.outbox.addLast(Outbound(id, method, text, bytes))
+ owner.queuedServerBytes += bytes
+ pump(owner)
+ }
+
+ /** The response envelope with the original ID bytes, or null if it cannot be encoded within limits. */
+ private fun encodeResponse(id: String, response: ServerResponse): String? {
+ if (!HermesWire.isValidRequestID(id)) return null
+ val envelope = try {
+ buildJsonObject {
+ put("jsonrpc", "2.0")
+ put("id", id)
+ when (response) {
+ is ServerResponse.Result -> put("result", response.value)
+ is ServerResponse.Failure -> {
+ if (response.message.isEmpty() || utf8Length(response.message) > HermesWire.MAXIMUM_CANCELLATION_REASON_BYTES) return null
+ put("error", buildJsonObject {
+ put("code", response.code)
+ put("message", response.message)
+ response.data?.let { put("data", it) }
+ })
+ }
+ }
+ }.toString()
+ } catch (_: Exception) {
+ return null
+ }
+ return envelope.takeIf { utf8Length(it) <= MAXIMUM_RESPONSE_BYTES && !exceedsNesting(it) }
+ }
+
+ private fun retireServerRequest(owner: Link, cancellation: RequestCancellation) {
+ if (!owner.serverRequests.retire(cancellation.id, cancellation.method)) return
+ owner.serverTasks.remove(cancellation.id)?.job?.cancel()
+ val index = owner.outbox.indexOfFirst { it.id == cancellation.id && it.serverMethod == cancellation.method }
+ if (index >= 0) {
+ uncount(owner, owner.outbox.removeAt(index))
+ }
+ }
+
+ /**
+ * Adopts the final `session.events.since.open_requests` snapshot through the same handler path as live
+ * requests. The whole snapshot (at most 64 rows of exactly `id`, `method` and `params`, each with
+ * `params.session_id == runtimeId`) is validated before anything is adopted. [generation] must be the
+ * current socket generation.
+ */
+ suspend fun adoptOpenRequests(rows: JsonElement, runtimeId: String, generation: Long) {
+ withContext(serial) {
+ val live = link
+ if (live == null || live.closed || live.generation != generation || live.socket.phase != SocketPhase.Ready) throw notConnected()
+ val invalid = HermesException(HermesException.Kind.InvalidResponse)
+ if (runtimeId.isEmpty() || utf8Length(runtimeId) > 4_096) throw invalid
+ val array = rows as? JsonArray ?: throw invalid
+ if (array.size > ServerRequestTable.MAXIMUM_OPEN) throw invalid
+ val requests = array.map { row ->
+ val entry = row as? JsonObject ?: throw invalid
+ if (entry.keys != setOf("id", "method", "params")) throw invalid
+ val id = (entry["id"] as? JsonPrimitive)?.takeIf { it.isString }?.content?.takeIf(HermesWire::isValidRequestID) ?: throw invalid
+ val method = (entry["method"] as? JsonPrimitive)?.takeIf { it.isString }?.content?.takeIf(HermesWire::isValidMethod) ?: throw invalid
+ val params = entry["params"] as? JsonObject ?: throw invalid
+ if ((params["session_id"] as? JsonPrimitive)?.takeIf { it.isString }?.content != runtimeId) throw invalid
+ Triple(id, method, params)
+ }
+ for ((id, method, params) in requests) acceptServerRequest(live, id, method, params)
+ }
+ }
+
+ // Closing
+
+ /**
+ * Ends this client for good: closes the socket, fails what is pending, forgets the handlers, and gives a
+ * renewal already on its way a moment to save. A new client (or [connect] on a fresh instance) is needed
+ * afterwards. Credentials in the store are untouched.
+ */
+ suspend fun disconnect() {
+ withContext(serial) {
+ terminal = true
+ recovery?.cancel()
+ recovery = null
+ opening?.cancel()
+ link?.let { closeLink(it, HermesException(HermesException.Kind.Disconnected), notify = false, orderly = true) }
+ handlers.clear()
+ publish()
+ subscribers.forEach { it.close() }
+ subscribers.clear()
+ }
+ authenticator.settlePendingRenewal()
+ }
+
+ private fun closeLink(owner: Link, reason: HermesException, notify: Boolean, orderly: Boolean = false) {
+ if (owner.closed) return
+ owner.closed = true
+ val uncertain = owner.pending.values.any { it.sendStarted && !it.readOnly }
+ val recover = notify && owner.connected && !terminal && !uncertain
+ if (link === owner) link = null
+ owner.readyDeadline?.cancel()
+ owner.heartbeat?.cancel()
+ owner.transport?.let { transport ->
+ if (orderly) {
+ transport.close(orderly = true)
+ // Not on `scope`: the owner cancels it right after disconnect(), which would drop this fallback.
+ fallbackClose.launch { delay(1_000); transport.close(orderly = false) }
+ } else {
+ transport.close(orderly = false)
+ }
+ }
+ owner.inbound.close()
+ owner.reader?.cancel()
+ owner.readyGate.completeExceptionally(reason)
+ val failing = owner.pending.values.toList()
+ owner.pending.clear()
+ for (pending in failing) {
+ pending.timeout?.cancel()
+ pending.result.completeExceptionally(
+ if (pending.sendStarted && !pending.readOnly) HermesException(HermesException.Kind.Disconnected, outcomeUnknown = true) else reason,
+ )
+ }
+ owner.serverTasks.values.forEach { it.job.cancel() }
+ owner.serverTasks.clear()
+ owner.serverRequests.removeAll()
+ owner.outbox.clear()
+ owner.queuedBytes = 0
+ owner.queuedAttachmentBytes = 0
+ owner.queuedServerBytes = 0
+ owner.attachmentId = null
+ lastFailure = reason
+ if (recover) {
+ startRecovery(reason)
+ } else if (owner.connected && recovery == null) {
+ // A connection that ended without automatic recovery: the next owner registers handlers again.
+ handlers.clear()
+ }
+ publish()
+ }
+
+ private fun startRecovery(initial: HermesException) {
+ if (recovery != null) return
+ recovery = scope.launch(serial) {
+ var last = initial
+ for (delayMillis in timings.reconnectDelaysMillis) {
+ if (delayMillis > 0) delay(delayMillis)
+ if (terminal) return@launch
+ try {
+ open(verify = true)
+ // Published state still says Recovering while this loop runs, so read the link itself.
+ if (link?.connected == true) {
+ recovery = null
+ publish()
+ return@launch
+ }
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Throwable) {
+ last = asHermes(e)
+ }
+ }
+ if (terminal) return@launch
+ recovery = null
+ handlers.clear()
+ lastFailure = last
+ publish()
+ }
+ publish()
+ }
+
+ private fun publish() {
+ val live = link
+ val connection = when {
+ terminal -> GatewayConnection.Closed
+ recovery != null -> GatewayConnection.Recovering
+ live == null -> GatewayConnection.Idle
+ live.connected -> GatewayConnection.Connected
+ else -> GatewayConnection.Connecting
+ }
+ val ready = live?.socket?.ready
+ val replayEpoch = (ready?.payload?.get("replay_epoch") as? JsonPrimitive)?.takeIf { it.isString }?.content
+ val heartbeat = (ready?.payload?.get("heartbeat") as? JsonPrimitive)?.takeIf { !it.isString && it !is JsonNull }?.content == "true"
+ mutableState.value = GatewayState(connection, generation, live?.owner, live?.socket, replayEpoch, heartbeat, lastFailure)
+ }
+
+ private fun notConnected() = HermesException(HermesException.Kind.NotConnected)
+
+ private fun asHermes(error: Throwable): HermesException = when (error) {
+ is HermesException -> error
+ is WireException -> HermesException(HermesException.Kind.InvalidResponse)
+ else -> HermesException(HermesException.Kind.ConnectionFailed)
+ }
+
+ /** Counts `{`/`[` depth outside strings, like the inbound check, so hostile nesting is never sent. */
+ private fun exceedsNesting(text: String): Boolean {
+ var depth = 0
+ var quoted = false
+ var escaped = false
+ for (c in text) {
+ if (quoted) {
+ if (escaped) escaped = false else if (c == '\\') escaped = true else if (c == '"') quoted = false
+ } else if (c == '"') {
+ quoted = true
+ } else if (c == '{' || c == '[') {
+ if (++depth > HermesWire.MAXIMUM_NESTING) return true
+ } else if (c == '}' || c == ']') {
+ depth--
+ }
+ }
+ return false
+ }
+
+ companion object {
+ const val DEFAULT_FRAME_BYTES = 2 * 1_024 * 1_024
+ const val ATTACHMENT_FRAME_BYTES = 12 * 1_024 * 1_024
+ const val MAXIMUM_PENDING = 64
+ const val MAXIMUM_QUEUED_BYTES = 8 * 1_024 * 1_024
+ const val MAXIMUM_RESPONSE_BYTES = 2 * 1_024 * 1_024
+ const val MAXIMUM_QUEUED_SERVER_BYTES = 4 * 1_024 * 1_024
+ const val EVENT_BUFFER = 8_192
+ private const val DRAIN_POLL_MILLIS = 2L
+ private const val DRAIN_POLL_MAX_MILLIS = 50L
+ // Few, because one message can be 4 MiB; a full buffer blocks the socket reader, which is TCP backpressure.
+ private const val INBOUND_BUFFER = 8
+ private val SUBMISSION_METHODS = setOf("prompt.submit", "slash.exec", "command.dispatch")
+ }
+}
diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayTypes.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayTypes.kt
new file mode 100644
index 00000000..7b479ce2
--- /dev/null
+++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayTypes.kt
@@ -0,0 +1,98 @@
+package app.bighelp.hermes
+
+import kotlin.coroutines.cancellation.CancellationException
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+
+/** Deadlines and paces of the gateway, injectable so tests need not wait. Defaults are the contract's. */
+class GatewayTimings(
+ /** From creating the socket to `gateway.ready`. HTTP 101 alone is not ready. */
+ val readyMillis: Long = 20_000,
+ /** `client.capabilities` reply deadline. */
+ val advertiseMillis: Long = 15_000,
+ /** An ordinary RPC, from enqueue (not from the host starting it). */
+ val requestMillis: Long = 45_000,
+ /** Periodic ping when `gateway.ready` said `heartbeat: true`. */
+ val heartbeatMillis: Long = 15_000,
+ /** Periodic ping otherwise. */
+ val pingMillis: Long = 20_000,
+ val pingReplyMillis: Long = 15_000,
+ /** A quick check after foreground or a network change. */
+ val livenessMillis: Long = 4_000,
+ /** The proof just before a prompt admission. */
+ val admissionMillis: Long = 5_000,
+ /** Automatic same-owner recovery attempts: the delay before each. */
+ val reconnectDelaysMillis: List = listOf(0, 1_000, 3_000),
+)
+
+/** One event with the socket generation it arrived on, so a consumer can drop a stale one. */
+class GatewayEvent(val generation: Long, val event: WireMessage.Event) {
+ override fun toString() = "GatewayEvent($generation, ${event.type})"
+}
+
+enum class GatewayConnection {
+ /** Never connected, or the last connection ended and recovery is not running. */
+ Idle,
+ Connecting,
+
+ /** Ready, advertised, healthy and with capabilities known. */
+ Connected,
+
+ /** The socket was lost and the automatic same-owner recovery is under way. */
+ Recovering,
+
+ /** [GatewayClient.disconnect] ran. This client object is finished. */
+ Closed,
+}
+
+/** What a consumer needs to know about the connection right now. */
+class GatewayState(
+ val connection: GatewayConnection,
+ /** The current (or last) socket generation; changes with every new socket, even to the same owner. */
+ val generation: Long,
+ val owner: ConnectionOwner?,
+ /** Phase, capabilities and the retained first `gateway.ready` of the current socket. */
+ val socket: GatewaySocket?,
+ /** `payload.replay_epoch` of the retained ready, when the host sent one. */
+ val replayEpoch: String?,
+ val heartbeatAdvertised: Boolean,
+ /** Why the previous socket ended, if it did. */
+ val lastFailure: HermesException?,
+) {
+ val ready: WireMessage.Event? get() = socket?.ready
+ val capabilities: GatewayCapabilities? get() = socket?.capabilities
+ val isConnected: Boolean get() = connection == GatewayConnection.Connected
+
+ override fun toString() = "GatewayState($connection, generation=$generation)"
+}
+
+/** A request the host sent to this client. [generation] is the socket it arrived on. */
+class IncomingServerRequest(val generation: Long, val id: String, val method: String, val params: JsonObject) {
+ override fun toString() = "IncomingServerRequest($method)"
+}
+
+/** The answer to a server request. The transport never makes a decision itself; only a handler does. */
+sealed interface ServerResponse {
+ class Result(val value: JsonElement) : ServerResponse
+
+ /** A JSON-RPC error; [message] is nonempty and at most 4,096 bytes. */
+ class Failure(val code: Long, val message: String, val data: JsonElement? = null) : ServerResponse
+}
+
+/**
+ * Answers one kind of server request (`approval`, `clarify`, `secret`, `sudo`). It runs in its own
+ * coroutine and may suspend for as long as a person takes. It is cancelled when the host sends a matching
+ * `request.cancel` or the socket generation ends, and then nothing is sent. Registering handlers is what
+ * makes the client advertise `server_requests`, after `gateway.ready`, on every socket.
+ */
+fun interface ServerRequestHandler {
+ suspend fun handle(request: IncomingServerRequest): ServerResponse
+}
+
+/**
+ * Thrown to a coroutine that was cancelled while its RPC was pending. It is a [CancellationException], so
+ * structured concurrency is unaffected, but it says how far the request got: [dispatch] is
+ * [DispatchOutcome.MayHaveBeenSent] once the frame was handed to the socket. Cancelling never stops the
+ * host and is not an interrupt; the request is never resent.
+ */
+class RequestCancelledException(val dispatch: DispatchOutcome) : CancellationException("Request cancelled")
diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayWebSocket.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayWebSocket.kt
new file mode 100644
index 00000000..c34773dc
--- /dev/null
+++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayWebSocket.kt
@@ -0,0 +1,297 @@
+package app.bighelp.hermes
+
+import java.io.IOException
+import java.net.InetAddress
+import java.net.URI
+import java.net.URISyntaxException
+import java.nio.ByteBuffer
+import java.util.concurrent.atomic.AtomicBoolean
+import org.java_websocket.WebSocketImpl
+import org.java_websocket.client.DnsResolver
+import org.java_websocket.client.WebSocketClient
+import org.java_websocket.drafts.Draft
+import org.java_websocket.drafts.Draft_6455
+import org.java_websocket.exceptions.InvalidHandshakeException
+import org.java_websocket.extensions.IExtension
+import org.java_websocket.framing.CloseFrame
+import org.java_websocket.handshake.ClientHandshake
+import org.java_websocket.handshake.Handshakedata
+import org.java_websocket.handshake.ServerHandshake
+import org.java_websocket.protocols.IProtocol
+import org.java_websocket.protocols.Protocol
+
+// The gateway's WebSocket I/O. OkHttp stays for bounded HTTP, but OkHttp 4.12 cannot give a WebSocket the
+// two things this contract needs: it assembles a whole inbound message before delivering it (so a declared
+// length cannot be refused up front) and it repairs malformed UTF-8 instead of rejecting it. Java-WebSocket
+// 1.6.0 checks a frame's declared length before allocating, caps the sum of fragments, decodes TEXT strictly
+// when a message completes, and turns on HTTPS hostname identification. Everything the library does not do is
+// done here: bounded and typed upgrade responses, exact subprotocol negotiation, no extensions, UTF-8 header
+// bytes, and no logging (see build.gradle.kts: SLF4J is bound to its no-op provider).
+
+/** One gateway socket as [GatewayClient] sees it. */
+internal interface GatewayTransport {
+ /**
+ * True while frames handed to [send] have not yet been taken by the socket's writer. The sender stops at
+ * this signal, so a stalled peer backs the queue up in the sender's own bounded outbox, not in the library.
+ */
+ val hasBufferedData: Boolean
+
+ /** Queues one TEXT frame in order; false when the socket is not open. */
+ fun send(text: String): Boolean
+
+ /** [orderly]: a close handshake. Otherwise the socket is dropped at once. Idempotent. */
+ fun close(orderly: Boolean)
+}
+
+/** Callbacks of one socket, on its reader thread, in wire order. [failed] is the one terminal event. */
+internal interface GatewayTransportListener {
+ fun opened(negotiatedSubprotocol: String?)
+
+ /** One whole message (a TEXT message is strict UTF-8, re-encoded; a BINARY message is the bytes as sent). */
+ fun message(bytes: ByteArray)
+
+ /** The socket ended for any reason: never called twice, never called after a deliberate [GatewayTransport.close]. */
+ fun failed(error: HermesException)
+}
+
+internal fun interface GatewayTransportFactory {
+ /** @throws HermesException if [request] cannot be sent as it is. Otherwise connecting continues in the background. */
+ fun open(request: SocketRequest, listener: GatewayTransportListener): GatewayTransport
+}
+
+internal object GatewayWebSockets : GatewayTransportFactory {
+ /** The largest inbound frame, and the largest sum of fragments: the contract's 4 MiB message. */
+ const val MAXIMUM_MESSAGE_BYTES = HermesWire.MAXIMUM_MESSAGE_BYTES
+
+ /** The upgrade response's header block, counted up to its blank line. */
+ const val MAXIMUM_UPGRADE_HEADER_BYTES = 16_384
+
+ private const val CONNECT_TIMEOUT_MILLIS = 20_000
+ private const val PROTOCOL_HEADER = "Sec-WebSocket-Protocol"
+
+ override fun open(request: SocketRequest, listener: GatewayTransportListener): GatewayTransport {
+ val uri = try {
+ URI(request.url)
+ } catch (_: URISyntaxException) {
+ throw HermesException(HermesException.Kind.InvalidEndpoint)
+ }
+ if (uri.scheme != "ws" && uri.scheme != "wss" || uri.host.isNullOrEmpty()) throw HermesException(HermesException.Kind.InvalidEndpoint)
+
+ val headers = LinkedHashMap(request.headers)
+ val offered = headers.keys.firstOrNull { it.equals(PROTOCOL_HEADER, ignoreCase = true) }
+ ?.let { headers.remove(it) }
+ ?.split(',')?.map { it.trim() }?.filter { it.isNotEmpty() }.orEmpty()
+ // Nothing may split the request line or header block, whatever the source of a header.
+ for ((name, value) in headers) {
+ if (name.isEmpty() || name.any { it.code <= 0x20 || it.code >= 0x7f || it == ':' } ||
+ value.any { it == '\r' || it == '\n' || it == '\u0000' }
+ ) throw HermesException(HermesException.Kind.InvalidAccessCredentials)
+ }
+ if (offered.any { protocol -> protocol.any { it.code <= 0x20 || it.code >= 0x7f || it == ',' } }) {
+ throw HermesException(HermesException.Kind.InvalidEndpoint)
+ }
+
+ val observer = HandshakeObserver()
+ // No extensions: the draft always adds RFC 6455's default one, and no permessage-deflate is configured.
+ val protocols: List = if (offered.isEmpty()) listOf(Protocol("")) else offered.map { Protocol(it) }
+ val draft = GatewayDraft(protocols, observer)
+ val client = SocketClient(uri, draft, headers, observer, listener, request.requiredSubprotocol)
+ client.connect()
+ return JavaWebSocketTransport(client)
+ }
+}
+
+/** What the upgrade response said, noted before the library turns it into an exception message. */
+private class HandshakeObserver {
+ @Volatile var status: Int? = null
+ @Volatile var headersTooLarge = false
+}
+
+/**
+ * The library's RFC 6455 draft with the gateway's bounds: 4 MiB frames and fragment sums, upgrade response
+ * headers capped (the library otherwise accumulates a never-ending header block without limit), the HTTP
+ * status recorded so a 401, 403 or redirect keeps its type, and the request written as UTF-8 bytes so a proxy
+ * header value with non-ASCII text arrives as sent (the library would write a question mark).
+ */
+private class GatewayDraft(
+ protocols: List,
+ private val observer: HandshakeObserver,
+) : Draft_6455(emptyList(), protocols, GatewayWebSockets.MAXIMUM_MESSAGE_BYTES) {
+
+ override fun translateHandshake(buf: ByteBuffer): Handshakedata {
+ val start = buf.position()
+ val end = buf.limit()
+ var terminator = -1
+ var i = start
+ while (i + 3 < end) {
+ if (buf.get(i) == CR && buf.get(i + 1) == LF && buf.get(i + 2) == CR && buf.get(i + 3) == LF) {
+ terminator = i
+ break
+ }
+ i++
+ }
+ val headerBytes = if (terminator >= 0) terminator + 4 - start else end - start
+ if (headerBytes > GatewayWebSockets.MAXIMUM_UPGRADE_HEADER_BYTES) {
+ observer.headersTooLarge = true
+ throw InvalidHandshakeException("Upgrade response headers are too large")
+ }
+ statusLine(buf, start, end)?.let { observer.status = it }
+ return super.translateHandshake(buf)
+ }
+
+ /** The status code of an `HTTP/1.x NNN ...` first line, if the line is complete. */
+ private fun statusLine(buf: ByteBuffer, start: Int, end: Int): Int? {
+ var lineEnd = start
+ while (lineEnd < end && lineEnd - start < 64 && buf.get(lineEnd) != CR && buf.get(lineEnd) != LF) lineEnd++
+ if (lineEnd >= end) return null
+ val line = ByteArray(lineEnd - start) { buf.get(start + it) }.toString(Charsets.ISO_8859_1)
+ val parts = line.split(' ')
+ return if (parts.size >= 2 && parts[0].startsWith("HTTP/")) parts[1].toIntOrNull() else null
+ }
+
+ override fun createHandshake(handshakedata: Handshakedata, withcontent: Boolean): List {
+ val request = handshakedata as? ClientHandshake ?: throw IllegalArgumentException("Client requests only")
+ val text = StringBuilder("GET ").append(request.resourceDescriptor).append(" HTTP/1.1\r\n")
+ val names = request.iterateHttpFields()
+ while (names.hasNext()) {
+ val name = names.next()
+ text.append(name).append(": ").append(request.getFieldValue(name)).append("\r\n")
+ }
+ text.append("\r\n")
+ return listOf(ByteBuffer.wrap(text.toString().toByteArray(Charsets.UTF_8)))
+ }
+
+ override fun copyInstance(): Draft = GatewayDraft(knownProtocols.map { it.copyInstance() }, observer)
+
+ private companion object {
+ const val CR: Byte = 13
+ const val LF: Byte = 10
+ }
+}
+
+private class SocketClient(
+ uri: URI,
+ draft: Draft,
+ headers: Map,
+ private val observer: HandshakeObserver,
+ private val listener: GatewayTransportListener,
+ private val requiredSubprotocol: String?,
+) : WebSocketClient(uri, draft, headers, 20_000) {
+ private val ended = AtomicBoolean(false)
+ @Volatile private var opened = false
+ @Volatile private var firstError: Exception? = null
+
+ init {
+ setDaemon(true)
+ // The RPC heartbeat is the only liveness check; the library's own ping timer is off.
+ setConnectionLostTimeout(0)
+ setTcpNoDelay(true)
+ // Android's Socket.connect refuses an unresolved address, which is what the library uses by default.
+ setDnsResolver(DnsResolver { target -> InetAddress.getByName(target.host) })
+ }
+
+ override fun onOpen(handshake: ServerHandshake) {
+ val negotiated = handshake.getFieldValue("Sec-WebSocket-Protocol").ifEmpty { null }
+ // Nothing was offered, so nothing may be accepted: an extension answer is a protocol violation, and
+ // the default extension would otherwise take any answer.
+ if (handshake.hasFieldValue("Sec-WebSocket-Extensions") ||
+ (requiredSubprotocol != null && negotiated != requiredSubprotocol)
+ ) {
+ terminate(HermesException(HermesException.Kind.InvalidResponse))
+ return
+ }
+ opened = true
+ listener.opened(negotiated)
+ }
+
+ override fun onMessage(message: String) {
+ if (!ended.get()) listener.message(message.toByteArray(Charsets.UTF_8))
+ }
+
+ override fun onMessage(bytes: ByteBuffer) {
+ if (ended.get()) return
+ val copy = ByteArray(bytes.remaining())
+ bytes.duplicate().get(copy)
+ listener.message(copy)
+ }
+
+ /** The library rejected something (size, UTF-8, framing) and is about to start a close handshake: end it now. */
+ override fun onCloseInitiated(code: Int, reason: String?) {
+ if (code != CloseFrame.NORMAL && code != CloseFrame.GOING_AWAY) terminate(map(code, remote = false))
+ }
+
+ override fun onClose(code: Int, reason: String?, remote: Boolean) {
+ terminate(map(code, remote), closeConnection = false)
+ }
+
+ override fun onError(ex: Exception) {
+ if (firstError == null) firstError = ex
+ }
+
+ /** After a deliberate close nothing more is reported: the owner already knows. */
+ fun silence() {
+ ended.set(true)
+ }
+
+ private fun terminate(error: HermesException, closeConnection: Boolean = true) {
+ if (!ended.compareAndSet(false, true)) return
+ listener.failed(error)
+ // A rejected stream must not linger half-closed waiting for a peer that may never answer.
+ if (!closeConnection) return
+ try {
+ (connection as? WebSocketImpl)?.closeConnection(CloseFrame.ABNORMAL_CLOSE, "")
+ } catch (_: RuntimeException) {
+ // already closed
+ }
+ }
+
+ private fun map(code: Int, remote: Boolean): HermesException {
+ if (!opened) {
+ if (observer.headersTooLarge) return HermesException(HermesException.Kind.MessageTooLarge)
+ observer.status?.let { status ->
+ return HermesException(
+ when {
+ status == 401 || status == 403 -> HermesException.Kind.InvalidCredentials
+ status in 300..399 -> HermesException.Kind.RedirectRefused
+ status != 101 -> HermesException.Kind.ConnectionFailed
+ else -> HermesException.Kind.InvalidResponse
+ },
+ )
+ }
+ firstError?.let { return OkHttpHermesHttp.map(it) }
+ return HermesException(
+ if (code == CloseFrame.PROTOCOL_ERROR) HermesException.Kind.InvalidResponse else HermesException.Kind.ConnectionFailed,
+ )
+ }
+ // 1006 is the library's word for "the connection went away", not for a rule that was broken.
+ if (remote || code == CloseFrame.ABNORMAL_CLOSE) return HermesException(HermesException.Kind.Disconnected)
+ return HermesException(if (code == CloseFrame.TOOBIG) HermesException.Kind.MessageTooLarge else HermesException.Kind.InvalidResponse)
+ }
+}
+
+private class JavaWebSocketTransport(private val client: SocketClient) : GatewayTransport {
+ override val hasBufferedData: Boolean get() = client.hasBufferedData()
+
+ override fun send(text: String): Boolean = try {
+ client.send(text)
+ true
+ } catch (_: RuntimeException) {
+ false
+ }
+
+ override fun close(orderly: Boolean) {
+ client.silence()
+ try {
+ if (orderly) {
+ client.close()
+ } else {
+ (client.connection as? WebSocketImpl)?.closeConnection(CloseFrame.ABNORMAL_CLOSE, "")
+ client.socket?.close()
+ }
+ } catch (_: RuntimeException) {
+ // already closed
+ } catch (_: IOException) {
+ // already closed
+ }
+ }
+}
diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAccess.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAccess.kt
new file mode 100644
index 00000000..53dd7103
--- /dev/null
+++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAccess.kt
@@ -0,0 +1,134 @@
+package app.bighelp.hermes
+
+import java.util.Base64
+
+// What guards a Hermes address before Hermes itself: a Cloudflare Access service token, a reverse proxy's
+// Basic login, or custom proxy headers. These are independent of the Hermes sign-in, are stored separately
+// by the app, and travel on every HTTP request and WebSocket upgrade to that one endpoint, never elsewhere.
+
+/** A proxy gate credential. Secrets never appear in [toString]. */
+class AccessCredential private constructor(
+ val kind: Kind,
+ /** The Cloudflare client ID, or the proxy username. */
+ val clientId: String,
+ /** The Cloudflare client secret, or the proxy password. */
+ val clientSecret: String,
+) {
+ enum class Kind { CloudflareAccess, ProxyBasic }
+
+ fun headers(): Map = when (kind) {
+ Kind.CloudflareAccess -> linkedMapOf("CF-Access-Client-Id" to clientId, "CF-Access-Client-Secret" to clientSecret)
+ Kind.ProxyBasic -> mapOf(
+ "Authorization" to "Basic " +
+ Base64.getEncoder().encodeToString("$clientId:$clientSecret".toByteArray(Charsets.UTF_8)),
+ )
+ }
+
+ /** Cloudflare Access is HTTPS only; Basic may also go to an approved private HTTP address. */
+ fun canSend(endpoint: HermesEndpoint): Boolean = endpoint.isSecure || kind == Kind.ProxyBasic
+
+ override fun equals(other: Any?) =
+ other is AccessCredential && kind == other.kind && clientId == other.clientId && clientSecret == other.clientSecret
+
+ override fun hashCode() = (kind.hashCode() * 31 + clientId.hashCode()) * 31 + clientSecret.hashCode()
+ override fun toString() = "AccessCredential($kind)"
+
+ companion object {
+ /** Both values trimmed, 1–512 bytes of printable ASCII with no spaces. */
+ fun cloudflareAccess(clientId: String, clientSecret: String): AccessCredential {
+ val id = clientId.trim()
+ val secret = clientSecret.trim()
+ if (!headerSafe(id) || !headerSafe(secret)) throw invalid()
+ return AccessCredential(Kind.CloudflareAccess, id, secret)
+ }
+
+ /** Username trimmed, 1–256 bytes, no colon or control; the password keeps its spaces, 1–512 bytes. */
+ fun proxyBasic(username: String, password: String): AccessCredential {
+ val user = username.trim()
+ if (user.isEmpty() || utf8Length(user) > 256 || ':' in user || user.any(::isControl) ||
+ password.isEmpty() || utf8Length(password) > 512 || password.any(::isControl)
+ ) throw invalid()
+ return AccessCredential(Kind.ProxyBasic, user, password)
+ }
+
+ private fun headerSafe(value: String) = value.isNotEmpty() && value.length <= 512 && value.all { it.code in 0x21..0x7e }
+ private fun isControl(c: Char) = c.code < 0x20 || c.code == 0x7f || c.code in 0x80..0x9f
+ private fun invalid() = HermesException(HermesException.Kind.InvalidAccessCredentials)
+ }
+}
+
+class CustomHeaderException(val problem: Problem) : IllegalArgumentException(problem.name) {
+ enum class Problem { InvalidName, Reserved, InvalidValue, Duplicate, TooMany }
+}
+
+/** A header a proxy in front of Hermes wants, such as `X-Access-Id`. Reserved names are the app's or HTTP's own. */
+class CustomHeader private constructor(val name: String, val value: String) {
+ override fun equals(other: Any?) = other is CustomHeader && name == other.name && value == other.value
+ override fun hashCode() = name.hashCode() * 31 + value.hashCode()
+ override fun toString() = "CustomHeader($name)"
+
+ companion object {
+ const val MAXIMUM_COUNT = 16
+
+ fun of(name: String, value: String): CustomHeader {
+ val trimmedName = name.trim()
+ val trimmedValue = value.trim()
+ if (!isToken(trimmedName) || utf8Length(trimmedName) > 128) invalid(CustomHeaderException.Problem.InvalidName)
+ if (isReserved(trimmedName)) invalid(CustomHeaderException.Problem.Reserved)
+ if (trimmedValue.isEmpty() || utf8Length(trimmedValue) > 4_096 ||
+ trimmedValue.any { !(it == '\t' || it.code in 0x20..0x7e || it.code >= 0x80) }
+ ) invalid(CustomHeaderException.Problem.InvalidValue)
+ return CustomHeader(trimmedName, trimmedValue)
+ }
+
+ /** Blank rows are skipped; at most 16; names unique ignoring case. */
+ fun list(pairs: List>): List {
+ val filled = pairs.filter { it.first.isNotBlank() || it.second.isNotBlank() }
+ if (filled.size > MAXIMUM_COUNT) invalid(CustomHeaderException.Problem.TooMany)
+ val seen = HashSet()
+ return filled.map { (name, value) ->
+ of(name, value).also { if (!seen.add(it.name.lowercase())) invalid(CustomHeaderException.Problem.Duplicate) }
+ }
+ }
+
+ fun isReserved(name: String): Boolean {
+ val lower = name.lowercase()
+ return lower in RESERVED || lower.startsWith("sec-") || lower.startsWith("x-loopdy-") ||
+ lower.startsWith("x-hermes-") || lower.startsWith("cf-access-")
+ }
+
+ private val RESERVED = setOf(
+ "host", "authorization", "proxy-authorization", "cookie", "content-type", "content-length",
+ "content-encoding", "transfer-encoding", "connection", "upgrade", "keep-alive", "te", "expect",
+ "accept", "accept-encoding", "cache-control", "range", "if-match", "if-none-match", "origin",
+ )
+
+ private fun isToken(name: String) = name.isNotEmpty() &&
+ name.all { (it in 'a'..'z' || it in 'A'..'Z' || it in '0'..'9') || it in "!#$%&'*+-.^_`|~" }
+
+ private fun invalid(problem: CustomHeaderException.Problem): Nothing = throw CustomHeaderException(problem)
+ }
+}
+
+/**
+ * The complete header set for one endpoint's gate. The values hold secrets; [toString] names none of them.
+ * Applied to every HTTP request and to the WebSocket upgrade explicitly.
+ */
+class AccessHeaders private constructor(val values: Map) {
+ override fun toString() = "AccessHeaders(${values.size} headers)"
+
+ companion object {
+ val none = AccessHeaders(emptyMap())
+
+ /** @throws HermesException [HermesException.Kind.InvalidAccessCredentials] if [credential] cannot go to [endpoint]. */
+ fun of(endpoint: HermesEndpoint, credential: AccessCredential?, custom: List): AccessHeaders {
+ if (credential != null && !credential.canSend(endpoint)) {
+ throw HermesException(HermesException.Kind.InvalidAccessCredentials)
+ }
+ val values = LinkedHashMap()
+ credential?.let { values.putAll(it.headers()) }
+ custom.forEach { values[it.name] = it.value }
+ return AccessHeaders(values)
+ }
+ }
+}
diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAddress.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAddress.kt
new file mode 100644
index 00000000..70a93e32
--- /dev/null
+++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAddress.kt
@@ -0,0 +1,94 @@
+package app.bighelp.hermes
+
+/**
+ * Literal IP syntax only. Nothing here touches `java.net.InetAddress`, so no host name is ever resolved
+ * and DNS can never decide whether plain HTTP is allowed.
+ */
+internal object HermesAddress {
+ /** Strict dotted-decimal: four parts, 0–255, no leading zeros. `127.1`, `0x7f.0.0.1` and integers fail. */
+ fun parseIPv4(text: String): ByteArray? {
+ val parts = text.split('.')
+ if (parts.size != 4) return null
+ val bytes = ByteArray(4)
+ for ((index, part) in parts.withIndex()) {
+ if (part.isEmpty() || part.length > 3 || !part.all { it in '0'..'9' }) return null
+ if (part.length > 1 && part[0] == '0') return null
+ val value = part.toInt()
+ if (value > 255) return null
+ bytes[index] = value.toByte()
+ }
+ return bytes
+ }
+
+ /** RFC 4291 text forms with `::` and a trailing dotted quad. No zone ID, no brackets. */
+ fun parseIPv6(text: String): ByteArray? {
+ if (text.isEmpty() || !text.all { it == ':' || it == '.' || Character.digit(it, 16) >= 0 && it.code < 0x80 }) {
+ return null
+ }
+ val gap = text.indexOf("::")
+ if (gap >= 0 && text.indexOf("::", gap + 1) >= 0) return null
+ val head = if (gap >= 0) text.substring(0, gap) else text
+ val tail = if (gap >= 0) text.substring(gap + 2) else ""
+ // The dotted quad may only close the address: the tail when there is a "::", else the whole text.
+ val headWords = words(head, allowIPv4 = gap < 0) ?: return null
+ val tailWords = words(tail, allowIPv4 = gap >= 0) ?: return null
+ val total = headWords.size + tailWords.size
+ if (gap >= 0) { if (total > 7) return null } else if (total != 8) return null
+ val all = headWords + List(8 - total) { 0 } + tailWords
+ return ByteArray(16) { (all[it / 2] shr (if (it % 2 == 0) 8 else 0)).toByte() }
+ }
+
+ private fun words(part: String, allowIPv4: Boolean): List? {
+ if (part.isEmpty()) return emptyList()
+ val pieces = part.split(':')
+ val result = ArrayList()
+ for ((index, piece) in pieces.withIndex()) {
+ if ('.' in piece) {
+ if (!allowIPv4 || index != pieces.lastIndex) return null
+ val quad = parseIPv4(piece) ?: return null
+ result += ((quad[0].toInt() and 0xff) shl 8) or (quad[1].toInt() and 0xff)
+ result += ((quad[2].toInt() and 0xff) shl 8) or (quad[3].toInt() and 0xff)
+ } else {
+ if (piece.isEmpty() || piece.length > 4) return null
+ result += piece.toInt(16)
+ }
+ }
+ return result
+ }
+
+ /** Names that only resolve inside a private network; a Tailscale Funnel name is public only over HTTPS. */
+ private val privateNameSuffixes = listOf(
+ "local", "lan", "internal", "home.arpa", "intranet", "corp", "localdomain", "private",
+ "localhost", "ts.net", "beta.tailscale.net",
+ )
+
+ /**
+ * Plain HTTP stays on a network the person controls: this device, home or office Wi-Fi, a VPN or
+ * Tailscale. IPv4-mapped and link-local IPv6 forms are deliberately not included.
+ */
+ fun isPrivateNetworkHost(host: String): Boolean {
+ val name = host.lowercase()
+ parseIPv4(name)?.let { return isPrivateIPv4(it) }
+ parseIPv6(name)?.let { return isLoopbackOrUniqueLocalIPv6(it) }
+ // A single-label name ("hermes") never leaves the local resolver.
+ if ('.' !in name) return true
+ return privateNameSuffixes.any { name.endsWith(".$it") }
+ }
+
+ private fun isPrivateIPv4(address: ByteArray): Boolean {
+ val a = address[0].toInt() and 0xff
+ val b = address[1].toInt() and 0xff
+ return a == 127 || // loopback
+ a == 10 || // 10.0.0.0/8
+ (a == 172 && b in 16..31) || // 172.16.0.0/12
+ (a == 192 && b == 168) || // 192.168.0.0/16
+ (a == 100 && b in 64..127) || // 100.64.0.0/10 (Tailscale, CGNAT)
+ (a == 169 && b == 254) // link-local
+ }
+
+ private fun isLoopbackOrUniqueLocalIPv6(address: ByteArray): Boolean {
+ val loopback = address.take(15).all { it.toInt() == 0 } && address[15].toInt() == 1
+ // fc00::/7 unique local, which includes Tailscale's fd7a:115c:a1e0::/48.
+ return loopback || (address[0].toInt() and 0xfe) == 0xfc
+ }
+}
diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAuthParsers.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAuthParsers.kt
new file mode 100644
index 00000000..7e053a85
--- /dev/null
+++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAuthParsers.kt
@@ -0,0 +1,231 @@
+package app.bighelp.hermes
+
+import java.time.ZoneOffset
+import java.time.ZonedDateTime
+import java.time.format.DateTimeFormatter
+import java.util.Locale
+import kotlinx.serialization.json.JsonArray
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonNull
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+
+/** Pure, bounded readers of what the host sends during sign-in. Nothing here does I/O. */
+internal object HermesAuthParsers {
+ private const val MAXIMUM_BOOTSTRAP_BYTES = 1_048_576
+ private val SCRIPT = Regex("""""", RegexOption.IGNORE_CASE)
+ // A lookbehind, not a consumed `;`: two assignments in a row must both be seen.
+ private val MODE_ASSIGNMENT = Regex("""(?<=^|;)\s*window\.__HERMES_AUTH_REQUIRED__\s*=\s*(true|false)\s*;""")
+ private const val TOKEN_NAME = "window.__HERMES_SESSION_TOKEN__"
+ private const val MAXIMUM_TOKEN_LITERAL = 65_536
+
+ private fun invalid() = HermesException(HermesException.Kind.InvalidResponse)
+
+ /**
+ * Inert `window.__HERMES_SESSION_TOKEN__` assignment of an ungated dashboard page. Only `" }}