Skip to content
Merged
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
2 changes: 1 addition & 1 deletion PROTOCOL.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,7 +244,7 @@ Quick Ask's `quick_shot` fails with `helper_failed` (the message is the helper's
| `ask_keychain` | none | `{}`: asks macOS again, in a child, about every secret it refused; sends `keychain_changed` (and again when the child ends). Refused to devices on the LAN |
| `lan_status` | none | `{on, port?, urls?, tailscaleUrls?, fingerprint?, devices:[Device]}`: whether the LAN client is serving, its URLs on local networks, its URLs on the user's Tailscale network (the MagicDNS name, then 100.64.0.0/10 addresses), its self-signed certificate's SHA-256 fingerprint, and paired devices |
| `set_lan` | `on` | `{}` with the new `lan_status`; turns the LAN client on or off and remembers it in `lan/on` |
| `pair_device` | none | `{code, expiresAt}`: opens a 6-digit pairing code that lasts 5 minutes or 5 tries; only one open at a time |
| `pair_device` | none | `{code, expiresAt, url?, qr?}`: opens a 6-digit pairing code that lasts 5 minutes or 5 tries; only one open at a time. When a network address is available, `url` is `https://<host>:<port>/?pair=<code>` and `qr` is `{size, rows}` for rendering a QR code. Paired Devices also serve `/manifest.webmanifest`, `/icon.svg`, `/sw.js`, and authenticated Web Push endpoints `GET /api/push/key`, `POST /api/push/subscribe`, `POST /api/push/unsubscribe` (VAPID key stored in Keychain; secret prompts never carry bot text or secret names in push payloads). |
| `remove_device` | `device` (an id) | `{}`: forgets the device, ending its active sessions immediately |
| `get_channels` | `bot` | `{channels: [{kind, hasToken, pairing, chats: [{chat, name}], error}]}`: one entry for `telegram` and one for `discord`. The token itself is never sent back. `pairing` says whether the code last given by `pair_channel` still lets a chat in. `error` says why the channel is not connected, else `null` |
| `set_channel` | `bot`, `kind`, `token` (empty: remove) | `{}`: saves the bot token of the channel and connects, or removes the channel and its paired chats. Code `token_in_use` when another bot has the same token |
Expand Down
20 changes: 19 additions & 1 deletion appd/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7158,6 +7158,19 @@ impl Core {
if let Some(used) = used {
self.routine_tokens(bot, id, used);
}
if matches!(
ev,
Event::TurnEnd {
reason: proto::TurnEnd::Done,
..
}
) {
let summary = ended.as_ref().map(|(s, _)| s.as_str()).unwrap_or("");
self.lan.notify_push(crate::push::payload_for_done(
&self.name_of(bot),
summary,
));
}
}
self.broadcast(&json!({"type": "bots_changed"}));
}
Expand Down Expand Up @@ -7200,8 +7213,13 @@ impl Core {
return;
};
self.record(bot, &conversation, with_context(&ev));
if matches!(ev, Event::Question { .. }) {
if let Event::Question { title, secret, .. } = &ev {
self.broadcast(&json!({"type": "bots_changed"}));
self.lan.notify_push(crate::push::payload_for_question(
&self.name_of(bot),
title,
secret.is_some(),
));
}
// The bot has replied: the conversation is titled, if it has no title yet.
if let Event::TurnEnd {
Expand Down
87 changes: 76 additions & 11 deletions appd/src/lan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

use crate::keychain;
use crate::paths;
use crate::push::Push;
use crate::sys::{self, log, now_ms};
use proto::MAX_WINDOW_FRAME;
use rustls::pki_types::pem::PemObject;
Expand Down Expand Up @@ -99,10 +100,12 @@ struct State {
asked: u64,
}

/// The state, and the switch: held while serving is turned on or off, which can take seconds,
/// so that such requests run one after another. It holds the thread that accepts connections,
/// if one runs. The state's own lock is never held that long.
pub struct Lan(Mutex<State>, Mutex<Option<thread::JoinHandle<()>>>);
/// The state, the switch (held while serving is turned on or off), and the Web Push store.
pub struct Lan(
Mutex<State>,
Mutex<Option<thread::JoinHandle<()>>>,
Arc<Push>,
);

fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
m.lock().unwrap_or_else(|e| e.into_inner())
Expand Down Expand Up @@ -133,11 +136,16 @@ impl Lan {
devices,
..State::default()
};
let lan = Arc::new(Lan(Mutex::new(state), Mutex::new(None)));
let lan = Arc::new(Lan(Mutex::new(state), Mutex::new(None), Push::load()));
lan.resume();
lan
}

/// Sends a Web Push notification to all subscribed paired devices on a background thread.
pub fn notify_push(&self, payload: Value) {
self.2.notify(payload);
}

/// Serves if the user left it on and it is not serving: at start, and again when the
/// Keychain, which held back the certificate's key, has been answered.
pub fn resume(self: &Arc<Self>) {
Expand Down Expand Up @@ -255,12 +263,29 @@ impl Lan {
return Err("turn on the page for other devices first".into());
}
let code = sys::pair_code();
let port = state.port;
let magic_dns = state.magic_dns.clone();
state.code = Some(Code {
code: code.clone(),
until: Instant::now() + CODE_LIFE,
tries: 0,
});
Ok(json!({"code": code, "expiresAt": now_ms() + CODE_LIFE.as_millis() as u64}))
let (lan, tailnet) = split(addresses());
let first_host = magic_dns
.or_else(|| tailnet.first().map(Ipv4Addr::to_string))
.or_else(|| lan.first().map(Ipv4Addr::to_string));
let mut out = json!({
"code": code,
"expiresAt": now_ms() + CODE_LIFE.as_millis() as u64,
});
if let Some(host) = first_host {
let url = format!("https://{host}:{port}/?pair={code}");
if let Some(qr) = proto::qr::encode(&url) {
out["qr"] = json!({"size": qr.size, "rows": qr.rows()});
}
out["url"] = json!(url);
}
Ok(out)
}

/// Forgets a device; its open pages lose their connection at once.
Expand All @@ -272,6 +297,7 @@ impl Lan {
return Err(format!("no device `{device}`"));
}
state.sessions.retain(|_, s| s.device != device);
self.2.remove_device(device);
save(&state.devices)
}

