grindr 0.1.1+26.9.1.163471

Unofficial async Rust client for the Grindr API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use std::sync::{Arc, Mutex, Once};

use tokio::sync::{broadcast, mpsc, watch, Notify};
use wreq::{
    Client, EmulationProvider, Http2Config, Method, PseudoOrder, SettingsOrder, SslCurve,
    TlsConfig, TlsVersion,
};

use crate::auth::{AuthEvent, AuthState, LoginResult, Session};
use crate::device::DeviceInfo;
use crate::error::GrindrError;
use crate::headers::build_user_agent;
use crate::rest::{Fingerprint, InnerClient, RawResponse};
use crate::ws::{make_channels, WsChannels, WsCommand, WsConnectionState, WsEvent};

/// References <https://opengrind.org/grindr-api/security-headers#cipher-suites>
const MODERN_TLS_CIPHERS: &str = concat!(
    "TLS_AES_128_GCM_SHA256",
    ":TLS_AES_256_GCM_SHA384",
    ":TLS_CHACHA20_POLY1305_SHA256",
    ":TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256",
    ":TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
    ":TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384",
    ":TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
    ":TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256",
    ":TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256",
    ":TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA",
    ":TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA",
    ":TLS_RSA_WITH_AES_128_GCM_SHA256",
    ":TLS_RSA_WITH_AES_256_GCM_SHA384",
    ":TLS_RSA_WITH_AES_128_CBC_SHA",
    ":TLS_RSA_WITH_AES_256_CBC_SHA",
);

/// References <https://opengrind.org/grindr-api/security-headers#extensions>
const SIGALGS: &str = concat!(
    "ecdsa_secp256r1_sha256",
    ":rsa_pss_rsae_sha256",
    ":rsa_pkcs1_sha256",
    ":ecdsa_secp384r1_sha384",
    ":rsa_pss_rsae_sha384",
    ":rsa_pkcs1_sha384",
    ":rsa_pss_rsae_sha512",
    ":rsa_pkcs1_sha512",
    ":rsa_pkcs1_sha1",
);

const CURVES: &[SslCurve] = &[SslCurve::X25519, SslCurve::SECP256R1, SslCurve::SECP384R1];

/// References <https://opengrind.org/grindr-api/security-headers#pseudoheaders>
const PSEUDO_ORDER: [PseudoOrder; 4] = [
    PseudoOrder::Method,
    PseudoOrder::Path,
    PseudoOrder::Authority,
    PseudoOrder::Scheme,
];

/// References <https://opengrind.org/grindr-api/security-headers#frames>
const SETTINGS_ORDER: [SettingsOrder; 8] = [
    SettingsOrder::InitialWindowSize,
    SettingsOrder::HeaderTableSize,
    SettingsOrder::EnablePush,
    SettingsOrder::MaxConcurrentStreams,
    SettingsOrder::MaxFrameSize,
    SettingsOrder::MaxHeaderListSize,
    SettingsOrder::UnknownSetting8,
    SettingsOrder::UnknownSetting9,
];

const OKHTTP_WINDOW_SIZE: u32 = 16 * 1024 * 1024;

fn okhttp_tls_config() -> TlsConfig {
    TlsConfig::builder()
        .enable_ocsp_stapling(true)
        .pre_shared_key(true)
        .curves(CURVES)
        .sigalgs_list(SIGALGS)
        .cipher_list(MODERN_TLS_CIPHERS)
        .min_tls_version(TlsVersion::TLS_1_2)
        .max_tls_version(TlsVersion::TLS_1_3)
        .build()
}

fn okhttp_http2_config() -> Http2Config {
    Http2Config::builder()
        .initial_stream_window_size(OKHTTP_WINDOW_SIZE)
        .initial_connection_window_size(OKHTTP_WINDOW_SIZE)
        .headers_pseudo_order(PSEUDO_ORDER)
        .settings_order(SETTINGS_ORDER)
        .build()
}

fn grindr_emulation() -> EmulationProvider {
    EmulationProvider::builder()
        .tls_config(okhttp_tls_config())
        .http2_config(okhttp_http2_config())
        .default_headers(None)
        .build()
}

/// The [`EmulationProvider`] that gives a `wreq` client the same TLS and HTTP/2
/// fingerprint as the Android app.
///
/// Use it to build your own `wreq::Client` with the same fingerprint (see the
/// `fingerprint_check` example).
pub fn probe_emulation() -> EmulationProvider {
    grindr_emulation()
}

/// Shared `wreq` setup: the emulation profile plus gzip-only encoding.
fn grindr_client_builder() -> wreq::ClientBuilder {
    Client::builder()
        .emulation(grindr_emulation())
        .gzip(true)
        .no_deflate()
        .no_brotli()
        .no_zstd()
}

fn build_http_client() -> Result<Client, GrindrError> {
    grindr_client_builder().build().map_err(Into::into)
}

fn build_ws_client() -> Result<Client, GrindrError> {
    // Websocket endpoint is http/1.1
    grindr_client_builder()
        .http1_only()
        .build()
        .map_err(Into::into)
}

