feat(session): lien à usage unique et journal des refus
CI / Formatting, tests and builds (push) Successful in 2m29s
CI / Formatting, tests and builds (push) Successful in 2m29s
Le jeton de room ouvrait la session jusqu'à ce que l'hôte en tire un autre : une URL photographiée ou collée dans un message servait pendant toute sa durée de validité (#35). Le premier appareil qui s'en sert le consomme désormais, la room tire aussitôt un nouveau jeton, et le QR code affiché change. Un lien déjà servi est refusé avec `token_used`, distinct de `token_expired` pour que le spectateur sache qu'il doit rescanner et pas qu'il s'est trompé. - L'appareil qui a consommé le lien le garde : il revient avec après une coupure ou une veille. Un appareil déconnecté par l'hôte est refusé avec `kicked`, même avec ce jeton. - Le code court n'est pas consommé. Il est dicté à voix haute, limité en débit, et chaque échange rend le jeton du moment. Un code qui tournerait après chaque spectateur obligerait l'hôte à le redicter pour un secret qui ne circule pas par un lien recopiable. - Les refus sont gardés (les 32 derniers : instant, adresse, appareil, cause), exposés dans l'état de partage donc dans l'interface de l'hôte et dans `/api/session`, et journalisés. Le panneau « Connexions refusées » les affiche. - La place est réservée avant l'autorisation : une room pleine ne consomme pas le lien du spectateur suivant, qui pourra réessayer. - La moitié « empreinte de certificat » du ticket tombe, et l'ADR 0010 dit pourquoi : l'ADR 0005 a établi qu'un navigateur ne peut pas épingler une empreinte et que le mode par défaut est HTTP sur le LAN. Il n'y a donc pas de certificat auquel lier le jeton, et prétendre le vérifier rassurerait à tort. Corrigé au passage dans ARCHITECTURE.md : le canal de signalement y était décrit comme chiffré et épinglé par empreinte, ce qui contredit l'ADR 0005 depuis la décision #65. Vérifié : quatre tests unitaires de room (rejeu refusé, lien tourné, code réutilisable, journal borné), le test de bout en bout rejoue l'URL capturée et relit les deux refus dans l'état de l'hôte, cargo test --workspace vert, clippy -D warnings, tsc, lint et tests des deux fronts.
This commit is contained in:
1 parent
a49d1002f8
commit
7937108fdc
22 files changed
+491
-69
No files matched your search
Generated
+1
@@ -1766,6 +1766,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tower-http",
|
||||
"tracing",
|
||||
"ts-rs",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
|
||||
@@ -23,7 +23,7 @@ test:
|
||||
# They are excluded from the formatter and the linter (see biome.json): their
|
||||
# format belongs to ts-rs, otherwise every `make` leaves a diff in the repository.
|
||||
proto:
|
||||
cargo test -p rs-proto -p rs-store -p rs-session export_bindings
|
||||
cargo test -p rs-proto -p rs-store -p rs-session -p rs-signaling export_bindings
|
||||
|
||||
build:
|
||||
cargo build --workspace
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { RefusalCause } from "./RefusalCause";
|
||||
|
||||
/**
|
||||
* A connection the host refused, kept for the interface and the diagnostics:
|
||||
* "who tried to get in, from where, and why it failed" answers most session
|
||||
* questions without reading a log (#35).
|
||||
*/
|
||||
export type Refusal = {
|
||||
/**
|
||||
* When, in milliseconds since the Unix epoch.
|
||||
*/
|
||||
at_ms: number, address: string,
|
||||
/**
|
||||
* Device name announced by the viewer, empty if it never said.
|
||||
*/
|
||||
device: string, cause: RefusalCause, };
|
||||
@@ -0,0 +1,6 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
/**
|
||||
* Why a connection was refused, as the host interface names it (#35).
|
||||
*/
|
||||
export type RefusalCause = "bad_token" | "token_used" | "expired_token" | "kicked" | "room_full";
|
||||
@@ -1,4 +1,5 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
import type { Refusal } from "./Refusal";
|
||||
import type { SharedSource } from "./SharedSource";
|
||||
import type { ViewerDevice } from "./ViewerDevice";
|
||||
|
||||
@@ -39,4 +40,9 @@ listen: string,
|
||||
/**
|
||||
* Chosen interface, `None` if the host listens everywhere.
|
||||
*/
|
||||
interface: string | null, devices: Array<ViewerDevice>, limit: number, started_ms: number, };
|
||||
interface: string | null, devices: Array<ViewerDevice>,
|
||||
/**
|
||||
* Connections refused since the share started, newest first (#35): who
|
||||
* tried, from where, and why it did not work.
|
||||
*/
|
||||
refusals: Array<Refusal>, limit: number, started_ms: number, };
|
||||
@@ -127,6 +127,26 @@ export function SharePanel({ share, onDisconnect, onNewCode }: Props) {
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{share.refusals.length > 0 && (
|
||||
<div className='card'>
|
||||
<h2 className='viewers-title'>
|
||||
{t('refused')}
|
||||
<span className='counter'>{share.refusals.length}</span>
|
||||
</h2>
|
||||
<ul className='devices'>
|
||||
{share.refusals.slice(0, 5).map((refusal) => (
|
||||
<li key={`${refusal.at_ms}-${refusal.address}-${refusal.cause}`}>
|
||||
<span className='device-name'>{refusal.device || t('unknownDevice')}</span>
|
||||
<span className='muted'>
|
||||
{t(`refusal.${refusal.cause}`)} · {refusal.address} ·{' '}
|
||||
{duration(refusal.at_ms, now)}
|
||||
</span>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -16,6 +16,8 @@ import { type WakeReason, watchLifecycle } from './lifecycle';
|
||||
export type ViewerErrorCode =
|
||||
| 'bad_token'
|
||||
| 'token_expired'
|
||||
/** The link was valid but another device used it first (#35). */
|
||||
| 'token_used'
|
||||
| 'bad_version'
|
||||
| 'room_full'
|
||||
| 'protocol_violation'
|
||||
@@ -54,6 +56,7 @@ export type SessionOptions = {
|
||||
const TERMINAL_CODES: ReadonlySet<string> = new Set([
|
||||
'bad_token',
|
||||
'token_expired',
|
||||
'token_used',
|
||||
'bad_version',
|
||||
'room_full',
|
||||
'kicked',
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type ErrorCode = "bad_version" | "bad_token" | "token_expired" | "room_full" | "source_unavailable" | "protocol_violation" | "internal" | "kicked" | "share_ended";
|
||||
export type ErrorCode = "bad_version" | "bad_token" | "token_expired" | "token_used" | "room_full" | "source_unavailable" | "protocol_violation" | "internal" | "kicked" | "share_ended";
|
||||
@@ -19,6 +19,10 @@ pub enum ErrorCode {
|
||||
/// a new one: distinct from `BadToken` so the viewer knows it needs a
|
||||
/// fresh QR code, not that it made a mistake (#19).
|
||||
TokenExpired,
|
||||
/// The token was valid and still in time, but another device used it
|
||||
/// first: the link is good for one viewer (#35). The viewer asks for the
|
||||
/// new QR code shown by the host, exactly as for `TokenExpired`.
|
||||
TokenUsed,
|
||||
RoomFull,
|
||||
SourceUnavailable,
|
||||
ProtocolViolation,
|
||||
|
||||
@@ -828,6 +828,7 @@ fn describe(view: &mut View) -> Share {
|
||||
since_ms: d.since_ms,
|
||||
})
|
||||
.collect(),
|
||||
refusals: view.room.refusals(),
|
||||
limit: view.room.limit(),
|
||||
started_ms: view.started_ms,
|
||||
}
|
||||
|
||||
@@ -193,6 +193,9 @@ pub struct Share {
|
||||
/// Chosen interface, `None` if the host listens everywhere.
|
||||
pub interface: Option<String>,
|
||||
pub devices: Vec<ViewerDevice>,
|
||||
/// Connections refused since the share started, newest first (#35): who
|
||||
/// tried, from where, and why it did not work.
|
||||
pub refusals: Vec<rs_signaling::Refusal>,
|
||||
pub limit: u8,
|
||||
#[ts(type = "number")]
|
||||
pub started_ms: u64,
|
||||
|
||||
@@ -144,12 +144,35 @@ async fn a_viewer_appears_then_is_kicked_and_cannot_come_back() {
|
||||
.expect("the viewer must disappear")
|
||||
.unwrap();
|
||||
|
||||
// Same device, same token: refused. Another device gets in.
|
||||
// Same device, same token: refused, because the host disconnected it.
|
||||
let (_ws, refused) = viewer(port, &room, &token, "tablet").await;
|
||||
assert_eq!(refused["code"], "kicked", "{refused}");
|
||||
let (_ws, welcome) = viewer(port, &room, &token, "phone").await;
|
||||
// The link is single use (#35): the token that let the tablet in no longer
|
||||
// opens the door, so the phone needs the fresh one the host now shows.
|
||||
let (_ws, spent) = viewer(port, &room, &token, "phone").await;
|
||||
assert_eq!(spent["code"], "token_used", "{spent}");
|
||||
let fresh = host.state().share.expect("share").url;
|
||||
let (_, _, fresh_token) = identifiers(&fresh);
|
||||
assert_ne!(fresh_token, token, "the link must rotate after a use");
|
||||
let (_ws, welcome) = viewer(port, &room, &fresh_token, "phone").await;
|
||||
assert_eq!(welcome["type"], "welcome", "{welcome}");
|
||||
|
||||
// Both refusals are visible to the interface, with their cause.
|
||||
let refusals = host.state().share.expect("share").refusals;
|
||||
assert!(
|
||||
refusals
|
||||
.iter()
|
||||
.any(|r| r.cause == rs_signaling::RefusalCause::Kicked),
|
||||
"{refusals:?}"
|
||||
);
|
||||
assert!(
|
||||
refusals
|
||||
.iter()
|
||||
.any(|r| r.cause == rs_signaling::RefusalCause::TokenUsed
|
||||
&& r.device == "device phone"),
|
||||
"{refusals:?}"
|
||||
);
|
||||
|
||||
host.stop().await;
|
||||
assert_eq!(host.state().phase, Phase::Stopped);
|
||||
assert!(host.state().share.is_none());
|
||||
|
||||
@@ -24,6 +24,7 @@ rcgen = "0.14.10"
|
||||
sha2 = "0.11.1"
|
||||
tower-http = { version = "0.7.1", features = ["fs"] }
|
||||
qrcode = { version = "0.14.1", default-features = false }
|
||||
ts-rs = "12.0.1"
|
||||
|
||||
[dev-dependencies]
|
||||
image = { version = "0.25.10", default-features = false }
|
||||
|
||||
@@ -15,7 +15,7 @@ pub mod room;
|
||||
pub mod server;
|
||||
pub mod tls;
|
||||
|
||||
pub use room::{CodeExchange, Device, Registration, Room, RoomError};
|
||||
pub use room::{CodeExchange, Device, Refusal, RefusalCause, Registration, Room, RoomError};
|
||||
pub use server::{
|
||||
Diagnostics, HostConfig, ServerError, SharedMediaSource, bind_listener, serve, serve_listener,
|
||||
session_url,
|
||||
|
||||
+260
-34
@@ -5,22 +5,29 @@
|
||||
//! connected devices, which the host interface shows and can disconnect one
|
||||
//! from (#15).
|
||||
//!
|
||||
//! Access (#19) comes down to three things: a 128-bit token carried by the QR
|
||||
//! code, a six-character short code for whoever has no camera, and a validity
|
||||
//! period. The host can issue a new access at any time: the old one no longer
|
||||
//! lets anyone in, but a device already admitted to the room comes back with
|
||||
//! it, after a dropout or a sleep. Expiry closes the door to newcomers, not to
|
||||
//! those already inside.
|
||||
//! Access (#19, #35) comes down to three things: a 128-bit token carried by the
|
||||
//! QR code, a six-character short code for whoever has no camera, and a validity
|
||||
//! period. The token is **single use**: the first device to present it consumes
|
||||
//! it, and the host's link rotates to a fresh one for the next viewer, so a
|
||||
//! photographed or pasted URL stops opening anything as soon as it served once.
|
||||
//! The short code, dictated out loud and rate-limited, stays valid: each
|
||||
//! exchange hands out the token of the moment.
|
||||
//!
|
||||
//! A device already admitted to the room keeps coming back with the token it
|
||||
//! used, after a dropout or a sleep. Expiry closes the door to newcomers, not to
|
||||
//! those already inside. Every refusal is kept, with its cause, for the host
|
||||
//! interface (#35).
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::net::IpAddr;
|
||||
use std::sync::atomic::{AtomicU8, AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rs_proto::{RoomId, SessionToken, SourceInfo, StreamSettings};
|
||||
use serde::Serialize;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::sync::{Notify, watch};
|
||||
use ts_rs::TS;
|
||||
|
||||
use rand::RngExt;
|
||||
|
||||
@@ -59,6 +66,15 @@ const ATTEMPTS_PER_ADDRESS: u32 = 5;
|
||||
const ATTEMPTS_TOTAL: u32 = 30;
|
||||
const ATTEMPT_WINDOW: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Why a token that was valid no longer opens the door.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
enum Spent {
|
||||
/// The host drew a new access; the old one only lets admitted devices in.
|
||||
Rotated,
|
||||
/// A device got in with it: a link is good for one device (#35).
|
||||
Used { by: String },
|
||||
}
|
||||
|
||||
/// The current way in: token, short code, deadline.
|
||||
struct Access {
|
||||
token: SessionToken,
|
||||
@@ -66,28 +82,45 @@ struct Access {
|
||||
/// Deadline in Unix milliseconds: the wall clock moves on during a sleep,
|
||||
/// the monotonic clock does not, and a sleep counts toward the validity.
|
||||
expires_ms: Option<u64>,
|
||||
/// Tokens and codes issued before, to answer "expired" rather than
|
||||
/// "invalid" to whoever presents one.
|
||||
old_tokens: Vec<SessionToken>,
|
||||
/// Tokens issued before, with the reason they stopped working, to answer
|
||||
/// "already used" or "expired" rather than "invalid" (#35).
|
||||
old_tokens: VecDeque<(SessionToken, Spent)>,
|
||||
old_codes: Vec<String>,
|
||||
}
|
||||
|
||||
/// Tokens kept after use: enough for a room where devices come and go, small
|
||||
/// enough that the list cannot grow for a whole day of sharing.
|
||||
const SPENT_TOKENS_KEPT: usize = 32;
|
||||
|
||||
impl Access {
|
||||
fn draw(validity: Option<Duration>) -> Self {
|
||||
let mut rng = rand::rng();
|
||||
let token: [u8; 16] = rng.random();
|
||||
let code: [u8; 6] = rng.random();
|
||||
let code: [u8; 6] = rand::rng().random();
|
||||
Self {
|
||||
token: SessionToken::new(hex::encode(token)),
|
||||
token: Self::draw_token(),
|
||||
code: RoomId::from_bytes(&code)
|
||||
.map(|c| c.as_str().to_string())
|
||||
.unwrap_or_default(),
|
||||
expires_ms: validity.map(|d| now_ms().saturating_add(d.as_millis() as u64)),
|
||||
old_tokens: Vec::new(),
|
||||
old_tokens: VecDeque::new(),
|
||||
old_codes: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn draw_token() -> SessionToken {
|
||||
let token: [u8; 16] = rand::rng().random();
|
||||
SessionToken::new(hex::encode(token))
|
||||
}
|
||||
|
||||
/// Retires the current token, keeping the code and the deadline: the link
|
||||
/// shown by the host changes, the code dictated out loud does not.
|
||||
fn spend_token(&mut self, spent: Spent) {
|
||||
let retired = std::mem::replace(&mut self.token, Self::draw_token());
|
||||
self.old_tokens.push_back((retired, spent));
|
||||
while self.old_tokens.len() > SPENT_TOKENS_KEPT {
|
||||
self.old_tokens.pop_front();
|
||||
}
|
||||
}
|
||||
|
||||
fn expired(&self) -> bool {
|
||||
self.expires_ms.is_some_and(|end| now_ms() >= end)
|
||||
}
|
||||
@@ -136,6 +169,54 @@ impl Attempts {
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a connection was refused, as the host interface names it (#35).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
#[ts(export, export_to = "../../../desktop/src/bindings/")]
|
||||
pub enum RefusalCause {
|
||||
/// The token does not belong to this room.
|
||||
BadToken,
|
||||
/// The token was valid: another device used it first, so the link is spent.
|
||||
TokenUsed,
|
||||
/// The token expired, or the host drew a new access.
|
||||
ExpiredToken,
|
||||
/// The host disconnected this device earlier.
|
||||
Kicked,
|
||||
/// No seat left.
|
||||
RoomFull,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for RefusalCause {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(match self {
|
||||
Self::BadToken => "invalid token",
|
||||
Self::TokenUsed => "the link was already used by another device",
|
||||
Self::ExpiredToken => "token expired or replaced by the host",
|
||||
Self::Kicked => "device disconnected by the host",
|
||||
Self::RoomFull => "no seat left",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A connection the host refused, kept for the interface and the diagnostics:
|
||||
/// "who tried to get in, from where, and why it failed" answers most session
|
||||
/// questions without reading a log (#35).
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, TS)]
|
||||
#[ts(export, export_to = "../../../desktop/src/bindings/")]
|
||||
pub struct Refusal {
|
||||
/// When, in milliseconds since the Unix epoch.
|
||||
#[ts(type = "number")]
|
||||
pub at_ms: u64,
|
||||
pub address: String,
|
||||
/// Device name announced by the viewer, empty if it never said.
|
||||
pub device: String,
|
||||
pub cause: RefusalCause,
|
||||
}
|
||||
|
||||
/// Refusals kept for the interface: a session that lasts an evening must not
|
||||
/// grow a list nobody reads.
|
||||
const REFUSALS_KEPT: usize = 32;
|
||||
|
||||
/// The outcome of exchanging a short code.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum CodeExchange {
|
||||
@@ -161,6 +242,8 @@ pub struct Room {
|
||||
present: Mutex<Vec<Present>>,
|
||||
/// Devices disconnected by the host: they do not come back with this token.
|
||||
banned: Mutex<Vec<String>>,
|
||||
/// Refusals, newest last. Bounded: the interface shows the last ones.
|
||||
refusals: Mutex<VecDeque<Refusal>>,
|
||||
next_connection: AtomicU64,
|
||||
/// Bumped on every arrival or departure: the interface subscribes to it
|
||||
/// instead of polling.
|
||||
@@ -185,6 +268,7 @@ impl Room {
|
||||
connected: AtomicU8::new(0),
|
||||
present: Mutex::new(Vec::new()),
|
||||
banned: Mutex::new(Vec::new()),
|
||||
refusals: Mutex::new(VecDeque::new()),
|
||||
next_connection: AtomicU64::new(1),
|
||||
changes: watch::Sender::new(0),
|
||||
}
|
||||
@@ -224,7 +308,9 @@ impl Room {
|
||||
let mut access = lock(&self.access);
|
||||
let mut fresh = Access::draw(validity);
|
||||
fresh.old_tokens = std::mem::take(&mut access.old_tokens);
|
||||
fresh.old_tokens.push(access.token.clone());
|
||||
fresh
|
||||
.old_tokens
|
||||
.push_back((access.token.clone(), Spent::Rotated));
|
||||
fresh.old_codes = std::mem::take(&mut access.old_codes);
|
||||
fresh.old_codes.push(access.code.clone());
|
||||
*access = fresh;
|
||||
@@ -232,6 +318,36 @@ impl Room {
|
||||
self.notify();
|
||||
}
|
||||
|
||||
/// The refusals the host interface shows, newest first.
|
||||
pub fn refusals(&self) -> Vec<Refusal> {
|
||||
lock(&self.refusals).iter().rev().cloned().collect()
|
||||
}
|
||||
|
||||
/// Keeps a refused connection for the interface, and says so in the log:
|
||||
/// a viewer turned away is the first thing to look at when a tablet "does
|
||||
/// not connect" (#35).
|
||||
pub fn record_refusal(&self, address: IpAddr, device: &str, cause: RefusalCause) {
|
||||
tracing::warn!(
|
||||
event = "connection_refused",
|
||||
%address,
|
||||
device,
|
||||
cause = %cause,
|
||||
"connection refused"
|
||||
);
|
||||
let mut refusals = lock(&self.refusals);
|
||||
refusals.push_back(Refusal {
|
||||
at_ms: now_ms(),
|
||||
address: address.to_string(),
|
||||
device: device.to_string(),
|
||||
cause,
|
||||
});
|
||||
while refusals.len() > REFUSALS_KEPT {
|
||||
refusals.pop_front();
|
||||
}
|
||||
drop(refusals);
|
||||
self.notify();
|
||||
}
|
||||
|
||||
/// Exchanges a short code for the room and the token.
|
||||
pub fn exchange_code(&self, input: &str, address: IpAddr) -> CodeExchange {
|
||||
let code = rs_proto::normalize_code(input);
|
||||
@@ -354,10 +470,14 @@ impl Room {
|
||||
/// Checks that an entry request targets this room and carries a token that
|
||||
/// still opens it.
|
||||
///
|
||||
/// The errors are distinct on purpose: an invalid token, an expired token
|
||||
/// and an unknown room do not mean the same thing to the user nor to the
|
||||
/// logs. `device` is the viewer's stable identifier: an already admitted
|
||||
/// device comes back with an expired or replaced token.
|
||||
/// The errors are distinct on purpose: an invalid token, a spent one, an
|
||||
/// expired token and an unknown room do not mean the same thing to the user
|
||||
/// nor to the logs. `device` is the viewer's stable identifier: an already
|
||||
/// admitted device comes back with the token it used (#35).
|
||||
///
|
||||
/// The token is single use: the first device to present it consumes it and
|
||||
/// the host's link rotates, so the same URL no longer opens the door for
|
||||
/// anyone else. The code, dictated out loud, is not consumed that way.
|
||||
pub fn authorize(
|
||||
&self,
|
||||
room: &RoomId,
|
||||
@@ -367,21 +487,47 @@ impl Room {
|
||||
if room != &self.id {
|
||||
return Err(RoomError::UnknownRoom);
|
||||
}
|
||||
let access = lock(&self.access);
|
||||
let current = access.token.matches(token.as_str());
|
||||
let old = access.old_tokens.iter().any(|t| t.matches(token.as_str()));
|
||||
if !current && !old {
|
||||
return Err(RoomError::BadToken);
|
||||
}
|
||||
if current && !access.expired() {
|
||||
return Ok(());
|
||||
if self.is_banned(device) {
|
||||
return Err(RoomError::Kicked);
|
||||
}
|
||||
let already_admitted =
|
||||
!device.is_empty() && lock(&self.admitted).iter().any(|a| a == device);
|
||||
if already_admitted {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RoomError::ExpiredToken)
|
||||
let mut access = lock(&self.access);
|
||||
if access.token.matches(token.as_str()) {
|
||||
if access.expired() {
|
||||
return if already_admitted {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RoomError::ExpiredToken)
|
||||
};
|
||||
}
|
||||
if !device.is_empty() {
|
||||
access.spend_token(Spent::Used {
|
||||
by: device.to_string(),
|
||||
});
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
match access
|
||||
.old_tokens
|
||||
.iter()
|
||||
.find(|(t, _)| t.matches(token.as_str()))
|
||||
{
|
||||
None => Err(RoomError::BadToken),
|
||||
Some((_, Spent::Used { by })) => {
|
||||
if by == device || already_admitted {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RoomError::TokenUsed)
|
||||
}
|
||||
}
|
||||
Some((_, Spent::Rotated)) => {
|
||||
if already_admitted {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(RoomError::ExpiredToken)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -447,12 +593,29 @@ pub enum RoomError {
|
||||
UnknownRoom,
|
||||
#[error("invalid token")]
|
||||
BadToken,
|
||||
#[error("this link was already used by another device: scan the QR code shown by the host")]
|
||||
TokenUsed,
|
||||
#[error("token expired or replaced by the host")]
|
||||
ExpiredToken,
|
||||
#[error("the host disconnected this device")]
|
||||
Kicked,
|
||||
#[error("room full: {limit} viewers at most")]
|
||||
Full { limit: u8 },
|
||||
}
|
||||
|
||||
impl RoomError {
|
||||
/// How the host interface names the refusal (#35).
|
||||
pub fn refusal(&self) -> RefusalCause {
|
||||
match self {
|
||||
Self::UnknownRoom | Self::BadToken => RefusalCause::BadToken,
|
||||
Self::TokenUsed => RefusalCause::TokenUsed,
|
||||
Self::ExpiredToken => RefusalCause::ExpiredToken,
|
||||
Self::Kicked => RefusalCause::Kicked,
|
||||
Self::Full { .. } => RefusalCause::RoomFull,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -618,10 +781,73 @@ mod tests {
|
||||
room.regenerate(None);
|
||||
assert_eq!(
|
||||
room.authorize(&room.id, &first, "tablet"),
|
||||
Err(RoomError::ExpiredToken)
|
||||
Err(RoomError::Kicked)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_link_opens_the_door_once() {
|
||||
let room = room(5);
|
||||
let link = room.token();
|
||||
assert!(room.authorize(&room.id, &link, "tablet").is_ok());
|
||||
// The host's link moved on: the URL a neighbour photographed is spent.
|
||||
assert_ne!(room.token(), link);
|
||||
assert_eq!(
|
||||
room.authorize(&room.id, &link, "phone"),
|
||||
Err(RoomError::TokenUsed)
|
||||
);
|
||||
// The device that used it still comes back with it.
|
||||
assert!(room.authorize(&room.id, &link, "tablet").is_ok());
|
||||
// And the new link opens for the next device.
|
||||
assert!(room.authorize(&room.id, &room.token(), "phone").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_code_is_not_consumed_by_the_first_viewer() {
|
||||
let room = room(5);
|
||||
let code = room.code();
|
||||
let first = match room.exchange_code(&code, ip(30)) {
|
||||
CodeExchange::Accepted { token, .. } => token,
|
||||
other => panic!("code refused: {other:?}"),
|
||||
};
|
||||
assert!(room.authorize(&room.id, &first, "tablet").is_ok());
|
||||
// Somebody else types the same code: it still works, with the token of
|
||||
// the moment.
|
||||
let second = match room.exchange_code(&code, ip(31)) {
|
||||
CodeExchange::Accepted { token, .. } => token,
|
||||
other => panic!("code refused on second use: {other:?}"),
|
||||
};
|
||||
assert_ne!(first, second);
|
||||
assert!(room.authorize(&room.id, &second, "phone").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refusals_are_kept_newest_first_with_their_cause() {
|
||||
let room = room(5);
|
||||
let mut changes = room.subscribe();
|
||||
room.record_refusal(ip(30), "tablet", RefusalCause::Kicked);
|
||||
changes.mark_unchanged();
|
||||
room.record_refusal(ip(31), "phone", RefusalCause::TokenUsed);
|
||||
assert!(changes.has_changed().unwrap());
|
||||
let kept = room.refusals();
|
||||
assert_eq!(kept.len(), 2);
|
||||
assert_eq!(kept[0].cause, RefusalCause::TokenUsed);
|
||||
assert_eq!(kept[0].address, "192.168.1.31");
|
||||
assert_eq!(kept[0].device, "phone");
|
||||
assert_eq!(kept[1].cause, RefusalCause::Kicked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_refusal_list_stays_bounded() {
|
||||
let room = room(5);
|
||||
for i in 0..REFUSALS_KEPT + 5 {
|
||||
room.record_refusal(ip(30), &format!("device {i}"), RefusalCause::BadToken);
|
||||
}
|
||||
let kept = room.refusals();
|
||||
assert_eq!(kept.len(), REFUSALS_KEPT);
|
||||
assert_eq!(kept[0].device, format!("device {}", REFUSALS_KEPT + 4));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_short_code_opens_the_room() {
|
||||
let room = room(5);
|
||||
|
||||
@@ -25,7 +25,7 @@ use serde::Serialize;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::qr;
|
||||
use crate::room::{CodeExchange, Room};
|
||||
use crate::room::{CodeExchange, Refusal, RefusalCause, Room};
|
||||
use crate::tls::TlsMaterial;
|
||||
|
||||
const HELLO_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
|
||||
@@ -131,6 +131,8 @@ struct SessionInfo {
|
||||
connected: u8,
|
||||
limit: u8,
|
||||
uptime_seconds: u64,
|
||||
/// Connections turned away, newest first (#35).
|
||||
refusals: Vec<Refusal>,
|
||||
}
|
||||
|
||||
/// Opens the listening port, without serving yet.
|
||||
@@ -339,6 +341,7 @@ async fn session_info(
|
||||
fingerprint: state.fingerprint.clone(),
|
||||
connected: state.room.connected(),
|
||||
limit: state.room.limit(),
|
||||
refusals: state.room.refusals(),
|
||||
uptime_seconds: state.started.elapsed().as_secs(),
|
||||
}))
|
||||
}
|
||||
@@ -514,11 +517,11 @@ async fn handle_socket(mut socket: WebSocket, state: Arc<AppState>, peer: Socket
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
let name = device_name(&device);
|
||||
if state.room.is_banned(&device.id.0) {
|
||||
tracing::warn!(
|
||||
event = "connection_refused",
|
||||
"device disconnected by the host"
|
||||
);
|
||||
state
|
||||
.room
|
||||
.record_refusal(peer.ip(), &name, RefusalCause::Kicked);
|
||||
let _ = send(
|
||||
&mut socket,
|
||||
&error(ErrorCode::Kicked, "the host disconnected this device"),
|
||||
@@ -526,24 +529,30 @@ async fn handle_socket(mut socket: WebSocket, state: Arc<AppState>, peer: Socket
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
if let Err(e) = state.room.authorize(&room_id, &token, &device.id.0) {
|
||||
let code = match e {
|
||||
crate::room::RoomError::UnknownRoom => ErrorCode::BadToken,
|
||||
crate::room::RoomError::BadToken => ErrorCode::BadToken,
|
||||
crate::room::RoomError::ExpiredToken => ErrorCode::TokenExpired,
|
||||
crate::room::RoomError::Full { .. } => ErrorCode::RoomFull,
|
||||
};
|
||||
tracing::warn!(%e, "connection refused");
|
||||
let _ = send(&mut socket, &error(code, &e.to_string())).await;
|
||||
return;
|
||||
}
|
||||
// The seat comes first: a full room must not spend the link of the next
|
||||
// viewer, which is single use (#35).
|
||||
let connected = match state.room.admit() {
|
||||
Ok(n) => n,
|
||||
Err(e) => {
|
||||
state.room.record_refusal(peer.ip(), &name, e.refusal());
|
||||
let _ = send(&mut socket, &error(ErrorCode::RoomFull, &e.to_string())).await;
|
||||
return;
|
||||
}
|
||||
};
|
||||
if let Err(e) = state.room.authorize(&room_id, &token, &device.id.0) {
|
||||
state.room.release();
|
||||
state.room.record_refusal(peer.ip(), &name, e.refusal());
|
||||
let code = match e {
|
||||
crate::room::RoomError::UnknownRoom => ErrorCode::BadToken,
|
||||
crate::room::RoomError::BadToken => ErrorCode::BadToken,
|
||||
crate::room::RoomError::TokenUsed => ErrorCode::TokenUsed,
|
||||
crate::room::RoomError::ExpiredToken => ErrorCode::TokenExpired,
|
||||
crate::room::RoomError::Kicked => ErrorCode::Kicked,
|
||||
crate::room::RoomError::Full { .. } => ErrorCode::RoomFull,
|
||||
};
|
||||
let _ = send(&mut socket, &error(code, &e.to_string())).await;
|
||||
return;
|
||||
}
|
||||
tracing::info!(
|
||||
event = "session_opened",
|
||||
device = %device.name,
|
||||
@@ -588,12 +597,9 @@ async fn handle_socket(mut socket: WebSocket, state: Arc<AppState>, peer: Socket
|
||||
return;
|
||||
};
|
||||
|
||||
let registration = state.room.register(
|
||||
&device.id.0,
|
||||
&device_name(&device),
|
||||
device.platform.clone(),
|
||||
peer.ip(),
|
||||
);
|
||||
let registration = state
|
||||
.room
|
||||
.register(&device.id.0, &name, device.platform.clone(), peer.ip());
|
||||
let connection = registration.connection;
|
||||
|
||||
let welcome = ServerMessage::Welcome {
|
||||
|
||||
@@ -123,10 +123,12 @@ système, prévention d'une fermeture accidentelle.
|
||||
|
||||
- Le média est chiffré de bout en bout par DTLS-SRTP entre l'hôte et le navigateur ; le serveur de
|
||||
signalement ne voit pas les frames.
|
||||
- Le canal de signalement est chiffré (WSS). Le certificat est auto-signé et épinglé par empreinte
|
||||
dans le QR code, ce qui remplace une autorité de certification locale.
|
||||
- Chaque room porte un jeton aléatoire (128 bits) et une durée de vie. Une connexion sans jeton est
|
||||
refusée, sauf en mode « réseau de confiance » explicite.
|
||||
- Le canal de signalement circule en clair sur le LAN en mode par défaut, TLS auto-signé en option
|
||||
(ADR 0005): aucun navigateur ne sait épingler un certificat depuis une URL. Le média, lui, est
|
||||
toujours chiffré par DTLS-SRTP.
|
||||
- Chaque room porte un jeton aléatoire (128 bits) **à usage unique**, une durée de vie et un journal
|
||||
des refus (ADR 0010). Une connexion sans jeton est refusée, sauf en mode « réseau de confiance »
|
||||
explicite.
|
||||
- Appareils de confiance : après appairage, une clé publique d'appareil permet de reconnecter sans
|
||||
mot de passe ; la révocation est immédiate et locale.
|
||||
- Aucune télémétrie, aucun appel sortant. Un test d'intégration vérifie l'absence de connexion
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
# ADR 0010: lien à usage unique, code court réutilisable
|
||||
|
||||
Statut: adoptée le 28 octobre 2026 (issue #35).
|
||||
|
||||
## Contexte
|
||||
|
||||
Le jeton de room vivait jusqu'à ce que l'hôte en tire un autre: une URL photographiée, collée dans
|
||||
un message ou retrouvée dans l'historique d'un navigateur ouvrait la session pendant toute sa durée
|
||||
de validité. Le ticket #35 demandait un jeton à usage unique « lié à une empreinte de certificat,
|
||||
vérifié des deux côtés », avec un journal des refus consultable.
|
||||
|
||||
La seconde moitié ne tient pas: l'ADR 0005 a établi qu'un navigateur ne peut pas vérifier
|
||||
l'empreinte d'un certificat avant d'établir la connexion, que le mode par défaut est HTTP sur le
|
||||
LAN et que le TLS auto-signé est une option dont l'empreinte n'est pas vérifiée par le viewer. Il
|
||||
n'y a donc, en mode par défaut, aucun certificat auquel lier quoi que ce soit. Faire semblant de
|
||||
vérifier une empreinte serait pire que ne pas en parler.
|
||||
|
||||
Reste le vrai risque, celui qui se produit: un lien qui traîne et qui sert à quelqu'un d'autre.
|
||||
|
||||
## Décision
|
||||
|
||||
1. **Le jeton est à usage unique.** Le premier appareil qui s'en sert le consomme. La room tire
|
||||
aussitôt un nouveau jeton, donc le QR code et le lien affichés par l'hôte changent: le suivant
|
||||
scanne celui-là. Un lien déjà servi est refusé avec `token_used`, distinct de `token_expired`
|
||||
pour que le spectateur sache qu'il doit rescanner plutôt que de chercher une faute de sa part.
|
||||
2. **L'appareil qui a consommé le lien le garde.** Il revient avec, après une coupure ou une mise
|
||||
en veille, sans rescanner: la liste des appareils admis de la room le reconnaît. Un appareil
|
||||
déconnecté par l'hôte est refusé même avec ce jeton (cause `kicked`).
|
||||
3. **Le code court n'est pas consommé.** Il est dicté à voix haute, limité en débit (cinq essais par
|
||||
adresse, trente au total par minute), et chaque échange rend le jeton du moment, qui sera
|
||||
consommé par le premier appareil à s'en servir. Un code qui tournerait après chaque spectateur
|
||||
obligerait l'hôte à le relire à chaque fois, pour un gain nul: il ne circule pas par un lien
|
||||
qu'on peut recopier.
|
||||
4. **Les refus sont gardés.** Les trente-deux derniers refus (instant, adresse, nom d'appareil,
|
||||
cause) sont exposés dans l'état du partage, donc dans l'interface de l'hôte et dans
|
||||
`/api/session`, et journalisés. « Qui a essayé, d'où, et pourquoi ça n'a pas marché » se lit sans
|
||||
ouvrir un journal.
|
||||
|
||||
## Conséquences
|
||||
|
||||
- Un lien intercepté ne sert qu'une fois, et seulement s'il n'a pas encore servi. La fenêtre est
|
||||
celle du premier scan, pas celle de la session.
|
||||
- Le QR code affiché change à chaque nouvel appareil. C'est voulu, et l'interface le reflète: elle
|
||||
redessine le QR depuis la room à chaque changement d'état.
|
||||
- Plusieurs spectateurs en même temps demandent plusieurs scans, un par appareil. Sur un écran
|
||||
d'hôte, c'est un scan de plus; sur un lien envoyé par messagerie, le second destinataire doit
|
||||
demander le lien à jour.
|
||||
- La place est réservée avant l'autorisation: une room pleine ne consomme pas le lien du spectateur
|
||||
suivant, qui pourra réessayer quand une place se libère.
|
||||
- Le journal est borné, sinon une session d'une soirée ferait grossir un état recopié à chaque
|
||||
changement.
|
||||
|
||||
## Alternatives écartées
|
||||
|
||||
- **Empreinte de certificat dans le hello, comparée des deux côtés**: sans certificat en mode par
|
||||
défaut, et sans moyen pour le navigateur de vérifier la session TLS réelle en mode `--tls`, la
|
||||
comparaison ne prouve rien contre un attaquant sur le chemin. Elle rassurerait à tort.
|
||||
- **Jeton valable jusqu'à la fin de la session, journal des refus seul**: laisse un lien copié
|
||||
ouvrir la session des heures durant. C'est le défaut qu'on corrige.
|
||||
- **Code court à usage unique aussi**: oblige l'hôte à redicter le code devant chaque spectateur,
|
||||
pour un secret qui ne circule pas par un lien recopiable.
|
||||
- **Jeton à durée très courte (une minute)**: ne distingue pas un lien qui traîne d'un spectateur
|
||||
lent à scanner, et punit l'usage normal.
|
||||
|
||||
## Condition de réouverture
|
||||
|
||||
Si l'appairage d'appareils de confiance (#34) rend le premier contact rare, le coût d'un scan par
|
||||
spectateur disparaît et la rotation peut devenir la seule règle. Si un mode TLS avec certificat
|
||||
d'autorité interne se répand, l'épinglage d'empreinte redevient possible, et cette ADR se rouvre
|
||||
pour la partie que l'ADR 0005 interdit aujourd'hui.
|
||||
@@ -16,6 +16,7 @@ le 26 octobre 2026 (issue #2); les suivantes tranchent ce qui restait ouvert.
|
||||
| [0007](0007-reprise-apres-coupure.md) | reprise après coupure réseau | renégociation complète, pas d'ICE restart |
|
||||
| [0008](0008-format-des-diagnostics.md) | diagnostics exportés | archive zip locale, manifeste et journaux expurgés, aucun envoi |
|
||||
| [0009](0009-capture-wayland-et-ecran-virtuel.md) | capture Linux et écran virtuel | PipeWire en feature, repli x11rb, type `VIRTUAL` du portail |
|
||||
| [0010](0010-jeton-usage-unique.md) | accès à la session | lien à usage unique, code court réutilisable, journal des refus |
|
||||
|
||||
Aucune décision structurante n'est ouverte à ce jour. Une nouvelle décision ouvre une issue, puis
|
||||
une ADR au même plan quand elle est tranchée.
|
||||
+13
-3
@@ -93,11 +93,21 @@ room et le jeton. Un code vaut un jeton: cinq essais faux par adresse et trente
|
||||
minute, puis `429` avec le délai. À 31⁶ codes possibles, une chance sur 500 000 par heure de
|
||||
validité.
|
||||
|
||||
Le jeton et le code **expirent** (réglage `validite_code_min`, 60 minutes par défaut, 0 pour
|
||||
Le jeton est **à usage unique** (ADR 0010): le premier appareil qui s'en sert le consomme, et la
|
||||
room en tire un autre aussitôt, donc le QR code et le lien affichés changent. Un lien déjà servi est
|
||||
refusé avec `token_used` (« ce lien a déjà servi, scannez celui que l'hôte affiche »), distinct de
|
||||
`bad_token` pour que le spectateur sache qu'il n'a rien à se reprocher. Le code court, lui, n'est
|
||||
pas consommé: chaque échange rend le jeton du moment.
|
||||
|
||||
Le jeton et le code **expirent** aussi (réglage `validite_code_min`, 60 minutes par défaut, 0 pour
|
||||
jamais), et « Nouveau code » en tire d'autres. L'expiration ferme la porte aux nouveaux venus, pas
|
||||
aux spectateurs déjà admis: un appareil entré une fois revient après une coupure ou une veille
|
||||
avec l'ancien jeton, sauf si l'hôte l'a déconnecté. Un nouvel appareil avec un jeton périmé reçoit
|
||||
`token_expired` (« ce QR code a expiré »), distinct de `bad_token`.
|
||||
avec le jeton qui l'a fait entrer, sauf si l'hôte l'a déconnecté (`kicked`). Un nouvel appareil
|
||||
avec un jeton périmé reçoit `token_expired`.
|
||||
|
||||
Les **refus sont gardés**: les trente-deux derniers (instant, adresse, appareil, cause), dans
|
||||
l'interface de l'hôte et dans `/api/session`. « Qui a essayé, d'où, et pourquoi ça n'a pas marché »
|
||||
se lit sans ouvrir un journal.
|
||||
|
||||
Sans avertissement de certificat: c'est vrai en HTTP (décision #65), le mode par défaut. En
|
||||
`--tls`, le certificat est auto-signé et le navigateur avertit une fois, avec ou sans empreinte dans
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
"errors": {
|
||||
"bad_token": "This link matches no session on this host. Scan its QR code again, or type its short code.",
|
||||
"token_expired": "This QR code has expired or was replaced by the host. Scan the one it shows now.",
|
||||
"token_used": "This link was already used by another device: it is good for one viewer. Scan the QR code the host shows now.",
|
||||
"bad_version": "The host and this viewer do not speak the same protocol version.",
|
||||
"room_full": "The session has reached its maximum number of viewers.",
|
||||
"source_unavailable": "The source shared by the host is no longer available.",
|
||||
@@ -103,6 +104,16 @@
|
||||
"nobody": "Nobody yet. The link and the QR code next to this let people join.",
|
||||
"disconnect": "Disconnect",
|
||||
"disconnectHelp": "The device is cut off and cannot come back with this link.",
|
||||
"refused": "Refused connections",
|
||||
"refusedNone": "No connection refused since this share started.",
|
||||
"unknownDevice": "unnamed device",
|
||||
"refusal": {
|
||||
"bad_token": "link matching no session",
|
||||
"token_used": "link already used by another device",
|
||||
"expired_token": "QR code expired or replaced",
|
||||
"kicked": "device disconnected by you",
|
||||
"room_full": "no seat left"
|
||||
},
|
||||
"sleepInhibited": "Sleep suspended while sharing",
|
||||
"sleepNotInhibited": "Sleep could not be suspended: the screen may turn off.",
|
||||
"settings": "Settings",
|
||||
|
||||
@@ -52,6 +52,7 @@
|
||||
"errors": {
|
||||
"bad_token": "Ce lien ne correspond à aucune session de cet hôte. Scannez à nouveau son QR code, ou tapez son code court.",
|
||||
"token_expired": "Ce QR code a expiré ou a été remplacé par l’hôte. Scannez celui qu’il affiche maintenant.",
|
||||
"token_used": "Ce lien a déjà servi à un autre appareil: il ne vaut que pour un seul spectateur. Scannez le QR code que l’hôte affiche maintenant.",
|
||||
"bad_version": "L’hôte et ce spectateur ne parlent pas la même version du protocole.",
|
||||
"room_full": "La session a atteint son nombre maximum de spectateurs.",
|
||||
"source_unavailable": "La source partagée par l’hôte n’est plus disponible.",
|
||||
@@ -103,6 +104,16 @@
|
||||
"nobody": "Personne pour l’instant. Le lien et le QR code ci-contre permettent de rejoindre.",
|
||||
"disconnect": "Déconnecter",
|
||||
"disconnectHelp": "L’appareil est coupé et ne peut plus revenir avec ce lien.",
|
||||
"refused": "Connexions refusées",
|
||||
"refusedNone": "Aucune connexion refusée depuis le début du partage.",
|
||||
"unknownDevice": "appareil sans nom",
|
||||
"refusal": {
|
||||
"bad_token": "lien qui ne correspond à aucune session",
|
||||
"token_used": "lien déjà utilisé par un autre appareil",
|
||||
"expired_token": "QR code expiré ou remplacé",
|
||||
"kicked": "appareil déconnecté par vous",
|
||||
"room_full": "plus de place"
|
||||
},
|
||||
"sleepInhibited": "Mise en veille suspendue pendant le partage",
|
||||
"sleepNotInhibited": "La mise en veille n’a pas pu être suspendue: l’écran peut s’éteindre.",
|
||||
"settings": "Réglages",
|
||||
|
||||
Reference in new issue
Block a user