forked from samuelthomas2774/nxapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoral.ts
More file actions
1099 lines (904 loc) · 39.9 KB
/
coral.ts
File metadata and controls
1099 lines (904 loc) · 39.9 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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { randomUUID } from 'node:crypto';
import { fetch, Response } from 'undici';
import createDebug from '../util/debug.js';
import { JwtPayload } from '../util/jwt.js';
import { timeoutSignal } from '../util/misc.js';
import { getAdditionalUserAgents } from '../util/useragent.js';
import type { CoralRemoteConfig } from '../common/remote-config.js';
import { AccountLogin, AccountLogin_4, AccountLoginParameter, AccountToken, AccountToken_4, AccountTokenParameter, Announcements_4, BlockingUsers, CoralError, CoralResponse, CoralStatus, CoralSuccessResponse, CreateFriendRequestChannel, CurrentUser, CurrentUserPermissions, Event, Friend_4, FriendCodeUrl, FriendCodeUser, FriendRouteChannel, Friends_4, GetActiveEventResult, ListChat, ListHashtag, ListHashtagParameter, ListMedia, ListPushNotificationSettings, Media, PlayLogPermissions, PresencePermissions, PushNotificationPlayInvitationScope, ReceivedFriendRequest, ReceivedFriendRequests, SentFriendRequests, ShowUserLogin, UpdatePushNotificationSettingsParameter, UpdatePushNotificationSettingsParameterItem, User, UserPlayLog, WebServices_4, WebServiceToken, WebServiceTokenParameter } from './coral-types.js';
import { createZncaApi, DecryptResponseResult, FResult, HashMethod, RequestEncryptionProvider, ZncaApi, ZncaApiNxapi } from './f.js';
import { generateAuthData, getNintendoAccountToken, getNintendoAccountUser, NintendoAccountScope, NintendoAccountSessionAuthorisation, NintendoAccountToken, NintendoAccountUser } from './na.js';
import { ErrorResponse, ResponseSymbol } from './util.js';
import { ErrorDescription, ErrorDescriptionSymbol, HasErrorDescription } from '../util/errors.js';
const debug = createDebug('nxapi:api:coral');
const ZNCA_PLATFORM = 'Android';
const ZNCA_PLATFORM_VERSION = '12';
export const ZNCA_VERSION = '3.2.0'; // TODO: update to 3.1.0
const ZNCA_USER_AGENT = `com.nintendo.znca/${ZNCA_VERSION}(${ZNCA_PLATFORM}/${ZNCA_PLATFORM_VERSION})`;
export const ZNCA_API_COMPATIBILITY_VERSION = 'hio87-mJks_e9GNF';
const ZNC_URL = 'https://api-lp1.znc.srv.nintendo.net';
export const ZNCA_CLIENT_ID = '71b963c1b7b6d119';
const FRIEND_CODE = /^\d{4}-\d{4}-\d{4}$/;
const FRIEND_CODE_HASH = /^[A-Za-z0-9]{10}$/;
export const ResponseEncryptionSymbol = Symbol('ResponseEncryption');
export const ResponseDataSymbol = Symbol('ResponseData');
export const CorrelationIdSymbol = Symbol('CorrelationId');
export type Result<T> = T & ResultData<T>;
export interface ResultData<T> {
[ResponseSymbol]: Response;
[ResponseEncryptionSymbol]: ResponseEncryption | null;
[ResponseDataSymbol]: CoralSuccessResponse<T>;
[CorrelationIdSymbol]: string;
/** @deprecated */
status: CoralStatus.OK;
/** @deprecated */
result: T;
/** @deprecated */
correlationId: string;
}
export interface ResponseEncryption {
encrypted: Uint8Array;
decrypt_result: DecryptResponseResult;
}
export interface CoralApiInterface {
getAnnouncements(): Promise<Result<Announcements_4>>;
getFriendList(): Promise<Result<Friends_4>>;
addFavouriteFriend(nsa_id: string): Promise<Result<{}>>;
removeFavouriteFriend(nsa_id: string): Promise<Result<{}>>;
deleteFriendIsNew(nsa_id: string): Promise<Result<{}>>;
getWebServices(): Promise<Result<WebServices_4>>;
getChats(): Promise<Result<ListChat>>;
getMedia(): Promise<Result<ListMedia>>;
getActiveEvent(): Promise<Result<GetActiveEventResult>>;
getEvent(id: number): Promise<Result<Event>>;
getUser(id: number): Promise<Result<User>>;
getUserByFriendCode(friend_code: string, hash?: string): Promise<Result<FriendCodeUser>>;
getCurrentUser(): Promise<Result<CurrentUser<true> | CurrentUser<false>>>;
getReceivedFriendRequests(): Promise<Result<ReceivedFriendRequests>>;
getSentFriendRequests(): Promise<Result<SentFriendRequests>>;
getFriendCodeUrl(): Promise<Result<FriendCodeUrl>>;
getCurrentUserPermissions(): Promise<Result<CurrentUserPermissions>>;
updateFriendOnlineNotificationSettings(nsa_id: string, value: boolean): Promise<Result<{}>>;
getWebServiceToken(id: number): Promise<Result<WebServiceToken>>;
}
export abstract class AbstractCoralApi {
abstract call<T extends {}, R extends {} = {}>(
url: string, parameter?: R & Partial<RequestFlags>,
): Promise<Result<T>>;
async getAnnouncements() {
return this.call<Announcements_4>('/v4/Announcement/List', {
[RequestFlagAddPlatformSymbol]: true,
});
}
async getWebServices() {
return this.call<WebServices_4>('/v4/GameWebService/List', {
[RequestFlagNoParameterSymbol]: true,
[RequestFlagRequestIdSymbol]: RequestFlagRequestId.AFTER,
});
}
async getChats() {
return this.call<ListChat>('/v5/Chat/List');
}
async getMedia() {
return this.call<ListMedia>('/v4/Media/List');
}
async getHashtags(media: Media) {
return this.call<ListHashtag, ListHashtagParameter>('/v5/Hashtag/List', {
applications: [
{
platformId: media.platformId,
acdIndex: media.acdIndex,
extraData: media.extraData,
applicationId: media.applicationId,
},
],
});
}
async getActiveEvent() {
return this.call<GetActiveEventResult>('/v1/Event/GetActiveEvent');
}
async getEvent(id: number) {
return this.call<Event, {id: number}>('/v1/Event/Show', {
id,
});
}
async getUser(id: number) {
return this.call<User, {id: number}>('/v3/User/Show', {
id,
});
}
async getFriendList() {
return this.call<Friends_4>('/v4/Friend/List', {
[RequestFlagAddPlatformSymbol]: true,
});
}
async addFavouriteFriend(nsa_id: string) {
return this.call('/v3/Friend/Favorite/Create', {
nsaId: nsa_id,
[RequestFlagAddPlatformSymbol]: true,
});
}
async removeFavouriteFriend(nsa_id: string) {
return this.call('/v3/Friend/Favorite/Delete', {
nsaId: nsa_id,
[RequestFlagAddPlatformSymbol]: true,
});
}
/** @deprecated unused */
async getFriend(nsa_id: string) {
return this.call<Friend_4, {nsaId: string}>('/v4/Friend/Show', {
nsaId: nsa_id,
});
}
async getPlayLog(nsa_id: string) {
return this.call<UserPlayLog, {nsaId: string}>('/v4/User/PlayLog/Show', {
nsaId: nsa_id,
});
}
async deleteFriendIsNew(nsa_id: string) {
return this.call<{}, {friendNsaId: string}>('/v4/Friend/IsNew/Delete', {
friendNsaId: nsa_id,
});
}
async deleteFriend(nsa_id: string) {
return this.call<{}, {nsaId: string}>('/v3/Friend/Delete', {
nsaId: nsa_id,
});
}
async getUserByFriendCode(friend_code: string, hash?: string) {
if (!FRIEND_CODE.test(friend_code)) throw new Error('Invalid friend code');
if (hash && !FRIEND_CODE_HASH.test(hash)) throw new Error('Invalid friend code hash');
return hash ? this.call<FriendCodeUser, {friendCode: string; friendCodeHash: string}>('/v3/Friend/GetUserByFriendCodeHash', {
friendCode: friend_code,
friendCodeHash: hash,
}) : this.call<FriendCodeUser, {friendCode: string}>('/v3/Friend/GetUserByFriendCode', {
friendCode: friend_code,
});
}
async sendFriendRequest(nsa_id: string, channel: CreateFriendRequestChannel = FriendRouteChannel.FRIEND_CODE) {
return this.call('/v4/FriendRequest/Create', {
nsaId: nsa_id,
channel,
});
}
async getReceivedFriendRequests() {
return this.call<ReceivedFriendRequests>('/v4/FriendRequest/Received/List');
}
async getReceivedFriendRequest(friend_request_id: string) {
return this.call<ReceivedFriendRequest, {id: string}>('/v4/FriendRequest/Received/Show', {
id: friend_request_id,
});
}
async setReceivedFriendRequestRead(friend_request_id: string) {
return this.call('/v4/FriendRequest/Received/MarkAsRead', {
id: friend_request_id,
});
}
async acceptFriendRequest(friend_request_id: string) {
return this.call('/v3/FriendRequest/Accept', {
id: friend_request_id,
});
}
async rejectFriendRequest(friend_request_id: string) {
return this.call('/v3/FriendRequest/Reject', {
id: friend_request_id,
});
}
async getSentFriendRequests() {
return this.call<SentFriendRequests>('/v3/FriendRequest/Sent/List');
}
async cancelFriendRequest(friend_request_id: string) {
return this.call('/v3/FriendRequest/Cancel', {
id: friend_request_id,
});
}
async getBlockedUsers() {
return this.call<BlockingUsers>('/v3/User/Block/List');
}
async addBlockedUser(nsa_id: string) {
return this.call('/v3/User/Block/Create', {
nsaId: nsa_id,
});
}
async removeBlockedUser(nsa_id: string) {
return this.call('/v3/User/Block/Delete', {
nsaId: nsa_id,
});
}
/**
* For announcement types:
*
* - OPERATION
*/
async setAnnouncementRead(id: string) {
return this.call('/v4/Announcement/MarkAsRead', {
id,
[RequestFlagAddPlatformSymbol]: true,
});
}
abstract getCurrentUser(): Promise<Result<CurrentUser<true> | CurrentUser<false>>>;
async getFriendCodeUrl() {
return this.call<FriendCodeUrl>('/v3/Friend/CreateFriendCodeUrl', {
[RequestFlagNoParameterSymbol]: true,
});
}
async getCurrentUserPermissions() {
return this.call<CurrentUserPermissions>('/v3/User/Permissions/ShowSelf', {
[RequestFlagNoParameterSymbol]: true,
[RequestFlagRequestIdSymbol]: RequestFlagRequestId.AFTER,
});
}
/** @deprecated Use updateUserPresencePermissions */
updateCurrentUserPermissions(to: PresencePermissions, from: PresencePermissions, etag: string): Promise<Result<{}>> {
return this.updateUserPresencePermissions(to);
}
async updateUserPresencePermissions(value: PresencePermissions) {
return this.call('/v4/User/Permissions/UpdateSelf', {
permissions: {
presence: value,
},
});
}
async updateUserPlayLogPermissions(value: PlayLogPermissions) {
return this.call('/v4/User/Permissions/UpdateSelf', {
permissions: {
playLog: value,
},
});
}
async updateUserFriendRequestPermissions(value: boolean) {
return this.call('/v4/User/Permissions/UpdateSelf', {
permissions: {
friendRequestReception: value,
},
});
}
async getNotificationSetting(item: UpdatePushNotificationSettingsParameterItem) {
return this.call<ListPushNotificationSettings>('/v5/PushNotification/Settings/List');
}
async updateNotificationSetting(item: UpdatePushNotificationSettingsParameterItem) {
return this.call<{}, UpdatePushNotificationSettingsParameter>('/v5/PushNotification/Settings/Update', [
item,
]);
}
async updateFriendRequestNotificationSettings(value: boolean) {
return this.updateNotificationSetting({
type: 'friendRequest',
value,
});
}
async updateChatInvitationNotificationSettings(value: boolean) {
return this.updateNotificationSetting({
type: 'chatInvitation',
value,
});
}
async updatePlayInvitationNotificationSettings(scope: PushNotificationPlayInvitationScope) {
return this.updateNotificationSetting({
type: 'playInvitation',
scope,
});
}
async updateWebServiceNotificationSettings(id: number, value: boolean) {
return this.updateNotificationSetting({
type: 'gws',
gwsId: id,
value,
});
}
async updateFriendOnlineNotificationSettings(nsa_id: string, value: boolean) {
return this.updateNotificationSetting({
type: 'friendOnline',
value,
friendId: nsa_id,
});
}
async getUserLoginFactor() {
return this.call<ShowUserLogin>('/v4/NA/User/LoginFactor/Show');
}
}
export interface ClientInfo {
platform: string;
version: string;
useragent: string;
}
const RemoteConfigSymbol = Symbol('RemoteConfigSymbol');
const ClientInfoSymbol = Symbol('CoralClientInfo');
const CoralUserIdSymbol = Symbol('CoralUserId');
const NintendoAccountIdSymbol = Symbol('NintendoAccountId');
const ZncaApiSymbol = Symbol('ZncaApi');
const ZncaApiPromiseSymbol = Symbol('ZncaApiPromise');
export const RequestFlagAddProductVersionSymbol = Symbol('RequestFlagAddProductVersion');
export const RequestFlagAddPlatformSymbol = Symbol('RequestFlagAddPlatform');
export const RequestFlagNoAuthenticationSymbol = Symbol('RequestFlagNoAuthentication');
export const RequestFlagNoEncryptionSymbol = Symbol('RequestFlagNoEncryption');
export const RequestFlagNoParameterSymbol = Symbol('RequestFlagNoParameter');
export const RequestFlagRequestIdSymbol = Symbol('RequestFlagRequestId');
export const RequestFlagNoAutoRenewTokenSymbol = Symbol('RequestFlagNoAutoRenewToken');
export const RequestFlagNxapiZncaApiRequestNsaAssertionSymbol = Symbol('RequestFlagNxapiZncaApiRequestNsaAssertion');
export interface RequestFlags {
[RequestFlagAddProductVersionSymbol]: boolean;
[RequestFlagAddPlatformSymbol]: boolean;
[RequestFlagNoAuthenticationSymbol]: boolean;
[RequestFlagNoEncryptionSymbol]: boolean;
[RequestFlagNoParameterSymbol]: boolean;
[RequestFlagRequestIdSymbol]: RequestFlagRequestId;
[RequestFlagNoAutoRenewTokenSymbol]: boolean;
[RequestFlagNxapiZncaApiRequestNsaAssertionSymbol]: boolean;
}
export enum RequestFlagRequestId {
NONE,
AFTER,
BEFORE,
}
class EncryptedRequestBody<T = unknown> {
constructor(
readonly request_encryption: RequestEncryptionProvider,
readonly encrypted: Uint8Array,
readonly data: T | null = null,
) {}
}
export default class CoralApi extends AbstractCoralApi implements CoralApiInterface {
[RemoteConfigSymbol]!: CoralRemoteConfig | null;
[ClientInfoSymbol]: ClientInfo;
[CoralUserIdSymbol]: number;
[NintendoAccountIdSymbol]: string;
[ZncaApiSymbol]: ZncaApi | null;
[ZncaApiPromiseSymbol]: Promise<ZncaApi> | null;
request_encryption: RequestEncryptionProvider | null = null;
onTokenExpired: ((data?: CoralError, res?: Response) => Promise<CoralAuthData | void>) | null = null;
/** @internal */
_renewToken: Promise<void> | null = null;
/** @internal */
_token_expired = false;
protected constructor(
public token: string,
public useragent: string | null = getAdditionalUserAgents(),
coral_user_id: number,
na_id: string,
znca_version = ZNCA_VERSION,
znca_useragent = ZNCA_USER_AGENT,
znca_api?: ZncaApi | null,
config?: CoralRemoteConfig,
) {
super();
this[ClientInfoSymbol] = {platform: ZNCA_PLATFORM, version: znca_version, useragent: znca_useragent};
this[CoralUserIdSymbol] = coral_user_id;
this[NintendoAccountIdSymbol] = na_id;
this[ZncaApiSymbol] = znca_api ?? null;
this[ZncaApiPromiseSymbol] = null;
if (znca_api?.supportsEncryption()) {
this.request_encryption = znca_api;
}
Object.defineProperty(this, RemoteConfigSymbol, {enumerable: false, value: config ?? null});
Object.defineProperty(this, 'token', {enumerable: false, value: this.token});
Object.defineProperty(this, '_renewToken', {enumerable: false, value: this._renewToken});
Object.defineProperty(this, '_token_expired', {enumerable: false, value: this._token_expired});
}
/** @internal */
get znca_version() {
return this[ClientInfoSymbol].version;
}
/** @internal */
get znca_useragent() {
return this[ClientInfoSymbol].useragent;
}
initZncaApi() {
if (this[ZncaApiPromiseSymbol]) return this[ZncaApiPromiseSymbol];
return this[ZncaApiPromiseSymbol] = createZncaApi({
...this[ClientInfoSymbol],
useragent: this.useragent ?? getAdditionalUserAgents(),
}).then(provider => {
this[ZncaApiSymbol] = provider;
if (provider.supportsEncryption()) {
this.request_encryption = provider;
}
return provider;
}).finally(() => this[ZncaApiPromiseSymbol] = null);
}
async fetch<T = unknown>(
url: URL | string, method = 'GET', body?: string | Uint8Array | EncryptedRequestBody, _headers?: HeadersInit,
flags: Partial<RequestFlags> = {},
): Promise<Result<T>> {
if (!this[ZncaApiSymbol]) await this.initZncaApi();
return (new CoralApiRequest<T>(this, url, method, body, _headers, flags)).fetch();
}
async call<T extends {}, R extends {}>(
url: string, parameter: R & Partial<RequestFlags> = {} as R,
) {
const body = {} as any;
const ri = parameter[RequestFlagRequestIdSymbol] ?? RequestFlagRequestId.NONE;
if (ri === RequestFlagRequestId.AFTER && !parameter[RequestFlagNoParameterSymbol]) body.parameter = parameter;
if (ri !== RequestFlagRequestId.NONE) {
// Android - lowercase, iOS - uppercase
const uuid = randomUUID();
body.requestId = uuid;
}
if (ri !== RequestFlagRequestId.AFTER && !parameter[RequestFlagNoParameterSymbol]) body.parameter = parameter;
return this.fetch<T>(url, 'POST', JSON.stringify(body), {}, parameter);
}
async getCurrentUser() {
return this.call<CurrentUser<true>, {id: number}>('/v4/User/ShowSelf', {
id: this[CoralUserIdSymbol],
});
}
async getWebServiceToken(id: number, /** @internal */ _attempt = 0): Promise<Result<WebServiceToken>> {
await this._renewToken;
const parameter: WebServiceTokenParameter = {
id,
registrationToken: '',
f: '',
requestId: '',
timestamp: 0,
};
const provider = this[ZncaApiSymbol] ?? await this.initZncaApi();
const fdata = await provider.genf(this.token, HashMethod.WEB_SERVICE, {
na_id: this[NintendoAccountIdSymbol], coral_user_id: '' + this[CoralUserIdSymbol],
}, provider.supportsEncryption() ? {
url: ZNC_URL + '/v4/Game/GetWebServiceToken',
parameter,
} : undefined);
let body;
if (provider.supportsEncryption() && fdata.encrypt_request_result) {
body = new EncryptedRequestBody(provider, fdata.encrypt_request_result);
} else {
parameter.f = fdata.f;
parameter.requestId = fdata.request_id;
parameter.timestamp = fdata.timestamp;
body = JSON.stringify({
parameter,
});
if (provider.supportsEncryption()) {
const result = await provider.encryptRequest(ZNC_URL + '/v4/Game/GetWebServiceToken', null, body);
body = new EncryptedRequestBody(provider, result.data, body);
}
}
try {
return await this.fetch<WebServiceToken>('/v4/Game/GetWebServiceToken', 'POST', body, undefined, {
[RequestFlagAddPlatformSymbol]: true,
[RequestFlagAddProductVersionSymbol]: true,
[RequestFlagNoAutoRenewTokenSymbol]: true,
[RequestFlagNxapiZncaApiRequestNsaAssertionSymbol]: true,
});
} catch (err) {
if (err instanceof CoralErrorResponse && err.status === CoralStatus.TOKEN_EXPIRED && !_attempt && this.onTokenExpired) {
debug('Error getting web service token, renewing token before retrying', err);
// _renewToken will be awaited when calling getWebServiceToken
this._renewToken = this._renewToken ?? this.onTokenExpired.call(null, err.data, err.response as Response).then(data => {
if (data) this.setTokenWithSavedToken(data);
}).finally(() => {
this._renewToken = null;
});
return this.getWebServiceToken(id, _attempt + 1);
} else {
throw err;
}
}
}
async getToken(token: string, user: NintendoAccountUserCoral): Promise<PartialCoralAuthData> {
const nintendoAccountToken = await getNintendoAccountToken(token, ZNCA_CLIENT_ID);
return this.getTokenWithNintendoAccountToken(nintendoAccountToken, user);
}
async getTokenWithNintendoAccountToken(
nintendoAccountToken: NintendoAccountToken, user: NintendoAccountUserCoral,
): Promise<PartialCoralAuthData> {
const parameter: AccountTokenParameter = {
naBirthday: user.birthday,
timestamp: 0,
f: '',
requestId: '',
naIdToken: nintendoAccountToken.id_token,
};
const provider = this[ZncaApiSymbol] ?? await this.initZncaApi();
const fdata = await provider.genf(nintendoAccountToken.id_token, HashMethod.CORAL, {
na_id: user.id, coral_user_id: '' + this[CoralUserIdSymbol],
}, provider.supportsEncryption() ? {
url: ZNC_URL + '/v4/Account/GetToken',
parameter,
} : undefined);
let body;
if (provider.supportsEncryption() && fdata.encrypt_request_result) {
body = new EncryptedRequestBody(provider, fdata.encrypt_request_result);
} else {
parameter.timestamp = fdata.timestamp;
parameter.f = fdata.f;
parameter.requestId = fdata.request_id;
body = JSON.stringify({
parameter,
});
if (provider.supportsEncryption()) {
const result = await provider.encryptRequest(ZNC_URL + '/v4/Account/GetToken', null, body);
body = new EncryptedRequestBody(provider, result.data, body);
}
}
const data = await this.fetch<AccountToken_4>('/v4/Account/GetToken', 'POST', body, undefined, {
[RequestFlagAddPlatformSymbol]: true,
[RequestFlagAddProductVersionSymbol]: true,
[RequestFlagNoAuthenticationSymbol]: true,
[RequestFlagNoAutoRenewTokenSymbol]: true,
});
return {
nintendoAccountToken,
// user,
f: fdata,
nsoAccount: data,
credential: data.webApiServerCredential,
};
}
async renewToken(token: string, user: NintendoAccountUserCoral) {
const data = await this.getToken(token, user);
this.setTokenWithSavedToken(data);
return data;
}
async renewTokenWithNintendoAccountToken(token: NintendoAccountToken, user: NintendoAccountUserCoral) {
const data = await this.getTokenWithNintendoAccountToken(token, user);
this.setTokenWithSavedToken(data);
return data;
}
protected setTokenWithSavedToken(data: CoralAuthData | PartialCoralAuthData) {
this.token = data.credential.accessToken;
this[CoralUserIdSymbol] = data.nsoAccount.user.id;
if ('user' in data) this[NintendoAccountIdSymbol] = data.user.id;
this._token_expired = false;
}
static async createWithSessionToken(token: string, useragent = getAdditionalUserAgents()) {
const data = await this.loginWithSessionToken(token, useragent);
return {nso: this.createWithSavedToken(data, useragent), data};
}
static async createWithNintendoAccountToken(
token: NintendoAccountToken, user: NintendoAccountUserCoral,
useragent = getAdditionalUserAgents()
) {
const data = await this.loginWithNintendoAccountToken(token, user, useragent);
return {nso: this.createWithSavedToken(data, useragent), data};
}
static createWithSavedToken(data: CoralAuthData, useragent = getAdditionalUserAgents()) {
return new this(
data.credential.accessToken,
useragent,
data.nsoAccount.user.id,
data.user.id,
data.znca_version,
data.znca_useragent,
data[ZncaApiSymbol] ?? null,
);
}
static async loginWithSessionToken(token: string, useragent = getAdditionalUserAgents()): Promise<CoralAuthData> {
const { default: { coral: config } } = await import('../common/remote-config.js');
if (!config) throw new Error('Remote configuration prevents Coral authentication');
// Nintendo Account token
const nintendoAccountToken = await getNintendoAccountToken(token, ZNCA_CLIENT_ID);
// Nintendo Account user data
const user = await getNintendoAccountUser<NintendoAccountScope.USER_BIRTHDAY | NintendoAccountScope.USER_SCREENNAME>(nintendoAccountToken);
return this.loginWithNintendoAccountToken(nintendoAccountToken, user, useragent);
}
static async loginWithNintendoAccountToken(
nintendoAccountToken: NintendoAccountToken,
user: NintendoAccountUserCoral,
useragent = getAdditionalUserAgents(),
) {
const { default: { coral: config } } = await import('../common/remote-config.js');
if (!config) throw new Error('Remote configuration prevents Coral authentication');
const znca_useragent = `com.nintendo.znca/${config.znca_version}(${ZNCA_PLATFORM}/${ZNCA_PLATFORM_VERSION})`;
const provider = await createZncaApi({
platform: ZNCA_PLATFORM,
version: config.znca_version,
useragent,
});
const parameter: AccountLoginParameter = {
naIdToken: nintendoAccountToken.id_token,
naBirthday: user.birthday,
naCountry: user.country,
language: user.language,
// These fields will be filled by the f-generation API when encrypting the request data
timestamp: 0,
requestId: '',
f: '',
};
const fdata = await provider.genf(nintendoAccountToken.id_token, HashMethod.CORAL, {
na_id: user.id,
}, provider.supportsEncryption() ? {
url: ZNC_URL + '/v4/Account/Login',
parameter,
} : undefined);
debug('fdata', fdata);
debug('Getting Nintendo Switch Online app token');
let encrypted: [RequestEncryptionProvider] | null = null;
let body;
if (provider.supportsEncryption() && fdata.encrypt_request_result) {
encrypted = [provider];
body = fdata.encrypt_request_result;
} else {
parameter.timestamp = fdata.timestamp;
parameter.requestId = fdata.request_id;
parameter.f = fdata.f;
body = JSON.stringify({
parameter,
});
if (provider.supportsEncryption()) {
const result = await provider.encryptRequest(ZNC_URL + '/v4/Account/Login', null, body);
encrypted = [provider];
body = result.data;
}
}
const headers = new Headers({
'X-Platform': ZNCA_PLATFORM,
'X-ProductVersion': config.znca_version,
'Content-Type': encrypted ? 'application/octet-stream' : 'application/json; charset=utf-8',
'Accept': (encrypted ? 'application/octet-stream,' : '') + 'application/json',
'User-Agent': znca_useragent,
});
const [signal, cancel] = timeoutSignal();
const response = await fetch(ZNC_URL + '/v4/Account/Login', {
method: 'POST',
headers,
body,
signal,
}).finally(cancel);
debug('fetch %s %s, response %s', 'POST', '/v4/Account/Login', response.status);
if (response.status !== 200) {
throw await CoralErrorResponse.fromResponse(response, '[znc] Non-200 status code');
}
const data: CoralResponse<AccountLogin_4> = encrypted ?
JSON.parse((await encrypted[0].decryptResponse(new Uint8Array(await response.arrayBuffer()))).data) :
await response.json() as CoralResponse<AccountLogin_4>;
if ('errorMessage' in data) {
throw new CoralErrorResponse('[znc] ' + data.errorMessage, response, data);
}
if (data.status !== CoralStatus.OK) {
throw new CoralErrorResponse('[znc] Unknown error', response, data);
}
debug('Got Nintendo Switch Online app token', data);
return {
nintendoAccountToken,
user,
f: fdata,
nsoAccount: data.result,
credential: data.result.webApiServerCredential,
znca_version: config.znca_version,
znca_useragent,
[ZncaApiSymbol]: provider,
};
}
}
class CoralApiRequest<T = unknown> {
constructor(
readonly coral: CoralApi,
readonly url: URL | string,
readonly method: string,
readonly body: string | Uint8Array | EncryptedRequestBody | undefined,
readonly headers: HeadersInit | undefined,
readonly flags: Partial<RequestFlags>,
) {}
async fetch(_attempt = 0): Promise<Result<T>> {
if (!this.flags[RequestFlagNoAutoRenewTokenSymbol]) {
if (this.coral._token_expired && !this.coral._renewToken) {
if (!this.coral.onTokenExpired || _attempt) throw new Error('Token expired');
this.coral._renewToken = this.coral.onTokenExpired.call(null).then(data => {
// @ts-expect-error
if (data) this.coral.setTokenWithSavedToken(data);
}).finally(() => {
this.coral._renewToken = null;
});
}
if (this.coral._renewToken) {
await this.coral._renewToken;
}
}
const headers = new Headers(this.headers);
headers.append('Content-Type', 'application/json');
headers.append('Accept-Language', 'en-GB');
if (this.flags[RequestFlagAddProductVersionSymbol]) {
headers.append('X-ProductVersion', this.coral[ClientInfoSymbol].version);
}
headers.append('Accept', 'application/json');
headers.append('User-Agent', this.coral[ClientInfoSymbol].useragent);
if (!this.flags[RequestFlagNoAuthenticationSymbol] && this.coral.token) {
headers.append('Authorization', 'Bearer ' + this.coral.token);
}
if (this.flags[RequestFlagAddPlatformSymbol]) {
headers.append('X-Platform', this.coral[ClientInfoSymbol].platform);
}
headers.append('Pragma', 'no-cache');
headers.append('Cache-Control', 'no-cache');
let body = this.body;
let encrypted: [RequestEncryptionProvider] | null = null;
if (this.coral.request_encryption && typeof this.body === 'string' && !this.flags[RequestFlagNoEncryptionSymbol]) {
const result = await this.coral.request_encryption.encryptRequest(
new URL(this.url, ZNC_URL).href,
!this.flags[RequestFlagNoAuthenticationSymbol] && this.coral.token ? this.coral.token : null,
this.body,
);
headers.set('Content-Type', 'application/octet-stream');
headers.set('Accept', 'application/octet-stream,application/json');
body = result.data;
encrypted = [this.coral.request_encryption];
}
if (body instanceof EncryptedRequestBody) {
const result = body;
headers.set('Content-Type', 'application/octet-stream');
headers.set('Accept', 'application/octet-stream,application/json');
body = result.encrypted;
encrypted = [result.request_encryption];
}
const [signal, cancel] = timeoutSignal();
const response = await fetch(new URL(this.url, ZNC_URL), {
method: this.method,
headers,
body,
signal,
}).finally(cancel);
return this.handleResponse(response, encrypted?.[0], _attempt);
}
async handleResponse(
response: Response, request_encryption: RequestEncryptionProvider | undefined,
/** @internal */ _attempt: number,
) {
const data = new Uint8Array(await response.arrayBuffer());
if (response.headers.get('Content-Type')?.match(/^application\/json($|;)/i)) {
if (request_encryption) {
return this.handleEncryptedJsonResponse(response, data, request_encryption, _attempt);
}
return this.decodeJsonResponse(response, data, null, _attempt);
}
if (!response.ok) {
throw new CoralErrorResponse('[znc] Non-200 status code', response, data);
}
throw new CoralErrorResponse('[znc] Unacceptable response type', response, data);
}
private async handleEncryptedJsonResponse(
response: Response, data: Uint8Array,
request_encryption: RequestEncryptionProvider,
/** @internal */ _attempt: number,
) {
debug('decrypting response', this.url, data.length);
const decrypted = request_encryption instanceof ZncaApiNxapi ?
await request_encryption.decryptResponse(data,
request_encryption.auth?.has_nsa_assertion_scope &&
this.flags[RequestFlagNxapiZncaApiRequestNsaAssertionSymbol]) :
await request_encryption.decryptResponse(data);
const encryption: ResponseEncryption = {
encrypted: data,
decrypt_result: decrypted,
};
return this.decodeJsonResponse(response, decrypted.data, encryption, _attempt);
}
private async decodeJsonResponse(
response: Response, data: string | Uint8Array, encryption: ResponseEncryption | null,
/** @internal */ _attempt: number,
) {
let json: CoralResponse<T>;
try {
const decoded = typeof data === 'string' ? data : (new TextDecoder()).decode(data);
json = JSON.parse(decoded);
} catch (err) {
if (!response.ok) {
throw new CoralErrorResponse('[znc] Non-200 status code', response, data);
}
throw new CoralErrorResponse('Error parsing JSON response', response, data);
}
if (!response.ok) {
throw new CoralErrorResponse('[znc] Non-200 status code', response, json as CoralError);
}
return this.handleJsonResponse(response, json, encryption, _attempt);
}
private async handleJsonResponse(
response: Response, data: CoralResponse<T>, encryption: ResponseEncryption | null,
/** @internal */ _attempt: number,
) {
debug('fetch %s %s, response %s, status %d %s, correlationId %s', this.method, this.url, response.status,
data.status, CoralStatus[data.status], data?.correlationId);
if (data.status === CoralStatus.TOKEN_EXPIRED && !this.flags[RequestFlagNoAutoRenewTokenSymbol] && !_attempt && this.coral.onTokenExpired) {
this.coral._token_expired = true;
// _renewToken will be awaited when calling fetch
this.coral._renewToken = this.coral._renewToken ?? this.coral.onTokenExpired.call(null, data, response).then(data => {
// @ts-expect-error
if (data) this.coral.setTokenWithSavedToken(data);
}).finally(() => {
this.coral._renewToken = null;
});
return this.fetch(_attempt + 1);
}
if ('errorMessage' in data) {
throw new CoralErrorResponse('[znc] ' + data.errorMessage, response, data);
}
if (data.status !== CoralStatus.OK) {
throw new CoralErrorResponse('[znc] Unknown error', response, data);
}
const result = data.result;
Object.defineProperty(result, ResponseSymbol, {enumerable: false, value: response});
Object.defineProperty(result, ResponseEncryptionSymbol, {enumerable: false, value: encryption});
Object.defineProperty(result, ResponseDataSymbol, {enumerable: false, value: data});
Object.defineProperty(result, CorrelationIdSymbol, {enumerable: false, value: data.correlationId});
Object.defineProperty(result, 'status', {enumerable: false, value: CoralStatus.OK});
Object.defineProperty(result, 'result', {enumerable: false, value: data.result});
Object.defineProperty(result, 'correlationId', {enumerable: false, value: data.correlationId});
return result as Result<T>;
}
}