fleetwire 0.2.1

Unofficial read-only client for the Tesla Fleet API
Documentation
# fleetwire

An **unofficial, read-only** Rust client for the Tesla Fleet API that knows which calls cost money.

> **Not affiliated with, endorsed by, or sponsored by Tesla, Inc.**
> Tesla names and trademarks belong to their respective owners.

- **Read-only.** GET requests only to the Fleet API (the one POST is the OAuth token refresh). There is
  no vehicle-command or signing code, and the endpoint trait is sealed, so a caller cannot add a write.
- **Cost-aware.** Every request type says whether Tesla bills it (`Pricing`). Billed calls are never
  retried or re-sent by the recovery paths, and `Client::send_guarded` checks for free whether the car is
  online before spending anything.
- **Synchronous.** Built on `ureq` with rustls. No async runtime needed.
- **Careful with tokens.** `TokenManager` keeps tokens in an owner-only directory at `0600`, persists a
  rotated refresh token before returning, and collapses concurrent refreshes within and across processes.
- **Careful with personal data.** Error messages and body previews redact tokens, VINs and coordinates;
  the types that hold tokens or a VIN print no secrets through `Debug`. A VIN is checked once when a
  request is built: one that could escape its path segment (empty, or containing `/`, `\`, `:`, NUL or
  `..`) is refused before anything is sent. The VIN's format itself is not checked.
- **Careful with hosts.** The region URL Tesla returns is adopted only if it is `https` and its host is
  on the allowlist (`TESLA_REGION_HOSTS` by default; `ClientBuilder::allow_region_host` adds to it).
  Otherwise the client stays on its bootstrap host.
- **No `unsafe`.** `unsafe_code = "forbid"` across the workspace, and product code is linted against
  `unwrap` and `panic`.

To see what each call costs without a token or a network connection:

```sh
cargo run --example pricing_table
```

```text
GET                                           cost          scopes
/api/1/vehicles/{vin}/vehicle_data            $0.002/call   vehicle_device_data
/api/1/vehicles/{vin}/nearby_charging_sites   $0.002/call   vehicle_device_data
/api/1/vehicles                               free          vehicle_device_data
/api/1/vehicles/{vin}                         free          vehicle_device_data
/api/1/vehicles/{vin}/invitations             free          vehicle_device_data
/api/1/vehicles/{vin}/mobile_enabled          free          vehicle_device_data
/api/1/vehicles/{vin}/recent_alerts           free          vehicle_device_data
/api/1/vehicles/{vin}/release_notes           free          vehicle_device_data
/api/1/vehicles/{vin}/service_data            free          vehicle_device_data
/api/1/vehicles/{vin}/drivers                 free          vehicle_device_data
/api/1/vehicles/{vin}/fleet_telemetry_config  free          vehicle_device_data
/api/1/vehicles/{vin}/fleet_telemetry_errors  free          vehicle_device_data
/api/1/users/region                           free          any of (openid, user_data, vehicle_device_data)
/api/1/users/me                               free          user_data
/api/1/users/orders                           free          vehicle_device_data
/api/1/users/feature_config                   free          user_data

2 of 16 endpoints are billed; 14 are free.
Use Client::send_guarded for the billed ones: it checks for free that the car is online first.
These are the prices the request types carry, read without any network call; they are not a live tariff.
```

To watch the guarantees above hold, also without a token or an outside connection:

```sh
cargo run --example offline_demo
```

It starts a mock Fleet API on a loopback port, drives the real client against it and checks its claims
against what the server received. Two of its eight scenes:

```text
4. A 401 on a billed endpoint: the token is repaired, the request is not re-sent
   server saw: GET /api/1/users/region, GET /api/1/vehicles/{vin}/vehicle_data
   ok the first call returns the 401 as an Auth error
   ok the error says the call was billed
   ok billed requests after the first call: 1 (not sent again)
   server saw: GET /api/1/users/region (x2), GET /api/1/vehicles/{vin}/vehicle_data (x2)
   ok the next call succeeds
   ok billed requests in total: 2 (one per call)
   ok the server saw the rejected token once, then the newly issued one
   .. the refresh below is counted by this example's stand-in for the token endpoint
   ok token refreshes: 1

6. A token that carries a command scope: refused before anything is sent
   server saw: nothing
   ok the call fails with CommandScopeOnReadToken
   ok requests of any kind the server received: 0
```

The other scenes cover a sleeping car's billed call being skipped, a 408 not being retried, a free
call recovering from a 401 by itself, a region answer that names another server not being adopted, and
an error body being scrubbed. It exits non-zero if any claim stops being true. What it does not show is
the GET-only rule: that is a property of the code, enforced by the sealed endpoint trait, a clippy
deny-list and a CI gate, not something a run can demonstrate.

## Quick start

**Before you start** you need two things from Tesla, and this crate does not obtain them for you:

- a Tesla developer app — its **client id**;
- a **refresh token** for your account, issued to that app with the scopes `openid`, `offline_access`
  and `vehicle_device_data`.

Tesla's [Fleet API docs](https://developer.tesla.com/docs/fleet-api) cover app registration and the
authorization-code flow that yields the refresh token. fleetwire takes over from there: it refreshes
access tokens, but it does not run the authorization-code exchange. Expect this part to take longer than
everything below.

The crate builds on Linux and macOS (CI runs on Linux).

1. Get the code. The example lives in the repository, so clone it, and run the commands below
   from the repository root.

   ```sh
   git clone https://github.com/fleetwire-dev/fleetwire-rs
   cd fleetwire-rs
   ```

2. Put the refresh token where only you can read it:

   ```sh
   mkdir -p ~/.fleetwire && chmod 700 ~/.fleetwire
   (umask 077 && cat > ~/.fleetwire/tokens.json <<'EOF'
   {"access_token": "", "refresh_token": "PASTE_YOUR_REFRESH_TOKEN", "expires_at": 0}
   EOF
   )
   ```

   - `expires_at` is a Unix time in seconds; `0` means "already expired", so the first call refreshes
     the access token and fills in `access_token`.
   - Do this **once**. fleetwire rewrites this file every time Tesla rotates the refresh token, and
     the newest refresh token exists only there. Running the command again over a working directory
     overwrites it with the old token you pasted.
   - The directory must not be accessible to other users, or the client refuses to read it.
   - A `tokens.lock` file appears next to it. It is the cross-process lock; leave it.

3. List your vehicles. This call is free and does not wake the car:

   ```sh
   TESLA_CLIENT_ID=your-client-id FLEETWIRE_TOKEN_DIR=$HOME/.fleetwire \
     cargo run --example list_vehicles
   ```

   ```text
   1 vehicle(s)
   - vin LRW**********1234 · state asleep
   ```

   The example masks the VIN; add `-- --show-vin` to print it in full. `TESLA_CLIENT_ID` and
   `FLEETWIRE_TOKEN_DIR` are read by the example only — the library takes both as arguments.

### If it fails

| You see | Usual cause |
|---|---|
| `error: set TESLA_CLIENT_ID … and FLEETWIRE_TOKEN_DIR …` | One or both environment variables are missing. |
| `token refresh failed: HTTP 400 … client_not_found` | The client id is wrong, or belongs to another app. |
| Any other `token refresh failed: HTTP 4xx …` | The refresh token is mistyped, expired, already rotated, or was issued to a different client id. Tesla's own message follows the status. |
| `error: authentication error: token directory: token directory permissions are too permissive` (or `token file permissions …`) | The directory or `tokens.json` is readable by others: `chmod 700 ~/.fleetwire && chmod 600 ~/.fleetwire/tokens.json`. The directory is checked first, so this is what you see even when `tokens.json` is missing as well. |
| `… token file not found` | `FLEETWIRE_TOKEN_DIR` points at an owner-only directory without `tokens.json` (step 2). |
| A scope error before any request is sent | The token lacks `vehicle_device_data`; re-authorize the app with that scope. |

4. Use it from your code. Add the dependency (`cargo add fleetwire`), then:

   ```rust,no_run
   use std::sync::Arc;
   use fleetwire::api::vehicles::ListVehicles;
   use fleetwire::{Client, HttpRefresher, TokenManager};

   # fn main() -> Result<(), Box<dyn std::error::Error>> {
   let tokens = TokenManager::new(
       "/home/me/.fleetwire".into(),
       Arc::new(HttpRefresher::new("your-client-id".to_owned())),
   );
   let client = Client::builder(tokens).build()?;
   let page = client.send(&ListVehicles { page: None, per_page: None })?;
   println!("{} vehicle(s)", page.items.len());
   # Ok(())
   # }
   ```

## Free calls

Fourteen of the sixteen endpoints are not billed, so you can poll them without spending anything.
Checking whether a car is awake, for example, uses the free `GET /api/1/vehicles/{vin}` and does not
wake it:

```rust,no_run
use std::sync::Arc;
use fleetwire::api::vehicles::GetVehicle;
use fleetwire::{Client, HttpRefresher, Pricing, TokenManager};

# fn main() -> Result<(), Box<dyn std::error::Error>> {
# let tokens = TokenManager::new(
#     "/home/me/.fleetwire".into(),
#     Arc::new(HttpRefresher::new("your-client-id".to_owned())),
# );
let client = Client::builder(tokens).build()?;
let req = GetVehicle::new("YOUR_VIN")?;
assert_eq!(fleetwire::FleetGet::pricing(&req), Pricing::NotCharged);
let car = client.send(&req)?;
println!("state {}", car.state.as_deref().unwrap_or("?"));
# Ok(())
# }
```

The other free ones include `ListVehicles`, `GetRecentAlerts`, `GetReleaseNotes`, `GetServiceData`,
`ListDrivers` and, under `fleetwire::api::users`, `GetMe` and `GetRegion`; `pricing_table` lists them all.

## Calls that cost money

Of the sixteen endpoints this crate models, two are billed: `GetVehicleData` and
`GetNearbyChargingSites` ($0.002 per request; a 408 from a sleeping vehicle was measured to use up a
quota slot like a successful call, and the crate counts it as billed). The other fourteen are not.

`examples/guarded_vehicle_data` shows the safe way to make a billed call: it reads the battery level
through `Client::send_guarded`, which skips the billed request when the car is not online.

| Entry point | What it does |
|---|---|
| `Client::send` | The typed response. |
| `Client::send_guarded` | Checks the car's state with a free call first and only makes the billed call when it is online; otherwise reports `Guarded::Skipped` and spends nothing. |
| `Client::send_metered` | The typed response plus the `ratelimit-*` quota the billed endpoints report. |
| `Client::send_raw` | The response body **verbatim and unscrubbed** (VIN, coordinates, odometer) as one `serde_json::Value`, for observing schema drift. Treat it as personal data. |

`max_attempts` defaults to `1`, and the 401/412 recovery paths never re-send a request to a billed
endpoint. `send_guarded` narrows the window but cannot close it: the car can fall asleep between the free
check and the billed call.

## Design

How the crate is put together, and why, is written up in the repository:
[architecture](https://github.com/fleetwire-dev/fleetwire-rs/blob/main/docs/architecture.md) (the send
loop, billing judgment, token layer, redaction) and
[how this is built](https://github.com/fleetwire-dev/fleetwire-rs/blob/main/docs/how-this-is-built.md)
(the review and gate workflow, with the defects it caught here).

## Status

Early release. The API may change before 1.0.

The sixteen modelled GET endpoints (12 vehicle, 4 user) are the ones that were exercised against the
live API. That is not sixteen verified response shapes: a response is strongly typed only where a real
one was observed and stays raw JSON elsewhere, `mobile_enabled` answers 403 to a read-only token, and
`nearby_charging_sites` has only been seen answering 408 because the car was asleep each time. The crate
documentation lists what was measured, what was not, and what would settle each open question.

Not implemented: vehicle commands and anything that writes — the only request this crate sends that is
not a GET is the OAuth token refresh, it has no signing code, and it is not a route to either — and the
charging, energy and partner endpoints, which are left out until a live response can verify their shape.

A custom `TokenRefresher` must bound its own request time: `TokenManager` holds a cross-process file lock
while a refresh runs.

## Minimum Supported Rust Version (MSRV)

Rust `1.89.0` (edition 2024 floor). The MSRV may rise only in a documented minor release.

## License

Licensed under either of

- Apache License, Version 2.0 ([LICENSE-APACHE]LICENSE-APACHE)
- MIT license ([LICENSE-MIT]LICENSE-MIT)

at your option.

Unless you explicitly state otherwise, any contribution intentionally
submitted for inclusion in the work by you shall be dual licensed as above,
without any additional terms or conditions.