tesla-fleet-api 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/commands.d.ts +352 -0
  2. package/dist/commands.js +875 -0
  3. package/dist/commands.js.map +1 -0
  4. package/dist/energy.js +6 -2
  5. package/dist/energy.js.map +1 -1
  6. package/dist/index.d.ts +8 -1
  7. package/dist/index.js +7 -1
  8. package/dist/index.js.map +1 -1
  9. package/dist/signing/crypto.d.ts +10 -0
  10. package/dist/signing/crypto.js +26 -0
  11. package/dist/signing/crypto.js.map +1 -0
  12. package/dist/signing/errors.d.ts +29 -0
  13. package/dist/signing/errors.js +40 -0
  14. package/dist/signing/errors.js.map +1 -0
  15. package/dist/signing/session.d.ts +69 -0
  16. package/dist/signing/session.js +102 -0
  17. package/dist/signing/session.js.map +1 -0
  18. package/dist/tariff.d.ts +29 -0
  19. package/dist/tariff.js +302 -0
  20. package/dist/tariff.js.map +1 -0
  21. package/dist/teslafleetapi.d.ts +5 -0
  22. package/dist/teslafleetapi.js +23 -9
  23. package/dist/teslafleetapi.js.map +1 -1
  24. package/dist/teslemetry.d.ts +4 -0
  25. package/dist/teslemetry.js +15 -1
  26. package/dist/teslemetry.js.map +1 -1
  27. package/dist/types/site_info.d.ts +37 -8
  28. package/dist/types/vehicle.d.ts +1 -0
  29. package/dist/types/vehicle.js +9 -1
  30. package/dist/types/vehicle.js.map +1 -1
  31. package/dist/vehicle.d.ts +12 -0
  32. package/dist/vehicle.js +13 -8
  33. package/dist/vehicle.js.map +1 -1
  34. package/dist/vehiclesigned.d.ts +13 -0
  35. package/dist/vehiclesigned.js +19 -0
  36. package/dist/vehiclesigned.js.map +1 -0
  37. package/dist/vehiclespecific.d.ts +3 -15
  38. package/dist/vehiclespecific.js.map +1 -1
  39. package/package.json +16 -6
  40. package/src/commands.ts +1134 -0
  41. package/src/energy.ts +197 -135
  42. package/src/index.ts +13 -1
  43. package/src/signing/crypto.ts +29 -0
  44. package/src/signing/errors.ts +50 -0
  45. package/src/signing/session.ts +132 -0
  46. package/src/tariff.ts +375 -0
  47. package/src/teslafleetapi.ts +160 -121
  48. package/src/teslemetry.ts +39 -24
  49. package/src/types/site_info.ts +38 -8
  50. package/src/types/vehicle.ts +10 -0
  51. package/src/vehicle.ts +16 -10
  52. package/src/vehiclesigned.ts +20 -0
  53. package/src/vehiclespecific.ts +811 -721
package/src/energy.ts CHANGED
@@ -5,151 +5,213 @@ import { SiteInfoResponse } from "./types/site_info.js";
5
5
 
6
6
  // Energy Class
