link-assistant-router 1.0.2

Link.Assistant.Router — Claude MAX OAuth proxy and token gateway for Anthropic APIs
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! Authorize the subscription of the *selected* router, not a local directory.
//!
//! `server use` establishes which router the CLI is talking to, and `with`
//! honours it. `auth` is the other half of that workflow — it exists to give
//! that router a working subscription — but it wrote to a local home instead,
//! so the obvious sequence
//!
//! ```text
//! router server use <url> --token-stdin
//! router auth claude
//! router with claude
//! ```
//!
//! did not do what it reads as: the login printed success while the router it
//! targeted still had no usable credential, and the failure surfaced later as
//! an unrelated-looking 401 (issue #246).
//!
//! The login itself still happens in front of the operator — the browser step
//! cannot be delegated — but the credential is completed on, and stored by,
//! the router being targeted, through the admin login API it already exposes.

use std::process::ExitCode;
use std::time::Duration;

use crate::managed_server::ResolvedServer;

/// How long to wait for one HTTP call to the selected router.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

/// How often a device-flow login asks the router whether it was approved.
///
/// Short enough that approval feels immediate, long enough not to hammer the
/// router while a human is reading their browser.
#[cfg(not(test))]
const POLL_INTERVAL: Duration = Duration::from_secs(3);
#[cfg(test)]
const POLL_INTERVAL: Duration = Duration::from_millis(20);

/// The selected router, when one is configured and reachable.
///
/// `None` means "no selection" — the caller keeps its local behaviour. An
/// unreachable *selected* server is an error rather than a silent fallback:
/// falling back to a local directory is exactly the surprise this fixes.
pub async fn selected_server(force_managed: bool) -> Result<Option<ResolvedServer>, String> {
    if force_managed {
        // `--managed` asks for a disposable container, which is what the local
        // path already provides for `auth`.
        return Ok(None);
    }
    if !has_selection() {
        // Nothing was selected, but a router already listening here is a
        // better target than this machine's credential directory: authorizing
        // locally when a live router is one port away lands the subscription
        // somewhere the router in use cannot see (issue #250).
        return Ok(crate::managed_server::discovered_local_router().await);
    }
    crate::managed_server::resolve(None, None, None, false)
        .await
        .map(Some)
        .map_err(|error| format!("the selected server is not usable: {error}"))
}

/// The router an `auth` invocation acts on, given its explicit target flags.
///
/// `None` means "act locally". The precedence is the same one `with` follows,
/// stated in one place so `auth` cannot drift from it again (issues #246,
/// #250): an explicit `--local` or `--managed` keeps the local path, `--server`
/// names one router for a single command, and otherwise the selection — or a
/// router already listening here — is used.
pub async fn target_for(
    local: bool,
    managed: bool,
    server: Option<&str>,
) -> Result<Option<ResolvedServer>, String> {
    if local || managed {
        return Ok(None);
    }
    if let Some(server) = server {
        return crate::managed_server::resolve(Some(server), None, None, false)
            .await
            .map(Some)
            .map_err(|error| format!("{server} is not usable: {error}"));
    }
    selected_server(managed).await
}

/// Whether the operator has selected a server, without contacting it.
///
/// Only an explicit selection counts. The managed local container is started on
/// demand by `with`, and a plain `auth` must not boot one.
fn has_selection() -> bool {
    if std::env::var_os("LINK_ASSISTANT_ROUTER_URL").is_some_and(|value| !value.is_empty())
        || std::env::var_os("ROUTER_URL").is_some_and(|value| !value.is_empty())
    {
        return true;
    }
    crate::managed_server::load_persisted()
        .ok()
        .flatten()
        .is_some()
}

/// Run a provider login against `server`, returning the process exit code.
pub async fn authorize(
    server: &ResolvedServer,
    provider: &str,
    mode: Option<&str>,
    code: Option<String>,
) -> ExitCode {
    match authorize_inner(server, provider, mode, code).await {
        Ok(()) => ExitCode::SUCCESS,
        Err(error) => {
            eprintln!("error: {error}");
            ExitCode::from(1)
        }
    }
}

