tesla-fleet-api 0.2.2 → 0.4.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 (192) hide show
  1. package/dist/_virtual/_rolldown/runtime.cjs +22 -0
  2. package/dist/_virtual/_rolldown/runtime.mjs +12 -0
  3. package/dist/charging.cjs +53 -0
  4. package/dist/charging.d.cts +31 -0
  5. package/dist/charging.d.mts +30 -0
  6. package/dist/charging.mjs +53 -0
  7. package/dist/commands.cjs +802 -0
  8. package/dist/commands.d.cts +350 -0
  9. package/dist/commands.d.mts +349 -0
  10. package/dist/commands.mjs +800 -0
  11. package/dist/const.cjs +300 -0
  12. package/dist/const.d.cts +287 -0
  13. package/dist/const.d.mts +287 -0
  14. package/dist/const.mjs +263 -0
  15. package/dist/energy.cjs +137 -0
  16. package/dist/energy.d.cts +95 -0
  17. package/{src/energy.ts → dist/energy.d.mts} +17 -140
  18. package/dist/energy.mjs +137 -0
  19. package/dist/energyspecific.cjs +99 -0
  20. package/dist/energyspecific.d.cts +78 -0
  21. package/dist/energyspecific.d.mts +77 -0
  22. package/dist/energyspecific.mjs +99 -0
  23. package/dist/exceptions.cjs +1487 -0
  24. package/dist/exceptions.d.cts +1142 -0
  25. package/dist/exceptions.d.mts +1142 -0
  26. package/dist/exceptions.mjs +1324 -0
  27. package/dist/index.cjs +226 -0
  28. package/dist/index.d.cts +14 -0
  29. package/dist/index.d.mts +14 -0
  30. package/dist/index.mjs +14 -0
  31. package/dist/partner.cjs +32 -0
  32. package/dist/partner.d.cts +24 -0
  33. package/dist/partner.d.mts +23 -0
  34. package/dist/partner.mjs +32 -0
  35. package/dist/router.cjs +0 -0
  36. package/dist/router.d.cts +1 -0
  37. package/dist/router.d.mts +1 -0
  38. package/dist/router.mjs +1 -0
  39. package/dist/signing/crypto.cjs +31 -0
  40. package/dist/signing/crypto.mjs +27 -0
  41. package/dist/signing/session.cjs +112 -0
  42. package/dist/signing/session.d.cts +69 -0
  43. package/dist/signing/session.d.mts +69 -0
  44. package/dist/signing/session.mjs +110 -0
  45. package/dist/tariff.cjs +292 -0
  46. package/dist/{tariff.d.ts → tariff.d.cts} +17 -17
  47. package/dist/tariff.d.mts +29 -0
  48. package/dist/tariff.mjs +291 -0
  49. package/dist/teslafleetapi.cjs +125 -0
  50. package/dist/teslafleetapi.d.cts +64 -0
  51. package/dist/teslafleetapi.d.mts +64 -0
  52. package/dist/teslafleetapi.mjs +125 -0
  53. package/dist/teslemetry.cjs +36 -0
  54. package/dist/teslemetry.d.cts +23 -0
  55. package/dist/teslemetry.d.mts +23 -0
  56. package/dist/teslemetry.mjs +36 -0
  57. package/dist/tessie.cjs +34 -0
  58. package/dist/tessie.d.cts +23 -0
  59. package/dist/tessie.d.mts +23 -0
  60. package/dist/tessie.mjs +34 -0
  61. package/dist/types/commands.d.cts +28 -0
  62. package/dist/types/commands.d.mts +28 -0
  63. package/dist/types/live_status.d.cts +30 -0
  64. package/dist/types/live_status.d.mts +30 -0
  65. package/dist/types/products.d.cts +58 -0
  66. package/dist/types/products.d.mts +58 -0
  67. package/dist/types/responses.d.cts +9 -0
  68. package/dist/types/responses.d.mts +9 -0
  69. package/dist/types/site_info.d.cts +154 -0
  70. package/dist/types/site_info.d.mts +154 -0
  71. package/dist/types/vehicle.d.cts +27 -0
  72. package/dist/types/vehicle.d.mts +27 -0
  73. package/dist/types/vehicle_data.d.cts +278 -0
  74. package/dist/types/vehicle_data.d.mts +278 -0
  75. package/dist/types.cjs +0 -0
  76. package/dist/types.d.cts +9 -0
  77. package/dist/types.d.mts +9 -0
  78. package/dist/types.mjs +1 -0
  79. package/dist/user.cjs +28 -0
  80. package/dist/user.d.cts +17 -0
  81. package/dist/user.d.mts +16 -0
  82. package/dist/user.mjs +28 -0
  83. package/dist/vehicle.cjs +804 -0
  84. package/dist/vehicle.d.cts +550 -0
  85. package/dist/vehicle.d.mts +549 -0
  86. package/dist/vehicle.mjs +804 -0
  87. package/dist/vehiclesigned.cjs +20 -0
  88. package/dist/vehiclesigned.d.cts +14 -0
  89. package/dist/{vehiclesigned.d.ts → vehiclesigned.d.mts} +3 -3
  90. package/dist/vehiclesigned.mjs +20 -0
  91. package/dist/vehiclespecific.cjs +604 -0
  92. package/dist/vehiclespecific.d.cts +433 -0
  93. package/dist/vehiclespecific.d.mts +432 -0
  94. package/dist/vehiclespecific.mjs +604 -0
  95. package/package.json +108 -35
  96. package/dist/charging.d.ts +0 -30
  97. package/dist/charging.js +0 -51
  98. package/dist/charging.js.map +0 -1
  99. package/dist/commands.d.ts +0 -352
  100. package/dist/commands.js +0 -875
  101. package/dist/commands.js.map +0 -1
  102. package/dist/energy.d.ts +0 -94
  103. package/dist/energy.js +0 -125
  104. package/dist/energy.js.map +0 -1
  105. package/dist/energyspecific.d.ts +0 -77
  106. package/dist/energyspecific.js +0 -97
  107. package/dist/energyspecific.js.map +0 -1
  108. package/dist/helpers.d.ts +0 -2
  109. package/dist/helpers.js +0 -10
  110. package/dist/helpers.js.map +0 -1
  111. package/dist/index.d.ts +0 -14
  112. package/dist/index.js +0 -14
  113. package/dist/index.js.map +0 -1
  114. package/dist/partner.d.ts +0 -23
  115. package/dist/partner.js +0 -31
  116. package/dist/partner.js.map +0 -1
  117. package/dist/signing/crypto.d.ts +0 -10
  118. package/dist/signing/crypto.js +0 -26
  119. package/dist/signing/crypto.js.map +0 -1
  120. package/dist/signing/errors.d.ts +0 -29
  121. package/dist/signing/errors.js +0 -40
  122. package/dist/signing/errors.js.map +0 -1
  123. package/dist/signing/session.d.ts +0 -69
  124. package/dist/signing/session.js +0 -102
  125. package/dist/signing/session.js.map +0 -1
  126. package/dist/tariff.js +0 -302
  127. package/dist/tariff.js.map +0 -1
  128. package/dist/teslafleetapi.d.ts +0 -58
  129. package/dist/teslafleetapi.js +0 -120
  130. package/dist/teslafleetapi.js.map +0 -1
  131. package/dist/teslemetry.d.ts +0 -29
  132. package/dist/teslemetry.js +0 -39
  133. package/dist/teslemetry.js.map +0 -1
  134. package/dist/tessie.d.ts +0 -23
  135. package/dist/tessie.js +0 -28
  136. package/dist/tessie.js.map +0 -1
  137. package/dist/types/commands.d.ts +0 -44
  138. package/dist/types/commands.js +0 -11
  139. package/dist/types/commands.js.map +0 -1
  140. package/dist/types/live_status.d.ts +0 -26
  141. package/dist/types/live_status.js +0 -2
  142. package/dist/types/live_status.js.map +0 -1
  143. package/dist/types/products.d.ts +0 -54
  144. package/dist/types/products.js +0 -2
  145. package/dist/types/products.js.map +0 -1
  146. package/dist/types/responses.d.ts +0 -5
  147. package/dist/types/responses.js +0 -2
  148. package/dist/types/responses.js.map +0 -1
  149. package/dist/types/site_info.d.ts +0 -150
  150. package/dist/types/site_info.js +0 -2
  151. package/dist/types/site_info.js.map +0 -1
  152. package/dist/types/vehicle.d.ts +0 -22
  153. package/dist/types/vehicle.js +0 -2
  154. package/dist/types/vehicle.js.map +0 -1
  155. package/dist/types/vehicle_data.d.ts +0 -274
  156. package/dist/types/vehicle_data.js +0 -2
  157. package/dist/types/vehicle_data.js.map +0 -1
  158. package/dist/user.d.ts +0 -16
  159. package/dist/user.js +0 -26
  160. package/dist/user.js.map +0 -1
  161. package/dist/vehicle.d.ts +0 -548
  162. package/dist/vehicle.js +0 -781
  163. package/dist/vehicle.js.map +0 -1
  164. package/dist/vehiclesigned.js +0 -19
  165. package/dist/vehiclesigned.js.map +0 -1
  166. package/dist/vehiclespecific.d.ts +0 -432
  167. package/dist/vehiclespecific.js +0 -601
  168. package/dist/vehiclespecific.js.map +0 -1
  169. package/src/charging.ts +0 -66
  170. package/src/commands.ts +0 -1134
  171. package/src/energyspecific.ts +0 -116
  172. package/src/helpers.ts +0 -11
  173. package/src/index.ts +0 -20
  174. package/src/partner.ts +0 -37
  175. package/src/signing/crypto.ts +0 -29
  176. package/src/signing/errors.ts +0 -50
  177. package/src/signing/session.ts +0 -132
  178. package/src/tariff.ts +0 -375
  179. package/src/teslafleetapi.ts +0 -182
  180. package/src/teslemetry.ts +0 -54
  181. package/src/tessie.ts +0 -42
  182. package/src/types/commands.ts +0 -62
  183. package/src/types/live_status.ts +0 -27
  184. package/src/types/products.ts +0 -61
  185. package/src/types/responses.ts +0 -1
  186. package/src/types/site_info.ts +0 -159
  187. package/src/types/vehicle.ts +0 -23
  188. package/src/types/vehicle_data.ts +0 -286
  189. package/src/user.ts +0 -35
  190. package/src/vehicle.ts +0 -895
  191. package/src/vehiclesigned.ts +0 -20
  192. package/src/vehiclespecific.ts +0 -818