7
7
  export default class Energy {
8
- parent: TeslaFleetApi;
8
+ parent: TeslaFleetApi;
9
9
 
10
- constructor(parent: TeslaFleetApi) {
11
- this.parent = parent;
12
- }
10
+ constructor(parent: TeslaFleetApi) {
11
+ this.parent = parent;
12
+ }
13
13
 
14
- /**
15
- * Create an Energy class for a specific site.
16
- * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
17
- * @returns `EnergySpecific` class
18
- */
19
- specific(energy_site_id: number): EnergySpecific {
20
- return new EnergySpecific(this, energy_site_id);
21
- }
14
+ /**
15
+ * Create an Energy class for a specific site.
16
+ * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
17
+ * @returns `EnergySpecific` class
18
+ */
19
+ specific(energy_site_id: number): EnergySpecific {
20
+ return new EnergySpecific(this, energy_site_id);
21
+ }
22
22
 
23
- /**
24
- * Adjust the site's backup reserve.
25
- * @param energy_site_id ID field of an energy site from /api/1/products endpoint.ID field of an energy site from /api/1/products endpoint.
26
- * @param backup_reserve_percent The desired backup reserve percent.
27
- * @returns
28
- */
29
- async backup(energy_site_id: number, backup_reserve_percent: number): Promise<Record<string, any>> {
30
- return this.parent._request("POST", `api/1/energy_sites/${energy_site_id}/backup`, null, { backup_reserve_percent });
31
- }
23
+ /**
24
+ * Adjust the site's backup reserve.
25
+ * @param energy_site_id ID field of an energy site from /api/1/products endpoint.ID field of an energy site from /api/1/products endpoint.
26
+ * @param backup_reserve_percent The desired backup reserve percent.
27
+ * @returns
28
+ */
29
+ async backup(
30
+ energy_site_id: number,
31
+ backup_reserve_percent: number,
32
+ ): Promise<Record<string, any>> {
33
+ return this.parent._request(
34
+ "POST",
35
+ `api/1/energy_sites/${energy_site_id}/backup`,
36
+ null,
37
+ { backup_reserve_percent },
38
+ );
39
+ }
32
40
 
33
- /**
34
- * Returns the backup (off-grid) event history of the site in duration of seconds.
35
- * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
36
- * @param kind The kind of history to be requested. 'backup', 'charge', 'energy' are all supported.
37
- * @param start_date Start date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
38
- * @param end_date End date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
39
- * @param period Period of the window to retrieve backup events. This can be day, week, month, year, lifetime and should align with the window requested.
40
- * @param time_zone Timezone of the requested window in IANA name format. i.e. 'America/Los_Angeles'
41
- * @returns
42
- */
43
- async backup_history(
44
- energy_site_id: number,
45
- kind: string,
46
- start_date: string,
47
- end_date: string,
48
- period: string,
49
- time_zone: string
50
- ): Promise<Record<string, any>> {
51
- return this.parent._request("GET", `api/1/energy_sites/${energy_site_id}/calendar_history`, null, { kind, start_date, end_date, period, time_zone });
52
- }
41
+ /**
42
+ * Returns the backup (off-grid) event history of the site in duration of seconds.
43
+ * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
44
+ * @param kind The kind of history to be requested. 'backup', 'charge', 'energy' are all supported.
45
+ * @param start_date Start date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
46
+ * @param end_date End date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
47
+ * @param period Period of the window to retrieve backup events. This can be day, week, month, year, lifetime and should align with the window requested.
48
+ * @param time_zone Timezone of the requested window in IANA name format. i.e. 'America/Los_Angeles'
49
+ * @returns
50
+ */
51
+ async backup_history(
52
+ energy_site_id: number,
53
+ kind: string,
54
+ start_date: string,
55
+ end_date: string,
56
+ period: string,
57
+ time_zone: string,
58
+ ): Promise<Record<string, any>> {
59
+ return this.parent._request(
60
+ "GET",
61
+ `api/1/energy_sites/${energy_site_id}/calendar_history`,
62
+ null,
63
+ { kind, start_date, end_date, period, time_zone },
64
+ );
65
+ }
53
66
 
54
- /**
55
- * Returns the charging history of a wall connector.
56
- * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
57
- * @param kind The kind of history to be requested. 'backup', 'charge', 'energy' are all supported.
58
- * @param start_date Start date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
59
- * @param end_date End date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
60
- * @param time_zone Timezone of the requested window in IANA name format. i.e. 'America/Los_Angeles'
61
- * @returns
62
- */
63
- async charge_history(energy_site_id: number, kind: string, start_date: string, end_date: string, time_zone: string): Promise<Record<string, any>> {
64
- return this.parent._request("GET", `api/1/energy_sites/${energy_site_id}/telemetry_history`, null, { kind, start_date, end_date, time_zone });
65
- }
67
+ /**
68
+ * Returns the charging history of a wall connector.
69
+ * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
70
+ * @param kind The kind of history to be requested. 'backup', 'charge', 'energy' are all supported.
71
+ * @param start_date Start date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
72
+ * @param end_date End date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
73
+ * @param time_zone Timezone of the requested window in IANA name format. i.e. 'America/Los_Angeles'
74
+ * @returns
75
+ */
76
+ async charge_history(
77
+ energy_site_id: number,
78
+ kind: string,
79
+ start_date: string,
80
+ end_date: string,
81
+ time_zone: string,
82
+ ): Promise<Record<string, any>> {
83
+ return this.parent._request(
84
+ "GET",
85
+ `api/1/energy_sites/${energy_site_id}/telemetry_history`,
86
+ null,
87
+ { kind, start_date, end_date, time_zone },
88
+ );
89
+ }
66
90
 
67
- /**
68
- * Returns the energy measurements of the site, aggregated to the requested period.
69
- * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
70
- * @param kind The kind of history to be requested. 'backup', 'charge', 'energy' are all supported.
71
- * @param start_dateStart date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
72
- * @param end_date End date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
73
- * @param period Period of the window to retrieve backup events. This can be day, week, month, year, lifetime and should align with the window requested.
74
- * @param time_zone Timezone of the requested window in IANA name format. i.e. 'America/Los_Angeles'
75
- * @returns
76
- */
77
- async energy_history(
78
- energy_site_id: number,
79
- kind: string,
80
- start_date: string,
81
- end_date: string,
82
- period: string,
83
- time_zone: string
84
- ): Promise<Record<string, any>> {
85
- return this.parent._request("GET", `api/1/energy_sites/${energy_site_id}/calendar_history`, null, { kind, start_date, end_date, period, time_zone });
86
- }
91
+ /**
92
+ * Returns the energy measurements of the site, aggregated to the requested period.
93
+ * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
94
+ * @param kind The kind of history to be requested. 'backup', 'charge', 'energy' are all supported.
95
+ * @param start_dateStart date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
96
+ * @param end_date End date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
97
+ * @param period Period of the window to retrieve backup events. This can be day, week, month, year, lifetime and should align with the window requested.
98
+ * @param time_zone Timezone of the requested window in IANA name format. i.e. 'America/Los_Angeles'
99
+ * @returns
100
+ */
101
+ async energy_history(
102
+ energy_site_id: number,
103
+ kind: string,
104
+ start_date: string,
105
+ end_date: string,
106
+ period: string,
107
+ time_zone: string,
108
+ ): Promise<Record<string, any>> {
109
+ return this.parent._request(
110
+ "GET",
111
+ `api/1/energy_sites/${energy_site_id}/calendar_history`,
112
+ null,
113
+ { kind, start_date, end_date, period, time_zone },
114
+ );
115
+ }
87
116
 
88
- /**
89
- * Allow/disallow charging from the grid and exporting energy to the grid.
90
- * @param energy_site_id
91
- * @param disallow_charge_from_grid_with_solar_installed The desired behavior towards importing from the grid. Charging from the grid is disabled when set to true and enabled when set to false.
92
- * @param customer_preferred_export_rule The desired behavior for grid exporting. The available options are battery_ok, pv_only, and never.
93
- * @returns
94
- */
95
- async grid_import_export(
96
- energy_site_id: number,
97
- disallow_charge_from_grid_with_solar_installed: boolean | null = null,
98
- customer_preferred_export_rule: string | null = null
99
- ): Promise<Record<string, any>> {
100
- return this.parent._request("POST", `api/1/energy_sites/${energy_site_id}/grid_import_export`, null, {
101
- disallow_charge_from_grid_with_solar_installed,
102
- customer_preferred_export_rule,
103
- });
104
- }
117
+ /**
118
+ * Allow/disallow charging from the grid and exporting energy to the grid.
119
+ * @param energy_site_id
120
+ * @param disallow_charge_from_grid_with_solar_installed The desired behavior towards importing from the grid. Charging from the grid is disabled when set to true and enabled when set to false.
121
+ * @param customer_preferred_export_rule The desired behavior for grid exporting. The available options are battery_ok, pv_only, and never.
122
+ * @returns
123
+ */
124
+ async grid_import_export(
125
+ energy_site_id: number,
126
+ disallow_charge_from_grid_with_solar_installed: boolean | null = null,
127
+ customer_preferred_export_rule: string | null = null,
128
+ ): Promise<Record<string, any>> {
129
+ return this.parent._request(
130
+ "POST",
131
+ `api/1/energy_sites/${energy_site_id}/grid_import_export`,
132
+ null,
133
+ {
134
+ disallow_charge_from_grid_with_solar_installed,
135
+ customer_preferred_export_rule,
136
+ },
137
+ );
138
+ }
105
139
 
106
- /**
107
- * Returns the live status of the site (power, state of energy, grid status, storm mode).
108
- * @param energy_site_id
109
- * @returns
110
- */
111
- async live_status(energy_site_id: number): Promise<LiveStatusResponse> {
112
- return this.parent._request("GET", `api/1/energy_sites/${energy_site_id}/live_status`).then(({response}) => response);
113
- }
140
+ /**
141
+ * Returns the live status of the site (power, state of energy, grid status, storm mode).
142
+ * @param energy_site_id
143
+ * @returns
144
+ */
145
+ async live_status(energy_site_id: number): Promise<LiveStatusResponse> {
146
+ return this.parent
147
+ ._request("GET", `api/1/energy_sites/${energy_site_id}/live_status`)
148
+ .then(({ response }) => response);
149
+ }
114
150
 
115
- /**
116
- * Adjust the site's off-grid vehicle charging backup reserve.
117
- * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
118
- * @param off_grid_vehicle_charging_reserve_percent The desired off grid vehicle charging reserve percent.
119
- * @returns
120
- */
121
- async off_grid_vehicle_charging_reserve(energy_site_id: number, off_grid_vehicle_charging_reserve_percent: number): Promise<Record<string, any>> {
122
- return this.parent._request("POST", `api/1/energy_sites/${energy_site_id}/off_grid_vehicle_charging_reserve`, null, {
123
- off_grid_vehicle_charging_reserve_percent,
124
- });
125
- }
151
+ /**
152
+ * Adjust the site's off-grid vehicle charging backup reserve.
153
+ * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
154
+ * @param off_grid_vehicle_charging_reserve_percent The desired off grid vehicle charging reserve percent.
155
+ * @returns
156
+ */
157
+ async off_grid_vehicle_charging_reserve(
158
+ energy_site_id: number,
159
+ off_grid_vehicle_charging_reserve_percent: number,
160
+ ): Promise<Record<string, any>> {
161
+ return this.parent._request(
162
+ "POST",
163
+ `api/1/energy_sites/${energy_site_id}/off_grid_vehicle_charging_reserve`,
164
+ null,
165
+ {
166
+ off_grid_vehicle_charging_reserve_percent,
167
+ },
168
+ );
169
+ }
126
170
 
127
- /**
128
- * Set the site's mode.
129
- * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
130
- * @param default_real_mode The desired operation mode. Use autonomous for time-based control and self_consumption for self-powered mode.
131
- * @returns
132
- */
133
- async operation(energy_site_id: number, default_real_mode: string): Promise<Record<string, any>> {
134
- return this.parent._request("POST", `api/1/energy_sites/${energy_site_id}/operation`, null, { default_real_mode });
135
- }
171
+ /**
172
+ * Set the site's mode.
173
+ * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
174
+ * @param default_real_mode The desired operation mode. Use autonomous for time-based control and self_consumption for self-powered mode.
175
+ * @returns
176
+ */
177
+ async operation(
178
+ energy_site_id: number,
179
+ default_real_mode: string,
180
+ ): Promise<Record<string, any>> {
181
+ return this.parent._request(
182
+ "POST",
183
+ `api/1/energy_sites/${energy_site_id}/operation`,
184
+ null,
185
+ { default_real_mode },
186
+ );
187
+ }
136
188
 
137
- /**
138
- * Returns information about the site. Things like assets (has solar, etc), settings (backup reserve, etc), and features (storm_mode_capable, etc).
139
- * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
140
- * @returns
141
- */
142
- async site_info(energy_site_id: number): Promise<SiteInfoResponse> {
143
- return this.parent._request("GET", `api/1/energy_sites/${energy_site_id}/site_info`).then(({response}) => response);
144
- }
189
+ /**
190
+ * Returns information about the site. Things like assets (has solar, etc), settings (backup reserve, etc), and features (storm_mode_capable, etc).
191
+ * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
192
+ * @returns
193
+ */
194
+ async site_info(energy_site_id: number): Promise<SiteInfoResponse> {
195
+ return this.parent
196
+ ._request("GET", `api/1/energy_sites/${energy_site_id}/site_info`)
197
+ .then(({ response }) => response);
198
+ }
145
199
 
146
- /**
147
- * Update storm watch participation.
148
- * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
149
- * @param enabled The storm mode participation value to set.
150
- * @returns
151
- */
152
- async storm_mode(energy_site_id: number, enabled: boolean): Promise<Record<string, any>> {
153
- return this.parent._request("POST", `api/1/energy_sites/${energy_site_id}/storm_mode`, null, { enabled });
154
- }
200
+ /**
201
+ * Update storm watch participation.
202
+ * @param energy_site_id ID field of an energy site from /api/1/products endpoint.
203
+ * @param enabled The storm mode participation value to set.
204
+ * @returns
205
+ */
206
+ async storm_mode(
207
+ energy_site_id: number,
208
+ enabled: boolean,
209
+ ): Promise<Record<string, any>> {
210
+ return this.parent._request(
211
+ "POST",
212
+ `api/1/energy_sites/${energy_site_id}/storm_mode`,
213
+ null,
214
+ { enabled },
215
+ );
216
+ }
155
217
  }
