-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.ts
339 lines (304 loc) · 8.9 KB
/
client.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
import { authenticator } from "otplib";
authenticator.options = { step: 30 };
import {
cookieFromArray,
promiseLock,
reduceCookiesObject,
type PromiseLock
} from "./utils";
import { type CurrentUserTotp, Routes } from "./api";
import { RefreshError, RequestError } from "./errors";
import type { Verify2FAResult, VerifyAuthTokenResult } from "vrchat";
import type { Awaitable, StorageAdapterAccount } from "./adapter";
export interface ClientOptions {
maxSessionRefreshAttempts: number;
sessionRefreshInterval: number;
maxRequestRetryAttempts: number;
requestRetryInterval: number;
baseUrl: string;
userAgent?: string;
onSessionRefreshed?: (client: Client) => Awaitable<void>;
onRequestOtpKey?: (
client: Client,
type: CurrentUserTotp["requiresTwoFactorAuth"]
) => Awaitable<string | undefined>;
debugRequest?: (
client: Client,
req: { url: string; init?: RequestInit },
res: Response
) => Awaitable<void>;
}
export type ClientRequestMethod = "GET" | "POST" | "PUT" | "DELETE";
export type ClientRequestInitHeaders = RequestInit["headers"];
export interface ClientRequestInit {
body?: object;
headers?: ClientRequestInitHeaders;
}
export class Client {
public options: ClientOptions;
private refreshLock: PromiseLock | undefined;
public constructor(
public auth: StorageAdapterAccount,
options?: Partial<ClientOptions>
) {
this.options = {
baseUrl: "https://api.vrchat.cloud/api/1",
maxRequestRetryAttempts: 5,
maxSessionRefreshAttempts: 3,
requestRetryInterval: 100,
sessionRefreshInterval: 500,
...options
};
}
// Raw request doesn't go through session management and request retries.
public async requestRaw(url: string, init?: RequestInit): Promise<Response> {
try {
const response = await fetch(this.options.baseUrl + url, {
...init,
headers: {
...(init?.headers || {}),
"User-Agent":
this.options.userAgent ||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0"
}
});
if (this.options.debugRequest) {
await this.options.debugRequest(
this,
{
init,
url
},
response
);
}
if (!response.ok) throw new RequestError(response);
return response;
} catch (reason) {
throw reason instanceof RequestError
? reason
: new RequestError(undefined, String(reason));
}
}
// Request goes through session management and request retries.
public async request(
url: string,
method: ClientRequestMethod = "GET",
init?: ClientRequestInit
): Promise<Response> {
if (
!this.auth.sessionToken ||
(this.auth.sessionTokenExpiresAt &&
this.auth.sessionTokenExpiresAt < new Date())
) {
await this.refreshSession();
}
let attempts = 0;
let response: Response | undefined;
do {
try {
return await this.requestRaw(url, {
body: init?.body ? JSON.stringify(init.body) : undefined,
headers: {
...(init?.headers || {}),
"Content-Type": "application/json",
Cookie: reduceCookiesObject({
auth: this.auth.sessionToken,
twoFactorAuth: this.auth.totpSessionToken
})
},
method
});
} catch (reason) {
if (attempts >= this.options.maxRequestRetryAttempts) break;
if (reason instanceof RequestError) response = reason.response;
if (reason instanceof RequestError && reason.hintsRefreshSession()) {
await this.refreshSession();
// We don't want to retry on these status codes. They indicate user error not server error.
} else if (reason instanceof RequestError && reason.hintsNoRetry()) {
break;
}
attempts++;
await new Promise((resolve) =>
setTimeout(resolve, this.options.requestRetryInterval)
);
}
} while (attempts <= this.options.maxRequestRetryAttempts);
throw new RequestError(response, `after ${attempts} attempts`);
}
// Shortcut methods for common HTTP methods. Will call `request` internally.
public async get<T>(
url: string,
headers?: ClientRequestInitHeaders
): Promise<T> {
return this.request(url, "GET", { headers }).then((response) =>
response.json()
);
}
public async post<T>(
url: string,
body?: object,
headers?: ClientRequestInitHeaders
): Promise<T> {
return this.request(url, "POST", { body, headers }).then((response) =>
response.json()
);
}
public async put<T>(
url: string,
body?: object,
headers?: ClientRequestInitHeaders
): Promise<T> {
return this.request(url, "PUT", { body, headers }).then((response) =>
response.json()
);
}
public async delete<T>(
url: string,
headers?: ClientRequestInitHeaders
): Promise<T> {
return this.request(url, "DELETE", { headers }).then((response) =>
response.json()
);
}
public async forceSessionRefresh(): Promise<void> {
return this.refreshSession();
}
// Abstract away all the session management from the end user.
private async refreshSession() {
if (this.refreshLock) return await this.refreshLock.promise;
this.refreshLock = promiseLock();
const resolve = () => {
const promise = this.refreshLock?.promise;
this.refreshLock?.resolve();
this.refreshLock = undefined;
return promise;
};
const reject = (error: Error) => {
const promise = this.refreshLock?.promise;
this.refreshLock?.reject(error);
this.refreshLock = undefined;
return promise;
};
let attempts = 0;
// Attempt a logout first with rawRequest so it doesnt go through session management.
// Or retry if it fails.
if (this.auth.sessionToken) {
try {
await this.requestRaw(Routes.logout(), {
headers: {
"Content-Type": "application/json",
Cookie: reduceCookiesObject({
auth: this.auth.sessionToken,
twoFactorAuth: this.auth.totpSessionToken
})
},
method: "PUT"
});
} catch {
// noop
}
}
do {
try {
await this.attemptSessionRefresh();
await this.options.onSessionRefreshed?.(this);
return resolve();
} catch (reason) {
if (attempts >= this.options.maxSessionRefreshAttempts) {
if (reason instanceof RefreshError) return reject(reason);
return reject(
new RefreshError(
`Failed to refresh session after ${attempts} attempts.`,
reason instanceof Error ? reason : new Error(String(reason))
)
);
}
attempts++;
await new Promise((resolve) =>
setTimeout(resolve, this.options.sessionRefreshInterval)
);
}
} while (attempts <= this.options.maxSessionRefreshAttempts);
}
private async attemptSessionRefresh() {
const loginResponse = await this.requestRaw(Routes.login(), {
headers: {
Authorization:
"Basic " +
Buffer.from(
`${encodeURIComponent(this.auth.email)}:${encodeURIComponent(this.auth.password)}`
).toString("base64"),
"Content-Type": "application/json"
}
});
const sessionCookie = cookieFromArray(
loginResponse.headers.getSetCookie(),
"auth"
);
if (!sessionCookie)
throw new RefreshError("Failed to get session cookie after login.");
this.auth.sessionToken = sessionCookie.value;
this.auth.sessionTokenExpiresAt = sessionCookie.expires;
const body = (await loginResponse.json()) as CurrentUserTotp;
if (body.requiresTwoFactorAuth?.length) {
await this.handleTwoFactorAuth(body);
} else if (!body.id) {
throw new RefreshError("Failed to get current user after login.");
}
}
private async handleTwoFactorAuth(body: CurrentUserTotp) {
let code: string | undefined;
if (this.auth.totpKey) {
code = authenticator.generate(this.auth.totpKey);
} else if (this.options.onRequestOtpKey) {
code = await this.options.onRequestOtpKey(
this,
body.requiresTwoFactorAuth
);
if (!code) {
throw new RefreshError(
"Called options.onRequestOtpKey, but returned undefined."
);
}
} else {
throw new RefreshError(
"One time password required but auth.totpKey is undefined and options.onRequestOtpKey is not set."
);
}
const verifyResponse = await this.requestRaw(Routes.verify2FACode(), {
body: JSON.stringify({ code }),
headers: {
"Content-Type": "application/json",
Cookie: reduceCookiesObject({ auth: this.auth.sessionToken })
},
method: "POST"
});
const totpBody = (await verifyResponse.json()) as Verify2FAResult;
if (!totpBody.verified)
throw new RefreshError("TOTP key failed to verify.");
const totpAuthCookie = cookieFromArray(
verifyResponse.headers.getSetCookie(),
"twoFactorAuth"
);
if (totpAuthCookie) {
this.auth.totpSessionToken = totpAuthCookie.value;
this.auth.totpSessionTokenExpiresAt = totpAuthCookie.expires;
}
const verifyAuthTokenResponse = await this.requestRaw(
Routes.verifyAuthToken(),
{
headers: {
Cookie: reduceCookiesObject({
auth: this.auth.sessionToken,
twoFactorAuth: this.auth.totpSessionToken
})
}
}
);
const verifyAuthTokenBody =
(await verifyAuthTokenResponse.json()) as VerifyAuthTokenResult;
if (!verifyAuthTokenBody.ok)
throw new RefreshError("Auth token result verification is not ok.");
}
}