async fn authorize_inner(
    server: &ResolvedServer,
    provider: &str,
    mode: Option<&str>,
    code: Option<String>,
) -> Result<(), String> {
    let client = reqwest::Client::builder()
        .timeout(REQUEST_TIMEOUT)
        .build()
        .map_err(|error| format!("could not build an HTTP client: {error}"))?;

    let mut body = serde_json::json!({ "provider": provider });
    if let Some(mode) = mode {
        body["mode"] = serde_json::Value::String(mode.to_string());
    }
    let begun: serde_json::Value = send(
        &client,
        server,
        reqwest::Method::POST,
        crate::route_contract::route_template(crate::route_contract::RouteId::Login),
        Some(body),
    )
    .await?;

    let login_id = begun
        .get("login_id")
        .and_then(serde_json::Value::as_str)
        .ok_or("the router did not return a login id")?
        .to_string();

    println!("Authorizing {provider} on {}", server.base_url);
    if let Some(url) = begun.get("url").and_then(serde_json::Value::as_str) {
        println!("Open this URL:\n{url}");
    }
    if let Some(user_code) = begun.get("user_code").and_then(serde_json::Value::as_str) {
        println!("Enter this code: {user_code}");
    }

    // A device flow authorizes itself once the human approves it in the
    // browser; only a code flow has something to submit.
    if status_of(&begun) == "authorized" {
        finish(provider, server);
        return Ok(());
    }
    if status_of(&begun) == "awaiting_device" {
        return poll_until_authorized(&client, server, &login_id, provider).await;
    }

    let submitted = match code {
        Some(code) => code,
        None => read_code().await?,
    };
    let submitted = submitted.trim();
    if submitted.is_empty() {
        return Err(format!(
            "no authorization code was supplied; the pending login is still open on the router — \
             finish it with `router auth {provider} --flow code --code <CODE>`"
        ));
    }

    let completed: serde_json::Value = send(
        &client,
        server,
        reqwest::Method::POST,
        &crate::route_contract::route_template(crate::route_contract::RouteId::LoginCode)
            .replace("{id}", &login_id),
        Some(serde_json::json!({ "code": submitted })),
    )
    .await?;
    if status_of(&completed) != "authorized" {
        return Err(format!(
            "the router did not accept the code: it reports `{}`",
            status_of(&completed)
        ));
    }
    finish(provider, server);
    Ok(())
}

/// Wait for a device-flow login the human approves in their browser.
async fn poll_until_authorized(
    client: &reqwest::Client,
    server: &ResolvedServer,
    login_id: &str,
    provider: &str,
) -> Result<(), String> {
    let deadline = std::time::Instant::now() + Duration::from_secs(10 * 60);
    while std::time::Instant::now() < deadline {
        tokio::time::sleep(POLL_INTERVAL).await;
        let view: serde_json::Value = send(
            client,
            server,
            reqwest::Method::GET,
            &crate::route_contract::route_template(crate::route_contract::RouteId::LoginSession)
                .replace("{id}", login_id),
            None,
        )
        .await?;
        match status_of(&view) {
            "authorized" => {
                finish(provider, server);
                return Ok(());
            }
            "failed" | "expired" | "cancelled" => {
                return Err(format!(
                    "the login ended as `{}` on the router",
                    status_of(&view)
                ));
            }
            _ => {}
        }
    }
    Err("the login was not approved in time".to_string())
}

fn finish(provider: &str, server: &ResolvedServer) {
    println!(
        "{provider} authorization saved on {} ({})",
        server.base_url, server.source
    );
}

fn status_of(view: &serde_json::Value) -> &str {
    view.get("status")
        .and_then(serde_json::Value::as_str)
        .unwrap_or("unknown")
}

/// Report each provider credential as the *selected router* sees it.
pub async fn status(server: &ResolvedServer) -> ExitCode {
    let client = match reqwest::Client::builder().timeout(REQUEST_TIMEOUT).build() {
        Ok(client) => client,
        Err(error) => {
            eprintln!("error: could not build an HTTP client: {error}");
            return ExitCode::from(1);
        }
    };
    match send::<serde_json::Value>(
        &client,
        server,
        reqwest::Method::GET,
        crate::route_contract::route_template(crate::route_contract::RouteId::Accounts),
        None,
    )
    .await
    {
        Ok(body) => {
            println!("server: {} ({})", server.base_url, server.source);
            report_credentials(&body);
            ExitCode::SUCCESS
        }
        Err(error) => {
            eprintln!("error: {error}");
            ExitCode::from(1)
        }
    }
}

