@alore/auth-react-sdk 1.0.7-alpha → 1.1.0-alpha.10

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.
package/dist/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './utils/AloreAuth';
2
2
  export * from './helpers/crypto';
3
+ export * from './types';
package/dist/index.js CHANGED
@@ -1,2 +1,3 @@
1
1
  export * from './utils/AloreAuth';
2
2
  export * from './helpers/crypto';
3
+ export * from './types';
@@ -1,4 +1,4 @@
1
- import { AuthMachineContext, AuthProviderConfig, FetchWithProgressiveBackoffConfig, ForgeData } from '../types';
1
+ import type { AuthMachineContext, AuthProviderConfig, FetchWithProgressiveBackoffConfig, ForgeData } from '../types';
2
2
  export declare class AloreAuth {
3
3
  protected readonly aloreBaseUrl: string;
4
4
  protected readonly emailTemplate: string;
@@ -15,17 +15,13 @@ export declare class AloreAuth {
15
15
  };
16
16
  }) => Promise<{
17
17
  salt: string;
18
- error?: undefined;
19
- } | {
20
- error: string;
21
- salt?: undefined;
22
- }>;
18
+ } | undefined>;
23
19
  verifyEmail: (context: AuthMachineContext, event: {
24
20
  type: 'VERIFY_EMAIL';
25
21
  payload: {
26
22
  secureCode: string;
27
23
  };
28
- }) => Promise<{}>;
24
+ }) => Promise<{} | undefined>;
29
25
  completeRegistration: (context: AuthMachineContext, event: {
30
26
  type: 'COMPLETE_REGISTRATION';
31
27
  payload: {
@@ -41,11 +37,7 @@ export declare class AloreAuth {
41
37
  email: string;
42
38
  passwordHash: string;
43
39
  };
44
- }) => Promise<{
45
- error?: undefined;
46
- } | {
47
- error: string;
48
- }>;
40
+ }) => Promise<{}>;
49
41
  sendConfirmationEmail: (context: AuthMachineContext, event: {
50
42
  type: 'RESEND_CODE';
51
43
  payload: {
@@ -67,22 +59,13 @@ export declare class AloreAuth {
67
59
  }) => Promise<{
68
60
  salt: any;
69
61
  sessionId: any;
70
- error?: undefined;
71
- } | {
72
- error: string;
73
- salt?: undefined;
74
- sessionId?: undefined;
75
- }>;
62
+ } | undefined>;
76
63
  sendCode: (context: AuthMachineContext, event: {
77
64
  type: 'SEND_CODE';
78
65
  payload: {
79
66
  email: string;
80
67
  };
81
- }) => Promise<{
82
- error: string;
83
- } | {
84
- error?: undefined;
85
- }>;
68
+ }) => Promise<{}>;
86
69
  verifyLogin: (context: AuthMachineContext, event: {
87
70
  type: 'VERIFY_LOGIN';
88
71
  payload: {
@@ -263,6 +246,10 @@ export declare class AloreAuth {
263
246
  }) => Promise<any>;
264
247
  };
265
248
  private delay;
249
+ private isLocalUrl;
266
250
  fetchWithProgressiveBackoff(url: RequestInfo | URL, options?: RequestInit, config?: FetchWithProgressiveBackoffConfig): Promise<Response>;
251
+ private parseErrorResponse;
252
+ private throwParsedResponseError;
267
253
  private verifyBackendStatus;
254
+ private extractErrorInfo;
268
255
  }
@@ -35,7 +35,8 @@ export class AloreAuth {
35
35
  const salt = yield response.json();
36
36
  return { salt };
37
37
  }
38
- return { error: response === null || response === void 0 ? void 0 : response.statusText };
38
+ // Propagate parsed error so machine receives full payload as event.data
39
+ yield this.throwParsedResponseError(response);
39
40
  }),
