Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion app/src/main/java/dev/r1ptt/data/Config.kt
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@ data class HermesLink(
val passthrough: Boolean = false,
/** The owner's own phone number; only its texts reach Hermes. */
val owner: String = "",
/**
* SMS sender numbers can be spoofed, so when set, [owner]'s texts reach Hermes only if they start
* with this, and Hermes gets them without it. Blank relays every text from [owner].
*/
val passphrase: String = "",
/** The Hermes session that holds the SMS conversation. */
val smsSession: String = "robotos-sms",
/** Texts Hermes may send through this R1 per day (0 = no limit). */
Expand All @@ -100,7 +105,17 @@ data class HermesLink(
val allowOpenApps: Boolean = false,
) {
fun valid(): Boolean = (!deviceApi || (token.length in 32..256 && port in 1024..65535)) &&
(!passthrough || dev.r1ptt.messages.SmsAddress.normalize(owner) == owner) && smsSession.length in 1..128
(!passthrough || dev.r1ptt.messages.SmsAddress.normalize(owner) == owner) && smsSession.length in 1..128 &&
(passphrase.isEmpty() || validPassphrase(passphrase))

companion object {
const val PASSPHRASE_MIN = 6
const val PASSPHRASE_MAX = 64

/** Something the owner can type at the start of a text: one line, no spaces around it. */
fun validPassphrase(value: String) = value.length in PASSPHRASE_MIN..PASSPHRASE_MAX && value == value.trim() &&
value.none { it == '\n' || it == '\r' }
}
}

data class Config(
Expand Down
5 changes: 3 additions & 2 deletions app/src/main/java/dev/r1ptt/data/ConfigJson.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ object ConfigJson {
})
put("hermes", JSONObject().apply {
put("deviceApi", c.hermes.deviceApi); put("token", c.hermes.token); put("port", c.hermes.port)
put("passthrough", c.hermes.passthrough); put("owner", c.hermes.owner)
put("passthrough", c.hermes.passthrough); put("owner", c.hermes.owner); put("passphrase", c.hermes.passphrase)
put("smsSession", c.hermes.smsSession); put("dailySendLimit", c.hermes.dailySendLimit)
put("allowSpeak", c.hermes.allowSpeak); put("allowShow", c.hermes.allowShow)
put("allowVolume", c.hermes.allowVolume); put("allowSaveRecipient", c.hermes.allowSaveRecipient)
Expand Down Expand Up @@ -99,13 +99,14 @@ object ConfigJson {
deviceApi = h.bool("deviceApi", base.hermes.deviceApi), token = h.str("token", base.hermes.token),
port = h.int("port", base.hermes.port), passthrough = h.bool("passthrough", base.hermes.passthrough),
owner = h.str("owner", base.hermes.owner).let { dev.r1ptt.messages.SmsAddress.normalize(it) ?: it },
passphrase = h.str("passphrase", base.hermes.passphrase),
smsSession = h.str("smsSession", base.hermes.smsSession),
dailySendLimit = h.int("dailySendLimit", base.hermes.dailySendLimit),
allowSpeak = h.bool("allowSpeak", base.hermes.allowSpeak), allowShow = h.bool("allowShow", base.hermes.allowShow),
allowVolume = h.bool("allowVolume", base.hermes.allowVolume),
allowSaveRecipient = h.bool("allowSaveRecipient", base.hermes.allowSaveRecipient),
allowOpenApps = h.bool("allowOpenApps", base.hermes.allowOpenApps),
).also { require(it.valid()) { "Hermes needs a 32+ character device token and the owner's full phone number." } } } ?: base.hermes,
).also { require(it.valid()) { "Hermes needs a 32+ character device token, the owner's full phone number and, if set, a 6–64 character passphrase." } } } ?: base.hermes,
earcons = j.bool("earcons", base.earcons),
quiet = j.bool("quiet", base.quiet),
textSizeSp = j.int("textSizeSp", base.textSizeSp),
Expand Down
9 changes: 8 additions & 1 deletion app/src/main/java/dev/r1ptt/hermes/DeviceApi.kt
Original file line number Diff line number Diff line change
Expand Up @@ -409,9 +409,16 @@ class DeviceApi(
}

