Luxe 0.1.3: your sessions on your phone, joinable sessions, and nested AGENTS.md
- luxe remote puts the sessions on your computer in reach of your own phone or tablet over Tailscale: write, steer, answer prompts, send photos, browse files, diffs and GitHub, with a paired device and your own Tailscale login. - luxe join lets another program on the same machine join a running session over the RPC protocol. - An AGENTS.md in a subfolder reaches the model the first time it works there. - Long sessions stay fast: no stall before each model call, lighter memory, cheaper drawing. - A session is open in one Luxe at a time, web_search shares results across its phrasings, and a grep glob starting with ! excludes. The CHANGELOG has the full list.
This commit is contained in:
87
crates/luxe-remote/src/push/api.rs
Normal file
87
crates/luxe-remote/src/push/api.rs
Normal file
@@ -0,0 +1,87 @@
|
||||
//! The routes a device turns its notifications on and off with, behind the paired-device check.
|
||||
//!
|
||||
//! `GET /api/push` gives the key to subscribe with and whether this device is subscribed,
|
||||
//! `PUT /api/push` takes the subscription the browser made, and `DELETE /api/push` stops them.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::extract::State;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::{Extension, Json};
|
||||
|
||||
use super::Subscription;
|
||||
use crate::access::Refusal;
|
||||
use crate::devices::Device;
|
||||
use crate::routes::Bridged;
|
||||
|
||||
/// What the app needs to subscribe, or to show that it has.
|
||||
#[derive(serde::Serialize)]
|
||||
struct PushStatus {
|
||||
/// The bridge's public key, base64url, for `PushManager.subscribe`
|
||||
key: String,
|
||||
/// Whether the bridge has a subscription for this device
|
||||
subscribed: bool,
|
||||
}
|
||||
|
||||
/// The bridge's push key, and whether this device is subscribed.
|
||||
pub(crate) async fn status(
|
||||
State(bridged): State<Arc<Bridged>>,
|
||||
Extension(device): Extension<Device>,
|
||||
) -> Response {
|
||||
let devices = bridged.devices.clone();
|
||||
let key = tokio::task::spawn_blocking(move || devices.push_key()).await;
|
||||
match key {
|
||||
Ok(Ok(vapid)) => {
|
||||
let subscribed = device.subscription().is_some();
|
||||
Json(PushStatus { key: vapid.public_key(), subscribed }).into_response()
|
||||
}
|
||||
Ok(Err(error)) => failed(&error),
|
||||
Err(error) => failed(&error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends this device's notifications to the subscription its browser made.
|
||||
pub(crate) async fn subscribe(
|
||||
State(bridged): State<Arc<Bridged>>,
|
||||
Extension(device): Extension<Device>,
|
||||
Json(subscription): Json<Subscription>,
|
||||
) -> Response {
|
||||
match subscription.checked() {
|
||||
Ok(subscription) => keep(&bridged, &device, Some(subscription)).await,
|
||||
Err(refused) => {
|
||||
tracing::warn!(device = %device.name, %refused, "refused a push subscription");
|
||||
(StatusCode::BAD_REQUEST, refused.to_string()).into_response()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops this device's notifications.
|
||||
pub(crate) async fn unsubscribe(
|
||||
State(bridged): State<Arc<Bridged>>,
|
||||
Extension(device): Extension<Device>,
|
||||
) -> Response {
|
||||
keep(&bridged, &device, None).await
|
||||
}
|
||||
|
||||
async fn keep(bridged: &Bridged, device: &Device, subscription: Option<Subscription>) -> Response {
|
||||
let (devices, id) = (bridged.devices.clone(), device.id.clone());
|
||||
let on = subscription.is_some();
|
||||
let kept = tokio::task::spawn_blocking(move || devices.subscribe(&id, subscription)).await;
|
||||
match kept {
|
||||
Ok(Ok(true)) => {
|
||||
tracing::info!(device = %device.name, on, "a device changed its notifications");
|
||||
StatusCode::NO_CONTENT.into_response()
|
||||
}
|
||||
// revoked since the request was let in
|
||||
Ok(Ok(false)) => Refusal::NotPaired.into_response(),
|
||||
Ok(Err(error)) => failed(&error),
|
||||
Err(error) => failed(&error),
|
||||
}
|
||||
}
|
||||
|
||||
fn failed(error: &dyn std::error::Error) -> Response {
|
||||
tracing::error!(%error, "couldn't read or keep a push subscription");
|
||||
let reason = format!("couldn't keep notifications: {error}");
|
||||
(StatusCode::INTERNAL_SERVER_ERROR, reason).into_response()
|
||||
}
|
||||
120
crates/luxe-remote/src/push/encryption.rs
Normal file
120
crates/luxe-remote/src/push/encryption.rs
Normal file
@@ -0,0 +1,120 @@
|
||||
//! Encryption — a push message sealed for one device, as RFC 8291 has it.
|
||||
//!
|
||||
//! The push service carries the message and can't read it: each one is sealed with a key agreed
|
||||
//! between a throwaway key of the bridge's and the key the device's browser made when it
|
||||
//! subscribed, mixed with the subscription's own secret.
|
||||
|
||||
use ring::rand::SecureRandom;
|
||||
use ring::{aead, agreement, hkdf, rand};
|
||||
|
||||
/// The record size a message declares. One record holds the whole message, which a push service
|
||||
/// caps at 4 KiB anyway.
|
||||
const RECORD_SIZE: u32 = 4096;
|
||||
|
||||
/// Bytes a record adds to its message: the delimiter that ends the last record, and the AES-GCM
|
||||
/// tag.
|
||||
const RECORD_OVERHEAD: usize = 1 + 16;
|
||||
|
||||
/// Why a message couldn't be sealed.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(crate) enum EncryptionError {
|
||||
/// The subscription's key isn't a P-256 point
|
||||
#[error("the subscription's key isn't a P-256 public key")]
|
||||
BadSubscriptionKey,
|
||||
/// The message won't fit one record
|
||||
#[error("a push message of {0} bytes is too long for one record")]
|
||||
TooLong(usize),
|
||||
/// The system's randomness failed
|
||||
#[error("the system's random number source failed")]
|
||||
Random,
|
||||
}
|
||||
|
||||
/// The two secrets a message is sealed with.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
struct ContentKeys {
|
||||
key: [u8; 16],
|
||||
nonce: [u8; 12],
|
||||
}
|
||||
|
||||
/// `message` sealed for the subscription with public key `device_key` and secret `auth`, as the
|
||||
/// body of an `aes128gcm` push request.
|
||||
pub(crate) fn encrypt(
|
||||
message: &[u8],
|
||||
device_key: &[u8],
|
||||
auth: &[u8],
|
||||
) -> Result<Vec<u8>, EncryptionError> {
|
||||
if message.len() + RECORD_OVERHEAD > RECORD_SIZE as usize {
|
||||
return Err(EncryptionError::TooLong(message.len()));
|
||||
}
|
||||
let random = rand::SystemRandom::new();
|
||||
let (ours, our_key) = throwaway_key(&random)?;
|
||||
let mut salt = [0u8; 16];
|
||||
random.fill(&mut salt).map_err(|_| EncryptionError::Random)?;
|
||||
let theirs = agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, device_key);
|
||||
let keys = agreement::agree_ephemeral(ours, &theirs, |shared| {
|
||||
content_keys(shared, auth, device_key, our_key.as_ref(), &salt)
|
||||
})
|
||||
.map_err(|_| EncryptionError::BadSubscriptionKey)?;
|
||||
Ok(seal(&keys, &salt, our_key.as_ref(), message))
|
||||
}
|
||||
|
||||
/// A key pair for one message, so a message read once its key leaks says nothing of the others.
|
||||
fn throwaway_key(
|
||||
random: &rand::SystemRandom,
|
||||
) -> Result<(agreement::EphemeralPrivateKey, agreement::PublicKey), EncryptionError> {
|
||||
let ours = agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, random)
|
||||
.map_err(|_| EncryptionError::Random)?;
|
||||
let public = ours.compute_public_key().map_err(|_| EncryptionError::Random)?;
|
||||
Ok((ours, public))
|
||||
}
|
||||
|
||||
/// The content keys from the agreed secret, RFC 8291 section 3.4: the subscription's secret and
|
||||
/// both public keys are mixed in first, then the message's salt.
|
||||
fn content_keys(
|
||||
shared: &[u8],
|
||||
auth: &[u8],
|
||||
device_key: &[u8],
|
||||
our_key: &[u8],
|
||||
salt: &[u8],
|
||||
) -> ContentKeys {
|
||||
let key_info = [b"WebPush: info\0".as_slice(), device_key, our_key].concat();
|
||||
let combined = hkdf::Salt::new(hkdf::HKDF_SHA256, auth).extract(shared);
|
||||
let keying: [u8; 32] = expand(&combined, &key_info);
|
||||
let content = hkdf::Salt::new(hkdf::HKDF_SHA256, salt).extract(&keying);
|
||||
ContentKeys {
|
||||
key: expand(&content, b"Content-Encoding: aes128gcm\0"),
|
||||
nonce: expand(&content, b"Content-Encoding: nonce\0"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The header (salt, record size, the bridge's key) and then the one sealed record.
|
||||
fn seal(keys: &ContentKeys, salt: &[u8; 16], our_key: &[u8], message: &[u8]) -> Vec<u8> {
|
||||
let mut record = [message, &[2]].concat();
|
||||
let unbound =
|
||||
aead::UnboundKey::new(&aead::AES_128_GCM, &keys.key).expect("16 bytes is an AES-128 key");
|
||||
let nonce = aead::Nonce::assume_unique_for_key(keys.nonce);
|
||||
aead::LessSafeKey::new(unbound)
|
||||
.seal_in_place_append_tag(nonce, aead::Aad::empty(), &mut record)
|
||||
.expect("one record is far below AES-GCM's length limit");
|
||||
let key_length = u8::try_from(our_key.len()).expect("a P-256 point is 65 bytes");
|
||||
let header = [salt.as_slice(), &RECORD_SIZE.to_be_bytes(), &[key_length], our_key].concat();
|
||||
[header, record].concat()
|
||||
}
|
||||
|
||||
/// `N` bytes of HKDF output.
|
||||
fn expand<const N: usize>(key: &hkdf::Prk, info: &[u8]) -> [u8; N] {
|
||||
struct Length(usize);
|
||||
impl hkdf::KeyType for Length {
|
||||
fn len(&self) -> usize {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
let mut out = [0u8; N];
|
||||
key.expand(&[info], Length(N))
|
||||
.and_then(|okm| okm.fill(&mut out))
|
||||
.expect("HKDF-SHA-256 gives up to 8160 bytes");
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
105
crates/luxe-remote/src/push/encryption/tests.rs
Normal file
105
crates/luxe-remote/src/push/encryption/tests.rs
Normal file
@@ -0,0 +1,105 @@
|
||||
use super::*;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use base64::Engine;
|
||||
|
||||
/// RFC 8291 Appendix A, whose values every test here is held to.
|
||||
mod rfc {
|
||||
pub(super) const MESSAGE: &str = "When I grow up, I want to be a watermelon";
|
||||
pub(super) const OUR_KEY: &str =
|
||||
"BP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8";
|
||||
pub(super) const DEVICE_KEY: &str =
|
||||
"BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4";
|
||||
pub(super) const SALT: &str = "DGv6ra1nlYgDCS1FRnbzlw";
|
||||
pub(super) const AUTH: &str = "BTBZMqHH6r4Tts7J_aSIgg";
|
||||
pub(super) const SHARED: &str = "kyrL1jIIOHEzg3sM2ZWRHDRB62YACZhhSlknJ672kSs";
|
||||
pub(super) const CONTENT_KEY: &str = "oIhVW04MRdy2XN9CiKLxTg";
|
||||
pub(super) const NONCE: &str = "4h_95klXJ5E_qnoN";
|
||||
pub(super) const HEADER: &str = "DGv6ra1nlYgDCS1FRnbzlwAAEABBBP4z9KsN6nGRTbVYI_c7VJSPQTBtkgcy27mlmlMoZIIgDll6e3vCYLocInmYWAmS6TlzAC8wEqKK6PBru3jl7A8";
|
||||
pub(super) const SEALED: &str =
|
||||
"8pfeW0KbunFT06SuDKoJH9Ql87S1QUrdirN6GcG7sFz1y1sqLgVi1VhjVkHsUoEsbI_0LpXMuGvnzQ";
|
||||
}
|
||||
|
||||
fn bytes(base64url: &str) -> Vec<u8> {
|
||||
URL_SAFE_NO_PAD.decode(base64url).expect("the RFC's values are base64url")
|
||||
}
|
||||
|
||||
fn rfc_keys() -> ContentKeys {
|
||||
let (shared, auth) = (bytes(rfc::SHARED), bytes(rfc::AUTH));
|
||||
let (device, ours, salt) = (bytes(rfc::DEVICE_KEY), bytes(rfc::OUR_KEY), bytes(rfc::SALT));
|
||||
content_keys(&shared, &auth, &device, &ours, &salt)
|
||||
}
|
||||
|
||||
/// The key and nonce come out as the RFC's do from its agreed secret.
|
||||
///
|
||||
/// The break this catches: any slip in the key schedule (the info strings, which key goes first,
|
||||
/// salt and secret swapped), each of which a device rejects as a message it can't open.
|
||||
#[test]
|
||||
fn the_content_keys_are_the_rfcs() {
|
||||
let keys = rfc_keys();
|
||||
assert_eq!(keys.key.as_slice(), bytes(rfc::CONTENT_KEY));
|
||||
assert_eq!(keys.nonce.as_slice(), bytes(rfc::NONCE));
|
||||
}
|
||||
|
||||
/// The sealed body is the RFC's header and ciphertext, byte for byte.
|
||||
///
|
||||
/// The break this catches: a wrong header field (record size, key length, the device's key where
|
||||
/// ours belongs) or a missing end-of-record delimiter.
|
||||
#[test]
|
||||
fn a_message_is_sealed_as_the_rfcs() {
|
||||
let salt: [u8; 16] = bytes(rfc::SALT).try_into().expect("16 bytes");
|
||||
let body = seal(&rfc_keys(), &salt, &bytes(rfc::OUR_KEY), rfc::MESSAGE.as_bytes());
|
||||
assert_eq!(body, [bytes(rfc::HEADER), bytes(rfc::SEALED)].concat());
|
||||
}
|
||||
|
||||
/// A device opens what `encrypt` sealed for it, agreeing its key with the one in the header.
|
||||
///
|
||||
/// The break this catches: `encrypt` mixing the keys in the wrong order or putting the wrong key
|
||||
/// in the header, which the pinned halves above can't see.
|
||||
#[test]
|
||||
fn a_device_opens_what_was_sealed_for_it() {
|
||||
let random = rand::SystemRandom::new();
|
||||
let device = agreement::EphemeralPrivateKey::generate(&agreement::ECDH_P256, &random).unwrap();
|
||||
let device_key = device.compute_public_key().unwrap();
|
||||
let auth = [7u8; 16];
|
||||
let body = encrypt(b"Approve bash", device_key.as_ref(), &auth).unwrap();
|
||||
assert_eq!(open(device, device_key.as_ref(), &auth, &body), b"Approve bash\x02");
|
||||
}
|
||||
|
||||
/// What the device with private key `device` reads from `body`, as its browser would: the key in
|
||||
/// the header agreed with its own, and the one record opened, delimiter and all.
|
||||
pub(crate) fn open(
|
||||
device: agreement::EphemeralPrivateKey,
|
||||
device_key: &[u8],
|
||||
auth: &[u8],
|
||||
body: &[u8],
|
||||
) -> Vec<u8> {
|
||||
let (salt, our_key, sealed) = (&body[..16], &body[21..86], &body[86..]);
|
||||
let ours = agreement::UnparsedPublicKey::new(&agreement::ECDH_P256, our_key);
|
||||
let keys = agreement::agree_ephemeral(device, &ours, |shared| {
|
||||
content_keys(shared, auth, device_key, our_key, salt)
|
||||
})
|
||||
.expect("the header's key is on the curve");
|
||||
let key = aead::LessSafeKey::new(aead::UnboundKey::new(&aead::AES_128_GCM, &keys.key).unwrap());
|
||||
let mut record = sealed.to_vec();
|
||||
let nonce = aead::Nonce::assume_unique_for_key(keys.nonce);
|
||||
key.open_in_place(nonce, aead::Aad::empty(), &mut record).expect("it opens").to_vec()
|
||||
}
|
||||
|
||||
/// The break this catches: sealing a message longer than its record says, which the push service
|
||||
/// refuses, rather than saying why here.
|
||||
#[test]
|
||||
fn a_message_too_long_for_one_record_is_refused() {
|
||||
let device = [4u8; 65];
|
||||
let longest = vec![b'x'; RECORD_SIZE as usize - RECORD_OVERHEAD];
|
||||
assert!(!matches!(encrypt(&longest, &device, &[0; 16]), Err(EncryptionError::TooLong(_))));
|
||||
let longer = vec![b'x'; longest.len() + 1];
|
||||
assert!(matches!(encrypt(&longer, &device, &[0; 16]), Err(EncryptionError::TooLong(_))));
|
||||
}
|
||||
|
||||
/// The break this catches: a key that isn't on the curve sealed for anyway, sending a message no
|
||||
/// device can open.
|
||||
#[test]
|
||||
fn a_key_off_the_curve_is_refused() {
|
||||
let sealed = encrypt(b"hi", &[4u8; 65], &[0; 16]);
|
||||
assert!(matches!(sealed, Err(EncryptionError::BadSubscriptionKey)));
|
||||
}
|
||||
118
crates/luxe-remote/src/push/notice.rs
Normal file
118
crates/luxe-remote/src/push/notice.rs
Normal file
@@ -0,0 +1,118 @@
|
||||
//! Notice — what a notification says, read from one session's events.
|
||||
//!
|
||||
//! A notification says what is waiting and where, never the detail: "Approve bash" with the
|
||||
//! folder's name, not the command, and opening it leads to the prompt. Answering takes the app.
|
||||
//!
|
||||
//! Two rules keep it from buzzing at someone sitting at their desk. A prompt is held for a few
|
||||
//! seconds first, and one answered meanwhile is never sent. A turn's end is only news when the
|
||||
//! turn ran long enough for someone to have walked away.
|
||||
|
||||
use luxe_core::{Event, StopReason};
|
||||
use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
|
||||
/// How long a prompt waits before it's sent, for an answer at the desk to beat it.
|
||||
pub(crate) const PROMPT_GRACE: Duration = Duration::from_secs(10);
|
||||
|
||||
/// The shortest turn whose end is sent: a quick reply is read where it was asked for.
|
||||
pub(crate) const LONG_TURN: Duration = Duration::from_secs(30);
|
||||
|
||||
/// One notification, as the service worker shows it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
|
||||
pub(crate) struct Notice {
|
||||
/// The project folder's name
|
||||
pub(crate) title: String,
|
||||
/// What's waiting, in a few words
|
||||
pub(crate) body: String,
|
||||
/// The session it opens
|
||||
pub(crate) session: String,
|
||||
/// Whether to deliver now rather than when the device saves power
|
||||
#[serde(skip)]
|
||||
pub(crate) urgent: bool,
|
||||
}
|
||||
|
||||
/// What an event means for notifications.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(crate) enum Heard {
|
||||
/// Send this now
|
||||
Now(Notice),
|
||||
/// Send this unless prompt `id` closes within [`PROMPT_GRACE`]
|
||||
Prompt(String, Notice),
|
||||
/// Prompt `id` was answered, wherever
|
||||
Closed(String),
|
||||
}
|
||||
|
||||
/// One session's stream, read for what's worth a notification.
|
||||
pub(crate) struct Reading {
|
||||
session: String,
|
||||
folder: String,
|
||||
turn_began: Option<Instant>,
|
||||
}
|
||||
|
||||
impl Reading {
|
||||
/// A reading of the session `session` running in `cwd`.
|
||||
pub(crate) fn new(session: &str, cwd: &str) -> Self {
|
||||
let folder = std::path::Path::new(cwd).file_name().map(|name| name.to_string_lossy());
|
||||
let folder = folder.map_or_else(|| cwd.to_string(), |name| name.into_owned());
|
||||
Self { session: session.to_string(), folder, turn_began: None }
|
||||
}
|
||||
|
||||
/// What `event`, seen at `now`, means.
|
||||
pub(crate) fn read(&mut self, event: &Event, now: Instant) -> Option<Heard> {
|
||||
if is_turn_sign(event) {
|
||||
self.turn_began.get_or_insert(now);
|
||||
}
|
||||
match event {
|
||||
Event::Ready { session_id, .. } | Event::SessionLoaded { session_id, .. } => {
|
||||
self.session.clone_from(session_id);
|
||||
None
|
||||
}
|
||||
Event::PermissionRequested { .. } | Event::QuestionAsked { .. } => self.prompt(event),
|
||||
Event::PromptClosed { id } => Some(Heard::Closed(id.clone())),
|
||||
Event::TurnEnded { reason } => self.turn_ended(reason, now).map(Heard::Now),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn prompt(&self, event: &Event) -> Option<Heard> {
|
||||
let (id, body) = match event {
|
||||
Event::PermissionRequested { id, tool, .. } => (id.as_str(), format!("Approve {tool}")),
|
||||
Event::QuestionAsked { id, .. } => (id.as_str(), "Luxe has a question".to_string()),
|
||||
_ => return None,
|
||||
};
|
||||
Some(Heard::Prompt(id.to_string(), self.notice(body, true)))
|
||||
}
|
||||
|
||||
fn turn_ended(&mut self, reason: &StopReason, now: Instant) -> Option<Notice> {
|
||||
let began = self.turn_began.take()?;
|
||||
if now.duration_since(began) < LONG_TURN {
|
||||
return None;
|
||||
}
|
||||
let body = match reason {
|
||||
StopReason::EndTurn | StopReason::ToolCall => "Finished, and waiting for you",
|
||||
StopReason::Other(_) => "Stopped",
|
||||
};
|
||||
Some(self.notice(body.into(), false))
|
||||
}
|
||||
|
||||
fn notice(&self, body: String, urgent: bool) -> Notice {
|
||||
Notice { title: self.folder.clone(), body, session: self.session.clone(), urgent }
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `event` shows a turn running. The engine says so with `TurnStarted`, which comes
|
||||
/// first; the message that opened the turn, or anything it streams, stands in for it from a
|
||||
/// session whose Luxe predates that event.
|
||||
fn is_turn_sign(event: &Event) -> bool {
|
||||
match event {
|
||||
Event::TurnStarted
|
||||
| Event::TokenDelta { .. }
|
||||
| Event::ThinkingDelta { .. }
|
||||
| Event::ToolCallComposing { .. } => true,
|
||||
Event::MessageCommitted { message, .. } => message.role == luxe_core::message::Role::User,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
126
crates/luxe-remote/src/push/notice/tests.rs
Normal file
126
crates/luxe-remote/src/push/notice/tests.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
use super::*;
|
||||
use luxe_core::Message;
|
||||
|
||||
/// Frames as a session sends them, copied from core's pinned wire shapes.
|
||||
const PERMISSION: &str = r#"{"kind":"permission_requested","content":{"id":"perm:1","session_id":"session-1","tool":"bash","permission":"bash","summary":"Run: rm -rf build","always_patterns":["rm *"]}}"#;
|
||||
const QUESTION: &str = r#"{"kind":"question_asked","content":{"id":"ask:1","session_id":"session-1","prompt":"Which database?","options":[{"label":"postgres","description":"Relational, boring, correct","recommended":true}],"multi":false}}"#;
|
||||
const CLOSED: &str = r#"{"kind":"prompt_closed","content":{"id":"perm:1"}}"#;
|
||||
const DELTA: &str = r#"{"kind":"token_delta","content":{"block":0,"delta":"hello"}}"#;
|
||||
const FINISHED: &str = r#"{"kind":"turn_ended","content":{"reason":"end_turn"}}"#;
|
||||
|
||||
fn event(line: &str) -> Event {
|
||||
serde_json::from_str(line).expect("a protocol frame")
|
||||
}
|
||||
|
||||
fn committed(message: Message) -> Event {
|
||||
let frame = serde_json::json!({
|
||||
"kind": "message_committed",
|
||||
"content": { "session_id": "session-1", "entry_id": "e1", "message": message },
|
||||
});
|
||||
serde_json::from_value(frame).expect("a committed message")
|
||||
}
|
||||
|
||||
fn reading() -> Reading {
|
||||
Reading::new("session-1", "/home/alex/work/luxe-dev")
|
||||
}
|
||||
|
||||
/// A notice for `body` from the reading above.
|
||||
fn notice(body: &str, urgent: bool) -> Notice {
|
||||
let (title, session) = ("luxe-dev".into(), "session-1".into());
|
||||
Notice { title, body: body.into(), session, urgent }
|
||||
}
|
||||
|
||||
/// The break this catches: the command, the question's text or its options in the notification,
|
||||
/// where a lock screen shows them to whoever is looking.
|
||||
#[test]
|
||||
fn a_prompt_says_what_waits_and_never_the_detail() {
|
||||
let now = Instant::now();
|
||||
let asked = reading().read(&event(PERMISSION), now);
|
||||
assert_eq!(asked, Some(Heard::Prompt("perm:1".into(), notice("Approve bash", true))));
|
||||
let asked = reading().read(&event(QUESTION), now);
|
||||
let expected = Heard::Prompt("ask:1".into(), notice("Luxe has a question", true));
|
||||
assert_eq!(asked, Some(expected));
|
||||
assert_eq!(reading().read(&event(CLOSED), now), Some(Heard::Closed("perm:1".into())));
|
||||
}
|
||||
|
||||
/// The break this catches: a quick reply at the desk buzzing the phone, or a long turn ending
|
||||
/// without a word to someone who walked away.
|
||||
#[test]
|
||||
fn only_a_long_turns_end_is_news() {
|
||||
let start = Instant::now();
|
||||
let mut quick = reading();
|
||||
quick.read(&committed(Message::user("hi")), start);
|
||||
assert_eq!(quick.read(&event(FINISHED), start + LONG_TURN - Duration::from_secs(1)), None);
|
||||
let mut long = reading();
|
||||
long.read(&committed(Message::user("refactor it")), start);
|
||||
let ended = long.read(&event(FINISHED), start + LONG_TURN);
|
||||
assert_eq!(ended, Some(Heard::Now(notice("Finished, and waiting for you", false))));
|
||||
}
|
||||
|
||||
/// The break this catches: timing a turn from its first sign each time it shows (every delta),
|
||||
/// so no turn is ever long; or from a reply the model committed, which isn't a turn starting.
|
||||
#[test]
|
||||
fn a_turn_is_timed_from_its_first_sign() {
|
||||
let start = Instant::now();
|
||||
let mut reading = reading();
|
||||
reading.read(&event(DELTA), start);
|
||||
reading.read(&event(DELTA), start + LONG_TURN);
|
||||
assert!(reading.read(&event(FINISHED), start + LONG_TURN).is_some(), "timed from the first");
|
||||
|
||||
let mut replies = super::tests::reading();
|
||||
replies.read(&committed(Message::assistant("done")), start);
|
||||
assert_eq!(replies.read(&event(FINISHED), start + LONG_TURN), None, "a reply isn't a start");
|
||||
}
|
||||
|
||||
/// A turn is timed from `turn_started`, ahead of anything it streams.
|
||||
///
|
||||
/// The break this catches: ignoring `turn_started`, so a turn that spends its first seconds
|
||||
/// waiting on the model is timed short, and its end isn't news.
|
||||
#[test]
|
||||
fn a_turn_is_timed_from_when_it_started() {
|
||||
let start = Instant::now();
|
||||
let mut reading = reading();
|
||||
reading.read(&event(r#"{"kind":"turn_started"}"#), start);
|
||||
reading.read(&event(DELTA), start + Duration::from_secs(20));
|
||||
assert!(reading.read(&event(FINISHED), start + LONG_TURN).is_some());
|
||||
}
|
||||
|
||||
/// The break this catches: a turn's start carried past its end, so the next quick turn looks long.
|
||||
#[test]
|
||||
fn each_turn_is_timed_on_its_own() {
|
||||
let start = Instant::now();
|
||||
let mut reading = reading();
|
||||
reading.read(&event(DELTA), start);
|
||||
reading.read(&event(FINISHED), start + Duration::from_secs(1));
|
||||
reading.read(&event(DELTA), start + LONG_TURN);
|
||||
assert_eq!(reading.read(&event(FINISHED), start + LONG_TURN + Duration::from_secs(1)), None);
|
||||
}
|
||||
|
||||
/// The break this catches: reading a stop's free-text reason (ruled out), or calling a cancelled
|
||||
/// or failed turn finished.
|
||||
#[test]
|
||||
fn a_turn_that_stopped_says_so() {
|
||||
let start = Instant::now();
|
||||
let mut reading = reading();
|
||||
reading.read(&event(DELTA), start);
|
||||
let stopped = Event::TurnEnded { reason: StopReason::Other("cancelled".into()) };
|
||||
assert_eq!(
|
||||
reading.read(&stopped, start + LONG_TURN),
|
||||
Some(Heard::Now(notice("Stopped", false)))
|
||||
);
|
||||
}
|
||||
|
||||
/// The break this catches: a notice naming the session the watcher joined after the terminal
|
||||
/// moved to another one, so opening it lands on a session that isn't running.
|
||||
#[test]
|
||||
fn a_notice_names_the_session_now_running() {
|
||||
let mut reading = reading();
|
||||
let loaded = serde_json::json!({
|
||||
"kind": "session_loaded", "content": { "session_id": "session-2", "messages": [] },
|
||||
});
|
||||
reading.read(&serde_json::from_value(loaded).unwrap(), Instant::now());
|
||||
let Some(Heard::Prompt(_, asked)) = reading.read(&event(PERMISSION), Instant::now()) else {
|
||||
panic!("a prompt is heard");
|
||||
};
|
||||
assert_eq!(asked.session, "session-2");
|
||||
}
|
||||
72
crates/luxe-remote/src/push/presence.rs
Normal file
72
crates/luxe-remote/src/push/presence.rs
Normal file
@@ -0,0 +1,72 @@
|
||||
//! Presence — which devices have which session open right now.
|
||||
//!
|
||||
//! The app closes its socket when it's hidden, so an open socket means the session is on that
|
||||
//! device's screen, and a notification about it would only repeat what's in front of you.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
/// A device id and a session id.
|
||||
type Visit = (String, String);
|
||||
|
||||
/// The sockets open now, counted per device and session.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub(crate) struct Presence {
|
||||
open: Arc<Mutex<HashMap<Visit, usize>>>,
|
||||
}
|
||||
|
||||
impl Presence {
|
||||
/// Counts `device` as looking at `session` until the returned guard drops.
|
||||
pub(crate) fn arrive(&self, device: &str, session: &str) -> Here {
|
||||
let visit = (device.to_string(), session.to_string());
|
||||
*self.lock().entry(visit.clone()).or_default() += 1;
|
||||
Here { presence: self.clone(), visit }
|
||||
}
|
||||
|
||||
/// Whether `device` has `session` open.
|
||||
pub(crate) fn is_here(&self, device: &str, session: &str) -> bool {
|
||||
self.lock().contains_key(&(device.to_string(), session.to_string()))
|
||||
}
|
||||
|
||||
// a panic elsewhere can't leave a count half-changed, so a poisoned lock is still right
|
||||
fn lock(&self) -> MutexGuard<'_, HashMap<Visit, usize>> {
|
||||
self.open.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
}
|
||||
|
||||
/// One open socket, counted while it lives.
|
||||
pub(crate) struct Here {
|
||||
presence: Presence,
|
||||
visit: Visit,
|
||||
}
|
||||
|
||||
impl Drop for Here {
|
||||
fn drop(&mut self) {
|
||||
let mut open = self.presence.lock();
|
||||
let Some(count) = open.get_mut(&self.visit) else { return };
|
||||
*count -= 1;
|
||||
if *count == 0 {
|
||||
open.remove(&self.visit);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The break this catches: the first socket to close clearing the device, though the session
|
||||
/// is still open in another tab or a second socket, or one device's socket covering another.
|
||||
#[test]
|
||||
fn a_device_is_here_while_any_of_its_sockets_is_open() {
|
||||
let presence = Presence::default();
|
||||
let first = presence.arrive("phone", "s1");
|
||||
let second = presence.arrive("phone", "s1");
|
||||
assert!(!presence.is_here("tablet", "s1"), "another device");
|
||||
assert!(!presence.is_here("phone", "s2"), "another session");
|
||||
drop(first);
|
||||
assert!(presence.is_here("phone", "s1"), "one socket is still open");
|
||||
drop(second);
|
||||
assert!(!presence.is_here("phone", "s1"));
|
||||
}
|
||||
}
|
||||
92
crates/luxe-remote/src/push/subscription.rs
Normal file
92
crates/luxe-remote/src/push/subscription.rs
Normal file
@@ -0,0 +1,92 @@
|
||||
//! Subscription — where a device asked to be sent notifications, and the keys to seal them with.
|
||||
//!
|
||||
//! The device names the address the bridge will post to, so the address is held to the push
|
||||
//! services browsers use: HTTPS, on a known host. Anything else would let a paired device point
|
||||
//! the bridge at a machine on your network.
|
||||
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use base64::Engine;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The push services a subscription may name, each with its subdomains: Apple's (Safari, every
|
||||
/// browser on iOS), Google's (Chrome), Mozilla's (Firefox) and Microsoft's (Edge).
|
||||
const PUSH_SERVICES: &[&str] =
|
||||
&["push.apple.com", "fcm.googleapis.com", "push.services.mozilla.com", "notify.windows.com"];
|
||||
|
||||
/// A device's push subscription, as `PushSubscription.toJSON()` gives it.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct Subscription {
|
||||
/// Where the push service takes this device's notifications
|
||||
pub(crate) endpoint: String,
|
||||
/// The keys the browser made for it
|
||||
pub(crate) keys: SubscriptionKeys,
|
||||
}
|
||||
|
||||
/// The browser's half of the encryption, base64url.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub(crate) struct SubscriptionKeys {
|
||||
/// Its P-256 public key
|
||||
pub(crate) p256dh: String,
|
||||
/// The secret shared with the bridge alone
|
||||
pub(crate) auth: String,
|
||||
}
|
||||
|
||||
/// Why a subscription was turned down.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub(crate) enum SubscriptionError {
|
||||
/// The endpoint isn't an HTTPS URL on the default port
|
||||
#[error("a push endpoint must be an https:// address")]
|
||||
NotHttps,
|
||||
/// The endpoint's host isn't a push service a browser uses
|
||||
#[error("{0} isn't a push service this bridge sends to")]
|
||||
UnknownService(String),
|
||||
/// The keys aren't a P-256 point and a 16-byte secret
|
||||
#[error("the subscription's keys aren't the ones Web Push uses")]
|
||||
BadKeys,
|
||||
}
|
||||
|
||||
impl Subscription {
|
||||
/// This subscription, if it names a push service and carries usable keys.
|
||||
pub(crate) fn checked(self) -> Result<Self, SubscriptionError> {
|
||||
let host = push_host(&self.endpoint)?;
|
||||
if !PUSH_SERVICES.iter().any(|service| is_within(&host, service)) {
|
||||
return Err(SubscriptionError::UnknownService(host));
|
||||
}
|
||||
let (public, auth) = self.key_bytes().ok_or(SubscriptionError::BadKeys)?;
|
||||
if public.len() != 65 || public[0] != 4 || auth.len() != 16 {
|
||||
return Err(SubscriptionError::BadKeys);
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// The browser's public key and the shared secret, decoded.
|
||||
pub(crate) fn key_bytes(&self) -> Option<(Vec<u8>, Vec<u8>)> {
|
||||
let public = URL_SAFE_NO_PAD.decode(&self.keys.p256dh).ok()?;
|
||||
let auth = URL_SAFE_NO_PAD.decode(&self.keys.auth).ok()?;
|
||||
Some((public, auth))
|
||||
}
|
||||
|
||||
/// The push service's origin, which a VAPID token must name.
|
||||
pub(crate) fn audience(&self) -> Option<String> {
|
||||
let url = reqwest::Url::parse(&self.endpoint).ok()?;
|
||||
Some(url.origin().ascii_serialization())
|
||||
}
|
||||
}
|
||||
|
||||
/// The host of `endpoint`, when it's HTTPS on the default port.
|
||||
fn push_host(endpoint: &str) -> Result<String, SubscriptionError> {
|
||||
let url = reqwest::Url::parse(endpoint).map_err(|_| SubscriptionError::NotHttps)?;
|
||||
if url.scheme() != "https" || url.port().is_some() {
|
||||
return Err(SubscriptionError::NotHttps);
|
||||
}
|
||||
let host = url.host_str().ok_or(SubscriptionError::NotHttps)?;
|
||||
Ok(host.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
/// Whether `host` is `service` or one of its subdomains.
|
||||
fn is_within(host: &str, service: &str) -> bool {
|
||||
host == service || host.strip_suffix(service).is_some_and(|rest| rest.ends_with('.'))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
70
crates/luxe-remote/src/push/subscription/tests.rs
Normal file
70
crates/luxe-remote/src/push/subscription/tests.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
use super::*;
|
||||
|
||||
/// A subscription in the shape the Push API gives `PushSubscription.toJSON()`, with an endpoint
|
||||
/// on Apple's push service and RFC 8291's example keys. Not captured from a device: swap in a real
|
||||
/// one when there is one.
|
||||
pub(crate) const FROM_SAFARI: &str = r#"{"endpoint":"https://web.push.apple.com/QGuQyavXutnMH8nrLlUjPZe_eVbc4ndHqoGAHGBrP2bIG7WY_DuCO7B0fhd7QAEXMaChjqCnDiuWvDEvkFvYg1vbqgxQp9zc5uj2BLsdLUn6R7Kp5YnWzMw6V_Ekd8CKk8Q3t6c2RU1yhp9eu5fcWkoUd3pUwP7sOTzmjVPCQCmY","keys":{"p256dh":"BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4","auth":"BTBZMqHH6r4Tts7J_aSIgg"},"expirationTime":null}"#;
|
||||
|
||||
fn safari() -> Subscription {
|
||||
serde_json::from_str(FROM_SAFARI).expect("Safari's shape reads")
|
||||
}
|
||||
|
||||
fn at(endpoint: &str) -> Subscription {
|
||||
Subscription { endpoint: endpoint.into(), ..safari() }
|
||||
}
|
||||
|
||||
/// The break this catches: reading only some other browser's shape, so Safari's subscription
|
||||
/// (the one an iPhone sends) is refused or loses its keys.
|
||||
#[test]
|
||||
fn a_subscription_from_safari_is_taken() {
|
||||
let subscription = safari().checked().expect("it's Apple's push service");
|
||||
assert_eq!(subscription.audience().as_deref(), Some("https://web.push.apple.com"));
|
||||
}
|
||||
|
||||
/// The break this catches: a host check that's a plain suffix or substring match, so a name
|
||||
/// that only ends like a push service's (or contains one) is posted to.
|
||||
#[test]
|
||||
fn only_a_push_services_own_hosts_are_taken() {
|
||||
for endpoint in [
|
||||
"https://fcm.googleapis.com/fcm/send/abc",
|
||||
"https://updates.push.services.mozilla.com/wpush/v2/abc",
|
||||
"https://wns2-par02p.notify.windows.com/w/?token=abc",
|
||||
] {
|
||||
assert!(at(endpoint).checked().is_ok(), "{endpoint}");
|
||||
}
|
||||
for endpoint in [
|
||||
"https://evilpush.apple.com.example.net/x",
|
||||
"https://notpush.apple.com/x",
|
||||
"https://example.net/web.push.apple.com",
|
||||
"https://192.168.1.1/push",
|
||||
] {
|
||||
let refused = at(endpoint).checked();
|
||||
assert!(matches!(refused, Err(SubscriptionError::UnknownService(_))), "{endpoint}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The break this catches: posting over plain HTTP, or to a push service's host on another port,
|
||||
/// where something other than the push service may be listening.
|
||||
#[test]
|
||||
fn an_endpoint_must_be_https_on_its_usual_port() {
|
||||
for endpoint in ["http://web.push.apple.com/x", "https://web.push.apple.com:8443/x", "nonsense"]
|
||||
{
|
||||
assert_eq!(at(endpoint).checked(), Err(SubscriptionError::NotHttps), "{endpoint}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The break this catches: taking keys that can't seal a message, so every notification to the
|
||||
/// device fails later, with nothing said when it subscribed.
|
||||
#[test]
|
||||
fn keys_that_cant_seal_a_message_are_refused() {
|
||||
let bad = |p256dh: &str, auth: &str| {
|
||||
let keys = SubscriptionKeys { p256dh: p256dh.into(), auth: auth.into() };
|
||||
Subscription { keys, ..safari() }.checked()
|
||||
};
|
||||
let good = safari().keys;
|
||||
assert_eq!(bad("not base64!", &good.auth), Err(SubscriptionError::BadKeys));
|
||||
assert_eq!(bad(&good.p256dh[..60], &good.auth), Err(SubscriptionError::BadKeys));
|
||||
assert_eq!(bad(&good.p256dh, "c2hvcnQ"), Err(SubscriptionError::BadKeys));
|
||||
let compressed = URL_SAFE_NO_PAD.encode([[2u8].as_slice(), &[9; 64]].concat());
|
||||
assert_eq!(bad(&compressed, &good.auth), Err(SubscriptionError::BadKeys));
|
||||
}
|
||||
121
crates/luxe-remote/src/push/tests.rs
Normal file
121
crates/luxe-remote/src/push/tests.rs
Normal file
@@ -0,0 +1,121 @@
|
||||
use super::*;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Mutex;
|
||||
|
||||
/// Posts nowhere: keeps the endpoints it was handed and the titles it was asked to show, and
|
||||
/// answers each with `reply`.
|
||||
pub(crate) struct Recording {
|
||||
sent: Mutex<Vec<String>>,
|
||||
titles: Mutex<Vec<String>>,
|
||||
reply: Delivery,
|
||||
}
|
||||
|
||||
impl Recording {
|
||||
fn answering(reply: Delivery) -> Self {
|
||||
Self { sent: Mutex::default(), titles: Mutex::default(), reply }
|
||||
}
|
||||
|
||||
/// The titles of the notices posted, in order.
|
||||
pub(crate) fn titles(&self) -> Vec<String> {
|
||||
self.titles.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
/// One whose every post goes through.
|
||||
pub(crate) fn taking() -> Self {
|
||||
Self::answering(Delivery::Taken)
|
||||
}
|
||||
|
||||
/// The endpoints posted to, in order.
|
||||
pub(crate) fn sent(&self) -> Vec<String> {
|
||||
self.sent.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl Courier for Recording {
|
||||
fn deliver<'a>(
|
||||
&'a self,
|
||||
subscription: &'a Subscription,
|
||||
notice: &'a Notice,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Delivery, web_push::PushError>> + Send + 'a>> {
|
||||
self.sent.lock().unwrap().push(subscription.endpoint.clone());
|
||||
self.titles.lock().unwrap().push(notice.title.clone());
|
||||
let reply = self.reply;
|
||||
Box::pin(async move { Ok(reply) })
|
||||
}
|
||||
}
|
||||
|
||||
fn notice() -> Notice {
|
||||
let (title, body, session) = ("luxe-dev".into(), "Approve bash".into(), "session-1".into());
|
||||
Notice { title, body, session, urgent: true }
|
||||
}
|
||||
|
||||
/// Pairs a device named `name`, subscribed at `endpoint` when there is one, and returns its id.
|
||||
fn device(book: &DeviceBook, name: &str, endpoint: Option<&str>) -> String {
|
||||
let token = book.invite().unwrap();
|
||||
let (device, _) = book.pair(&token, name, "alex@github").unwrap();
|
||||
let keys = SubscriptionKeys {
|
||||
p256dh: "BCVxsr7N_eNgVRqvHtD0zTZsEc6-VV-JvLexhqUzORcxaOzi6-AYWXvTBHm4bjyPjs7Vd8pZGH6SRpkNtoIAiw4"
|
||||
.into(),
|
||||
auth: "BTBZMqHH6r4Tts7J_aSIgg".into(),
|
||||
};
|
||||
let subscription = endpoint.map(|endpoint| Subscription { endpoint: endpoint.into(), keys });
|
||||
book.subscribe(&device.id, subscription).unwrap();
|
||||
device.id
|
||||
}
|
||||
|
||||
fn book() -> (tempfile::TempDir, DeviceBook) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let book = DeviceBook::at(dir.path().join("remote.json"));
|
||||
(dir, book)
|
||||
}
|
||||
|
||||
/// The break this catches: a notice sent to a device with that very session on screen, to one
|
||||
/// that never opted in, or held back from a device that's only looking at another session.
|
||||
#[tokio::test]
|
||||
async fn a_notice_reaches_each_subscribed_device_not_looking_at_it() {
|
||||
let (_dir, book) = book();
|
||||
let presence = Presence::default();
|
||||
let elsewhere = device(&book, "iPhone", Some("https://web.push.apple.com/phone"));
|
||||
let looking = device(&book, "iPad", Some("https://web.push.apple.com/ipad"));
|
||||
device(&book, "Laptop", None);
|
||||
let _phone = presence.arrive(&elsewhere, "session-2");
|
||||
let _ipad = presence.arrive(&looking, "session-1");
|
||||
|
||||
let courier = Recording::answering(Delivery::Taken);
|
||||
dispatch(&book, &presence, &courier, ¬ice()).await;
|
||||
assert_eq!(courier.sent(), ["https://web.push.apple.com/phone"]);
|
||||
}
|
||||
|
||||
fn kept(book: &DeviceBook, id: &str) -> Option<String> {
|
||||
let devices = book.devices();
|
||||
let device = devices.iter().find(|device| device.id == id)?;
|
||||
Some(device.subscription()?.endpoint.clone())
|
||||
}
|
||||
|
||||
/// The break this catches: a subscription Apple has dropped posted to forever (each one a wasted
|
||||
/// request, and a 410 in the log), or one forgotten after a post that went through.
|
||||
#[tokio::test]
|
||||
async fn a_subscription_is_forgotten_only_when_its_service_says_it_is_gone() {
|
||||
let (_dir, book) = book();
|
||||
let id = device(&book, "iPhone", Some("https://web.push.apple.com/phone"));
|
||||
let presence = Presence::default();
|
||||
|
||||
dispatch(&book, &presence, &Recording::answering(Delivery::Taken), ¬ice()).await;
|
||||
assert_eq!(kept(&book, &id).as_deref(), Some("https://web.push.apple.com/phone"));
|
||||
dispatch(&book, &presence, &Recording::answering(Delivery::Gone), ¬ice()).await;
|
||||
assert_eq!(kept(&book, &id), None);
|
||||
}
|
||||
|
||||
/// A named bridge's notice says which computer it's from, after the project; an unnamed one is
|
||||
/// left as the session wrote it.
|
||||
///
|
||||
/// The break this catches: a phone paired with two computers told "luxe-dev" wants it, with no
|
||||
/// way to know which computer to open, or the body or session changed along with the title.
|
||||
#[test]
|
||||
fn a_notice_names_the_computer_it_came_from() {
|
||||
let named = on_machine(notice(), Some("desk"));
|
||||
assert_eq!(named.title, "luxe-dev \u{00b7} desk");
|
||||
assert_eq!((named.body.as_str(), named.session.as_str()), ("Approve bash", "session-1"));
|
||||
assert_eq!(on_machine(notice(), None).title, "luxe-dev");
|
||||
}
|
||||
74
crates/luxe-remote/src/push/vapid.rs
Normal file
74
crates/luxe-remote/src/push/vapid.rs
Normal file
@@ -0,0 +1,74 @@
|
||||
//! VAPID — how the bridge proves to a push service that it's the server a device subscribed to.
|
||||
//!
|
||||
//! A device subscribes with the bridge's public key, and each push carries a short token signed
|
||||
//! with the private one (RFC 8292). The token names the push service it's for and when it
|
||||
//! expires, and as its contact the project's homepage: nothing about this machine or its owner.
|
||||
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use base64::Engine;
|
||||
use ring::rand::SystemRandom;
|
||||
use ring::signature::{EcdsaKeyPair, KeyPair, ECDSA_P256_SHA256_FIXED_SIGNING};
|
||||
|
||||
/// The contact a token names. A push service wants a URL or `mailto:` there.
|
||||
const CONTACT: &str = env!("CARGO_PKG_HOMEPAGE");
|
||||
|
||||
/// Why the bridge's push key couldn't be made, read or used.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(crate) enum VapidError {
|
||||
/// The stored key isn't a P-256 key in PKCS#8
|
||||
#[error("the stored push key isn't a P-256 private key")]
|
||||
Unreadable,
|
||||
/// The system's randomness failed
|
||||
#[error("the system's random number source failed")]
|
||||
Random,
|
||||
}
|
||||
|
||||
/// The bridge's push signing key.
|
||||
pub(crate) struct Vapid {
|
||||
pair: EcdsaKeyPair,
|
||||
random: SystemRandom,
|
||||
}
|
||||
|
||||
impl Vapid {
|
||||
/// A new key, and the PKCS#8 document to keep it in.
|
||||
pub(crate) fn generate() -> Result<(Self, Vec<u8>), VapidError> {
|
||||
let random = SystemRandom::new();
|
||||
let document = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, &random)
|
||||
.map_err(|_| VapidError::Random)?;
|
||||
let kept = document.as_ref().to_vec();
|
||||
Ok((Self::from_pkcs8(&kept)?, kept))
|
||||
}
|
||||
|
||||
/// The key kept in `document`.
|
||||
pub(crate) fn from_pkcs8(document: &[u8]) -> Result<Self, VapidError> {
|
||||
let random = SystemRandom::new();
|
||||
let pair = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, document, &random)
|
||||
.map_err(|_| VapidError::Unreadable)?;
|
||||
Ok(Self { pair, random })
|
||||
}
|
||||
|
||||
/// The public key, base64url, as a device passes it to `PushManager.subscribe`.
|
||||
pub(crate) fn public_key(&self) -> String {
|
||||
URL_SAFE_NO_PAD.encode(self.pair.public_key().as_ref())
|
||||
}
|
||||
|
||||
/// The `Authorization` header for the push service at origin `audience`, good until
|
||||
/// `expires_at` (seconds since the Unix epoch).
|
||||
pub(crate) fn authorization(
|
||||
&self,
|
||||
audience: &str,
|
||||
expires_at: u64,
|
||||
) -> Result<String, VapidError> {
|
||||
let header = URL_SAFE_NO_PAD.encode(br#"{"typ":"JWT","alg":"ES256"}"#);
|
||||
let claims = serde_json::json!({ "aud": audience, "exp": expires_at, "sub": CONTACT });
|
||||
let claims = URL_SAFE_NO_PAD.encode(claims.to_string());
|
||||
let signed = format!("{header}.{claims}");
|
||||
let signature =
|
||||
self.pair.sign(&self.random, signed.as_bytes()).map_err(|_| VapidError::Random)?;
|
||||
let signature = URL_SAFE_NO_PAD.encode(signature.as_ref());
|
||||
Ok(format!("vapid t={signed}.{signature}, k={}", self.public_key()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
68
crates/luxe-remote/src/push/vapid/tests.rs
Normal file
68
crates/luxe-remote/src/push/vapid/tests.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
use super::*;
|
||||
use ring::signature::{UnparsedPublicKey, ECDSA_P256_SHA256_FIXED};
|
||||
|
||||
const APPLE: &str = "https://web.push.apple.com";
|
||||
|
||||
/// The token and key out of an `Authorization` header.
|
||||
fn parts(header: &str) -> (String, Vec<u8>) {
|
||||
let rest = header.strip_prefix("vapid t=").expect("a vapid header");
|
||||
let (token, key) = rest.split_once(", k=").expect("a token and a key");
|
||||
(token.to_string(), URL_SAFE_NO_PAD.decode(key).expect("the key is base64url"))
|
||||
}
|
||||
|
||||
fn decoded(segment: &str) -> serde_json::Value {
|
||||
serde_json::from_slice(&URL_SAFE_NO_PAD.decode(segment).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The token says what Apple checks: ES256, the push service it's for, the expiry, and a URL to
|
||||
/// reach the sender.
|
||||
///
|
||||
/// The break this catches: a claim renamed or dropped, or a contact that isn't a URL, which Apple
|
||||
/// answers with 403 `BadJwtToken` for every push.
|
||||
#[test]
|
||||
fn the_token_carries_what_apple_checks() {
|
||||
let (vapid, _) = Vapid::generate().unwrap();
|
||||
let (token, _) = parts(&vapid.authorization(APPLE, 1_800_000_000).unwrap());
|
||||
let segments: Vec<&str> = token.split('.').collect();
|
||||
assert_eq!(segments.len(), 3, "{token}");
|
||||
assert_eq!(decoded(segments[0]), serde_json::json!({ "typ": "JWT", "alg": "ES256" }));
|
||||
let claims =
|
||||
serde_json::json!({ "aud": APPLE, "exp": 1_800_000_000u64, "sub": "https://luxe.dev" });
|
||||
assert_eq!(decoded(segments[1]), claims);
|
||||
}
|
||||
|
||||
/// The signature checks out against the key the header gives, with ring's verifier rather than
|
||||
/// anything of the bridge's.
|
||||
///
|
||||
/// The break this catches: signing other bytes than the token's first two parts, a DER signature
|
||||
/// where JWS wants the fixed 64 bytes, or the header naming another key.
|
||||
#[test]
|
||||
fn the_token_is_signed_by_the_key_it_names() {
|
||||
let (vapid, _) = Vapid::generate().unwrap();
|
||||
let (token, key) = parts(&vapid.authorization(APPLE, 1_800_000_000).unwrap());
|
||||
let (signed, signature) = token.rsplit_once('.').unwrap();
|
||||
let signature = URL_SAFE_NO_PAD.decode(signature).unwrap();
|
||||
let verifier = UnparsedPublicKey::new(&ECDSA_P256_SHA256_FIXED, &key);
|
||||
assert!(verifier.verify(signed.as_bytes(), &signature).is_ok());
|
||||
assert_eq!(URL_SAFE_NO_PAD.encode(&key), vapid.public_key());
|
||||
}
|
||||
|
||||
/// The key a device subscribed with is the one the bridge signs with after a restart.
|
||||
///
|
||||
/// The break this catches: the kept document not being the key in use, so every subscription is
|
||||
/// refused (`VapidPkHashMismatch`) once the bridge restarts.
|
||||
#[test]
|
||||
fn a_kept_key_is_the_same_key() {
|
||||
let (vapid, document) = Vapid::generate().unwrap();
|
||||
let kept = Vapid::from_pkcs8(&document).unwrap();
|
||||
assert_eq!(kept.public_key(), vapid.public_key());
|
||||
let key = URL_SAFE_NO_PAD.decode(kept.public_key()).unwrap();
|
||||
assert_eq!((key.len(), key[0]), (65, 4), "an uncompressed P-256 point");
|
||||
}
|
||||
|
||||
/// The break this catches: a damaged key file taken for a key, or a panic, rather than an error
|
||||
/// the bridge can report.
|
||||
#[test]
|
||||
fn a_damaged_key_is_an_error() {
|
||||
assert!(matches!(Vapid::from_pkcs8(b"not a key"), Err(VapidError::Unreadable)));
|
||||
}
|
||||
162
crates/luxe-remote/src/push/watch.rs
Normal file
162
crates/luxe-remote/src/push/watch.rs
Normal file
@@ -0,0 +1,162 @@
|
||||
//! Watch — the bridge's own reader on every running session, while any device wants notifications.
|
||||
//!
|
||||
//! A phone's socket lasts only while the app is on screen, so nothing would hear a prompt
|
||||
//! arrive while it's in a pocket. Instead the bridge joins each running session itself, as a
|
||||
//! watch-only client, which the terminal doesn't announce and which can't act. It reads the
|
||||
//! stream and sends nothing back. With no device subscribed it joins nothing, and leaves what it
|
||||
//! had joined.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use luxe_core::local_endpoint::{self, LiveSession};
|
||||
use luxe_core::Event;
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::Instant;
|
||||
|
||||
use super::notice::{Heard, Notice, Reading, PROMPT_GRACE};
|
||||
use crate::devices::DeviceBook;
|
||||
|
||||
/// How often the running sessions and the subscriptions are looked at again.
|
||||
pub(crate) const WATCH_CHECK: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Who the watcher joins as: unannounced, so its name shows only in the session's log.
|
||||
pub(crate) const WATCHER: crate::relay::Introduction<'static> =
|
||||
crate::relay::Introduction { name: "Notifications", watch_only: true, yours: false };
|
||||
|
||||
/// Keeps a reader on each running session while any device is subscribed, sending what they hear
|
||||
/// to `notices`, until the task is dropped.
|
||||
pub(crate) async fn watch_sessions(
|
||||
runtime_dir: PathBuf,
|
||||
devices: DeviceBook,
|
||||
notices: mpsc::Sender<Notice>,
|
||||
) {
|
||||
let mut watching: HashMap<String, Watcher> = HashMap::new();
|
||||
loop {
|
||||
let running = if anyone_subscribed(&devices).await {
|
||||
running(runtime_dir.clone()).await
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
keep_watching(&mut watching, running, ¬ices);
|
||||
tokio::time::sleep(WATCH_CHECK).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// Stops the readers of sessions no longer running (and of any that quit), and starts one on each
|
||||
/// session that has none, keyed by endpoint: a session's id changes when the terminal switches.
|
||||
fn keep_watching(
|
||||
watching: &mut HashMap<String, Watcher>,
|
||||
running: Vec<LiveSession>,
|
||||
notices: &mpsc::Sender<Notice>,
|
||||
) {
|
||||
let live = |address: &String| running.iter().any(|session| &session.address == address);
|
||||
watching.retain(|address, watcher| live(address) && !watcher.0.is_finished());
|
||||
for session in running {
|
||||
let notices = notices.clone();
|
||||
watching
|
||||
.entry(session.address.clone())
|
||||
.or_insert_with(|| Watcher(tokio::spawn(watch_session(session, notices))));
|
||||
}
|
||||
}
|
||||
|
||||
/// A task stopped when dropped: a session's reader, or the notifications as a whole.
|
||||
pub(crate) struct Watcher(pub(super) tokio::task::JoinHandle<()>);
|
||||
|
||||
impl Drop for Watcher {
|
||||
fn drop(&mut self) {
|
||||
self.0.abort();
|
||||
}
|
||||
}
|
||||
|
||||
async fn anyone_subscribed(devices: &DeviceBook) -> bool {
|
||||
let devices = devices.clone();
|
||||
let paired = tokio::task::spawn_blocking(move || devices.devices()).await;
|
||||
paired.is_ok_and(|paired| paired.iter().any(|device| device.subscription().is_some()))
|
||||
}
|
||||
|
||||
async fn running(runtime_dir: PathBuf) -> Vec<LiveSession> {
|
||||
// reads a folder and, on Windows, asks `tasklist` about each pid
|
||||
let found = tokio::task::spawn_blocking(move || local_endpoint::running_sessions(&runtime_dir));
|
||||
found.await.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Reads `session` until it ends, sending its notices on, each prompt only once it's waited
|
||||
/// [`PROMPT_GRACE`] unanswered.
|
||||
pub(crate) async fn watch_session(session: LiveSession, notices: mpsc::Sender<Notice>) {
|
||||
let Some(mut lines) = join(&session).await else { return };
|
||||
let mut reading = Reading::new(&session.session_id, &session.cwd);
|
||||
let mut held = Held::default();
|
||||
loop {
|
||||
// both are cancel-safe: a line stays buffered, and a held prompt is taken only once due
|
||||
let heard = tokio::select! {
|
||||
line = lines.next_line() => match line {
|
||||
Ok(Some(line)) => {
|
||||
decode(&line).and_then(|event| reading.read(&event, Instant::now()))
|
||||
}
|
||||
Ok(None) | Err(_) => return,
|
||||
},
|
||||
notice = held.due() => Some(Heard::Now(notice)),
|
||||
};
|
||||
if !held.take(heard, ¬ices).await {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The session's stream, joined as the watcher.
|
||||
async fn join(
|
||||
session: &LiveSession,
|
||||
) -> Option<tokio::io::Lines<BufReader<local_endpoint::LocalStream>>> {
|
||||
match crate::routes::open(&session.address, &WATCHER).await {
|
||||
Ok(stream) => Some(BufReader::new(stream).lines()),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, session = %session.session_id, "couldn't watch a session");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn decode(line: &str) -> Option<Event> {
|
||||
serde_json::from_str(line)
|
||||
.inspect_err(|error| tracing::debug!(%error, "a session line that isn't an event"))
|
||||
.ok()
|
||||
}
|
||||
|
||||
/// Prompts waiting out their grace.
|
||||
#[derive(Default)]
|
||||
struct Held {
|
||||
prompts: Vec<(Instant, String, Notice)>,
|
||||
}
|
||||
|
||||
impl Held {
|
||||
/// Acts on what was heard: sends it, holds it or lets one go. False once nobody's listening.
|
||||
async fn take(&mut self, heard: Option<Heard>, notices: &mpsc::Sender<Notice>) -> bool {
|
||||
match heard {
|
||||
Some(Heard::Now(notice)) => return notices.send(notice).await.is_ok(),
|
||||
Some(Heard::Prompt(id, notice)) => {
|
||||
self.prompts.push((Instant::now() + PROMPT_GRACE, id, notice));
|
||||
}
|
||||
Some(Heard::Closed(id)) => self.prompts.retain(|(_, held, _)| *held != id),
|
||||
None => {}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
/// The next prompt to come due, once it has; never, with none held.
|
||||
async fn due(&mut self) -> Notice {
|
||||
let Some(next) = self.prompts.iter().map(|(due, ..)| *due).min() else {
|
||||
return std::future::pending().await;
|
||||
};
|
||||
tokio::time::sleep_until(next).await;
|
||||
let at = self.prompts.iter().position(|(due, ..)| *due == next);
|
||||
// only `take` drops a prompt, and it can't run while this waits
|
||||
let at = at.expect("a due prompt is still held");
|
||||
self.prompts.remove(at).2
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
145
crates/luxe-remote/src/push/watch/tests.rs
Normal file
145
crates/luxe-remote/src/push/watch/tests.rs
Normal file
@@ -0,0 +1,145 @@
|
||||
use super::*;
|
||||
use luxe_core::event::Action;
|
||||
use luxe_core::local_endpoint::{EndpointListener, Joined, Publication};
|
||||
use tokio::io::AsyncWriteExt;
|
||||
|
||||
const PERMISSION: &str = r#"{"kind":"permission_requested","content":{"id":"perm:1","session_id":"session-1","tool":"bash","permission":"bash","summary":"Run: rm -rf build","always_patterns":["rm *"]}}"#;
|
||||
const QUESTION: &str = r#"{"kind":"question_asked","content":{"id":"ask:1","session_id":"session-1","prompt":"Which database?","options":[],"multi":false}}"#;
|
||||
const CLOSED: &str = r#"{"kind":"prompt_closed","content":{"id":"perm:1"}}"#;
|
||||
|
||||
/// A session's endpoint, and the folder it's published in.
|
||||
struct Session {
|
||||
listener: EndpointListener,
|
||||
live: LiveSession,
|
||||
runtime: tempfile::TempDir,
|
||||
}
|
||||
|
||||
fn session() -> Session {
|
||||
let runtime = tempfile::tempdir().unwrap();
|
||||
let listener = EndpointListener::bind(runtime.path()).unwrap();
|
||||
let live = LiveSession {
|
||||
pid: std::process::id(),
|
||||
session_id: "session-1".into(),
|
||||
cwd: "/work/luxe-dev".into(),
|
||||
address: listener.address().to_string(),
|
||||
luxe_version: "0.1.3".into(),
|
||||
};
|
||||
Session { listener, live, runtime }
|
||||
}
|
||||
|
||||
/// Starts a watcher on `session`, and takes its notices and the session's end of the stream.
|
||||
async fn watched(session: &mut Session) -> (mpsc::Receiver<Notice>, Joined, Watcher) {
|
||||
let (notices, heard) = mpsc::channel(8);
|
||||
let watcher = Watcher(tokio::spawn(watch_session(session.live.clone(), notices)));
|
||||
let joined = session.listener.accept().await.unwrap();
|
||||
(heard, joined, watcher)
|
||||
}
|
||||
|
||||
async fn say(joined: &mut Joined, lines: &[&str]) {
|
||||
let text: String = lines.iter().map(|line| format!("{line}\n")).collect();
|
||||
joined.stream.write_all(text.as_bytes()).await.unwrap();
|
||||
}
|
||||
|
||||
/// The watcher opens as watch-only, so the terminal doesn't announce it, and then says nothing.
|
||||
///
|
||||
/// The break this catches: a watcher that joins as an ordinary client (the terminal says
|
||||
/// "Notifications joined this session" in every session) or that sends the session anything else,
|
||||
/// an answer included.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn the_watcher_introduces_itself_and_says_nothing_else() {
|
||||
let mut session = session();
|
||||
let (_heard, joined, _watcher) = watched(&mut session).await;
|
||||
let mut lines = BufReader::new(joined.stream).lines();
|
||||
let first = lines.next_line().await.unwrap().unwrap();
|
||||
let introduced: Action = serde_json::from_str(&first).unwrap();
|
||||
let watcher =
|
||||
Action::Introduce { name: "Notifications".into(), watch_only: true, yours: false };
|
||||
assert_eq!(introduced, watcher);
|
||||
let more = tokio::time::timeout(Duration::from_secs(60), lines.next_line()).await;
|
||||
assert!(more.is_err(), "the watcher sent {more:?}");
|
||||
}
|
||||
|
||||
/// The break this catches: a prompt sent the moment it's asked, buzzing a phone while you answer
|
||||
/// at the desk, or never sent at all.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_prompt_is_sent_once_it_has_waited() {
|
||||
let mut session = session();
|
||||
let (mut heard, mut joined, _watcher) = watched(&mut session).await;
|
||||
let asked = Instant::now();
|
||||
say(&mut joined, &[PERMISSION]).await;
|
||||
let notice = heard.recv().await.expect("a notice");
|
||||
assert_eq!((notice.title.as_str(), notice.body.as_str()), ("luxe-dev", "Approve bash"));
|
||||
assert!(asked.elapsed() >= PROMPT_GRACE, "sent after {:?}", asked.elapsed());
|
||||
}
|
||||
|
||||
/// The break this catches: a prompt answered at the desk still reaching the phone, or one answer
|
||||
/// letting every held prompt go.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_prompt_answered_in_time_is_never_sent() {
|
||||
let mut session = session();
|
||||
let (mut heard, mut joined, _watcher) = watched(&mut session).await;
|
||||
say(&mut joined, &[PERMISSION, QUESTION, CLOSED]).await;
|
||||
let notice = heard.recv().await.expect("a notice");
|
||||
assert_eq!(notice.body, "Luxe has a question");
|
||||
tokio::time::sleep(PROMPT_GRACE * 2).await;
|
||||
assert!(heard.try_recv().is_err(), "the answered prompt was sent");
|
||||
}
|
||||
|
||||
/// The break this catches: a watcher that outlives its session, holding a task (and in time a
|
||||
/// file handle) for every session that ever ran.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn the_watcher_ends_with_its_session() {
|
||||
let mut session = session();
|
||||
let (_heard, joined, watcher) = watched(&mut session).await;
|
||||
// once it has introduced itself it's reading, rather than failing to join
|
||||
let mut lines = BufReader::new(joined.stream).lines();
|
||||
lines.next_line().await.unwrap().expect("an introduction");
|
||||
drop(lines);
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
while !watcher.0.is_finished() {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("the watcher stopped");
|
||||
}
|
||||
|
||||
/// A book with one paired device, and that device's id.
|
||||
fn paired() -> (tempfile::TempDir, DeviceBook, String) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let book = DeviceBook::at(dir.path().join("remote.json"));
|
||||
let token = book.invite().unwrap();
|
||||
let (device, _) = book.pair(&token, "iPhone", "alex@github").unwrap();
|
||||
(dir, book, device.id)
|
||||
}
|
||||
|
||||
fn subscribe(book: &DeviceBook, id: &str, on: bool) {
|
||||
let subscription = on.then(|| serde_json::from_str(crate::push::FROM_SAFARI).unwrap());
|
||||
book.subscribe(id, subscription).unwrap();
|
||||
}
|
||||
|
||||
/// Whether the watcher joins `session` within a few checks.
|
||||
async fn joins(session: &mut Session) -> Option<Joined> {
|
||||
tokio::time::timeout(WATCH_CHECK * 3, session.listener.accept()).await.ok()?.ok()
|
||||
}
|
||||
|
||||
/// The break this catches: a bridge that sits in every session whether or not anyone wants
|
||||
/// notifications (a "Notifications joined" line in every terminal), or that never joins.
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn sessions_are_watched_only_while_a_device_is_subscribed() {
|
||||
let mut session = session();
|
||||
let _record: Publication = session.live.publish(session.runtime.path()).unwrap();
|
||||
let (_dir, book, id) = paired();
|
||||
let (notices, _heard) = mpsc::channel(8);
|
||||
let runtime = session.runtime.path().to_path_buf();
|
||||
let _watching = Watcher(tokio::spawn(watch_sessions(runtime, book.clone(), notices)));
|
||||
assert!(joins(&mut session).await.is_none(), "joined with nobody subscribed");
|
||||
|
||||
subscribe(&book, &id, true);
|
||||
let joined = joins(&mut session).await.expect("joined once a device subscribed");
|
||||
subscribe(&book, &id, false);
|
||||
let mut lines = BufReader::new(joined.stream).lines();
|
||||
let _introduction = lines.next_line().await.unwrap();
|
||||
let ended = tokio::time::timeout(WATCH_CHECK * 3, lines.next_line()).await;
|
||||
assert!(matches!(ended, Ok(Ok(None))), "still watching after the last device left: {ended:?}");
|
||||
}
|
||||
177
crates/luxe-remote/src/push/web_push.rs
Normal file
177
crates/luxe-remote/src/push/web_push.rs
Normal file
@@ -0,0 +1,177 @@
|
||||
//! Web push — one notification posted to the push service a device subscribed through (RFC 8030).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use std::time::Duration;
|
||||
|
||||
use super::encryption::{encrypt, EncryptionError};
|
||||
use super::notice::Notice;
|
||||
use super::{Subscription, Vapid, VapidError};
|
||||
|
||||
/// How long a push service keeps a notification for a device that's offline, in seconds. Past an
|
||||
/// hour, what it says has likely changed.
|
||||
const TIME_TO_LIVE: u32 = 3600;
|
||||
|
||||
/// How long a signed token is good for. Apple takes up to a day.
|
||||
const TOKEN_LIFETIME_SECS: u64 = 12 * 3600;
|
||||
|
||||
/// A token is signed again once it has less than this left. Apple asks for no new token more
|
||||
/// often than hourly, which this keeps to.
|
||||
const TOKEN_RENEWAL_SECS: u64 = 3600;
|
||||
|
||||
/// The longest a post to a push service may take, so a stalled one can't hold the rest back.
|
||||
const POST_TIMEOUT: Duration = Duration::from_secs(15);
|
||||
|
||||
/// What a push service did with a notification.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum Delivery {
|
||||
/// Taken for delivery
|
||||
Taken,
|
||||
/// The subscription has expired or been withdrawn, and won't take any more
|
||||
Gone,
|
||||
}
|
||||
|
||||
/// Why a notification wasn't posted.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub(crate) enum PushError {
|
||||
/// It couldn't be sealed for the device
|
||||
#[error(transparent)]
|
||||
Encryption(#[from] EncryptionError),
|
||||
/// The token couldn't be signed
|
||||
#[error(transparent)]
|
||||
Key(#[from] VapidError),
|
||||
/// The push service couldn't be reached
|
||||
#[error("couldn't reach the push service: {0}")]
|
||||
Network(#[from] reqwest::Error),
|
||||
/// The push service turned it down
|
||||
#[error("the push service refused it with {status}: {reason}")]
|
||||
Refused {
|
||||
/// Its status code
|
||||
status: u16,
|
||||
/// What it said, cut short
|
||||
reason: String,
|
||||
},
|
||||
/// The subscription's endpoint or keys don't read
|
||||
#[error("the subscription doesn't read")]
|
||||
BadSubscription,
|
||||
}
|
||||
|
||||
/// What posts a notification. The bridge's is [`WebPush`]; tests post nowhere.
|
||||
pub(crate) trait Courier: Send + Sync {
|
||||
/// Posts `notice` to `subscription`.
|
||||
fn deliver<'a>(
|
||||
&'a self,
|
||||
subscription: &'a Subscription,
|
||||
notice: &'a Notice,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Delivery, PushError>> + Send + 'a>>;
|
||||
}
|
||||
|
||||
/// A signed token, and when it expires.
|
||||
struct Token {
|
||||
header: String,
|
||||
expires_at: u64,
|
||||
}
|
||||
|
||||
/// The bridge's courier: Web Push over HTTPS, signed with the bridge's key.
|
||||
pub(crate) struct WebPush {
|
||||
client: reqwest::Client,
|
||||
vapid: Vapid,
|
||||
tokens: Mutex<HashMap<String, Token>>,
|
||||
}
|
||||
|
||||
impl WebPush {
|
||||
/// A courier signing with `vapid`.
|
||||
pub(crate) fn new(vapid: Vapid) -> Result<Self, PushError> {
|
||||
let client = reqwest::Client::builder().timeout(POST_TIMEOUT).build()?;
|
||||
Ok(Self { client, vapid, tokens: Mutex::new(HashMap::new()) })
|
||||
}
|
||||
|
||||
/// The post for `notice` to `subscription`, as of `now` (seconds since the Unix epoch).
|
||||
pub(crate) fn request(
|
||||
&self,
|
||||
subscription: &Subscription,
|
||||
notice: &Notice,
|
||||
now: u64,
|
||||
) -> Result<reqwest::Request, PushError> {
|
||||
let audience = subscription.audience().ok_or(PushError::BadSubscription)?;
|
||||
let body = sealed(subscription, notice)?;
|
||||
let urgency = if notice.urgent { "high" } else { "normal" };
|
||||
let mut post = self.client.post(&subscription.endpoint).body(body);
|
||||
post = post.header("TTL", TIME_TO_LIVE).header("Urgency", urgency);
|
||||
post = post.header("Content-Encoding", "aes128gcm");
|
||||
post = post.header("Content-Type", "application/octet-stream");
|
||||
post = post.header("Authorization", self.authorization(&audience, now)?);
|
||||
post = post.header("Topic", topic(¬ice.session));
|
||||
Ok(post.build()?)
|
||||
}
|
||||
|
||||
/// The `Authorization` header for `audience`, reusing a token that has an hour left.
|
||||
fn authorization(&self, audience: &str, now: u64) -> Result<String, PushError> {
|
||||
let mut tokens = self.tokens.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(token) = tokens.get(audience) {
|
||||
if token.expires_at > now + TOKEN_RENEWAL_SECS {
|
||||
return Ok(token.header.clone());
|
||||
}
|
||||
}
|
||||
let expires_at = now + TOKEN_LIFETIME_SECS;
|
||||
let header = self.vapid.authorization(audience, expires_at)?;
|
||||
tokens.insert(audience.to_string(), Token { header: header.clone(), expires_at });
|
||||
Ok(header)
|
||||
}
|
||||
|
||||
async fn post(
|
||||
&self,
|
||||
subscription: &Subscription,
|
||||
notice: &Notice,
|
||||
) -> Result<Delivery, PushError> {
|
||||
let request = self.request(subscription, notice, unix_now())?;
|
||||
let response = self.client.execute(request).await?;
|
||||
let status = response.status();
|
||||
if status.is_success() {
|
||||
return Ok(Delivery::Taken);
|
||||
}
|
||||
if status == reqwest::StatusCode::NOT_FOUND || status == reqwest::StatusCode::GONE {
|
||||
return Ok(Delivery::Gone);
|
||||
}
|
||||
let reason = response.text().await.unwrap_or_default().chars().take(200).collect();
|
||||
Err(PushError::Refused { status: status.as_u16(), reason })
|
||||
}
|
||||
}
|
||||
|
||||
impl Courier for WebPush {
|
||||
fn deliver<'a>(
|
||||
&'a self,
|
||||
subscription: &'a Subscription,
|
||||
notice: &'a Notice,
|
||||
) -> Pin<Box<dyn Future<Output = Result<Delivery, PushError>> + Send + 'a>> {
|
||||
Box::pin(self.post(subscription, notice))
|
||||
}
|
||||
}
|
||||
|
||||
/// `notice` as the service worker reads it, sealed for the subscription's device.
|
||||
fn sealed(subscription: &Subscription, notice: &Notice) -> Result<Vec<u8>, PushError> {
|
||||
let (device_key, auth) = subscription.key_bytes().ok_or(PushError::BadSubscription)?;
|
||||
let message = serde_json::to_vec(notice).expect("a notice is plain strings");
|
||||
Ok(encrypt(&message, &device_key, &auth)?)
|
||||
}
|
||||
|
||||
/// The `Topic` for a session's notifications, so a push service holding several for an offline
|
||||
/// device passes on only the newest. Apple takes at most 32 base64url characters and reads them as
|
||||
/// base64, refusing some lengths, so it's always 32: a hash of the id, which also keeps the id
|
||||
/// itself from the push service.
|
||||
fn topic(session: &str) -> String {
|
||||
use base64::Engine as _;
|
||||
use sha2::Digest as _;
|
||||
let digest = sha2::Sha256::digest(session.as_bytes());
|
||||
base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(&digest[..24])
|
||||
}
|
||||
|
||||
fn unix_now() -> u64 {
|
||||
let since = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH);
|
||||
since.map(|elapsed| elapsed.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
126
crates/luxe-remote/src/push/web_push/tests.rs
Normal file
126
crates/luxe-remote/src/push/web_push/tests.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
use super::*;
|
||||
use crate::push::encryption::tests::open;
|
||||
use crate::push::SubscriptionKeys;
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use base64::Engine;
|
||||
use ring::agreement::{EphemeralPrivateKey, ECDH_P256};
|
||||
|
||||
const NOW: u64 = 1_800_000_000;
|
||||
const SESSION: &str = "5898d57b-0000-4000-8000-000000000001";
|
||||
|
||||
/// A device's private key and the subscription its browser would make with it.
|
||||
fn device() -> (EphemeralPrivateKey, Subscription) {
|
||||
let private = EphemeralPrivateKey::generate(&ECDH_P256, &ring::rand::SystemRandom::new());
|
||||
let private = private.unwrap();
|
||||
let public = private.compute_public_key().unwrap();
|
||||
let keys = SubscriptionKeys {
|
||||
p256dh: URL_SAFE_NO_PAD.encode(public.as_ref()),
|
||||
auth: URL_SAFE_NO_PAD.encode([7u8; 16]),
|
||||
};
|
||||
(private, Subscription { endpoint: "https://web.push.apple.com/abc".into(), keys })
|
||||
}
|
||||
|
||||
fn courier() -> WebPush {
|
||||
WebPush::new(Vapid::generate().unwrap().0).unwrap()
|
||||
}
|
||||
|
||||
fn notice(urgent: bool) -> Notice {
|
||||
let (title, body) = ("luxe-dev".into(), "Approve bash".into());
|
||||
Notice { title, body, session: SESSION.into(), urgent }
|
||||
}
|
||||
|
||||
fn header<'a>(request: &'a reqwest::Request, name: &str) -> &'a str {
|
||||
request.headers()[name].to_str().unwrap()
|
||||
}
|
||||
|
||||
/// The post goes to the subscription with the headers a push service requires, and the device
|
||||
/// opens the body to the notice the service worker shows.
|
||||
///
|
||||
/// The break this catches: a missing `TTL` (Apple's `BadTtl`) or encoding, the wrong urgency, or a
|
||||
/// body sealed for someone else or carrying fields the worker doesn't read.
|
||||
#[test]
|
||||
fn a_post_carries_what_the_push_service_and_the_device_need() {
|
||||
let (private, subscription) = device();
|
||||
let request = courier().request(&subscription, ¬ice(true), NOW).unwrap();
|
||||
assert_eq!(request.url().as_str(), subscription.endpoint);
|
||||
assert_eq!(header(&request, "TTL"), "3600");
|
||||
assert_eq!(header(&request, "Urgency"), "high");
|
||||
assert_eq!(header(&request, "Content-Encoding"), "aes128gcm");
|
||||
assert_eq!(header(&request, "Topic"), "DJZtLYoay56CTZC7EDzavnWaSjSnBF8s");
|
||||
assert!(header(&request, "Authorization").starts_with("vapid t="));
|
||||
let body = request.body().and_then(reqwest::Body::as_bytes).unwrap();
|
||||
let (device_key, auth) = subscription.key_bytes().unwrap();
|
||||
let opened = open(private, &device_key, &auth, body);
|
||||
let shown: serde_json::Value = serde_json::from_slice(&opened[..opened.len() - 1]).unwrap();
|
||||
let expected =
|
||||
serde_json::json!({ "title": "luxe-dev", "body": "Approve bash", "session": SESSION });
|
||||
assert_eq!(shown, expected);
|
||||
let later = courier().request(&subscription, ¬ice(false), NOW).unwrap();
|
||||
assert_eq!(header(&later, "Urgency"), "normal");
|
||||
}
|
||||
|
||||
/// The claims inside a request's token.
|
||||
fn claims(request: &reqwest::Request) -> serde_json::Value {
|
||||
let token = header(request, "Authorization").strip_prefix("vapid t=").unwrap();
|
||||
let claims = token.split('.').nth(1).unwrap();
|
||||
serde_json::from_slice(&URL_SAFE_NO_PAD.decode(claims).unwrap()).unwrap()
|
||||
}
|
||||
|
||||
/// The break this catches: a token signed for every post, which Apple asks servers not to do more
|
||||
/// than hourly, or one kept past its expiry, which it refuses; or a token for the wrong service.
|
||||
#[test]
|
||||
fn a_token_is_reused_until_it_has_an_hour_left() {
|
||||
let (_, subscription) = device();
|
||||
let courier = courier();
|
||||
let first = courier.request(&subscription, ¬ice(true), NOW).unwrap();
|
||||
let token = |request: &reqwest::Request| header(request, "Authorization").to_string();
|
||||
let expected = serde_json::json!({ "aud": "https://web.push.apple.com", "exp": NOW + TOKEN_LIFETIME_SECS, "sub": "https://luxe.dev" });
|
||||
assert_eq!(claims(&first), expected);
|
||||
let renew_at = NOW + TOKEN_LIFETIME_SECS - TOKEN_RENEWAL_SECS;
|
||||
let reused = courier.request(&subscription, ¬ice(true), renew_at - 1).unwrap();
|
||||
assert_eq!(token(&reused), token(&first));
|
||||
let renewed = courier.request(&subscription, ¬ice(true), renew_at).unwrap();
|
||||
assert_eq!(claims(&renewed)["exp"], renew_at + TOKEN_LIFETIME_SECS);
|
||||
}
|
||||
|
||||
/// The topic is 32 base64url characters whatever the id, and differs between sessions.
|
||||
///
|
||||
/// The break this catches: a session id passed through whole, whose 36 characters Apple refuses
|
||||
/// (`BadWebPushTopic`), a shorter one at a length Apple can't read as base64, or one topic for
|
||||
/// every session, so a newer notice from one session replaces another's.
|
||||
#[test]
|
||||
fn a_topic_is_always_32_url_safe_characters() {
|
||||
assert_eq!(topic(SESSION), "DJZtLYoay56CTZC7EDzavnWaSjSnBF8s");
|
||||
assert_eq!(topic("short-1"), "GA5_ZXQcTDu9kMi-CVbgVxwQ_TCZQ-fp");
|
||||
assert_eq!(topic("").len(), 32);
|
||||
}
|
||||
|
||||
/// A push service on this machine that answers every post with the status in its path.
|
||||
async fn push_service() -> String {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let answer = |axum::extract::Path(status): axum::extract::Path<u16>| async move {
|
||||
(axum::http::StatusCode::from_u16(status).unwrap(), "BadDeviceToken")
|
||||
};
|
||||
let app = axum::Router::new().route("/{status}", axum::routing::post(answer));
|
||||
tokio::spawn(async move { axum::serve(listener, app).await });
|
||||
format!("http://{address}")
|
||||
}
|
||||
|
||||
async fn delivered(courier: &WebPush, service: &str, status: u16) -> String {
|
||||
let (_, mut subscription) = device();
|
||||
subscription.endpoint = format!("{service}/{status}");
|
||||
format!("{:?}", courier.deliver(&subscription, ¬ice(false)).await)
|
||||
}
|
||||
|
||||
/// The break this catches: a dropped subscription (404 or 410) taken as a failure, so it's posted
|
||||
/// to forever, or any other refusal taken as gone, so one bad request forgets a working device.
|
||||
#[tokio::test]
|
||||
async fn what_the_push_service_answers_is_told_apart() {
|
||||
let (courier, service) = (courier(), push_service().await);
|
||||
assert_eq!(delivered(&courier, &service, 201).await, "Ok(Taken)");
|
||||
assert_eq!(delivered(&courier, &service, 404).await, "Ok(Gone)");
|
||||
assert_eq!(delivered(&courier, &service, 410).await, "Ok(Gone)");
|
||||
let refused = delivered(&courier, &service, 400).await;
|
||||
assert!(refused.contains("status: 400") && refused.contains("BadDeviceToken"), "{refused}");
|
||||
}
|
||||
Reference in New Issue
Block a user