40
41
  verifyEmail: (context, event) => __awaiter(this, void 0, void 0, function* () {
41
42
  const { secureCode } = event.payload;
@@ -52,8 +53,7 @@ export class AloreAuth {
52
53
  if (response.ok) {
53
54
  return {};
54
55
  }
55
- const data = yield response.json();
56
- throw new Error((data === null || data === void 0 ? void 0 : data.message) || (data === null || data === void 0 ? void 0 : data.error) || data);
56
+ yield this.throwParsedResponseError(response);
57
57
  }),
58
58
  completeRegistration: (context, event) => __awaiter(this, void 0, void 0, function* () {
59
59
  const { email, nickname, passwordHash, device } = event.payload;
@@ -73,7 +73,7 @@ export class AloreAuth {
73
73
  const data = yield response.json();
74
74
  if (response.ok)
75
75
  return data;
76
- throw new Error(data.message || data.error || 'Authentication failed');
76
+ yield this.throwParsedResponseError(response);
77
77
  }),
78
78
  confirmPassword: (context, event) => __awaiter(this, void 0, void 0, function* () {
79
79
  const { email, passwordHash } = event.payload;
@@ -88,8 +88,8 @@ export class AloreAuth {
88
88
  }),
89
89
  });
90
90
  if (!response.ok)
91
- return {};
92
- return { error: response === null || response === void 0 ? void 0 : response.statusText };
91
+ yield this.throwParsedResponseError(response);
92
+ return {};
93
93
  }),
94
94
  sendConfirmationEmail: (context, event) => __awaiter(this, void 0, void 0, function* () {
95
95
  const { email, nickname, locale } = event.payload;
@@ -116,11 +116,8 @@ export class AloreAuth {
116
116
  const { salt, sessionId } = resJson;
117
117
  return { salt, sessionId };
118
118
  }
119
- if (response.status === 403) {
120
- const resJson = yield response.json();
121
- throw new Error(resJson);
122
- }
123
- return { error: response === null || response === void 0 ? void 0 : response.statusText };
119
+ // Throw parsed error for machine to consume
120
+ yield this.throwParsedResponseError(response);
124
121
  }),
125
122
  sendCode: (context, event) => __awaiter(this, void 0, void 0, function* () {
126
123
  const { email } = event.payload;
@@ -134,7 +131,7 @@ export class AloreAuth {
134
131
  }),
135
132
  });
136
133
  if (!response.ok)
137
- return { error: response === null || response === void 0 ? void 0 : response.statusText };
134
+ yield this.throwParsedResponseError(response);
138
135
  return {};
139
136
  }),
140
137
  verifyLogin: (context, event) => __awaiter(this, void 0, void 0, function* () {
@@ -168,7 +165,7 @@ export class AloreAuth {
168
165
  if (((_a = data === null || data === void 0 ? void 0 : data.error) === null || _a === void 0 ? void 0 : _a.includes('2FA')) || ((_b = data === null || data === void 0 ? void 0 : data.error) === null || _b === void 0 ? void 0 : _b.includes('device'))) {
169
166
  return { error: data === null || data === void 0 ? void 0 : data.error };
170
167
  }
171
- throw new Error((data === null || data === void 0 ? void 0 : data.message) || (data === null || data === void 0 ? void 0 : data.error) || data);
168
+ yield this.throwParsedResponseError(response);
172
169
  }
173
170
  else {
174
171
  return data;
@@ -191,6 +188,8 @@ export class AloreAuth {
191
188
  }),
192
189
  });
193
190
  const data = yield startPasskeyRegistrationResponse.json();
191
+ if (!startPasskeyRegistrationResponse.ok)
192
+ yield this.throwParsedResponseError(startPasskeyRegistrationResponse);
194
193
  return data;
195
194
  }),
