Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/key-handling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
"tesla-fleet-api": minor
---

Key handling, compatible with python-tesla-fleet-api's key files:

- **Breaking:** `loadPrivateKey` is removed. It wrote no file and replaced `accessToken` with the PEM.
- New on every client: `get_private_key`, `get_rsa_private_key`, `private_key`, `rsa_private_key`, `has_private_key`, `has_rsa_private_key`, `public_pem`, `public_uncompressed_point`, `ec_public_der_spki`, `ec_public_der_spki_b64`, `rsa_public_der_pkcs1`, `rsa_public_der_pkcs1_b64` and `rsa_public_pem`. `get_private_key` returns the raw 32-byte `Buffer` that `Commands` takes, and `get_rsa_private_key` an RSA `KeyObject`.
- New files are created at mode 0600 with no world-readable window; a process that loses the create race reads the winner's file. An unusable existing key raises `PrivateKeyError` with reason `unreadable`, `encrypted`, `malformed` or `wrong_type`.
- `createSigned` falls back to the client's `private_key`.
- New in-memory helpers for keys kept outside files: `generate_ec_private_key_pem`, `generate_rsa_private_key_pem`, `ec_private_key_from_pem` and `rsa_public_der_pkcs1`.
5 changes: 5 additions & 0 deletions .changeset/teslafleetoauth.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tesla-fleet-api": minor
---

Add `TeslaFleetOAuth`, a port of python-tesla-fleet-api's OAuth client: `get_login_url`, `get_refresh_token`, `access_token`, `check_access_token` and `refresh_access_token`, with the token host following the region and an expired token refreshed before each request. `expires` is in epoch seconds, as in Python. Concurrent requests share one refresh, because Tesla's refresh tokens are single use. A refused code exchange or refresh rejects with the matching `TeslaFleetError`, e.g. `LoginRequired`.
7 changes: 7 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,13 @@ This file is the project's committed home for project-intrinsic agent knowledge:
- `Commands`'s `#privateKey`/`#publicKey` are native private class fields, not `protected`/TS-only `private` — the raw signing key must be unreachable off the instance entirely (`JSON.stringify`, structured logs), not merely inaccessible to outside code. Tests observe key derivation through a captured handshake message on the wire, never by reading the field.
- `test/helpers/fakevehicle.ts` is a from-scratch reimplementation of the vehicle side (independent HMAC verification, not a mock), so round-trip tests check the client against a second implementation of the wire format.

## Keys (`src/signing/keys.ts`)

