@alore/auth-react-sdk 1.0.0-alpha

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,509 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { startAuthentication } from '@simplewebauthn/browser';
11
+ import argon2 from 'argon2-browser';
12
+ import crypto from 'crypto';
13
+ export function hashUserInfo(userInfo) {
14
+ const hash = crypto.createHash('sha256');
15
+ hash.update(userInfo);
16
+ return hash.digest('hex');
17
+ }
18
+ export function generateSecureHash(password_1, salt_1) {
19
+ return __awaiter(this, arguments, void 0, function* (password, salt, keyDerivationFunction = 'argon2d') {
20
+ if (keyDerivationFunction === 'argon2d') {
21
+ const result = yield argon2.hash({
22
+ pass: password,
23
+ salt,
24
+ type: argon2.ArgonType.Argon2d,
25
+ hashLen: 32,
26
+ mem: 32768,
27
+ time: 3,
28
+ parallelism: 2,
29
+ });
30
+ return result.encoded;
31
+ }
32
+ throw new Error('Unsupported key derivation function');
33
+ });
34
+ }
35
+ const DEFAULT_URL = 'https://alpha-api.bealore.com/v1';
36
+ export class AloreAuth {
37
+ constructor(apiKey, options) {
38
+ this.apiKey = apiKey;
39
+ this.services = {
40
+ completeRegistration: (context, event) => __awaiter(this, void 0, void 0, function* () {
41
+ const { email, nickname, passwordHash, device } = event.payload;
42
+ const response = yield this.fetchWithProgressiveBackoff('/auth/account-registration', {
43
+ method: 'POST',
44
+ headers: {
45
+ 'Content-Type': 'application/json',
46
+ },
47
+ body: JSON.stringify({
48
+ email,
49
+ nickname,
50
+ passwordHash,
51
+ device,
52
+ }),
53
+ });
54
+ const data = yield response.json();
55
+ if (response.ok)
56
+ return data;
57
+ throw new Error(data.message || data.error || 'Authentication failed');
58
+ }),
59
+ confirmPassword: (context, event) => __awaiter(this, void 0, void 0, function* () {
60
+ const { email, passwordHash } = event.payload;
61
+ const response = yield this.fetchWithProgressiveBackoff(`/auth/password-creation`, {
62
+ method: 'POST',
63
+ headers: {
64
+ 'Content-Type': 'application/json',
65
+ },
66
+ body: JSON.stringify({
67
+ email,
68
+ newPasswordHash: passwordHash,
69
+ }),
70
+ });
71
+ if (!response.ok)
72
+ return {};
73
+ return { error: response === null || response === void 0 ? void 0 : response.statusText };
74
+ }),
75
+ sendConfirmationEmail: (context, event) => __awaiter(this, void 0, void 0, function* () {
76
+ const { email, nickname, locale } = event.payload;
77
+ const searchParams = new URLSearchParams();
78
+ const url = '/auth/confirmation-email';
79
+ if (locale) {
80
+ searchParams.append('locale', locale);
81
+ }
82
+ if (this.emailTemplate !== '') {
83
+ searchParams.append('template', this.emailTemplate);
84
+ }
85
+ const response = yield this.fetchWithProgressiveBackoff(searchParams.size > 0 ? `${url}?${searchParams.toString()}` : url, {
86
+ method: 'POST',
87
+ headers: {
88
+ 'Content-Type': 'application/json',
89
+ },
90
+ body: JSON.stringify({
91
+ email,
92
+ nickname,
93
+ }),
94
+ });
95
+ if (response.ok) {
96
+ const resJson = yield response.json();
97
+ const { salt, sessionId } = resJson;
98
+ return { salt, sessionId };
99
+ }
100
+ if (response.status === 403) {
101
+ const resJson = yield response.json();
102
+ throw new Error(resJson);
103
+ }
104
+ return { error: response === null || response === void 0 ? void 0 : response.statusText };
105
+ }),
106
+ retrieveSalt: (context, _event) => __awaiter(this, void 0, void 0, function* () {
107
+ const { credentialEmail: email } = context;
108
+ const response = yield this.fetchWithProgressiveBackoff(`/auth/salt/${email}`, {
109
+ headers: {
110
+ 'Content-Type': 'application/json',
111
+ },
112
+ });
113
+ if (response.ok) {
114
+ const salt = yield response.json();
115
+ return { salt };
116
+ }
117
+ return { error: response === null || response === void 0 ? void 0 : response.statusText };
118
+ }),
119
+ sendCode: (context, event) => __awaiter(this, void 0, void 0, function* () {
120
+ const { email } = event.payload;
121
+ const response = yield this.fetchWithProgressiveBackoff(`/reset-password`, {
122
+ method: 'POST',
123
+ headers: {
124
+ 'Content-Type': 'application/json',
125
+ },
126
+ body: JSON.stringify({
127
+ email,
128
+ }),
129
+ });
130
+ if (!response.ok)
131
+ return { error: response === null || response === void 0 ? void 0 : response.statusText };
132
+ return {};
133
+ }),
134
+ startRegisterPasskey: (_context, event) => __awaiter(this, void 0, void 0, function* () {
135
+ const { email, nickname, device } = event.payload;
136
+ const startPasskeyRegistrationResponse = yield this.fetchWithProgressiveBackoff(`/auth/account-registration-passkey`, {
137
+ method: 'POST',
138
+ headers: {
139
+ 'Content-Type': 'application/json',
140
+ },
141
+ body: JSON.stringify({
142
+ userEmail: email,
143
+ userNickname: nickname,
144
+ userDevice: device,
145
+ }),
146
+ });
147
+ const data = yield startPasskeyRegistrationResponse.json();
148
+ return data;
149
+ }),
150
+ finishRegisterPasskey: (context, event) => __awaiter(this, void 0, void 0, function* () {
151
+ const { email, nickname, device, passkeyRegistration } = event.payload;
152
+ const response = yield this.fetchWithProgressiveBackoff(`/auth/account-registration-passkey-finish`, {
153
+ method: 'POST',
154
+ headers: {
155
+ 'Content-Type': 'application/json',
156
+ },
157
+ body: JSON.stringify({
158
+ userEmail: email,
159
+ userNickname: nickname,
160
+ userDevice: device,
161
+ passkeyRegistration,
162
+ sessionId: context.sessionId,
163
+ }),
164
+ });
165
+ const data = yield response.json();
166
+ if (response.ok)
167
+ return data;
168
+ }),
169
+ finishPasskeyAuth: (context, event) => __awaiter(this, void 0, void 0, function* () {
170
+ const { passkeyAuth } = event.payload;
171
+ const response = yield this.fetchWithProgressiveBackoff(`/auth/login-passkey-finish`, {
172
+ method: 'POST',
173
+ headers: {
174
+ 'Content-Type': 'application/json',
175
+ },
176
+ body: JSON.stringify({ passkeyAuth, sessionId: context.sessionId }),
177
+ });
178
+ const data = yield response.json();
179
+ if (response.ok)
180
+ return data;
181
+ }),
182
+ startPasskeyAuth: (_, event) => __awaiter(this, void 0, void 0, function* () {
183
+ var _a;
184
+ const email = event.type === 'START_PASSKEY_LOGIN' ? (_a = event.payload) === null || _a === void 0 ? void 0 : _a.email : undefined;
185
+ const url = `/auth/login-passkey${email ? `?email=${encodeURIComponent(email)}` : ''}`;
186
+ const startAuthResponse = yield this.fetchWithProgressiveBackoff(url);
187
+ const data = yield startAuthResponse.json();
188
+ if (startAuthResponse.ok)
189
+ return data;
190
+ }),
191
+ verifyLogin: (_, event) => __awaiter(this, void 0, void 0, function* () {
192
+ var _b, _c;
193
+ const { email, passwordHash, device, locale } = event.payload;
194
+ const searchParams = new URLSearchParams();
195
+ const url = '/auth/login-verification';
196
+ if (locale) {
197
+ searchParams.append('locale', locale);
198
+ }
199
+ if (this.emailTemplate !== '') {
200
+ searchParams.append('template', this.emailTemplate);
201
+ }
202
+ const response = yield this.fetchWithProgressiveBackoff(searchParams.size > 0 ? `${url}?${searchParams.toString()}` : url, {
203
+ method: 'POST',
204
+ headers: {
205
+ 'Content-Type': 'application/json',
206
+ },
207
+ body: JSON.stringify({
208
+ email,
209
+ passwordHash,
210
+ device,
211
+ }),
212
+ });
213
+ const data = yield response.json();
214
+ if (!response.ok) {
215
+ if (response.status === 403) {
216
+ return { active2fa: data };
217
+ }
218
+ if (((_b = data === null || data === void 0 ? void 0 : data.error) === null || _b === void 0 ? void 0 : _b.includes('2FA')) || ((_c = data === null || data === void 0 ? void 0 : data.error) === null || _c === void 0 ? void 0 : _c.includes('device'))) {
219
+ return { error: data === null || data === void 0 ? void 0 : data.error };
220
+ }
221
+ throw new Error((data === null || data === void 0 ? void 0 : data.message) || (data === null || data === void 0 ? void 0 : data.error) || data);
222
+ }
223
+ else {
224
+ return data;
225
+ }
226
+ }),
227
+ verify2faCode: (_context, event) => __awaiter(this, void 0, void 0, function* () {
228
+ const { email, passwordHash, device, otp } = event.payload;
229
+ const response = yield this.fetchWithProgressiveBackoff('/auth/sw-2fa-verification', {
230
+ method: 'POST',
231
+ headers: {
232
+ 'Content-Type': 'application/json',
233
+ },
234
+ body: JSON.stringify({
235
+ email,
236
+ passwordHash,
237
+ device,
238
+ otp,
239
+ }),
240
+ });
241
+ const data = yield response.json();
242
+ if (response.ok)
243
+ return data;
244
+ throw new Error(data.message || data.error || 'Authentication failed');
245
+ }),
246
+ authenticateWebauthn: (context, event) => __awaiter(this, void 0, void 0, function* () {
247
+ const { email, passwordHash, device, authId } = event.payload;
248
+ const optionsResponse = yield this.fetchWithProgressiveBackoff('/auth/hw-2fa-start-verification', {
249
+ method: 'POST',
250
+ headers: {
251
+ 'Content-Type': 'application/json',
252
+ },
253
+ body: JSON.stringify({
254
+ twofaId: authId,
255
+ email,
256
+ passwordHash,
257
+ }),
258
+ });
259
+ if (optionsResponse.status !== 200) {
260
+ throw new Error(optionsResponse.statusText);
261
+ }
262
+ const optionsData = yield optionsResponse.json();
263
+ const credential = yield startAuthentication(optionsData.requestChallengeResponse.publicKey).catch((err) => {
264
+ throw new Error(err);
265
+ });
266
+ const response = yield this.fetchWithProgressiveBackoff('/auth/hw-2fa-finish-verification', {
267
+ method: 'POST',
268
+ headers: {
269
+ 'Content-Type': 'application/json',
270
+ },
271
+ body: JSON.stringify({
272
+ email,
273
+ passwordHash,
274
+ device,
275
+ credential,
276
+ sessionId: optionsData.sessionId,
277
+ }),
278
+ });
279
+ const data = yield response.json();
280
+ if (response.ok)
281
+ return data;
282
+ throw new Error(data.message || data.error || 'Authentication failed');
283
+ }),
284
+ verifyDeviceCode: (context, event) => __awaiter(this, void 0, void 0, function* () {
285
+ const { email, passwordHash, device, secureCode } = event.payload;
286
+ const response = yield this.fetchWithProgressiveBackoff('/auth/device-ownership-verification', {
287
+ method: 'POST',
288
+ headers: {
289
+ 'Content-Type': 'application/json',
290
+ },
291
+ body: JSON.stringify({
292
+ email,
293
+ passwordHash,
294
+ deviceSecret: device,
295
+ emailCode: secureCode,
296
+ sessionId: context.sessionId,
297
+ }),
298
+ });
299
+ const data = yield response.json();
300
+ if (response.ok)
301
+ return data;
302
+ throw new Error(data.message || data.error || 'Authentication failed');
303
+ }),
304
+ verifyEmail: (context, event) => __awaiter(this, void 0, void 0, function* () {
305
+ const { secureCode } = event.payload;
306
+ const response = yield this.fetchWithProgressiveBackoff('/auth/registration-code-verification', {
307
+ method: 'POST',
308
+ headers: {
309
+ 'Content-Type': 'application/json',
310
+ },
311
+ body: JSON.stringify({
312
+ emailCode: secureCode,
313
+ sessionId: context.sessionId,
314
+ }),
315
+ });
316
+ if (!response.ok) {
317
+ const data = yield response.json();
318
+ throw new Error((data === null || data === void 0 ? void 0 : data.message) || (data === null || data === void 0 ? void 0 : data.error) || data);
319
+ }
320
+ else {
321
+ return {};
322
+ }
323
+ }),
324
+ verifyEmail2fa: (context, event) => __awaiter(this, void 0, void 0, function* () {
325
+ const { email, passwordHash, secureCode } = event.payload;
326
+ const response = yield this.fetchWithProgressiveBackoff('/auth/email-2fa-verification', {
327
+ method: 'POST',
328
+ body: JSON.stringify({
329
+ email,
330
+ passwordHash,
331
+ emailCode: secureCode,
332
+ sessionId: context.sessionId,
333
+ }),
334
+ headers: {
335
+ 'Content-Type': 'application/json',
336
+ },
337
+ });
338
+ const data = yield response.json();
339
+ if (response.ok)
340
+ return data;
341
+ throw new Error(data.message || data.error || 'Authentication failed');
342
+ }),
343
+ verifyEmailEligibility: (_, event) => __awaiter(this, void 0, void 0, function* () {
344
+ const { email } = event;
345
+ const response = yield this.fetchWithProgressiveBackoff('/auth/email-eligibility-verification', {
346
+ method: 'POST',
347
+ headers: {
348
+ 'Content-Type': 'application/json',
349
+ },
350
+ body: JSON.stringify({
351
+ email,
352
+ }),
353
+ });
354
+ const data = yield response.json();
355
+ if (!response.ok)
356
+ throw new Error((data === null || data === void 0 ? void 0 : data.message) || (data === null || data === void 0 ? void 0 : data.error) || data);
357
+ return data;
358
+ }),
359
+ verifyClaimNftEmail2fa: (context, event) => __awaiter(this, void 0, void 0, function* () {
360
+ const { email, emailCode } = event.payload;
361
+ const response = yield this.fetchWithProgressiveBackoff('/auth/eligible-email-code-verification', {
362
+ method: 'POST',
363
+ body: JSON.stringify({
364
+ email,
365
+ emailCode,
366
+ sessionId: context.sessionId,
367
+ }),
368
+ headers: {
369
+ 'Content-Type': 'application/json',
370
+ },
371
+ });
372
+ const data = yield response.json();
373
+ if (response.ok)
374
+ return data;
375
+ throw new Error(data || 'Authentication failed');
376
+ }),
377
+ fetchForgeData: (_, event) => __awaiter(this, void 0, void 0, function* () {
378
+ const response = yield this.fetchWithProgressiveBackoff(`/forges/${event.forgeId}`);
379
+ const data = (yield response.json());
380
+ if (!response.ok) {
381
+ throw new Error(`Failed to fetchWithProgressiveBackoff: ${data}`);
382
+ }
383
+ return data;
384
+ }),
385
+ googleLogin: (_, event) => __awaiter(this, void 0, void 0, function* () {
386
+ const { googleToken } = event;
387
+ const response = yield this.fetchWithProgressiveBackoff('/auth/google-login', {
388
+ method: 'POST',
389
+ headers: {
390
+ 'Content-Type': 'application/json',
391
+ },
392
+ body: JSON.stringify({
393
+ accessToken: googleToken,
394
+ }),
395
+ });
396
+ const data = yield response.json();
397
+ if (response.ok) {
398
+ return {
399
+ googleOtpCode: data.otpCode,
400
+ salt: data.salt,
401
+ googleUser: {
402
+ email: data.email,
403
+ nickname: data.nickname,
404
+ salt: data.salt,
405
+ },
406
+ sessionId: data.sessionId,
407
+ };
408
+ }
409
+ if (response.status === 404) {
410
+ return {
411
+ isNewUser: true,
412
+ registerUser: {
413
+ email: data.email,
414
+ nickname: data.nickname,
415
+ salt: data.salt,
416
+ },
417
+ };
418
+ }
419
+ if (!response.ok)
420
+ throw new Error(data.error || data.message || data);
421
+ return {};
422
+ }),
423
+ verifyGoogleLogin: (context, event) => __awaiter(this, void 0, void 0, function* () {
424
+ const { email, passwordHash, otp } = event.payload;
425
+ const response = yield this.fetchWithProgressiveBackoff('/auth/google-2fa-verification', {
426
+ method: 'POST',
427
+ body: JSON.stringify({
428
+ email,
429
+ emailCode: otp,
430
+ passwordHash,
431
+ sessionId: context.sessionId,
432
+ }),
433
+ headers: {
434
+ 'Content-Type': 'application/json',
435
+ },
436
+ });
437
+ const data = yield response.json();
438
+ if (response.ok)
439
+ return data;
440
+ throw new Error(data.message || data.error || 'Authentication failed');
441
+ }),
442
+ };
443
+ if (!apiKey)
444
+ throw new Error('API_KEY is required');
445
+ this.endpoint = (options === null || options === void 0 ? void 0 : options.endpoint) || DEFAULT_URL;
446
+ this.emailTemplate = (options === null || options === void 0 ? void 0 : options.emailTemplate) || '';
447
+ }
448
+ // eslint-disable-next-line class-methods-use-this
449
+ delay(ms) {
450
+ return __awaiter(this, void 0, void 0, function* () {
451
+ // eslint-disable-next-line no-promise-executor-return
452
+ yield new Promise((resolve) => setTimeout(resolve, ms));
453
+ });
454
+ }
455
+ fetchWithProgressiveBackoff(
456
+ // eslint-disable-next-line no-undef
457
+ url,
458
+ // eslint-disable-next-line no-undef
459
+ options, config) {
460
+ return __awaiter(this, void 0, void 0, function* () {
461
+ const { maxAttempts = 3, initialDelay = 200 } = config || {};
462
+ let attempt = 0;
463
+ let delayValue = initialDelay;
464
+ // eslint-disable-next-line no-undef
465
+ const init = Object.assign(Object.assign({}, options), { credentials: 'include', headers: Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.headers), { 'X-API-KEY': this.apiKey }) });
466
+ while (attempt < maxAttempts) {
467
+ if (attempt > 0) {
468
+ // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, no-loop-func
469
+ yield this.delay(delayValue);
470
+ delayValue *= 2;
471
+ }
472
+ attempt += 1;
473
+ try {
474
+ // eslint-disable-next-line no-await-in-loop
475
+ const response = yield fetch(new URL(`${this.endpoint}${url}`), init);
476
+ if (response.ok || attempt === maxAttempts || response.status !== 500) {
477
+ return response;
478
+ }
479
+ }
480
+ catch (error) {
481
+ console.error(error);
482
+ if (error instanceof TypeError &&
483
+ error.message === 'Failed to fetch' &&
484
+ attempt >= maxAttempts) {
485
+ console.error('Connection refused, the backend is probably not running.');
486
+ this.verifyBackendStatus();
487
+ }
488
+ else if (attempt < maxAttempts) {
489
+ console.error(`Attempt ${attempt} failed, retrying in ${delayValue}ms...`);
490
+ }
491
+ }
492
+ }
493
+ throw new Error(`Max attempts (${maxAttempts}) exceeded`);
494
+ });
495
+ }
496
+ verifyBackendStatus() {
497
+ return __awaiter(this, void 0, void 0, function* () {
498
+ try {
499
+ const res = yield fetch(`${this.endpoint}/health-check`);
500
+ if (!res.ok) {
501
+ throw new Error('Failed to fetch');
502
+ }
503
+ }
504
+ catch (_a) {
505
+ throw new Error('Server down');
506
+ }
507
+ });
508
+ }
509
+ }
@@ -0,0 +1 @@
1
+ export * from './AloreAuth';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './AloreAuth';
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@alore/auth-react-sdk",
3
+ "version": "1.0.0-alpha",
4
+ "repository": "https://github.com/0xCarbon/alore-js",
5
+ "description": "SDK for Alore Auth",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "default": "./dist/index.js"
15
+ }
16
+ },
17
+ "author": "0xCarbon",
18
+ "license": "LGPL-2.1-only",
19
+ "engines": {
20
+ "node": ">=20.0.0"
21
+ },
22
+ "dependencies": {
23
+ "@simplewebauthn/browser": "7.4.0",
24
+ "argon2-browser": "1.18.0",
25
+ "ethers": "6.7.1",
26
+ "js-cookie": "3.0.5",
27
+ "jwt-decode": "4.0.0"
28
+ },
29
+ "devDependencies": {
30
+ "@types/argon2-browser": "1.18.1",
31
+ "@types/js-cookie": "3.0.6",
32
+ "@types/node": "20.4.8",
33
+ "typescript": "5.4.5"
34
+ },
35
+ "packageManager": "pnpm@8.15.7+sha512.c85cd21b6da10332156b1ca2aa79c0a61ee7ad2eb0453b88ab299289e9e8ca93e6091232b25c07cbf61f6df77128d9c849e5c9ac6e44854dbd211c49f3a67adc",
36
+ "scripts": {
37
+ "build": "rm -rf dist/* && tsc"
38
+ }
39
+ }