196
195
  finishRegisterPasskey: (context, event) => __awaiter(this, void 0, void 0, function* () {
@@ -251,7 +250,7 @@ export class AloreAuth {
251
250
  const data = yield response.json();
252
251
  if (response.ok)
253
252
  return data;
254
- throw new AloreAuthError(ErrorTypes.FAILED_TO_FETCH, data.message || data.error || data);
253
+ yield this.throwParsedResponseError(response);
255
254
  }),
256
255
  // Hardware 2FA flow
257
256
  verify2faCode: (_context, event) => __awaiter(this, void 0, void 0, function* () {
@@ -271,7 +270,7 @@ export class AloreAuth {
271
270
  const data = yield response.json();
272
271
  if (response.ok)
273
272
  return data;
274
- throw new Error(data.message || data.error || 'Authentication failed');
273
+ yield this.throwParsedResponseError(response);
275
274
  }),
276
275
  authenticateWebauthn: (context, event) => __awaiter(this, void 0, void 0, function* () {
277
276
  const { email, passwordHash, device, authId } = event.payload;
@@ -309,7 +308,7 @@ export class AloreAuth {
309
308
  const data = yield response.json();
310
309
  if (response.ok)
311
310
  return data;
312
- throw new Error(data.message || data.error || 'Authentication failed');
311
+ yield this.throwParsedResponseError(response);
313
312
  }),
314
313
  verifyDeviceCode: (context, event) => __awaiter(this, void 0, void 0, function* () {
315
314
  const { email, passwordHash, device, secureCode } = event.payload;
@@ -365,7 +364,7 @@ export class AloreAuth {
365
364
  });
366
365
  const data = yield response.json();
367
366
  if (!response.ok)
368
- throw new Error((data === null || data === void 0 ? void 0 : data.message) || (data === null || data === void 0 ? void 0 : data.error) || data);
367
+ yield this.throwParsedResponseError(response);
369
368
  return data;
370
369
  }),
371
370
  verifyClaimNftEmail2fa: (context, event) => __awaiter(this, void 0, void 0, function* () {
@@ -384,14 +383,13 @@ export class AloreAuth {
384
383
  const data = yield response.json();
385
384
  if (response.ok)
386
385
  return data;
387
- throw new Error(data || 'Authentication failed');
386
+ yield this.throwParsedResponseError(response);
388
387
  }),
389
388
  fetchForgeData: (_, event) => __awaiter(this, void 0, void 0, function* () {
390
389
  const response = yield this.fetchWithProgressiveBackoff(`/forges/${event.forgeId}`);
391
390
  const data = (yield response.json());
392
- if (!response.ok) {
393
- throw new Error(`Failed to fetchWithProgressiveBackoff: ${data}`);
394
- }
391
+ if (!response.ok)
392
+ yield this.throwParsedResponseError(response);
395
393
  return data;
396
394
  }),
397
395
  // Google login flow
@@ -433,7 +431,7 @@ export class AloreAuth {
433
431
  };
434
432
  }
435
433
  if (!response.ok)
436
- throw new Error(data.error || data.message || data);
434
+ yield this.throwParsedResponseError(response);
437
435
  return {};
438
436
  }),
439
437
  verifyGoogleLogin: (context, event) => __awaiter(this, void 0, void 0, function* () {
@@ -469,6 +467,21 @@ export class AloreAuth {
469
467
  yield new Promise((resolve) => setTimeout(resolve, ms));
470
468
  });
471
469
  }
