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*?PZ#Hk|=xn zGM#0*w4CaB^y0G(J4q=;5NeM@m-P}#mv7QZNF)M!dK^w{mk_!n0`+Y3PQutu-%NBt zzgPXug?JLEbUL{e_dk;Vd896&yPe(hliVK!lj%5+@BKdcrEZ2Nc_*i@ve*2lB>u~{ zFozd2FM|_0+nAGR4TLNHanQn_Oeb!Jr UcvzJ?7p9TTNB}ocO3j$7ij!li8#k6 z@2tSd1>K03K9A#_-MIq)S;T#oE^;>U$)&}okIvDf3lm?kI{d80$>~ xKUoS!%q1Pi?WpsUUt(tI ztjNjY*y&Rm9(S(DC2GuPHBJs@5M{RGm`c1z<6nwyN^)rMo-AS{M2$oM9|y%fM|}G~ DHx0+F literal 0 HcmV?d00001 diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..36e4933e --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,8 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionSha256Sum=20f1b1176237254a6fc204d8434196fa11a4cfb387567519c61556e8710aed78 +distributionUrl=https\://services.gradle.org/distributions/gradle-8.13-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/android/gradlew b/android/gradlew new file mode 100755 index 00000000..faf93008 --- /dev/null +++ b/android/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/android/gradlew.bat b/android/gradlew.bat new file mode 100644 index 00000000..9d21a218 --- /dev/null +++ b/android/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/android/hermes/build.gradle.kts b/android/hermes/build.gradle.kts new file mode 100644 index 00000000..9123188d --- /dev/null +++ b/android/hermes/build.gradle.kts @@ -0,0 +1,16 @@ +plugins { + kotlin("jvm") +} +kotlin { + jvmToolchain(17) +} +dependencies { + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0") + testImplementation("junit:junit:4.13.2") +} +tasks.test { + val wireVectors = rootProject.file("../docs/hermes/vectors/wire.json") + // The tests read the shared vectors by path; declare the file so a content change reruns them. + inputs.file(wireVectors).withPropertyName("wireVectors").withPathSensitivity(PathSensitivity.NONE) + systemProperty("hermes.wireVectors", wireVectors.absolutePath) +} 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/HermesConnection.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesConnection.kt new file mode 100644 index 00000000..97ff187b --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesConnection.kt @@ -0,0 +1,194 @@ +package app.bighelp.hermes + +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull + +// Pure, immutable policy for who owns a connection and what it may do. It performs no I/O: a transport +// feeds it facts (upgraded, a decoded message, a capability result) and asks before acting. It is not a +// client; nothing here opens a socket, sends a frame or reconnects. + +/** + * Who a socket, request or result belongs to. [generation] changes on every new connection, even to the + * same endpoint and principal, so an older answer can never be mistaken for the current one. + */ +data class ConnectionOwner(val endpoint: String, val principal: String, val generation: Long) + +/** + * The one current owner, or none while disconnected. Hold it in a single atomic holder and check + * [accepts] on the same context that applies the result: a retired owner can never publish. + */ +class OwnerState private constructor(val current: ConnectionOwner?, private val lastGeneration: Long) { + /** Supersedes any current owner. Generations only grow, also across [disconnect]. */ + fun connect(endpoint: HermesEndpoint, principal: String): OwnerState { + val owner = ConnectionOwner(endpoint.canonical, principal, lastGeneration + 1) + return OwnerState(owner, owner.generation) + } + + fun disconnect(): OwnerState = OwnerState(null, lastGeneration) + + /** True only for the exact current owner: same endpoint, same principal, same generation. */ + fun accepts(owner: ConnectionOwner): Boolean = owner == current + + companion object { + val none = OwnerState(null, 0) + } +} + +/** Host-advertised `gateway.capabilities`. Unknown keys are ignored; the one Boolean is required. */ +data class GatewayCapabilities(val perSessionExclusiveSubmit: Boolean) { + companion object { + /** + * @throws WireException unless [result] is an object whose `per_session_exclusive_submit` is a JSON + * Boolean. Missing, `"true"` or any other shape fails discovery; never infer it from a version. + */ + fun decode(result: JsonElement): GatewayCapabilities { + val flag = (result as? JsonObject)?.get("per_session_exclusive_submit") as? JsonPrimitive + val value = flag?.takeIf { !it.isString }?.booleanOrNull + ?: throw WireException(WireException.Kind.InvalidResponse) + return GatewayCapabilities(value) + } + } +} + +enum class SocketPhase { + /** The upgrade request is under way. */ + Connecting, + + /** The WebSocket opened (HTTP 101) but Hermes has not said `gateway.ready`. Not usable. */ + Upgraded, + + /** `gateway.ready` arrived. Only now may the application write. */ + Ready, + + Closed, +} + +/** What a request needs from the connection. */ +enum class GatewayOperation { + /** Reads such as listing sessions. */ + Read, + + /** Prompt answers, stop, steer and other session controls that do not submit a new turn. */ + Control, + + /** Starting a turn: chat send, queue and slash commands. Needs the exclusive-submit guarantee. */ + Submission, +} + +enum class Refusal { + /** The owner was superseded or disconnected. */ + StaleOwner, + + /** The socket is not past `gateway.ready`; an upgrade alone allows no application writes. */ + NotReady, + + /** Capabilities have not been discovered on this socket yet. */ + CapabilitiesUnknown, + + /** The host did not guarantee serialized submitters, so starting a turn stays off. */ + ExclusiveSubmitUnavailable, +} + +sealed interface Admission { + data object Admitted : Admission + data class Refused(val reason: Refusal) : Admission +} + +/** + * One socket generation's readiness and capabilities. Readiness is a separate fact from the upgrade and + * from capability discovery; every transition returns a new value. + */ +class GatewaySocket private constructor( + val owner: ConnectionOwner, + val phase: SocketPhase, + /** Null until discovered on this ready socket. Capabilities belong to one socket and are never carried over. */ + val capabilities: GatewayCapabilities?, + /** The retained initial `gateway.ready`, so a late consumer still sees its epoch and heartbeat hint. */ + val ready: WireMessage.Event?, +) { + fun upgraded(): GatewaySocket = + if (phase == SocketPhase.Connecting) GatewaySocket(owner, SocketPhase.Upgraded, null, null) else this + + /** + * Feeds one decoded message. The first `gateway.ready` on an upgraded socket makes it ready; a second + * one on an already ready socket is invalid and closes it. Everything else changes nothing. + */ + fun receive(message: WireMessage): GatewaySocket { + if (message !is WireMessage.Event || message.type != GATEWAY_READY) return this + return when (phase) { + SocketPhase.Upgraded -> GatewaySocket(owner, SocketPhase.Ready, null, message) + SocketPhase.Ready -> closed() + else -> this + } + } + + /** @throws IllegalStateException unless the socket is ready: capabilities are asked after `gateway.ready`. */ + fun discovered(capabilities: GatewayCapabilities): GatewaySocket { + check(phase == SocketPhase.Ready) { "Capabilities are only discovered on a ready socket." } + return GatewaySocket(owner, phase, capabilities, ready) + } + + fun closed(): GatewaySocket = GatewaySocket(owner, SocketPhase.Closed, null, ready) + + /** Server requests may arrive early, but their responses and every client frame wait for this. */ + val canWriteApplicationFrames: Boolean get() = phase == SocketPhase.Ready + + fun admit(operation: GatewayOperation, owners: OwnerState): Admission { + if (!owners.accepts(owner)) return Admission.Refused(Refusal.StaleOwner) + if (!canWriteApplicationFrames) return Admission.Refused(Refusal.NotReady) + if (operation == GatewayOperation.Submission) { + val known = capabilities ?: return Admission.Refused(Refusal.CapabilitiesUnknown) + if (!known.perSessionExclusiveSubmit) return Admission.Refused(Refusal.ExclusiveSubmitUnavailable) + } + return Admission.Admitted + } + + companion object { + const val GATEWAY_READY = "gateway.ready" + + fun opening(owner: ConnectionOwner) = GatewaySocket(owner, SocketPhase.Connecting, null, null) + } +} + +/** How far one outgoing RPC got. Mark [MayHaveBeenSent] before awaiting the socket send, not after. */ +enum class DispatchOutcome { + /** Nothing left the device. */ + NotSent, + + /** Bytes may have reached the host. A failed send call does not prove otherwise. */ + MayHaveBeenSent, + + ConfirmedResult, + ConfirmedRefusal, +} + +object DispatchPolicy { + /** The current client's conservative read-only allowlist. Anything else counts as a mutation. */ + val readOnlyMethods: Set = setOf( + "gateway.ping", "session.list", "session.active_list", "session.history", + "session.status", "session.usage", "session.events.since", "commands.catalog", + "config.get", "delegation.status", "spawn_tree.list", + "profiles.list", "profiles.describe", "profiles.get_asset", "model.options", + "projects.list", "projects.get", "subagent.list", "subagent.tail", "client.capabilities", + "groups.capabilities", "groups.list", "groups.state", "groups.log", "pet.gallery", "pet.thumb", + ) + + fun isReadOnly(method: String): Boolean = method in readOnlyMethods + + /** A mutation that may have been sent has an unknown outcome: show it as uncertain, never as failed. */ + fun isUncertain(method: String, outcome: DispatchOutcome): Boolean = + outcome == DispatchOutcome.MayHaveBeenSent && !isReadOnly(method) + + /** + * Whether the owning layer may issue a fresh request after a lost connection. This is never a license + * to copy the old frame to a new socket, and a mutation with an uncertain outcome is never retried by + * the transport: an operation-specific recovery contract has to reconcile host state first. + */ + fun mayRetry(method: String, outcome: DispatchOutcome): Boolean = when (outcome) { + DispatchOutcome.NotSent -> true + DispatchOutcome.MayHaveBeenSent -> isReadOnly(method) + DispatchOutcome.ConfirmedResult, DispatchOutcome.ConfirmedRefusal -> false + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesEndpoint.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesEndpoint.kt new file mode 100644 index 00000000..1b8d5a95 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesEndpoint.kt @@ -0,0 +1,158 @@ +package app.bighelp.hermes + +import java.net.URI +import java.net.URISyntaxException + +/** Why an address or route was refused. Callers show plain words per reason and never echo the input. */ +class HermesEndpointException(val reason: Reason) : IllegalArgumentException(reason.name) { + enum class Reason { InvalidEndpoint, PlaintextNotAllowed, InvalidRoute } +} + +/** + * A validated Hermes dashboard base address, including an optional deployment prefix. [canonical] is the + * endpoint's identity: scheme, effective port and prefix are all part of it, so credentials for + * `/hermes-a` are never credentials for `/hermes-b`. Saved endpoints must go through [parse] again. + * + * Plain HTTP needs both the caller's explicit private-network opt-in and a host that is private by its + * syntax alone. No name is ever resolved, so DNS cannot authorize plaintext. + */ +class HermesEndpoint private constructor( + val isSecure: Boolean, + /** Lowercase host without IPv6 brackets. */ + val host: String, + /** The explicit port, or null when it is the scheme's default. */ + val port: Int?, + /** Deployment prefix: empty, or `/a/b` with no trailing slash. */ + val prefix: String, + val allowPrivateHttp: Boolean, +) { + private val authority: String = + (if (':' in host) "[$host]" else host) + (port?.let { ":$it" } ?: "") + + val canonical: String = "${if (isSecure) "https" else "http"}://$authority$prefix" + + /** The gateway socket, `wss` for HTTPS and `ws` for HTTP. The prefix is kept. */ + val webSocketUrl: String = "${if (isSecure) "wss" else "ws"}://$authority$prefix/api/ws" + + /** + * Appends an application-owned [route] to the prefix. Caller-supplied absolute URLs, queries and + * traversal never pass; add query values separately with a real query encoder. + */ + fun httpUrl(route: String): URI { + if (!route.startsWith("/") || "//" in route || route.any { it.code !in 0x21..0x7e || it in "?#%\\" } || + route.split('/').any { it == "." || it == ".." } + ) throw HermesEndpointException(HermesEndpointException.Reason.InvalidRoute) + return try { + URI("$canonical$route") + } catch (_: URISyntaxException) { + throw HermesEndpointException(HermesEndpointException.Reason.InvalidRoute) + } + } + + override fun equals(other: Any?): Boolean = + other is HermesEndpoint && canonical == other.canonical && allowPrivateHttp == other.allowPrivateHttp + + override fun hashCode(): Int = 31 * canonical.hashCode() + allowPrivateHttp.hashCode() + + override fun toString(): String = canonical + + companion object { + private const val MAXIMUM_INPUT_BYTES = 2_048 + private const val PREFIX_CHARACTERS = + "/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~" + + /** + * @throws HermesEndpointException (an [IllegalArgumentException]) for anything the contract refuses: + * whitespace, credentials, query, fragment, percent escapes, traversal, numeric host aliases, ports + * outside 1–65535, an unsupported scheme, or plain HTTP that is not both opted in and private. + */ + fun parse(input: String, allowPrivateHttp: Boolean = false): HermesEndpoint { + // The only characters any valid endpoint holds are ASCII, so non-ASCII can never be accepted. + if (input.isEmpty() || input.length > MAXIMUM_INPUT_BYTES || + input.any { it.code !in 0x21..0x7e } || '\\' in input + ) throw invalidEndpoint() + + val separator = input.indexOf("://") + val explicitScheme = if (separator >= 0) input.substring(0, separator).lowercase() else null + val rest = when { + separator >= 0 -> input.substring(separator + 3) + // An unbracketed IPv6 literal with no path or port is unambiguous. + HermesAddress.parseIPv6(input) != null -> "[$input]" + else -> input + } + val secure = when (explicitScheme) { + null, "https" -> true + "http" -> false + else -> throw invalidEndpoint() + } + // Credentials, query and fragment never belong in an endpoint, even when empty. + if (rest.any { it == '@' || it == '?' || it == '#' }) throw invalidEndpoint() + + val slash = rest.indexOf('/') + val authority = if (slash >= 0) rest.substring(0, slash) else rest + val path = if (slash >= 0) rest.substring(slash) else "" + if ('%' in authority) throw invalidEndpoint() // zone IDs and escaped hosts + + val (host, portText) = splitAuthority(authority) + val port = portText?.let { parsePort(it) } + if (!validHost(host)) throw invalidEndpoint() + + if (path.any { it !in PREFIX_CHARACTERS } || "//" in path || + path.split('/').any { it == "." || it == ".." } + ) throw invalidEndpoint() + + if (!secure && !(allowPrivateHttp && HermesAddress.isPrivateNetworkHost(host))) { + throw HermesEndpointException(HermesEndpointException.Reason.PlaintextNotAllowed) + } + val defaultPort = if (secure) 443 else 80 + return HermesEndpoint( + isSecure = secure, + host = host, + port = port?.takeIf { it != defaultPort }, + prefix = path.removeSuffix("/"), + allowPrivateHttp = allowPrivateHttp, + ) + } + + /** Host (lowercase, no brackets) and the raw port digits, when a port is present. */ + private fun splitAuthority(authority: String): Pair { + if (authority.startsWith("[")) { + val close = authority.indexOf(']') + if (close < 0) throw invalidEndpoint() + val literal = authority.substring(1, close).lowercase() + if (HermesAddress.parseIPv6(literal) == null) throw invalidEndpoint() + val after = authority.substring(close + 1) + return when { + after.isEmpty() -> literal to null + after.startsWith(":") -> literal to after.substring(1) + else -> throw invalidEndpoint() + } + } + // An unbracketed host never holds ':' except before its port. + val colon = authority.indexOf(':') + if (colon < 0) return authority.lowercase() to null + if (authority.indexOf(':', colon + 1) >= 0) throw invalidEndpoint() + return authority.substring(0, colon).lowercase() to authority.substring(colon + 1) + } + + private fun parsePort(text: String): Int { + // An empty port ("host:") is refused rather than read as the default. + if (text.isEmpty() || text.length > 5 || !text.all { it in '0'..'9' }) throw invalidEndpoint() + return text.toInt().also { if (it !in 1..65_535) throw invalidEndpoint() } + } + + private fun validHost(host: String): Boolean { + if (host.isEmpty()) return false + if (':' in host) return HermesAddress.parseIPv6(host) != null // bracketed literal, already checked + if (HermesAddress.parseIPv4(host) != null) return true + // Refuse numeric aliases (127.1, integer and hex IPv4) and ambiguous DNS. + if (host.length > 253 || host.all { it in '0'..'9' || it == '.' } || host.startsWith("0x")) return false + return host.split('.').all { label -> + label.length in 1..63 && label.first() != '-' && label.last() != '-' && + label.all { it in 'a'..'z' || it in '0'..'9' || it == '-' } + } + } + + private fun invalidEndpoint() = HermesEndpointException(HermesEndpointException.Reason.InvalidEndpoint) + } +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesWire.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesWire.kt new file mode 100644 index 00000000..27a855c3 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/HermesWire.kt @@ -0,0 +1,272 @@ +package app.bighelp.hermes + +import java.nio.ByteBuffer +import java.nio.charset.CharacterCodingException +import java.nio.charset.CodingErrorAction +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive + +/** A frame that must not be applied. Carries only a category, never frame text. */ +class WireException(val kind: Kind) : Exception(kind.category) { + enum class Kind(val category: String) { + InvalidResponse("invalidResponse"), + MessageTooLarge("messageTooLarge"), + } + + /** The shared vectors' name for [kind]. */ + val category: String get() = kind.category +} + +/** + * One decoded gateway entry. IDs are the exact decoded strings: never trimmed, normalized or replaced, + * so canonically equivalent but byte-distinct IDs stay distinct. + */ +sealed interface WireMessage { + /** `event: `, `request: `, `result: ` or `failure: `, as in the shared vectors. */ + val classification: String + + /** `parameters` is the complete original `params`, including future envelope metadata. */ + data class Event( + val type: String, + val sessionID: String?, + val payload: JsonObject, + val sequence: Long?, + val parameters: JsonObject = JsonObject(emptyMap()), + ) : WireMessage { + override val classification get() = "event:$type" + } + + /** A live server request, answered with the same [id]. Absent or null `params` become `{}`. */ + data class Request(val id: String, val method: String, val params: JsonObject) : WireMessage { + override val classification get() = "request:$method" + } + + data class Result(val id: String, val value: JsonElement) : WireMessage { + override val classification get() = "result:$id" + } + + /** `reason` is `error.data.reason`; `message` is Hermes' words flattened for display, never a decision input. */ + data class Failure(val id: String, val code: Long, val reason: String?, val message: String?) : WireMessage { + override val classification get() = "failure:$id" + } +} + +/** Exact payload of a `request.cancel` event. */ +data class RequestCancellation(val id: String, val method: String, val reason: String) + +/** + * The gateway's framing seam. [decode] validates a whole WebSocket message before returning anything, so a + * caller either gets every entry in wire order or a [WireException] and nothing: a good first line followed + * by a bad one never publishes the first. + */ +object HermesWire { + const val MAXIMUM_MESSAGE_BYTES = 4 * 1_024 * 1_024 + const val MAXIMUM_BATCH_COUNT = 4_096 + const val MAXIMUM_METHOD_BYTES = 256 + const val MAXIMUM_REQUEST_ID_BYTES = 1_024 + const val MAXIMUM_CANCELLATION_REASON_BYTES = 4_096 + const val MAXIMUM_NESTING = StrictJson.MAXIMUM_DEPTH + const val MAXIMUM_REFUSAL_CHARACTERS = 280 + + private const val NEWLINE = 0x0a.toByte() + private val CANCELLATION_KEYS = setOf("id", "method", "reason") + + /** Lines are checked in order, like the iOS decoder, so the first violation decides the category. */ + fun decode(bytes: ByteArray): List { + if (bytes.size > MAXIMUM_MESSAGE_BYTES) throw tooLarge() + val messages = ArrayList () + var start = 0 + while (start < bytes.size) { + var end = start + while (end < bytes.size && bytes[end] != NEWLINE) end++ + if (!isBlank(bytes, start, end)) { + if (messages.size >= MAXIMUM_BATCH_COUNT) throw tooLarge() + validateNesting(bytes, start, end) + messages += decodeLine(bytes, start, end) + } + start = end + 1 + } + if (messages.isEmpty()) throw invalid() + return messages + } + + fun isValidMethod(method: String): Boolean = + method.length in 1..MAXIMUM_METHOD_BYTES && method.all { it.code in 33..126 } + + fun isValidRequestID(id: String): Boolean = utf8Length(id) <= MAXIMUM_REQUEST_ID_BYTES + + /** + * The documented cancellation is exact: only `id`, `method` and `reason`. Matching both ID and method + * stops a malformed cancel from retiring another prompt. + * @throws WireException if [event] is not a well-formed `request.cancel`. + */ + fun cancellation(event: WireMessage.Event): RequestCancellation { + val payload = event.payload + val id = payload["id"].string + val method = payload["method"].string + val reason = payload["reason"].string + if (event.type != "request.cancel" || payload.keys != CANCELLATION_KEYS || + id == null || !isValidRequestID(id) || + method == null || !isValidMethod(method) || + reason == null || utf8Length(reason) > MAXIMUM_CANCELLATION_REASON_BYTES + ) throw invalid() + return RequestCancellation(id, method, reason) + } + + private fun decodeLine(bytes: ByteArray, start: Int, end: Int): WireMessage { + val text = try { + Charsets.UTF_8.newDecoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .decode(ByteBuffer.wrap(bytes, start, end - start)) + .toString() + } catch (_: CharacterCodingException) { + throw invalid() + } + val root = try { + StrictJson.parse(text) + } catch (_: StrictJson.Malformed) { + throw invalid() + } + val envelope = root as? JsonObject ?: throw invalid() + if (envelope["jsonrpc"].string != "2.0") throw invalid() + + val method = envelope["method"] + val hasResponse = "result" in envelope || "error" in envelope + if (method != null) { + val name = method.string?.takeIf(::isValidMethod) ?: throw invalid() + if (hasResponse) throw invalid() + return if (name == "event") event(envelope) else request(envelope, name) + } + return response(envelope) + } + + private fun event(envelope: JsonObject): WireMessage { + if ("id" in envelope) throw invalid() + val params = envelope["params"] as? JsonObject ?: throw invalid() + val type = params["type"].string?.takeIf { it.isNotEmpty() && utf8Length(it) <= MAXIMUM_METHOD_BYTES } + ?: throw invalid() + val payload = params["payload"] + if (payload != null && payload !is JsonObject) throw invalid() + val session = params["session_id"] + if (session != null && session !is JsonNull && session.string == null) throw invalid() + val seq = params["seq"] + if (seq != null && seq.integer == null) throw invalid() + val event = WireMessage.Event( + type = type, + sessionID = session.string, + payload = payload as? JsonObject ?: JsonObject(emptyMap()), + sequence = seq.integer, + parameters = params, + ) + if (type == "request.cancel") cancellation(event) + return event + } + + private fun request(envelope: JsonObject, method: String): WireMessage { + // Backend notifications use method "event"; any other method needs a string ID to be a request. + val id = envelope["id"].string?.takeIf(::isValidRequestID) ?: throw invalid() + val params = when (val raw = envelope["params"]) { + null, JsonNull -> JsonObject(emptyMap()) + is JsonObject -> raw + else -> throw invalid() + } + return WireMessage.Request(id, method, params) + } + + private fun response(envelope: JsonObject): WireMessage { + // This client uses string IDs only; a numeric, null or absent ID is never reinterpreted. + val id = envelope["id"].string?.takeIf(::isValidRequestID) ?: throw invalid() + if ("params" in envelope) throw invalid() + val error = envelope["error"] as? JsonObject + val code = error?.get("code").integer + val result = envelope["result"] + return when { + error != null && code != null -> { + if (result != null) throw invalid() + val data = error["data"] as? JsonObject + WireMessage.Failure(id, code, data?.get("reason").string, refusalText(error["message"].string)) + } + result != null && "error" !in envelope -> WireMessage.Result(id, result) + else -> throw invalid() + } + } + + /** Counts `{`/`[` depth outside strings before any parsing, so hostile nesting never reaches the parser. */ + private fun validateNesting(bytes: ByteArray, start: Int, end: Int) { + var depth = 0 + var quoted = false + var escaped = false + for (index in start until end) { + val byte = bytes[index].toInt() + if (quoted) { + if (escaped) escaped = false + else if (byte == 0x5c) escaped = true + else if (byte == 0x22) quoted = false + } else if (byte == 0x22) quoted = true + else if (byte == 0x7b || byte == 0x5b) { + depth++ + if (depth > MAXIMUM_NESTING) throw tooLarge() + } else if (byte == 0x7d || byte == 0x5d) depth-- + } + } + + private fun isBlank(bytes: ByteArray, start: Int, end: Int): Boolean { + for (index in start until end) { + val byte = bytes[index].toInt() + if (byte != 0x20 && byte != 0x0d && byte != 0x09) return false + } + return true + } + + /** Hermes' refusal words as one short line of plain text: breaks, control and format characters become spaces. */ + private fun refusalText(raw: String?): String? { + if (raw.isNullOrEmpty()) return null + val words = ArrayList () + val word = StringBuilder() + var index = 0 + while (index < raw.length) { + val point = raw.codePointAt(index) + index += Character.charCount(point) + val separator = Character.isWhitespace(point) || Character.isSpaceChar(point) || + Character.getType(point).let { it == Character.CONTROL.toInt() || it == Character.FORMAT.toInt() } + if (separator) { + if (word.isNotEmpty()) { words += word.toString(); word.setLength(0) } + } else word.appendCodePoint(point) + } + if (word.isNotEmpty()) words += word.toString() + val line = words.joinToString(" ") + if (line.isEmpty()) return null + if (line.codePointCount(0, line.length) <= MAXIMUM_REFUSAL_CHARACTERS) return line + return line.substring(0, line.offsetByCodePoints(0, MAXIMUM_REFUSAL_CHARACTERS - 1)) + "…" + } + + private fun invalid() = WireException(WireException.Kind.InvalidResponse) + private fun tooLarge() = WireException(WireException.Kind.MessageTooLarge) + + private val JsonElement?.string: String? + get() = (this as? JsonPrimitive)?.takeIf { it.isString }?.content + + /** Only a JSON integer literal that fits 64 bits; `1.0`, `1e2`, strings and null are not integers. */ + private val JsonElement?.integer: Long? + get() = (this as? JsonPrimitive)?.takeIf { !it.isString && this !is JsonNull }?.content?.toLongOrNull() +} + +/** UTF-8 byte length of a string that holds no unpaired surrogate (the parser never produces one). */ +internal fun utf8Length(text: String): Int { + var bytes = 0 + var index = 0 + while (index < text.length) { + val unit = text[index] + bytes += when { + unit.code < 0x80 -> 1 + unit.code < 0x800 -> 2 + unit.isHighSurrogate() -> { index++; 4 } + else -> 3 + } + index++ + } + return bytes +} diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/StrictJson.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/StrictJson.kt new file mode 100644 index 00000000..5c4944a0 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/StrictJson.kt @@ -0,0 +1,209 @@ +package app.bighelp.hermes + +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 + +/** + * RFC 8259 parser for one gateway line. Trailing commas, comments, leading zeros, non-finite numbers, + * duplicate object keys and unpaired surrogate escapes are all rejected: the wire layer treats any of + * them as an invalid frame instead of guessing which value a host meant. + * + * Integers that fit a signed 64-bit value stay [Long]; every other number must be a finite [Double], so + * `1.0` is deliberately not an integer cursor. + */ +internal class StrictJson private constructor(private val text: String) { + private var position = 0 + + class Malformed : Exception() { + // A parse failure carries no frame text and no stack: it only means "reject the frame". + override fun fillInStackTrace(): Throwable = this + } + + companion object { + const val MAXIMUM_DEPTH = 64 + + /** @throws Malformed for any grammar violation or nesting beyond [MAXIMUM_DEPTH]. */ + fun parse(text: String): JsonElement { + val parser = StrictJson(text) + parser.skipWhitespace() + val value = parser.value(depth = 0) + parser.skipWhitespace() + if (parser.position != text.length) throw Malformed() + return value + } + } + + private fun value(depth: Int): JsonElement { + if (position >= text.length) throw Malformed() + return when (val c = text[position]) { + '{' -> obj(depth + 1) + '[' -> array(depth + 1) + '"' -> JsonPrimitive(string()) + 't' -> literal("true", JsonPrimitive(true)) + 'f' -> literal("false", JsonPrimitive(false)) + 'n' -> literal("null", JsonNull) + else -> if (c == '-' || c in '0'..'9') number() else throw Malformed() + } + } + + private fun obj(depth: Int): JsonElement { + if (depth > MAXIMUM_DEPTH) throw Malformed() + position++ // { + val members = LinkedHashMap () + skipWhitespace() + if (peek() == '}') { position++; return JsonObject(members) } + while (true) { + skipWhitespace() + if (peek() != '"') throw Malformed() + val key = string() + skipWhitespace() + if (peek() != ':') throw Malformed() + position++ + skipWhitespace() + val member = value(depth) + // First-wins (Foundation) and last-wins (most others) disagree; a duplicate is never legitimate. + if (members.put(key, member) != null) throw Malformed() + skipWhitespace() + when (peek()) { + ',' -> position++ + '}' -> { position++; return JsonObject(members) } + else -> throw Malformed() + } + } + } + + private fun array(depth: Int): JsonElement { + if (depth > MAXIMUM_DEPTH) throw Malformed() + position++ // [ + val elements = ArrayList () + skipWhitespace() + if (peek() == ']') { position++; return JsonArray(elements) } + while (true) { + skipWhitespace() + elements += value(depth) + skipWhitespace() + when (peek()) { + ',' -> position++ + ']' -> { position++; return JsonArray(elements) } + else -> throw Malformed() + } + } + } + + private fun string(): String { + position++ // opening quote + val out = StringBuilder() + while (true) { + if (position >= text.length) throw Malformed() + val c = text[position++] + when { + c == '"' -> return out.toString() + c < ' ' -> throw Malformed() // raw control characters must be escaped + c == '\\' -> { + if (position >= text.length) throw Malformed() + when (text[position++]) { + '"' -> out.append('"') + '\\' -> out.append('\\') + '/' -> out.append('/') + 'b' -> out.append('\b') + 'f' -> out.append('\u000c') + 'n' -> out.append('\n') + 'r' -> out.append('\r') + 't' -> out.append('\t') + 'u' -> out.append(unicodeEscape()) + else -> throw Malformed() + } + } + // An unpaired surrogate cannot be echoed back as the same UTF-8 bytes. Valid pairs are + // consumed together, so any surrogate seen on its own is a lone one. + c.isHighSurrogate() -> { + if (position >= text.length || !text[position].isLowSurrogate()) throw Malformed() + out.append(c).append(text[position++]) + } + c.isLowSurrogate() -> throw Malformed() + else -> out.append(c) + } + } + } + + private fun unicodeEscape(): String { + val first = hex4() + val unit = first.toChar() + return when { + unit.isHighSurrogate() -> { + if (position + 1 >= text.length || text[position] != '\\' || text[position + 1] != 'u') throw Malformed() + position += 2 + val low = hex4().toChar() + if (!low.isLowSurrogate()) throw Malformed() + String(charArrayOf(unit, low)) + } + unit.isLowSurrogate() -> throw Malformed() + else -> unit.toString() + } + } + + private fun hex4(): Int { + if (position + 4 > text.length) throw Malformed() + var result = 0 + repeat(4) { + val digit = Character.digit(text[position++], 16) + // Character.digit also accepts fullwidth and other non-ASCII digits. + if (digit < 0 || text[position - 1].code > 0x7f) throw Malformed() + result = result * 16 + digit + } + return result + } + + private fun number(): JsonElement { + val start = position + if (peek() == '-') position++ + when (peek()) { + '0' -> position++ + in '1'..'9' -> digits() + else -> throw Malformed() + } + var integral = true + if (peek() == '.') { + integral = false + position++ + if (peek() !in '0'..'9') throw Malformed() + digits() + } + if (peek() == 'e' || peek() == 'E') { + integral = false + position++ + if (peek() == '+' || peek() == '-') position++ + if (peek() !in '0'..'9') throw Malformed() + digits() + } + val raw = text.substring(start, position) + if (integral) raw.toLongOrNull()?.let { return JsonPrimitive(it) } + val double = raw.toDouble() + if (!double.isFinite()) throw Malformed() + return JsonPrimitive(double) + } + + private fun digits() { + while (peek() in '0'..'9') position++ + } + + private fun literal(word: String, value: JsonElement): JsonElement { + if (!text.startsWith(word, position)) throw Malformed() + position += word.length + return value + } + + private fun peek(): Char = if (position < text.length) text[position] else '\u0000' + + private fun skipWhitespace() { + while (position < text.length) { + when (text[position]) { + ' ', '\t', '\n', '\r' -> position++ + else -> return + } + } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesConnectionTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesConnectionTest.kt new file mode 100644 index 00000000..36e18178 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesConnectionTest.kt @@ -0,0 +1,202 @@ +package app.bighelp.hermes + +import kotlinx.serialization.json.Json +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertSame +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +/** Scripted ownership, readiness and admission scenarios. Nothing here opens a socket. */ +class HermesConnectionTest { + private val endpoint = HermesEndpoint.parse("hermes.example/p") + private val ready = HermesWire.decode( + """{"jsonrpc":"2.0","method":"event","params":{"type":"gateway.ready","payload":{"heartbeat":true}}}""".toByteArray(), + ).single() + private val notice = HermesWire.decode( + """{"jsonrpc":"2.0","method":"event","params":{"type":"notice","payload":{}}}""".toByteArray(), + ).single() + private val approval = HermesWire.decode( + """{"jsonrpc":"2.0","id":"s","method":"approval","params":{}}""".toByteArray(), + ).single() + + private fun capabilities(json: String) = GatewayCapabilities.decode(Json.parseToJsonElement(json)) + + private fun readySocket(owners: OwnerState) = + GatewaySocket.opening(owners.current!!).upgraded().receive(ready) + + private fun admit(socket: GatewaySocket, owners: OwnerState, operation: GatewayOperation) = + socket.admit(operation, owners) + + // Readiness is not the upgrade + + @Test fun upgradeAloneAllowsNoApplicationWrites() { + val owners = OwnerState.none.connect(endpoint, "principal-1") + val connecting = GatewaySocket.opening(owners.current!!) + val upgraded = connecting.upgraded() + assertEquals(SocketPhase.Connecting, connecting.phase) + assertEquals(SocketPhase.Upgraded, upgraded.phase) + listOf(connecting, upgraded).forEach { socket -> + assertFalse(socket.canWriteApplicationFrames) + GatewayOperation.entries.forEach { + assertEquals(Admission.Refused(Refusal.NotReady), admit(socket, owners, it)) + } + } + } + + @Test fun onlyGatewayReadyEndsTheWaitAndOtherMessagesDoNot() { + val owners = OwnerState.none.connect(endpoint, "principal-1") + val upgraded = GatewaySocket.opening(owners.current!!).upgraded() + assertSame(upgraded, upgraded.receive(notice)) + assertSame("Early server requests are processed but do not make the socket ready", upgraded, upgraded.receive(approval)) + val now = upgraded.receive(ready) + assertEquals(SocketPhase.Ready, now.phase) + assertTrue(now.canWriteApplicationFrames) + assertEquals("gateway.ready", now.ready?.type) + assertEquals(Admission.Admitted, admit(now, owners, GatewayOperation.Read)) + } + + @Test fun readyBeforeTheUpgradeCompletesIsNotAcceptedAndASecondReadyClosesTheSocket() { + val owners = OwnerState.none.connect(endpoint, "principal-1") + val connecting = GatewaySocket.opening(owners.current!!) + assertEquals(SocketPhase.Connecting, connecting.receive(ready).phase) + val now = readySocket(owners) + val closed = now.receive(ready) + assertEquals(SocketPhase.Closed, closed.phase) + assertFalse(closed.canWriteApplicationFrames) + assertEquals(Admission.Refused(Refusal.NotReady), admit(closed, owners, GatewayOperation.Read)) + assertEquals("A closed socket cannot become ready again", SocketPhase.Closed, closed.upgraded().receive(ready).phase) + } + + // Capability is a required Boolean + + @Test fun exclusiveSubmitMustBeAJsonBoolean() { + assertTrue(capabilities("""{"per_session_exclusive_submit":true,"future":{"x":1}}""").perSessionExclusiveSubmit) + assertFalse(capabilities("""{"per_session_exclusive_submit":false}""").perSessionExclusiveSubmit) + listOf( + "{}", "[]", "null", "true", "\"true\"", + """{"per_session_exclusive_submit":"true"}""", """{"per_session_exclusive_submit":"false"}""", + """{"per_session_exclusive_submit":null}""", """{"per_session_exclusive_submit":1}""", + """{"per_session_exclusive_submit":0}""", """{"per_session_exclusive_submit":[true]}""", + """{"per_session_exclusive_submit":{"v":true}}""", """{"Per_Session_Exclusive_Submit":true}""", + ).forEach { + try { + capabilities(it) + fail("Expected $it to fail discovery") + } catch (error: WireException) { + assertEquals("invalidResponse", error.category) + } + } + } + + @Test fun submissionNeedsTheGuaranteeButReadsAndControlsDoNot() { + var owners = OwnerState.none.connect(endpoint, "principal-1") + val undiscovered = readySocket(owners) + assertNull(undiscovered.capabilities) + assertEquals(Admission.Refused(Refusal.CapabilitiesUnknown), admit(undiscovered, owners, GatewayOperation.Submission)) + assertEquals(Admission.Admitted, admit(undiscovered, owners, GatewayOperation.Read)) + + val unsafe = undiscovered.discovered(capabilities("""{"per_session_exclusive_submit":false}""")) + assertEquals(Admission.Refused(Refusal.ExclusiveSubmitUnavailable), admit(unsafe, owners, GatewayOperation.Submission)) + assertEquals(Admission.Admitted, admit(unsafe, owners, GatewayOperation.Read)) + assertEquals(Admission.Admitted, admit(unsafe, owners, GatewayOperation.Control)) + + val safe = undiscovered.discovered(capabilities("""{"per_session_exclusive_submit":true}""")) + GatewayOperation.entries.forEach { assertEquals(Admission.Admitted, admit(safe, owners, it)) } + + // A new connection starts without them: nothing carries over from a retired socket. + owners = owners.connect(endpoint, "principal-1") + val replacement = readySocket(owners) + assertNull(replacement.capabilities) + assertEquals(Admission.Refused(Refusal.CapabilitiesUnknown), admit(replacement, owners, GatewayOperation.Submission)) + } + + @Test fun capabilitiesCanOnlyBeDiscoveredOnAReadySocket() { + val owners = OwnerState.none.connect(endpoint, "principal-1") + val upgraded = GatewaySocket.opening(owners.current!!).upgraded() + try { + upgraded.discovered(GatewayCapabilities(true)) + fail("Discovery before gateway.ready is a caller bug") + } catch (_: IllegalStateException) { + } + assertNull(readySocket(owners).closed().capabilities) + } + + // Retired generations cannot publish + + @Test fun aSupersededSocketIsRefusedEvenThoughItsOwnStateIsReady() { + val first = OwnerState.none.connect(endpoint, "principal-1") + val oldSocket = readySocket(first).discovered(GatewayCapabilities(true)) + assertEquals(Admission.Admitted, admit(oldSocket, first, GatewayOperation.Submission)) + + val second = first.connect(endpoint, "principal-1") + assertEquals(1L, first.current!!.generation) + assertEquals(2L, second.current!!.generation) + assertTrue(oldSocket.canWriteApplicationFrames) + GatewayOperation.entries.forEach { + assertEquals(Admission.Refused(Refusal.StaleOwner), admit(oldSocket, second, it)) + } + assertFalse(second.accepts(first.current!!)) + assertTrue(second.accepts(second.current!!)) + } + + @Test fun nothingPublishesWhileDisconnectedAndGenerationsNeverRepeat() { + val first = OwnerState.none.connect(endpoint, "principal-1") + val gone = first.disconnect() + assertNull(gone.current) + assertFalse(gone.accepts(first.current!!)) + assertEquals(Admission.Refused(Refusal.StaleOwner), admit(readySocket(first), gone, GatewayOperation.Read)) + + val back = gone.connect(endpoint, "principal-1") + assertEquals(2L, back.current!!.generation) + assertNotEquals("The same endpoint and principal again is still a different owner", first.current, back.current) + assertFalse(back.accepts(first.current!!)) + assertEquals(3L, back.disconnect().disconnect().connect(endpoint, "principal-1").current!!.generation) + } + + @Test fun endpointAndPrincipalAreBothPartOfWhoOwnsAResult() { + val owners = OwnerState.none.connect(endpoint, "principal-1") + val current = owners.current!! + assertTrue(owners.accepts(current.copy())) + assertFalse(owners.accepts(current.copy(principal = "principal-2"))) + assertFalse(owners.accepts(current.copy(endpoint = HermesEndpoint.parse("hermes.example/q").canonical))) + assertFalse(owners.accepts(current.copy(endpoint = HermesEndpoint.parse("hermes.example:8443/p").canonical))) + assertFalse(owners.accepts(current.copy(generation = current.generation + 1))) + assertEquals("https://hermes.example/p", current.endpoint) + + // Switching principal on the same endpoint retires the old owner's results. + val switched = owners.connect(endpoint, "principal-2") + assertFalse(switched.accepts(current)) + } + + // An unknown dispatch is never resent + + @Test fun aMutationThatMayHaveBeenSentIsUncertainAndNeverRetried() { + listOf("prompt.submit", "session.create", "session.interrupt", "future.method", "gateway.Ping", "", "session.list ") + .forEach { method -> + assertFalse(method, DispatchPolicy.isReadOnly(method)) + assertTrue(method, DispatchPolicy.isUncertain(method, DispatchOutcome.MayHaveBeenSent)) + assertFalse(method, DispatchPolicy.mayRetry(method, DispatchOutcome.MayHaveBeenSent)) + assertTrue("Never sent is safe to issue", DispatchPolicy.mayRetry(method, DispatchOutcome.NotSent)) + } + } + + @Test fun readsMayBeAskedAgainAndAnsweredRequestsNeverAre() { + assertEquals(26, DispatchPolicy.readOnlyMethods.size) + DispatchPolicy.readOnlyMethods.forEach { method -> + assertFalse(DispatchPolicy.isUncertain(method, DispatchOutcome.MayHaveBeenSent)) + assertTrue(DispatchPolicy.mayRetry(method, DispatchOutcome.MayHaveBeenSent)) + assertTrue(DispatchPolicy.mayRetry(method, DispatchOutcome.NotSent)) + } + listOf("session.history", "prompt.submit").forEach { method -> + listOf(DispatchOutcome.ConfirmedResult, DispatchOutcome.ConfirmedRefusal).forEach { + assertFalse(DispatchPolicy.mayRetry(method, it)) + assertFalse(DispatchPolicy.isUncertain(method, it)) + } + assertFalse(DispatchPolicy.isUncertain(method, DispatchOutcome.NotSent)) + } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointContractTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointContractTest.kt new file mode 100644 index 00000000..488fb31e --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointContractTest.kt @@ -0,0 +1,191 @@ +package app.bighelp.hermes + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNotEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +/** The CONNECTION.md §1 rules the basic endpoint tests do not pin down. */ +class HermesEndpointContractTest { + private fun canonical(input: String, allowPrivateHttp: Boolean = false) = + HermesEndpoint.parse(input, allowPrivateHttp).canonical + + private fun rejects(input: String, allowPrivateHttp: Boolean = false, reason: HermesEndpointException.Reason? = null) { + try { + HermesEndpoint.parse(input, allowPrivateHttp) + fail("Expected rejection of '$input'") + } catch (error: HermesEndpointException) { + if (reason != null) assertEquals(input, reason, error.reason) + } + } + + @Test fun documentedExampleBuildsEveryRoute() { + val endpoint = HermesEndpoint.parse("HERMES.EXAMPLE:443/hermes/") + assertEquals("https://hermes.example/hermes", endpoint.canonical) + assertEquals("https://hermes.example/hermes/api/status", endpoint.httpUrl("/api/status").toString()) + assertEquals("https://hermes.example/hermes/", endpoint.httpUrl("/").toString()) + assertEquals("wss://hermes.example/hermes/api/ws", endpoint.webSocketUrl) + } + + @Test fun schemeDefaultsToHttpsAndIsCaseInsensitive() { + assertEquals("https://hermes.example", canonical("hermes.example")) + assertEquals("https://hermes.example", canonical("HTTPS://Hermes.Example/")) + listOf("ftp://h.example", "ws://h.example", "wss://h.example", "file://h.example", "://h.example", + "https:/h.example", "https:///h.example", "https://", "http s://h.example", "https:h.example") + .forEach { rejects(it, true) } + } + + @Test fun defaultPortsDisappearAndOthersStayPartOfTheIdentity() { + assertEquals("https://h.example", canonical("https://h.example:443")) + assertEquals("https://h.example:8443", canonical("https://h.example:8443")) + assertEquals("https://h.example:80", canonical("https://h.example:80")) + assertEquals("http://hermes", canonical("http://hermes:80", true)) + assertEquals("http://hermes:443", canonical("http://hermes:443", true)) + assertEquals("ws://hermes:8080/p/api/ws", HermesEndpoint.parse("http://hermes:8080/p", true).webSocketUrl) + assertEquals("https://h.example:65535", canonical("h.example:65535")) + listOf("h.example:0", "h.example:65536", "h.example:", "h.example:-1", "h.example:+1", "h.example:1 2", + "h.example:999999", "h.example:80a", "h.example::80", "https://h.example:0x50").forEach { rejects(it) } + } + + @Test fun pathsPreserveThePrefixAndRejectEverythingAmbiguous() { + assertEquals("https://h.example/a/b", canonical("h.example/a/b/")) + assertEquals("https://h.example", canonical("h.example/")) + assertEquals("https://h.example/a-b_c.d~e", canonical("h.example/a-b_c.d~e")) + listOf("h.example/a//b", "h.example//", "h.example/a/./b", "h.example/./", "h.example/..", "h.example/a/../b", + "h.example/%2e%2e", "h.example/a%2fb", "h.example/%41", "h.example/a b", "h.example/ü", "h.example/a:b", + "h.example/a;b", "h.example/a@b", "h.example/a'b", "h.example/a*b", "h.example/a,b", "h.example/a=b", + "h.example/a+b", "h.example/a!b", "h.example/a(b)", "h.example/a\\b").forEach { rejects(it) } + } + + @Test fun credentialsQueryAndFragmentAreRefusedEvenWhenEmpty() { + listOf("https://@h.example", "https://u@h.example", "https://u:p@h.example", "https://h.example:443@evil.example", + "https://evil.example\\@h.example", "https://h.example?", "https://h.example/?", "https://h.example/a?x=1", + "https://h.example#", "https://h.example/#f", "h.example/a#b", "https://h.example/p?next=//evil") + .forEach { rejects(it, true) } + } + + @Test fun whitespaceControlsAndNonAsciiAreRefused() { + listOf("", " ", "\th.example", "h.example\n", "h .example", "h.example\u007f", "h.example\u0000", "hérmes.example", + "h.example\u00a0", "h.example", "h.example/\u2028", "https://h.example/a\r\n", "h" + "e".repeat(2_048) + ".example") + .forEach { rejects(it, true) } + } + + @Test fun hostNamesFollowDnsLabelRulesWithoutNumericAliases() { + assertEquals("https://xn--bcher-kva.example", canonical("XN--BCHER-KVA.EXAMPLE")) + assertEquals("https://a-b.example", canonical("a-b.example")) + assertEquals("https://1e3.example", canonical("1e3.example")) + val label = "a".repeat(63) + assertEquals("https://$label.example", canonical("$label.example")) + listOf("${label}a.example", "-a.example", "a-.example", "a..example", ".example", "a_b.example", "a b.example", + "a.example.", "a.", "[a.example]", "${"a".repeat(62)}.".repeat(5) + "example", + // Numeric aliases and malformed dotted quads + "127.1", "127.0.1", "0x7f.0.0.1", "0x7f000001", "2130706433", "017700000001", "1.2.3", "1.2.3.4.5", "256.1.1.1", + "010.0.0.1", "1.2.3.04", "1.2.3.4.", ".1.2.3.4", "0x1", "0X7F000001", "1..2.3", + ).forEach { rejects(it, true) } + assertEquals("https://0.0.0.0", canonical("0.0.0.0")) + assertEquals("https://8.8.8.8:8080", canonical("8.8.8.8:8080")) + } + + @Test fun ipv6LiteralsAreBracketedLowercasedAndNeverResolved() { + assertEquals("https://[::1]", canonical("[::1]")) + assertEquals("https://[::1]", canonical("::1")) + assertEquals("https://[fd7a:115c:a1e0::1]:8443/p", canonical("[FD7A:115C:A1E0::1]:8443/p/")) + assertEquals("https://[fd7a:115c:a1e0::1]", canonical("FD7A:115C:A1E0::1")) + assertEquals("https://[::ffff:1.2.3.4]", canonical("[::ffff:1.2.3.4]")) + assertEquals("https://[1:2:3:4:5:6:7:8]", canonical("[1:2:3:4:5:6:7:8]")) + assertEquals("https://[1:2:3:4:5:6:7::]", canonical("[1:2:3:4:5:6:7::]")) + assertEquals("wss://[::1]:9/p/api/ws", HermesEndpoint.parse("[::1]:9/p").webSocketUrl) + assertEquals("https://[::1]:9/p/api/x", HermesEndpoint.parse("[::1]:9/p").httpUrl("/api/x").toString()) + // A bare literal has no way to carry a port, so "::1:8080" is the address ::1:8080, not port 8080. + assertEquals("https://[::1:8080]", canonical("::1:8080")) + listOf("[::1", "::1]", "[::1]x", "[::1]:", "[::1]:0", "[[::1]]", "[]", "[:::1]", "[1::2::3]", "[1:2:3:4:5:6:7:8:9]", + "[1:2:3:4:5:6:7::8]", "[1:2:3:4:5:6:7:8::]", "[12345::]", "[g::1]", "[1.2.3.4]", "[example.com]", "[::1.2.3]", + "[::01.2.3.4]", "[1.2.3.4::]", "[::1%25en0]", "[::1%en0]", "[fe80::1%25en0]", "::1%en0", "[ ::1]", + "[::ff]", "1:2:3::4::", "::1/path:x@y", "https://::1", "https://::1:80").forEach { rejects(it, true) } + } + + @Test fun plainHttpNeedsOptInAndASyntacticallyPrivateHost() { + val rejectedWithoutOptIn = HermesEndpointException.Reason.PlaintextNotAllowed + rejects("http://hermes", false, rejectedWithoutOptIn) + rejects("http://example.com", true, rejectedWithoutOptIn) + rejects("http://192.0.2.1", true, rejectedWithoutOptIn) + rejects("http://h.example/%", true, HermesEndpointException.Reason.InvalidEndpoint) + + listOf( + "127.0.0.1", "127.255.255.254", "10.0.0.1", "10.255.255.255", "172.16.0.1", "172.31.255.255", + "192.168.0.1", "192.168.255.255", "100.64.0.1", "100.127.255.255", "169.254.1.1", + "[::1]", "[0:0:0:0:0:0:0:1]", "[fc00::1]", "[fdff:ffff::1]", "[fd7a:115c:a1e0::1]", "[FD7A::1]", + "hermes", "HERMES", "localhost", "printer.local", "nas.lan", "box.internal", "r.home.arpa", "app.intranet", + "x.corp", "pc.localdomain", "x.private", "app.localhost", "a.b.local", "bot.ts.net", "x.y.ts.net", + "bot.beta.tailscale.net", "local", "xlocal", + ).forEach { assertEquals("http://${it.lowercase()}", canonical("http://$it", true)) } + + listOf( + "172.15.255.255", "172.32.0.1", "100.63.255.255", "100.128.0.1", "192.167.0.1", "192.169.0.1", "11.0.0.1", + "9.255.255.255", "169.253.1.1", "126.0.0.1", "128.0.0.1", "1.1.1.1", "0.0.0.0", "255.255.255.255", + "[::]", "[::2]", "[::ffff:127.0.0.1]", "[::ffff:10.0.0.1]", "[fe80::1]", "[fe00::1]", "[fb00::1]", "[fe00::]", + "[2001:db8::1]", "[1::1]", "[::1:0]", "[100::1]", + "example.com", "hermes.example.com", "127.0.0.1.example.com", "hermes.lan.example.com", "example-ts.net", + "ts.net", "tailscale.net", "beta.tailscale.net", "x.localhost.com", "x.corpus", "my.home.arpa.evil.com", + "xts.net", "bot.ts.net.evil.com", + ).forEach { rejects("http://$it", true, HermesEndpointException.Reason.PlaintextNotAllowed) } + } + + @Test fun routesAreAppOwnedRelativePathsOnly() { + val endpoint = HermesEndpoint.parse("h.example:8443/p") + assertEquals("https://h.example:8443/p/api/sessions/abc:1_x-y.z~", endpoint.httpUrl("/api/sessions/abc:1_x-y.z~").toString()) + assertEquals("https://h.example:8443/p/api/files/", endpoint.httpUrl("/api/files/").toString()) + listOf( + "", "api/x", "x", "https://h.example/p/api/x", "http://evil", "//evil", "//", "/a//b", "/./x", "/x/.", "/..", "/x/../y", + "/x?q=1", "/x?", "/x#f", "/x#", "/x%2f", "/x%", "/x\\y", "\\x", "/x y", "/x\ty", "/x\ny", "/é", "/x\u0000", "/x\u007f", + "/x\"y", "/x y", "/x{y}", "/x|y", "/x^y", "/x`y", "/x[y]", "@evil", "/x\u2028", + ).forEach { route -> + try { + endpoint.httpUrl(route) + fail("Expected route '$route' to be refused") + } catch (error: HermesEndpointException) { + assertEquals(HermesEndpointException.Reason.InvalidRoute, error.reason) + } + } + // Every accepted route stays under the exact origin and prefix. + val url = endpoint.httpUrl("/api/x") + assertEquals("h.example", url.host) + assertEquals(8443, url.port) + assertTrue(url.path.startsWith("/p/")) + } + + @Test fun canonicalFormParsesBackToItself() { + listOf( + "HERMES.EXAMPLE:443/hermes/", "h.example:8443/a/b/", "[FD7A::1]:80/p", "::1", "http://Hermes.LAN:80/x/", + "http://[::1]:8080", "https://8.8.8.8", "http://100.64.0.1/p/q", + ).forEach { input -> + val first = HermesEndpoint.parse(input, true) + val again = HermesEndpoint.parse(first.canonical, true) + assertEquals(input, first.canonical, again.canonical) + assertEquals(input, first, again) + assertEquals(first.webSocketUrl, again.webSocketUrl) + } + } + + @Test fun identityIncludesSchemePortPrefixAndTheOptIn() { + val base = HermesEndpoint.parse("https://h.example/a") + assertEquals(base, HermesEndpoint.parse("H.EXAMPLE:443/a/")) + assertEquals(base.hashCode(), HermesEndpoint.parse("H.EXAMPLE:443/a/").hashCode()) + assertNotEquals(base, HermesEndpoint.parse("https://h.example/b")) + assertNotEquals(base, HermesEndpoint.parse("https://h.example:8443/a")) + assertNotEquals(base, HermesEndpoint.parse("https://h.example")) + assertNotEquals(base, HermesEndpoint.parse("https://h.example/a", allowPrivateHttp = true)) + assertNotEquals(HermesEndpoint.parse("http://hermes", true), HermesEndpoint.parse("https://hermes", true)) + } + + @Test fun failuresAreIllegalArgumentsThatNeverEchoTheInput() { + val secret = "https://user:hunter2@h.example/?token=abc" + try { + HermesEndpoint.parse(secret) + fail("credentials must be refused") + } catch (error: IllegalArgumentException) { + assertTrue(!(error.message ?: "").contains("hunter2") && !(error.message ?: "").contains("abc")) + } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointTest.kt new file mode 100644 index 00000000..9a4d1179 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesEndpointTest.kt @@ -0,0 +1,39 @@ +package app.bighelp.hermes + +import org.junit.Assert.* +import org.junit.Test + +class HermesEndpointTest { + @Test fun normalizesIdentityAndPreservesDeploymentPrefix() { + val endpoint = HermesEndpoint.parse("HERMES.EXAMPLE:443/hermes/") + assertEquals("https://hermes.example/hermes", endpoint.canonical) + assertEquals("https://hermes.example/hermes/api/status", endpoint.httpUrl("/api/status").toString()) + assertEquals("wss://hermes.example/hermes/api/ws", endpoint.webSocketUrl) + } + + @Test fun privateHttpRequiresBothOptInAndPrivateSyntax() { + listOf("127.0.0.1", "10.2.3.4", "100.64.0.1", "hermes", "bot.ts.net", "[::1]").forEach { + rejects("http://$it") + assertTrue(HermesEndpoint.parse("http://$it", true).canonical.startsWith("http://")) + } + listOf("example.com", "127.0.0.1.example.com", "example-ts.net", "8.8.8.8", "[fe80::1]").forEach { + rejects("http://$it", true) + } + } + + @Test fun rejectsCredentialSmugglingTraversalAndAmbiguousAddresses() { + listOf(" https://hermes.example", "https://u:p@hermes.example", "https://hermes.example/?token=x", + "https://hermes.example/#x", "https://hermes.example/a/../b", "https://hermes.example/%2e", + "https://hermes.example//a", "https://hermes.example:", "https://hermes.example:65536", + "https://127.1", "https://0x7f000001", "https://2130706433", "https://host.", "https://host\\evil" + ).forEach { rejects(it, true) } + val endpoint = HermesEndpoint.parse("hermes.example/prefix") + listOf("https://other.example", "//evil", "/a/../b", "/api/x?q=1", "/%2f").forEach { + try { endpoint.httpUrl(it); fail(it) } catch (_: IllegalArgumentException) { } + } + } + + private fun rejects(input: String, allowPrivateHttp: Boolean = false) { + try { HermesEndpoint.parse(input, allowPrivateHttp); fail(input) } catch (_: IllegalArgumentException) { } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireLimitsTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireLimitsTest.kt new file mode 100644 index 00000000..6708762d --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireLimitsTest.kt @@ -0,0 +1,191 @@ +package app.bighelp.hermes + +import org.junit.Assert.assertEquals +import org.junit.Assert.assertArrayEquals +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +/** Every documented ceiling, at the limit and one byte over, in characters of 1 to 4 UTF-8 bytes. */ +class HermesWireLimitsTest { + private val units = listOf("a", "é", "€", "😀") + + /** A string of exactly [bytes] UTF-8 bytes whose bulk is [unit], padded with ASCII. */ + private fun exactly(unit: String, bytes: Int): String { + val bulk = unit.repeat(bytes / unit.toByteArray().size) + return bulk + "a".repeat(bytes - bulk.toByteArray().size) + } + + private fun decode(frame: String) = HermesWire.decode(frame.toByteArray()) + + private fun rejects(category: String, frame: String) = rejects(category, frame.toByteArray()) + + private fun rejects(category: String, bytes: ByteArray) { + try { + HermesWire.decode(bytes) + fail("Expected $category") + } catch (error: WireException) { + assertEquals(category, error.category) + } + } + + private fun response(id: String) = """{"jsonrpc":"2.0","id":"$id","result":null}""" + private fun request(id: String, method: String = "approval") = """{"jsonrpc":"2.0","id":"$id","method":"$method","params":{}}""" + private fun event(type: String, payload: String = "{}") = + """{"jsonrpc":"2.0","method":"event","params":{"type":"$type","payload":$payload}}""" + private fun cancel(id: String = "a", method: String = "clarify", reason: String = "expired") = + event("request.cancel", """{"id":"$id","method":"$method","reason":"$reason"}""") + + @Test fun idsAreBoundedInUtf8BytesForRequestsAndResponses() { + units.forEach { unit -> + val atLimit = exactly(unit, 1_024) + assertEquals(1_024, atLimit.toByteArray().size) + assertEquals("result:$atLimit", decode(response(atLimit)).single().classification) + assertEquals("request:approval", decode(request(atLimit)).single().classification) + rejects("invalidResponse", response(atLimit + "a")) + rejects("invalidResponse", request(atLimit + "a")) + } + } + + @Test fun methodsAreAsciiAndBoundedAt256() { + val atLimit = "m".repeat(256) + assertEquals("request:$atLimit", decode(request("a", atLimit)).single().classification) + rejects("invalidResponse", request("a", atLimit + "m")) + // Printable ASCII only: the boundary characters U+0021 and U+007E pass, space, DEL and non-ASCII do not. + assertEquals("request:!~", decode(request("a", "!~")).single().classification) + listOf(" ", "\\u007f", "m\\u00e9", "m\\u0001").forEach { rejects("invalidResponse", request("a", "x$it")) } + } + + @Test fun eventTypesAreBoundedInUtf8Bytes() { + units.forEach { unit -> + val atLimit = exactly(unit, 256) + assertEquals("event:$atLimit", decode(event(atLimit)).single().classification) + rejects("invalidResponse", event(atLimit + "a")) + } + } + + @Test fun cancellationReasonIsBoundedInUtf8Bytes() { + units.forEach { unit -> + val atLimit = exactly(unit, 4_096) + val cancellation = HermesWire.cancellation(decode(cancel(reason = atLimit)).single() as WireMessage.Event) + assertEquals(atLimit, cancellation.reason) + rejects("invalidResponse", cancel(reason = atLimit + "a")) + } + } + + @Test fun cancellationIdAndMethodAreValidatedLikeRequests() { + val longestId = exactly("😀", 1_024) + assertEquals(longestId, HermesWire.cancellation(decode(cancel(id = longestId)).single() as WireMessage.Event).id) + rejects("invalidResponse", cancel(id = longestId + "a")) + rejects("invalidResponse", cancel(method = "m".repeat(257))) + rejects("invalidResponse", cancel(method = "has space")) + } + + @Test fun cancellationPayloadMustBeExactlyIdMethodReason() { + listOf( + """{"id":"a","method":"clarify"}""", + """{"id":"a","reason":"x"}""", + """{"method":"clarify","reason":"x"}""", + """{"id":"a","method":"clarify","reason":"x","extra":1}""", + """{"id":1,"method":"clarify","reason":"x"}""", + """{"id":"a","method":null,"reason":"x"}""", + """{"id":"a","method":"clarify","reason":7}""", + """{"id":"a","method":"clarify","reason":null}""", + """{}""", + ).forEach { rejects("invalidResponse", event("request.cancel", it)) } + // An event with no payload key at all is a cancellation with no keys. + rejects("invalidResponse", """{"jsonrpc":"2.0","method":"event","params":{"type":"request.cancel"}}""") + } + + @Test fun cancellationIsDecodedFromTheEventForTheOwnerToMatch() { + val message = decode(cancel(id = " é ", method = "approval", reason = "done")).single() as WireMessage.Event + assertEquals(RequestCancellation(" é ", "approval", "done"), HermesWire.cancellation(message)) + try { + HermesWire.cancellation(decode(event("notice")).single() as WireMessage.Event) + fail("A non-cancel event is not a cancellation") + } catch (error: WireException) { + assertEquals("invalidResponse", error.category) + } + } + + @Test fun wholeMessageCeilingCountsBytesNotCharacters() { + val head = """{"jsonrpc":"2.0","id":"r","result":"""" + val tail = "\"}" + val body = 4_194_304 - head.length - tail.length + // 4-byte characters fill the frame with a character count far under the byte ceiling. + val filler = "😀".repeat(body / 4) + "a".repeat(body % 4) + val exact = (head + filler + tail).toByteArray() + assertEquals(4_194_304, exact.size) + assertTrue(exact.size > (head + filler + tail).length) + assertEquals(1, HermesWire.decode(exact).size) + rejects("messageTooLarge", exact + byteArrayOf(' '.code.toByte())) + } + + @Test fun messageCeilingIsCheckedBeforeAnyParsing() { + // Not even JSON, but over the ceiling: the size category wins and nothing is parsed. + rejects("messageTooLarge", ByteArray(4_194_305) { 0xff.toByte() }) + } + + @Test fun nonBlankLineCountIgnoresBlankLines() { + val one = response("r") + val padded = List(4_096) { one }.joinToString("\n\n \t\r\n") + assertEquals(4_096, decode(padded + "\n\n\n").size) + rejects("messageTooLarge", List(4_097) { one }.joinToString("\n\n")) + } + + @Test fun nestingDepthCountsTheWholeValueIncludingEnvelopeObjects() { + fun nested(arrays: Int) = event("deep", """{"x":""" + "[".repeat(arrays) + "0" + "]".repeat(arrays) + "}") + // Envelope (1) + params (2) + payload (3) + "x" arrays: 61 arrays reach exactly 64 levels. + assertEquals(1, decode(nested(61)).size) + rejects("messageTooLarge", nested(62)) + // Objects count like arrays: the envelope plus 63 nested objects is 64 levels. + fun objects(count: Int) = + """{"jsonrpc":"2.0","id":"r","result":""" + """{"a":""".repeat(count - 1) + "{}" + "}".repeat(count - 1) + "}" + assertEquals(1, decode(objects(63)).size) + rejects("messageTooLarge", objects(64)) + } + + @Test fun bracketsInsideStringsDoNotCountAsDepth() { + val noisy = "[".repeat(200) + """\"[[""" + "]".repeat(200) + assertEquals("result:r", decode("""{"jsonrpc":"2.0","id":"r","result":"$noisy"}""").single().classification) + } + + @Test fun depthIsMeasuredPerLineSoNewlinesResetIt() { + val deepEnough = """{"jsonrpc":"2.0","id":"r","result":""" + "[".repeat(63) + "0" + "]".repeat(63) + "}" + assertEquals(3, decode(listOf(deepEnough, deepEnough, deepEnough).joinToString("\n")).size) + } + + @Test fun anyBadLineRejectsTheWholeMessageWithoutPublishingEarlierOnes() { + val good = response("first") + val tooDeep = """{"jsonrpc":"2.0","id":"b","result":""" + "[".repeat(65) + "]".repeat(65) + "}" + listOf( + "invalidResponse" to good.toByteArray() + "\n{".toByteArray(), + "invalidResponse" to good.toByteArray() + "\n".toByteArray() + byteArrayOf(0x7b, 0x22, 0xff.toByte(), 0x22, 0x7d), + "invalidResponse" to good.toByteArray() + "\n[1]".toByteArray(), + "messageTooLarge" to (good + "\n" + tooDeep).toByteArray(), + ).forEach { (category, bytes) -> rejects(category, bytes) } + } + + @Test fun firstViolationInWireOrderDecidesTheCategory() { + val bad = "{" + val one = response("r") + // An invalid line before the 4,097th object is reported first... + rejects("invalidResponse", (listOf(bad) + List(4_097) { one }).joinToString("\n")) + // ...and one after it is never reached. + rejects("messageTooLarge", (List(4_097) { one } + listOf(bad)).joinToString("\n")) + } + + @Test fun opaqueIdsKeepTheirExactUtf8Bytes() { + val composed = "request:é" + val decomposed = "request:é" + listOf(composed, decomposed, "😀", "", " lead\ttrail ", "").forEach { id -> + val escaped = id.map { if (it.code < 0x20) "\\u%04x".format(it.code) else it.toString() }.joinToString("") + val request = decode("""{"jsonrpc":"2.0","id":"$escaped","method":"approval","params":{}}""").single() + as WireMessage.Request + assertArrayEquals(id.toByteArray(), request.id.toByteArray()) + } + val a = decode(request(composed)).single() as WireMessage.Request + val b = decode(request(decomposed)).single() as WireMessage.Request + assertTrue("Canonically equivalent IDs must stay distinct", a.id != b.id) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireStrictnessTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireStrictnessTest.kt new file mode 100644 index 00000000..19540956 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireStrictnessTest.kt @@ -0,0 +1,165 @@ +package app.bighelp.hermes + +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import org.junit.Assert.assertEquals +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Assert.fail +import org.junit.Test + +/** What counts as a well-formed frame beyond the shared vectors: JSON grammar, UTF-8 and field types. */ +class HermesWireStrictnessTest { + private fun decode(frame: String) = HermesWire.decode(frame.toByteArray()) + + private fun rejects(frame: String, category: String = "invalidResponse") = rejects(frame.toByteArray(), category, frame) + + private fun rejects(bytes: ByteArray, category: String = "invalidResponse", label: String = bytes.contentToString()) { + try { + HermesWire.decode(bytes) + fail("Expected rejection of $label") + } catch (error: WireException) { + assertEquals(label, category, error.category) + } + } + + private fun result(value: String) = """{"jsonrpc":"2.0","id":"r","result":$value}""" + private fun eventParams(params: String) = """{"jsonrpc":"2.0","method":"event","params":$params}""" + + @Test fun grammarViolationsRejectTheFrame() { + listOf( + """{"jsonrpc":"2.0","id":"r","result":{},}""", // trailing comma + """{"jsonrpc":"2.0","id":"r","result":[1,]}""", + """{"jsonrpc":"2.0","id":"r","jsonrpc":"2.0","result":{}}""", // duplicate keys, top level + """{"jsonrpc":"2.0","id":"r","result":{"a":1,"a":2}}""", // and nested + """{"jsonrpc":"2.0","id":"r","id":"s","result":{}}""", + result("01"), result("+1"), result(".5"), result("1."), result("1e"), result("-"), result("0x10"), + result("NaN"), result("Infinity"), result("-Infinity"), result("1e999"), result("-1e999"), + result("'single'"), result("tru"), result("nul"), result("True"), + result("\"a\tb\""), // raw control character in a string + result("\"a\\x41\""), result("\"\\u12G4\""), result("\"\\u12\""), result("\"unterminated"), + result("{} /* comment */"), result("1 2"), + result("{\"a\" 1}"), result("{\"a\":}"), result("{1:2}"), result("[,]"), + """{"jsonrpc":"2.0","id":"r","result":{}} x""", // trailing text + """{"jsonrpc":"2.0","id":"r","result":{}}{"jsonrpc":"2.0","id":"s","result":{}}""", // two on one line + "\u0000" + result("{}"), "\u000b" + result("{}"), "\u00a0" + result("{}"), + "\ufeff" + result("{}"), // a byte-order mark is not whitespace + ).forEach { rejects(it) } + } + + @Test fun legalGrammarIsAccepted() { + val frame = result("""{"neg":-0,"exp":1E+2,"frac":0.5,"zero":0,"empty":[],"esc":"\/\b\f\n\r\t\"\\","u":"\u00e9\ud83d\ude00"}""") + val value = (decode(frame).single() as WireMessage.Result).value as JsonObject + assertEquals("é😀", (value["u"] as JsonPrimitive).content) + assertEquals("/\b\u000c\n\r\t\"\\", (value["esc"] as JsonPrimitive).content) + } + + @Test fun integersKeepSixtyFourBitsAndOtherNumbersAreNotIntegers() { + fun seq(text: String) = (decode(eventParams("""{"type":"n","seq":$text}""")).single() as WireMessage.Event).sequence + assertEquals(Long.MAX_VALUE, seq("9223372036854775807")) + assertEquals(Long.MIN_VALUE, seq("-9223372036854775808")) + assertEquals(0L, seq("-0")) + listOf("1.0", "1e2", "1E0", "9223372036854775808", "-9223372036854775809", "\"1\"", "null", "true", "[]") + .forEach { rejects(eventParams("""{"type":"n","seq":$it}""")) } + // A result value is any JSON value; an integer too large for 64 bits is a finite number, not an error. + assertEquals("result:r", decode(result("9223372036854775808")).single().classification) + } + + @Test fun malformedUtf8RejectsTheWholeMessageEvenInBlankOrIgnoredPlaces() { + val prefix = """{"jsonrpc":"2.0","id":"r","result":"""".toByteArray() + val suffix = "\"}".toByteArray() + listOf( + byteArrayOf(0xff.toByte()), // never valid + byteArrayOf(0xc0.toByte(), 0x80.toByte()), // overlong NUL + byteArrayOf(0xe0.toByte(), 0x80.toByte(), 0xaf.toByte()), // overlong slash + byteArrayOf(0xed.toByte(), 0xa0.toByte(), 0x80.toByte()), // UTF-8 encoded surrogate + byteArrayOf(0xf4.toByte(), 0x90.toByte(), 0x80.toByte(), 0x80.toByte()), // above U+10FFFF + byteArrayOf(0xe2.toByte(), 0x82.toByte()), // truncated euro sign + byteArrayOf(0x80.toByte()), // stray continuation byte + ).forEach { rejects(prefix + it + suffix) } + // A multibyte sequence cut by a newline is malformed too; it cannot borrow the next line's bytes. + rejects(prefix + byteArrayOf(0xe2.toByte(), 0x0a) + suffix) + } + + @Test fun escapedUnpairedSurrogatesCannotBecomeIds() { + listOf("\\ud800", "\\udc00", "\\ud800x", "\\ud800\\u0041", "\\udc00\\ud800", "\\ud83d") + .forEach { rejects("""{"jsonrpc":"2.0","id":"$it","result":null}""") } + val pair = decode("""{"jsonrpc":"2.0","id":"\ud83d\ude00","result":null}""").single() as WireMessage.Result + assertEquals("😀", pair.id) + // Keys obey the same rule. + rejects(result("""{"\ud800":1}""")) + } + + @Test fun envelopeFieldsHaveExactTypes() { + listOf( + """{"jsonrpc":2.0,"id":"r","result":{}}""", + """{"jsonrpc":null,"id":"r","result":{}}""", + """{"jsonrpc":"2.0","id":"r","method":null,"params":{}}""", + """{"jsonrpc":"2.0","id":"r","method":"approval","params":"x"}""", + """{"jsonrpc":"2.0","id":"r","method":"approval","params":1}""", + """{"jsonrpc":"2.0","id":"r","method":"approval","params":{},"error":null}""", + """{"jsonrpc":"2.0","id":"r","error":null}""", + """{"jsonrpc":"2.0","id":"r","error":[]}""", + """{"jsonrpc":"2.0","id":"r","error":{}}""", + """{"jsonrpc":"2.0","id":"r","error":{"code":1.5}}""", + """{"jsonrpc":"2.0","id":"r","error":{"code":null}}""", + """{"jsonrpc":"2.0","id":"r","error":{"code":1},"result":null}""", + """{"jsonrpc":"2.0","id":"r","result":{},"params":null}""", + eventParams("""{"type":"n","payload":"x"}"""), + eventParams("""{"type":"n","session_id":false}"""), + eventParams("""{"type":7}"""), + eventParams("null"), eventParams("[]"), eventParams("\"x\""), + """{"jsonrpc":"2.0","method":"event"}""", + """{"jsonrpc":"2.0","method":"event","id":null,"params":{"type":"n"}}""", + """{"jsonrpc":"2.0","method":"event","params":{"type":"n"},"result":null}""", + ).forEach { rejects(it) } + } + + @Test fun eventsKeepTheirCoordinatesPayloadDefaultsAndFutureMetadata() { + val event = decode(eventParams("""{"type":"future","session_id":"runtime-é","seq":-3,"extra":{"k":[1]}}""")).single() + as WireMessage.Event + assertEquals("runtime-é", event.sessionID) + assertEquals(-3L, event.sequence) + assertTrue(event.payload.isEmpty()) + assertTrue("extra" in event.parameters && "type" in event.parameters) + + val noCoordinates = decode(eventParams("""{"type":"n","session_id":null,"payload":{"k":1}}""")).single() + as WireMessage.Event + assertNull(noCoordinates.sessionID) + assertNull(noCoordinates.sequence) + assertEquals(setOf("k"), noCoordinates.payload.keys) + } + + @Test fun serverRequestsDefaultParamsAndAcceptUnknownMethods() { + val absent = decode("""{"jsonrpc":"2.0","id":"s","method":"future.method"}""").single() as WireMessage.Request + val nullParams = decode("""{"jsonrpc":"2.0","id":"s","method":"secret","params":null}""").single() as WireMessage.Request + assertTrue(absent.params.isEmpty() && nullParams.params.isEmpty()) + assertEquals("request:future.method", absent.classification) + } + + @Test fun failuresKeepCodeMachineReasonAndASafeMessageSeparately() { + fun failure(error: String) = decode("""{"jsonrpc":"2.0","id":"r","error":$error}""").single() as WireMessage.Failure + + val busy = failure("""{"code":4090,"message":"Busy","data":{"reason":"MAX_CONCURRENT_SESSIONS"}}""") + assertEquals(4090L, busy.code) + assertEquals("MAX_CONCURRENT_SESSIONS", busy.reason) + assertEquals("Busy", busy.message) + + val bare = failure("""{"code":-32601}""") + assertNull(bare.reason) + assertNull(bare.message) + // Anything that is not a string reason is no reason; code 4090 alone is not the session limit. + assertNull(failure("""{"code":4090,"data":{"reason":7}}""").reason) + assertNull(failure("""{"code":4090,"data":"MAX_CONCURRENT_SESSIONS"}""").reason) + assertEquals(Long.MIN_VALUE, failure("""{"code":-9223372036854775808}""").code) + + // Hermes' words become one plain line: breaks, control and bidi characters turn into spaces. + assertEquals("one two three four", failure("""{"code":1,"message":"one\ntwo\u202ethree four"}""").message) + assertNull(failure("""{"code":1,"message":" \n\t\u200b "}""").message) + val long = failure("""{"code":1,"message":"${"x".repeat(400)}"}""").message!! + assertEquals(280, long.codePointCount(0, long.length)) + assertTrue(long.endsWith("…")) + val emoji = failure("""{"code":1,"message":"${"😀".repeat(400)}"}""").message!! + assertEquals(280, emoji.codePointCount(0, emoji.length)) + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireTest.kt new file mode 100644 index 00000000..b1f5b708 --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/HermesWireTest.kt @@ -0,0 +1,58 @@ +package app.bighelp.hermes + +import java.io.File +import kotlinx.serialization.json.* +import org.junit.Assert.* +import org.junit.Test + +class HermesWireTest { + @Test fun sharedContractVectors() { + val vectors = Json.parseToJsonElement(File(System.getProperty("hermes.wireVectors")).readText()).jsonObject + val cases = vectors.getValue("cases").jsonArray + assertEquals(55, cases.size) + cases.forEach { element -> + val case = element.jsonObject + val name = case.getValue("id").jsonPrimitive.content + val expected = case.getValue("expected").jsonArray.map { it.jsonPrimitive.content } + try { + val actual = HermesWire.decode(case.getValue("frame").jsonPrimitive.content.toByteArray()) + assertEquals(name, expected, actual.map { it.classification }) + } catch (error: WireException) { + // The vectors spell a rejection "reject: "; tests elsewhere use the bare category. + assertEquals(name, expected, listOf("reject:${error.category}")) + } + } + } + + @Test fun generatedLimitsUseUtf8BytesAndWholeEnvelopeDepth() { + fun result(id: String) = """{"jsonrpc":"2.0","id":"$id","result":null}""" + assertEquals(1, HermesWire.decode(result("é".repeat(512)).toByteArray()).size) + rejects("invalidResponse", result("é".repeat(512) + "a")) + val one = result("r") + assertEquals(4096, HermesWire.decode(List(4096) { one }.joinToString("\n").toByteArray()).size) + rejects("messageTooLarge", List(4097) { one }.joinToString("\n")) + val base = """{"jsonrpc":"2.0","id":"r","result":""" + assertEquals(1, HermesWire.decode((base + "[".repeat(63) + "0" + "]".repeat(63) + "}").toByteArray()).size) + rejects("messageTooLarge", base + "[".repeat(64) + "0" + "]".repeat(64) + "}") + // Pad a small valid frame instead, to isolate the entire-message byte ceiling. + val exact = one + " ".repeat(4_194_304 - one.toByteArray().size) + assertEquals(1, HermesWire.decode(exact.toByteArray()).size) + rejects("messageTooLarge", exact + " ") + } + + @Test fun preservesOpaqueIdsAndMachineRefusalReason() { + val request = HermesWire.decode("""{"jsonrpc":"2.0","id":" é ","method":"approval","params":{}}""".toByteArray()).single() as WireMessage.Request + assertEquals(" é ", request.id) + val refusal = HermesWire.decode("""{"jsonrpc":"2.0","id":"r","error":{"code":4090,"message":"Busy","data":{"reason":"SESSION_NOT_OWNED"}}}""".toByteArray()).single() as WireMessage.Failure + assertEquals("SESSION_NOT_OWNED", refusal.reason) + } + + private fun rejects(category: String, frame: String) { + try { + HermesWire.decode(frame.toByteArray()) + fail("Expected $category") + } catch (error: WireException) { + assertEquals(category, error.category) + } + } +} diff --git a/android/hermes/src/test/kotlin/app/bighelp/hermes/StrictJsonTest.kt b/android/hermes/src/test/kotlin/app/bighelp/hermes/StrictJsonTest.kt new file mode 100644 index 00000000..83b9292e --- /dev/null +++ b/android/hermes/src/test/kotlin/app/bighelp/hermes/StrictJsonTest.kt @@ -0,0 +1,30 @@ +package app.bighelp.hermes + +import org.junit.Assert.assertEquals +import org.junit.Assert.fail +import org.junit.Test + +/** The parser on its own, for the cases the byte-level decoder's earlier checks make unreachable. */ +class StrictJsonTest { + private fun rejects(text: String) { + try { + StrictJson.parse(text) + fail("Expected '$text' to be malformed") + } catch (_: StrictJson.Malformed) { + } + } + + @Test fun unpairedSurrogateCharactersAreMalformedEvenWhenNotEscaped() { + rejects("\"\ud800\"") + rejects("\"\udc00\"") + rejects("\"\ud800a\"") + rejects("\"\udc00\ud800\"") + assertEquals("\"😀\"", StrictJson.parse("\"😀\"").toString()) + } + + @Test fun parserEnforcesItsOwnDepthCeiling() { + StrictJson.parse("[".repeat(64) + "]".repeat(64)) + rejects("[".repeat(65) + "]".repeat(65)) + rejects("{\"a\":".repeat(65) + "0" + "}".repeat(65)) + } +} diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 00000000..54521a73 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,17 @@ +pluginManagement { + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} +dependencyResolutionManagement { + repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) + repositories { + google() + mavenCentral() + } +} +rootProject.name = "bighelp-android" +include(":hermes") +include(":app") diff --git a/docs/superpowers/plans/2026-10-27-android-foundation.md b/docs/superpowers/plans/2026-10-27-android-foundation.md new file mode 100644 index 00000000..6b9cd83c --- /dev/null +++ b/docs/superpowers/plans/2026-10-27-android-foundation.md @@ -0,0 +1,64 @@ +# Android Foundation Implementation Plan + +> **For agentic workers:** Use focused implementation tasks with independent review. Steps use checkbox syntax for tracking. + +**Goal:** Establish a buildable native Android app and a tested portable Hermes foundation. + +**Architecture:** A Kotlin/JVM `hermes` module owns the bounded protocol and connection policy. A Compose `app` module owns consent, secure platform persistence and UI. Demo fixtures exercise screens without a host. + +**Tech Stack:** Kotlin, Gradle, Jetpack Compose, OkHttp, kotlinx.serialization, coroutines, JUnit. + +**Spec:** `docs/superpowers/specs/2026-10-27-android-foundation-design.md` + +## Global Constraints + +- Minimum Android API is 26; compile and target API are 36. +- Use `app.bighelp.android` as the development application ID, with `.debug` on debug builds. +- No host request is sent before consent. +- No credentialed redirects or ambient cookies. +- A dispatched mutation without a receipt is uncertain, not failed, and is never automatically repeated. +- Personal information and real host data never enter this public repository. + +## Review Focus + +- A malformed trailing frame publishes no earlier message from the same WebSocket message. +- UTF-8 byte boundaries and deeply nested JSON fail before unbounded parsing. +- A deployment prefix remains part of endpoint identity and every route. +- Switching owner or closing a connection retires late responses. +- Demo responses remain labeled examples; unsupported live behavior is unavailable. + +### Task 1: Reproducible build and portable protocol + +**Files:** `android/settings.gradle.kts`, `android/build.gradle.kts`, `android/gradle/`, `android/hermes/`. + +**Interfaces:** `HermesEndpoint.parse(input, allowPrivateHttp)` produces a canonical endpoint with prefix preserving route construction. `HermesWire.decode(bytes)` returns an ordered list of typed frames or a typed rejection, atomically. + +- [ ] Add the Gradle wrapper, pinned build dependencies and JVM test harness. +- [ ] Write failing vector and endpoint tests; capture the failure. +- [ ] Implement the decoder and endpoint rules from `CONNECTION.md` and Swift source. +- [ ] Run all vectors and generated limit tests; independently review trust boundaries. + +### Task 2: App shell and explicitly scoped live connection + +**Files:** `android/app/`, `android/README.md`. + +**Interfaces:** App state owns consent and connection generation; screens observe state and invoke explicit actions. Demo and live repositories implement the same UI model without invented host success. + +- [ ] Add Compose app, manifest and local consent preferences with backup exclusions; introduce Keystore storage with authenticated sign-in in the next milestone. +- [ ] Add consent, connection setup, demo sessions/chat, agents and one Settings surface. +- [ ] Add consent-gated public host discovery through `HostDiscovery.check(endpoint, consentGranted): DiscoveryResult`; do not label discovery as a connection or collect credentials. +- [ ] Test consent, failed setup, draft preservation and demo control behavior. + +### Task 3: Verify, review and record evidence + +**Files:** `android/README.md`, Android CI workflow, issue/PR. + +- [ ] Run JVM tests, Android unit checks, lint and debug assemble. +- [ ] Inspect demo screens and use controls in light and dark on a dedicated emulator, when available. +- [ ] Review the full diff, fix concrete findings and repeat affected verification. +- [ ] Document remaining acceptance gaps, commit changes and open a draft PR linked to its issue. + +### Parallel account preparation + +- [ ] Use Terra/max for browser work to prepare personal Play Console registration. +- [ ] Leave identity, verification and any required direct checkout with the maintainer; report the exact remaining steps. diff --git a/docs/superpowers/specs/2026-10-27-android-foundation-design.md b/docs/superpowers/specs/2026-10-27-android-foundation-design.md new file mode 100644 index 00000000..d4589b73 --- /dev/null +++ b/docs/superpowers/specs/2026-10-27-android-foundation-design.md @@ -0,0 +1,21 @@ +# Android foundation + +The Android app lives in `android/` in this repository, written in Kotlin with Jetpack Compose. It talks directly to the selected Hermes dashboard, using `docs/NATIVE_TRANSPORT.md` and its chapters as the integration contract. The Apple targets and notification services remain independently buildable. + +## First milestone + +Build a reproducible Android debug APK and a pure JVM Hermes module. The module owns endpoint validation, bounded atomic wire decoding, explicit connection ownership, readiness and capability gates. Its tests consume the repository's shared wire vectors directly. The app provides the AI data agreement, connection setup, a sessions list, agents, short Settings and an explicitly labeled demo mode. Live operations are offered only as their implementation and acceptance tests become available. Unsupported sign-in methods and uncertain outcomes stay visible and never trigger fallback or mutation replay. + +Use `app.bighelp.android` as the development application ID, with `.debug` on debug builds. This reserves nothing on Google Play; confirm the release identity before the first upload. Minimum Android API is 26; compile and target API are 36. Credentials belong in Android Keystore protected storage, excluded from backups and logs. No host request is sent before consent. HTTPS uses ordinary certificate validation; private HTTP requires explicit opt-in and endpoint validation. No credentialed redirects or ambient cookies. + +The first app milestone checks only public `/api/status` discovery. It does not collect credentials, save a sign-in, open a gateway or send a live turn. A discovered host is labeled as found, never connected. Keystore persistence arrives with authenticated connection support; the first milestone persists only consent and nonsecret preview preferences. + +## Boundaries + +`android/hermes` is Kotlin/JVM and owns protocol policy without Android dependencies. `android/app` owns platform storage, lifecycle, screens and demo composition. The pure module exposes typed endpoint and frame models. Readiness, authenticated health and exclusive submission are separate facts. A dispatched mutation without a receipt is uncertain, not failed, and is never automatically repeated. Session runtime IDs and durable stored IDs remain separate. + +The initial foundation is not full Android parity. Browser PKCE, reconnect/replay, durable submit recovery, attachments, live voice, groups, phone tools, FCM, Code mode and store release each require their own acceptance evidence. There are no default agent jobs, cloud sign-up dependency or production service deployments. + +## Evidence + +Run all 55 shared wire vectors and generated byte/count/depth boundaries, endpoint trust tests and scripted readiness/ownership tests. Build the APK and exercise demo controls in light and dark on a dedicated Android emulator if the platform is available. Record JVM, scripted HTTP/WebSocket, emulator, disposable Hermes host and physical-device evidence separately. Account registration may require the maintainer's direct sign-in, identity verification and payment; private information never enters this public repository. From c0c285c51be7cb019b50cccc5781bbb4915b268f Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:05:50 -0500 Subject: [PATCH 02/18] Keep Android history clear and clarify setup feedback --- android/README.md | 4 +- .../app/bighelp/android/BighelpAppModel.kt | 5 +- .../kotlin/app/bighelp/android/ChatScreen.kt | 39 +++++----- .../app/bighelp/android/SessionsScreen.kt | 9 ++- .../app/bighelp/android/SettingsScreen.kt | 2 +- .../kotlin/app/bighelp/android/SetupScreen.kt | 25 +++++-- .../app/bighelp/android/AppModelTest.kt | 16 +++++ .../app/bighelp/android/HostDiscoveryTest.kt | 71 ++++++++++++++++++- .../plans/2026-10-27-android-foundation.md | 32 ++++----- 9 files changed, 157 insertions(+), 46 deletions(-) diff --git a/android/README.md b/android/README.md index e5abaf5b..2b7a1151 100644 --- a/android/README.md +++ b/android/README.md @@ -35,7 +35,7 @@ The foundation is not an Android feature-parity or release-readiness claim. Reco - **Try the demo** opens sample chats, agents and Settings. Everything is invented and stays on the phone; every demo screen says so, and every reply is the same fixed, labeled example. It needs no agreement because nothing is sent. Controls that work: New chat, Send, search, agent choice, Light/Dark/Same as phone, drafts kept while you look elsewhere, Latest button and Android Back. - **Connect your computer** asks for the one-time AI data agreement first (stored as `bighelp.privacy.ai-data-agreed` in app-private preferences, excluded from backup and device transfer), then checks one typed address with `GET /api/status`. A host that answers is reported as *found*, never *connected*. It collects no token or password, stores no address or sign-in, opens no gateway and sends no chat. -- Discovery sends no cookies, tokens or custom headers, follows no redirect, reads at most 16,384 decoded bytes, and keeps no response text. HTTPS uses the platform's certificate checks. +- Discovery sends no cookies, tokens or custom headers, follows no redirect, reads at most 16,384 decoded bytes, and keeps no response text. HTTPS uses the platform's certificate checks, and `network_security_config.xml` trusts only the phone's built-in (system) certificate authorities. A certificate signed by a private authority that you installed on the phone is not trusted, so a host that uses one looks like "No Hermes computer answered". Use a certificate from a public authority, or plain HTTP on a private network. This preview offers no way to trust a private authority. ### Plain HTTP on a private network @@ -43,7 +43,7 @@ The foundation is not an Android feature-parity or release-readiness claim. Reco ### Tests in this milestone -`app/src/test` holds JVM tests only: `AppModelTest` (consent gating, address refusal, one check at a time, stale and cancelled results, demo send, drafts, search, Back), `HostStatusTest` (strict status shape and bounds) and `HostDiscoveryTest` (real requests to a local scripted server: no credentials, no redirect, malformed and oversized bodies). Emulator verification is recorded separately; there are no automated UI tests yet. Demo drafts and chats survive navigation and rotation, but reset after process death or leaving the demo. UI localization is not implemented yet. +`app/src/test` holds JVM tests only: `AppModelTest` (consent gating, address refusal, one check at a time, stale and cancelled results, demo send, drafts, search, Back), `HostStatusTest` (strict status shape and bounds) and `HostDiscoveryTest` (real requests to a local scripted server: the GET and its headers, no credentials, no redirect, only HTTP 200, malformed bodies, the 16,384-byte limit with and without a declared length, and a cancelled check cancelling the real call). Emulator verification is recorded separately; there are no automated UI tests yet. Demo drafts and chats survive navigation and rotation, but reset after process death or leaving the demo. UI localization is not implemented yet. Before a working live-chat milestone, implement and test authenticated ordered WebSocket readiness, prompt handlers, the exclusive-submit gate, distinct runtime/stored IDs, a durable uncertainty journal, streaming/history reconciliation and reconnect/replay. Do not expose live Send before those acceptance cases pass. Follow [PORTING.md](../docs/hermes/PORTING.md) in order. diff --git a/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt b/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt index 03899b28..22874076 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/BighelpAppModel.kt @@ -216,7 +216,10 @@ class BighelpAppModel( private fun titleFrom(message: String): String { val line = message.lineSequence().first().trim() - return if (line.length <= MAXIMUM_TITLE) line else line.take(MAXIMUM_TITLE).trimEnd() + "…" + if (line.length <= MAXIMUM_TITLE) return line + // Step back one unit when the cut would leave half of an emoji (a surrogate pair) behind. + val cut = if (line[MAXIMUM_TITLE - 1].isHighSurrogate()) MAXIMUM_TITLE - 1 else MAXIMUM_TITLE + return line.take(cut).trimEnd() + "…" } // -- settings ----------------------------------------------------------------------------- diff --git a/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt index d3e8d541..491b2888 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/ChatScreen.kt @@ -57,7 +57,8 @@ import kotlinx.coroutines.launch /** * A demo chat. The reader owns the scroll position: nothing moves it while they read history, Send always - * brings the newest message into view, and a Latest button appears whenever they are away from the end. + * brings the newest message into view, and a Latest button appears, in its own row above the message box, + * whenever they are away from the end. * Rows are keyed by message ID, so a row's identity survives every change to the list. */ @Composable @@ -101,34 +102,40 @@ fun ChatScreen( } } // Keep the end in view when the keyboard opens or closes, but only for a reader who is at the end. + // Never while a scroll runs: a drag or fling is the reader's, and a programmatic scroll would fight it. LaunchedEffect(listState) { snapshotFlow { listState.layoutInfo.viewportSize.height }.collect { - if (followTail && lastIndex >= 0) listState.scrollToLatest(lastIndex, animated = false) + if (followTail && !listState.isScrollInProgress && lastIndex >= 0) { + listState.scrollToLatest(lastIndex, animated = false) + } } } - val awayFromLatest by remember { derivedStateOf { listState.canScrollForward } } + // The Latest row takes its own height out of the transcript, so it must never be what moves the reader. + // It appears only once a finished scroll has left the end (followTail is already false then, so the + // viewport follow above skips the shrink) and goes away when the reader is back at the end. + val showLatest by remember { derivedStateOf { !followTail && listState.canScrollForward } } Column(Modifier.fillMaxSize().safeDrawingPadding().testTag("screen.chat")) { ChatHeader(session.title, agent, onBack) - Box(Modifier.weight(1f).fillMaxWidth()) { - LazyColumn( - state = listState, - contentPadding = PaddingValues(horizontal = 12.dp, vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier.fillMaxSize().testTag("chat.messages"), - ) { - if (messages.isEmpty()) { - item(key = "empty") { EmptyChatNote(agent) } - } - items(messages, key = { it.id }) { message -> MessageRow(message) } + LazyColumn( + state = listState, + contentPadding = PaddingValues(horizontal = 12.dp, vertical = 12.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + modifier = Modifier.weight(1f).fillMaxWidth().testTag("chat.messages"), + ) { + if (messages.isEmpty()) { + item(key = "empty") { EmptyChatNote(agent) } } - if (awayFromLatest) { + items(messages, key = { it.id }) { message -> MessageRow(message) } + } + if (showLatest) { + // Its own row between the transcript and the message box, so the button covers no message. + Box(Modifier.fillMaxWidth().padding(vertical = 4.dp), contentAlignment = Alignment.Center) { JumpToLatest( onClick = { followTail = true scope.launch { listState.scrollToLatest(lastIndex, animated = ValueAnimator.areAnimatorsEnabled()) } }, - modifier = Modifier.align(Alignment.BottomCenter).padding(bottom = 12.dp), ) } } diff --git a/android/app/src/main/kotlin/app/bighelp/android/SessionsScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/SessionsScreen.kt index 3c033d4f..67cce8d2 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/SessionsScreen.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/SessionsScreen.kt @@ -112,16 +112,19 @@ private fun SessionRow(session: DemoSession, agent: DemoAgent, draft: String?, o overflow = TextOverflow.Ellipsis, ) Text(agent.name, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) + // A box holding only spaces or new lines is not a draft worth previewing. + val draftText = draft?.trim().orEmpty() + val hasDraft = draftText.isNotEmpty() val preview = when { - draft != null -> "Draft: ${draft.trim().replace('\n', ' ')}" + hasDraft -> "Draft: ${draftText.replace('\n', ' ')}" session.messages.isEmpty() -> "No messages yet" else -> session.messages.last().text.replace('\n', ' ') } Text( preview, style = MaterialTheme.typography.bodyMedium, - color = if (draft != null) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, - fontWeight = if (draft != null) FontWeight.Medium else FontWeight.Normal, + color = if (hasDraft) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, + fontWeight = if (hasDraft) FontWeight.Medium else FontWeight.Normal, maxLines = 1, overflow = TextOverflow.Ellipsis, ) diff --git a/android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt index 8c75cbc9..840b0bf1 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/SettingsScreen.kt @@ -73,7 +73,7 @@ fun SettingsScreen( SectionLabel("Your data and AI") Text( if (consentGranted) "You agreed to share chat data with your computer and its AI providers." - else "Not asked yet. bighelp asks before it connects to a computer.", + else "Not agreed yet. bighelp asks before it connects to a computer.", style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(horizontal = 4.dp, vertical = 4.dp).testTag("settings.consent-status"), diff --git a/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt b/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt index 8cf1493c..7afb2fee 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/SetupScreen.kt @@ -28,7 +28,10 @@ import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.testTag import androidx.compose.ui.graphics.Color +import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.liveRegion +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardCapitalization @@ -93,7 +96,7 @@ fun SetupScreen( InkButton("Check computer", onCheck, tag = "setup.check", enabled = setup.address.isNotBlank()) } - DiscoveryResultCard(setup.discovery, onCheck = onCheck, onTryDemo = onTryDemo) + DiscoveryResultCard(setup.discovery, setup.allowPrivateHttp, onCheck = onCheck, onTryDemo = onTryDemo) Spacer(Modifier.height(8.dp)) } } @@ -139,16 +142,27 @@ private fun PrivateHttpRow(checked: Boolean, enabled: Boolean, onChange: (Boolea } @Composable -private fun DiscoveryResultCard(discovery: DiscoveryState, onCheck: () -> Unit, onTryDemo: () -> Unit) { +private fun DiscoveryResultCard( + discovery: DiscoveryState, + allowPrivateHttp: Boolean, + onCheck: () -> Unit, + onTryDemo: () -> Unit, +) { when (discovery) { DiscoveryState.Idle, DiscoveryState.Checking -> Unit is DiscoveryState.AddressProblem -> ResultCard( title = "That address can't be used", body = when (discovery.reason) { + // With the switch already on, the address itself is the problem, so don't send them to the switch. HermesEndpointException.Reason.PlaintextNotAllowed -> - "Plain http:// works only inside your own network. Turn on the private network " + - "switch for an address like 192.168.1.20, or use https://." + if (allowPrivateHttp) { + "Plain http:// works only for an address inside your own network, like " + + "192.168.1.20, and this one is not. Use https:// instead." + } else { + "Plain http:// works only inside your own network. Turn on the private network " + + "switch for an address like 192.168.1.20, or use https://." + } HermesEndpointException.Reason.InvalidEndpoint, HermesEndpointException.Reason.InvalidRoute -> "Use a name or number like hermes.example.com or 192.168.1.20:9119, with no spaces, " + "username, password or question mark." @@ -194,7 +208,8 @@ private fun ResultCard( Surface( color = MaterialTheme.colorScheme.surfaceContainerHigh, shape = RoundedCornerShape(16.dp), - modifier = Modifier.fillMaxWidth().testTag(tag), + // The card appears or changes after a check; polite means a screen reader announces it without interrupting. + modifier = Modifier.fillMaxWidth().semantics { liveRegion = LiveRegionMode.Polite }.testTag(tag), ) { Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { Text(title, style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Bold) diff --git a/android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt b/android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt index 93ac7e16..d1f2855e 100644 --- a/android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt +++ b/android/app/src/test/kotlin/app/bighelp/android/AppModelTest.kt @@ -264,6 +264,22 @@ class AppModelTest { assertEquals(4, model.demo().session(id)!!.messages.map { it.id }.toSet().size) } + @Test fun aLongFirstMessageTitleNeverCutsAnEmojiInHalf() = runTest { + val model = model() + model.tryDemo() + model.startNewChat() + val id = (model.state.value.route as Route.Chat).sessionId + + // The 40-character title limit falls between the two halves of the emoji (a surrogate pair). + val message = "a".repeat(39) + "😀 and some more words" + model.setDraft(id, message) + assertTrue(model.send(id)) + + val session = model.demo().session(id)!! + assertEquals("a".repeat(39) + "…", session.title) + assertEquals(message, session.messages[0].text) + } + @Test fun aBlankDraftDoesNotSend() = runTest { val model = model() model.tryDemo() diff --git a/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt b/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt index d6afb80b..d75b7059 100644 --- a/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt +++ b/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt @@ -1,9 +1,19 @@ package app.bighelp.android import app.bighelp.hermes.HermesEndpoint +import java.util.concurrent.TimeUnit +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.launch +import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest +import kotlinx.coroutines.withTimeout +import okhttp3.Call +import okhttp3.EventListener +import okhttp3.OkHttpClient import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer +import okhttp3.mockwebserver.SocketPolicy import org.junit.After import org.junit.Assert.* import org.junit.Before @@ -27,7 +37,10 @@ class HostDiscoveryTest { val result = HostDiscovery().check(endpoint(), consentGranted = true) assertEquals(DiscoveryResult.Available(authRequired = true, browserSignIn = true), result) val request = host.takeRequest() + assertEquals("GET", request.method) assertEquals("/hermes/api/status", request.path) + assertEquals("application/json", request.getHeader("Accept")) + assertEquals("no-store", request.getHeader("Cache-Control")) assertNull(request.getHeader("Authorization")) assertNull(request.getHeader("Cookie")) assertNull(request.getHeader("X-Hermes-Session-Token")) @@ -40,11 +53,18 @@ class HostDiscoveryTest { assertEquals(1, host.requestCount) } - @Test fun malformedOversizedOrNonJsonResponsesStayUnavailable() = runTest { + @Test fun onlyAnHttp200CountsEvenWhenTheBodyIsAValidStatus() = runTest { + listOf(201, 404, 500).forEach { code -> + host.enqueue(json("""{"auth_required":false}""").setResponseCode(code)) + assertEquals("HTTP $code", DiscoveryResult.Unavailable, HostDiscovery().check(endpoint(), true)) + } + assertEquals(3, host.requestCount) + } + + @Test fun malformedOrNonJsonResponsesStayUnavailable() = runTest { listOf( json("""{"auth_required":"false"}"""), json("""{"auth_required":false,"auth_flows":["native_pkce","native_pkce"]}"""), - json("""{"auth_required":false,"auth_flows":null}""" + "x".repeat(16_384)), MockResponse().setHeader("Content-Type", "text/html").setBody("Private proxy diagnostic"), ).forEach { response -> host.enqueue(response) @@ -52,6 +72,28 @@ class HostDiscoveryTest { } } + // The budget is 16,384 decoded bytes. Each body below is valid JSON padded with spaces, so size is the + // only thing that can make the answer differ. + + @Test fun aStatusExactlyAtTheSizeBudgetIsAccepted() = runTest { + host.enqueue(json(statusPaddedTo(HostStatus.MAXIMUM_BYTES))) + assertEquals(DiscoveryResult.Available(false, false), HostDiscovery().check(endpoint(), true)) + } + + @Test fun aStatusOneByteOverTheSizeBudgetIsRefused() = runTest { + host.enqueue(json(statusPaddedTo(HostStatus.MAXIMUM_BYTES + 1))) + assertEquals(DiscoveryResult.Unavailable, HostDiscovery().check(endpoint(), true)) + } + + @Test fun theSizeBudgetAlsoHoldsWhenTheLengthIsNotDeclared() = runTest { + // A chunked body has no Content-Length, so only reading the stream can tell it is too large. + host.enqueue(chunkedJson(statusPaddedTo(HostStatus.MAXIMUM_BYTES))) + assertEquals(DiscoveryResult.Available(false, false), HostDiscovery().check(endpoint(), true)) + + host.enqueue(chunkedJson(statusPaddedTo(HostStatus.MAXIMUM_BYTES + 1))) + assertEquals(DiscoveryResult.Unavailable, HostDiscovery().check(endpoint(), true)) + } + @Test fun discoveryIsNotAnAuthenticatedConnection() = runTest { host.enqueue(json("""{"auth_required":false,"auth_flows":null}""")) assertEquals(DiscoveryResult.Available(false, false), HostDiscovery().check(endpoint(), true)) @@ -59,5 +101,30 @@ class HostDiscoveryTest { assertEquals("/hermes/api/status", host.takeRequest().path) } + /** Real time and a real socket: the server reads the request and never answers, then the caller cancels. */ + @Test fun cancellingTheCheckCancelsTheRealCall() = runBlocking { + host.enqueue(MockResponse().setSocketPolicy(SocketPolicy.NO_RESPONSE)) + val cancelled = CompletableDeferred () + val client = OkHttpClient.Builder() + .eventListener(object : EventListener() { + override fun canceled(call: Call) { cancelled.complete(Unit) } + }) + .build() + + val check = launch(Dispatchers.Default) { HostDiscovery(client).check(endpoint(), true) } + assertNotNull("the request never reached the server", host.takeRequest(5, TimeUnit.SECONDS)) + check.cancel() + withTimeout(5_000) { cancelled.await() } + check.join() + } + + private fun statusPaddedTo(bytes: Int): String { + val status = """{"auth_required":false}""" + return status + " ".repeat(bytes - status.length) + } + private fun json(body: String) = MockResponse().setHeader("Content-Type", "application/json").setBody(body) + + private fun chunkedJson(body: String) = + MockResponse().setHeader("Content-Type", "application/json").setChunkedBody(body, 1_000) } diff --git a/docs/superpowers/plans/2026-10-27-android-foundation.md b/docs/superpowers/plans/2026-10-27-android-foundation.md index 6b9cd83c..d2c3d5ee 100644 --- a/docs/superpowers/plans/2026-10-27-android-foundation.md +++ b/docs/superpowers/plans/2026-10-27-android-foundation.md @@ -4,7 +4,7 @@ **Goal:** Establish a buildable native Android app and a tested portable Hermes foundation. -**Architecture:** A Kotlin/JVM `hermes` module owns the bounded protocol and connection policy. A Compose `app` module owns consent, secure platform persistence and UI. Demo fixtures exercise screens without a host. +**Architecture:** A Kotlin/JVM `hermes` module owns the bounded protocol and connection policy. A Compose `app` module owns consent, local preferences and UI. Demo fixtures exercise screens without a host. **Tech Stack:** Kotlin, Gradle, Jetpack Compose, OkHttp, kotlinx.serialization, coroutines, JUnit. @@ -33,32 +33,32 @@ **Interfaces:** `HermesEndpoint.parse(input, allowPrivateHttp)` produces a canonical endpoint with prefix preserving route construction. `HermesWire.decode(bytes)` returns an ordered list of typed frames or a typed rejection, atomically. -- [ ] Add the Gradle wrapper, pinned build dependencies and JVM test harness. -- [ ] Write failing vector and endpoint tests; capture the failure. -- [ ] Implement the decoder and endpoint rules from `CONNECTION.md` and Swift source. -- [ ] Run all vectors and generated limit tests; independently review trust boundaries. +- [x] Add the Gradle wrapper, pinned build dependencies and JVM test harness. +- [x] Write failing vector and endpoint tests; capture the failure. +- [x] Implement the decoder and endpoint rules from `CONNECTION.md` and Swift source. +- [x] Run all vectors and generated limit tests; independently review trust boundaries. -### Task 2: App shell and explicitly scoped live connection +### Task 2: App shell and public host discovery **Files:** `android/app/`, `android/README.md`. -**Interfaces:** App state owns consent and connection generation; screens observe state and invoke explicit actions. Demo and live repositories implement the same UI model without invented host success. +**Interfaces:** App state owns consent and discovery generation; screens observe state and invoke explicit actions. `HostChecker` separates discovery from the state model. Demo chat has no live repository or invented host success. -- [ ] Add Compose app, manifest and local consent preferences with backup exclusions; introduce Keystore storage with authenticated sign-in in the next milestone. -- [ ] Add consent, connection setup, demo sessions/chat, agents and one Settings surface. -- [ ] Add consent-gated public host discovery through `HostDiscovery.check(endpoint, consentGranted): DiscoveryResult`; do not label discovery as a connection or collect credentials. -- [ ] Test consent, failed setup, draft preservation and demo control behavior. +- [x] Add Compose app, manifest and local consent preferences with backup exclusions; introduce Keystore storage with authenticated sign-in in the next milestone. +- [x] Add consent, connection setup, demo sessions/chat, agents and one Settings surface. +- [x] Add consent-gated public host discovery through `HostDiscovery.check(endpoint, consentGranted): DiscoveryResult`; do not label discovery as a connection or collect credentials. +- [x] Test consent, failed setup, draft preservation and demo control behavior. ### Task 3: Verify, review and record evidence **Files:** `android/README.md`, Android CI workflow, issue/PR. -- [ ] Run JVM tests, Android unit checks, lint and debug assemble. -- [ ] Inspect demo screens and use controls in light and dark on a dedicated emulator, when available. +- [x] Run JVM tests, Android unit checks, lint and debug assemble. +- [x] Inspect demo screens and use controls in light and dark on a dedicated emulator, when available. - [ ] Review the full diff, fix concrete findings and repeat affected verification. -- [ ] Document remaining acceptance gaps, commit changes and open a draft PR linked to its issue. +- [ ] Document remaining acceptance gaps, commit changes and open a pull request linked to its issue. ### Parallel account preparation -- [ ] Use Terra/max for browser work to prepare personal Play Console registration. -- [ ] Leave identity, verification and any required direct checkout with the maintainer; report the exact remaining steps. +- [x] Use Terra/max for browser work to prepare personal Play Console registration. +- [x] Leave identity, verification and any required direct checkout with the maintainer; report the exact remaining steps. From 03530e8b4f1baf73b8be27f133b030964d4601c9 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:26:39 -0500 Subject: [PATCH 03/18] Run Android CI within the repository action policy --- .github/workflows/android.yml | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index 4860e921..e2bda802 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -22,7 +22,7 @@ concurrency: jobs: build: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 defaults: run: working-directory: android @@ -32,8 +32,17 @@ jobs: with: distribution: temurin java-version: '17' - - uses: android-actions/setup-android@v3 - - uses: gradle/actions/setup-gradle@v4 + cache: gradle + cache-dependency-path: | + android/**/*.gradle.kts + android/gradle/wrapper/gradle-wrapper.properties + - name: Validate Gradle wrapper + run: echo '81a82aaea5abcc8ff68b3dfcb58b3c3c429378efd98e7433460610fecd7ae45f gradle/wrapper/gradle-wrapper.jar' | sha256sum --check --strict + # The pinned GitHub runner includes these SDK packages; use no unapproved setup actions. + - name: Verify Android SDK + run: | + test -d "$ANDROID_HOME/platforms/android-36" + test -d "$ANDROID_HOME/build-tools/35.0.0" - name: Test, lint and build run: ./gradlew :hermes:test :app:testDebugUnitTest :app:lintDebug :app:assembleDebug - uses: actions/upload-artifact@v4 From 591c44dba80477f135f9b3e191b93dd6edc26b0e Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:37:46 -0500 Subject: [PATCH 04/18] Avoid stale pooled sockets during Android host discovery --- .../app/bighelp/android/HostDiscovery.kt | 8 +- .../app/bighelp/android/HostDiscoveryTest.kt | 76 +++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) diff --git a/android/app/src/main/kotlin/app/bighelp/android/HostDiscovery.kt b/android/app/src/main/kotlin/app/bighelp/android/HostDiscovery.kt index da70b8e0..4e4e5a80 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/HostDiscovery.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/HostDiscovery.kt @@ -37,7 +37,9 @@ fun interface HostChecker { * the first milestone, and it takes no credential of any kind. * * The request carries no cookies, tokens or custom headers and follows no redirects (not even to the same - * origin), so a proxy or sign-in page can never turn into a "found" host. The decoded body is capped at + * origin), so a proxy or sign-in page can never turn into a "found" host. It asks the host to close the + * connection afterwards (`Connection: close`), so each check opens its own socket and none is reused; the + * client's no-retry policy stays as it is and is never loosened for other requests. The decoded body is capped at * [HostStatus.MAXIMUM_BYTES] and is never kept or logged, whatever it holds. Certificates are checked by * the platform; HTTPS is the default and plain HTTP exists only on an endpoint that already passed the * private-network opt-in in [HermesEndpoint.parse]. @@ -50,6 +52,10 @@ class HostDiscovery(private val client: OkHttpClient = defaultClient) : HostChec .url(endpoint.httpUrl("/api/status").toString()) .header("Accept", "application/json") .header("Cache-Control", "no-store") + // A check never rides an idle pooled socket. A host (or a proxy, or an HTTP/1.0 server) may + // have closed it, and for a GET OkHttp only learns that by failing to read the reply, which + // retryOnConnectionFailure(false) turns into "unavailable" with nothing reaching the host. + .header("Connection", "close") .build() } catch (_: IllegalArgumentException) { return DiscoveryResult.Unavailable diff --git a/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt b/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt index d75b7059..c4fdc18e 100644 --- a/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt +++ b/android/app/src/test/kotlin/app/bighelp/android/HostDiscoveryTest.kt @@ -1,7 +1,13 @@ package app.bighelp.android import app.bighelp.hermes.HermesEndpoint +import java.io.IOException +import java.net.InetAddress +import java.net.ServerSocket +import java.net.Socket import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import kotlin.concurrent.thread import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -41,6 +47,7 @@ class HostDiscoveryTest { assertEquals("/hermes/api/status", request.path) assertEquals("application/json", request.getHeader("Accept")) assertEquals("no-store", request.getHeader("Cache-Control")) + assertEquals("close", request.getHeader("Connection")) assertNull(request.getHeader("Authorization")) assertNull(request.getHeader("Cookie")) assertNull(request.getHeader("X-Hermes-Session-Token")) @@ -118,6 +125,75 @@ class HostDiscoveryTest { check.join() } + // A host may close a socket after replying: HTTP/1.0, a keep-alive timeout, a proxy. OkHttp's idle pool + // cannot see that until it reads, and a GET only gets that limited check, so a later check could pick the + // dead socket and fail with no request ever reaching the host. Each check must therefore find a host that + // keeps answering, and the host must receive one request per check. + + @Test fun repeatedChecksOfAHostThatClosesAfterEveryReplyAllFindIt() = runBlocking { + ClosingServer().use { server -> + val discovery = HostDiscovery() + val results = List(4) { discovery.check(server.endpoint(), true) } + assertEquals(List(4) { DiscoveryResult.Available(false, false) }, results) + assertEquals(4, server.requests.get()) + } + } + + @Test fun repeatedChecksOfAKeepAliveHostThatThenClosesAllFindIt() = runTest { + repeat(4) { host.enqueue(json("""{"auth_required":false}""").setSocketPolicy(SocketPolicy.DISCONNECT_AT_END)) } + val discovery = HostDiscovery() + val results = List(4) { discovery.check(endpoint(), true) } + assertEquals(List(4) { DiscoveryResult.Available(false, false) }, results) + assertEquals(4, host.requestCount) + } + + @Test fun eachCheckOpensItsOwnConnectionEvenWhenTheHostKeepsOneOpen() = runTest { + repeat(3) { host.enqueue(json("""{"auth_required":false}""")) } + val discovery = HostDiscovery() + repeat(3) { assertEquals(DiscoveryResult.Available(false, false), discovery.check(endpoint(), true)) } + // sequenceNumber counts requests on one connection; 0 each time means no idle socket was reused. + assertEquals(listOf(0, 0, 0), List(3) { host.takeRequest().sequenceNumber }) + } + + /** Answers like Python's BaseHTTPRequestHandler: HTTP/1.0, Content-Length, then closes the socket. */ + private class ClosingServer : AutoCloseable { + private val listener = ServerSocket(0, 50, InetAddress.getLoopbackAddress()) + val requests = AtomicInteger() + + fun endpoint() = HermesEndpoint.parse("http://127.0.0.1:${listener.localPort}/hermes", allowPrivateHttp = true) + + init { + thread(isDaemon = true) { + try { + while (true) { + val socket = listener.accept() + thread(isDaemon = true) { serve(socket) } + } + } catch (_: IOException) { + } + } + } + + private fun serve(socket: Socket) = socket.use { + val input = socket.getInputStream() + var tail = 0 + while (tail != 0x0d0a0d0a) { + val next = input.read() + if (next < 0) return@use + tail = (tail shl 8) or next + } + requests.incrementAndGet() + val body = """{"auth_required":false}""".toByteArray() + socket.getOutputStream().apply { + write("HTTP/1.0 200 OK\r\nContent-Type: application/json\r\nContent-Length: ${body.size}\r\n\r\n".toByteArray()) + write(body) + flush() + } + } + + override fun close() = listener.close() + } + private fun statusPaddedTo(bytes: Int): String { val status = """{"auth_required":false}""" return status + " ".repeat(bytes - status.length) From 6f721ffbc351c1ace751d6eabc9388f151f1d660 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:49:17 -0500 Subject: [PATCH 05/18] Record Android preview verification and remaining milestones --- android/README.md | 12 ++++++++++-- .../plans/2026-10-27-android-foundation.md | 6 ++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/android/README.md b/android/README.md index 2b7a1151..6798e861 100644 --- a/android/README.md +++ b/android/README.md @@ -35,7 +35,7 @@ The foundation is not an Android feature-parity or release-readiness claim. Reco - **Try the demo** opens sample chats, agents and Settings. Everything is invented and stays on the phone; every demo screen says so, and every reply is the same fixed, labeled example. It needs no agreement because nothing is sent. Controls that work: New chat, Send, search, agent choice, Light/Dark/Same as phone, drafts kept while you look elsewhere, Latest button and Android Back. - **Connect your computer** asks for the one-time AI data agreement first (stored as `bighelp.privacy.ai-data-agreed` in app-private preferences, excluded from backup and device transfer), then checks one typed address with `GET /api/status`. A host that answers is reported as *found*, never *connected*. It collects no token or password, stores no address or sign-in, opens no gateway and sends no chat. -- Discovery sends no cookies, tokens or custom headers, follows no redirect, reads at most 16,384 decoded bytes, and keeps no response text. HTTPS uses the platform's certificate checks, and `network_security_config.xml` trusts only the phone's built-in (system) certificate authorities. A certificate signed by a private authority that you installed on the phone is not trusted, so a host that uses one looks like "No Hermes computer answered". Use a certificate from a public authority, or plain HTTP on a private network. This preview offers no way to trust a private authority. +- Discovery sends no cookies, tokens or custom headers, follows no redirect, reads at most 16,384 decoded bytes, and keeps no response text. Each status request sends `Connection: close` to avoid reusing a closed HTTP/1.x connection; automatic retries remain disabled. HTTPS uses the platform's certificate checks, and `network_security_config.xml` trusts only the phone's built-in (system) certificate authorities. A certificate signed by a private authority that you installed on the phone is not trusted, so a host that uses one looks like "No Hermes computer answered". Use a certificate from a public authority, or plain HTTP on a private network. This preview offers no way to trust a private authority. ### Plain HTTP on a private network @@ -43,7 +43,15 @@ The foundation is not an Android feature-parity or release-readiness claim. Reco ### Tests in this milestone -`app/src/test` holds JVM tests only: `AppModelTest` (consent gating, address refusal, one check at a time, stale and cancelled results, demo send, drafts, search, Back), `HostStatusTest` (strict status shape and bounds) and `HostDiscoveryTest` (real requests to a local scripted server: the GET and its headers, no credentials, no redirect, only HTTP 200, malformed bodies, the 16,384-byte limit with and without a declared length, and a cancelled check cancelling the real call). Emulator verification is recorded separately; there are no automated UI tests yet. Demo drafts and chats survive navigation and rotation, but reset after process death or leaving the demo. UI localization is not implemented yet. +`app/src/test` holds JVM tests only: `AppModelTest` (consent gating, address refusal, one check at a time, stale and cancelled results, demo send, drafts, search, Back), `HostStatusTest` (strict status shape and bounds) and `HostDiscoveryTest` (real requests to a local scripted server: the GET and its headers, no credentials, no redirect, only HTTP 200, malformed bodies, the 16,384-byte limit with and without a declared length, a cancelled check cancelling the real call, and repeated checks of closing and keep-alive HTTP/1.x hosts). Emulator verification is recorded separately; there are no automated UI tests yet. Demo drafts and chats survive navigation and rotation, but reset after process death or leaving the demo. UI localization is not implemented yet. + +### Verified preview snapshot: 2026-10-27 + +At source commit `591c44d`, all 57 core and 41 app JVM tests pass, debug assemble succeeds, and lint reports 0 errors and 9 dependency-version notices. [Android CI passed on that commit](https://github.com/promptclickrun/bighelp/actions/runs/40552550144). The core suite includes all 55 shared wire vectors; changing the shared vector file invalidates Gradle's test result. + +Manual checks on an Android 16 / API 36 emulator exercised demo controls, drafts, keyboard/Back, history/Latest, rotation, light/dark appearance, consent and setup. After the HTTP/1.x connection fix, the initial status check and eight consecutive Check again taps each showed Found with exactly one matching local-fixture receipt and response. A separate two-second delayed check passed. The installed APK's on-device SHA-256 matched the built file. + +These are demo and synthetic HTTP/1.0 fixture results. No real Hermes host, HTTPS/HTTP/2 discovery, physical device, lower API level or TalkBack behavior was verified. The rotation checks did not reproduce the suspected jump; they do not rule out a timing race. Before a working live-chat milestone, implement and test authenticated ordered WebSocket readiness, prompt handlers, the exclusive-submit gate, distinct runtime/stored IDs, a durable uncertainty journal, streaming/history reconciliation and reconnect/replay. Do not expose live Send before those acceptance cases pass. Follow [PORTING.md](../docs/hermes/PORTING.md) in order. diff --git a/docs/superpowers/plans/2026-10-27-android-foundation.md b/docs/superpowers/plans/2026-10-27-android-foundation.md index d2c3d5ee..03e343f4 100644 --- a/docs/superpowers/plans/2026-10-27-android-foundation.md +++ b/docs/superpowers/plans/2026-10-27-android-foundation.md @@ -55,8 +55,10 @@ - [x] Run JVM tests, Android unit checks, lint and debug assemble. - [x] Inspect demo screens and use controls in light and dark on a dedicated emulator, when available. -- [ ] Review the full diff, fix concrete findings and repeat affected verification. -- [ ] Document remaining acceptance gaps, commit changes and open a pull request linked to its issue. +- [x] Review the full diff, fix concrete findings and repeat affected verification. +- [x] Document remaining acceptance gaps, commit changes and open a pull request linked to its issue. + +Preview implementation: [PR #647](https://github.com/promptclickrun/bighelp/pull/647), closing [#644](https://github.com/promptclickrun/bighelp/issues/644). Executed verification and remaining acceptance gaps are recorded in [the Android README](../../../android/README.md#verified-preview-snapshot-2026-10-27). Authenticated live chat and Play release are subsequent milestones. ### Parallel account preparation From ac54ff898ed8e66b4442b6c325f9f1ee8fce3543 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:59:58 -0500 Subject: [PATCH 06/18] Plan the functioning Android app and parity acceptance --- .../plans/2026-10-27-android-parity.md | 95 +++++++++++++++++++ .../specs/2026-10-27-android-parity-design.md | 44 +++++++++ 2 files changed, 139 insertions(+) create mode 100644 docs/superpowers/plans/2026-10-27-android-parity.md create mode 100644 docs/superpowers/specs/2026-10-27-android-parity-design.md diff --git a/docs/superpowers/plans/2026-10-27-android-parity.md b/docs/superpowers/plans/2026-10-27-android-parity.md new file mode 100644 index 00000000..a18c0be3 --- /dev/null +++ b/docs/superpowers/plans/2026-10-27-android-parity.md @@ -0,0 +1,95 @@ +# Android End-to-End Parity Implementation Plan + +> **For agentic workers:** Use superpowers:subagent-driven-development. Continue all tasks; the user explicitly requires a functioning close-parity app, not a preview checkpoint. Steps use checkbox syntax for tracking. + +**Goal:** Deliver a functioning Android app with real Hermes conversations and the current app's everyday workflows. + +**Architecture:** Retain Kotlin/JVM protocol and domain clients in `android/hermes`; Android adapters and Compose live/demo presentation live in `android/app`. One authenticated authority owns each client, cache, journal and pending prompt. Platform integration follows verified domain behavior. + +**Tech Stack:** Existing pinned Kotlin, coroutines, kotlinx JSON, OkHttp, Compose, Android Keystore and protected atomic files. + +**Spec:** `docs/superpowers/specs/2026-10-27-android-parity-design.md`. + +## Global Constraints + +- Minimum API 26, compile/target 36. Existing pinned dependencies unless necessary. +- Real host data only on the live path; labeled synthetic demo remains separate. No fake progress or default AI spending. +- Consent precedes every host access; secure credentials never enter ordinary preferences, logs, public artifacts or backups. +- Validated canonical endpoints retain deployment prefixes; TLS stays enabled; private HTTP needs explicit opt-in. No ambient cookies, credentialed redirects or automatic mutation replay. +- Actual capabilities gate behavior, never release versions. Register handlers before server-request advertisement on every ready socket. +- Journal before mutation dispatch; original uncertain bytes stay reviewable and never automatically resend. Separate principal/owner/socket/profile/runtime/stored/epoch coordinates. +- Every async callback and persistence replacement checks its original owner. Protect reader-controlled chat scroll, drafts, input and history. +- Only isolated disposable Hermes clones/homes with synthetic data/models for live verification. No maintainer hosts, shared gateway restarts, production services, merges or releases. +- User-selected workers: Claude Sonnet 5.5 / Xhigh implementation and review; GPT-6.1 Terra / max device/browser. + +## Review Focus + +- A late reply/refresh/prompt from a retired host never publishes or rewrites a replacement sign-in. +- Socket upgrade without readiness and an absent/false exclusive-submit guarantee never admit a turn. +- Lost submit/create/refresh receipts follow their distinct reconciliation contracts, including process death. +- Streaming, paging, keyboard, background/reconnect and active-turn sends preserve reader/input ownership and never duplicate an answer. +- Missing plugin features, newer/older optional fields and per-agent context differences disable only the relevant operation without fabricating data. + +### Task 1: Real authentication, bounded HTTP and ordered gateway + +**Files:** New `android/hermes/src/{main,test}/kotlin/app/bighelp/hermes/` authentication/HTTP/gateway classes; `android/hermes/build.gradle.kts` dependencies. Existing endpoint/wire/policy files only where required; preserve all existing tests. + +**Interfaces:** Provide public JVM types for auth status/providers, saved credentials, sign-in input, a compare-and-replace credential store, bounded authenticated HTTP, and an ordered gateway interface. Publish exact signatures in the report for later tasks. Store authority is canonical endpoint plus exact principal. Android browser composition uses a supplied browser-launch callback and a real device-local loopback listener; no invented app-scheme callback. RPC consumers need connect/close, request/result/failure, ordered event and server-request streams, exact-owned server replies, generation and current capability/readiness state. + +- [ ] Write failing tests for bootstrap extraction, dashboard versus bearer headers, password/native browser PKCE query/cookie/state/code validation, token identity/expiry, single-flight rotating refresh with durable CAS and 401-only retirement, mode/principal changes, response bounds, no redirects/cookies/retries and cancellation. +- [ ] Write failing scripted WebSocket tests: no outbound before ready, 20-second ready deadline, fresh bearer ticket per connection, heartbeat, strict atomic ordered frames, RPC correlation, separate inbound/outbound ID namespaces, 64-entry prompt table, duplicates, wrong-method cancellation, late replies, unknown request `-32601`, close during mutation, false/malformed exclusive-submit and reconnect re-advertisement. +- [ ] Observe RED, implement actual contract in `docs/hermes/CONNECTION.md`, then run all Hermes JVM tests and document GREEN. No speculative retries; expose typed uncertain outcome after possible dispatch. +- [ ] Publish the exact API and focused evidence; independent scoped review before dependent code. + +### Task 2: Durable conversations, catalog, prompts and recovery + +**Files:** New JVM chat/catalog/history/journal models and tests in `android/hermes`; consume Task 1's published API. + +**Interfaces:** A screen-facing live workspace/chat repository exposes state flows for agents, sessions, transcript, real activity, prompts, connectivity, retained intents and drafts. Actions cover load/search/page/create/open, send/steer/queue/stop, answer/cancel prompts, rename/archive/restore/delete/fork, model/reasoning/slash controls and reconnect. A platform-neutral durable store supports atomic scoped cache/draft/journal transactions; persistence failure prevents dispatch. Publish exact API for Android composition. + +- [ ] Write failing cases for `source:bighelp`, persistent create key, distinct runtime/stored IDs, canonical Bot Chat merge, archived catalog and physical history pagination. +- [ ] Write failing reducer/admission cases for streaming before receipt, `streaming` admission versus `session.info running:false` terminal, tools and interims, active-turn steer, queued receipt, exact prompt ownership, unknown secure methods and cancellation. +- [ ] Write failing process-death/reconnect cases: journal before write, lost ACK never resend, create retry same key, canonical history/replay fallback, compaction successor, stale runtime/epoch, draft edits newer than sent intent, failed disk writes and explicit uncertainty review. +- [ ] Implement from `docs/hermes/CHAT.md` and current Swift domain code; run full JVM suite GREEN. Review focused diff; publish usable repository APIs, not just policy types. + +### Task 3: Everyday feature clients and capability discovery + +**Files:** JVM typed stock/plugin feature clients and tests under `android/hermes`; consume Task 1 HTTP/gateway and Task 2 identities. + +**Interfaces:** Typed models/actions for agents and instructions/avatar/model, workspace files and attachment transfer, Feed/Ideas/Goals and feedback, Projects/stock Git/Code, Kanban, scheduled tasks, Workflows/Dev Factory, Usage, Apps/connections, groups and supported voice control. Native extension context is per owner with feature gate, ETag and exact request-ID echo; optional absence is distinct from error. + +- [ ] Turn the inventory in `/tmp/bighelp-android-parity-inventory.md` into a durable parity matrix with actual call/decoder/acceptance references. Do not silently defer ordinary app features. +- [ ] Write failing request/response and ownership tests for every family used by the UI; cover native context normalization/correlation/conflict, missing feature, bounded payloads and unknown mutation readback. +- [ ] Implement documented everyday list/detail/write flows from `REFERENCE.md`, `EXTENSIONS.md`, `GROUPS_AND_DEVICE_TOOLS.md` and current Swift typed clients. Scope all file/agent/session/project/room IDs correctly. Readback validates mutations where contracted; no generic replay. +- [ ] Verify upload/download offsets/size/digest, edited-file conflict and stock Git project-worktree restrictions, groups durable event/idempotency/pending-action variants and voice allocation/result uncertainty. +- [ ] Full JVM GREEN, scoped review, published API and matrix dispositions. Missing host feature never becomes a fake success. + +### Task 4: Android secure persistence and complete live UI + +**Files:** `android/app/src/main/`, app tests, manifest/build dependencies as needed. Preserve demo behavior and shared design components. + +**Interfaces:** Android Keystore AES-GCM credential store implements Task 1 CAS and verifies readback; app-private atomic history/journal/draft store implements Task 2. A lifecycle ViewModel composes live repositories and shared menu/settings/navigation. Browser launch uses system browser with owned loopback callback. All UI actions call real typed clients. + +- [ ] Write failing state/storage tests for consent, add/select/remove/restore computers, cancelled sign-in owner, process-death drafts/journal, private HTTP, credential rotation and feature availability. +- [ ] Implement sign-in and saved hosts, real agent/Bot/session list, chat streaming/tools/prompts/secure input, slash/model/reasoning controls, active-turn controls, history paging/search and uncertainty review. +- [ ] Implement everyday feature screens from Task 3 with real list/detail/edit controls: agents/instructions, files/transfers/text editing, content/feedback, projects/Code/changes, Kanban, tasks/workflows, Usage and Apps. Keep unsupported rows truthful, host admin behind Nerd Mode, one menu and Settings. +- [ ] Add appearance/layout/mode and user identity preferences; readable Markdown, selectable output, stable reader position and keyboard behavior. Demo uses the same presentational components with labeled fixtures. +- [ ] Full app/core JVM checks, lint, debug/release assembly, focused source review and Terra actual-control verification before accepting the slice. + +### Task 5: Android media, groups, lifecycle and granted tools + +**Files:** Focused platform adapters/screens/tests under `android/app`, domain refinements only when required by observed integration. + +- [ ] Add file picker/share/open and incoming attachment/image presentation, bounded caches and permission handling. +- [ ] Add microphone permission/audio focus/recording/playback and real supported voice flows. Keep a lost voice result append uncertain, not replayed. Implement hosted group membership/chat/pending actions via actual advertised path; never fan out normal chats to fake a group. +- [ ] Add applicable Android device tools behind explicit persistent off-by-default grants and OS permissions; advertise only implemented operations. Keep Apple-only tools unavailable. Add supported Android notification delivery only with a proven server adapter; no APNs/FCM substitution. +- [ ] Verify lifecycle foreground recovery, stopped process restoration, sign-in preservation, host switching, cancelled prompts and media transfers. Test and review each affected boundary. + +### Task 6: Integrated parity acceptance and delivery + +**Files:** Android README, parity matrix, test fixtures/probes, existing PR/issue and final evidence records. + +- [ ] Use isolated real Hermes/plugin hosts from `/tmp/bighelp-android-disposable-host.md`, recorded source revisions and synthetic model. Never shared Hermes launchers or actual maintainer hosts. +- [ ] Terra/max installs exact APK and exercises open/password/browser/token sign-in, saved restore, create/resume/send/stream/steer/stop/prompts, history/restart/reconnect and host switch, files and all implemented everyday feature controls in light/dark. Record fixture versus actual-host boundaries and exact receipts. +- [ ] Run integrated checks, fix reproduced failures, one whole-branch review with scoped fix follow-up, repeat affected verification and reconcile every parity-matrix row. Unfinished ordinary workflows keep this task open. +- [ ] Update real PR title/body around the final application, source/evidence/limitations and model/harness footer. Commit and push logical changes, keep PR linked and maintainer merge/release authority. Stop owned temporary servers/emulator runtime; retain exact artifacts and installed toolchain. diff --git a/docs/superpowers/specs/2026-10-27-android-parity-design.md b/docs/superpowers/specs/2026-10-27-android-parity-design.md new file mode 100644 index 00000000..ba021fd3 --- /dev/null +++ b/docs/superpowers/specs/2026-10-27-android-parity-design.md @@ -0,0 +1,44 @@ +# Functioning Android app with everyday bighelp parity + +## Outcome and authority + +The requested outcome is a functioning end-to-end Android application close to the current Apple app, not another discovery-only preview. Continue the existing Kotlin/Jetpack Compose implementation in `android/`. Current Apple behavior, `DESIGN.md`, `docs/CHAT_INTERACTION_CONTRACT.md`, `docs/NATIVE_TRANSPORT.md` and its chapters are the reference. The earlier foundation is the starting point and remains a clearly labeled optional demo. + +The user has directed implementation and supplied the platform/model choices. Preserve those choices and the existing Ink direction; do not introduce another design selection gate or stop at an intermediate milestone. A checkpoint or PR is progress, not acceptance of a partial application. + +## Architecture + +`android/hermes` remains JVM-testable and owns authentication, ordered transport, domain clients, durable intent/recovery rules and feature decoding. `android/app` supplies Android Keystore encryption, protected atomic local storage, browser/audio/files/permissions/lifecycle adapters, observable app state and Compose presentation. Network results and persistence are bound to endpoint, exact principal and owner generation. Demo and live repositories implement the same screen-facing interfaces, while demo provenance remains explicit. + +Build on the already selected native Kotlin approach rather than changing frameworks or embedding the dashboard. Screens follow existing bighelp navigation and plain language. One menu, one Settings, searchable lists, readable chat and stable input take precedence over copying Apple-only visual effects. + +## Required workflows + +1. Add, save, select, reconnect and remove computers. Discover the advertised authentication mode. Support automatic dashboard bootstrap, explicit session/access tokens, password PKCE and browser PKCE without collecting browser cookies. Save credentials with Android Keystore encryption and verify rotating sign-in identity with single-flight compare-and-replace. Consent precedes all host access. +2. Load agents and durable sessions from the host, including canonical Bot Chats and archived sessions. Start and resume the exact agent/chat with `source: "bighelp"`, preserving runtime and stored identifiers independently. Search, rename, archive, restore, delete and select models/reasoning through real supported operations. +3. Send and stream real turns, display tools and terminal states, steer by default during active work, queue or stop when available, and show questions, approvals and secure requests. Register handlers before advertising them on every socket. Unknown requests fail explicitly. Acknowledgement means admission, not completion. +4. Preserve drafts, cached history and uncertainty across process death. Page canonical history, replay/catch up after interruption, keep reading position and composer stable, and never automatically resend an uncertain mutation. A refused send remains editable; a lost receipt remains reviewable. +5. Offer agents/Bots, configured workspace files and attachments, Feed/Ideas/Goals, Projects, Kanban, Workflows/Dev Factory, scheduled tasks, Usage and connected Apps using their real documented stock/plugin APIs. Implement everyday read/write/detail interactions and truthful supported/unsupported states; do not substitute raw JSON viewers for the product. Optional plugin capabilities are discovered from context and protected with its ETag/request-ID envelope. +6. Offer Code workflows for project/branch/worktree selection, launching chats in the exact folder, inspecting Changes and the supported Ship actions. Preserve ownership and confirmation semantics of the Apple client. +7. Add Android file picking/sharing, rendered incoming media, turn-based voice and supported live voice, hosted groups, permissions and applicable device tools with explicit grants. Android lifecycle recovery must work across background/foreground. Advertise only actually implemented platform capabilities. +8. Settings cover saved computers, appearance/layout/mode, identity, device access and advanced host tools under Nerd Mode. No cloud bighelp account or retired Link pairing. + +Platform-specific Apple surfaces (Watch, CarPlay, visionOS, Live Activities, Shortcuts, Health/Focus/AlarmKit) require honest Android equivalents or explicit platform boundaries. They do not justify omitting ordinary Android app workflows. Android push needs a real supported delivery adapter; never claim APNs registration works with an FCM token. Store verification remains a distribution gate and does not pause application implementation. + +## Invariants + +- Minimum API 26, target/compile 36; keep existing pinned toolchain unless a necessary change is justified. +- No host access before consent, credentials in URLs/logs/preferences, ambient cookies, credentialed redirects, disabled TLS checks or automatic mutation replay. +- Preserve deployment prefixes and independent proxy credentials. Public HTTP remains prohibited; private HTTP is explicit and typed. +- Wait for `gateway.ready`, authenticated health and actual exclusive-submit capability. No version allowlist. +- Strict bounded atomic frame decoding; ordered reader/writer, distinct inbound/outbound IDs, stale-owner fences, bounded prompt table and secure cancellation. +- Journal before dispatch; persistence failure prevents send. Same text is not proof of acceptance. Create retries retain the creation key; ordinary submits have no invented idempotency guarantee. +- Native extensions require advertised feature, current context and exact response correlation. Missing fields are tolerated as documented; unknown fields never break unrelated screens. +- Real data only outside labeled demo. No invented progress, fake tools or canned replies on the live path. No AI spending from default jobs. +- Public repository artifacts contain synthetic data only. Use isolated disposable Hermes clones/homes and synthetic models for verification. Never contact maintainer hosts or restart shared gateways. + +## Verification and completion + +Each independently testable task gets meaningful failing-before/fixed-after tests and a focused independent review. Build and lint the integrated app. Exercise real controls in light/dark on Android with exact installed APK identity, including connection, live send/stream, active-turn controls, prompts, files, navigation, restart/background and recovery. Run isolated stock Hermes/plugin processes with recorded source revisions and synthetic model responses, distinguishing those from scripted socket tests and demo data. Retain screenshots and receipts outside the public repository. + +Maintain an explicit parity/acceptance matrix through implementation. A row is complete only when its implementation and appropriate evidence exist; capability absence and platform boundaries are separate dispositions. Do not label the outcome complete merely because the initial chat works, tests pass or the preview builds. Publish logical commits and a real linked PR; the maintainer merges and controls release. Identity documents/payment remain directly in Google. From c65c476b6d154e96f64c921644a336af0e00614b Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:07:28 -0500 Subject: [PATCH 07/18] Track Android parity and match current refresh rejection behavior --- docs/ANDROID_PARITY.md | 52 +++++++++++++++++++ docs/hermes/CONNECTION.md | 4 +- .../plans/2026-10-27-android-parity.md | 2 +- 3 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 docs/ANDROID_PARITY.md diff --git a/docs/ANDROID_PARITY.md b/docs/ANDROID_PARITY.md new file mode 100644 index 00000000..1e85a113 --- /dev/null +++ b/docs/ANDROID_PARITY.md @@ -0,0 +1,52 @@ +# Android parity acceptance matrix + +Target: a functioning Android application close to bighelp's everyday Apple workflows. The discovery/demo foundation is not acceptance of the target. Current Apple source and the [transport contract](NATIVE_TRANSPORT.md) define behavior. The implementation plan is [Android end-to-end parity](superpowers/plans/2026-10-27-android-parity.md). + +Status is updated from source and executed evidence. **Not started** and **pending** are incomplete. Host capability absence is a runtime state, not proof that the Android implementation exists. Tests of a policy type do not establish live behavior. Apple-only platform surfaces and store-distribution gates have separate dispositions. + +Contract references below name chapters under `docs/hermes/`, with product references relative to the repository root. Exact source implementations are linked from those chapters. + +| Workflow | Required behavior | Authority | Implementation | Evidence | +|---|---|---|---|---| +| Authentication | Automatic dashboard, session/access token, password PKCE, loopback browser PKCE; restore and rotation | CONNECTION.md §§3–7 | In progress: Task 1 | Pending | +| Proxy access | Independent proxy headers, private HTTP consent and prefix-safe paths | CONNECTION.md §§1–2 | In progress: Task 1 | Endpoint tests exist; full proxy pending | +| Gateway | Ready deadline, ticket subprotocol, ordered RPC/events, heartbeat and reconnect | CONNECTION.md §§7–10 | In progress: Task 1 | Pending | +| Prompts | Questions, approval, secret/sudo and exact cancellation ownership | CHAT.md §§8–9 | Not started | Pending | +| Saved computers | Encrypted credentials, add/select/remove, restore exact principal | CONNECTION.md §6 | Not started | Pending | +| Agents and Bots | Real directory and canonical Bot Chats; edit instructions, model, appearance | REFERENCE.md §Profiles | Not started | Pending | +| Sessions | Catalog, create/resume, search, rename, archive/restore/delete/fork | CHAT.md §§1–3,11 | Not started | Pending | +| Live chat | Streaming, tools, segment finals and authoritative turn terminal | CHAT.md §§4,7 | Not started | Pending | +| Active-turn controls | Steer default, queue, stop and slash/model/reasoning controls | CHAT.md §§4,6,12 | Not started | Pending | +| Durable recovery | Draft/journal before dispatch, no uncertain replay, replay/history after restart | CHAT.md §§5,10–11 | Not started | Pending | +| Reader and input | Stable history anchor, paging, Latest, keyboard, rotation and background recovery | ../CHAT_INTERACTION_CONTRACT.md | Demo only | Live verification pending | +| Rich transcript | Markdown, tools, reasoning and supported cards with inert invalid fallback | EXTENSIONS.md §§Card documents,Agent deliveries | Not started | Pending | +| Outgoing attachments | Image/PDF/file admission and uncertainty, real picker/share | EXTENSIONS.md §Outgoing chat attachments | Not started | Pending | +| Incoming media | Resolved chunked downloads, digest/cache, image/audio/video/file viewer | EXTENSIONS.md §§Incoming attachment resolution,Managed transfers | Not started | Pending | +| Files | Agent workspace scope, browse/read/upload/download/edit with conflict handling | EXTENSIONS.md §Configured workspace; REFERENCE.md §Stock files | Not started | Pending | +| Feed, Ideas, Goals | Per-agent content, details, feedback and state changes; empty by default | EXTENSIONS.md §Board | Not started | Pending | +| Projects | Real catalog/folders/active pointer and exact session workspace binding | REFERENCE.md §Projects | Not started | Pending | +| Code | Project/branch/worktree launch, Changes, supported Ship and staged jobs | REFERENCE.md §Stock Git; AGENTS.md Code mode | Not started | Pending | +| Kanban | Boards, task CRUD/move/comments, attachments and ordered event updates | EXTENSIONS.md §Independent Hermes Kanban plugin | Not started | Pending | +| Workflows and Dev Factory | Recipes/runs/editor/actions, exact sign-off and verified artifacts | EXTENSIONS.md §Workflows | Not started | Pending | +| Scheduled tasks | List/detail/runs, capability-gated friendly editing and run actions | REFERENCE.md §Scheduled tasks | Not started | Pending | +| Usage | Host analytics and provider limits, unknown values remain unknown | REFERENCE.md §Usage; EXTENSIONS.md §Usage | Not started | Pending | +| Apps | Native connection cards, Composio/MCP connection and account management | GROUPS_AND_DEVICE_TOOLS.md §App connection cards; EXTENSIONS.md §Composio | Not started | Pending | +| Groups | Hosted rooms, durable send/log, pending actions and stop; both host paths | GROUPS_AND_DEVICE_TOOLS.md §§1–8 | Not started | Pending | +| Voice | Transcription/speech and supported real live call delegation | EXTENSIONS.md §Voice protocols | Not started | Pending | +| Bot Screen | Authenticated display bridge, bounded RFB viewer and control handoff | GROUPS_AND_DEVICE_TOOLS.md §Display transport | Not started | Pending | +| Android tools | Applicable device tools, explicit grants, OS permission and revocation | GROUPS_AND_DEVICE_TOOLS.md §§9–10 | Not started | Pending | +| Notifications | Foreground alerts and exact-chat routing; background delivery needs real Android adapter | NATIVE_TRANSPORT.md; Android delivery adapter | Not started | No FCM server contract established | +| Settings and navigation | One menu/Settings, appearance/layout/mode, identity, computers and Nerd Mode | ../../DESIGN.md; ../../AGENTS.md | Demo subset | Live acceptance pending | +| Accessibility | TalkBack, focus, font scale, contrast and reduced motion | ../../DESIGN.md | Not started | Pending | +| Apple-only surfaces | Watch, CarPlay, visionOS, Live Activities, Shortcuts, Health/Focus/AlarmKit | PORTING.md §Android and Expo boundaries | Platform boundary | No Android support claim | +| Store distribution | Permanent ID/signing, identity and physical-device checks, Play testing | ../../android/README.md | Account created; verification deferred | Distribution gate, separate from app implementation | + +## Evidence classes + +- JVM/scripted: deterministic HTTP/WebSocket, persistence, reducers and failure injection. +- Demo emulator: UI controls with explicitly invented data, no Hermes compatibility claim. +- Disposable Hermes: actual isolated host/plugin at recorded revisions, synthetic model and made-up workspace. +- Android emulator/device: installed-file identity and exercised real controls/lifecycle; emulator evidence does not establish physical-device behavior. +- Live services: only explicitly authorized services; no inference from fixtures or an Apple client. + +The full goal remains open while required everyday workflows lack implementation or appropriate end-to-end evidence. Each accepted row records exact source/build and evidence; no placeholder control or generic raw-data page counts as implementation. diff --git a/docs/hermes/CONNECTION.md b/docs/hermes/CONNECTION.md index 58bb6309..c638564f 100644 --- a/docs/hermes/CONNECTION.md +++ b/docs/hermes/CONNECTION.md @@ -291,12 +291,12 @@ read current credential and exact principal POST /auth/native/refresh (the saved credential keeps its refresh token) on 2xx: validate minted session and unchanged principal compare-and-replace the old record with the new credential -on 401: compare-and-replace the record with one that has no refresh token; require a new sign-in +on 401 without WWW-Authenticate: require a new sign-in; do not write or erase the stored record on anything else (503, 429, a proxy 5xx, a network error, a timeout, cancellation): change nothing; the next attempt sends the same refresh token again ``` -The refresh token is dropped only when Hermes answers 401. Hermes coalesces repeat refreshes for 30 seconds (the same token gets the same answer), and after a lost answer a resend cannot do worse than the sign-out that dropping the token would force; Hermes Desktop keeps its token the same way. A resend may come from the same authenticator, a new one after a reconnect, or the next launch. A stale authenticator never overwrites a newer record: the compare-and-replace fails first, whatever the host answered. +Only Hermes' own 401 requires a new sign-in; it does not erase the saved credential. Another authenticator may be saving a newer sign-in, and the rejected authenticator must not overwrite it. Hermes coalesces repeat refreshes for 30 seconds (the same token gets the same answer). After a lost answer, the saved refresh token remains available to the same authenticator, a reconnect or the next launch. A stale authenticator never overwrites a newer record: the compare-and-replace fails first, whatever the host answered. This matches `performRefresh` and `aRejectedRenewalAsksForANewSignIn` in the linked source and renewal tests. Authenticated JSON HTTP performs one narrowly defined retry: on HTTP 401 **without** `WWW-Authenticate`, renew the Bearer token, or rebootstrap an automatic dashboard token that changed, and resend once. If another concurrent request already installed a new credential, use that one. This relies on the Hermes contract that auth refusal happens before route execution. A 401 with `WWW-Authenticate` is a proxy challenge, not this retry path. Other HTTP failures are not retried here. Dedicated multipart/binary transfers do not inherit this generic JSON retry loop. diff --git a/docs/superpowers/plans/2026-10-27-android-parity.md b/docs/superpowers/plans/2026-10-27-android-parity.md index a18c0be3..b83fb625 100644 --- a/docs/superpowers/plans/2026-10-27-android-parity.md +++ b/docs/superpowers/plans/2026-10-27-android-parity.md @@ -36,7 +36,7 @@ **Interfaces:** Provide public JVM types for auth status/providers, saved credentials, sign-in input, a compare-and-replace credential store, bounded authenticated HTTP, and an ordered gateway interface. Publish exact signatures in the report for later tasks. Store authority is canonical endpoint plus exact principal. Android browser composition uses a supplied browser-launch callback and a real device-local loopback listener; no invented app-scheme callback. RPC consumers need connect/close, request/result/failure, ordered event and server-request streams, exact-owned server replies, generation and current capability/readiness state. -- [ ] Write failing tests for bootstrap extraction, dashboard versus bearer headers, password/native browser PKCE query/cookie/state/code validation, token identity/expiry, single-flight rotating refresh with durable CAS and 401-only retirement, mode/principal changes, response bounds, no redirects/cookies/retries and cancellation. +- [ ] Write failing tests for bootstrap extraction, dashboard versus bearer headers, password/native browser PKCE query/cookie/state/code validation, token identity/expiry, single-flight rotating refresh with durable CAS and a 401 requiring new sign-in without overwriting the vault, mode/principal changes, response bounds, no redirects/cookies/retries and cancellation. - [ ] Write failing scripted WebSocket tests: no outbound before ready, 20-second ready deadline, fresh bearer ticket per connection, heartbeat, strict atomic ordered frames, RPC correlation, separate inbound/outbound ID namespaces, 64-entry prompt table, duplicates, wrong-method cancellation, late replies, unknown request `-32601`, close during mutation, false/malformed exclusive-submit and reconnect re-advertisement. - [ ] Observe RED, implement actual contract in `docs/hermes/CONNECTION.md`, then run all Hermes JVM tests and document GREEN. No speculative retries; expose typed uncertain outcome after possible dispatch. - [ ] Publish the exact API and focused evidence; independent scoped review before dependent code. From 97b5db4d230c882e6220f3ad386062f5e9f52179 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:14:43 -0500 Subject: [PATCH 08/18] Add encrypted storage for Android sign-in records --- .../android/storage/AndroidCredentialKey.kt | 28 +++ .../android/storage/ProtectedRecordStore.kt | 100 +++++++++++ .../bighelp/android/storage/RecordCipher.kt | 63 +++++++ .../storage/ProtectedRecordStoreTest.kt | 168 ++++++++++++++++++ 4 files changed, 359 insertions(+) create mode 100644 android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt create mode 100644 android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt create mode 100644 android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt diff --git a/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt b/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt new file mode 100644 index 00000000..f554baed --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt @@ -0,0 +1,28 @@ +package app.bighelp.android.storage + +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import java.security.KeyStore +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey + +/** One non-exportable device key. Records remain unavailable if the key is lost or invalidated. */ +object AndroidCredentialKey { + private const val ALIAS = "bighelp.credentials.v1" + + @Synchronized + fun get(): SecretKey { + val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + (store.getKey(ALIAS, null) as? SecretKey)?.let { return it } + return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply { + init( + KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + .setKeySize(256) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setRandomizedEncryptionRequired(true) + .build(), + ) + }.generateKey() + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt b/android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt new file mode 100644 index 00000000..2034ad20 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt @@ -0,0 +1,100 @@ +package app.bighelp.android.storage + +import java.io.ByteArrayOutputStream +import java.io.File +import java.io.FileOutputStream +import java.io.IOException +import java.nio.channels.FileChannel +import java.nio.file.Files +import java.nio.file.StandardCopyOption.ATOMIC_MOVE +import java.nio.file.StandardCopyOption.REPLACE_EXISTING +import java.nio.file.StandardOpenOption.CREATE +import java.nio.file.StandardOpenOption.READ +import java.nio.file.StandardOpenOption.WRITE +import java.security.MessageDigest +import java.util.concurrent.ConcurrentHashMap + +/** + * Encrypted, atomic compare-and-replace for records in an app-private, backup-excluded directory. + * Run on an I/O dispatcher. The credential adapter supplies an unambiguous authority-bound record key. + */ +class ProtectedRecordStore(private val directory: File, private val cipher: RecordCipher) { + fun read(key: String): ByteArray? = locked(key) { file -> readRecord(key, file) } + + fun compareAndSet(key: String, expected: ByteArray?, replacement: ByteArray?): Boolean = locked(key) { file -> + if (replacement != null && replacement.size > RecordCipher.MAXIMUM_RECORD_BYTES) { + throw RecordStorageException(StorageProblem.RecordTooLarge) + } + val current = readRecord(key, file) + val matches = if (expected == null || current == null) expected == null && current == null + else MessageDigest.isEqual(expected, current) + if (!matches) return@locked false + if (replacement == null) { + Files.deleteIfExists(file.toPath()) + syncDirectory() + } else { + writeRecord(file, cipher.encrypt(key, replacement)) + } + true + } + + private fun readRecord(key: String, file: File): ByteArray? { + if (!file.exists()) return null + val bytes = file.inputStream().use { input -> + val output = ByteArrayOutputStream() + val buffer = ByteArray(8_192) + while (true) { + val count = input.read(buffer, 0, minOf(buffer.size, RecordCipher.MAXIMUM_ENVELOPE_BYTES + 1 - output.size())) + if (count < 0) break + output.write(buffer, 0, count) + if (output.size() > RecordCipher.MAXIMUM_ENVELOPE_BYTES) { + throw RecordStorageException(StorageProblem.RecordTooLarge) + } + } + output.toByteArray() + } + return cipher.decrypt(key, bytes) + } + + private fun writeRecord(file: File, bytes: ByteArray) { + val pending = File.createTempFile(".record-", ".pending", directory) + try { + FileOutputStream(pending).use { output -> + output.write(bytes) + output.fd.sync() + } + // Never replace a valid credential with a partly written file. + Files.move(pending.toPath(), file.toPath(), ATOMIC_MOVE, REPLACE_EXISTING) + syncDirectory() + } finally { + Files.deleteIfExists(pending.toPath()) + } + } + + private fun syncDirectory() { + FileChannel.open(directory.toPath(), READ).use { it.force(true) } + } + + private fun locked(key: String, body: (File) -> T): T { + require(key.isNotEmpty() && key.toByteArray(Charsets.UTF_8).size <= 8_192) + try { + Files.createDirectories(directory.toPath()) + val digest = MessageDigest.getInstance("SHA-256").digest(key.toByteArray(Charsets.UTF_8)) + .joinToString("") { "%02x".format(it) } + val file = File(directory, "$digest.sealed") + val monitor = monitors.computeIfAbsent(file.canonicalPath) { Any() } + return synchronized(monitor) { + FileChannel.open(File(directory, "$digest.lock").toPath(), CREATE, WRITE).use { channel -> + // The monitor handles multiple authenticators in this process; the lock covers another process. + channel.lock().use { body(file) } + } + } + } catch (_: IOException) { + throw RecordStorageException(StorageProblem.DiskUnavailable) + } + } + + private companion object { + val monitors = ConcurrentHashMap () + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt b/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt new file mode 100644 index 00000000..f54da6a1 --- /dev/null +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt @@ -0,0 +1,63 @@ +package app.bighelp.android.storage + +import java.security.GeneralSecurityException +import javax.crypto.AEADBadTagException +import javax.crypto.Cipher +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +enum class StorageProblem { CorruptRecord, RecordTooLarge, KeyUnavailable, DiskUnavailable } + +/** Carries a category, never a credential, authority or filesystem path. */ +class RecordStorageException(val problem: StorageProblem) : Exception(problem.name) + +/** The authority is authenticated too: copying ciphertext to another host never adopts its identity. */ +class RecordCipher(private val key: () -> SecretKey) { + fun encrypt(binding: String, plaintext: ByteArray): ByteArray { + if (plaintext.size > MAXIMUM_RECORD_BYTES) throw RecordStorageException(StorageProblem.RecordTooLarge) + val secret = deviceKey() + try { + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.ENCRYPT_MODE, secret) + cipher.updateAAD(binding.toByteArray(Charsets.UTF_8)) + val nonce = cipher.iv + if (nonce.size != NONCE_BYTES) throw RecordStorageException(StorageProblem.KeyUnavailable) + return MAGIC + nonce + cipher.doFinal(plaintext) + } catch (_: GeneralSecurityException) { + throw RecordStorageException(StorageProblem.KeyUnavailable) + } + } + + fun decrypt(binding: String, envelope: ByteArray): ByteArray { + if (envelope.size > MAXIMUM_ENVELOPE_BYTES) throw RecordStorageException(StorageProblem.RecordTooLarge) + if (envelope.size < OVERHEAD_BYTES || !envelope.copyOfRange(0, MAGIC.size).contentEquals(MAGIC)) { + throw RecordStorageException(StorageProblem.CorruptRecord) + } + val secret = deviceKey() + try { + val cipher = Cipher.getInstance("AES/GCM/NoPadding") + val nonce = envelope.copyOfRange(MAGIC.size, MAGIC.size + NONCE_BYTES) + cipher.init(Cipher.DECRYPT_MODE, secret, GCMParameterSpec(128, nonce)) + cipher.updateAAD(binding.toByteArray(Charsets.UTF_8)) + return cipher.doFinal(envelope, MAGIC.size + NONCE_BYTES, envelope.size - MAGIC.size - NONCE_BYTES) + } catch (_: AEADBadTagException) { + throw RecordStorageException(StorageProblem.CorruptRecord) + } catch (_: GeneralSecurityException) { + throw RecordStorageException(StorageProblem.KeyUnavailable) + } + } + + private fun deviceKey(): SecretKey = try { + key() + } catch (_: Exception) { + throw RecordStorageException(StorageProblem.KeyUnavailable) + } + + companion object { + const val MAXIMUM_RECORD_BYTES = 65_536 + private val MAGIC = "BHCREDS1".toByteArray(Charsets.US_ASCII) + private const val NONCE_BYTES = 12 + private val OVERHEAD_BYTES = MAGIC.size + NONCE_BYTES + 16 + val MAXIMUM_ENVELOPE_BYTES = MAXIMUM_RECORD_BYTES + OVERHEAD_BYTES + } +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt b/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt new file mode 100644 index 00000000..4ea062e7 --- /dev/null +++ b/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt @@ -0,0 +1,168 @@ +package app.bighelp.android.storage + +import java.nio.file.Files +import java.util.concurrent.CountDownLatch +import java.util.concurrent.Executors +import java.util.concurrent.TimeUnit +import java.util.concurrent.atomic.AtomicInteger +import javax.crypto.KeyGenerator +import org.junit.Assert.* +import org.junit.Rule +import org.junit.Test +import org.junit.rules.TemporaryFolder + +class ProtectedRecordStoreTest { + @get:Rule val temporary = TemporaryFolder() + private val key = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + private val binding = "https://example.test/hermes|basic|synthetic-person" + private fun store() = ProtectedRecordStore(temporary.root, RecordCipher { key }) + private fun bytes(value: String) = value.toByteArray(Charsets.UTF_8) + + @Test fun savedCredentialSurvivesReopeningWithoutPlaintextOnDisk() { + val value = bytes("synthetic-access-token and synthetic-refresh-token") + assertTrue(store().compareAndSet(binding, null, value)) + assertArrayEquals(value, store().read(binding)) + val saved = temporary.root.listFiles()!!.single { it.extension == "sealed" }.readBytes() + assertFalse(saved.toString(Charsets.ISO_8859_1).contains("synthetic-access-token")) + assertFalse(saved.toString(Charsets.ISO_8859_1).contains("synthetic-refresh-token")) + } + + @Test fun oldRefreshCannotOverwriteOrEraseANewerSignIn() { + val first = bytes("refresh-1") + val rotated = bytes("refresh-2") + val newer = bytes("newer-sign-in") + val vault = store() + assertTrue(vault.compareAndSet(binding, null, first)) + assertTrue(vault.compareAndSet(binding, first, rotated)) + assertTrue(store().compareAndSet(binding, rotated, newer)) + assertFalse(vault.compareAndSet(binding, rotated, bytes("stale-answer"))) + assertFalse(vault.compareAndSet(binding, rotated, null)) + assertArrayEquals(newer, store().read(binding)) + } + + @Test fun concurrentAuthenticatorsHaveOnlyOneReplacementWinner() { + val initial = bytes("initial") + assertTrue(store().compareAndSet(binding, null, initial)) + val start = CountDownLatch(1) + val executor = Executors.newFixedThreadPool(2) + try { + val attempts = listOf("answer-a", "answer-b").map { answer -> + executor.submit { + start.await() + store().compareAndSet(binding, initial, bytes(answer)) + } + } + start.countDown() + assertEquals(1, attempts.count { it.get(5, TimeUnit.SECONDS) }) + assertTrue(store().read(binding)!!.toString(Charsets.UTF_8) in setOf("answer-a", "answer-b")) + } finally { + executor.shutdownNow() + } + } + + @Test fun ciphertextCannotBeMovedToAnotherAuthority() { + val vault = store() + assertTrue(vault.compareAndSet(binding, null, bytes("first"))) + val first = temporary.root.listFiles()!!.single { it.extension == "sealed" } + val other = "https://other.example.test|basic|synthetic-person" + assertTrue(vault.compareAndSet(other, null, bytes("second"))) + val second = temporary.root.listFiles()!!.single { it.extension == "sealed" && it != first } + Files.copy(first.toPath(), second.toPath(), java.nio.file.StandardCopyOption.REPLACE_EXISTING) + refuses(StorageProblem.CorruptRecord) { vault.read(other) } + assertArrayEquals(bytes("first"), vault.read(binding)) + } + + @Test fun modifiedOrTruncatedRecordRequiresRecoveryInsteadOfBecomingSignedOut() { + val vault = store() + assertTrue(vault.compareAndSet(binding, null, bytes("secret"))) + val file = temporary.root.listFiles()!!.single { it.extension == "sealed" } + val original = file.readBytes() + file.writeBytes(original.copyOf().also { it[it.lastIndex] = (it.last().toInt() xor 1).toByte() }) + refuses(StorageProblem.CorruptRecord) { vault.read(binding) } + file.writeBytes(original.copyOf(12)) + refuses(StorageProblem.CorruptRecord) { vault.read(binding) } + } + + @Test fun wrongDeviceKeyCannotReadARecord() { + assertTrue(store().compareAndSet(binding, null, bytes("secret"))) + val anotherKey = KeyGenerator.getInstance("AES").apply { init(256) }.generateKey() + val anotherDevice = ProtectedRecordStore(temporary.root, RecordCipher { anotherKey }) + refuses(StorageProblem.CorruptRecord) { anotherDevice.read(binding) } + } + + @Test fun sizeLimitIsInBytesAndRefusalPreservesThePriorRecord() { + val limit = ByteArray(65_536) { 0x61 } + val vault = store() + assertTrue(vault.compareAndSet(binding, null, limit)) + assertArrayEquals(limit, store().read(binding)) + refuses(StorageProblem.RecordTooLarge) { + vault.compareAndSet(binding, limit, ByteArray(65_537)) + } + assertArrayEquals(limit, store().read(binding)) + } + + @Test fun anOversizedFileIsRejectedBeforeDecode() { + val vault = store() + assertTrue(vault.compareAndSet(binding, null, bytes("secret"))) + temporary.root.listFiles()!!.single { it.extension == "sealed" }.writeBytes(ByteArray(70_000)) + refuses(StorageProblem.RecordTooLarge) { vault.read(binding) } + } + + @Test fun successfulLocalSignOutRemovesOnlyTheExpectedRecord() { + val vault = store() + val value = bytes("saved") + assertNull(vault.read(binding)) + assertTrue(vault.compareAndSet(binding, null, value)) + assertTrue(vault.compareAndSet(binding, value, null)) + assertNull(store().read(binding)) + assertFalse(vault.compareAndSet(binding, value, bytes("late-refresh"))) + } + + @Test fun encryptingTheSameRecordUsesANewNonce() { + val cipher = RecordCipher { key } + val plain = bytes("same-token") + val first = cipher.encrypt(binding, plain) + val second = cipher.encrypt(binding, plain) + assertFalse(first.contentEquals(second)) + assertArrayEquals(plain, cipher.decrypt(binding, first)) + assertArrayEquals(plain, cipher.decrypt(binding, second)) + } + + @Test fun failureToEncryptAReplacementKeepsThePreviousCredential() { + val value = bytes("saved-sign-in") + assertTrue(store().compareAndSet(binding, null, value)) + val calls = AtomicInteger() + val failing = ProtectedRecordStore(temporary.root, RecordCipher { + if (calls.getAndIncrement() == 0) key else throw IllegalStateException("device key unavailable") + }) + refuses(StorageProblem.KeyUnavailable) { failing.compareAndSet(binding, value, bytes("new-token")) } + assertArrayEquals(value, store().read(binding)) + assertFalse(temporary.root.listFiles()!!.any { it.extension == "pending" }) + } + + @Test fun unavailableDiskDoesNotLookLikeAnAbsentSignIn() { + val notDirectory = temporary.newFile("not-a-directory") + val vault = ProtectedRecordStore(notDirectory, RecordCipher { key }) + refuses(StorageProblem.DiskUnavailable) { vault.read(binding) } + refuses(StorageProblem.DiskUnavailable) { vault.compareAndSet(binding, null, bytes("value")) } + } + + @Test fun distinctOpaquePrincipalStringsHaveSeparateRecords() { + val first = "https://example.test|basic|caf\u00e9" + val second = "https://example.test|basic|cafe\u0301" + val vault = store() + assertTrue(vault.compareAndSet(first, null, bytes("one"))) + assertTrue(vault.compareAndSet(second, null, bytes("two"))) + assertArrayEquals(bytes("one"), vault.read(first)) + assertArrayEquals(bytes("two"), vault.read(second)) + } + + private fun refuses(problem: StorageProblem, action: () -> Unit) { + try { + action() + fail("Expected $problem") + } catch (failure: RecordStorageException) { + assertEquals(problem, failure.problem) + } + } +} From e2d20f33634b4b31b28f75dbf2f56c2e40106b6b Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:32:08 -0500 Subject: [PATCH 09/18] Handle Android credential key loss and storage failures safely --- android/app/build.gradle.kts | 2 + .../storage/AndroidCredentialStorageTest.kt | 93 ++++++++++++ .../android/storage/AndroidCredentialKey.kt | 19 ++- .../android/storage/ProtectedRecordStore.kt | 57 +++++++- .../bighelp/android/storage/RecordCipher.kt | 64 +++++++-- .../storage/ProtectedRecordStoreTest.kt | 132 ++++++++++++++++++ 6 files changed, 343 insertions(+), 24 deletions(-) create mode 100644 android/app/src/androidTest/kotlin/app/bighelp/android/storage/AndroidCredentialStorageTest.kt diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 8ce2ef7a..29b88468 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -54,4 +54,6 @@ dependencies { testImplementation("junit:junit:4.13.2") testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2") testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") + androidTestImplementation("androidx.test:runner:1.7.0") + androidTestImplementation("androidx.test.ext:junit:1.3.0") } diff --git a/android/app/src/androidTest/kotlin/app/bighelp/android/storage/AndroidCredentialStorageTest.kt b/android/app/src/androidTest/kotlin/app/bighelp/android/storage/AndroidCredentialStorageTest.kt new file mode 100644 index 00000000..f5a128b8 --- /dev/null +++ b/android/app/src/androidTest/kotlin/app/bighelp/android/storage/AndroidCredentialStorageTest.kt @@ -0,0 +1,93 @@ +package app.bighelp.android.storage + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry +import java.io.File +import java.util.UUID +import java.security.KeyStore +import org.junit.Assert.* +import org.junit.Test +import org.junit.runner.RunWith + +/** Exercises the real Android Keystore and app filesystem rather than the JVM crypto provider. */ +@RunWith(AndroidJUnit4::class) +class AndroidCredentialStorageTest { + @Test fun deviceKeyIsNonExportable() { + val key = AndroidCredentialKey.getOrCreate() + assertEquals("AES", key.algorithm) + assertNull(key.encoded) + } + + @Test fun protectedRecordReopensAndAStaleAuthenticatorCannotReplaceOrDeleteIt() = withStore { root -> + val binding = "storage-probe:https://example.test/hermes|basic|synthetic-person" + val original = "synthetic-refresh-one".toByteArray() + val replacement = "synthetic-refresh-two".toByteArray() + fun vault() = ProtectedRecordStore(root, RecordCipher(AndroidCredentialKey)) + assertTrue(vault().compareAndSet(binding, null, original)) + assertArrayEquals(original, vault().read(binding)) + assertTrue(vault().compareAndSet(binding, original, replacement)) + assertFalse(vault().compareAndSet(binding, original, "stale".toByteArray())) + assertFalse(vault().compareAndSet(binding, original, null)) + assertArrayEquals(replacement, vault().read(binding)) + assertTrue(vault().compareAndSet(binding, replacement, null)) + assertNull(vault().read(binding)) + } + + @Test fun aModifiedCiphertextIsRefusedOnAndroid() = withStore { root -> + val vault = ProtectedRecordStore(root, RecordCipher(AndroidCredentialKey)) + val binding = "storage-probe:synthetic-authority" + assertTrue(vault.compareAndSet(binding, null, "synthetic-token".toByteArray())) + val file = root.listFiles()!!.single { it.extension == "sealed" } + val bytes = file.readBytes() + assertFalse(bytes.toString(Charsets.ISO_8859_1).contains("synthetic-token")) + file.writeBytes(bytes.also { it[it.lastIndex] = (it.last().toInt() xor 1).toByte() }) + try { + vault.read(binding) + fail("Modified ciphertext must not be adopted") + } catch (failure: RecordStorageException) { + assertEquals(StorageProblem.CorruptRecord, failure.problem) + } + } + + @Test fun maximumRecordRoundTripsWithTheAndroidKey() = withStore { root -> + val vault = ProtectedRecordStore(root, RecordCipher(AndroidCredentialKey)) + val value = ByteArray(65_536) { (it % 127).toByte() } + assertTrue(vault.compareAndSet("storage-probe:maximum", null, value)) + assertArrayEquals(value, vault.read("storage-probe:maximum")) + } + + @Test fun missingKeyIsNotRecreatedByReadingAndAllowsExplicitLocalRecovery() = withStore { root -> + val alias = "bighelp.storage-probe.${UUID.randomUUID()}" + val keys = AndroidKeyStoreRecordKeys(alias) + val keyStore = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + val vault = ProtectedRecordStore(root, RecordCipher(keys)) + val binding = "storage-probe:missing-key" + try { + assertTrue(vault.compareAndSet(binding, null, "synthetic-first".toByteArray())) + keyStore.deleteEntry(alias) + try { + vault.read(binding) + fail("Reading must not create a replacement key") + } catch (failure: RecordStorageException) { + assertEquals(StorageProblem.KeyMissing, failure.problem) + } + assertFalse(keyStore.containsAlias(alias)) + assertTrue(vault.discardUnreadable(binding)) + val next = "synthetic-new-sign-in".toByteArray() + assertTrue(vault.compareAndSet(binding, null, next)) + assertArrayEquals(next, vault.read(binding)) + } finally { + keyStore.deleteEntry(alias) + } + } + + private fun withStore(block: (File) -> Unit) { + val context = InstrumentationRegistry.getInstrumentation().targetContext + val root = File(context.noBackupFilesDir, "storage-probe-${UUID.randomUUID()}") + try { + block(root) + } finally { + root.deleteRecursively() + } + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt b/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt index f554baed..dec2ce25 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/AndroidCredentialKey.kt @@ -6,17 +6,24 @@ import java.security.KeyStore import javax.crypto.KeyGenerator import javax.crypto.SecretKey -/** One non-exportable device key. Records remain unavailable if the key is lost or invalidated. */ -object AndroidCredentialKey { - private const val ALIAS = "bighelp.credentials.v1" +/** Device-local, non-exportable key, usable after first unlock without a prompt for background renewal. */ +object AndroidCredentialKey : RecordKeyProvider by AndroidKeyStoreRecordKeys("bighelp.credentials.v1") +internal class AndroidKeyStoreRecordKeys(private val alias: String) : RecordKeyProvider { @Synchronized - fun get(): SecretKey { + override fun existing(): SecretKey? { val store = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } - (store.getKey(ALIAS, null) as? SecretKey)?.let { return it } + if (!store.containsAlias(alias)) return null + return store.getKey(alias, null) as? SecretKey + ?: throw RecordStorageException(StorageProblem.KeyUnavailable) + } + + @Synchronized + override fun getOrCreate(): SecretKey { + existing()?.let { return it } return KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore").apply { init( - KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + KeyGenParameterSpec.Builder(alias, KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) .setKeySize(256) .setBlockModes(KeyProperties.BLOCK_MODE_GCM) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) diff --git a/android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt b/android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt index 2034ad20..415a33fb 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/ProtectedRecordStore.kt @@ -4,8 +4,11 @@ import java.io.ByteArrayOutputStream import java.io.File import java.io.FileOutputStream import java.io.IOException +import java.io.InputStream import java.nio.channels.FileChannel import java.nio.file.Files +import java.nio.file.NoSuchFileException +import java.nio.file.Path import java.nio.file.StandardCopyOption.ATOMIC_MOVE import java.nio.file.StandardCopyOption.REPLACE_EXISTING import java.nio.file.StandardOpenOption.CREATE @@ -18,9 +21,16 @@ import java.util.concurrent.ConcurrentHashMap * Encrypted, atomic compare-and-replace for records in an app-private, backup-excluded directory. * Run on an I/O dispatcher. The credential adapter supplies an unambiguous authority-bound record key. */ -class ProtectedRecordStore(private val directory: File, private val cipher: RecordCipher) { +class ProtectedRecordStore internal constructor( + private val directory: File, + private val cipher: RecordCipher, + private val files: RecordFileOperations, +) { + constructor(directory: File, cipher: RecordCipher) : this(directory, cipher, SystemRecordFileOperations) + fun read(key: String): ByteArray? = locked(key) { file -> readRecord(key, file) } + /** A disk error after rename/delete can mean it committed. Read back before retrying any write. */ fun compareAndSet(key: String, expected: ByteArray?, replacement: ByteArray?): Boolean = locked(key) { file -> if (replacement != null && replacement.size > RecordCipher.MAXIMUM_RECORD_BYTES) { throw RecordStorageException(StorageProblem.RecordTooLarge) @@ -38,9 +48,28 @@ class ProtectedRecordStore(private val directory: File, private val cipher: Reco true } + /** Deliberate local recovery only. A valid record or a transient failure is never discarded. */ + fun discardUnreadable(key: String): Boolean = locked(key) { file -> + try { + readRecord(key, file) + false + } catch (failure: RecordStorageException) { + if (failure.problem !in setOf(StorageProblem.CorruptRecord, StorageProblem.RecordTooLarge, StorageProblem.KeyMissing)) { + throw failure + } + Files.deleteIfExists(file.toPath()) + syncDirectory() + true + } + } + private fun readRecord(key: String, file: File): ByteArray? { - if (!file.exists()) return null - val bytes = file.inputStream().use { input -> + val stream = try { + files.read(file) + } catch (_: NoSuchFileException) { + return null + } + val bytes = stream.use { input -> val output = ByteArrayOutputStream() val buffer = ByteArray(8_192) while (true) { @@ -59,12 +88,12 @@ class ProtectedRecordStore(private val directory: File, private val cipher: Reco private fun writeRecord(file: File, bytes: ByteArray) { val pending = File.createTempFile(".record-", ".pending", directory) try { - FileOutputStream(pending).use { output -> + files.write(pending).use { output -> output.write(bytes) output.fd.sync() } // Never replace a valid credential with a partly written file. - Files.move(pending.toPath(), file.toPath(), ATOMIC_MOVE, REPLACE_EXISTING) + files.move(pending.toPath(), file.toPath()) syncDirectory() } finally { Files.deleteIfExists(pending.toPath()) @@ -76,10 +105,10 @@ class ProtectedRecordStore(private val directory: File, private val cipher: Reco } private fun locked(key: String, body: (File) -> T): T { - require(key.isNotEmpty() && key.toByteArray(Charsets.UTF_8).size <= 8_192) + val binding = recordBindingBytes(key) try { Files.createDirectories(directory.toPath()) - val digest = MessageDigest.getInstance("SHA-256").digest(key.toByteArray(Charsets.UTF_8)) + val digest = MessageDigest.getInstance("SHA-256").digest(binding) .joinToString("") { "%02x".format(it) } val file = File(directory, "$digest.sealed") val monitor = monitors.computeIfAbsent(file.canonicalPath) { Any() } @@ -98,3 +127,17 @@ class ProtectedRecordStore(private val directory: File, private val cipher: Reco val monitors = ConcurrentHashMap () } } + +internal interface RecordFileOperations { + fun read(file: File): InputStream + fun write(file: File): FileOutputStream + fun move(from: Path, to: Path) +} + +internal object SystemRecordFileOperations : RecordFileOperations { + override fun read(file: File): InputStream = Files.newInputStream(file.toPath()) + override fun write(file: File) = FileOutputStream(file) + override fun move(from: Path, to: Path) { + Files.move(from, to, ATOMIC_MOVE, REPLACE_EXISTING) + } +} diff --git a/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt b/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt index f54da6a1..0231b543 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt @@ -1,30 +1,52 @@ package app.bighelp.android.storage import java.security.GeneralSecurityException +import java.security.ProviderException +import java.nio.CharBuffer +import java.nio.charset.CharacterCodingException +import java.nio.charset.CodingErrorAction import javax.crypto.AEADBadTagException import javax.crypto.Cipher import javax.crypto.SecretKey import javax.crypto.spec.GCMParameterSpec -enum class StorageProblem { CorruptRecord, RecordTooLarge, KeyUnavailable, DiskUnavailable } +enum class StorageProblem { CorruptRecord, RecordTooLarge, KeyMissing, KeyUnavailable, DiskUnavailable, InvalidBinding } /** Carries a category, never a credential, authority or filesystem path. */ class RecordStorageException(val problem: StorageProblem) : Exception(problem.name) -/** The authority is authenticated too: copying ciphertext to another host never adopts its identity. */ -class RecordCipher(private val key: () -> SecretKey) { +interface RecordKeyProvider { + fun existing(): SecretKey? + fun getOrCreate(): SecretKey +} + +/** The record binding is authenticated too, so ciphertext cannot be adopted under another key. */ +class RecordCipher internal constructor( + private val keys: RecordKeyProvider, + private val cipherFactory: () -> Cipher, +) { + constructor(keys: RecordKeyProvider) : this(keys, { Cipher.getInstance("AES/GCM/NoPadding") }) + constructor(key: () -> SecretKey) : this(object : RecordKeyProvider { + override fun existing() = key() + override fun getOrCreate() = key() + }) + fun encrypt(binding: String, plaintext: ByteArray): ByteArray { if (plaintext.size > MAXIMUM_RECORD_BYTES) throw RecordStorageException(StorageProblem.RecordTooLarge) - val secret = deviceKey() + val bindingBytes = recordBindingBytes(binding) + val secret = deviceKey(create = true) try { - val cipher = Cipher.getInstance("AES/GCM/NoPadding") + val cipher = cipherFactory() cipher.init(Cipher.ENCRYPT_MODE, secret) - cipher.updateAAD(binding.toByteArray(Charsets.UTF_8)) + cipher.updateAAD(MAGIC) + cipher.updateAAD(bindingBytes) val nonce = cipher.iv if (nonce.size != NONCE_BYTES) throw RecordStorageException(StorageProblem.KeyUnavailable) return MAGIC + nonce + cipher.doFinal(plaintext) } catch (_: GeneralSecurityException) { throw RecordStorageException(StorageProblem.KeyUnavailable) + } catch (_: ProviderException) { + throw RecordStorageException(StorageProblem.KeyUnavailable) } } @@ -33,22 +55,28 @@ class RecordCipher(private val key: () -> SecretKey) { if (envelope.size < OVERHEAD_BYTES || !envelope.copyOfRange(0, MAGIC.size).contentEquals(MAGIC)) { throw RecordStorageException(StorageProblem.CorruptRecord) } - val secret = deviceKey() + val bindingBytes = recordBindingBytes(binding) + val secret = deviceKey(create = false) try { - val cipher = Cipher.getInstance("AES/GCM/NoPadding") + val cipher = cipherFactory() val nonce = envelope.copyOfRange(MAGIC.size, MAGIC.size + NONCE_BYTES) cipher.init(Cipher.DECRYPT_MODE, secret, GCMParameterSpec(128, nonce)) - cipher.updateAAD(binding.toByteArray(Charsets.UTF_8)) + cipher.updateAAD(MAGIC) + cipher.updateAAD(bindingBytes) return cipher.doFinal(envelope, MAGIC.size + NONCE_BYTES, envelope.size - MAGIC.size - NONCE_BYTES) } catch (_: AEADBadTagException) { throw RecordStorageException(StorageProblem.CorruptRecord) } catch (_: GeneralSecurityException) { throw RecordStorageException(StorageProblem.KeyUnavailable) + } catch (_: ProviderException) { + throw RecordStorageException(StorageProblem.KeyUnavailable) } } - private fun deviceKey(): SecretKey = try { - key() + private fun deviceKey(create: Boolean): SecretKey = try { + keys.existing() ?: if (create) keys.getOrCreate() else throw RecordStorageException(StorageProblem.KeyMissing) + } catch (failure: RecordStorageException) { + throw failure } catch (_: Exception) { throw RecordStorageException(StorageProblem.KeyUnavailable) } @@ -61,3 +89,17 @@ class RecordCipher(private val key: () -> SecretKey) { val MAXIMUM_ENVELOPE_BYTES = MAXIMUM_RECORD_BYTES + OVERHEAD_BYTES } } + +internal fun recordBindingBytes(binding: String): ByteArray { + if (binding.isEmpty() || binding.length > 8_192) throw RecordStorageException(StorageProblem.InvalidBinding) + val encoded = try { + Charsets.UTF_8.newEncoder() + .onMalformedInput(CodingErrorAction.REPORT) + .onUnmappableCharacter(CodingErrorAction.REPORT) + .encode(CharBuffer.wrap(binding)) + } catch (_: CharacterCodingException) { + throw RecordStorageException(StorageProblem.InvalidBinding) + } + if (encoded.remaining() > 8_192) throw RecordStorageException(StorageProblem.InvalidBinding) + return ByteArray(encoded.remaining()).also(encoded::get) +} diff --git a/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt b/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt index 4ea062e7..58233947 100644 --- a/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt +++ b/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt @@ -1,12 +1,20 @@ package app.bighelp.android.storage import java.nio.file.Files +import java.nio.file.Path +import java.io.File +import java.io.FileOutputStream +import java.io.FilterInputStream +import java.io.IOException +import java.io.InputStream +import java.security.ProviderException import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import java.util.concurrent.TimeUnit import java.util.concurrent.atomic.AtomicInteger import javax.crypto.KeyGenerator import org.junit.Assert.* +import org.junit.Assume.assumeTrue import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder @@ -81,6 +89,10 @@ class ProtectedRecordStoreTest { refuses(StorageProblem.CorruptRecord) { vault.read(binding) } file.writeBytes(original.copyOf(12)) refuses(StorageProblem.CorruptRecord) { vault.read(binding) } + file.writeBytes(original.copyOf(original.size - 1)) + refuses(StorageProblem.CorruptRecord) { vault.read(binding) } + file.writeBytes(original.copyOf().also { it[8] = (it[8].toInt() xor 1).toByte() }) + refuses(StorageProblem.CorruptRecord) { vault.read(binding) } } @Test fun wrongDeviceKeyCannotReadARecord() { @@ -157,6 +169,126 @@ class ProtectedRecordStoreTest { assertArrayEquals(bytes("two"), vault.read(second)) } + @Test fun aStatFailureIsNeverTreatedAsAnAbsentRecord() { + val vault = store() + assertTrue(vault.compareAndSet(binding, null, bytes("saved"))) + val file = temporary.root.listFiles()!!.single { it.extension == "sealed" }.toPath() + Files.delete(file) + Files.createSymbolicLink(file, file.fileName) + refuses(StorageProblem.DiskUnavailable) { vault.read(binding) } + refuses(StorageProblem.DiskUnavailable) { vault.compareAndSet(binding, null, bytes("replacement")) } + assertTrue(Files.isSymbolicLink(file)) + } + + @Test fun readingWithAMissingDeviceKeyNeverCreatesAnotherKey() { + assertTrue(store().compareAndSet(binding, null, bytes("saved"))) + var created = false + val missing = object : RecordKeyProvider { + override fun existing() = null + override fun getOrCreate() = key.also { created = true } + } + val vault = ProtectedRecordStore(temporary.root, RecordCipher(missing)) + refuses(StorageProblem.KeyMissing) { vault.read(binding) } + assertFalse(created) + assertArrayEquals(bytes("saved"), store().read(binding)) + } + + @Test fun providerRuntimeFailuresAreTypedOnEncryptAndDecrypt() { + val provider = object : RecordKeyProvider { + override fun existing() = key + override fun getOrCreate() = key + } + val broken = RecordCipher(provider) { throw ProviderException("synthetic provider failure") } + refuses(StorageProblem.KeyUnavailable) { broken.encrypt(binding, bytes("secret")) } + val envelope = RecordCipher { key }.encrypt(binding, bytes("secret")) + refuses(StorageProblem.KeyUnavailable) { broken.decrypt(binding, envelope) } + } + + @Test fun unreadableRecordsCanBeExplicitlyDiscardedWithoutDeletingValidOnes() { + val vault = store() + assertFalse(vault.discardUnreadable(binding)) + assertTrue(vault.compareAndSet(binding, null, bytes("saved"))) + assertFalse(vault.discardUnreadable(binding)) + val file = temporary.root.listFiles()!!.single { it.extension == "sealed" } + file.writeBytes(byteArrayOf(1, 2, 3)) + assertTrue(vault.discardUnreadable(binding)) + assertNull(vault.read(binding)) + assertTrue(vault.compareAndSet(binding, null, bytes("new-sign-in"))) + } + + @Test fun aTransientKeyFailureCannotDiscardAnyRecord() { + assertTrue(store().compareAndSet(binding, null, bytes("saved"))) + val broken = ProtectedRecordStore(temporary.root, RecordCipher { throw ProviderException("unavailable") }) + refuses(StorageProblem.KeyUnavailable) { broken.discardUnreadable(binding) } + assertArrayEquals(bytes("saved"), store().read(binding)) + } + + @Test fun theReadBudgetStopsAnOversizedInputAfterOneExcessByte() { + assertTrue(store().compareAndSet(binding, null, bytes("saved"))) + var consumed = 0 + val io = object : RecordFileOperations by SystemRecordFileOperations { + override fun read(file: File): InputStream = object : FilterInputStream(ByteArray(70_000).inputStream()) { + override fun read(bytes: ByteArray, offset: Int, length: Int): Int = + super.read(bytes, offset, length).also { if (it > 0) consumed += it } + } + } + val vault = ProtectedRecordStore(temporary.root, RecordCipher { key }, io) + refuses(StorageProblem.RecordTooLarge) { vault.read(binding) } + assertEquals(RecordCipher.MAXIMUM_ENVELOPE_BYTES + 1, consumed) + } + + @Test fun partialWriteAndMoveFailureLeaveThePreviousRecordReadable() { + val original = bytes("saved") + assertTrue(store().compareAndSet(binding, null, original)) + val failures = listOf( + object : RecordFileOperations by SystemRecordFileOperations { + override fun write(file: File): FileOutputStream = object : FileOutputStream(file) { + override fun write(bytes: ByteArray) { + super.write(bytes, 0, minOf(8, bytes.size)) + throw IOException("synthetic interrupted write") + } + } + }, + object : RecordFileOperations by SystemRecordFileOperations { + override fun move(from: Path, to: Path) { throw IOException("synthetic failed move") } + }, + ) + for (io in failures) { + val vault = ProtectedRecordStore(temporary.root, RecordCipher { key }, io) + refuses(StorageProblem.DiskUnavailable) { vault.compareAndSet(binding, original, bytes("replacement")) } + assertArrayEquals(original, store().read(binding)) + assertFalse(temporary.root.listFiles()!!.any { it.extension == "pending" }) + } + } + + @Test fun malformedOpaqueKeysNeverCollapseToAQuestionMark() { + val vault = store() + assertTrue(vault.compareAndSet("?", null, bytes("valid"))) + refuses(StorageProblem.InvalidBinding) { vault.read("\ud800") } + refuses(StorageProblem.InvalidBinding) { vault.compareAndSet("\udc00", null, bytes("invalid")) } + assertArrayEquals(bytes("valid"), vault.read("?")) + } + + @Test fun directorySyncFailureCanFollowACommittedReplaceAndNeedsReadback() { + assumeTrue(System.getProperty("user.name") != "root") + assumeTrue(temporary.root.toPath().fileSystem.supportedFileAttributeViews().contains("posix")) + val vault = store() + val original = bytes("saved") + val next = bytes("rotated") + assertTrue(vault.compareAndSet(binding, null, original)) + val mode = Files.getPosixFilePermissions(temporary.root.toPath()) + try { + Files.setPosixFilePermissions( + temporary.root.toPath(), + java.nio.file.attribute.PosixFilePermissions.fromString("-wx------"), + ) + refuses(StorageProblem.DiskUnavailable) { vault.compareAndSet(binding, original, next) } + } finally { + Files.setPosixFilePermissions(temporary.root.toPath(), mode) + } + assertArrayEquals(next, vault.read(binding)) + } + private fun refuses(problem: StorageProblem, action: () -> Unit) { try { action() From f421b45e70371ad01610d62f8d74c145b219d08d Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:04:36 -0500 Subject: [PATCH 10/18] Restrict record-key helpers and record verified Android storage --- .../src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt | 2 +- .../app/bighelp/android/storage/ProtectedRecordStoreTest.kt | 1 + docs/ANDROID_PARITY.md | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt b/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt index 0231b543..1e396cd4 100644 --- a/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt +++ b/android/app/src/main/kotlin/app/bighelp/android/storage/RecordCipher.kt @@ -26,7 +26,7 @@ class RecordCipher internal constructor( private val cipherFactory: () -> Cipher, ) { constructor(keys: RecordKeyProvider) : this(keys, { Cipher.getInstance("AES/GCM/NoPadding") }) - constructor(key: () -> SecretKey) : this(object : RecordKeyProvider { + internal constructor(key: () -> SecretKey) : this(object : RecordKeyProvider { override fun existing() = key() override fun getOrCreate() = key() }) diff --git a/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt b/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt index 58233947..6d8fc053 100644 --- a/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt +++ b/android/app/src/test/kotlin/app/bighelp/android/storage/ProtectedRecordStoreTest.kt @@ -177,6 +177,7 @@ class ProtectedRecordStoreTest { Files.createSymbolicLink(file, file.fileName) refuses(StorageProblem.DiskUnavailable) { vault.read(binding) } refuses(StorageProblem.DiskUnavailable) { vault.compareAndSet(binding, null, bytes("replacement")) } + refuses(StorageProblem.DiskUnavailable) { vault.discardUnreadable(binding) } assertTrue(Files.isSymbolicLink(file)) } diff --git a/docs/ANDROID_PARITY.md b/docs/ANDROID_PARITY.md index 1e85a113..e58e3512 100644 --- a/docs/ANDROID_PARITY.md +++ b/docs/ANDROID_PARITY.md @@ -12,7 +12,7 @@ Contract references below name chapters under `docs/hermes/`, with product refer | Proxy access | Independent proxy headers, private HTTP consent and prefix-safe paths | CONNECTION.md §§1–2 | In progress: Task 1 | Endpoint tests exist; full proxy pending | | Gateway | Ready deadline, ticket subprotocol, ordered RPC/events, heartbeat and reconnect | CONNECTION.md §§7–10 | In progress: Task 1 | Pending | | Prompts | Questions, approval, secret/sudo and exact cancellation ownership | CHAT.md §§8–9 | Not started | Pending | -| Saved computers | Encrypted credentials, add/select/remove, restore exact principal | CONNECTION.md §6 | Not started | Pending | +| Saved computers | Encrypted credentials, add/select/remove, restore exact principal | CONNECTION.md §6 | In progress: verified Keystore backing; live composition pending | 22 storage JVM cases and 5 API36 instrumentation cases pass | | Agents and Bots | Real directory and canonical Bot Chats; edit instructions, model, appearance | REFERENCE.md §Profiles | Not started | Pending | | Sessions | Catalog, create/resume, search, rename, archive/restore/delete/fork | CHAT.md §§1–3,11 | Not started | Pending | | Live chat | Streaming, tools, segment finals and authoritative turn terminal | CHAT.md §§4,7 | Not started | Pending | From 32a6ee9c5b7d7f336c61bdaceb92b1adc0f358c8 Mon Sep 17 00:00:00 2001 From: Colt Coan <59135406+promptclickrun@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:30:03 -0500 Subject: [PATCH 11/18] Add real Hermes authentication and ordered gateway transport --- android/hermes/build.gradle.kts | 8 +- .../app/bighelp/hermes/BrowserSignIn.kt | 279 ++++++ .../app/bighelp/hermes/GatewayClient.kt | 894 ++++++++++++++++++ .../kotlin/app/bighelp/hermes/GatewayTypes.kt | 98 ++ .../kotlin/app/bighelp/hermes/HermesAccess.kt | 134 +++ .../app/bighelp/hermes/HermesAuthParsers.kt | 231 +++++ .../app/bighelp/hermes/HermesAuthTypes.kt | 84 ++ .../app/bighelp/hermes/HermesAuthenticator.kt | 663 +++++++++++++ .../app/bighelp/hermes/HermesCredentials.kt | 213 +++++ .../app/bighelp/hermes/HermesException.kt | 50 + .../kotlin/app/bighelp/hermes/HermesHttp.kt | 100 ++ .../app/bighelp/hermes/HermesHttpLimits.kt | 105 ++ .../app/bighelp/hermes/HermesSecrets.kt | 27 + .../app/bighelp/hermes/OkHttpHermesHttp.kt | 240 +++++ .../app/bighelp/hermes/ServerRequestTable.kt | 56 ++ .../app/bighelp/hermes/GatewayFramingTest.kt | 144 +++ .../bighelp/hermes/GatewayHandshakeTest.kt | 284 ++++++ .../app/bighelp/hermes/GatewayRecoveryTest.kt | 193 ++++ .../app/bighelp/hermes/GatewayRpcTest.kt | 239 +++++ .../hermes/GatewayServerRequestTest.kt | 266 ++++++ .../app/bighelp/hermes/GatewayTestSupport.kt | 99 ++ .../app/bighelp/hermes/HermesAccessTest.kt | 119 +++ .../bighelp/hermes/HermesAuthParsersTest.kt | 234 +++++ .../hermes/HermesAuthenticatorBrowserTest.kt | 203 ++++ .../hermes/HermesAuthenticatorSessionTest.kt | 521 ++++++++++ .../hermes/HermesAuthenticatorSignInTest.kt | 366 +++++++ .../hermes/LoopbackCallbackListenerTest.kt | 231 +++++ .../bighelp/hermes/OkHttpHermesHttpTest.kt | 399 ++++++++ .../hermes/OkHttpWebSocketNegotiationTest.kt | 77 ++ .../bighelp/hermes/RealHostIntegrationTest.kt | 352 +++++++ .../app/bighelp/hermes/SavedConnectionTest.kt | 139 +++ .../app/bighelp/hermes/ScriptedGateway.kt | 183 ++++ .../kotlin/app/bighelp/hermes/ScriptedHost.kt | 69 ++ 33 files changed, 7299 insertions(+), 1 deletion(-) create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/BrowserSignIn.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayClient.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/GatewayTypes.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAccess.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAuthParsers.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAuthTypes.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesAuthenticator.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesCredentials.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesException.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesHttp.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesHttpLimits.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/HermesSecrets.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/OkHttpHermesHttp.kt create mode 100644 android/hermes/src/main/kotlin/app/bighelp/hermes/ServerRequestTable.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayFramingTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayHandshakeTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayRecoveryTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayRpcTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayServerRequestTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/GatewayTestSupport.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAccessTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthParsersTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorBrowserTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorSessionTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/HermesAuthenticatorSignInTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/LoopbackCallbackListenerTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/OkHttpHermesHttpTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/OkHttpWebSocketNegotiationTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/RealHostIntegrationTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/SavedConnectionTest.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/ScriptedGateway.kt create mode 100644 android/hermes/src/test/kotlin/app/bighelp/hermes/ScriptedHost.kt diff --git a/android/hermes/build.gradle.kts b/android/hermes/build.gradle.kts index 9123188d..a123dbca 100644 --- a/android/hermes/build.gradle.kts +++ b/android/hermes/build.gradle.kts @@ -5,8 +5,14 @@ kotlin { jvmToolchain(17) } dependencies { - implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0") + // Public signatures expose JsonElement and coroutine types, so consumers see them. + api("org.jetbrains.kotlinx:kotlinx-serialization-json:1.9.0") + api("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.10.2") + // OkHttp stays an implementation detail: no public signature mentions its types. + implementation("com.squareup.okhttp3:okhttp:4.12.0") testImplementation("junit:junit:4.13.2") + testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.10.2") + testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0") } tasks.test { val wireVectors = rootProject.file("../docs/hermes/vectors/wire.json") diff --git a/android/hermes/src/main/kotlin/app/bighelp/hermes/BrowserSignIn.kt b/android/hermes/src/main/kotlin/app/bighelp/hermes/BrowserSignIn.kt new file mode 100644 index 00000000..8dbf0da0 --- /dev/null +++ b/android/hermes/src/main/kotlin/app/bighelp/hermes/BrowserSignIn.kt @@ -0,0 +1,279 @@ +package app.bighelp.hermes + +import java.io.ByteArrayOutputStream +import java.io.IOException +import java.net.InetAddress +import java.net.ServerSocket +import java.net.Socket +import java.security.MessageDigest +import java.util.concurrent.ConcurrentHashMap +import java.util.concurrent.atomic.AtomicBoolean +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.TimeoutCancellationException +import kotlinx.coroutines.cancel +import kotlinx.coroutines.coroutineScope +import kotlinx.coroutines.delay +import kotlinx.coroutines.launch +import kotlinx.coroutines.withTimeout + +/** + * The device-local half of browser sign-in. It binds `127.0.0.1` on an OS-chosen port **before** the + * browser is opened, and only a validated HTTP request received here supplies the one-use code: browser + * completion URLs are never consulted and no browser cookie is read. There is no custom URL scheme. + * + * Bad requests (a favicon, a stray probe, a wrong path or state, a slow client) close their own connection + * without consuming the sign-in. At most four connections are served at once, each has + * [AuthTimings.callbackRequestMillis] to deliver its request, and the whole wait is bounded by + * [AuthTimings.browserSignInMillis]. After the code is captured every other connection is closed, a static + * no-store page is flushed (within [AuthTimings.callbackResponseFlushMillis]), and the code is delivered once. + */ +internal class LoopbackCallbackListener private constructor( + private val server: ServerSocket, + private val path: String, + private val state: String, + private val timings: AuthTimings, +) : AutoCloseable { + val port: Int = server.localPort + val callbackUrl: String = "http://127.0.0.1:$port$path" + val boundAddress: String get() = server.inetAddress.hostAddress.orEmpty() + + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) + private val result = CompletableDeferred