gent-link 0.1.0

Connect Codex and Claude Code chats across machines with the Gent CLI and desktop companion.
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
408
409
410
//! Client metadata retrieval. Only owner-selected URLs can be fetched, and
//! every fetch pins validated DNS answers before TLS connection.
use super::{assertion::Policy, registry::oauth::Registration};
use anyhow::{Context, Result, ensure};
use serde::Deserialize;
use std::{
    collections::BTreeSet,
    net::{IpAddr, SocketAddr},
    time::Duration,
};
use url::{Host, Url};

const MAX_BYTES: usize = 64 * 1024;
const TIMEOUT: Duration = Duration::from_secs(10);
const CACHE_TTL: Duration = Duration::from_secs(60);

pub(crate) mod runtime;

#[cfg(test)]
pub(crate) mod tests;

#[derive(Deserialize)]
struct Document {
    client_id: String,
    client_name: String,
    redirect_uris: Vec<String>,
    jwks_uri: String,
    jwks: Option<serde_json::Value>,
    token_endpoint_auth_method: Option<String>,
    token_endpoint_auth_methods_supported: Option<Vec<String>>,
    token_endpoint_auth_signing_alg: Option<String>,
    grant_types: Option<Vec<String>>,
    response_types: Option<Vec<String>>,
}

fn endpoint(raw: &str) -> Result<Url> {
    ensure!(raw.len() <= 2048, "metadata URL is too long");
    let url = Url::parse(raw).context("invalid client metadata URL")?;
    ensure!(
        url.as_str() == raw
            && url.scheme() == "https"
            && url.port().is_none()
            && url.username().is_empty()
            && url.password().is_none()
            && url.query().is_none()
            && url.fragment().is_none()
            && url.path() != "/",
        "metadata URL must be canonical HTTPS on port 443 with a path and no credentials, query or fragment"
    );
    let Some(Host::Domain(host)) = url.host() else {
        anyhow::bail!("metadata URL must use a public DNS name");
    };
    ensure!(
        host.len() <= 253
            && host.contains('.')
            && host.split('.').all(|label| !label.is_empty()
                && label.len() <= 63
                && !label.starts_with('-')
                && !label.ends_with('-')
                && label
                    .bytes()
                    .all(|b| b.is_ascii_alphanumeric() || b == b'-')),
        "invalid metadata DNS name"
    );
    Ok(url)
}

fn public_ip(ip: IpAddr) -> bool {
    match ip {
        IpAddr::V4(ip) => {
            let [a, b, c, _] = ip.octets();
            !matches!(a, 0 | 10 | 127 | 224..=255)
                && !(a == 100 && (64..=127).contains(&b))
                && !(a == 169 && b == 254)
                && !(a == 172 && (16..=31).contains(&b))
                && !(a == 192
                    && (b == 168 || (b == 0 && matches!(c, 0 | 2)) || (b == 88 && c == 99)))
                && !(a == 198 && (matches!(b, 18 | 19) || (b == 51 && c == 100)))
                && !(a == 203 && b == 0 && c == 113)
        }
        IpAddr::V6(ip) => {
            let [a, b, ..] = ip.segments();
            (0x2000..0x4000).contains(&a)
                && !(a == 0x2001 && (b < 0x200 || b == 0xdb8))
                && a != 0x2002
                && a != 0x3fff
        }
    }
}

pub(super) fn destinations(addresses: Vec<SocketAddr>) -> Result<Vec<SocketAddr>> {
    ensure!(
        !addresses.is_empty()
            && addresses.len() <= 32
            && addresses
                .iter()
                .all(|a| a.port() == 443 && public_ip(a.ip())),
        "metadata DNS must resolve only to public unicast addresses (at most 32)"
    );
    Ok(addresses
        .into_iter()
        .collect::<BTreeSet<_>>()
        .into_iter()
        .collect())
}

pub(super) fn client(url: &Url, addresses: &[SocketAddr]) -> reqwest::ClientBuilder {
    reqwest::Client::builder()
        .https_only(true)
        .no_proxy()
        .http1_only()
        .redirect(reqwest::redirect::Policy::none())
        .timeout(TIMEOUT)
        .connect_timeout(Duration::from_secs(5))
        .pool_max_idle_per_host(0)
        .no_gzip()
        .no_brotli()
        .no_deflate()
        .no_zstd()
        .resolve_to_addrs(
            url.host_str().expect("validated metadata hostname"),
            addresses,
        )
}

struct Fetched {
    bytes: Vec<u8>,
    ttl: Duration,
}