/// Builds the transport shared by [`GrindrClient::new`] and [`GrindrClient::rotate_device`].
fn build_fingerprint(device: DeviceInfo) -> Result<Arc<Fingerprint>, GrindrError> {
    let user_agent = build_user_agent(&device, "Free");
    let http = build_http_client()?;
    let ws_http = build_ws_client()?;
    Ok(Arc::new(Fingerprint {
        http,
        ws_http,
        device,
        user_agent,
    }))
}

/// Everything needed to start the background websocket task.
struct WsSpawn {
    inner: Arc<InnerClient>,
    auth: Arc<AuthState>,
    channels: WsChannels,
    cmd_rx: mpsc::Receiver<WsCommand>,
    logout_notify: Arc<Notify>,
}

/// An async client for the Grindr API.
///
/// Cheap to [`Clone`] — clones share the connection pool, session, and the
/// background websocket task. Build one with [`new`](Self::new), log in with
/// [`login`](Self::login) or [`google_sign_in`](Self::google_sign_in), then make
/// requests with [`request_authenticated_raw`](Self::request_authenticated_raw)
/// and read events from [`ws_receiver`](Self::ws_receiver).
///
/// The client owns no Tokio runtime. The background websocket task is spawned on
/// the caller's runtime on the first authenticated call (or an explicit
/// [`connect`](Self::connect)), so [`new`](Self::new) can be called from
/// non-async code.
#[derive(Clone)]
pub struct GrindrClient {
    inner: Arc<InnerClient>,
    auth: Arc<AuthState>,
    session_rx: watch::Receiver<Option<Session>>,
    ws_event_tx: broadcast::Sender<WsEvent>,
    ws_cmd_tx: mpsc::Sender<WsCommand>,
    ws_state_rx: watch::Receiver<WsConnectionState>,
    logout_notify: Arc<Notify>,
    ws_started: Arc<Once>,
    ws_spawn: Arc<Mutex<Option<WsSpawn>>>,
}

impl GrindrClient {
    /// Creates a client for a [`DeviceInfo`], optionally resuming a saved
    /// [`Session`].
    ///
    /// Pass `None` to start logged out, or a saved session to resume without
    /// logging in again. This is sync and needs no runtime — the websocket
    /// starts on the first authenticated call (e.g. [`login`](Self::login)) or
    /// [`connect`](Self::connect), and connects once there's a session.
    pub fn new(device: DeviceInfo, session: Option<Session>) -> Result<Self, GrindrError> {
        let fingerprint = build_fingerprint(device)?;

        let inner = Arc::new(InnerClient {
            fingerprint: tokio::sync::RwLock::new(fingerprint),
        });

        let (auth_state, session_rx) = AuthState::new(session);
        let auth = Arc::new(auth_state);

        let (ws_channels, ws_handles) = make_channels();
        let logout_notify = Arc::new(Notify::new());

        let ws_event_tx = ws_channels.event_tx.clone();
        let ws_cmd_tx = ws_handles.cmd_tx;
        let ws_state_rx = ws_handles.state_rx;

        let ws_spawn = WsSpawn {
            inner: Arc::clone(&inner),
            auth: Arc::clone(&auth),
            channels: ws_channels,
            cmd_rx: ws_handles.cmd_rx,
            logout_notify: Arc::clone(&logout_notify),
        };

        Ok(Self {
            inner,
            auth,
            session_rx,
            ws_event_tx,
            ws_cmd_tx,
            ws_state_rx,
            logout_notify,
            ws_started: Arc::new(Once::new()),
            ws_spawn: Arc::new(Mutex::new(Some(ws_spawn))),
        })
    }

    /// Spawns the background websocket task once, on the current Tokio
    /// runtime. Cheap to call repeatedly, only the first call does any work.
    ///
    /// Must be called from within an async context (every async method in here),
    /// so the task attaches to the caller's runtime.
    fn ensure_ws_task(&self) {
        self.ws_started.call_once(|| {
            // Only this closure runs (once), so the parts are always present.
            if let Some(parts) = self.ws_spawn.lock().unwrap().take() {
                crate::ws::spawn_ws_task(
                    parts.inner,
                    parts.auth,
                    parts.channels,
                    parts.cmd_rx,
                    parts.logout_notify,
                );
            }
        });
    }

    /// Subscribes to [`AuthEvent`]s sent when a background token refresh fails
    /// (e.g. the session was revoked).
    pub fn auth_event_receiver(&self) -> broadcast::Receiver<AuthEvent> {
        self.auth.auth_event_tx.subscribe()
    }

    /// Watches the current [`Session`].
    ///
    /// It changes on login, refresh, and logout — read it here to save the
    /// session to disk.
    pub fn session_receiver(&self) -> watch::Receiver<Option<Session>> {
        self.session_rx.clone()
    }

    /// Watches the websocket [`WsConnectionState`].
    pub fn connection_state(&self) -> watch::Receiver<WsConnectionState> {
        self.ws_state_rx.clone()
    }

    /// Subscribes to incoming [`WsEvent`]s (messages, taps, presence). You only
    /// get events sent after you subscribe.
    pub fn ws_receiver(&self) -> broadcast::Receiver<WsEvent> {
        self.ws_event_tx.subscribe()
    }