package/src/index.ts CHANGED
@@ -1,9 +1,21 @@
1
+ import Commands from "./commands.js";
1
2
  import Energy from "./energy.js";
2
3
  import EnergySpecific from "./energyspecific.js";
3
4
  import TeslaFleetApi from "./teslafleetapi.js";
4
5
  import Teslemetry from "./teslemetry.js";
5
6
  import Tessie from "./tessie.js";
6
7
  import Vehicle from "./vehicle.js";
8
+ import VehicleSigned from "./vehiclesigned.js";
7
9
  import VehicleSpecific from "./vehiclespecific.js";
8
10
 
9
- export { Energy, EnergySpecific, TeslaFleetApi, Teslemetry, Tessie, Vehicle, VehicleSpecific };
11
+ export { Commands, Energy, EnergySpecific, TeslaFleetApi, Teslemetry, Tessie, Vehicle, VehicleSigned, VehicleSpecific };
12
+ export { Session } from "./signing/session.js";
13
+ export {
14
+ SignedCommandError,
15
+ NotOnVehicleWhitelistError,
16
+ SignedCommandFaultError,
17
+ RetryableSignedCommandFaultError,
18
+ } from "./signing/errors.js";
19
+ export { getTariffPeriods } from "./tariff.js";
20
+ export { Models } from "./types/vehicle.js";
21
+ export type { TariffRate, TariffPeriod, TariffResolution } from "./tariff.js";
@@ -0,0 +1,29 @@
1
+ import crypto from "crypto";
2
+
3
+ const CURVE = "prime256v1"; // NIST P-256, matches the vehicle-command protocol.
4
+
5
+ /** Derive the uncompressed public key point for a raw P-256 private scalar. */
6
+ export function publicKeyFor(privateKey: Buffer): Buffer {
7
+ const ecdh = crypto.createECDH(CURVE);
8
+ ecdh.setPrivateKey(privateKey);
9
+ return ecdh.getPublicKey();
10
+ }
11
+
12
+ /**
13
+ * Derive the 16-byte signed-command shared key: ECDH(ourPrivate, vehiclePublic),
14
+ * then SHA-1 truncated to 16 bytes - matching the vehicle-command protocol
15
+ * (not a general-purpose KDF, do not reuse this for anything else).
16
+ */
17
+ export function deriveSharedKey(privateKey: Buffer, vehiclePublicKey: Buffer): Buffer {
18
+ const ecdh = crypto.createECDH(CURVE);
19
+ ecdh.setPrivateKey(privateKey);
20
+ const secret = ecdh.computeSecret(vehiclePublicKey);
21
+ return crypto.createHash("sha1").update(secret).digest().subarray(0, 16);
22
+ }
23
+
24
+ /** Big-endian uint32, as used throughout the signed-command metadata tags. */
25
+ export function uint32BE(value: number): Buffer {
26
+ const buffer = Buffer.alloc(4);
27
+ buffer.writeUInt32BE(value >>> 0, 0);
28
+ return buffer;
29
+ }
@@ -0,0 +1,50 @@
1
+ import { MessageFaultE, messageFaultEToJSON } from "@teslemetry/tesla-protocol/command/universal_message";
2
+
3
+ /**
4
+ * Base class for every error raised by the signed-command layer.
5
+ */
6
+ export class SignedCommandError extends Error {}
7
+
8
+ /**
9
+ * The vehicle rejected the session handshake because this key has not been
10
+ * paired with it (added via the Tesla app / NFC card).
11
+ */
12
+ export class NotOnVehicleWhitelistError extends SignedCommandError {
13
+ constructor() {
14
+ super(
15
+ "This public key is not on the vehicle's key whitelist. Pair it with the vehicle first.",
16
+ );
17
+ }
18
+ }
19
+
20
+ /**
21
+ * The vehicle rejected a signed command with a `MessageFaultE` other than
22
+ * `MESSAGEFAULT_ERROR_NONE`.
23
+ */
24
+ export class SignedCommandFaultError extends SignedCommandError {
25
+ fault: MessageFaultE;
26
+
27
+ constructor(fault: MessageFaultE) {
28
+ super(`Vehicle rejected signed command: ${messageFaultEToJSON(fault)}`);
29
+ this.fault = fault;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * A `SignedCommandFaultError` whose fault the vehicle resolves by handing back
35
+ * fresh session info (epoch/counter drift) - `_command` retries these,
36
+ * bounded, by re-signing against the updated session before giving up.
37
+ */
38
+ export class RetryableSignedCommandFaultError extends SignedCommandFaultError {}
39
+
40
+ export function createFaultError(
41
+ fault: MessageFaultE,
42
+ ): SignedCommandFaultError {
43
+ if (
44
+ fault === MessageFaultE.MESSAGEFAULT_ERROR_INCORRECT_EPOCH ||
45
+ fault === MessageFaultE.MESSAGEFAULT_ERROR_INVALID_TOKEN_OR_COUNTER
46
+ ) {
47
+ return new RetryableSignedCommandFaultError(fault);
48
+ }
49
+ return new SignedCommandFaultError(fault);
50
+ }
@@ -0,0 +1,132 @@
1
+ import crypto from "crypto";
2
+ import { Domain } from "@teslemetry/tesla-protocol/command/universal_message";
3
+ import {
4
+ HMACPersonalizedSignatureData,
5
+ SessionInfo,
6
+ } from "@teslemetry/tesla-protocol/command/signatures";
7
+
8
+ /** Key material derived (but not yet trusted/committed) for a candidate vehicle public key. */
9
+ export interface SessionKeys {
10
+ sharedKey: Buffer;
11
+ hmacKey: Buffer;
12
+ sessionInfoKey: Buffer;
13
+ }
14
+
15
+ /**
16
+ * Per-domain (VCSEC / Infotainment) signed-command session: tracks the
17
+ * anti-replay counter/epoch handed out by the vehicle's handshake reply and
18
+ * the HMAC keys derived from it.
19
+ *
20
+ * Deriving key material (`keysFor`) is split from committing it (`commit`)
21
+ * because the caller must authenticate a `SessionInfo` reply - by verifying
22
+ * its `session_info_tag` against the very keys derived here - *before*
23
+ * trusting anything in it, including the vehicle public key the shared key
24
+ * itself is derived from. See `Commands.validateAndUpdateSession`.
25
+ *
26
+ * A `Session` is not itself thread-safe; `withLock` serializes the
27
+ * message-build step (which mutates `counter`) so concurrent commands on the
28
+ * same domain cannot race on the same counter value.
29
+ */
30
+ export class Session {
31
+ readonly domain: Domain;
32
+ counter: number = 0;
33
+ epoch?: Buffer;
34
+ delta?: number;
35
+ sharedKey?: Buffer;
36
+ hmacKey?: Buffer;
37
+ sessionInfoKey?: Buffer;
38
+ publicKey?: Buffer;
39
+
40
+ /** Clock time of the last *authenticated* SessionInfo committed for the current epoch, guarding against replay/rollback. */
41
+ private lastAuthenticatedClockTime?: number;
42
+ private queue: Promise<void> = Promise.resolve();
43
+
44
+ constructor(
45
+ domain: Domain,
46
+ private readonly deriveSharedKey: (vehiclePublicKey: Buffer) => Buffer,
47
+ ) {
48
+ this.domain = domain;
49
+ }
50
+
51
+ /** Whether the handshake has completed and commands can be signed. */
52
+ get ready(): boolean {
53
+ return this.epoch !== undefined && this.hmacKey !== undefined && this.delta !== undefined;
54
+ }
55
+
56
+ /**
57
+ * Derive the shared key and its two HMAC sub-keys for a candidate vehicle
58
+ * public key, without touching any session state. Pure and side-effect
59
+ * free so a caller can verify authenticity first and discard the result
60
+ * if verification fails.
61
+ */
62
+ keysFor(vehiclePublicKey: Buffer): SessionKeys {
63
+ const sharedKey = this.deriveSharedKey(vehiclePublicKey);
64
+ const hmacKey = crypto.createHmac("sha256", sharedKey).update("authenticated command").digest();
65
+ const sessionInfoKey = crypto.createHmac("sha256", sharedKey).update("session info").digest();
66
+ return { sharedKey, hmacKey, sessionInfoKey };
67
+ }
68
+
69
+ /**
70
+ * Commit an already-authenticated `SessionInfo` plus the `keysFor` result
71
+ * derived from its public key. Per the vehicle-command protocol, the
72
+ * anti-replay counter must never roll back within the same epoch, and a
73
+ * clock time that regresses within the same epoch marks the reply as
74
+ * stale/replayed - returns `false` (without mutating any state) in that
75
+ * case so the caller can reject it.
76
+ */
77
+ commit(sessionInfo: SessionInfo, keys: SessionKeys): boolean {
78
+ const incomingEpoch = Buffer.from(sessionInfo.epoch);
79
+ const sameEpoch = this.epoch !== undefined && this.epoch.equals(incomingEpoch);
80
+
81
+ if (sameEpoch && this.lastAuthenticatedClockTime !== undefined && sessionInfo.clockTime < this.lastAuthenticatedClockTime) {
82
+ return false;
83
+ }
84
+
85
+ this.counter = sameEpoch ? Math.max(this.counter, sessionInfo.counter) : sessionInfo.counter;
86
+ this.epoch = incomingEpoch;
87
+ this.delta = Math.floor(Date.now() / 1000) - sessionInfo.clockTime;
88
+ this.lastAuthenticatedClockTime = sessionInfo.clockTime;
89
+ this.publicKey = Buffer.from(sessionInfo.publicKey);
90
+ this.sharedKey = keys.sharedKey;
91
+ this.hmacKey = keys.hmacKey;
92
+ this.sessionInfoKey = keys.sessionInfoKey;
93
+ return true;
94
+ }
95
+
96
+ /**
97
+ * Advance the anti-replay counter and return fresh signature metadata for
98
+ * an HMAC-personalized command. The command expires 10 seconds from now,
99
+ * corrected for clock drift against the vehicle (`delta`).
100
+ */
101
+ hmacPersonalized(): HMACPersonalizedSignatureData {
102
+ if (!this.ready || !this.epoch || this.delta === undefined) {
103
+ throw new Error("Session is not ready: perform the handshake first.");
104
+ }
105
+ this.counter++;
106
+ return HMACPersonalizedSignatureData.create({
107
+ epoch: this.epoch,
108
+ counter: this.counter,
109
+ expiresAt: Math.floor(Date.now() / 1000) - this.delta + 10,
110
+ });
111
+ }
112
+
113
+ /**
114
+ * Run `fn` with exclusive access to this session, queuing behind any
115
+ * in-flight caller. Held only for as long as `fn` takes - callers should
116
+ * keep it scoped to the synchronous message-build step, not a full
117
+ * network round trip.
118
+ */
119
+ async withLock<T>(fn: () => T | Promise<T>): Promise<T> {
120
+ const previous = this.queue;
121
+ let release!: () => void;
122
+ this.queue = new Promise<void>((resolve) => {
123
+ release = resolve;
124
+ });
125
+ await previous.catch((): void => undefined);
126
+ try {
127
+ return await fn();
128
+ } finally {
129
+ release();
130
+ }
131
+ }
132
+ }