// Cap publisher freshness at one minute. Invalid or revalidation-required
// directives disable reuse; failed requests never extend an existing cache.
fn freshness(headers: &reqwest::header::HeaderMap) -> Duration {
    let mut ttl = CACHE_TTL.as_secs();
    let mut max_age_seen = false;
    for value in headers.get_all("cache-control") {
        let Ok(value) = value.to_str() else {
            return Duration::ZERO;
        };
        for directive in value.split(',') {
            let (name, argument) = directive
                .trim()
                .split_once('=')
                .map_or((directive.trim(), None), |(n, v)| {
                    (n.trim(), Some(v.trim()))
                });
            if ["no-store", "no-cache"]
                .iter()
                .any(|v| name.eq_ignore_ascii_case(v))
            {
                return Duration::ZERO;
            }
            if name.eq_ignore_ascii_case("max-age") {
                if max_age_seen {
                    return Duration::ZERO;
                }
                max_age_seen = true;
                let Some(age) = argument.and_then(|v| {
                    let value = if v.starts_with('"') {
                        v.strip_prefix('"')?.strip_suffix('"')?
                    } else {
                        v
                    };
                    decimal(value)
                }) else {
                    return Duration::ZERO;
                };
                ttl = age;
            }
        }
    }
    let mut apparent_age = Duration::ZERO;
    let mut dates = headers.get_all("date").iter();
    if let Some(date) = dates.next() {
        let Some(date) = date
            .to_str()
            .ok()
            .and_then(|v| httpdate::parse_http_date(v).ok())
        else {
            return Duration::ZERO;
        };
        if dates.next().is_some() {
            return Duration::ZERO;
        }
        apparent_age = std::time::SystemTime::now()
            .duration_since(date)
            .unwrap_or_default();
    }
    let mut ages = headers.get_all("age").iter();
    if let Some(age) = ages.next() {
        let Some(age) = age.to_str().ok().and_then(decimal) else {
            return Duration::ZERO;
        };
        if ages.next().is_some() {
            return Duration::ZERO;
        }
        apparent_age = apparent_age.max(Duration::from_secs(age));
    }
    // Without max-age, an Expires header may prohibit reuse; avoid interpreting
    // remote wall clocks and conservatively revalidate such responses.
    if !max_age_seen && headers.contains_key("expires") {
        return Duration::ZERO;
    }
    Duration::from_secs(ttl)
        .saturating_sub(apparent_age)
        .min(CACHE_TTL)
}

fn decimal(value: &str) -> Option<u64> {
    if value.is_empty() || !value.bytes().all(|b| b.is_ascii_digit()) {
        return None;
    }
    value.parse().ok()
}

async fn fetch_response(client: &reqwest::Client, url: &Url) -> Result<Fetched> {
    let started = std::time::Instant::now();
    let mut response = client
        .get(url.clone())
        .header("accept", "application/json, application/jwk-set+json")
        .send()
        .await
        .context("client metadata fetch failed")?;
    ensure!(
        response.status() == reqwest::StatusCode::OK,
        "metadata endpoint must return HTTP 200 without redirects"
    );
    let types: Vec<_> = response.headers().get_all("content-type").iter().collect();
    ensure!(
        types.len() == 1
            && types[0].to_str().ok().is_some_and(|v| matches!(
                v.split(';').next().unwrap_or("").trim(),
                "application/json" | "application/jwk-set+json"
            )),
        "metadata must be served as JSON"
    );
    ensure!(
        !response.headers().contains_key("content-encoding"),
        "encoded metadata responses are unsupported"
    );
    let ttl = freshness(response.headers());
    ensure!(
        response
            .content_length()
            .is_none_or(|n| n <= MAX_BYTES as u64),
        "metadata response is too large"
    );
    let mut bytes = Vec::new();
    while let Some(chunk) = response
        .chunk()
        .await
        .context("metadata body read failed")?
    {
        ensure!(
            chunk.len() <= MAX_BYTES - bytes.len(),
            "metadata response is too large"
        );
        bytes.extend_from_slice(&chunk);
    }
    Ok(Fetched {
        bytes,
        ttl: ttl.saturating_sub(started.elapsed()),
    })
}

#[cfg(test)]
async fn response(client: &reqwest::Client, url: &Url) -> Result<Vec<u8>> {
    Ok(fetch_response(client, url).await?.bytes)
}