- `TeslaFleetApi.get_private_key` returns, and `Commands` takes, a raw 32-byte `Buffer`; `get_rsa_private_key` returns a `KeyObject`, which is what `EnergySpecific` takes. Both live in native `#private` fields behind accessors. The files are PEMs shared with Python (SEC1 and PKCS#1), so don't change the format.
- A raw scalar has no curve, so a non-P-256 EC file is `wrong_type` here, though Python's loader accepts any curve.
- Encrypted-PEM detection reads the PEM markers. OpenSSL's error for a missing passphrase varies across Node versions.
- `test/fixtures/keys.ts` is generated by Python `cryptography`; never regenerate it from Node, or the byte comparisons stop proving anything.

## Errors (`src/exceptions.ts`)

- A class-for-class port of `python-tesla-fleet-api`'s `exceptions.py`: same names, parents, and `message`/`status`/`key`/`code` (as statics, copied onto instances). Add new errors there under their Python name, with no aliases; don't reintroduce per-module error files. `message` is always the class message; per-instance detail goes in `data`.
Expand Down
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,40 @@ class MyApi extends Teslemetry {
static override Vehicles = MyVehicles;
}
```

## OAuth

```ts
import { Scope, TeslaFleetOAuth } from "tesla-fleet-api";

const api = new TeslaFleetOAuth({ region: "na", client_id, client_secret, redirect_uri });
const url = api.get_login_url([Scope.OPENID, Scope.OFFLINE_ACCESS]);
await api.get_refresh_token(code);
```

An expired token refreshes before the next request. Tesla's refresh tokens are single use, so store `api.refresh_token` and `api.expires` (epoch seconds) after `get_refresh_token`, and whatever `refresh_access_token()` or `check_access_token()` returns. To store a refresh made by a request, read those two fields after it.

## Keys

`get_private_key` and `get_rsa_private_key` load a PEM file, or create it at mode 0600. Python's library reads the same files.

```ts
const privateKey = await api.get_private_key("private_key.pem"); // raw 32-byte Buffer
api.vehicles!.createSigned(vin); // falls back to it
api.public_pem;

await api.get_rsa_private_key("tedapi_rsa_private.pem"); // RSA KeyObject
api.rsa_public_der_pkcs1_b64;
```

To keep keys somewhere other than a file, as Homey does:

```ts
const pem = await generate_ec_private_key_pem();
api.private_key = ec_private_key_from_pem(pem);

const rsaPem = await generate_rsa_private_key_pem();
rsa_public_der_pkcs1(rsaPem);
```

An existing file or PEM that cannot be used raises `PrivateKeyError`, whose `reason` is `unreadable`, `encrypted`, `malformed` or `wrong_type`.
2 changes: 1 addition & 1 deletion src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ export default abstract class Commands extends VehicleSpecific {
throw new Error(`Signed commands require a 17-character VIN, got ${vin.length} characters.`);
}

const resolvedPrivateKey = privateKey ?? (parent as unknown as { private_key?: Buffer }).private_key;
const resolvedPrivateKey = privateKey ?? parent.private_key ?? parent.parent.private_key;
if (!resolvedPrivateKey) {
throw new Error("No private key provided for signed commands.");
}
Expand Down
10 changes: 9 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,25 @@ import Commands, { infotainment_command_name, vcsec_command_name } from "./comma
import Energy from "./energy.js";
import EnergySpecific from "./energyspecific.js";
import TeslaFleetApi from "./teslafleetapi.js";
import TeslaFleetOAuth from "./oauth.js";
import Teslemetry from "./teslemetry.js";
import Tessie from "./tessie.js";
import Vehicle from "./vehicle.js";
import VehicleSigned from "./vehiclesigned.js";
import VehicleSpecific from "./vehiclespecific.js";

export { Commands, Energy, EnergySpecific, TeslaFleetApi, Teslemetry, Tessie, Vehicle, VehicleSigned, VehicleSpecific };
export { Commands, Energy, EnergySpecific, TeslaFleetApi, TeslaFleetOAuth, Teslemetry, Tessie, Vehicle, VehicleSigned, VehicleSpecific };
export { infotainment_command_name, vcsec_command_name };
export type { AccessToken } from "./teslafleetapi.js";
export type { RefreshedToken, TeslaFleetOAuthOptions } from "./oauth.js";
export type { Logger } from "./log.js";
export { Session } from "./signing/session.js";
export {
ec_private_key_from_pem,
generate_ec_private_key_pem,
generate_rsa_private_key_pem,
rsa_public_der_pkcs1,
} from "./signing/keys.js";
export { DAY_OF_WEEK_BITS, days_of_week_mask } from "./commands.js";
export * from "./exceptions.js";
export { getTariffPeriods, unwrapTariffV2 } from "./tariff.js";
Expand Down
200 changes: 200 additions & 0 deletions src/oauth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
import { Method, Region, SERVERS, Scope, TOKEN_URLS, is_valid_region } from "./const.js";
import { InvalidResponse, MissingToken, TeslaFleetConnectionError, TeslaFleetError } from "./exceptions.js";
import { Logger } from "./log.js";
import TeslaFleetApi from "./teslafleetapi.js";

export type TeslaFleetOAuthOptions = {
region: Region;
client_id: string;
/** Needed only to exchange an authorization code. */
client_secret?: string;
redirect_uri?: string;
access_token?: string;
refresh_token?: string;
/** Expiry of `access_token`, in epoch seconds as `TeslaFleetOAuth.expires`. */
expires?: number;
debug?: boolean;
logger?: Logger;
fetch?: typeof fetch;
timeout?: number;
};

/** What a refresh hands back for the caller to persist. */
export type RefreshedToken = {
refresh_token: string;
/** Epoch seconds. */
expires: number;
};

function nowSeconds(): number {
return Date.now() / 1000;
}

/** The fields every token reply needs; a reply without them must not replace a working token. */
function tokenFrom(data: any): { access_token: string; expires: number } {
if (typeof data?.access_token !== "string" || typeof data.expires_in !== "number") {
throw new InvalidResponse();
}
return { access_token: data.access_token, expires: Math.floor(nowSeconds()) + data.expires_in };
}

/**
* Tesla Fleet API client that signs a user in with OAuth and keeps its access
* token fresh. `expires` is in epoch seconds, as in Python, so a stored
* token works with either library.
*/
export default class TeslaFleetOAuth extends TeslaFleetApi {
readonly client_id: string;
redirect_uri: string | null;
refresh_token: string | null;
/** Expiry of the access token, in epoch seconds. */
expires: number;
#client_secret: string | null;
// Tesla's refresh tokens are single use, so concurrent requests must share one refresh.
#refreshing: Promise<RefreshedToken> | null = null;

constructor(options: TeslaFleetOAuthOptions) {
if (!is_valid_region(options.region)) {
throw new Error("Invalid region");
}
const { region, client_id, client_secret, redirect_uri, access_token, refresh_token, expires, ...rest } = options;
super({ ...rest, region, accessToken: access_token });
this.client_id = client_id;
this.#client_secret = client_secret ?? null;
this.redirect_uri = redirect_uri ?? null;
this.refresh_token = refresh_token ?? null;
this.expires = expires ?? 0;
}

/**
* The URL to send the user to, built exactly as Python builds it: values are
* not URL-encoded.
* @param scopes Scopes to request.
* @param state Value Tesla echoes back on the redirect.
*/
get_login_url(scopes: Scope[], state: string = "login"): string {
if (this.redirect_uri == null) {
throw new Error("Redirect URI is missing");
}
const domain = this.region === "cn" ? "auth.tesla.cn" : "auth.tesla.com";
return `https://${domain}/oauth2/v3/authorize?response_type=code&client_id=${this.client_id}&redirect_uri=${this.redirect_uri}&scope=${scopes.join("+")}&state=${state}`;
}