Expand Down Expand Up @@ -366,7 +392,9 @@ impl Lan {
};
}
// Only the page itself sends this; a page of another site cannot without asking.
if r.method != "POST" && r.path != "/api/recv" || r.header("x-bate") != Some("1") {
let is_get_ok =
r.method == "GET" && matches!(r.path.as_str(), "/api/recv" | "/api/push/key");
if (r.method != "POST" && !is_get_ok) || r.header("x-bate") != Some("1") {
return Answer::error(403, "not from Bate's page");
}
if r.path == "/api/pair" {
Expand All @@ -378,6 +406,37 @@ impl Lan {
let session = query(&r.query, "session");
match r.path.as_str() {
"/api/session" => self.open_session(&device),
"/api/push/key" => match self.2.public_key() {
Ok(public_key) => Answer::json(200, &json!({"publicKey": public_key})),
Err(e) => Answer::error(500, &e),
},
"/api/push/subscribe" => {
let Ok(v) = serde_json::from_slice::<Value>(&r.body) else {
return Answer::error(400, "send {endpoint, keys: {p256dh, auth}}");
};
let endpoint = v["endpoint"].as_str().unwrap_or("");
let p256dh = v["keys"]["p256dh"]
.as_str()
.or_else(|| v["p256dh"].as_str())
.unwrap_or("");
let auth = v["keys"]["auth"]
.as_str()
.or_else(|| v["auth"].as_str())
.unwrap_or("");
match self.2.subscribe(&device, endpoint, p256dh, auth) {
Ok(()) => Answer::json(200, &json!({})),
Err(e) => Answer::error(400, &e),
}
}
"/api/push/unsubscribe" => {
let endpoint = serde_json::from_slice::<Value>(&r.body)
.ok()
.and_then(|v| v["endpoint"].as_str().map(str::to_owned));
match self.2.unsubscribe(&device, endpoint.as_deref()) {
Ok(()) => Answer::json(200, &json!({})),
Err(e) => Answer::error(500, &e),
}
}
"/api/send" | "/api/recv" => {
let found = lock(&self.0).sessions.get(session).cloned();
let Some(s) = found.filter(|s| s.device == device) else {
Expand Down Expand Up @@ -870,14 +929,20 @@ fn static_file(path: &str) -> Answer {
"png" => "image/png",
"ico" => "image/x-icon",
"woff2" => "font/woff2",
"webmanifest" => "application/manifest+json; charset=utf-8",
"json" => "application/json; charset=utf-8",
_ => "application/octet-stream",
};
let mut headers = vec![
("content-type", kind.into()),
("content-security-policy", PAGE_POLICY.into()),
];
if path == "/sw.js" {
headers.push(("service-worker-allowed", "/".into()));
}
Answer {
status: 200,
headers: vec![
("content-type", kind.into()),
("content-security-policy", PAGE_POLICY.into()),
],
headers,
body: body.to_vec(),
}
}
Expand Down
1 change: 1 addition & 0 deletions appd/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ mod paths;
mod precheck;
mod project_server;
mod proxy;
mod push;
mod report;
mod roles;
mod schedule;
Expand Down
Loading
Loading