Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

fix(devices): accept the numeric pairingExpiresAt and surface a refused register\n\nTwo defects found while reviewing this PR, both in the path #5871 reports.\n\n**The backend sends `pairingExpiresAt` as a number.** `TunnelRegisterAck`\n(backend `socketHandlers/tunnel/types.ts`) types it `number` and `handler.ts`\nfills it with `Date.getTime()`, but the field here is `String` with no custom\ndeserializer — so a *successful* register ACK could not deserialize at all\n(`invalid type: integer, expected a string`). Accept either shape and normalise\nepoch milliseconds to ISO 8601, rather than widening the field to `i64`:\n`PairingSession::expires_at` and `CreatePairingResponse::expires_at` are both\ndocumented as ISO 8601 and are handed to the paired device.\n\n**A refused register was reported as a client parse error.** The backend answers\nfailures with `{ ok: false, error }` and no `channelId`; feeding that to the\nsuccess shape yields `missing field 'channelId'` — verbatim the error in #5871 —\nand discards the reason the backend gave. Check the failure envelope first and\nreturn the backend's message.\n\nThe ACK decision moved into `parse_register_ack` so it is reachable without a\nlive `SocketManager`. That is not cosmetic: the first version of these tests\nasserted on the `backend_ack_error` predicate alone, and a revert-check showed\nthey still passed with the check deleted from the call path — they pinned the\nhelper, not the behaviour. Testing through `parse_register_ack` fixes that.\n\nRevert-checked, each fix separately, because one revert cannot exercise both:\n\n - envelope check removed -> 2 failures, both naming their own assertion\n - deserializer detached -> 2 failures, including the successful-ack case\n - baseline and restored -> 7/7\n\nThe camelCase/snake_case aliases from the original commits are kept: they are\nadditive and harmless. Note for the author — the PR body's premise looks\ninverted. Backend #709 *introduced* the camelCase shape (its own diff adds\n`+ channelId: string;` and `+ pairingExpiresAt: number;`) and `main` still sends\nit, so the aliases match a shape nothing currently emits. The body also\ndescribes logging `raw ack = {ack}`, which would put the `pairing_token` bearer\ncredential in logs; the code correctly logs key names only.\n

