-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.ts
541 lines (472 loc) · 15.1 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
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
import { mapChainAndNetwork, urlEncoded } from './utils';
import { MONERIUM_CONFIG } from './config';
import type {
AuthArgs,
AuthorizationCodeCredentials,
AuthCodeRequest,
AuthContext,
Balances,
BearerProfile,
BearerTokenCredentials,
ClassOptions,
ClientCredentialsRequest,
ENV,
Environment,
LinkAddress,
MoneriumEvent,
MoneriumEventListener,
NewOrder,
AuthFlowOptions,
Order,
OrderFilter,
OrderNotification,
OrderState,
PKCERequestArgs,
Profile,
RefreshTokenRequest,
SupportingDoc,
Token,
ClientCredentials,
} from './types';
import { STORAGE_CODE_VERIFIER, STORAGE_REFRESH_TOKEN } from './constants';
import {
cleanQueryString,
getAuthFlowUrlAndStoreCodeVerifier,
isAuthCode,
isClientCredentials,
isRefreshToken,
rest,
} from './helpers';
// import pjson from "../package.json";
const isServer = typeof window === 'undefined';
export class MoneriumClient {
#env: Environment;
#authorizationHeader?: string;
/**
* @deprecated, use localStorage, will be removed in v3
* The PKCE code verifier
* */
codeVerifier?: string;
/** The bearer profile will be available after authentication, it includes the access_token and refresh_token */
bearerProfile?: BearerProfile;
/** The socket will be available after subscribing to an event */
#socket?: WebSocket;
/** The subscriptions map will be available after subscribing to an event */
#subscriptions: Map<OrderState, MoneriumEventListener> = new Map();
// TODO: need this?
isAuthorized = !!this.bearerProfile;
#client?: BearerTokenCredentials;
state: string | undefined;
/** Constructor for no arguments, defaults to sandbox */
constructor();
/** Constructor with only env as an argument*/
constructor(env: ENV);
/** Constructor with {@link ClassOptions} */
constructor(options: ClassOptions);
constructor(envOrOptions?: ENV | ClassOptions) {
// No arguments, default to sandbox
if (!envOrOptions) {
this.#env = MONERIUM_CONFIG.environments['sandbox'];
return;
}
// String argument
if (typeof envOrOptions === 'string') {
this.#env = MONERIUM_CONFIG.environments[envOrOptions];
} else {
this.#env =
MONERIUM_CONFIG.environments[envOrOptions.environment || 'sandbox'];
if (!isServer) {
const { clientId, redirectUrl } =
envOrOptions as AuthorizationCodeCredentials;
this.#client = {
clientId: clientId as string,
redirectUrl: redirectUrl as string,
};
} else {
const { clientId, clientSecret } = envOrOptions as ClientCredentials;
this.#client = {
clientId: clientId as string,
clientSecret: clientSecret as string,
};
}
// this.getAccess();
}
}
/**
* Construct the url to the authorization code flow,
* Code Verifier needed for the code challenge is stored in local storage
* For automatic wallet link, add the following properties: `address`, `signature` & `chainId`
* @returns string
* {@link https://monerium.dev/api-docs#operation/auth}
*/
async authorize(client?: AuthFlowOptions) {
const clientId =
client?.clientId ||
(this.#client as AuthorizationCodeCredentials)?.clientId;
const redirectUrl =
client?.redirectUrl ||
(this.#client as AuthorizationCodeCredentials)?.redirectUrl;
if (!clientId) {
throw new Error('Missing ClientId');
}
if (!redirectUrl) {
throw new Error('Missing RedirectUrl');
}
const authFlowUrl = getAuthFlowUrlAndStoreCodeVerifier(this.#env.api, {
client_id: clientId,
redirect_uri: redirectUrl,
address: client?.address,
signature: client?.signature,
chainId: client?.chainId,
state: client?.state,
});
// Redirect to the authFlow
window.location.replace(authFlowUrl);
}
/**
* Get access to the API
* @param {AuthorizationCodeCredentials | ClientCredentials} client - the client credentials
* @returns boolean to indicate if access has been granted
*/
async getAccess(
client?: AuthorizationCodeCredentials | ClientCredentials
): Promise<boolean> {
const clientId = client?.clientId || this.#client?.clientId;
const clientSecret =
(client as ClientCredentials)?.clientSecret ||
(this.#client as ClientCredentials)?.clientSecret;
if (clientSecret) {
if (!isServer) {
throw new Error('Only use client credentials on server side');
}
await this.#clientCredentialsAuthorization(
this.#client as ClientCredentials
);
return !!this.bearerProfile;
}
const redirectUrl =
(client as AuthorizationCodeCredentials)?.redirectUrl ||
(this.#client as AuthorizationCodeCredentials)?.redirectUrl;
if (!clientId) {
throw new Error('Missing ClientId');
}
if (isServer) {
throw new Error('This only works client side');
}
const authCode =
new URLSearchParams(window.location.search).get('code') || undefined;
const state =
new URLSearchParams(window.location.search).get('state') || undefined;
const refreshToken =
localStorage.getItem(STORAGE_REFRESH_TOKEN) || undefined;
if (refreshToken) {
await this.#refreshTokenAuthorization(clientId, refreshToken);
} else if (authCode) {
await this.#authCodeAuthorization(clientId, redirectUrl, authCode, state);
}
return !!this.bearerProfile;
}
/**
* {@link https://monerium.dev/api-docs#operation/auth-token}
*/
async #grantAccess(args: AuthArgs): Promise<BearerProfile> {
let params:
| AuthCodeRequest
| RefreshTokenRequest
| ClientCredentialsRequest;
if (isAuthCode(args)) {
params = { ...args, grant_type: 'authorization_code' };
} else if (isRefreshToken(args)) {
params = { ...args, grant_type: 'refresh_token' };
} else if (isClientCredentials(args)) {
params = { ...args, grant_type: 'client_credentials' };
} else {
throw new Error('Authorization grant type could not be detected.');
}
await this.#api<BearerProfile>(
'post',
`auth/token`,
params as unknown as Record<string, string>,
true
)
.then((res) => {
this.bearerProfile = res;
this.isAuthorized = !!res;
this.#authorizationHeader = `Bearer ${res?.access_token}`;
if (!isServer) {
window.localStorage.setItem(
STORAGE_REFRESH_TOKEN,
this.bearerProfile?.refresh_token || ''
);
}
})
.catch((err) => {
if (!isServer) {
localStorage.removeItem(STORAGE_CODE_VERIFIER);
localStorage.removeItem(STORAGE_REFRESH_TOKEN);
cleanQueryString();
}
throw new Error(err?.message);
});
/**
* Remove auth code from URL.
* Make sure this is the last action before returning the bearer profile
* NextJS seems to overwrite this if there is data fetching in the background
*/
if (isAuthCode(args)) {
cleanQueryString();
}
return this.bearerProfile as BearerProfile;
}
// -- Read Methods
/**
* {@link https://monerium.dev/api-docs#operation/auth-context}
*/
getAuthContext(): Promise<AuthContext> {
return this.#api<AuthContext>('get', `auth/context`);
}
/**
* {@link https://monerium.dev/api-docs#operation/profile}
* @param {string} profileId - the id of the profile to fetch.
*/
getProfile(profileId: string): Promise<Profile> {
return this.#api<Profile>('get', `profiles/${profileId}`);
}
/**
* {@link https://monerium.dev/api-docs#operation/profile-balances}
* @param {string=} profileId - the id of the profile to fetch balances.
*/
getBalances(profileId?: string): Promise<Balances[]> {
if (profileId) {
return this.#api<Balances[]>('get', `profiles/${profileId}/balances`);
} else {
return this.#api<Balances[]>('get', `balances`);
}
}
/**
* {@link https://monerium.dev/api-docs#operation/orders}
*/
getOrders(filter?: OrderFilter): Promise<Order[]> {
const searchParams = urlEncoded(filter as Record<string, string>);
return this.#api<Order[]>('get', `orders?${searchParams}`);
}
/**
* {@link https://monerium.dev/api-docs#operation/order}
*/
getOrder(orderId: string): Promise<Order> {
return this.#api<Order>('get', `orders/${orderId}`);
}
/**
* {@link https://monerium.dev/api-docs#operation/tokens}
*/
getTokens(): Promise<Token[]> {
return this.#api<Token[]>('get', 'tokens');
}
// -- Write Methods
/**
* {@link https://monerium.dev/api-docs#operation/profile-addresses}
*/
linkAddress(profileId: string, body: LinkAddress) {
body = mapChainAndNetwork(body);
body.accounts = body.accounts.map((account) => mapChainAndNetwork(account));
return this.#api(
'post',
`profiles/${profileId}/addresses`,
JSON.stringify(body)
);
}
/**
* {@link https://monerium.dev/api-docs#operation/post-orders}
*/
placeOrder(order: NewOrder, profileId?: string): Promise<Order> {
const body = {
kind: 'redeem',
currency: 'eur',
...mapChainAndNetwork(order),
counterpart: {
...order.counterpart,
identifier: mapChainAndNetwork(order.counterpart.identifier),
},
};
if (profileId) {
return this.#api<Order>(
'post',
`profiles/${profileId}/orders`,
JSON.stringify(body)
);
} else {
return this.#api<Order>('post', `orders`, JSON.stringify(body));
}
}
/**
* {@link https://monerium.dev/api-docs#operation/supporting-document}
*/
uploadSupportingDocument(document: File): Promise<SupportingDoc> {
const formData = new FormData();
formData.append('file', document as unknown as Blob);
return rest<SupportingDoc>(`${this.#env.api}/files`, 'post', formData, {
Authorization: this.#authorizationHeader || '',
});
}
// -- Helper Methods
async #api<T>(
method: string,
resource: string,
body?: BodyInit | Record<string, string>,
isFormEncoded?: boolean
): Promise<T> {
return rest<T>(
`${this.#env.api}/${resource}`,
method,
isFormEncoded ? urlEncoded(body as Record<string, string>) : body,
{
Authorization: this.#authorizationHeader || '',
'Content-Type': `application/${
isFormEncoded ? 'x-www-form-urlencoded' : 'json'
}`,
}
);
}
/*
* Triggered when the client has claimed an authorization code
* 1. Code Verifier is picked up from the localStorage
* 2. auth service is called to claim the tokens
* 3. Refresh token is stored in the localStorage
*/
#authCodeAuthorization = async (
clientId: string,
redirectUrl: string,
authCode: string,
state?: string
) => {
const codeVerifier = localStorage.getItem(STORAGE_CODE_VERIFIER) || '';
if (!codeVerifier) {
throw new Error('Code verifier not found');
}
/** @deprecated, use localStorage, will be removed in v3 */
this.codeVerifier = codeVerifier;
this.state = state;
localStorage.removeItem(STORAGE_CODE_VERIFIER);
// Remove auth code from URL.
return await this.#grantAccess({
code: authCode,
redirect_uri: redirectUrl as string,
client_id: clientId,
code_verifier: codeVerifier,
});
};
#clientCredentialsAuthorization = async ({
clientId,
clientSecret,
}: ClientCredentials) => {
return await this.#grantAccess({
client_id: clientId,
client_secret: clientSecret as string,
});
};
#refreshTokenAuthorization = async (
clientId: string,
refreshToken: string
) => {
return await this.#grantAccess({
refresh_token: refreshToken,
client_id: clientId,
});
};
// -- Notifications
async connectOrderSocket() {
// When the user is authenticated, we connect to the order notifications socket in case
// the user has subscribed to any event
if (this.bearerProfile?.access_token && this.#subscriptions.size > 0) {
this.#socket = this.subscribeToOrderNotifications();
}
}
subscribeToOrderNotifications = (): WebSocket => {
const socketUrl = `${this.#env.wss}/profiles/${
this.bearerProfile?.profile
}/orders?access_token=${this.bearerProfile?.access_token}`;
const socket = new WebSocket(socketUrl);
socket.addEventListener('open', () => {
console.info(`Socket connected: ${socketUrl}`);
});
socket.addEventListener('error', (event) => {
console.error(event);
throw new Error(`Socket error: ${socketUrl}`);
});
socket.addEventListener('message', (event) => {
const notification = JSON.parse(event.data) as OrderNotification;
this.#subscriptions.get(notification.meta.state as OrderState)?.(
notification
);
});
socket.addEventListener('close', () => {
console.info(`Socket connection closed: ${socketUrl}`);
});
return socket;
};
/**
* Cleanups the socket and the subscriptions
*/
async disconnect() {
if (!isServer) {
localStorage.removeItem(STORAGE_CODE_VERIFIER);
}
this.#subscriptions.clear();
this.#socket?.close();
this.#authorizationHeader = undefined;
this.bearerProfile = undefined;
}
/**
* Revokes access
*/
async revokeAccess() {
if (!isServer) {
localStorage.removeItem(STORAGE_REFRESH_TOKEN);
}
this.disconnect();
}
/**
* Subscribe to MoneriumEvent to receive notifications using the Monerium API (WebSocket)
* We are setting a subscription map because we need the user to have a token to start the WebSocket connection
* {@link https://monerium.dev/api-docs#operation/profile-orders-notifications}
* @param event The event to subscribe to
* @param handler The handler to be called when the event is triggered
*/
subscribeOrders(event: MoneriumEvent, handler: MoneriumEventListener): void {
this.#subscriptions.set(event as OrderState, handler);
}
/**
* Unsubscribe from MoneriumEvent and close the socket if there are no more subscriptions
* @param event The event to unsubscribe from
*/
unsubscribeOrders(event: MoneriumEvent): void {
this.#subscriptions.delete(event as OrderState);
if (this.#subscriptions.size === 0) {
this.#socket?.close();
this.#socket = undefined;
}
}
// -- Deprecated methods
/**
* @deprecated since v2.6.4, will be removed in 2.7.2+, use {@link getAccess} instead.
*/
auth = async (args: AuthArgs) => await this.#grantAccess(args);
/**
* @deprecated since v2.7.1, will be removed in 2.7.2+, use {@link getAccess} instead.
*/
connect = async (args: AuthArgs) => await this.#grantAccess(args);
/**
* @deprecated since v2.6.4, will be removed in 2.7.2+, use {@link authorize} instead.
*/
getAuthFlowURI = (args: PKCERequestArgs): string => {
const url = getAuthFlowUrlAndStoreCodeVerifier(this.#env.api, args);
this.codeVerifier = localStorage.getItem(STORAGE_CODE_VERIFIER) as string;
return url;
};
/**
* @deprecated since v2.0.7, will be removed in 2.7.2+, use {@link getAuthFlowURI} instead.
*/
pkceRequest = (args: PKCERequestArgs) => this.getAuthFlowURI(args);
// -- Getters (mainly for testing)
getEnvironment = (): Environment => this.#env;
}