/// Where the selected router reads `provider`'s credential from.
///
/// `auth status` already asks the same endpoint for exactly this, so a command
/// that cannot act on the remote deployment can still name the directory the
/// credential would have to land in. An error that says only "not from here"
/// leaves the operator to guess the next step; one that names the path is the
/// instruction (issue #291).
///
/// `None` when the router cannot be reached or does not report homes — the
/// refusal is still correct without it, so this never turns into a hard
/// failure of its own.
pub async fn credential_home(server: &ResolvedServer, provider: &str) -> Option<String> {
    let client = reqwest::Client::builder()
        .timeout(REQUEST_TIMEOUT)
        .build()
        .ok()?;
    let body: serde_json::Value = send(
        &client,
        server,
        reqwest::Method::GET,
        crate::route_contract::route_template(crate::route_contract::RouteId::Accounts),
        None,
    )
    .await
    .ok()?;
    home_in_accounts(&body, provider)
}

/// `accounts list` against the selected router (issue #294).
///
/// The endpoint reports a superset of what the local table prints, so this
/// renders the same columns from the same field names rather than growing a
/// second format an operator would have to reconcile.
pub async fn accounts(server: &ResolvedServer) -> ExitCode {
    match get(
        server,
        crate::route_contract::route_template(crate::route_contract::RouteId::Accounts),
    )
    .await
    {
        Ok(body) => {
            println!("server: {} ({})", server.base_url, server.source);
            report_credentials(&body);
            ExitCode::SUCCESS
        }
        Err(error) => {
            eprintln!("error: {error}");
            ExitCode::from(1)
        }
    }
}

/// `GET path` on the selected router, returning its JSON answer.
///
/// The admin credential is attached and the failure messages are shared with
/// every other remote command, so a refused credential reads the same however
/// the operator arrived at it.
///
/// # Errors
///
/// Returns an operator-readable message when the call cannot be made or the
/// router answers with a failure.
pub async fn get(server: &ResolvedServer, path: &str) -> Result<serde_json::Value, String> {
    let client = http_client()?;
    send(&client, server, reqwest::Method::GET, path, None).await
}

/// `POST path` with `body` on the selected router.
///
/// # Errors
///
/// Returns an operator-readable message when the call cannot be made or the
/// router answers with a failure.
pub async fn post(
    server: &ResolvedServer,
    path: &str,
    body: serde_json::Value,
) -> Result<serde_json::Value, String> {
    let client = http_client()?;
    send(&client, server, reqwest::Method::POST, path, Some(body)).await
}

/// `DELETE path` on the selected router.
///
/// # Errors
///
/// Returns an operator-readable message when the call cannot be made or the
/// router answers with a failure.
pub async fn delete(server: &ResolvedServer, path: &str) -> Result<serde_json::Value, String> {
    let client = http_client()?;
    send(&client, server, reqwest::Method::DELETE, path, None).await
}

fn http_client() -> Result<reqwest::Client, String> {
    reqwest::Client::builder()
        .timeout(REQUEST_TIMEOUT)
        .build()
        .map_err(|error| format!("could not build an HTTP client: {error}"))
}

/// Why an import cannot act on a router other than the machine running it.
///
/// The lines an operator reads, built here rather than at the call site so the
/// wording is asserted directly. Import installs into the credential home of
/// the executing machine, and no endpoint accepts a credential document —
/// `/api/management/login` begins an interactive OAuth flow and `submit_code` takes a
/// short-lived code, neither of which adopts a credential that already exists.
///
/// `home` names the directory that router reads from, when it reports one:
/// "not from here" alone leaves the operator to guess the next step, and the
/// path is the instruction. It is omitted rather than guessed when the router
/// does not say (issue #291).
#[must_use]
pub fn remote_import_refusal(base_url: &str, home: Option<&str>) -> Vec<String> {
    let mut lines = vec![format!(
        "error: import installs a credential into the credential home of the machine running \
         it, so it cannot provision {base_url} from here."
    )];
    if let Some(home) = home {
        lines.push(format!("note: {base_url} reads its credential from {home}"));
    }
    lines.push(String::from(
        "note: that deployment accepts no credential over HTTP, so run `router auth import` \
         there, or authorize it from here with `router auth claude` / `router auth codex`, \
         which do act on the selected server.",
    ));
    lines.push(String::from(
        "note: pass --local to import into this machine's credential home.",
    ));
    lines
}

/// The home an `/api/management/accounts` body reports for `provider`, if it names one.
///
/// Split from the request so the shape-handling can be asserted without a
/// server: single-account deployments report under `credentials` and pooled
/// ones under `accounts`, and a router predating either simply omits both.
#[must_use]
pub fn home_in_accounts(body: &serde_json::Value, provider: &str) -> Option<String> {
    ["credentials", "accounts"]
        .into_iter()
        .filter_map(|key| body.get(key).and_then(serde_json::Value::as_array))
        .flatten()
        .find(|entry| {
            entry
                .get("name")
                .and_then(serde_json::Value::as_str)
                .is_some_and(|name| name.eq_ignore_ascii_case(provider))
        })
        .and_then(|entry| entry.get("home").and_then(serde_json::Value::as_str))
        .map(str::to_owned)
}