M3gA-Mind4afc8bb49d0b
diff --git a/src/openhuman/security/devices/tunnel_client.rs b/src/openhuman/security/devices/tunnel_client.rs
index 61e49f9578..76b00fcc46 100644
--- a/src/openhuman/security/devices/tunnel_client.rs
+++ b/src/openhuman/security/devices/tunnel_client.rs
@@ -34,10 +34,51 @@ pub struct TunnelRegisterResponse {
pub channel_id: String,
#[serde(rename = "pairingToken", alias = "pairing_token")]
pub pairing_token: String,
- #[serde(rename = "pairingExpiresAt", alias = "pairing_expires_at")]
+ /// Deserialized through [`expires_at_from_string_or_epoch_millis`]: the
+ /// backend sends this as a JSON **number** (`pairingExpiresAt:
+ /// r.pairingExpiresAt.getTime()` in `socketHandlers/tunnel/handler.ts`),
+ /// while the field — and `PairingSession::expires_at` downstream — is
+ /// documented and consumed as an ISO 8601 string.
+ #[serde(
+ rename = "pairingExpiresAt",
+ alias = "pairing_expires_at",
+ deserialize_with = "expires_at_from_string_or_epoch_millis"
+ )]
pub pairing_expires_at: String,
}
+/// Accept `pairingExpiresAt` as either an ISO 8601 string or epoch
+/// milliseconds, always yielding the ISO 8601 string the rest of the domain
+/// expects.
+///
+/// The backend's `TunnelRegisterAck` types this field as `number` and fills it
+/// with `Date.getTime()`, so a plain `String` field cannot deserialize a
+/// successful ACK at all — it fails with `invalid type: integer, expected a
+/// string`. Widening to `i64` instead would push the epoch value into
+/// `PairingSession::expires_at` and `CreatePairingResponse::expires_at`, both
+/// documented as "ISO 8601 timestamp" and handed to the paired device, so the
+/// conversion happens here where the wire shape is known.
+fn expires_at_from_string_or_epoch_millis<'de, D>(deserializer: D) -> Result<String, D::Error>
+where
+ D: serde::Deserializer<'de>,
+{
+ use serde::de::Error as _;
+
+ #[derive(Deserialize)]
+ #[serde(untagged)]
+ enum Raw {
+ Text(String),
+ EpochMillis(i64),
+ }
+
+ match Raw::deserialize(deserializer)? {
+ Raw::Text(text) => Ok(text),
+ Raw::EpochMillis(millis) => chrono::DateTime::from_timestamp_millis(millis)
+ .map(|dt| dt.to_rfc3339())
+ .ok_or_else(|| D::Error::custom(format!("pairingExpiresAt out of range: {millis}"))),
+ }
+}
+
/// Payload emitted as `tunnel:connect` to join a channel.
#[derive(Debug, Serialize)]
pub struct TunnelConnectPayload {
@@ -91,6 +132,28 @@ pub async fn emit_register() -> Result<TunnelRegisterResponse, String> {
.await
.map_err(|e| format!("[devices/tunnel] emit tunnel:register failed: {e}"))?;
+ parse_register_ack(ack)
+}
+
+/// Turn a `tunnel:register` ACK into a response or an error message.
+///
+/// Split out of [`emit_register`] so the whole decision — failure envelope
+/// first, success shape second — is reachable without a live `SocketManager`.
+/// Testing only the [`backend_ack_error`] predicate would not have caught the
+/// envelope check being dropped from the call path, which is the regression
+/// that matters.
+pub(crate) fn parse_register_ack(ack: serde_json::Value) -> Result<TunnelRegisterResponse, String> {
+ // A failed register is answered with `{ ok: false, error: "..." }`
+ // (`safeAck<TunnelRegisterAck>(ack, { ok: false, error: publicError(err) })`
+ // in the backend handler), which carries no `channelId`. Parsing that as
+ // the success shape reports `missing field 'channelId'` and throws away the
+ // reason the backend gave — which is exactly what #5871 was: a register
+ // that failed server-side, surfaced to the user as a client parse error.
+ if let Some(error) = backend_ack_error(&ack) {
+ log::error!("[devices/tunnel] tunnel:register refused by backend: {error}");
+ return Err(format!("[devices/tunnel] tunnel:register failed: {error}"));
+ }
+
serde_json::from_value::<TunnelRegisterResponse>(ack.clone()).map_err(|e| {
log::error!(
"[devices/tunnel] parse tunnel:register ack failed: {e}; ack fields = {:?}",
@@ -100,6 +163,26 @@ pub async fn emit_register() -> Result<TunnelRegisterResponse, String> {
})
}
+/// The backend's error message when an ACK carries the `{ ok: false, error }`
+/// failure envelope, or `None` for anything else.
+///
+/// `ok` is only ever present on the failure path — a successful
+/// `TunnelRegisterAck` has no such field — so an ACK carrying `ok: false` is
+/// unambiguously a refusal and its `error` is the only useful thing in it.
+pub(crate) fn backend_ack_error(ack: &serde_json::Value) -> Option<String> {
+ let object = ack.as_object()?;
+ if object.get("ok")?.as_bool()? {
+ return None;
+ }
+ Some(
+ object
+ .get("error")
+ .and_then(|e| e.as_str())
+ .unwrap_or("unspecified error")
+ .to_string(),
+ )
+}
+
/// Emit `tunnel:connect` to start listening on a channel as `role:"core"`.
pub async fn emit_connect(channel_id: &str) -> Result<(), String> {
log::debug!("[devices/tunnel] emit_connect channel_id={channel_id}");
diff --git a/src/openhuman/security/devices/tunnel_client_tests.rs b/src/openhuman/security/devices/tunnel_client_tests.rs
index 5e8a92f248..bc53b11d7d 100644
--- a/src/openhuman/security/devices/tunnel_client_tests.rs
+++ b/src/openhuman/security/devices/tunnel_client_tests.rs
@@ -41,3 +41,87 @@ fn build_core_connect_payload_omits_session_token_for_core_role() {
assert!(payload.get("sessionToken").is_none());
assert!(payload.get("pairingToken").is_none());
}
+
+// ── The shape the backend actually sends (#5871) ──────────────────────────
+
+/// The live backend types `pairingExpiresAt` as a **number** and fills it with
+/// `Date.getTime()` (`TunnelRegisterAck` in `socketHandlers/tunnel/types.ts`,
+/// `handler.ts:102-107`). Before this was handled a *successful* register ACK
+/// could not deserialize at all — `invalid type: integer, expected a string` —
+/// so pairing could not have completed even once register started succeeding.
+///
+/// The epoch value is normalised to ISO 8601 rather than passed through as a
+/// decimal string, because `PairingSession::expires_at` and
+/// `CreatePairingResponse::expires_at` are both documented as ISO 8601 and go
+/// straight to the paired device.
+#[test]
+fn tunnel_register_response_accepts_numeric_pairing_expires_at() {
+ let response: TunnelRegisterResponse = serde_json::from_value(json!({
+ "channelId": "ch_789",
+ "pairingToken": "pt_789",
+ "pairingExpiresAt": 1_790_000_000_000i64
+ }))
+ .expect("the numeric pairingExpiresAt the backend sends should parse");
+
+ assert_eq!(response.channel_id, "ch_789");
+ assert_eq!(
+ response.pairing_expires_at, "2026-09-21T14:13:20+00:00",
+ "epoch milliseconds must be rendered as the ISO 8601 string the rest \
+ of the domain documents and forwards to the paired device"
+ );
+}
+
+/// A register the backend refuses is answered with `{ ok: false, error }` and
+/// no `channelId`. Parsing that as the success shape is what produced the
+/// `missing field 'channelId'` in #5871 — a server-side refusal reported to the
+/// user as a client parse error, with the backend's own explanation discarded.
+#[test]
+fn register_failure_envelope_surfaces_the_backend_error_not_a_parse_error() {
+ let ack = json!({ "ok": false, "error": "tunnel_channel_limit_reached" });
+
+ // Through the real decision path, not the predicate alone. Asserting only
+ // `backend_ack_error` would keep passing if the check were dropped from
+ // that path — which a revert-check caught it doing.
+ let error = parse_register_ack(ack.clone()).expect_err("a refused register must be an error");
+ assert!(
+ error.contains("tunnel_channel_limit_reached"),
+ "the backend's reason must reach the caller, got: {error}"
+ );
+ assert!(
+ !error.contains("channelId"),
+ "the refusal must not be reported as a missing-field parse error (#5871), got: {error}"
+ );
+
+ // What it used to do, and what the check above exists to prevent.
+ let parsed = serde_json::from_value::<TunnelRegisterResponse>(ack);
+ assert!(
+ parsed.unwrap_err().to_string().contains("channelId"),
+ "sanity: the success shape is what produced the misleading error"
+ );
+}
+
+/// A failure envelope with no `error` string still must not be read as success.
+#[test]
+fn register_failure_envelope_without_a_message_is_still_a_failure() {
+ let error = parse_register_ack(json!({ "ok": false }))
+ .expect_err("a refusal with no message is still a refusal");
+ assert!(error.contains("unspecified error"), "got: {error}");
+}
+
+/// A successful ACK carries no `ok` field, so it must not be mistaken for a
+/// refusal — otherwise every successful pairing would be rejected.
+#[test]
+fn a_successful_ack_is_not_treated_as_a_failure_envelope() {
+ let ack = json!({
+ "channelId": "ch_1",
+ "pairingToken": "pt_1",
+ "pairingExpiresAt": 1_790_000_000_000i64
+ });
+ assert!(backend_ack_error(&ack).is_none());
+ assert!(backend_ack_error(&json!({ "ok": true })).is_none());
+
+ // And end to end: a successful ACK must come back as a response, not be
+ // swallowed by the refusal branch.
+ let response = parse_register_ack(ack).expect("a successful ack must parse");
+ assert_eq!(response.channel_id, "ch_1");
+}