@@ -1,116 +0,0 @@
1
- import Energy from "./energy.js";
2
- import { LiveStatusResponse } from "./types/live_status.js";
3
- import { SiteInfoResponse } from "./types/site_info.js";
4
-
5
- // Energy Class
6
- export default class EnergySpecific {
7
- parent: Energy;
8
- energy_site_id: number;
9
-
10
- constructor(parent: Energy, energy_site_id: number) {
11
- this.parent = parent;
12
- this.energy_site_id = energy_site_id;
13
- }
14
-
15
- /**
16
- * Adjust the site's backup reserve.
17
- * @param backup_reserve_percent The desired backup reserve percent.
18
- * @returns
19
- */
20
- async backup(backup_reserve_percent: number): Promise<Record<string, any>> {
21
- return this.parent.backup(this.energy_site_id, backup_reserve_percent);
22
- }
23
-
24
- /**
25
- * Returns the backup (off-grid) event history of the site in duration of seconds.
26
- * @param kind The kind of history to be requested. 'backup', 'charge', 'energy' are all supported.
27
- * @param start_date Start date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
28
- * @param end_date End date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
29
- * @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.
30
- * @param time_zone Timezone of the requested window in IANA name format. i.e. 'America/Los_Angeles'
31
- * @returns
32
- */
33
- async backup_history(kind: string, start_date: string, end_date: string, period: string, time_zone: string): Promise<Record<string, any>> {
34
- return this.parent.backup_history(this.energy_site_id, kind, start_date, end_date, period, time_zone);
35
- }
36
-
37
- /**
38
- * Returns the charging history of a wall connector.
39
- * @param kind The kind of history to be requested. 'backup', 'charge', 'energy' are all supported.
40
- * @param start_date Start date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
41
- * @param end_date End date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
42
- * @param time_zone Timezone of the requested window in IANA name format. i.e. 'America/Los_Angeles'
43
- * @returns
44
- */
45
- async charge_history(kind: string, start_date: string, end_date: string, time_zone: string): Promise<Record<string, any>> {
46
- return this.parent.charge_history(this.energy_site_id, kind, start_date, end_date, time_zone);
47
- }
48
-
49
- /**
50
- * Returns the energy history of the site in duration of seconds.
51
- * @param kind The kind of history to be requested. 'backup', 'charge', 'energy' are all supported.
52
- * @param start_date Start date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
53
- * @param end_date End date of the window to retrieve backup events in RFC3339 format. i.e. 2023-01-01T00:00:00-08:00
54
- * @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.
55
- * @param time_zone Timezone of the requested window in IANA name format. i.e. 'America/Los_Angeles'
56
- * @returns
57
- */
58
- async energy_history(kind: string, start_date: string, end_date: string, period: string, time_zone: string): Promise<Record<string, any>> {
59
- return this.parent.energy_history(this.energy_site_id, kind, start_date, end_date, period, time_zone);
60
- }
61
-
62
- /**
63
- * Allow/disallow charging from the grid and exporting energy to the grid.
64
- * @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.
65
- * @param customer_preferred_export_rule The desired behavior for grid exporting. The available options are battery_ok, pv_only, and never.
66
- * @returns
67
- */
68
- async grid_import_export(
69
- disallow_charge_from_grid_with_solar_installed: boolean | null = null,
70
- customer_preferred_export_rule: string | null = null
71
- ): Promise<Record<string, any>> {
72
- return this.parent.grid_import_export(this.energy_site_id, disallow_charge_from_grid_with_solar_installed, customer_preferred_export_rule);
73
- }
74
-
75
- /**
76
- * Returns the live status of the site.
77
- * @returns
78
- */
79
- async live_status(): Promise<LiveStatusResponse> {
80
- return this.parent.live_status(this.energy_site_id);
81
- }
82
-
83
- /**
84
- * Adjust the site's off-grid vehicle charging backup reserve.
85
- * @param off_grid_vehicle_charging_reserve_percent The desired off grid vehicle charging reserve percent.
86
- * @returns
87
- */
88
- async off_grid_vehicle_charging_reserve(off_grid_vehicle_charging_reserve_percent: number): Promise<Record<string, any>> {
89
- return this.parent.off_grid_vehicle_charging_reserve(this.energy_site_id, off_grid_vehicle_charging_reserve_percent);
90
- }
91
-
92
- /**
93
- * Set the site's mode.
94
- * @param default_real_mode
95
- * @returns
96
- */
97
- async operation(default_real_mode: string): Promise<Record<string, any>> {
98
- return this.parent.operation(this.energy_site_id, default_real_mode);
99
- }
100
-
101
- /**
102
- * Returns information about the site. Things like assets (has solar, etc), settings (backup reserve, etc), and features (storm_mode_capable, etc).
103
- */
104
- async site_info(): Promise<SiteInfoResponse> {
105
- return this.parent.site_info(this.energy_site_id);
106
- }
107
-
108
- /**
109
- * Update storm watch participation.
110
- * @param enabled The storm mode participation value to set.
111
- * @returns
112
- */
113
- async storm_mode(enabled: boolean): Promise<Record<string, any>> {
114
- return this.parent.storm_mode(this.energy_site_id, enabled);
115
- }
116
- }
package/src/helpers.ts DELETED
@@ -1,11 +0,0 @@
1
- import { CommandResponse } from "./types/commands.js";
2
-
3
- export const validate = async (body: CommandResponse): Promise<void> => {
4
- if (body?.error) {
5
- return Promise.reject(body.error);
6
- }
7
- if (body?.response?.result == false) {
8
- return Promise.reject(body.response.reason);
9
- }
10
- return Promise.resolve();
11
- };
package/src/index.ts DELETED
@@ -1,20 +0,0 @@
1
- import Commands from "./commands.js";
2
- import Energy from "./energy.js";
3
- import EnergySpecific from "./energyspecific.js";
4
- import TeslaFleetApi from "./teslafleetapi.js";
5
- import Teslemetry from "./teslemetry.js";
6
- import Tessie from "./tessie.js";
7
- import Vehicle from "./vehicle.js";
8
- import VehicleSigned from "./vehiclesigned.js";
9
- import VehicleSpecific from "./vehiclespecific.js";
10
-
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 type { TariffRate, TariffPeriod, TariffResolution } from "./tariff.js";
package/src/partner.ts DELETED
@@ -1,37 +0,0 @@
1
- import TeslaFleetApi from "./teslafleetapi.js";
2
-
3
- // Partner Class
4
- export default class Partner {
5
- parent: TeslaFleetApi;
6
-
7
- constructor(parent: TeslaFleetApi) {
8
- this.parent = parent;
9
- }
10
-
11
- /**
12
- * Returns the public key associated with a domain. It can be used to ensure the registration was successful.
13
- * @param domain Domain of the partner account.
14
- * @returns
15
- */
16
- async public_key(domain: string | null = null): Promise<Record<string, any>> {
17
- return this.parent._request("GET", "api/1/partner_accounts/public_key", { domain });
18
- }
19
-
20
- /**
21
- * Registers an existing account before it can be used for general API access. Each application from developer.tesla.com must complete this step.
22
- * @param domain Domain of the partner account.
23
- * @returns
24
- */
25
- async register(domain: string): Promise<Record<string, any>> {
26
- return this.parent._request("POST", "api/1/partner_accounts", null, { domain });
27
- }
28
-
29
- /**
30
- * Returns recent fleet telemetry errors reported by vehicles after receiving the config.
31
- * @param domain Domain of the partner account.
32
- * @returns
33
- */
34
- async fleet_telemetry_errors(domain: string): Promise<Record<string, any>> {
35
- return this.parent._request("GET", "api/1/partner_accounts/fleet_telemetry_errors", { domain });
36
- }
37
- }
@@ -1,29 +0,0 @@
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
- }
@@ -1,50 +0,0 @@
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
- }
@@ -1,132 +0,0 @@
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
- }