-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathAuthorize.cs
403 lines (314 loc) · 12.9 KB
/
Authorize.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using core.audiamus.aux;
using core.audiamus.aux.ex;
using core.audiamus.connect.ex;
using static core.audiamus.aux.Logging;
namespace core.audiamus.connect {
class Authorize {
const string HTTP_AUTHORITY = @"https://api.amazon.";
const string HTTP_PATH_REGISTER = @"/auth/register";
const string HTTP_PATH_DEREGISTER = @"/auth/deregister";
const string HTTP_PATH_TOKEN = @"/auth/token";
const string IOS_VERSION = "15.0.0";
const string APP_VERSION = "3.56.2";
const string SOFTWARE_VERSION = "35602678";
const string APP_NAME = "Audible";
private IAuthorizeSettings Settings { get; }
private Uri BaseUri => HttpClientAmazon?.BaseAddress;
private Configuration Configuration { get; set; }
private ConfigTokenDelegate GetTokenFunc { get; }
public HttpClientEx HttpClientAmazon { get; private set; }
public Authorize (ConfigTokenDelegate getTokenFunc, IAuthorizeSettings settings) {
Log (3, this);
GetTokenFunc = getTokenFunc;
Settings = settings;
}
internal IProfile GetProfile (IProfileKey key) => Configuration?.Get (key);
public async Task<(bool, IProfile)> RegisterAsync (Profile profile) {
using var _ = new LogGuard (3, this);
ensureHttpClient (profile);
try {
var request = buildRegisterRequest (profile);
await request.LogAsync (4, this, HttpClientAmazon.DefaultRequestHeaders, HttpClientAmazon.CookieContainer, BaseUri);
var response = await HttpClientAmazon.SendAsync (request);
await response.LogAsync (4, this, HttpClientAmazon.CookieContainer, BaseUri);
response.EnsureSuccessStatusCode ();
string content = await response.Content.ReadAsStringAsync ();
return await addProfileToConfig (profile, content);
} catch (Exception exc) {
Log (1, this, () => exc.Summary ());
return (false, null);
}
}
// internal instead of private for testing only
internal async Task<(bool, IProfile)> addProfileToConfig (Profile profile, string content) {
bool succ = updateProfile (profile, content);
if (!succ)
return (false, null);
await readConfigurationAsync ();
IProfile prevProfile = Configuration.AddOrReplace (profile);
await WriteConfigurationAsync ();
return (true, prevProfile);
}
public async Task<bool> DeregisterAsync (IProfile profile) {
ensureHttpClient (profile);
try {
await refreshTokenAsync (profile);
var request = buildDeregisterRequest (profile);
await request.LogAsync (4, this, HttpClientAmazon.DefaultRequestHeaders, HttpClientAmazon.CookieContainer, BaseUri);
var response = await HttpClientAmazon.SendAsync (request);
await response.LogAsync (4, this, HttpClientAmazon.CookieContainer, BaseUri);
response.EnsureSuccessStatusCode ();
string content = await response.Content.ReadAsStringAsync ();
return true;
} catch (Exception exc) {
Log (1, this, () => exc.Summary ());
return false;
}
}
public async Task<EAuthorizeResult> RemoveProfileAsync (IProfileKey key) {
Log (3, this, () => key.ToString());
IProfile profile = Configuration.Remove (key);
if (profile is null)
return EAuthorizeResult.removeProfileFailed;
await WriteConfigurationAsync ();
// TODO modify/test
//bool succ = await DeregisterAsync (profile);
//EAuthorizeResult result = succ ? EAuthorizeResult.succ : EAuthorizeResult.deregistrationFailed;
//return result;
return EAuthorizeResult.succ;
}
internal async Task WriteConfigurationAsync () {
Log (3, this);
if (Configuration is null)
return;
string token = GetTokenFunc?.Invoke ();
await Configuration.WriteAsync (token);
}
private void ensureHttpClient (IProfile profile) {
string domain = Locale.FromCountryCode (profile.Region).Domain;
Uri baseUri = new Uri (HTTP_AUTHORITY + domain);
if (HttpClientAmazon is not null) {
if (BaseUri == baseUri)
return;
else
HttpClientAmazon.Dispose ();
}
HttpClientAmazon = HttpClientEx.Create (baseUri);
}
public async Task RefreshTokenAsync (IProfile profile) =>
await RefreshTokenAsync (profile, false);
internal async Task RefreshTokenAsync (IProfile profile, bool late) {
using var _ = new LogGuard (3, this, () => $"auto={Settings?.AutoRefresh}, late={late}");
ensureHttpClient (profile);
await readConfigurationAsync ();
if ((Settings?.AutoRefresh ?? true) != late) {
if (profile is Profile prof1 && (Configuration.Profiles?.Contains (prof1) ?? false))
await refreshTokenAsync (prof1);
else {
Profile prof2 = Configuration.Profiles?.FirstOrDefault (d => d.Matches (profile));
if (prof2 is not null)
await refreshTokenAsync (prof2);
}
await WriteConfigurationAsync ();
}
}
private async Task refreshTokenAsync (IProfile profile) {
if (profile is null)
return;
using var _ = new LogGuard (3, this);
try {
if (DateTime.UtcNow < profile.Token.Expiration - TimeSpan.FromMinutes (5))
return;
Log (3, this, () => "from server");
HttpRequestMessage request = buildRefreshRequest (profile);
await request.LogAsync (4, this, HttpClientAmazon.DefaultRequestHeaders, HttpClientAmazon.CookieContainer, BaseUri);
var response = await HttpClientAmazon.SendAsync (request);
await response.LogAsync (4, this, HttpClientAmazon.CookieContainer, BaseUri);
response.EnsureSuccessStatusCode ();
string content = await response.Content.ReadAsStringAsync ();
refreshToken (profile, content);
} catch (Exception exc) {
Log (1, this, () => exc.Summary ());
}
}
private HttpRequestMessage buildRefreshRequest (IProfile profile) {
var content = new Dictionary<string, string> {
["app_name"] = APP_NAME,
["app_version"] = APP_VERSION,
["source_token"] = profile.Token.RefreshToken,
["requested_token_type"] = "access_token",
["source_token_type"] = "refresh_token"
};
Uri uri = new Uri (HTTP_PATH_TOKEN, UriKind.Relative);
var request = new HttpRequestMessage {
Method = HttpMethod.Post,
RequestUri = uri,
Content = new FormUrlEncodedContent (content)
};
request.Headers.Add ("x-amzn-identity-auth-domain", BaseUri.Host);
request.Headers.Add ("Accept", "application/json");
return request;
}
private void refreshToken (IProfile profile, string json) {
try {
var jsonDoc = JsonDocument.Parse (json);
var elRoot = jsonDoc.RootElement;
string accessToken = elRoot.GetProperty ("access_token").GetString ();
int expires = elRoot.GetProperty ("expires_in").GetInt32();
DateTime expiration = DateTime.UtcNow.AddSeconds (expires);
var bearer = new TokenBearer (
elRoot.GetProperty ("access_token").GetString (),
DateTime.UtcNow.AddSeconds (expires)
);
profile.Refresh (bearer);
} catch (Exception exc) {
Log (1, this, () => exc.Summary ());
}
}
public async Task<IEnumerable<IProfile>> GetRegisteredProfilesAsync () {
if (Configuration is null)
await readConfigurationAsync ();
return Configuration.GetSorted ();
}
private async Task readConfigurationAsync () {
using var _ = new LogGuard (3, this);
if (Configuration is not null)
return;
Configuration = new Configuration ();
await readConfigAsync (false);
if (Configuration.IsEncrypted)
await readConfigAsync (true);
async Task readConfigAsync (bool enforce) {
string token = GetTokenFunc?.Invoke (enforce);
await Configuration.ReadAsync (token);
}
}
private HttpRequestMessage buildRegisterRequest (IProfile profile) {
ILocale locale = profile.Region.FromCountryCode ();
Uri uri = new Uri (HTTP_PATH_REGISTER, UriKind.Relative);
string jsonBody = buildRegisterBody (profile, locale);
HttpContent content = new StringContent (jsonBody, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage {
Method = HttpMethod.Post,
RequestUri = uri,
Content = content
};
request.Headers.Accept.Add (new MediaTypeWithQualityHeaderValue ("application/json"));
return request;
}
private HttpRequestMessage buildDeregisterRequest (IProfile profile) {
Uri uri = new Uri (HTTP_PATH_DEREGISTER, UriKind.Relative);
var content = new Dictionary<string, string> {
["deregister_all_existing_accounts"] = "false",
};
var request = new HttpRequestMessage {
Method = HttpMethod.Post,
RequestUri = uri,
Content = new FormUrlEncodedContent (content)
};
request.Headers.Add ("Authorization", $"Bearer {profile.Token.AccessToken}");
request.Headers.Add ("Accept", "application/json");
return request;
}
private string buildRegisterBody (IProfile profile, ILocale locale) {
string json = $@"{{
""requested_token_type"":
[""bearer"", ""mac_dms"", ""website_cookies"",
""store_authentication_cookie""],
""cookies"": {{
""website_cookies"": [],
""domain"": "".amazon.{locale.Domain}""
}},
""registration_data"": {{
""domain"": ""Device"",
""app_version"": ""{APP_VERSION}"",
""device_serial"": ""{profile.DeviceInfo.Serial}"",
""device_type"": ""{AudibleLogin.DEVICE_TYPE}"",
""device_name"":
""%FIRST_NAME%%FIRST_NAME_POSSESSIVE_STRING%%DUPE_STRATEGY_1ST%Audible for iPhone"",
""os_version"": ""{IOS_VERSION}"",
""software_version"": ""{SOFTWARE_VERSION}"",
""device_model"": ""iPhone"",
""app_name"": ""{APP_NAME}""
}},
""auth_data"": {{
""client_id"": ""{AudibleLogin.buildClientId(profile.DeviceInfo.Serial)}"",
""authorization_code"": ""{profile.Authorization.AuthorizationCode}"",
""code_verifier"": ""{profile.Authorization.CodeVerifier}"",
""code_algorithm"": ""SHA-256"",
""client_domain"": ""DeviceLegacy""
}},
""requested_extensions"": [""device_info"", ""customer_info""]
}}";
if (Logging.Level >= 4) {
string file = json.WriteTempTextFile ();
Log (4, this, () => $"buildRegisterBody: {file}");
}
json = json.CompactJson ();
if (!json.ValidateJson ())
throw new InvalidOperationException ("invalid json");
return json;
}
// internal instead of private for testing only
internal bool updateProfile (Profile profile, string json) {
try {
var root = adb.json.RegistrationResponse.Deserialize (json);
var response = root.response;
var success = response.success;
var extensions = success.extensions;
var device_info = extensions.device_info;
var deviceInfo = new DeviceInfo {
Name = device_info.device_name,
Type = device_info.device_type,
Serial = device_info.device_serial_number
};
var customer_info = extensions.customer_info;
var customerInfo = new CustomerInfo {
Name = customer_info.name,
AccountId = customer_info.user_id
};
var tokens = success.tokens;
var website_cookies = tokens.website_cookies;
var cookies = new List<KeyValuePair<string, string>> ();
foreach (var cookie in website_cookies) {
cookies.Add (new KeyValuePair<string, string> (
cookie.Name,
cookie.Value.Replace ("\"", "")
));
}
var store_authentication_cookie = tokens.store_authentication_cookie;
string storeAuthentCookie = store_authentication_cookie.cookie;
var mac_dms = tokens.mac_dms;
string devicePrivateKey = mac_dms.device_private_key;
string adpToken = mac_dms.adp_token;
var bearer = tokens.bearer;
int.TryParse (bearer.expires_in, out var expires);
var tokenBearer = new TokenBearer (
bearer.access_token,
bearer.refresh_token,
DateTime.UtcNow.AddSeconds (expires)
);
profile.Update (
tokenBearer,
cookies,
deviceInfo,
customerInfo,
devicePrivateKey,
adpToken,
storeAuthentCookie);
} catch (Exception exc) {
Log (1, this, () => exc.Summary ());
return false;
}
return true;
}
}
}