-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathindex.js
More file actions
612 lines (567 loc) · 17.1 KB
/
index.js
File metadata and controls
612 lines (567 loc) · 17.1 KB
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
/* eslint-disable max-len */
/* eslint-disable camelcase */
'use strict';
const _ = require('lodash');
const crypto = require('crypto');
const {emitWarning} = require('process');
const SmartcarService = require('./lib/smartcar-service');
const util = require('./lib/util');
const config = require('./lib/config.json');
/* eslint-disable global-require */
/** @exports smartcar */
const smartcar = {
/** @see {@link module:errors} */
SmartcarError: require('./lib/smartcar-error'),
/** @see {@link Vehicle} */
Vehicle: require('./lib/vehicle'),
/** @see {@link AuthClient}*/
AuthClient: require('./lib/auth-client'),
};
/* eslint-enable global-require */
const spaceSeparatedList = (list) => {
if (Array.isArray(list)) {
return list.join(' ');
}
return list;
};
const buildCredentials = (options) => {
const clientId =
options.clientId || util.getOrThrowConfig('SMARTCAR_CLIENT_ID');
const clientSecret =
options.clientSecret || util.getOrThrowConfig('SMARTCAR_CLIENT_SECRET');
return Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
};
const buildOptionQueryParams = (options) => {
const parameters = {};
if (options.flags) {
parameters.flags = util.getFlagsString(options.flags);
}
if (options.hasOwnProperty('testMode')) {
emitWarning(
// eslint-disable-next-line max-len
'The "testMode" parameter is deprecated, please use the "mode" parameter instead.',
);
parameters.mode = options.testMode === true ? 'test' : 'live';
} else if (options.hasOwnProperty('mode')) {
parameters.mode = options.mode;
if (!['test', 'live', 'simulated'].includes(parameters.mode)) {
throw new Error( // eslint-disable-next-line max-len
"The \"mode\" parameter MUST be one of the following: 'test', 'live', 'simulated'",
);
}
}
if (options.testModeCompatibilityLevel) {
// eslint-disable-next-line camelcase
parameters.test_mode_compatibility_level =
options.testModeCompatibilityLevel;
parameters.mode = 'test';
}
return parameters;
};
/**
* Sets the version of Smartcar API you are using
* @method
* @param {String} version
*/
smartcar.setApiVersion = function(version) {
config.version = version;
};
/**
* Gets the version of Smartcar API that is set
* @method
* @return {String} version
*/
smartcar.getApiVersion = () => config.version;
/**
* @type {Object}
* @typedef User
* @property {String} id - User Id
* @property {module:smartcar.Vehicle.Meta} meta
*
* @example
* {
* id: "e0514ef4-5226-11e8-8c13-8f6e8f02e27e",
* meta: {
* requestId: 'b9593682-8515-4f36-8190-bb56cde4c38a',
* }
* }
*/
/**
* Return the user's id.
* @async
* @method
* @param {String} accessToken - access token
* @return {module:smartcar~User}
* @throws {SmartcarError} - an instance of SmartcarError.
* See the [errors section](https://github.com/smartcar/node-sdk/tree/master/doc#errors)
* for all possible errors.
*/
smartcar.getUser = async function(accessToken) {
const response = await new SmartcarService({
baseUrl: util.getConfig('SMARTCAR_API_ORIGIN') || config.api,
headers: {Authorization: `Bearer ${accessToken}`},
}).request('get', `v${config.version}/user/`);
return response;
};
/**
* @type {Object}
* @typedef VehicleIds
* @property {String[]} vehicles - A list of the user's authorized vehicle ids.
* @property {Object} paging
* @property {Number} paging.count- The total number of vehicles.
* @property {Number} paging.offset - The current start index of returned
* vehicle ids.
* @property {module:smartcar.Vehicle.Meta} meta
*
* @example
* {
* vehicles: [
* '36ab27d0-fd9d-4455-823a-ce30af709ffc',
* '770bdda4-2429-4b20-87fd-6af475c4365e',
* ],
* paging: {
* count: 2,
* offset: 0,
* },
* meta: {
* requestId: 'b9593682-8515-4f36-8190-bb56cde4c38a',
* }
* }
*/
/**
* Return list of the user's vehicles ids.
* @async
* @method
* @param {String} accessToken - access token
* @param {Object} [paging]
* @param {Number} [paging.limit] - number of vehicles to return
* @param {Number} [paging.offset] - index to start vehicle list
* @return {module:smartcar~VehicleIds}
* @throws {SmartcarError} - an instance of SmartcarError.
* See the [errors section](https://github.com/smartcar/node-sdk/tree/master/doc#errors)
* for all possible errors.
*/
smartcar.getVehicles = async function(accessToken, paging = {}) {
const response = await new SmartcarService({
baseUrl: util.getUrl(),
headers: {Authorization: `Bearer ${accessToken}`},
qs: paging,
}).request('get', '');
return response;
};
/**
* @typedef {Object} VehicleRes
* @property {Vehicle} body - The vehicle response data.
* @property {Object} [headers] - Response headers
*/
/**
* @type {Object}
* @typedef Vehicle
* @property {String} id - Vehicle Id
* @property {String} type - Resource type
* @property {Object} attributes
* @property {String} attributes.make - Vehicle make
* @property {String} attributes.model - Vehicle model
* @property {Number} attributes.year - Vehicle year
* @property {Object} links
* @property {String} links.self - Link to vehicle resource
* @example
* {
* "id": "36ab27d0-fd9d-4455-823a-ce30af709ffc",
* "type": "vehicle",
* "attributes": {
* "make": "TESLA",
* "model": "Model 3",
* "year": 2019
* },
* "links": {
* "self": "/vehicles/36ab27d0-fd9d-4455-823a-ce30af709ffc"
* }
* }
*/
/**
* Return basic info about a vehicle.
* @async
* @method
* @param {String} accessToken - access token
* @param {String} vehicleId - vehicle id
* @return {module:smartcar~VehicleRes}
* @throws {SmartcarError} - an instance of SmartcarError.
* See the [errors section](https://github.com/smartcar/node-sdk/tree/master/doc#errors)
* for all possible errors.
*/
smartcar.getVehicle = async function(accessToken, vehicleId) {
const response = await new SmartcarService({
baseUrl: util.getUrl(vehicleId, '', '3'),
headers: {Authorization: `Bearer ${accessToken}`},
apiVersion: '3',
}).request('get', '');
return {
body: response,
headers: response.meta,
};
};
/**
* @type {Object}
* @typedef Compatibility
* @property {Boolean} compatible
* @property {(VEHICLE_NOT_COMPATIBLE|MAKE_NOT_COMPATIBLE|null)} reason
* @property {Array.<String>} capabilities
* @property {String} capabilities[].permission
* @property {String} capabilities[].endpoint
* @property {Boolean} capabilities[].capable
* @property {(VEHICLE_NOT_COMPATIBLE|MAKE_NOT_COMPATIBLE|null)} capabilities[].reason
* @property {module:smartcar.Vehicle.Meta} meta
*
* @example
* {
* compatible: true,
* reason: null,
* capabilities: [
* {
* capable: false,
* endpoint: '/engine/oil',
* permission: 'read_engine_oil',
* reason: 'SMARTCAR_NOT_CAPABLE',
* },
* {
* capable: true,
* endpoint: '/vin',
* permission: 'read_vin',
* reason: null,
* },
* ],
* meta: {
* 'requestId':'6d4226e7-a7dd-44e0-b29c-9eed26be249d'
* }
* }
*/
/**
* @type {Object}
* @typedef CompatibilityMatrixEntry
* @property {String} model
* @property {Number} startYear
* @property {Number} endYear
* @property {String} type
* @property {Array.<String>} endpoints
* @property {Array.<String>} permissions
*
* @example
* {
* model: "LEAF",
* startYear: 2018,
* endYear: 2022,
* type: "BEV",
* endpoints: [
* "EV battery",
* "EV charging status",
* "Location",
* "Lock & unlock",
* "Odometer"
* ],
* permissions: [
* "read_battery",
* "read_charge",
* "read_location",
* "control_security",
* "read_odometer"
* ]
* }
*/
/**
* @type {Object}
* @typedef CompatibilityMatrix
* @property {Object.<String, CompatibilityMatrixEntry[]>} makes -
* A mapping of make names to arrays of CompatibilityMatrixEntry objects.
*
* @example
* {
* "NISSAN": [
* {
* "model": "LEAF",
* "startYear": 2018,
* "endYear": 2022,
* "type": "BEV",
* "endpoints": [
* "EV battery",
* "EV charging status",
* "Location",
* "Lock & unlock",
* "Odometer"
* ],
* "permissions": [
* "read_battery",
* "read_charge",
* "read_location",
* "control_security",
* "read_odometer"
* ]
* }
* ],
* "TESLA": [
* {
* "model": "3",
* "startYear": 2017,
* "endYear": 2023,
* "type": "BEV",
* "endpoints": [
* "EV battery",
* "EV charging status",
* "EV start & stop charge",
* "Location",
* "Lock & unlock",
* "Odometer",
* "Tire pressure"
* ],
* "permissions": [
* "read_battery",
* "read_charge",
* "control_charge",
* "read_location",
* "control_security",
* "read_odometer",
* "read_tires"
* ]
* }
* ]
* }
*/
/**
* Determine whether a vehicle is compatible with Smartcar.
*
* A compatible vehicle is a vehicle that:
* 1. has the hardware required for internet connectivity,
* 2. belongs to the makes and models Smartcar supports, and
* 3. supports the permissions.
*
* _To use this function, please contact us!_
* @async
* @param {String} vin - the VIN of the vehicle
* @param {String[]} scope - list of permissions to check compatibility for
* @param {String} [country='US'] - an optional country code according to [ISO 3166-1 alpha-2](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2).
* @param {Object} [options]
* @param {Boolean} [options.testMode] - Deprecated, please use `mode` instead.
* Launch Smartcar Connect in [test mode](https://smartcar.com/docs/guides/testing/).
* @param {String} [options.mode] - Determine what mode Smartcar Connect should be
* launched in. Should be one of test, live or simulated.
* @param {String} [options.testModeCompatibilityLevel] - This string determines which permissions
* the simulated vehicle is capable of. Possible Values can be found at this link:
* (https://smartcar.com/docs/integration-guide/test-your-integration/test-requests/#test-successful-api-requests-with-specific-vins)
* @return {module:smartcar~Compatibility}
* @throws {SmartcarError} - an instance of SmartcarError.
* See the [errors section](https://github.com/smartcar/node-sdk/tree/master/doc#errors)
* for all possible errors.
*
* @example
* // Called with country parameter
* const compatibility = await smartcar.getCompatibility(
* '5YJ3E1EA7KF317XXX',
* ['read_odometer', 'read_location'],
* 'US',
* { mode: 'live' },
* );
*
* @example
* // Called without country parameter
* const compatibility = await smartcar.getCompatibility(
* '5YJ3E1EA7KF317XXX',
* ['read_odometer', 'read_location'],
* { mode: 'live' },
* );
*/
smartcar.getCompatibility = async function(vin, scope, countryOrOptions, options = {}) {
let country;
if (typeof countryOrOptions === 'string') {
country = countryOrOptions;
} else if (typeof countryOrOptions === 'object' && countryOrOptions !== null) {
options = countryOrOptions;
}
country = country || 'US';
const qs = {
...buildOptionQueryParams(options),
scope: spaceSeparatedList(scope),
country,
vin,
};
const credentials = buildCredentials(options);
const response = await new SmartcarService({
baseUrl: util.getConfig('SMARTCAR_API_ORIGIN') || config.api,
headers: {
Authorization: `Basic ${credentials}`,
},
qs,
}).request('get', `v${options.version || config.version}/compatibility`);
return response;
};
/**
* Retrieve the Smartcar compatibility matrix for a given region.
* Provides the ability to filter by scope, make, and type.
*
* A compatible vehicle is a vehicle that:
* 1. has the hardware required for internet connectivity,
* 2. belongs to the makes and models Smartcar supports, and
* 3. supports the permissions.
*
* _To use this function, please contact us!_
* @async
* @param {String} region - the region to retrieve the compatibility matrix for
* @param {Object} [options]
* @param {String[]} [options.scope] - list of permissions to filter the matrix by
* @param {String[]} [options.make] - list of makes to filter the matrix by
* @param {String} [options.type] - Engine type to filter the matrix by
* (e.g., "ICE", "HEV", "PHEV", "BEV").
* @param {String} [options.mode] - Determine what mode Smartcar Connect should be
* launched in. Should be one of test, live or simulated.
* @param {String} [options.version] - API version to use for the request
* @return {module:smartcar~CompatibilityMatrix}
* @throws {SmartcarError} - an instance of SmartcarError.
* See the [errors section](https://github.com/smartcar/node-sdk/tree/master/doc#errors)
* for all possible errors.
*/
smartcar.getCompatibilityMatrix = async function(region, options = {}) {
const credentials = buildCredentials(options);
const qs = {
...buildOptionQueryParams(options),
region,
};
['scope', 'make'].forEach((param) => {
if (options[param]) {
qs[param] = spaceSeparatedList(options[param]);
}
});
if (options.type) {
qs.type = options.type;
}
const response = await new SmartcarService({
baseUrl: util.getConfig('SMARTCAR_API_ORIGIN') || config.api,
headers: {
Authorization: `Basic ${credentials}`,
},
qs,
}).request(
'get', `/v${options.version || config.version}/compatibility/matrix`,
);
return response;
};
/**
* Generate hash challenege for webhooks. It does HMAC_SHA256(amt, challenge)
*
* @method
* @param {String} amt - Application Management Token
* @param {String} challenge - Challenge string
* @return {String} String representing the hex digest
*/
smartcar.hashChallenge = function(amt, challenge) {
const hmac = crypto.createHmac('sha256', amt);
return hmac.update(challenge).digest('hex');
};
/**
* Verify webhook payload with AMT and signature.
*
* @method
* @param {String} amt - Application Management Token
* @param {String} signature - sc-signature header value
* @param {object} body - webhook response body
* @return {Boolean} true if signature matches the hex digest of amt and body
*/
smartcar.verifyPayload = (amt, signature, body) =>
smartcar.hashChallenge(amt, JSON.stringify(body)) === signature;
/**
* Returns a paged list of all the vehicles that are connected to the application associated
* with the management API token used sorted in descending order by connection date.
* @async
* @type {Object}
* @typedef Connection
* @property {String} vehicleId
* @property {String} userId
* @property {String} connectedAt
*
* @type {Object}
* @typedef GetConnections
* @property {Connection[]} connections
* @property {Object} [paging]
* @property {string} [paging.cursor]
*
* @param {String} amt - Application Management Token
* @param {object} filter
* @param {String} filter.userId
* @param {String} filter.vehicleId
* @param {object} paging
* @param {number} paging.limit
* @param {String} paging.cursor
* @returns {Promise<GetConnections>}
*/
smartcar.getConnections = async function(amt, filter = {}, paging = {}) {
const {userId, vehicleId} = _.pick(filter, ['userId', 'vehicleId']);
const {limit, cursor} = _.pick(paging, ['limit', 'cursor']);
const credentials = Buffer.from(`default:${amt}`).toString('base64');
const qs = {};
if (userId) {
qs.user_id = userId;
}
if (vehicleId) {
qs.vehicle_id = vehicleId;
}
if (limit) {
qs.limit = limit;
}
if (cursor) {
qs.cursor = cursor;
}
const response = await new SmartcarService({
// eslint-disable-next-line max-len
baseUrl:
`${util.getConfig('SMARTCAR_MANAGEMENT_API_ORIGIN') || config.management}/v${config.version}`,
headers: {
Authorization: `Basic ${credentials}`,
},
qs,
}).request('get', '/management/connections');
return response;
};
/**
* Deletes all the connections by vehicle or user ID and returns a
* list of all connections that were deleted.
* @async
* @type {Object}
* @typedef Connection
* @property {String} vehicleId
* @property {String} userId
*
* @type {Object}
* @typedef DeleteConnections
* @property {Connection[]} connections
*
* @param {String} amt - Application Management Token
* @param {object} filter
* @param {String} filter.userId
* @param {String} filter.vehicleId
* @returns {Promise<DeleteConnections>}
*/
smartcar.deleteConnections = async function(amt, filter) {
const {userId, vehicleId} = _.pick(filter, ['userId', 'vehicleId']);
if (userId && vehicleId) {
// eslint-disable-next-line max-len
throw new Error(
'Filter can contain EITHER user_id OR vehicle_id, not both',
);
}
const qs = {};
if (userId) {
qs.user_id = userId;
}
if (vehicleId) {
qs.vehicle_id = vehicleId;
}
const credentials = Buffer.from(`default:${amt}`).toString('base64');
const response = await new SmartcarService({
baseUrl:
`${util.getConfig('SMARTCAR_MANAGEMENT_API_ORIGIN') || config.management}/v${config.version}`,
headers: {
Authorization: `Basic ${credentials}`,
},
qs,
}).request('delete', '/management/connections');
return response;
};
module.exports = smartcar;