    /// A sender for [`WsCommand`]s over the websocket.
    pub fn ws_sender(&self) -> mpsc::Sender<WsCommand> {
        self.ws_cmd_tx.clone()
    }

    /// Starts the background websocket task if it isn't running yet.
    ///
    /// It also starts on the first authenticated call ([`login`](Self::login),
    /// [`request_authenticated_raw`](Self::request_authenticated_raw)), so you
    /// only need this when resuming a saved [`Session`] and want the connection
    /// up before making a request. Calling it more than once does nothing.
    pub async fn connect(&self) {
        self.ensure_ws_task();
    }

    /// Logs in with email and password and stores the session.
    pub async fn login(&self, email: &str, password: &str) -> Result<LoginResult, GrindrError> {
        self.ensure_ws_task();
        crate::auth::login_email(&self.inner, &self.auth, email, password).await
    }

    /// Signs in with a Google OAuth access token and stores the session.
    pub async fn google_sign_in(
        &self,
        google_access_token: &str,
    ) -> Result<LoginResult, GrindrError> {
        self.ensure_ws_task();
        crate::auth::google_sign_in(&self.inner, &self.auth, google_access_token).await
    }

    /// Forces a token refresh.
    ///
    /// This happens automatically before the token expires, so you rarely need
    /// to call it yourself.
    pub async fn refresh_token(&self) -> Result<LoginResult, GrindrError> {
        self.ensure_ws_task();
        crate::auth::refresh_token(&self.inner, &self.auth).await
    }

    /// Clears the session and closes the websocket.
    pub async fn logout(&self) {
        self.auth.clear_session().await;
        self.logout_notify.notify_waiters();
    }

    /// Makes an authenticated request and returns the raw status and body.
    ///
    /// `path` is added to the API base URL and must start with `/` (e.g.
    /// `/v3/me/profile`), otherwise you get [`GrindrError::InvalidRequest`]. The
    /// session token is added for you, refreshing first if it's about to expire.
    /// The body comes back as-is for you to deserialize.
    ///
    /// This crate doesn't ship response types. See the API reference at
    /// <https://opengrind.org/grindr-api/> and the dev tool at
    /// <https://git.opengrind.org/open-grind/grindr-api-dev-tool>.
    pub async fn request_authenticated_raw(
        &self,
        method: Method,
        path: &str,
        body: Option<serde_json::Value>,
    ) -> Result<RawResponse, GrindrError> {
        self.ensure_ws_task();
        self.inner
            .request_authenticated_raw(&self.auth, method, path, body)
            .await
    }

    /// Replaces the device identity (and its clients) while keeping the session.
    /// Returns the old device.
    pub async fn rotate_device(&self, device: DeviceInfo) -> Result<DeviceInfo, GrindrError> {
        let new_fp = build_fingerprint(device)?;
        let old_fp = {
            let mut guard = self.inner.fingerprint.write().await;
            std::mem::replace(&mut *guard, new_fp)
        };
        Ok(old_fp.device.clone())
    }

    /// The device identity currently in use.
    pub async fn current_device(&self) -> DeviceInfo {
        self.inner.fingerprint().await.device.clone()
    }

    /// Whether the server has first-party reCAPTCHA enabled. No auth needed.
    pub async fn recaptcha_first_party_enabled(&self) -> Result<bool, GrindrError> {
        crate::auth::recaptcha_first_party_enabled(&self.inner).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_does_not_require_a_runtime() {
        // The constructor is synchronous and must not panic when called outside
        // of any Tokio runtime.
        let client = GrindrClient::new(DeviceInfo::generate(), None).unwrap();
        assert!(!client.ws_started.is_completed());
    }

    #[tokio::test]
    async fn ws_task_spawns_on_first_async_call() {
        // The key property: the lazy spawn attaches to the caller's runtime on
        // the first async call, without the "there is no reactor running" panic.
        let client = GrindrClient::new(DeviceInfo::generate(), None).unwrap();

        // No session => an auth error is returned before any network I/O, but
        // ensure_ws_task() has already spawned the background task by then.
        let err = client
            .request_authenticated_raw(Method::GET, "/v3/me/profile", None)
            .await
            .unwrap_err();

        assert!(matches!(err, GrindrError::Auth(_)));
        assert!(client.ws_started.is_completed());
    }

    #[tokio::test]
    async fn connect_starts_the_ws_task() {
        // Resuming a session and only calling connect() (no request) must still
        // bring the background task up.
        let client = GrindrClient::new(DeviceInfo::generate(), None).unwrap();
        assert!(!client.ws_started.is_completed());
        client.connect().await;
        assert!(client.ws_started.is_completed());
    }

    #[tokio::test]
    async fn dropping_client_in_async_context_does_not_panic() {
        // Regression guard: the old owned-runtime design panicked when the last
        // clone was dropped inside an async context.
        let client = GrindrClient::new(DeviceInfo::generate(), None).unwrap();
        let clone = client.clone();
        drop(client);
        drop(clone);
    }
}