forked from samuelthomas2774/nxapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcoral.ts
385 lines (317 loc) · 12.9 KB
/
coral.ts
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
import fetch, { Response } from 'node-fetch';
import { v4 as uuidgen } from 'uuid';
import createDebug from 'debug';
import { f, FResult, HashMethod } from './f.js';
import { AccountLogin, AccountToken, Announcements, CurrentUser, CurrentUserPermissions, Event, Friends, GetActiveEventResult, PresencePermissions, User, WebServices, WebServiceToken, CoralErrorResponse, CoralResponse, CoralStatus, CoralSuccessResponse, FriendCodeUser, FriendCodeUrl, AccountTokenParameter, AccountLoginParameter } from './coral-types.js';
import { getNintendoAccountToken, getNintendoAccountUser, NintendoAccountToken, NintendoAccountUser } from './na.js';
import { ErrorResponse, ResponseSymbol } from './util.js';
import { JwtPayload } from '../util/jwt.js';
import { getAdditionalUserAgents } from '../util/useragent.js';
import { timeoutSignal } from '../util/misc.js';
const debug = createDebug('nxapi:api:coral');
const ZNCA_PLATFORM = 'Android';
const ZNCA_PLATFORM_VERSION = '8.0.0';
const ZNCA_VERSION = '2.2.0';
const ZNCA_USER_AGENT = `com.nintendo.znca/${ZNCA_VERSION}(${ZNCA_PLATFORM}/${ZNCA_PLATFORM_VERSION})`;
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 ResponseDataSymbol = Symbol('ResponseData');
export const CorrelationIdSymbol = Symbol('CorrelationId');
export type Result<T> = T & ResultData<T>;
export interface ResultData<T> {
[ResponseSymbol]: Response;
[ResponseDataSymbol]: CoralSuccessResponse<T>;
[CorrelationIdSymbol]: string;
/** @deprecated */
status: CoralStatus.OK;
/** @deprecated */
result: T;
/** @deprecated */
correlationId: string;
}
export default class CoralApi {
onTokenExpired: ((data: CoralErrorResponse, res: Response) => Promise<void>) | null = null;
/** @internal */
_renewToken: Promise<void> | null = null;
protected constructor(
public token: string,
public useragent: string | null = getAdditionalUserAgents(),
readonly znca_version = ZNCA_VERSION,
readonly znca_useragent = ZNCA_USER_AGENT,
) {}
async fetch<T = unknown>(
url: string, method = 'GET', body?: string, headers?: object,
/** @internal */ _autoRenewToken = true,
/** @internal */ _attempt = 0
): Promise<Result<T>> {
if (this._renewToken && _autoRenewToken) {
await this._renewToken;
}
const [signal, cancel] = timeoutSignal();
const response = await fetch(ZNC_URL + url, {
method,
headers: Object.assign({
'X-Platform': ZNCA_PLATFORM,
'X-ProductVersion': this.znca_version,
'Authorization': 'Bearer ' + this.token,
'Content-Type': 'application/json; charset=utf-8',
'User-Agent': this.znca_useragent,
}, headers),
body,
signal,
}).finally(cancel);
debug('fetch %s %s, response %s', method, url, response.status);
if (response.status !== 200) {
throw new ErrorResponse('[znc] Non-200 status code', response, await response.text());
}
const data = await response.json() as CoralResponse<T>;
if (data.status === CoralStatus.TOKEN_EXPIRED && _autoRenewToken && !_attempt && this.onTokenExpired) {
// _renewToken will be awaited when calling fetch
this._renewToken = this._renewToken ?? this.onTokenExpired.call(null, data, response).finally(() => {
this._renewToken = null;
});
return this.fetch(url, method, body, headers, _autoRenewToken, _attempt + 1);
}
if ('errorMessage' in data) {
throw new ErrorResponse('[znc] ' + data.errorMessage, response, data);
}
if (data.status !== CoralStatus.OK) {
throw new ErrorResponse('[znc] Unknown error', response, data);
}
const result = data.result;
Object.defineProperty(result, ResponseSymbol, {enumerable: false, value: response});
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>;
}
async call<T = unknown>(
url: string, parameter = {},
/** @internal */ _autoRenewToken = true
) {
const uuid = uuidgen();
return this.fetch<T>(url, 'POST', JSON.stringify({
parameter,
requestId: uuid,
}), {}, _autoRenewToken);
}
async getAnnouncements() {
return this.call<Announcements>('/v1/Announcement/List');
}
async getFriendList() {
return this.call<Friends>('/v3/Friend/List');
}
async addFavouriteFriend(nsaid: string) {
return this.call<{}>('/v3/Friend/Favorite/Create', {
nsaId: nsaid,
});
}
async removeFavouriteFriend(nsaid: string) {
return this.call<{}>('/v3/Friend/Favorite/Delete', {
nsaId: nsaid,
});
}
async getWebServices() {
return this.call<WebServices>('/v1/Game/ListWebServices');
}
async getActiveEvent() {
return this.call<GetActiveEventResult>('/v1/Event/GetActiveEvent');
}
async getEvent(id: number) {
return this.call<Event>('/v1/Event/Show', {
id,
});
}
async getUser(id: number) {
return this.call<User>('/v3/User/Show', {
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>('/v3/Friend/GetUserByFriendCodeHash', {
friendCode: friend_code,
friendCodeHash: hash,
}) : this.call<FriendCodeUser>('/v3/Friend/GetUserByFriendCode', {
friendCode: friend_code,
});
}
async sendFriendRequest(nsa_id: string) {
return this.call<{}>('/v3/FriendRequest/Create', {
nsaId: nsa_id,
});
}
async getCurrentUser() {
return this.call<CurrentUser>('/v3/User/ShowSelf');
}
async getFriendCodeUrl() {
return this.call<FriendCodeUrl>('/v3/Friend/CreateFriendCodeUrl');
}
async getCurrentUserPermissions() {
return this.call<CurrentUserPermissions>('/v3/User/Permissions/ShowSelf');
}
async updateCurrentUserPermissions(to: PresencePermissions, from: PresencePermissions, etag: string) {
return this.call<{}>('/v3/User/Permissions/UpdateSelf', {
permissions: {
presence: {
toValue: to,
fromValue: from,
},
},
etag,
});
}
async getWebServiceToken(id: number) {
const data = await f(this.token, HashMethod.WEB_SERVICE, this.useragent ?? getAdditionalUserAgents());
const req = {
id,
registrationToken: '',
f: data.f,
requestId: data.request_id,
timestamp: data.timestamp,
};
return this.call<WebServiceToken>('/v2/Game/GetWebServiceToken', req);
}
async getToken(token: string, user: NintendoAccountUser): Promise<PartialCoralAuthData> {
// Nintendo Account token
const nintendoAccountToken = await getNintendoAccountToken(token, ZNCA_CLIENT_ID);
const fdata = await f(nintendoAccountToken.id_token, HashMethod.CORAL,
this.useragent ?? getAdditionalUserAgents());
const req: AccountTokenParameter = {
naBirthday: user.birthday,
timestamp: fdata.timestamp,
f: fdata.f,
requestId: fdata.request_id,
naIdToken: nintendoAccountToken.id_token,
};
const data = await this.call<AccountToken>('/v3/Account/GetToken', req, false);
return {
nintendoAccountToken,
// user,
f: fdata,
nsoAccount: data,
credential: data.webApiServerCredential,
};
}
async renewToken(token: string, user: NintendoAccountUser) {
const data = await this.getToken(token, user);
this.token = data.credential.accessToken;
return data;
}
static async createWithSessionToken(token: string, useragent = getAdditionalUserAgents()) {
const data = await this.loginWithSessionToken(token, useragent);
return {nso: this.createWithSavedToken(data, useragent), data};
}
static createWithSavedToken(data: CoralAuthData, useragent = getAdditionalUserAgents()) {
return new this(
data.credential.accessToken,
useragent,
data.znca_version,
data.znca_useragent,
);
}
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');
const znca_useragent = `com.nintendo.znca/${config.znca_version}(${ZNCA_PLATFORM}/${ZNCA_PLATFORM_VERSION})`;
// Nintendo Account token
const nintendoAccountToken = await getNintendoAccountToken(token, ZNCA_CLIENT_ID);
// Nintendo Account user data
const user = await getNintendoAccountUser(nintendoAccountToken);
const fdata = await f(nintendoAccountToken.id_token, HashMethod.CORAL, useragent);
debug('Getting Nintendo Switch Online app token');
const parameter: AccountLoginParameter = {
naIdToken: nintendoAccountToken.id_token,
naBirthday: user.birthday,
naCountry: user.country,
language: user.language,
timestamp: fdata.timestamp,
requestId: fdata.request_id,
f: fdata.f,
};
const [signal, cancel] = timeoutSignal();
const response = await fetch(ZNC_URL + '/v3/Account/Login', {
method: 'POST',
headers: {
'X-Platform': ZNCA_PLATFORM,
'X-ProductVersion': config.znca_version,
'Content-Type': 'application/json; charset=utf-8',
'User-Agent': znca_useragent,
},
body: JSON.stringify({
parameter,
}),
signal,
}).finally(cancel);
debug('fetch %s %s, response %s', 'POST', '/v3/Account/Login', response.status);
if (response.status !== 200) {
throw new ErrorResponse('[znc] Non-200 status code', response, await response.text());
}
const data = await response.json() as CoralResponse<AccountLogin>;
if ('errorMessage' in data) {
throw new ErrorResponse('[znc] ' + data.errorMessage, response, data);
}
if (data.status !== 0) {
throw new ErrorResponse('[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,
};
}
}
export interface CoralAuthData {
nintendoAccountToken: NintendoAccountToken;
user: NintendoAccountUser;
f: FResult;
nsoAccount: AccountLogin;
credential: AccountLogin['webApiServerCredential'];
znca_version: string;
znca_useragent: string;
}
export type PartialCoralAuthData =
Pick<CoralAuthData, 'nintendoAccountToken' | 'f' | 'nsoAccount' | 'credential'>;
export interface CoralJwtPayload extends JwtPayload {
isChildRestricted: boolean;
membership: {
active: boolean;
};
aud: string;
exp: number;
iat: number;
iss: 'api-lp1.znc.srv.nintendo.net';
/** Coral user ID (CurrentUser.id, not CurrentUser.nsaId) */
sub: number;
typ: 'id_token';
}
export interface CoralWebServiceJwtPayload extends JwtPayload {
isChildRestricted: boolean;
aud: string;
exp: number;
iat: number;
iss: 'api-lp1.znc.srv.nintendo.net';
jti: string;
/** Coral user ID (CurrentUser.id, not CurrentUser.nsaId) */
sub: number;
links: {
networkServiceAccount: {
/** NSA ID (CurrentUser.nsaId) */
id: string;
};
};
typ: 'id_token';
membership: {
active: boolean;
};
}