async fn fetch(url: &Url) -> Result<Fetched> {
    tokio::time::timeout(TIMEOUT, async {
        let addresses = tokio::net::lookup_host((url.host_str().unwrap(), 443))
            .await
            .context("client metadata DNS lookup failed")?
            .take(33)
            .collect();
        let addresses = destinations(addresses)?;
        fetch_response(&client(url, &addresses).build()?, url).await
    })
    .await
    .context("client metadata fetch timed out")?
}

fn entries(values: &[String]) -> bool {
    !values.is_empty()
        && values.len() <= 16
        && values.iter().all(|v| {
            !v.is_empty() && v.len() <= 128 && v.bytes().all(|b| (0x21..=0x7e).contains(&b))
        })
        && values.iter().collect::<BTreeSet<_>>().len() == values.len()
}

fn document(bytes: &[u8], id: &Url, resource: &str, callbacks: &[String]) -> Result<Url> {
    ensure!(
        bytes.len() <= MAX_BYTES,
        "client metadata document is too large"
    );
    let doc: Document =
        serde_json::from_slice(bytes).context("invalid client metadata document")?;
    ensure!(
        doc.client_id == id.as_str(),
        "metadata client ID does not match its exact URL"
    );
    ensure!(
        !doc.client_name.trim().is_empty()
            && doc.client_name.len() <= 200
            && !doc.client_name.chars().any(char::is_control),
        "invalid published client name"
    );
    let supported = match &doc.token_endpoint_auth_methods_supported {
        Some(methods) => entries(methods) && methods.iter().any(|m| m == "private_key_jwt"),
        None => doc.token_endpoint_auth_method.as_deref() == Some("private_key_jwt"),
    };
    ensure!(
        supported
            && doc
                .token_endpoint_auth_signing_alg
                .as_deref()
                .is_none_or(|a| a == "RS256"),
        "client metadata must support RS256 private_key_jwt"
    );
    ensure!(
        doc.grant_types.as_ref().is_none_or(|g| entries(g)
            && ["authorization_code", "refresh_token"]
                .iter()
                .all(|v| g.iter().any(|s| s == v)))
            && doc
                .response_types
                .as_ref()
                .is_none_or(|r| entries(r) && r.iter().any(|v| v == "code")),
        "metadata does not permit the code and refresh flow"
    );
    Registration {
        resource: resource.into(),
        redirect_uris: doc.redirect_uris.clone(),
        assertion: None,
    }
    .validate()?;
    Registration {
        resource: resource.into(),
        redirect_uris: callbacks.to_vec(),
        assertion: None,
    }
    .validate()?;
    ensure!(
        callbacks.iter().all(|c| doc.redirect_uris.contains(c)),
        "requested callback is absent from published metadata"
    );
    ensure!(doc.jwks.is_none(), "inline JWKS cannot accompany jwks_uri");
    let keys = endpoint(&doc.jwks_uri)?;
    ensure!(
        keys.origin() == id.origin(),
        "client JWKS must use the metadata document's HTTPS origin"
    );
    Ok(keys)
}

pub(crate) async fn import(id: &str, resource: &str, callbacks: &[String]) -> Result<Policy> {
    Ok(import_fresh(id, resource, callbacks).await?.0)
}

async fn import_fresh(
    id: &str,
    resource: &str,
    callbacks: &[String],
) -> Result<(Policy, Duration)> {
    import_fresh_using(
        id,
        resource,
        callbacks,
        |url| async move { fetch(&url).await },
    )
    .await
}

async fn import_fresh_using<F, Fut>(
    id: &str,
    resource: &str,
    callbacks: &[String],
    fetcher: F,
) -> Result<(Policy, Duration)>
where
    F: Fn(Url) -> Fut,
    Fut: std::future::Future<Output = Result<Fetched>>,
{
    let started = std::time::Instant::now();
    let id = endpoint(id)?;
    let doc = fetcher(id.clone()).await?;
    let keys = document(&doc.bytes, &id, resource, callbacks)?;
    let keys = fetcher(keys).await?;
    let ttl = doc.ttl.min(keys.ttl).saturating_sub(started.elapsed());
    Ok((Policy::from_jwks(&keys.bytes, id.as_str())?, ttl))
}

#[cfg(test)]
async fn import_using<F, Fut>(
    id: &str,
    resource: &str,
    callbacks: &[String],
    fetcher: F,
) -> Result<Policy>
where
    F: Fn(Url) -> Fut,
    Fut: std::future::Future<Output = Result<Vec<u8>>>,
{
    let id = endpoint(id)?;
    let keys = document(&fetcher(id.clone()).await?, &id, resource, callbacks)?;
    Policy::from_jwks(&fetcher(keys).await?, id.as_str())
}