@redzone/taunt-logins 0.0.3 → 0.0.5

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.
@@ -0,0 +1,760 @@
1
+ import { OAuthExtension } from '@magic-ext/oauth2';
2
+ import { Magic } from 'magic-sdk';
3
+ import axios from 'axios';
4
+
5
+ // From RFC 2616
6
+ // 1xx: Informational - Request received, continuing process
7
+ // 2xx: Success - The action was successfully received, understood, and accepted
8
+ // 3xx: Redirection - Further action must be taken in order to complete the request
9
+ // 4xx: Client Error - The request contains bad syntax or cannot be fulfilled
10
+ // 5xx: Server Error - The server failed to fulfill an apparently valid request
11
+ // HTTP status codes are extensible. HTTP applications are not required to understand the meaning of all registered status codes,
12
+ // though such understanding is obviously desirable. However, applications MUST understand the class of any status code,
13
+ // as indicated by the first digit, and treat any unrecognized response as being equivalent to the x00 status code of that class,
14
+ // with the exception that an unrecognized response MUST NOT be cached. For example, if an unrecognized status code of 431 is received
15
+ // by the client, it can safely assume that there was something wrong with its request and treat the response as if it had
16
+ // received a 400 status code.
17
+ // 400 Bad Request - The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
18
+ // 401 Unauthorized - The request requires user authentication. The response MUST include a WWW-Authenticate header field (section 14.47) containing a challenge applicable to the requested resource. The client MAY repeat the request with a suitable Authorization header field (section 14.8). If the request already included Authorization credentials, then the 401 response indicates that authorization has been refused for those credentials. If the401 response contains the same challenge as the prior response, it SHOULD be resent again. HTTP access authentication is explained in "HTTP Authentication: Basic and Digest Access Authentication" (http://www.ietf.org/rfc/rfc2617.txt).
19
+ // 402 Payment Required - Payment required.
20
+ // 403 Forbidden - The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated.
21
+ // 404 Not Found - The server has not found anything matching the Request-URI. No indication is given of whether the condition is temporary or permanent. The 410 (Gone) status code SHOULD be used if the server knows, through some internally configurable mechanism, that an old resource is permanently unavailable and has no forwarding address. This status code is commonly used when the server does not wish to reveal exactly why the request has been refused, or when the server is unwilling to return a 401 Unauthorized response for Authentication reasons.
22
+ // 405 Method Not Allowed - The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.
23
+ // 406 Not Acceptable - The resource identified by the request is only capable of generating response entities which have content characteristics not acceptable according to the accept headers sent in the request.
24
+ // 407 Proxy Authentication Required - The client must first authenticate itself with the proxy.
25
+ // 408 Request Timeout - The server timed out waiting for the request. According to W3 HTTP specifications: "The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time."
26
+ // 409 Conflict - The request could not be completed due to a conflict with the current state of the resource.
27
+ // 410 Gone - The requested resource is no longer available at the server and no forwarding address is known. This condition is expected to be considered permanent. Clients with link editing capabilities SHOULD delete references to the Request-URI after user approval. If the server does not know, or has no facility to determine, whether or not the condition is permanent, the status code 404 (Not Found) SHOULD be used instead. This response is cacheable unless indicated otherwise.
28
+ // 411 Length Required - The server refuses to accept the request without a defined Content-Length. The client MAY repeat the request if it adds a valid Content-Length header field containing the length of the message-body in the request message.
29
+ // 412 Precondition Failed - The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server.
30
+ // 413 Request Entity Too Large - The server is refusing to process a request because the request entity is larger than the server is willing or able to process.
31
+ // 414 Request-URI Too Long - The server is refusing to service the request because the Request-URI is longer than the server is willing to interpret.
32
+ // 415 Unsupported Media Type - The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.
33
+ // 416 Requested Range Not Satisfiable - The server cannot meet the requirements of the Range header field in the request.
34
+ // 417 Expectation Failed - The server could not meet the requirements of the Expect header field in the request.
35
+ // 418 I'm a teapot - This code was defined in 1998 as one of the traditional IETF April Fools' jokes, in RFC 2324, Hyper Text Coffee Pot Control Protocol, and is not expected to be implemented by actual HTTP servers. The RFC specifies this code should be returned by teapots requested to brew coffee.
36
+ // 419 Authentication Timeout - The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.
37
+ // 420 Method Failure - The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource.
38
+ // 421 Misdirected Request - The request was directed at a server that is not able to produce a response. This can be sent by a server that is not configured to produce responses for the combination of scheme and authority that are included in the request URI.
39
+ // 422 Unprocessable Entity - The request was well-formed but was unable to be followed due to semantic errors.
40
+ // 423 Locked - The resource that is being accessed is locked.
41
+ // 424 Failed Dependency - The request failed due to failure of a previous request (e.g., a PROPPATCH).
42
+ // 425 Unordered Collection - The server is unwilling to process the request because either an individual header field, or all the header fields collectively, are too large.
43
+ // 426 Upgrade Required - The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. The server MUST specify an Upgrade header field in a 426 response containing a list of the required upgrade methods.
44
+ // 428 Precondition Required - The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict.
45
+ // 429 Too Many Requests - The user has sent too many requests in a given amount of time. Intended for use with rate-limiting schemes.
46
+ // 432-450 Unassigned
47
+ // 450 Blocked by Windows Parental Controls - Microsoft's Internet Explorer 4.0 does not support the HTTP protocol, and therefore cannot understand the requests for the Windows Parental Controls page.
48
+ // 451 Unavailable For Legal Reasons - The server is denying access to the resource as a consequence of a legal demand.
49
+ // 452-499 Unassigned
50
+ // 500 Internal Server Error - The server encountered an unexpected condition that prevented it from fulfilling the request.
51
+ // 501 Not Implemented - The server does not support the functionality required to fulfill the request. This is the appropriate response when the server does not recognize the request method and is not capable of supporting it for any resource.
52
+ // 502 Bad Gateway - The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.
53
+ // 503 Service Unavailable - The server is currently unable to handle the request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay. If known, the length of the delay MAY be indicated in a Retry-After header. If no Retry-After is given, the client SHOULD handle the response as it would for a 500 response.
54
+ // 504 Gateway Timeout - The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access in attempting to complete the request.
55
+ // 505 HTTP Version Not Supported - The server does not support, or refuses to support, the HTTP protocol version that was used in the request message. The server is indicating that it is unable or unwilling to complete the request using the same major version as the client, as described in section 3.1, other than with this error message. The response SHOULD contain an entity describing why that version is not supported and what other protocols are supported by that server.
56
+ // 506 Variant Also Negotiates - The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.
57
+ // 507 Insufficient Storage - The server is unable to store the representation needed to complete the request.
58
+ // 508 Loop Detected - The server detected an infinite loop while processing the request.
59
+ // 509 Bandwidth Limit Exceeded - This status code, while used by the HTTP transport, is not specified in any RFCs.
60
+ // 510 Not Extended - Further extensions to the request are required for the server to fulfill it.
61
+ // 511 Network Authentication Required - The client needs to authenticate to gain network access.
62
+ class ErrorResponse {
63
+ constructor(message, summary = "", explanation = "", status = 0){
64
+ this.message = message;
65
+ this.summary = summary;
66
+ this.explanation = explanation;
67
+ this.status = status;
68
+ }
69
+ }
70
+ class BadRequestError {
71
+ constructor(message, summary = "Bad Request", explanation = "The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.", status = 400){
72
+ this.message = message;
73
+ this.summary = summary;
74
+ this.explanation = explanation;
75
+ this.status = status;
76
+ }
77
+ }
78
+ class UnauthorizedError {
79
+ constructor(message, summary = "Unauthorized", explanation = "The request requires user authentication.", status = 401){
80
+ this.message = message;
81
+ this.summary = summary;
82
+ this.explanation = explanation;
83
+ this.status = status;
84
+ }
85
+ }
86
+ class PaymentRequiredError {
87
+ constructor(message, summary = "Payment Required", explanation = "Payment required.", status = 402){
88
+ this.message = message;
89
+ this.summary = summary;
90
+ this.explanation = explanation;
91
+ this.status = status;
92
+ }
93
+ }
94
+ class ForbiddenError {
95
+ constructor(message, summary = "Forbidden", explanation = "The server understood the request, but is refusing to fulfill it.", status = 403){
96
+ this.message = message;
97
+ this.summary = summary;
98
+ this.explanation = explanation;
99
+ this.status = status;
100
+ }
101
+ }
102
+ class NotFoundError {
103
+ constructor(message, summary = "Not Found", explanation = "The server has not found anything matching the Request-URI.", status = 404){
104
+ this.message = message;
105
+ this.summary = summary;
106
+ this.explanation = explanation;
107
+ this.status = status;
108
+ }
109
+ }
110
+ class MethodNotAllowedError {
111
+ constructor(message, summary = "Method Not Allowed", explanation = "The method specified in the Request-Line is not allowed for the resource identified by the Request-URI.", status = 405){
112
+ this.message = message;
113
+ this.summary = summary;
114
+ this.explanation = explanation;
115
+ this.status = status;
116
+ }
117
+ }
118
+ class NotAcceptableError {
119
+ constructor(message, summary = "Not Acceptable", explanation = "The server can only generate a response that is not accepted by the client.", status = 406){
120
+ this.message = message;
121
+ this.summary = summary;
122
+ this.explanation = explanation;
123
+ this.status = status;
124
+ }
125
+ }
126
+ class ProxyAuthenticationRequiredError {
127
+ constructor(message, summary = "Proxy Authentication Required", explanation = "The client must first authenticate itself with the proxy.", status = 407){
128
+ this.message = message;
129
+ this.summary = summary;
130
+ this.explanation = explanation;
131
+ this.status = status;
132
+ }
133
+ }
134
+ class RequestTimeoutError {
135
+ constructor(message, summary = "Request Timeout", explanation = "The server did not receive a complete request message within the time that it was prepared to wait.", status = 408){
136
+ this.message = message;
137
+ this.summary = summary;
138
+ this.explanation = explanation;
139
+ this.status = status;
140
+ }
141
+ }
142
+ class ConflictError {
143
+ constructor(message, summary = "Conflict", explanation = "The request could not be completed due to a conflict with the current state of the resource.", status = 409){
144
+ this.message = message;
145
+ this.summary = summary;
146
+ this.explanation = explanation;
147
+ this.status = status;
148
+ }
149
+ }
150
+ class GoneError {
151
+ constructor(message, summary = "Gone", explanation = "The requested resource is no longer available at the server and no forwarding address is known.", status = 410){
152
+ this.message = message;
153
+ this.summary = summary;
154
+ this.explanation = explanation;
155
+ this.status = status;
156
+ }
157
+ }
158
+ class LengthRequiredError {
159
+ constructor(message, summary = "Length Required", explanation = "The server refuses to accept the request without a defined Content-Length.", status = 411){
160
+ this.message = message;
161
+ this.summary = summary;
162
+ this.explanation = explanation;
163
+ this.status = status;
164
+ }
165
+ }
166
+ class PreconditionFailedError {
167
+ constructor(message, summary = "Precondition Failed", explanation = "The precondition given in one or more of the request-header fields evaluated to false when it was tested on the server.", status = 412){
168
+ this.message = message;
169
+ this.summary = summary;
170
+ this.explanation = explanation;
171
+ this.status = status;
172
+ }
173
+ }
174
+ class RequestEntityTooLargeError {
175
+ constructor(message, summary = "Request Entity Too Large", explanation = "The server is refusing to process a request because the request entity is larger than the server is willing or able to process.", status = 413){
176
+ this.message = message;
177
+ this.summary = summary;
178
+ this.explanation = explanation;
179
+ this.status = status;
180
+ }
181
+ }
182
+ class RequestUriTooLongError {
183
+ constructor(message, summary = "Request-URI Too Long", explanation = "The server is refusing to service the request because the request-URI is longer than the server is willing to interpret.", status = 414){
184
+ this.message = message;
185
+ this.summary = summary;
186
+ this.explanation = explanation;
187
+ this.status = status;
188
+ }
189
+ }
190
+ class UnsupportedMediaTypeError {
191
+ constructor(message, summary = "Unsupported Media Type", explanation = "The server is refusing to service the request because the entity of the request is in a format not supported by the requested resource for the requested method.", status = 415){
192
+ this.message = message;
193
+ this.summary = summary;
194
+ this.explanation = explanation;
195
+ this.status = status;
196
+ }
197
+ }
198
+ class RequestedRangeNotSatisfiableError {
199
+ constructor(message, summary = "Requested Range Not Satisfiable", explanation = "The server cannot supply the requested range.", status = 416){
200
+ this.message = message;
201
+ this.summary = summary;
202
+ this.explanation = explanation;
203
+ this.status = status;
204
+ }
205
+ }
206
+ class ExpectationFailedError {
207
+ constructor(message, summary = "Expectation Failed", explanation = "The server cannot meet the requirements of the Expect request-header field.", status = 417){
208
+ this.message = message;
209
+ this.summary = summary;
210
+ this.explanation = explanation;
211
+ this.status = status;
212
+ }
213
+ }
214
+ class ImATeapotError {
215
+ constructor(message, summary = "I'm a teapot", explanation = "The server should return this if it is a teapot.", status = 418){
216
+ this.message = message;
217
+ this.summary = summary;
218
+ this.explanation = explanation;
219
+ this.status = status;
220
+ }
221
+ }
222
+ class UnprocessableEntityError {
223
+ constructor(message, summary = "Unprocessable Entity", explanation = "The request was well-formed but was unable to be followed due to semantic errors.", status = 422){
224
+ this.message = message;
225
+ this.summary = summary;
226
+ this.explanation = explanation;
227
+ this.status = status;
228
+ }
229
+ }
230
+ class LockedError {
231
+ constructor(message, summary = "Locked", explanation = "The resource that is being accessed is locked.", status = 423){
232
+ this.message = message;
233
+ this.summary = summary;
234
+ this.explanation = explanation;
235
+ this.status = status;
236
+ }
237
+ }
238
+ class FailedDependencyError {
239
+ constructor(message, summary = "Failed Dependency", explanation = "The request failed due to failure of a previous request.", status = 424){
240
+ this.message = message;
241
+ this.summary = summary;
242
+ this.explanation = explanation;
243
+ this.status = status;
244
+ }
245
+ }
246
+ class UpgradeRequiredError {
247
+ constructor(message, summary = "Upgrade Required", explanation = "The client should switch to a different protocol.", status = 426){
248
+ this.message = message;
249
+ this.summary = summary;
250
+ this.explanation = explanation;
251
+ this.status = status;
252
+ }
253
+ }
254
+ class PreconditionRequiredError {
255
+ constructor(message, summary = "Precondition Required", explanation = "The origin server requires the request to be conditional.", status = 428){
256
+ this.message = message;
257
+ this.summary = summary;
258
+ this.explanation = explanation;
259
+ this.status = status;
260
+ }
261
+ }
262
+ class TooManyRequestsError {
263
+ constructor(message, summary = "Too Many Requests", explanation = "The user has sent too many requests in a given amount of time.", status = 429){
264
+ this.message = message;
265
+ this.summary = summary;
266
+ this.explanation = explanation;
267
+ this.status = status;
268
+ }
269
+ }
270
+ class RequestHeaderFieldsTooLargeError {
271
+ constructor(message, summary = "Request Header Fields Too Large", explanation = "The server is unwilling to process the request because either an individual header field, or all the header fields collectively, are too large.", status = 431){
272
+ this.message = message;
273
+ this.summary = summary;
274
+ this.explanation = explanation;
275
+ this.status = status;
276
+ }
277
+ }
278
+ class InternalServerError {
279
+ constructor(message, summary = "Internal Server Error", explanation = "The server encountered an unexpected condition which prevented it from fulfilling the request.", status = 500){
280
+ this.message = message;
281
+ this.summary = summary;
282
+ this.explanation = explanation;
283
+ this.status = status;
284
+ }
285
+ }
286
+ class NotImplementedError {
287
+ constructor(message, summary = "Not Implemented", explanation = "The server does not support the functionality required to fulfill the request.", status = 501){
288
+ this.message = message;
289
+ this.summary = summary;
290
+ this.explanation = explanation;
291
+ this.status = status;
292
+ }
293
+ }
294
+ class BadGatewayError {
295
+ constructor(message, summary = "Bad Gateway", explanation = "The server, while acting as a gateway or proxy, received an invalid response from the upstream server it accessed in attempting to fulfill the request.", status = 502){
296
+ this.message = message;
297
+ this.summary = summary;
298
+ this.explanation = explanation;
299
+ this.status = status;
300
+ }
301
+ }
302
+ class ServiceUnavailableError {
303
+ constructor(message, summary = "Service Unavailable", explanation = "The server is currently unable to handle the request due to a temporary overloading or maintenance of the server.", status = 503){
304
+ this.message = message;
305
+ this.summary = summary;
306
+ this.explanation = explanation;
307
+ this.status = status;
308
+ }
309
+ }
310
+ class GatewayTimeoutError {
311
+ constructor(message, summary = "Gateway Timeout", explanation = "The server, while acting as a gateway or proxy, did not receive a timely response from the upstream server specified by the URI (e.g. HTTP, FTP, LDAP) or some other auxiliary server (e.g. DNS) it needed to access in attempting to complete the request.", status = 504){
312
+ this.message = message;
313
+ this.summary = summary;
314
+ this.explanation = explanation;
315
+ this.status = status;
316
+ }
317
+ }
318
+ class HTTPVersionNotSupportedError {
319
+ constructor(message, summary = "HTTP Version Not Supported", explanation = "The server does not support, or refuses to support, the HTTP protocol version that was used in the request message.", status = 505){
320
+ this.message = message;
321
+ this.summary = summary;
322
+ this.explanation = explanation;
323
+ this.status = status;
324
+ }
325
+ }
326
+ class VariantAlsoNegotiatesError {
327
+ constructor(message, summary = "Variant Also Negotiates", explanation = "The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process.", status = 506){
328
+ this.message = message;
329
+ this.summary = summary;
330
+ this.explanation = explanation;
331
+ this.status = status;
332
+ }
333
+ }
334
+ class InsufficientStorageError {
335
+ constructor(message, summary = "Insufficient Storage", explanation = "The server is unable to store the representation needed to complete the request.", status = 507){
336
+ this.message = message;
337
+ this.summary = summary;
338
+ this.explanation = explanation;
339
+ this.status = status;
340
+ }
341
+ }
342
+ class LoopDetectedError {
343
+ constructor(message, summary = "Loop Detected", explanation = "The server detected an infinite loop while processing the request.", status = 508){
344
+ this.message = message;
345
+ this.summary = summary;
346
+ this.explanation = explanation;
347
+ this.status = status;
348
+ }
349
+ }
350
+ class BandwidthLimitExceededError {
351
+ constructor(message, summary = "Bandwidth Limit Exceeded", explanation = "The server has exceeded the bandwidth specified by the server administrator; this is often used by shared hosting providers to limit the bandwidth of customers.", status = 509){
352
+ this.message = message;
353
+ this.summary = summary;
354
+ this.explanation = explanation;
355
+ this.status = status;
356
+ }
357
+ }
358
+ class NotExtendedError {
359
+ constructor(message, summary = "Not Extended", explanation = "Further extensions to the request are required for the server to fulfill it.", status = 510){
360
+ this.message = message;
361
+ this.summary = summary;
362
+ this.explanation = explanation;
363
+ this.status = status;
364
+ }
365
+ }
366
+ class NetworkAuthenticationRequiredError {
367
+ constructor(message, summary = "Network Authentication Required", explanation = "The client needs to authenticate to gain network access.", status = 511){
368
+ this.message = message;
369
+ this.summary = summary;
370
+ this.explanation = explanation;
371
+ this.status = status;
372
+ }
373
+ }
374
+ class UnknownError {
375
+ constructor(message, summary = "Unknown Error", explanation = "", status = 0){
376
+ this.message = message;
377
+ this.summary = summary;
378
+ this.explanation = explanation;
379
+ this.status = status;
380
+ }
381
+ }
382
+ function ErrorFromResponse(response) {
383
+ const message = response.data.message ?? "";
384
+ switch(response.status){
385
+ case 400:
386
+ return new BadRequestError(message);
387
+ case 401:
388
+ return new UnauthorizedError(message);
389
+ case 402:
390
+ return new PaymentRequiredError(message);
391
+ case 403:
392
+ return new ForbiddenError(message);
393
+ case 404:
394
+ return new NotFoundError(message);
395
+ case 405:
396
+ return new MethodNotAllowedError(message);
397
+ case 406:
398
+ return new NotAcceptableError(message);
399
+ case 407:
400
+ return new ProxyAuthenticationRequiredError(message);
401
+ case 408:
402
+ return new RequestTimeoutError(message);
403
+ case 409:
404
+ return new ConflictError(message);
405
+ case 410:
406
+ return new GoneError(message);
407
+ case 411:
408
+ return new LengthRequiredError(message);
409
+ case 412:
410
+ return new PreconditionFailedError(message);
411
+ case 413:
412
+ return new RequestEntityTooLargeError(message);
413
+ case 414:
414
+ return new RequestUriTooLongError(message);
415
+ case 415:
416
+ return new UnsupportedMediaTypeError(message);
417
+ case 417:
418
+ return new ExpectationFailedError(message);
419
+ case 418:
420
+ return new ImATeapotError(message);
421
+ case 422:
422
+ return new UnprocessableEntityError(message);
423
+ case 423:
424
+ return new LockedError(message);
425
+ case 424:
426
+ return new FailedDependencyError(message);
427
+ case 426:
428
+ return new UpgradeRequiredError(message);
429
+ case 428:
430
+ return new PreconditionRequiredError(message);
431
+ case 429:
432
+ return new TooManyRequestsError(message);
433
+ case 431:
434
+ return new RequestHeaderFieldsTooLargeError(message);
435
+ case 500:
436
+ return new InternalServerError(message);
437
+ case 501:
438
+ return new NotImplementedError(message);
439
+ case 502:
440
+ return new BadGatewayError(message);
441
+ case 503:
442
+ return new ServiceUnavailableError(message);
443
+ case 504:
444
+ return new GatewayTimeoutError(message);
445
+ case 505:
446
+ return new HTTPVersionNotSupportedError(message);
447
+ case 506:
448
+ return new VariantAlsoNegotiatesError(message);
449
+ case 507:
450
+ return new InsufficientStorageError(message);
451
+ case 508:
452
+ return new LoopDetectedError(message);
453
+ case 509:
454
+ return new BandwidthLimitExceededError(message);
455
+ case 510:
456
+ return new NotExtendedError(message);
457
+ case 511:
458
+ return new NetworkAuthenticationRequiredError(message);
459
+ default:
460
+ return new UnknownError(message, "Unknown Error", "An unknown error has occurred.");
461
+ }
462
+ }
463
+
464
+ class TauntApi {
465
+ async stdPGET(method, url, body, headers = {}) {
466
+ const response = await this.api.request({
467
+ url,
468
+ method,
469
+ headers: {
470
+ "Content-Type": "application/json",
471
+ Accept: "application/json",
472
+ ...headers
473
+ },
474
+ data: body ? JSON.stringify(body) : null
475
+ });
476
+ const data = response.data;
477
+ if (data.refreshToken) {
478
+ this.refreshToken = data.refreshToken;
479
+ }
480
+ return data;
481
+ }
482
+ async post(url, body = {}, headers = {}) {
483
+ return this.stdPGET("POST", url, body, headers);
484
+ }
485
+ async get(url, headers = {}) {
486
+ return this.stdPGET("GET", url, undefined, headers);
487
+ }
488
+ // this.user = data
489
+ // localStorage.setItem("user", JSON.stringify(data))
490
+ // localStorage.setItem(
491
+ // "name",
492
+ // this.user.email ? this.user.email.split("@")[0] : this.user.ethAddress
493
+ // )
494
+ // await this.getCToken()
495
+ // this.setRefId(this.router.currentRoute.value.query['ref_id'])
496
+ // const nftStore = useNftStore()
497
+ // nftStore.fetchAll()
498
+ // return data as TauntUser
499
+ // }
500
+ // async loginPlayFabPlayer() {}
501
+ /*async loginPlayFabPlayer() {
502
+ try {
503
+ // Get the user's playfab id from taunt api
504
+ let id = null;
505
+ if (!this.user && !this.user?.id) {
506
+ id = this.getPlayfabAnonId()
507
+ if (!id) {
508
+ const { data: playFabResponse } = await this.api.get('/v1/auth/playfab', {})
509
+ id = playFabResponse.playFabId
510
+ this.setAnonPlayfabUserId(playFabResponse.playFabId);
511
+ }
512
+ } else {
513
+ const { data: playFabResponse } = await this.api.get('/v1/auth/playfab', {})
514
+ id = playFabResponse.playFabId
515
+ }
516
+ // Login with playfab via the unique id from taunt api
517
+ const { data: playFabLoginResults } = await Axios.post(loginEndpoint, {
518
+ CustomId: id,
519
+ CreateAccount: true,
520
+ titleId: playFabTitleId,
521
+ })
522
+ const playFabSession = JSON.stringify(playFabLoginResults.data)
523
+ this.setPlayFabSession(playFabSession)
524
+ }
525
+ catch (error) {
526
+ const err = error as AxiosError
527
+ if (err?.response) {
528
+ console.log(err.response.status, err.response.data)
529
+ }
530
+ else {
531
+ console.log(error)
532
+ }
533
+ }
534
+ }*/ // async getCToken() {
535
+ // try {
536
+ // const url = "v1/claimr/token"
537
+ // const { data } = await this.api.get<{ data: { token: string } }>(`${url}`)
538
+ // this.claimrToken = data.data.token
539
+ // this.setClaimrToken(this.claimrToken)
540
+ // } catch (e) {
541
+ // console.error(e)
542
+ // }
543
+ // }
544
+ // setLastWalletConnection(lastWalletConnection: string) {
545
+ // localStorage.setItem("lastWalletConnection", lastWalletConnection)
546
+ // }
547
+ // setRefId(ref = "") {
548
+ // this.refId = ref
549
+ // }
550
+ // clearLocalAuthStorage() {
551
+ // localStorage.removeItem("user")
552
+ // localStorage.removeItem("refreshToken")
553
+ // localStorage.removeItem("playFabSession")
554
+ // this.user = null
555
+ // }
556
+ // setAccessToken(accessToken: string) {
557
+ // localStorage.setItem("accessToken", accessToken)
558
+ // }
559
+ // setRefreshToken(refreshToken: string) {
560
+ // localStorage.setItem("refreshToken", refreshToken)
561
+ // }
562
+ // setIsFirsTimeLogin(isFirstTimeLogin: string) {
563
+ // localStorage.setItem("isFirstTimeLogin", isFirstTimeLogin)
564
+ // }
565
+ // setPlayFabSession(playFabSession: string) {
566
+ // localStorage.setItem("playFabSession", playFabSession)
567
+ // }
568
+ // setAnonPlayfabUserId(id: string) {
569
+ // localStorage.setItem("playfabAnonId", id)
570
+ // }
571
+ // setClaimrToken(token: string) {
572
+ // localStorage.setItem("ctoken", token)
573
+ // }
574
+ // getAccessToken() {
575
+ // return localStorage.getItem("accessToken")
576
+ // }
577
+ // getRefreshToken() {
578
+ // return localStorage.getItem("refreshToken")
579
+ // }
580
+ // getPlayfabAnonId() {
581
+ // return localStorage.getItem("playfabAnonId")
582
+ // }
583
+ // Write a playfab event. retryfIfLoginNeeded should not be set by caller. It's used for stopping recursive calls when login is needed.
584
+ // If login is needed, for example, if the web browser has been open longer than playfab session timeout, we'll try to login again at most
585
+ // one time. Then we'll retry the event.
586
+ async writePlayerEvent(eventName, eventData = null, retryIfLoginNeeded = true) {
587
+ console.log("writePlayerEvent", {
588
+ eventName,
589
+ eventData,
590
+ retryIfLoginNeeded
591
+ });
592
+ return Promise.resolve();
593
+ }
594
+ constructor(endpoint){
595
+ this.refreshToken = null;
596
+ this.claimrToken = null;
597
+ this.onError = async (error)=>{
598
+ const originalRequest = error.config;
599
+ if (error.response.status === 401 && !originalRequest._retry) {
600
+ originalRequest._retry = true;
601
+ console.log("401 - refreshing token");
602
+ try {
603
+ const data = await this.refresh();
604
+ return this.api(originalRequest);
605
+ } catch (error) {
606
+ console.log("Unable to refresh access token, please log in");
607
+ this.refreshToken = null;
608
+ window.location.href = "/";
609
+ return Promise.reject(error);
610
+ }
611
+ }
612
+ return Promise.reject(ErrorFromResponse(error.response));
613
+ };
614
+ this.nonceLogin = (walletAddress, clientNonce)=>this.post("/v1/auth/nonce/login", {
615
+ walletAddress,
616
+ clientNonce
617
+ });
618
+ this.loginWithMagicDid = (did)=>this.post("/v1/auth/login/did", {
619
+ did
620
+ });
621
+ this.loginWithWeb3WalletSignature = (props)=>this.post("/v1/auth/login/signature", props);
622
+ this.loginExtWithWeb3WalletSignature = (props)=>this.post("/v1/auth/login/ext-signature", props);
623
+ this.refresh = (refreshToken)=>this.post(`/v1/auth/token/refresh`, {
624
+ token: refreshToken || this.refreshToken
625
+ });
626
+ // Logout of the backend with access token. Assumes user is currently logged in and has a cookie with the access token
627
+ this.logout = async ()=>{
628
+ // If logging out fails on the backend we'll still remove the user info
629
+ await this.api.post("/v1/auth/logout");
630
+ await this.writePlayerEvent("player_logged_out");
631
+ };
632
+ this.getClaimrToken = async ()=>{
633
+ if (!this.claimrToken) {
634
+ const url = "v1/claimr/token";
635
+ const { data } = await this.api.get(`${url}`);
636
+ this.claimrToken = data.data.token;
637
+ }
638
+ return this.claimrToken;
639
+ };
640
+ // Use the cookie stored in the browser to get the user and save user model in state and local storage
641
+ // This assumes that the user is logged to backend in and has a cookie jwt
642
+ this.getLoggedInUser = ()=>this.api.get("/v1/auth/me");
643
+ this.api = axios.create({
644
+ baseURL: `${endpoint}`,
645
+ withCredentials: true
646
+ });
647
+ // Response interceptor for API calls
648
+ this.api.interceptors.response.use((response)=>response, (error)=>this.onError(error));
649
+ }
650
+ }
651
+
652
+ const customNodeOptions = {
653
+ rpcUrl: "https://polygon-rpc.com",
654
+ chainId: 137
655
+ };
656
+ const getMagic = (magicKey)=>new Magic(magicKey, {
657
+ network: customNodeOptions,
658
+ extensions: [
659
+ new OAuthExtension()
660
+ ]
661
+ });
662
+ function emailOTPWithMagic(magicKey, email) {
663
+ const magic = getMagic(magicKey);
664
+ return magic.auth.loginWithEmailOTP({
665
+ email
666
+ });
667
+ }
668
+ function telegramWithMagic(magicKey) {
669
+ const magic = getMagic(magicKey);
670
+ return magic.oauth2.loginWithPopup({
671
+ provider: "telegram"
672
+ });
673
+ }
674
+ async function tauntMagicTelegramLogin(tauntServiceEndpoint, magicKey, tauntApi) {
675
+ const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
676
+ try {
677
+ let result = await telegramWithMagic(magicKey);
678
+ const errResult = result;
679
+ if (errResult.error) {
680
+ throw new Error(`No ID token returned ${errResult.error}`);
681
+ }
682
+ result = result;
683
+ console.log("Magic telegram login", {
684
+ result
685
+ });
686
+ return taunt.loginWithMagicDid(result.magic.idToken);
687
+ } catch (err) {
688
+ console.error("Magic login error:", err);
689
+ throw err;
690
+ }
691
+ }
692
+ async function tauntMagicEmailOTPLogin(tauntServiceEndpoint, magicKey, email, tauntApi) {
693
+ const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
694
+ try {
695
+ const did = await emailOTPWithMagic(magicKey, email);
696
+ if (!did) throw new Error("No DID returned");
697
+ console.log("Magic email OTP login", {
698
+ did
699
+ });
700
+ return taunt.loginWithMagicDid(did);
701
+ } catch (err) {
702
+ console.error("Magic login error:", err);
703
+ throw err;
704
+ }
705
+ }
706
+ async function tauntMagicDidLogin(tauntServiceEndpoint, did, tauntApi) {
707
+ const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
708
+ return taunt.loginWithMagicDid(did);
709
+ }
710
+
711
+ async function tauntSignWithMetamask(tauntServiceEndpoint, provider, tauntApi) {
712
+ provider = provider || window.ethereum;
713
+ if (!provider) throw new Error("MetaMask provider not found");
714
+ const accounts = await provider.request({
715
+ method: "eth_requestAccounts"
716
+ });
717
+ if (!accounts.length) throw new Error("No accounts returned");
718
+ console.log("MetaMask", {
719
+ accounts
720
+ });
721
+ const walletAddress = accounts[0];
722
+ const cryptoValuesArray = new Uint32Array(3);
723
+ const clientNonce = crypto.getRandomValues(cryptoValuesArray).toString();
724
+ const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
725
+ const serverNonce = await taunt.nonceLogin(walletAddress, clientNonce);
726
+ const payload = JSON.stringify({
727
+ clientNonce,
728
+ serverNonce
729
+ });
730
+ const message = `Sign this message with your wallet to connect to Taunt Battleworld ::: ${payload}`;
731
+ let signature;
732
+ try {
733
+ signature = await provider.request({
734
+ method: "personal_sign",
735
+ params: [
736
+ message,
737
+ walletAddress
738
+ ]
739
+ });
740
+ } catch (err) {
741
+ throw new Error("User denied message signature");
742
+ }
743
+ if (!signature) throw new Error("No signature returned");
744
+ return {
745
+ walletAddress,
746
+ message,
747
+ signature
748
+ };
749
+ }
750
+ async function tauntMetamaskLogin(tauntServiceEndpoint, providerParam, tauntApi) {
751
+ const taunt = tauntApi || new TauntApi(tauntServiceEndpoint);
752
+ const { walletAddress, message, signature } = await tauntSignWithMetamask(tauntServiceEndpoint, providerParam, tauntApi);
753
+ return taunt.loginWithWeb3WalletSignature({
754
+ walletAddress,
755
+ message,
756
+ signature
757
+ });
758
+ }
759
+
760
+ export { BadGatewayError, BadRequestError, BandwidthLimitExceededError, ConflictError, ErrorFromResponse, ErrorResponse, ExpectationFailedError, FailedDependencyError, ForbiddenError, GatewayTimeoutError, GoneError, HTTPVersionNotSupportedError, ImATeapotError, InsufficientStorageError, InternalServerError, LengthRequiredError, LockedError, LoopDetectedError, MethodNotAllowedError, NetworkAuthenticationRequiredError, NotAcceptableError, NotExtendedError, NotFoundError, NotImplementedError, PaymentRequiredError, PreconditionFailedError, PreconditionRequiredError, ProxyAuthenticationRequiredError, RequestEntityTooLargeError, RequestHeaderFieldsTooLargeError, RequestTimeoutError, RequestUriTooLongError, RequestedRangeNotSatisfiableError, ServiceUnavailableError, TauntApi, TooManyRequestsError, UnauthorizedError, UnknownError, UnprocessableEntityError, UnsupportedMediaTypeError, UpgradeRequiredError, VariantAlsoNegotiatesError, emailOTPWithMagic, tauntMagicDidLogin, tauntMagicEmailOTPLogin, tauntMagicTelegramLogin, tauntMetamaskLogin, tauntSignWithMetamask, telegramWithMagic };