private fun message(r: SmsRecord) = JSONObject().put("id", r.id).put("direction", if (r.incoming) "in" else "out")
.put("at", Instant.ofEpochMilli(r.createdAt).toString()).put("body", r.body)
.put("at", Instant.ofEpochMilli(r.createdAt).toString()).put("body", visible(r))
.put("status", if (r.incoming) "received" else r.status(clock()).name.lowercase())

/** The owner's texts as Hermes got them through the relay: without the passphrase. */
private fun visible(r: SmsRecord): String {
val link = app.store.value.hermes
return if (r.incoming && link.passphrase.isNotEmpty() && SmsRecipientText.sameNumber(r.peer, link.owner, SmsRecipientText.region(app)))
HermesTexts.redact(r.body, link.passphrase) else r.body
}

private fun describe(r: SmsRecord) = JSONObject().put("id", r.id).put("to", r.peer).put("parts", r.parts.size)
.put("status", r.status(clock()).name.lowercase())
.put("error_codes", JSONArray(r.parts.mapNotNull { it.error }))
Expand Down
15 changes: 15 additions & 0 deletions app/src/main/java/dev/r1ptt/hermes/HermesActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ class HermesActivity : DeviceActivity() {
private lateinit var tasks: LinearLayout
private lateinit var act: Switch
private lateinit var passthrough: Switch
private lateinit var passphrase: EditText
private lateinit var owner: EditText
private lateinit var name: EditText
private var initialName = ""
Expand Down Expand Up @@ -113,6 +114,15 @@ class HermesActivity : DeviceActivity() {
body.addView(ui.section("Your texts to $agent"))
passthrough = ui.toggle("Relay my texts to $agent", cfg.hermes.passthrough); body.addView(passthrough)
body.addView(ui.note("Only texts from your number are relayed. $agent replies by SMS."))
passphrase = ui.field("Passphrase · ${HermesLink.PASSPHRASE_MIN} or more characters", cfg.hermes.passphrase,
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD).apply {
contentDescription = "Passphrase for your texts to $agent"
filters = arrayOf(InputFilter.LengthFilter(HermesLink.PASSPHRASE_MAX))
}
body.addView(passphrase)
body.addView(ui.note("A text can fake your number. With a passphrase, only your texts that start with it are relayed, " +
"and $agent never sees it. Without one, a faked text could use $agent and its tools. " +
"${HermesTexts.MISS_LIMIT} texts without it in an hour pause the relay."))
body.addView(ui.section("Text limit"))
limit = ui.field("Texts per day · 0 for unlimited", cfg.hermes.dailySendLimit.toString(), InputType.TYPE_CLASS_NUMBER)
body.addView(limit)
Expand Down Expand Up @@ -327,6 +337,10 @@ class HermesActivity : DeviceActivity() {
if (number == null || (passthrough.isChecked && number.isEmpty())) { toast("Enter your phone number with its country code"); return }
val perDay = limit.text.toString().trim().toIntOrNull()
if (perDay == null || perDay !in 0..10_000) { toast("Enter a daily limit from 0 to 10000"); return }
val phrase = passphrase.text.toString().trim()
if (phrase.isNotEmpty() && !HermesLink.validPassphrase(phrase)) {
toast("Use a passphrase of ${HermesLink.PASSPHRASE_MIN} to ${HermesLink.PASSPHRASE_MAX} characters, or leave it empty"); return
}
val typed = name.text.toString().trim()
val newName = if (typed.isEmpty()) "" else Agent.cleanName(typed)
?: run { toast("Use letters or numbers for the name, with spaces, apostrophes, hyphens or periods"); return }
Expand All @@ -339,6 +353,7 @@ class HermesActivity : DeviceActivity() {
deviceApi = if (act.isChecked != initialLink.deviceApi) act.isChecked && act.isEnabled else current.deviceApi,
passthrough = if (passthrough.isChecked != initialLink.passthrough) passthrough.isChecked else current.passthrough,
owner = if (owner.text.toString() != initialLink.owner) number else current.owner,
passphrase = if (phrase != initialLink.passphrase) phrase else current.passphrase,
dailySendLimit = if (perDay != initialLink.dailySendLimit) perDay else current.dailySendLimit,
allowSpeak = if (speak.isChecked != initialLink.allowSpeak) speak.isChecked else current.allowSpeak,
allowShow = if (show.isChecked != initialLink.allowShow) show.isChecked else current.allowShow,
Expand Down
82 changes: 72 additions & 10 deletions app/src/main/java/dev/r1ptt/hermes/HermesTexts.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import android.util.Log
import dev.r1ptt.App
import dev.r1ptt.data.Msg
import dev.r1ptt.data.Config
import dev.r1ptt.data.EventLog
import dev.r1ptt.data.HermesLink
import dev.r1ptt.messages.SmsDraft
import dev.r1ptt.messages.SmsRecipientText
import dev.r1ptt.messages.SmsRecord
Expand All @@ -20,12 +22,17 @@ import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import java.security.MessageDigest
import kotlin.math.abs

/**
* The owner texting this R1's number is texting Hermes: each text goes to Hermes in its own SMS
* session and the reply is texted back. Texts from anyone else stay in Messages. Hermes can act on
* the R1 meanwhile (for example, text someone else) through its robotos tools.
*
* Sender numbers can be spoofed, so with a passphrase set only the owner's texts that start with it
* are relayed, without it. [MISS_LIMIT] texts from the owner's number without it in an hour pause
* the relay, which keeps a short passphrase from being guessed.
*
* Pending texts survive a restart and are retried with backoff for [GIVE_UP_MS]; after that the owner
* gets one short notice instead of silence. A reply is never sent twice for one text.
*/
Expand All @@ -50,8 +57,10 @@ class HermesTexts(
if (!SmsRecipientText.sameNumber(record.peer, link.owner, SmsRecipientText.region(app))) return false
synchronized(prefs) {
if (prefs.contains("pending.${record.id}") || prefs.getBoolean("done.${record.id}", false)) return true
if (link.passphrase.isNotEmpty() && !unlocked(record, link)) return false
if (request(record.body, link.passphrase) == null) return false // the passphrase alone asks nothing
prefs.edit().putLong("pending.${record.id}", clock()).putString("owner.${record.id}", link.owner)
.putString("connection.${record.id}", connection(app)).commit()
.putString("connection.${record.id}", connection(app)).putBoolean("gated.${record.id}", link.passphrase.isNotEmpty()).commit()
}
Log.i(TAG, "hermes text: received from owner")
worker.execute(::drain)
Expand All @@ -67,17 +76,44 @@ class HermesTexts(

private fun done(id: String) = synchronized(prefs) {
val edit = prefs.edit().remove("pending.$id").remove("tries.$id").remove("answer.$id")
.remove("owner.$id").remove("connection.$id").remove("asking.$id").remove("replying.$id").remove("recovery_wait.$id")
.remove("owner.$id").remove("connection.$id").remove("gated.$id").remove("asking.$id").remove("replying.$id").remove("recovery_wait.$id")
.putBoolean("done.$id", true)
// Incoming SMS records are the durable source; bound this additional deduplication cache.
prefs.all.keys.filter { it.startsWith("done.") }.dropLast(511).forEach { edit.remove(it) }
edit.commit()
}

private fun authorityAllowed(record: SmsRecord, owner: String, connection: String): Boolean {
/**
* Checks an owner text against the passphrase, with prefs locked. A text without it is a miss, and
* while the last hour holds [MISS_LIMIT] misses even a correct one stays in Messages.
*/
private fun unlocked(record: SmsRecord, link: HermesLink): Boolean {
val now = clock()
val opened = after(record.body, link.passphrase) != null
val recent = prefs.getString("misses", "").orEmpty().split(',').mapNotNull { it.toLongOrNull() }
.filter { abs(now - it) < MISS_WINDOW_MS }
val misses = if (opened) recent else (recent + now).takeLast(MISS_LIMIT)
if (!opened) prefs.edit().putString("misses", misses.joinToString(",")).commit()
val paused = misses.size >= MISS_LIMIT
when {
paused -> {
last = "Relay paused: $MISS_LIMIT texts from your number in the last hour didn't start with the passphrase"
EventLog.record("hermes text: relay paused after texts from the owner's number without the passphrase")
}
!opened -> {
last = "A text from your number didn't start with the passphrase, so it stayed in Messages"
EventLog.record("hermes text: owner's number without the passphrase, kept in Messages")
}
}
return opened && !paused
}

/** Passthrough, owner, connection and passphrase are all as they were when the text arrived. */
private fun authorityAllowed(record: SmsRecord, owner: String, connection: String, gated: Boolean): Boolean {
val link = app.store.value.hermes
return !app.workspace.quarantined && link.passthrough && link.owner == owner && connection(app) == connection &&
SmsRecipientText.sameNumber(record.peer, owner, SmsRecipientText.region(app))
SmsRecipientText.sameNumber(record.peer, owner, SmsRecipientText.region(app)) &&
link.passphrase.isNotEmpty() == gated && request(record.body, link.passphrase) != null
}

private fun drain() {
Expand All @@ -99,8 +135,9 @@ class HermesTexts(
private fun process(record: SmsRecord, since: Long): Boolean {
val owner = prefs.getString("owner.${record.id}", null)
val connection = prefs.getString("connection.${record.id}", null)
val gated = prefs.getBoolean("gated.${record.id}", false)
// Old unbound queued work cannot safely acquire a different owner's authority on upgrade.
if (owner == null || connection == null || !authorityAllowed(record, owner, connection)) {
if (owner == null || connection == null || !authorityAllowed(record, owner, connection, gated)) {
last = "A queued text was kept in Messages because relay access changed"
return true
}
Expand Down Expand Up @@ -132,14 +169,16 @@ class HermesTexts(
"robotOS couldn't reach Hermes. Your text is saved in Messages; no request was submitted."
} else {
val config = app.store.value
if (!authorityAllowed(record, owner, connection)) return true
if (!authorityAllowed(record, owner, connection, gated)) return true
// Hermes never sees the passphrase.
val text = request(record.body, config.hermes.passphrase) ?: return true
if (!app.workspace.networkAllowed) { app.workspace.recoverNow(); return false }
check(prefs.edit().putBoolean("asking.${record.id}", true).commit())
try { (ask?.invoke(record.body) ?: if (app.workspace.identity.paired) runBlocking {
try { (ask?.invoke(text) ?: if (app.workspace.identity.paired) runBlocking {
val deviceId = app.workspace.identity.value.getString("device_id")
SharedChat.ask(app, "shared-sms-$deviceId", record.body,
SharedChat.ask(app, "shared-sms-$deviceId", text,
STYLE + " This request came through robotOS device_id=$deviceId. Target that exact device_id for device tools unless the user explicitly chooses another device.")
} else askHermes(config, record.body)).trim() }
} else askHermes(config, text)).trim() }
catch (e: Exception) {
Log.w(TAG, "hermes text: ${e.javaClass.simpleName}")
// Legacy chat has no durable idempotency contract. Never replay possible actions.
Expand All @@ -150,7 +189,7 @@ class HermesTexts(
check(prefs.edit().putString("answer.${record.id}", answer).commit())
answer
}
if (!authorityAllowed(record, owner, connection)) {
if (!authorityAllowed(record, owner, connection, gated)) {
last = "Reply cancelled because relay access changed"
return true
}
Expand Down Expand Up @@ -184,6 +223,9 @@ class HermesTexts(
companion object {
private const val TAG = "r1ptt"
const val GIVE_UP_MS = 30 * 60_000L
/** Texts from the owner's number without the passphrase that pause the relay, per [MISS_WINDOW_MS]. */
const val MISS_LIMIT = 5
const val MISS_WINDOW_MS = 60 * 60_000L
/** Long agent answers become several SMS parts; past this, the text says it was cut. */
const val MAX_REPLY_CHARS = 1200
private const val UNKNOWN = "Hermes's response was interrupted and the outcome is unknown. Your request may have run. Check Hermes before asking it to perform the action again."
Expand All @@ -204,6 +246,26 @@ class HermesTexts(

fun fit(text: String): String = if (text.length <= MAX_REPLY_CHARS) text else text.take(MAX_REPLY_CHARS - 1).trimEnd() + "…"

/**
* What an owner text asks Hermes: [body] after [passphrase], or null when it doesn't start with it
* or asks nothing. Case is ignored (keyboards capitalize the first word), and the passphrase must
* be followed by a space, a colon or a comma, or end the text. Blank [passphrase]: the body as is.
*/
fun request(body: String, passphrase: String): String? =
(if (passphrase.isEmpty()) body else after(body, passphrase))?.takeIf { it.isNotBlank() }

/** [body] without a leading [passphrase], so Hermes reading the owner's texts never sees it. */
fun redact(body: String, passphrase: String): String = if (passphrase.isEmpty()) body else after(body, passphrase) ?: body

private fun after(body: String, passphrase: String): String? {
val text = body.trimStart()
if (!text.startsWith(passphrase, ignoreCase = true)) return null
val rest = text.substring(passphrase.length)
if (rest.isNotEmpty() && !rest[0].isWhitespace() && rest[0] !in SEPARATORS) return null
return rest.trimStart { it.isWhitespace() || it in SEPARATORS }
}
private const val SEPARATORS = ":,"

private fun askHermes(cfg: Config, text: String): String {
val req = ChatRequest.build(cfg.copy(systemPrompt = STYLE), listOf(Msg(Msg.USER, text)), "", session = cfg.hermes.smsSession)
return ChatClient().stream(req, CallRegistry(), {}, {})
Expand Down
13 changes: 13 additions & 0 deletions app/src/test/java/dev/r1ptt/data/ConfigJsonTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@ class ConfigJsonTest {
assertEquals(7, ConfigJson.merge(reachable, JSONObject("""{"power":{"stayReachable":false}}""")).power.wifiIdleMinutes)
}

@Test fun aRelayPassphraseRoundTripsAndMustBeTypeable() {
val token = "x".repeat(32)
val gated = ConfigJson.merge(Config(), JSONObject("""{"hermes":{"deviceApi":true,"token":"$token","passphrase":"otter-42"}}"""))
assertEquals("otter-42", gated.hermes.passphrase)
assertEquals(gated, ConfigJson.merge(Config(), ConfigJson.toJson(gated)))
assertEquals("otter-42", ConfigJson.merge(gated, JSONObject("""{"hermes":{"dailySendLimit":5}}""")).hermes.passphrase)
assertEquals("", ConfigJson.merge(gated, JSONObject("""{"hermes":{"passphrase":""}}""")).hermes.passphrase)
listOf("short", " otter-42", "otter\n42", "x".repeat(HermesLink.PASSPHRASE_MAX + 1)).forEach { bad ->
assertFalse(bad, HermesLink.validPassphrase(bad))
assertTrue(bad, runCatching { ConfigJson.merge(gated, JSONObject().put("hermes", JSONObject().put("passphrase", bad))) }.isFailure)
}
}

@Test fun theAgentsNameIsTidiedAndAnInvalidOneIsIgnored() {
assertEquals("Robot", Agent.cleanName(" Robot "))
assertEquals("Mr. Robot", Agent.cleanName("Mr. Robot"))
Expand Down
Loading
Loading