async fn send<T: serde::de::DeserializeOwned>(
    client: &reqwest::Client,
    server: &ResolvedServer,
    method: reqwest::Method,
    path: &str,
    body: Option<serde_json::Value>,
) -> Result<T, String> {
    let url = format!("{}{path}", server.base_url.trim_end_matches('/'));
    let mut request = client.request(method, &url);
    if let Some(token) = server.token.as_deref() {
        request = request.bearer_auth(token);
    }
    if let Some(body) = body {
        request = request.json(&body);
    }
    let response = request
        .send()
        .await
        .map_err(|error| format!("could not reach {url}: {error}"))?;
    let status = response.status();
    let text = response.text().await.unwrap_or_default();
    if !status.is_success() {
        // The most likely cause by far, and the one whose fix is not obvious.
        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(format!(
                "the selected router refused an administrator credential ({status}). Re-select it \
                 with an admin token: `router server use {} --token-stdin`",
                server.base_url
            ));
        }
        return Err(format!("{url} returned {status}: {}", text.trim()));
    }
    serde_json::from_str(&text)
        .map_err(|error| format!("could not read the reply from {url}: {error}"))
}

/// Read one authorization code from standard input.
///
/// Duplicated from the local path rather than shared: the two prompts differ in
/// what they say about where the pending login lives, and the shared half is
/// one `read_line`.
async fn read_code() -> Result<String, String> {
    use std::io::BufRead as _;

    println!("Paste authorization code:");
    tokio::task::spawn_blocking(|| {
        let mut line = String::new();
        std::io::stdin()
            .lock()
            .read_line(&mut line)
            .map(|_| line)
            .map_err(|error| format!("could not read authorization code: {error}"))
    })
    .await
    .map_err(|error| format!("authorization prompt failed: {error}"))?
}

#[cfg(test)]
#[path = "auth_remote_tests.rs"]
mod tests;

/// Print what the router said about its credentials.
///
/// An empty `accounts` array means *no account pool*, which is the ordinary
/// state of a single-subscription deployment rather than a missing credential.
/// Printing "no accounts are configured on this router" for it described a
/// router serving live traffic as unauthorized, and pointed the operator at a
/// re-authentication it did not need (issue #281).
///
/// So the pool is reported when there is one, the per-provider credentials when
/// the router sends them, and the server's own `note` when it explains an empty
/// array — in that order. The last two are what an older router does not send,
/// and falling through to the original sentence keeps this readable against one.
fn report_credentials(body: &serde_json::Value) {
    for line in credential_report(body) {
        println!("{line}");
    }
}

/// [`report_credentials`] as lines, so what it prints can be asserted.
fn credential_report(body: &serde_json::Value) -> Vec<String> {
    let rows = |key: &str| {
        body.get(key)
            .and_then(serde_json::Value::as_array)
            .map(Vec::as_slice)
            .unwrap_or_default()
    };
    let accounts = rows("accounts");
    // `credentials` is the single-account answer; it is absent when a pool is
    // configured, and on a router predating it.
    let entries = if accounts.is_empty() {
        rows("credentials")
    } else {
        accounts
    };
    if !entries.is_empty() {
        let mut lines = vec![crate::accounts_cli::header()];
        lines.extend(entries.iter().map(|entry| {
            let text = |key: &str| {
                entry
                    .get(key)
                    .and_then(serde_json::Value::as_str)
                    .unwrap_or("-")
            };
            let number = |key: &str| entry.get(key).and_then(serde_json::Value::as_u64);
            crate::accounts_cli::row(&crate::accounts_cli::AccountRow {
                name: text("name"),
                healthy: entry.get("healthy").and_then(serde_json::Value::as_bool),
                credential: text("credential"),
                used: number("used"),
                limit: number("request_limit"),
                remaining: number("remaining_requests"),
                home: text("home").to_string(),
            })
        }));
        return lines;
    }
    // The server explains an empty array when it can; that explanation is the
    // answer, and discarding it is what produced the misleading sentence.
    if let Some(note) = body.get("note").and_then(serde_json::Value::as_str) {
        return vec![note.to_string()];
    }
    vec!["no accounts are configured on this router".to_string()]
}