470
+ // eslint-disable-next-line class-methods-use-this
471
+ isLocalUrl(urlString) {
472
+ try {
473
+ const parsed = new URL(urlString);
474
+ const isHttp = parsed.protocol === 'http:';
475
+ const isLoopbackHost = parsed.hostname === 'localhost' ||
476
+ parsed.hostname === '127.0.0.1' ||
477
+ parsed.hostname === '::1';
478
+ const isPort8000 = parsed.port === '8000';
479
+ return isHttp || isLoopbackHost || isPort8000;
480
+ }
481
+ catch (_e) {
482
+ return false;
483
+ }
484
+ }
472
485
  fetchWithProgressiveBackoff(
473
486
  // eslint-disable-next-line no-undef
474
487
  url,
@@ -478,8 +491,9 @@ export class AloreAuth {
478
491
  const { maxAttempts = 3, initialDelay = 200 } = config || {};
479
492
  let attempt = 0;
480
493
  let delayValue = initialDelay;
494
+ const isLocal = this.isLocalUrl(this.aloreBaseUrl);
481
495
  // eslint-disable-next-line no-undef
482
- const init = Object.assign(Object.assign({}, options), { credentials: 'include', headers: Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.headers), { 'X-CLIENT-ID': this.clientId, 'CF-Connecting-IP': '127.0.0.1' }) });
496
+ const init = Object.assign(Object.assign({}, options), { credentials: 'include', headers: Object.assign(Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.headers), { 'X-CLIENT-ID': this.clientId }), (isLocal && { 'CF-Connecting-IP': '127.0.0.1' })) });
483
497
  while (attempt < maxAttempts) {
484
498
  if (attempt > 0) {
485
499
  // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, no-loop-func
@@ -496,31 +510,110 @@ export class AloreAuth {
496
510
  }
497
511
  catch (error) {
498
512
  console.error(error);
499
- if (error instanceof TypeError &&
500
- error.message === 'Failed to fetch' &&
501
- attempt >= maxAttempts) {
502
- console.error('Connection refused, the backend is probably not running.');
503
- this.verifyBackendStatus();
513
+ // Treat any fetch TypeError as a network/CORS-style failure. Browsers localize the message.
514
+ const isFailedToFetch = error instanceof TypeError;
515
+ if (isFailedToFetch && attempt >= maxAttempts) {
516
+ // Determine whether backend is down or the request is likely blocked (e.g., CORS)
517
+ const origin = typeof window !== 'undefined' ? window.location.origin : undefined;
518
+ try {
519
+ // eslint-disable-next-line no-await-in-loop
520
+ const health = yield this.verifyBackendStatus();
521
+ const fullUrl = `${this.aloreBaseUrl}${url}`;
522
+ const message = origin
523
+ ? `Request blocked by CORS policy. Endpoint: ${fullUrl}. Please ensure origin ${origin} is allowed.`
524
+ : `Request blocked by CORS policy. Endpoint: ${fullUrl}.`;
525
+ const corsErr = new AloreAuthError(ErrorTypes.CORS_BLOCKED, message);
526
+ // Preserve original fetch error and health-check details for diagnostics
527
+ // @ts-ignore
528
+ corsErr.data = {
529
+ originalError: this.extractErrorInfo(error),
530
+ healthCheck: Object.assign({ reachable: true }, health),
531
+ };
532
+ throw corsErr;
533
+ }
534
+ catch (healthError) {
535
+ // Backend health-check failed → server likely down/unreachable
536
+ const downErr = new AloreAuthError(ErrorTypes.SERVER_DOWN, `Server is unreachable at ${this.aloreBaseUrl}. Please try again later.`);
537
+ // @ts-ignore
538
+ downErr.data = {
539
+ originalError: this.extractErrorInfo(error),
540
+ healthCheck: { reachable: false, error: this.extractErrorInfo(healthError) },
541
+ };
542
+ throw downErr;
543
+ }
504
544
  }
505
- else if (attempt < maxAttempts) {
545
+ if (attempt < maxAttempts) {
506
546
  console.error(`Attempt ${attempt} failed, retrying in ${delayValue}ms...`);
507
547
  }
508
548
  }
509
549
  }
510
- throw new Error(`Max attempts (${maxAttempts}) exceeded`);
550
+ // Final fallback (should rarely hit due to early throws above)
551
+ throw new AloreAuthError(ErrorTypes.FAILED_TO_FETCH, `Max attempts (${maxAttempts}) exceeded while contacting ${this.aloreBaseUrl}${url}`);
511
552
  });
512
553
  }
