Skip to main content

rusty_time_wasm/
lib.rs

1//! rusty_time-wasm — disciplined time for the browser and the edge.
2//!
3//! This is the capability chrony cannot follow us into. There is no OS clock to
4//! adjust here and no UDP socket to use, so instead of *setting* time this
5//! crate *estimates* it: the page keeps calling `now_ms()` and gets a corrected
6//! reading, with an honest error bound attached.
7//!
8//! **The split is deliberate.** JavaScript owns the transport — `fetch`,
9//! WebTransport, a worker, whatever the page has — and this crate owns the time
10//! math. That keeps the protocol identical to the native client (the same
11//! packet codec, the same regression filter, both already fuzzed) and leaves
12//! the one part that genuinely differs per environment in the environment's own
13//! hands.
14//!
15//! The wire format is a real NTPv4 packet, not a JSON shape invented for the
16//! browser: one codec, one set of tests, and a gateway that is an NTP server
17//! with an HTTP door on it.
18
19use rusty_time_core::ntp::{self, HEADER_LEN, LeapIndicator, Mode, NtpPacket, NtpTimestamp};
20use rusty_time_core::{Sample, SampleRegister, VirtualClock};
21
22#[cfg(target_arch = "wasm32")]
23use wasm_bindgen::prelude::*;
24
25/// Milliseconds of extra error we attribute to a browser exchange beyond the
26/// measured delay — the page's timers are coarse and its scheduling is not
27/// ours to control, so the bound stays honest about that.
28const BROWSER_ERROR_FLOOR_MS: f64 = 1.0;
29
30/// How many samples the register keeps. Small: a browser tab is not a daemon
31/// and should not hold a long history it will never use.
32const REGISTER_CAPACITY: usize = 16;
33
34/// A disciplined view of time for a page or an edge function.
35#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
36pub struct TimeClient {
37    register: SampleRegister,
38    vclock: VirtualClock,
39    /// Wall-clock time (ms) when the in-flight request was built.
40    pending_t1_ms: Option<f64>,
41    /// The nonce we put in that request's transmit field, echoed back as
42    /// origin — the only spoofing check an unauthenticated exchange has.
43    pending_nonce: NtpTimestamp,
44    /// Monotonic reading paired with the last accepted sample.
45    last_mono_ms: f64,
46    accepted: u32,
47    rejected: u32,
48}
49
50impl Default for TimeClient {
51    fn default() -> Self {
52        Self::new_inner()
53    }
54}
55
56impl TimeClient {
57    fn new_inner() -> Self {
58        TimeClient {
59            register: SampleRegister::new(REGISTER_CAPACITY),
60            vclock: VirtualClock::new(),
61            pending_t1_ms: None,
62            pending_nonce: NtpTimestamp::ZERO,
63            last_mono_ms: 0.0,
64            accepted: 0,
65            rejected: 0,
66        }
67    }
68
69    /// Build a client request. `date_now_ms` is the page's `Date.now()`, and
70    /// `nonce` must be unpredictable — it is echoed back as the origin
71    /// timestamp and is what stops an off-path attacker forging a reply.
72    pub fn build_request_with_nonce(&mut self, date_now_ms: f64, nonce: u64) -> Vec<u8> {
73        let nonce = NtpTimestamp(nonce);
74        self.pending_nonce = nonce;
75        self.pending_t1_ms = Some(date_now_ms);
76        NtpPacket::client_request(4, nonce).to_bytes().to_vec()
77    }
78
79    /// Feed a gateway response. Returns true if it was accepted.
80    ///
81    /// `date_now_ms` is `Date.now()` at receipt (T4) and `perf_now_ms` is
82    /// `performance.now()`, which is monotonic and therefore what the estimate
83    /// is anchored to — `Date.now()` can jump under us at any moment.
84    pub fn process_response_inner(
85        &mut self,
86        bytes: &[u8],
87        date_now_ms: f64,
88        perf_now_ms: f64,
89    ) -> bool {
90        let Some(t1_ms) = self.pending_t1_ms else {
91            self.rejected += 1;
92            return false;
93        };
94        if bytes.len() < HEADER_LEN {
95            self.rejected += 1;
96            return false;
97        }
98        let Ok(packet) = NtpPacket::parse(bytes) else {
99            self.rejected += 1;
100            return false;
101        };
102
103        // Everything that makes a reply *ours* and *usable*, before any of its
104        // numbers are allowed to influence the clock.
105        let usable = packet.mode == Mode::Server
106            && packet.origin_ts == self.pending_nonce
107            && packet.stratum != 0
108            && packet.stratum <= 15
109            && packet.leap != LeapIndicator::Unsynchronized
110            && !packet.receive_ts.is_zero()
111            && !packet.transmit_ts.is_zero();
112        if !usable {
113            self.rejected += 1;
114            return false;
115        }
116        self.pending_t1_ms = None;
117
118        // Resolve the server's timestamps near our own reading, so the NTP era
119        // is unambiguous without the page having to know what an era is.
120        let t1 = t1_ms / 1e3;
121        let t4 = date_now_ms / 1e3;
122        let t2 = ntp_to_unix_near(packet.receive_ts, t1);
123        let t3 = ntp_to_unix_near(packet.transmit_ts, t4);
124        let (offset, delay) = ntp::offset_delay(t1, t2, t3, t4);
125        if delay < 0.0 {
126            // Non-causal: the exchange cannot have happened this way.
127            self.rejected += 1;
128            return false;
129        }
130
131        let mono_s = perf_now_ms / 1e3;
132        self.register.push(Sample {
133            t: mono_s,
134            offset,
135            delay,
136            dispersion: packet.root_dispersion.to_seconds(),
137        });
138        self.last_mono_ms = perf_now_ms;
139        self.accepted += 1;
140
141        // Prefer the regression once it has enough spread; fall back to the
142        // lowest-delay sample, which is the least contaminated single reading.
143        let (best_offset, error_s) = match self.register.regress(mono_s) {
144            Some(est) => (
145                est.offset,
146                est.offset_sd.max(delay / 2.0) + BROWSER_ERROR_FLOOR_MS / 1e3,
147            ),
148            None => (offset, delay / 2.0 + BROWSER_ERROR_FLOOR_MS / 1e3),
149        };
150        self.vclock.update(mono_s, best_offset, None, error_s);
151        true
152    }
153}
154
155/// Resolve an NTP timestamp into Unix seconds near a pivot (era disambiguation).
156fn ntp_to_unix_near(ts: NtpTimestamp, pivot_unix_s: f64) -> f64 {
157    const ERA: f64 = 4_294_967_296.0;
158    let base = ts.seconds() as f64 - ntp::UNIX_EPOCH_OFFSET as f64 + ts.fraction() as f64 / ERA;
159    let mut best = base;
160    let mut best_dist = (base - pivot_unix_s).abs();
161    for k in [-1.0f64, 1.0] {
162        let candidate = base + k * ERA;
163        let distance = (candidate - pivot_unix_s).abs();
164        if distance < best_dist {
165            best = candidate;
166            best_dist = distance;
167        }
168    }
169    best
170}
171
172#[cfg_attr(target_arch = "wasm32", wasm_bindgen)]
173impl TimeClient {
174    #[cfg_attr(target_arch = "wasm32", wasm_bindgen(constructor))]
175    pub fn new() -> TimeClient {
176        TimeClient::new_inner()
177    }
178
179    /// Build a request, drawing the nonce from the caller.
180    ///
181    /// Exposed this way because the page has `crypto.getRandomValues` and this
182    /// crate should not carry a random source into wasm just to duplicate it.
183    pub fn build_request(&mut self, date_now_ms: f64, nonce_hi: u32, nonce_lo: u32) -> Vec<u8> {
184        let nonce = ((nonce_hi as u64) << 32) | nonce_lo as u64;
185        self.build_request_with_nonce(date_now_ms, nonce)
186    }
187
188    /// Feed a gateway response; returns true if it was accepted.
189    pub fn process_response(&mut self, bytes: &[u8], date_now_ms: f64, perf_now_ms: f64) -> bool {
190        self.process_response_inner(bytes, date_now_ms, perf_now_ms)
191    }
192
193    /// Corrected Unix time in milliseconds. Never steps backwards.
194    pub fn now_ms(&mut self, date_now_ms: f64, perf_now_ms: f64) -> f64 {
195        self.vclock.now(perf_now_ms / 1e3, date_now_ms / 1e3) * 1e3
196    }
197
198    /// Current error bound in milliseconds; `Infinity` until the first
199    /// accepted exchange. Mesh apps gate CRDT and capability decisions on this
200    /// rather than assuming the clock is good.
201    pub fn confidence_ms(&self, perf_now_ms: f64) -> f64 {
202        self.vclock.confidence(perf_now_ms / 1e3) * 1e3
203    }
204
205    /// The correction currently applied, in milliseconds.
206    pub fn offset_ms(&mut self, perf_now_ms: f64) -> f64 {
207        let mono_s = perf_now_ms / 1e3;
208        self.register
209            .regress(mono_s)
210            .map(|e| e.offset * 1e3)
211            .or_else(|| self.register.best().map(|b| b.offset * 1e3))
212            .unwrap_or(0.0)
213    }
214
215    pub fn is_synchronized(&self) -> bool {
216        self.vclock.is_synchronized()
217    }
218
219    pub fn accepted(&self) -> u32 {
220        self.accepted
221    }
222
223    pub fn rejected(&self) -> u32 {
224        self.rejected
225    }
226}
227
228#[cfg(test)]
229mod tests;