-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth.js
224 lines (197 loc) · 8.72 KB
/
auth.js
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
// Helper library to authenticate to Tesla Owner API. Includes support for MFA.
const axios = require('axios');
const sha256 = require("js-sha256");
const URLSafeBase64 = require('urlsafe-base64');
const TESLA_CLIENT_ID = "81527cff06843c8634fdc09e8ac0abefb46ac849f38fe1e431c2ef2106796384";
const TESLA_CLIENT_SECRET = "c7257eb71a564034f9419ee651c7d0e5f7aa6bfbd18bafb5c5c033b093bb2fa3";
const DEBUG = false;
const DEBUG_ERRORS = false;
let loginInfo = {
CodeVerifier: "",
CodeChallenge: "",
State: "",
};
// Calls the callback with 'TRUE' if login state is valid, otherwise FALSE.
function CheckAuthStateAsync(tokenData, callback) {
if(tokenData === null || !tokenData.hasOwnProperty('AccessToken')) {
// We cannot possibly be logged in if there is no tokenData present.
callback(false);
return;
}
let testURL = "https://owner-api.teslamotors.com/api/1/products";
let reqHeaders = {
"Authorization": "Bearer " + tokenData.AccessToken,
"Content-Type": "application/json; charset=utf-8"
};
DebugLog("CheckAuthStateAsync\n"+ testURL);
axios.get(testURL, { 'headers': reqHeaders }).then(function(webResponse) {
DebugLog("Auth check. Sent GET request... \nHTTP Response Code: "+ webResponse.status);
callback(true);
}).catch(function (e) {
console.log(e);
DebugError("Auth check. FAILED. HTTP Status code: "+e.status);
callback(false);
});
}
// Constructor and HttpClient initialisation
function Init() {
loginInfo.CodeVerifier = RandomString(86);
loginInfo.State = RandomString(20);
}
function DebugError(msg) {
if(DEBUG_ERRORS) {
console.log(msg);
}
}
function DebugLog(msg) {
if(DEBUG) {
console.log(msg);
}
}
function GetStandardHeaders() {
let x = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'User-Agent': 'TeslaAuthJS/1.0',
}
};
return x;
}
// Public API for browser-assisted auth
function GetLoginUrlForBrowser() {
Init();
loginInfo.CodeChallenge = ComputeSHA256Hash(loginInfo.CodeVerifier);
let url = new URL(GetBaseAddressForRegion("USA") + "/oauth2/v3/authorize");
url.searchParams.append('client_id', 'ownerapi');
url.searchParams.append('code_challenge', loginInfo.CodeChallenge);
url.searchParams.append('code_challenge_method', 'S256');
url.searchParams.append('redirect_uri', 'https://auth.tesla.com/void/callback');
url.searchParams.append('response_type', 'code');
url.searchParams.append('scope', 'openid email offline_access');
url.searchParams.append('state', loginInfo.State);
return url.toString();
}
//public async Task<Tokens> GetTokenAfterLoginAsync(string redirectUrl, CancellationToken cancellationToken = default) {
function GetTokenAfterLoginAsync(redirectUrl, callback) {
// URL is something like https://auth.tesla.com/void/callback?code=b6a6a44dea889eb08cd8afe5adc16353662cc5d82ba0c6044c95b13d6f…"
let code = new URL(redirectUrl).searchParams.get('code');
ExchangeCodeForBearerTokenAsync(code, function (results) {
DebugLog("AFTER ExchangeCodeForBearerTokenAsync -- our results are:");
DebugLog(results);
callback({
AccessToken: results.access_token,
RefreshToken: results.refresh_token,
TokenType: results.token_type,
ExpiresIn: results.expires_in,
CreatedAt: new Date().getTime()
});
// As of March 21 2022, the above already returns a bearer token. No need to call ExchangeAccessTokenForBearerToken anymore [for now]
});
}
function RefreshTokenAsync(refreshToken, callback) {
let url = GetBaseAddressForRegion("USA") + "/oauth2/v3/token";
let body = {
grant_type: "refresh_token",
client_id: "ownerapi",
refresh_token: refreshToken,
scope: "openid email offline_access",
};
axios.post(url, JSON.stringify(body), GetStandardHeaders()).then(webResponse => {
DebugLog("sent POST request " + url + "\ngot response:\n");
DebugLog(webResponse.data);
let returnVal = {
// AccessToken: webResponse.data['access_token'],
// RefreshToken: webResponse.data['refresh_token'],
// ExpiresIn: webResponse.data['expires_in']
AccessToken: webResponse.data["access_token"],
RefreshToken: webResponse.data["refresh_token"],
CreatedAt: new Date().getTime(),
ExpiresIn: webResponse.data["expires_in"]
};
DebugLog(returnVal);
callback(returnVal);
// As of March 21 2022, this returns what we need -- no need to call ExchangeAccessTokenForBearerToken ... for now.
}).catch(function (e) {
DebugError("error submitting request...! 0000 \n");
DebugError(e);
callback(false);
});
}
function ExchangeCodeForBearerTokenAsync(code, callback) {
let body = {
"grant_type": "authorization_code",
"client_id": "ownerapi",
"code": code,
"code_verifier": loginInfo.CodeVerifier,
"redirect_uri": "https://auth.tesla.com/void/callback"
};
let url = GetBaseAddressForRegion("USA") + "/oauth2/v3/token";
axios.post(url, JSON.stringify(body), GetStandardHeaders()).then(webResponse => {
DebugLog("sent POST request " + url + "\ngot response:");
DebugLog(webResponse.data);
callback(webResponse.data);
}).catch(function (e) {
DebugError("error submitting request...! "+url+"\n 1111\n" + e.toString() + "\n"+JSON.stringify(body));
});
}
// NO LONGER USED/NEEDED AS OF MARCH 21 2022
function ExchangeAccessTokenForBearerTokenAsync(accessToken, callback) {
let body = {
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"client_id": TESLA_CLIENT_ID,
"client_secret": TESLA_CLIENT_SECRET,
};
let url = "https://owner-api.teslamotors.com/oauth/token";
let headers = GetStandardHeaders();
headers['headers']['Authorization'] = 'Bearer ' + accessToken;
axios.post(url, JSON.stringify(body), headers).then(webResponse => {
// var createdAt = ; //DateTimeOffset.FromUnixTimeSeconds(response["created_at"]!.Value<long>());
// var expiresIn = ; //TimeSpan.FromSeconds(response["expires_in"]!.Value<long>());
// var bearerToken = ; //!.Value<string>();
// var refreshToken = ; //!.Value<string>();
let resultData = {
AccessToken: webResponse.data["access_token"],
RefreshToken: webResponse.data["refresh_token"],
CreatedAt: webResponse.data["created_at"],
ExpiresIn: webResponse.data["expires_in"]
};
DebugLog("result data...");
DebugLog(resultData);
callback(resultData);
}).catch(function (err) {
DebugError("error submitting request...! 2222\n" + err.toString());
});
}
/// <summary>
/// Should your Owner API token begin with "cn-" you should POST to auth.tesla.cn Tesla SSO service to have it refresh. Owner API tokens
/// starting with "qts-" are to be refreshed using auth.tesla.com
/// </summary>
/// <param name="region">Which Tesla server is this account created with?</param>
/// <returns>Address like "https://auth.tesla.com", no trailing slash</returns>
function GetBaseAddressForRegion(region) {
switch (region) {
case "China":
return "https://auth.tesla.cn";
default:
return "https://auth.tesla.com";
}
}
function RandomString(length) {
const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
let result = '';
for (let i = length; i > 0; --i) {
result += chars[Math.floor(Math.random() * chars.length)];
}
return result;
}
function ComputeSHA256Hash(text) {
return URLSafeBase64.encode(sha256(text));
}
let auth = {
GetLoginUrlForBrowser,
GetTokenAfterLoginAsync,
RefreshTokenAsync,
CheckAuthStateAsync
};
module.exports = { auth };