513
- verifyBackendStatus() {
554
+ // eslint-disable-next-line class-methods-use-this
555
+ parseErrorResponse(response) {
514
556
  return __awaiter(this, void 0, void 0, function* () {
515
557
  try {
516
- const res = yield fetch(`${this.aloreBaseUrl}/health-check`);
517
- if (!res.ok) {
518
- throw new Error('Failed to fetch');
558
+ const data = yield response.json();
559
+ // Standardize to server payload when present
560
+ if (data && typeof data === 'object' && (data.message || data.status)) {
561
+ return {
562
+ status: data.status || response.status,
563
+ message: data.message || data.error || response.statusText,
564
+ timestamp: data.timestamp,
565
+ };
519
566
  }
567
+ return { status: response.status, message: response.statusText };
568
+ }
569
+ catch (_a) {
570
+ return { status: response.status, message: response.statusText };
571
+ }
572
+ });
573
+ }
574
+ // eslint-disable-next-line class-methods-use-this
575
+ throwParsedResponseError(response) {
576
+ return __awaiter(this, void 0, void 0, function* () {
577
+ const parsed = yield this.parseErrorResponse(response);
578
+ // Normalize well-known auth errors for consistent UI handling
579
+ let normalizedMessage = parsed.message || 'Request failed';
580
+ if (parsed.status === 401) {
581
+ normalizedMessage = 'INVALID_CREDENTIALS';
582
+ }
583
+ else if (parsed.status === 403 && parsed.message === 'EMAIL_NOT_ALLOWED') {
584
+ normalizedMessage = 'EMAIL_NOT_ALLOWED';
585
+ }
586
+ const err = new AloreAuthError(ErrorTypes.FAILED_TO_FETCH, normalizedMessage);
587
+ // @ts-ignore attach server payload for consumers
588
+ err.data = Object.assign(Object.assign({}, parsed), { message: normalizedMessage });
589
+ throw err;
590
+ });
591
+ }
592
+ verifyBackendStatus() {
593
+ return __awaiter(this, void 0, void 0, function* () {
594
+ const endpoint = '/health/ready';
595
+ // eslint-disable-next-line no-undef
596
+ const init = { mode: 'no-cors', cache: 'no-store' };
597
+ try {
598
+ yield fetch(`${this.aloreBaseUrl}${endpoint}`, init);
599
+ return { checkedEndpoints: [endpoint] };
520
600
  }
521
601
  catch (_a) {
522
602
  throw new Error('Server down');
523
603
  }
524
604
  });
525
605
  }
606
+ // Capture a concise, serializable snapshot of an unknown error
607
+ // eslint-disable-next-line class-methods-use-this
608
+ extractErrorInfo(error) {
609
+ if (error instanceof Error) {
610
+ return { name: error.name, message: error.message, stack: error.stack };
611
+ }
612
+ try {
613
+ return JSON.parse(JSON.stringify(error));
614
+ }
615
+ catch (_a) {
616
+ return { error };
617
+ }
618
+ }
526
619
  }
@@ -5,10 +5,12 @@ export declare enum ErrorCodes {
5
5
  }
6
6
  export declare enum ErrorTypes {
7
7
  CLIENT_ID_REQUIRED = "CLIENT_ID_REQUIRED",
8
+ EMAIL_DOMAIN_NOT_ALLOWED = "EMAIL_DOMAIN_NOT_ALLOWED",
8
9
  PASSKEY_NOT_SUPPORTED = "PASSKEY_NOT_SUPPORTED",
9
10
  USER_ALREADY_EXISTS = "USER_ALREADY_EXISTS",
10
11
  FAILED_TO_FETCH = "FAILED_TO_FETCH",
11
12
  SERVER_DOWN = "SERVER_DOWN",
13
+ CORS_BLOCKED = "CORS_BLOCKED",
12
14
  BAD_RESPONSE = "BAD_RESPONSE",
13
15
  UNKNOWN_ERROR = "UNKNOWN_ERROR",
14
16
  INVALID_CREDENTIALS = "INVALID_CREDENTIALS",
@@ -8,10 +8,12 @@ export var ErrorCodes;
8
8
  export var ErrorTypes;
9
9
  (function (ErrorTypes) {
10
10
  ErrorTypes["CLIENT_ID_REQUIRED"] = "CLIENT_ID_REQUIRED";
11
+ ErrorTypes["EMAIL_DOMAIN_NOT_ALLOWED"] = "EMAIL_DOMAIN_NOT_ALLOWED";
11
12
  ErrorTypes["PASSKEY_NOT_SUPPORTED"] = "PASSKEY_NOT_SUPPORTED";
12
13
  ErrorTypes["USER_ALREADY_EXISTS"] = "USER_ALREADY_EXISTS";
13
14
  ErrorTypes["FAILED_TO_FETCH"] = "FAILED_TO_FETCH";
14
15
  ErrorTypes["SERVER_DOWN"] = "SERVER_DOWN";
16
+ ErrorTypes["CORS_BLOCKED"] = "CORS_BLOCKED";
15
17
  ErrorTypes["BAD_RESPONSE"] = "BAD_RESPONSE";
16
18
  ErrorTypes["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
17
19
  ErrorTypes["INVALID_CREDENTIALS"] = "INVALID_CREDENTIALS";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alore/auth-react-sdk",
3
- "version": "1.0.7-alpha",
3
+ "version": "1.1.0-alpha.10",
4
4
  "repository": "https://github.com/0xCarbon/alore-js",
5
5
  "description": "SDK for Alore Auth",
6
6
  "main": "dist/index.js",
@@ -14,10 +14,6 @@
14
14
  "default": "./dist/index.js"
15
15
  }
16
16
  },
17
- "scripts": {
18
- "prepare": "pnpm build",
19
- "build": "rm -rf dist/* && tsc"
20
- },
21
17
  "author": "0xCarbon",
22
18
  "license": "LGPL-2.1-only",
23
19
  "engines": {
@@ -36,5 +32,8 @@
36
32
  "@types/node": "20.4.8",
37
33
  "typescript": "5.4.5"
38
34
  },
39
- "packageManager": "pnpm@8.15.7+sha512.c85cd21b6da10332156b1ca2aa79c0a61ee7ad2eb0453b88ab299289e9e8ca93e6091232b25c07cbf61f6df77128d9c849e5c9ac6e44854dbd211c49f3a67adc"
40
- }
35
+ "packageManager": "pnpm@8.15.9",
36
+ "scripts": {
37
+ "build": "rm -rf dist/* && tsc"
38
+ }
39
+ }