/**
* Exchange an authorization code for tokens. A code prefixed with a region
* (e.g. `NA_...`) also selects that region's server.
* @param code The code from the login redirect.
*/
async get_refresh_token(code: string): Promise<void> {
if (this.#client_secret == null) {
throw new Error("Client secret is missing");
}
if (this.redirect_uri == null) {
throw new Error("Redirect URI is missing");
}
this.server ??= SERVERS[this.region ?? "na"];

const data = await this.#token({
grant_type: "authorization_code",
client_id: this.client_id,
client_secret: this.#client_secret,
code,
audience: this.server,
redirect_uri: this.redirect_uri,
});
const { access_token, expires } = tokenFrom(data);
this.refresh_token = data.refresh_token ?? null;
this.accessToken = access_token;
this.expires = expires;

const region = code.split("_")[0].toLowerCase();
if (is_valid_region(region)) {
this.server = SERVERS[region];
}
}

/**
* The current access token, refreshed first when `expires` has passed.
* @throws MissingToken when there is no token and none can be refreshed.
*/
override async access_token(): Promise<string> {
if (this.expires < nowSeconds()) {
await this.refresh_access_token();
}
if (this.accessToken && typeof this.accessToken === "string") {
return this.accessToken;
}
throw new MissingToken("Access token is missing");
}

/**
* Refresh the access token if it is missing or expired.
* @returns The refreshed token to persist, or `null` when none was needed.
*/
async check_access_token(): Promise<RefreshedToken | null> {
if (this.accessToken && this.expires > nowSeconds()) {
return null;
}
return this.refresh_access_token();
}

/**
* Refresh the access token. Tesla rotates the refresh token, so persist what
* this returns.
* @throws MissingToken without a refresh token, or the `TeslaFleetError`
* matching the failure, e.g. `LoginRequired`.
*/
refresh_access_token(): Promise<RefreshedToken> {
this.#refreshing ??= this.#refresh().finally(() => {
this.#refreshing = null;
});
return this.#refreshing;
}

async #refresh(): Promise<RefreshedToken> {
if (!this.refresh_token) {
throw new MissingToken("Refresh token is missing");
}
const data = await this.#token({
grant_type: "refresh_token",
client_id: this.client_id,
refresh_token: this.refresh_token,
});
const { access_token, expires } = tokenFrom(data);
if (typeof data.refresh_token !== "string") {
throw new InvalidResponse();
}
this.accessToken = access_token;
this.refresh_token = data.refresh_token;
this.expires = expires;
return { refresh_token: data.refresh_token, expires };
}

/** POST a form to the region's token endpoint. Bypasses `_request`, which would log the reply. */
async #token(form: Record<string, string>): Promise<any> {
try {
const resp = await this._fetch(TOKEN_URLS[this.region ?? "na"], {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams(form),
signal: this.timeout != null ? AbortSignal.timeout(this.timeout) : null,
});
return await this._response(resp);
} catch (error) {
if (error instanceof TeslaFleetError) {
throw error;
}
throw new TeslaFleetConnectionError(null, null, { cause: error });
}
}

override async _request(
method: Method,
path: string,
params: Record<string, any> | null = null,
json: Record<string, any> | null = null,
): Promise<any> {
await this.check_access_token();
return super._request(method, path, params, json);
}
}
Loading
Loading