@alore/auth-react-sdk 1.0.0-alpha → 1.0.2-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,3 @@
1
+ import { KeyDerivationFunction } from '../types';
2
+ export declare function hashUserInfo(userInfo: string): string;
3
+ export declare function generateSecureHash(password: string, salt: string, keyDerivationFunction?: KeyDerivationFunction): Promise<string>;
@@ -0,0 +1,33 @@
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 argon2 from 'argon2-browser';
11
+ import crypto from 'crypto';
12
+ export function hashUserInfo(userInfo) {
13
+ const hash = crypto.createHash('sha256');
14
+ hash.update(userInfo);
15
+ return hash.digest('hex');
16
+ }
17
+ export function generateSecureHash(password_1, salt_1) {
18
+ return __awaiter(this, arguments, void 0, function* (password, salt, keyDerivationFunction = 'argon2d') {
19
+ if (keyDerivationFunction === 'argon2d') {
20
+ const result = yield argon2.hash({
21
+ pass: password,
22
+ salt,
23
+ type: argon2.ArgonType.Argon2d,
24
+ hashLen: 32,
25
+ mem: 32768,
26
+ time: 3,
27
+ parallelism: 2,
28
+ });
29
+ return result.encoded;
30
+ }
31
+ throw new Error('Unsupported key derivation function');
32
+ });
33
+ }
package/dist/index.d.ts CHANGED
@@ -1 +1,2 @@
1
- export * from './AloreAuth';
1
+ export * from './utils/AloreAuth';
2
+ export * from './helpers/crypto';
package/dist/index.js CHANGED
@@ -1 +1,2 @@
1
- export * from './AloreAuth';
1
+ export * from './utils/AloreAuth';
2
+ export * from './helpers/crypto';
@@ -0,0 +1,102 @@
1
+ export type FetchWithProgressiveBackoffConfig = {
2
+ maxAttempts?: number;
3
+ initialDelay?: number;
4
+ };
5
+ export type KeyDerivationFunction = 'argon2d' | 'pbkdf2';
6
+ /**
7
+ * Configuration options for Auth Provider.
8
+ *
9
+ * @property rpDomain - Optional relying party domain, used for passkey.
10
+ * @property locale - Optional locale for translation.
11
+ * @property emailTemplate - Optional email template for authentication-related emails.
12
+ * @property requireEmailVerification - Optional boolean to require email verification.
13
+ * @property requireUsername - Optional boolean to require username.
14
+ * @property passwordMinLength - Optional number for password minimum length.
15
+ * @property enablePasskeys - Optional boolean to enable passkeys.
16
+ * @property socialLoginEnabled - Optional boolean to enable social login.
17
+ * @property privacyPolicyUrl - Optional string for privacy policy URL.
18
+ * @property termsOfServiceUrl - Optional string for terms of service URL.
19
+ * @property logoUrl - Optional string for logo URL.
20
+ * @property socialProviders - Optional social login providers.
21
+ */
22
+ export interface AuthProviderConfig {
23
+ rpDomain?: string;
24
+ locale?: 'pt' | 'en';
25
+ emailTemplate?: string;
26
+ requireEmailVerification?: boolean;
27
+ requireUsername?: boolean;
28
+ passwordMinLength?: number;
29
+ enablePasskeys?: boolean;
30
+ enablePasswords?: boolean;
31
+ socialLoginEnabled?: boolean;
32
+ privacyPolicyUrl?: string;
33
+ termsOfServiceUrl?: string;
34
+ logoUrl?: string;
35
+ socialProviders?: SocialProvider[];
36
+ }
37
+ export interface AuthMachineContext {
38
+ authProviderConfigs?: AuthProviderConfig;
39
+ salt?: string;
40
+ error?: string;
41
+ active2fa?: TwoFactorAuth[];
42
+ sessionId?: string;
43
+ registerUser?: {
44
+ email: string;
45
+ nickname: string;
46
+ salt?: string;
47
+ };
48
+ forgeData?: ForgeData;
49
+ googleOtpCode?: string;
50
+ googleUser?: {
51
+ email: string;
52
+ nickname: string;
53
+ };
54
+ sessionUser?: SessionUser;
55
+ CCRPublicKey?: {
56
+ publicKey: PublicKeyCredentialCreationOptions;
57
+ };
58
+ RCRPublicKey?: {
59
+ publicKey: PublicKeyCredentialRequestOptions;
60
+ };
61
+ credentialEmail?: string;
62
+ }
63
+ type SessionUser = {
64
+ createdAt: string;
65
+ device: string;
66
+ deviceCreatedAt: string;
67
+ email: string;
68
+ id: string;
69
+ lastLogin: string | null;
70
+ lastTransaction: string | null;
71
+ nickname: string;
72
+ status: string;
73
+ accessToken: string;
74
+ refreshToken: string;
75
+ };
76
+ export type TwoFactorAuth = {
77
+ id: string;
78
+ name: string | null;
79
+ twoFaTypeId: number;
80
+ };
81
+ export interface ForgeData {
82
+ tokenAddress: string;
83
+ name: string;
84
+ symbol: string;
85
+ contractType: string;
86
+ id: string;
87
+ mintMethod: string;
88
+ maxSupply: number;
89
+ endTime: string;
90
+ contractAddress: string;
91
+ chainId: number;
92
+ }
93
+ export interface SocialProvider {
94
+ id: string;
95
+ authProviderConfigId: string;
96
+ providerName: string;
97
+ clientId: string;
98
+ enabled?: boolean;
99
+ createdAt: string;
100
+ updatedAt?: string;
101
+ }
102
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -1,75 +1,31 @@
1
- export declare function hashUserInfo(userInfo: string): string;
2
- type KeyDerivationFunction = 'argon2d' | 'pbkdf2';
3
- export declare function generateSecureHash(password: string, salt: string, keyDerivationFunction?: KeyDerivationFunction): Promise<string>;
4
- export interface AloreAuthConfiguration {
5
- endpoint?: string;
6
- emailTemplate?: string;
7
- }
8
- type FetchWithProgressiveBackoffConfig = {
9
- maxAttempts?: number;
10
- initialDelay?: number;
11
- };
12
- type SessionUser = {
13
- createdAt: string;
14
- device: string;
15
- deviceCreatedAt: string;
16
- email: string;
17
- id: string;
18
- lastLogin: string | null;
19
- lastTransaction: string | null;
20
- nickname: string;
21
- status: string;
22
- accessToken: string;
23
- refreshToken: string;
24
- };
25
- export type TwoFactorAuth = {
26
- id: string;
27
- name: string | null;
28
- twoFaTypeId: number;
29
- };
30
- interface ForgeData {
31
- tokenAddress: string;
32
- name: string;
33
- symbol: string;
34
- contractType: string;
35
- id: string;
36
- mintMethod: string;
37
- maxSupply: number;
38
- endTime: string;
39
- contractAddress: string;
40
- chainId: number;
41
- }
42
- interface AuthMachineContext {
43
- salt?: string;
44
- error?: string;
45
- active2fa?: TwoFactorAuth[];
46
- sessionId?: string;
47
- registerUser?: {
48
- email: string;
49
- nickname: string;
50
- salt?: string;
51
- };
52
- forgeData?: ForgeData;
53
- googleOtpCode?: string;
54
- googleUser?: {
55
- email: string;
56
- nickname: string;
57
- };
58
- sessionUser?: SessionUser;
59
- CCRPublicKey?: {
60
- publicKey: PublicKeyCredentialCreationOptions;
61
- };
62
- RCRPublicKey?: {
63
- publicKey: PublicKeyCredentialRequestOptions;
64
- };
65
- credentialEmail?: string;
66
- }
1
+ import { AuthMachineContext, AuthProviderConfig, FetchWithProgressiveBackoffConfig, ForgeData } from '../types';
67
2
  export declare class AloreAuth {
68
- readonly apiKey: string;
69
- protected readonly endpoint: string;
3
+ protected readonly aloreBaseUrl: string;
70
4
  protected readonly emailTemplate: string;
71
- constructor(apiKey: string, options?: AloreAuthConfiguration);
5
+ protected readonly clientId: string;
6
+ constructor(clientId: string, aloreBaseUrl?: string, config?: AuthProviderConfig);
72
7
  services: {
8
+ healthCheck: () => Promise<{
9
+ data: boolean;
10
+ }>;
11
+ retrieveSalt: (context: AuthMachineContext, event: {
12
+ type: 'SELECT_PASSWORD';
13
+ payload: {
14
+ email: string;
15
+ };
16
+ }) => Promise<{
17
+ salt: string;
18
+ error?: undefined;
19
+ } | {
20
+ error: string;
21
+ salt?: undefined;
22
+ }>;
23
+ verifyEmail: (context: AuthMachineContext, event: {
24
+ type: 'VERIFY_EMAIL';
25
+ payload: {
26
+ secureCode: string;
27
+ };
28
+ }) => Promise<{}>;
73
29
  completeRegistration: (context: AuthMachineContext, event: {
74
30
  type: 'COMPLETE_REGISTRATION';
75
31
  payload: {
@@ -117,18 +73,6 @@ export declare class AloreAuth {
117
73
  salt?: undefined;
118
74
  sessionId?: undefined;
119
75
  }>;
120
- retrieveSalt: (context: AuthMachineContext, _event: {
121
- type: 'SELECT_PASSWORD';
122
- payload: {
123
- email: string;
124
- };
125
- }) => Promise<{
126
- salt: string;
127
- error?: undefined;
128
- } | {
129
- error: string;
130
- salt?: undefined;
131
- }>;
132
76
  sendCode: (context: AuthMachineContext, event: {
133
77
  type: 'SEND_CODE';
134
78
  payload: {
@@ -139,7 +83,27 @@ export declare class AloreAuth {
139
83
  } | {
140
84
  error?: undefined;
141
85
  }>;
142
- startRegisterPasskey: (_context: AuthMachineContext, event: {
86
+ verifyLogin: (_: AuthMachineContext, event: {
87
+ type: 'VERIFY_LOGIN';
88
+ payload: {
89
+ email: string;
90
+ device: string;
91
+ passwordHash: string;
92
+ isForgeClaim?: boolean | undefined;
93
+ locale?: string | undefined;
94
+ };
95
+ } | {
96
+ type: 'RESEND_CODE';
97
+ payload: {
98
+ email: string;
99
+ nickname?: string | undefined;
100
+ device?: string | undefined;
101
+ passwordHash?: string | undefined;
102
+ isForgeClaim?: boolean | undefined;
103
+ locale?: string | undefined;
104
+ };
105
+ }) => Promise<any>;
106
+ startRegisterPasskey: (context: AuthMachineContext, event: {
143
107
  type: 'START_PASSKEY_REGISTER';
144
108
  payload: {
145
109
  device: string;
@@ -164,6 +128,12 @@ export declare class AloreAuth {
164
128
  device: string;
165
129
  };
166
130
  }) => Promise<any>;
131
+ startPasskeyAuth: (context: AuthMachineContext, event: {
132
+ type: 'START_PASSKEY_LOGIN';
133
+ payload: {
134
+ email: string;
135
+ };
136
+ }) => Promise<any>;
167
137
  finishPasskeyAuth: (context: AuthMachineContext, event: {
168
138
  type: 'FINISH_PASSKEY_LOGIN';
169
139
  payload: {
@@ -195,32 +165,6 @@ export declare class AloreAuth {
195
165
  };
196
166
  };
197
167
  }) => Promise<any>;
198
- startPasskeyAuth: (_: AuthMachineContext, event: {
199
- type: 'START_PASSKEY_LOGIN';
200
- payload: {
201
- email: string;
202
- };
203
- }) => Promise<any>;
204
- verifyLogin: (_: AuthMachineContext, event: {
205
- type: 'VERIFY_LOGIN';
206
- payload: {
207
- email: string;
208
- device: string;
209
- passwordHash: string;
210
- isForgeClaim?: boolean | undefined;
211
- locale?: string | undefined;
212
- };
213
- } | {
214
- type: 'RESEND_CODE';
215
- payload: {
216
- email: string;
217
- nickname?: string | undefined;
218
- device?: string | undefined;
219
- passwordHash?: string | undefined;
220
- isForgeClaim?: boolean | undefined;
221
- locale?: string | undefined;
222
- };
223
- }) => Promise<any>;
224
168
  verify2faCode: (_context: AuthMachineContext, event: {
225
169
  type: 'CONFIRM_SW_CODE';
226
170
  payload: {
@@ -248,12 +192,6 @@ export declare class AloreAuth {
248
192
  secureCode: string;
249
193
  };
250
194
  }) => Promise<any>;
251
- verifyEmail: (context: AuthMachineContext, event: {
252
- type: 'VERIFY_EMAIL';
253
- payload: {
254
- secureCode: string;
255
- };
256
- }) => Promise<{}>;
257
195
  verifyEmail2fa: (context: AuthMachineContext, event: {
258
196
  type: 'VERIFY_EMAIL_2FA';
259
197
  payload: {
@@ -325,4 +263,3 @@ export declare class AloreAuth {
325
263
  fetchWithProgressiveBackoff(url: RequestInfo | URL, options?: RequestInit, config?: FetchWithProgressiveBackoffConfig): Promise<Response>;
326
264
  private verifyBackendStatus;
327
265
  }
328
- export {};
@@ -8,38 +8,55 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
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
- }
11
+ import { AloreAuthError, ErrorTypes } from './AuthError';
35
12
  const DEFAULT_URL = 'https://alpha-api.bealore.com/v1';
36
13
  export class AloreAuth {
37
- constructor(apiKey, options) {
38
- this.apiKey = apiKey;
14
+ constructor(clientId, aloreBaseUrl, config) {
39
15
  this.services = {
16
+ healthCheck: () => __awaiter(this, void 0, void 0, function* () {
17
+ try {
18
+ yield this.verifyBackendStatus();
19
+ }
20
+ catch (error) {
21
+ throw new AloreAuthError(ErrorTypes.SERVER_DOWN, 'Server is down');
22
+ }
23
+ return { data: true };
24
+ }),
25
+ // Email and password flow
26
+ retrieveSalt: (context, event) => __awaiter(this, void 0, void 0, function* () {
27
+ const { email } = event.payload;
28
+ const response = yield this.fetchWithProgressiveBackoff(`/auth/v1/salt/${email}`, {
29
+ headers: {
30
+ 'Content-Type': 'application/json',
31
+ },
32
+ });
33
+ if (response.ok) {
34
+ const salt = yield response.json();
35
+ return { salt };
36
+ }
37
+ return { error: response === null || response === void 0 ? void 0 : response.statusText };
38
+ }),
39
+ verifyEmail: (context, event) => __awaiter(this, void 0, void 0, function* () {
40
+ const { secureCode } = event.payload;
41
+ const response = yield this.fetchWithProgressiveBackoff('/auth/v1/registration-code-verification', {
42
+ method: 'POST',
43
+ headers: {
44
+ 'Content-Type': 'application/json',
45
+ },
46
+ body: JSON.stringify({
47
+ emailCode: secureCode,
48
+ sessionId: context.sessionId,
49
+ }),
50
+ });
51
+ if (response.ok) {
52
+ return {};
53
+ }
54
+ const data = yield response.json();
55
+ throw new Error((data === null || data === void 0 ? void 0 : data.message) || (data === null || data === void 0 ? void 0 : data.error) || data);
56
+ }),
40
57
  completeRegistration: (context, event) => __awaiter(this, void 0, void 0, function* () {
41
58
  const { email, nickname, passwordHash, device } = event.payload;
42
- const response = yield this.fetchWithProgressiveBackoff('/auth/account-registration', {
59
+ const response = yield this.fetchWithProgressiveBackoff('/auth/v1/account-registration', {
43
60
  method: 'POST',
44
61
  headers: {
45
62
  'Content-Type': 'application/json',
@@ -58,7 +75,7 @@ export class AloreAuth {
58
75
  }),
59
76
  confirmPassword: (context, event) => __awaiter(this, void 0, void 0, function* () {
60
77
  const { email, passwordHash } = event.payload;
61
- const response = yield this.fetchWithProgressiveBackoff(`/auth/password-creation`, {
78
+ const response = yield this.fetchWithProgressiveBackoff(`/auth/v1/password-creation`, {
62
79
  method: 'POST',
63
80
  headers: {
64
81
  'Content-Type': 'application/json',
@@ -75,7 +92,7 @@ export class AloreAuth {
75
92
  sendConfirmationEmail: (context, event) => __awaiter(this, void 0, void 0, function* () {
76
93
  const { email, nickname, locale } = event.payload;
77
94
  const searchParams = new URLSearchParams();
78
- const url = '/auth/confirmation-email';
95
+ const url = '/auth/v1/confirmation-email';
79
96
  if (locale) {
80
97
  searchParams.append('locale', locale);
81
98
  }
@@ -103,19 +120,6 @@ export class AloreAuth {
103
120
  }
104
121
  return { error: response === null || response === void 0 ? void 0 : response.statusText };
105
122
  }),
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
123
  sendCode: (context, event) => __awaiter(this, void 0, void 0, function* () {
120
124
  const { email } = event.payload;
121
125
  const response = yield this.fetchWithProgressiveBackoff(`/reset-password`, {
@@ -131,102 +135,125 @@ export class AloreAuth {
131
135
  return { error: response === null || response === void 0 ? void 0 : response.statusText };
132
136
  return {};
133
137
  }),
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`, {
138
+ verifyLogin: (_, event) => __awaiter(this, void 0, void 0, function* () {
139
+ var _a, _b;
140
+ const { email, passwordHash, device, locale } = event.payload;
141
+ const searchParams = new URLSearchParams();
142
+ const url = '/auth/v1/login-verification';
143
+ if (locale) {
144
+ searchParams.append('locale', locale);
145
+ }
146
+ if (this.emailTemplate !== '') {
147
+ searchParams.append('template', this.emailTemplate);
148
+ }
149
+ const response = yield this.fetchWithProgressiveBackoff(searchParams.size > 0 ? `${url}?${searchParams.toString()}` : url, {
137
150
  method: 'POST',
138
151
  headers: {
139
152
  'Content-Type': 'application/json',
140
153
  },
141
154
  body: JSON.stringify({
142
- userEmail: email,
143
- userNickname: nickname,
144
- userDevice: device,
155
+ email,
156
+ passwordHash,
157
+ device,
145
158
  }),
146
159
  });
147
- const data = yield startPasskeyRegistrationResponse.json();
148
- return data;
160
+ const data = yield response.json();
161
+ if (!response.ok) {
162
+ if (response.status === 403) {
163
+ return { active2fa: data };
164
+ }
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'))) {
166
+ return { error: data === null || data === void 0 ? void 0 : data.error };
167
+ }
168
+ throw new Error((data === null || data === void 0 ? void 0 : data.message) || (data === null || data === void 0 ? void 0 : data.error) || data);
169
+ }
170
+ else {
171
+ return data;
172
+ }
149
173
  }),
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`, {
174
+ // Passkey registration flow
175
+ startRegisterPasskey: (context, event) => __awaiter(this, void 0, void 0, function* () {
176
+ const { rpDomain } = context.authProviderConfigs || {};
177
+ const { email, nickname, device } = event.payload || context.registerUser;
178
+ const startPasskeyRegistrationResponse = yield this.fetchWithProgressiveBackoff('/auth/v1/account-registration-passkey', {
153
179
  method: 'POST',
154
180
  headers: {
155
181
  'Content-Type': 'application/json',
156
182
  },
157
183
  body: JSON.stringify({
158
- userEmail: email,
159
- userNickname: nickname,
184
+ userEmail: email || null,
185
+ userNickname: nickname || null,
160
186
  userDevice: device,
161
- passkeyRegistration,
162
- sessionId: context.sessionId,
187
+ rpOrigin: rpDomain,
163
188
  }),
164
189
  });
165
- const data = yield response.json();
166
- if (response.ok)
167
- return data;
190
+ const data = yield startPasskeyRegistrationResponse.json();
191
+ return data;
168
192
  }),
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`, {
193
+ finishRegisterPasskey: (context, event) => __awaiter(this, void 0, void 0, function* () {
194
+ const { rpDomain } = context.authProviderConfigs || {};
195
+ const { email, nickname, device, passkeyRegistration } = event.payload || {};
196
+ const response = yield this.fetchWithProgressiveBackoff('/auth/v1/account-registration-passkey-finish', {
172
197
  method: 'POST',
173
198
  headers: {
174
199
  'Content-Type': 'application/json',
175
200
  },
176
- body: JSON.stringify({ passkeyAuth, sessionId: context.sessionId }),
201
+ body: JSON.stringify({
202
+ userEmail: email || null,
203
+ userNickname: nickname || null,
204
+ userDevice: device,
205
+ passkeyRegistration,
206
+ sessionId: context.sessionId,
207
+ rpOrigin: rpDomain,
208
+ }),
177
209
  });
178
210
  const data = yield response.json();
179
211
  if (response.ok)
180
212
  return data;
181
213
  }),
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);
214
+ // Passkey login flow
215
+ startPasskeyAuth: (context, event) => __awaiter(this, void 0, void 0, function* () {
216
+ var _c;
217
+ const { rpDomain } = context.authProviderConfigs || {};
218
+ const email = (_c = event.payload) === null || _c === void 0 ? void 0 : _c.email;
219
+ const searchParams = new URLSearchParams();
220
+ const url = '/auth/v1/login-passkey';
221
+ if (rpDomain) {
222
+ searchParams.append('rp_origin', rpDomain);
223
+ }
224
+ if (email) {
225
+ searchParams.append('email', encodeURIComponent(email));
226
+ }
227
+ const urlWithParams = `${url}?${searchParams.toString()}`;
228
+ const startAuthResponse = yield this.fetchWithProgressiveBackoff(urlWithParams);
187
229
  const data = yield startAuthResponse.json();
188
230
  if (startAuthResponse.ok)
189
231
  return data;
232
+ throw new Error(data.message || data.error || data);
190
233
  }),
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, {
234
+ finishPasskeyAuth: (context, event) => __awaiter(this, void 0, void 0, function* () {
235
+ const { rpDomain } = context.authProviderConfigs || {};
236
+ const { passkeyAuth } = event.payload;
237
+ const response = yield this.fetchWithProgressiveBackoff(`/auth/v1/login-passkey-finish`, {
203
238
  method: 'POST',
204
239
  headers: {
205
240
  'Content-Type': 'application/json',
206
241
  },
207
242
  body: JSON.stringify({
208
- email,
209
- passwordHash,
210
- device,
243
+ passkeyAuth,
244
+ sessionId: context.sessionId,
245
+ rpOrigin: rpDomain,
211
246
  }),
212
247
  });
213
248
  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 {
249
+ if (response.ok)
224
250
  return data;
225
- }
251
+ throw new AloreAuthError(ErrorTypes.FAILED_TO_FETCH, data.message || data.error || data);
226
252
  }),
253
+ // Hardware 2FA flow
227
254
  verify2faCode: (_context, event) => __awaiter(this, void 0, void 0, function* () {
228
255
  const { email, passwordHash, device, otp } = event.payload;
229
- const response = yield this.fetchWithProgressiveBackoff('/auth/sw-2fa-verification', {
256
+ const response = yield this.fetchWithProgressiveBackoff('/auth/v1/sw-2fa-verification', {
230
257
  method: 'POST',
231
258
  headers: {
232
259
  'Content-Type': 'application/json',
@@ -245,7 +272,7 @@ export class AloreAuth {
245
272
  }),
246
273
  authenticateWebauthn: (context, event) => __awaiter(this, void 0, void 0, function* () {
247
274
  const { email, passwordHash, device, authId } = event.payload;
248
- const optionsResponse = yield this.fetchWithProgressiveBackoff('/auth/hw-2fa-start-verification', {
275
+ const optionsResponse = yield this.fetchWithProgressiveBackoff('/auth/v1/hw-2fa-start-verification', {
249
276
  method: 'POST',
250
277
  headers: {
251
278
  'Content-Type': 'application/json',
@@ -263,7 +290,7 @@ export class AloreAuth {
263
290
  const credential = yield startAuthentication(optionsData.requestChallengeResponse.publicKey).catch((err) => {
264
291
  throw new Error(err);
265
292
  });
266
- const response = yield this.fetchWithProgressiveBackoff('/auth/hw-2fa-finish-verification', {
293
+ const response = yield this.fetchWithProgressiveBackoff('/auth/v1/hw-2fa-finish-verification', {
267
294
  method: 'POST',
268
295
  headers: {
269
296
  'Content-Type': 'application/json',
@@ -283,7 +310,7 @@ export class AloreAuth {
283
310
  }),
284
311
  verifyDeviceCode: (context, event) => __awaiter(this, void 0, void 0, function* () {
285
312
  const { email, passwordHash, device, secureCode } = event.payload;
286
- const response = yield this.fetchWithProgressiveBackoff('/auth/device-ownership-verification', {
313
+ const response = yield this.fetchWithProgressiveBackoff('/auth/v1/device-ownership-verification', {
287
314
  method: 'POST',
288
315
  headers: {
289
316
  'Content-Type': 'application/json',
@@ -301,29 +328,9 @@ export class AloreAuth {
301
328
  return data;
302
329
  throw new Error(data.message || data.error || 'Authentication failed');
303
330
  }),
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
331
  verifyEmail2fa: (context, event) => __awaiter(this, void 0, void 0, function* () {
325
332
  const { email, passwordHash, secureCode } = event.payload;
326
- const response = yield this.fetchWithProgressiveBackoff('/auth/email-2fa-verification', {
333
+ const response = yield this.fetchWithProgressiveBackoff('/auth/v1/email-2fa-verification', {
327
334
  method: 'POST',
328
335
  body: JSON.stringify({
329
336
  email,
@@ -342,7 +349,7 @@ export class AloreAuth {
342
349
  }),
343
350
  verifyEmailEligibility: (_, event) => __awaiter(this, void 0, void 0, function* () {
344
351
  const { email } = event;
345
- const response = yield this.fetchWithProgressiveBackoff('/auth/email-eligibility-verification', {
352
+ const response = yield this.fetchWithProgressiveBackoff('/auth/v1/email-eligibility-verification', {
346
353
  method: 'POST',
347
354
  headers: {
348
355
  'Content-Type': 'application/json',
@@ -358,7 +365,7 @@ export class AloreAuth {
358
365
  }),
359
366
  verifyClaimNftEmail2fa: (context, event) => __awaiter(this, void 0, void 0, function* () {
360
367
  const { email, emailCode } = event.payload;
361
- const response = yield this.fetchWithProgressiveBackoff('/auth/eligible-email-code-verification', {
368
+ const response = yield this.fetchWithProgressiveBackoff('/auth/v1/eligible-email-code-verification', {
362
369
  method: 'POST',
363
370
  body: JSON.stringify({
364
371
  email,
@@ -382,9 +389,10 @@ export class AloreAuth {
382
389
  }
383
390
  return data;
384
391
  }),
392
+ // Google login flow
385
393
  googleLogin: (_, event) => __awaiter(this, void 0, void 0, function* () {
386
394
  const { googleToken } = event;
387
- const response = yield this.fetchWithProgressiveBackoff('/auth/google-login', {
395
+ const response = yield this.fetchWithProgressiveBackoff('/auth/v1/google-login', {
388
396
  method: 'POST',
389
397
  headers: {
390
398
  'Content-Type': 'application/json',
@@ -422,7 +430,7 @@ export class AloreAuth {
422
430
  }),
423
431
  verifyGoogleLogin: (context, event) => __awaiter(this, void 0, void 0, function* () {
424
432
  const { email, passwordHash, otp } = event.payload;
425
- const response = yield this.fetchWithProgressiveBackoff('/auth/google-2fa-verification', {
433
+ const response = yield this.fetchWithProgressiveBackoff('/auth/v1/google-2fa-verification', {
426
434
  method: 'POST',
427
435
  body: JSON.stringify({
428
436
  email,
@@ -440,10 +448,11 @@ export class AloreAuth {
440
448
  throw new Error(data.message || data.error || 'Authentication failed');
441
449
  }),
442
450
  };
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) || '';
451
+ if (!clientId)
452
+ throw new AloreAuthError(ErrorTypes.CLIENT_ID_REQUIRED, 'Client ID is required');
453
+ this.clientId = clientId;
454
+ this.aloreBaseUrl = aloreBaseUrl || DEFAULT_URL;
455
+ this.emailTemplate = (config === null || config === void 0 ? void 0 : config.emailTemplate) || '';
447
456
  }
448
457
  // eslint-disable-next-line class-methods-use-this
449
458
  delay(ms) {
@@ -462,7 +471,7 @@ export class AloreAuth {
462
471
  let attempt = 0;
463
472
  let delayValue = initialDelay;
464
473
  // 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 }) });
474
+ 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' }) });
466
475
  while (attempt < maxAttempts) {
467
476
  if (attempt > 0) {
468
477
  // eslint-disable-next-line no-await-in-loop, no-promise-executor-return, no-loop-func
@@ -472,7 +481,7 @@ export class AloreAuth {
472
481
  attempt += 1;
473
482
  try {
474
483
  // eslint-disable-next-line no-await-in-loop
475
- const response = yield fetch(new URL(`${this.endpoint}${url}`), init);
484
+ const response = yield fetch(new URL(`${this.aloreBaseUrl}${url}`), init);
476
485
  if (response.ok || attempt === maxAttempts || response.status !== 500) {
477
486
  return response;
478
487
  }
@@ -496,7 +505,7 @@ export class AloreAuth {
496
505
  verifyBackendStatus() {
497
506
  return __awaiter(this, void 0, void 0, function* () {
498
507
  try {
499
- const res = yield fetch(`${this.endpoint}/health-check`);
508
+ const res = yield fetch(`${this.aloreBaseUrl}/health-check`);
500
509
  if (!res.ok) {
501
510
  throw new Error('Failed to fetch');
502
511
  }
@@ -0,0 +1,29 @@
1
+ export declare enum ErrorCodes {
2
+ BAD_REQUEST = 400,
3
+ FORBIDDEN = 403,
4
+ TOO_MANY_REQUESTS = 429
5
+ }
6
+ export declare enum ErrorTypes {
7
+ CLIENT_ID_REQUIRED = "CLIENT_ID_REQUIRED",
8
+ PASSKEY_NOT_SUPPORTED = "PASSKEY_NOT_SUPPORTED",
9
+ USER_ALREADY_EXISTS = "USER_ALREADY_EXISTS",
10
+ FAILED_TO_FETCH = "FAILED_TO_FETCH",
11
+ SERVER_DOWN = "SERVER_DOWN",
12
+ BAD_RESPONSE = "BAD_RESPONSE",
13
+ UNKNOWN_ERROR = "UNKNOWN_ERROR",
14
+ INVALID_CREDENTIALS = "INVALID_CREDENTIALS",
15
+ WRONG_2FA_CODE = "WRONG_2FA_CODE",
16
+ INVALID_EMAIL_PASSWORD = "INVALID_EMAIL_PASSWORD",
17
+ PUBLIC_KEY_CREATION_OPTIONS_UNDEFINED = "PUBLIC_KEY_CREATION_OPTIONS_UNDEFINED",
18
+ CREATE_SECRET_FROM_CREDENTIAL_FAILED = "CREATE_SECRET_FROM_CREDENTIAL_FAILED",
19
+ PASSKEY_GET_ERROR = "PASSKEY_GET_ERROR",
20
+ PASSKEY_CREATE_ERROR = "PASSKEY_CREATE_ERROR",
21
+ PRF_EXTENSION_NOT_SUPPORTED = "PRF_EXTENSION_NOT_SUPPORTED",
22
+ LARGE_BLOB_EXTENSION_NOT_SUPPORTED = "LARGE_BLOB_EXTENSION_NOT_SUPPORTED",
23
+ TOO_MANY_REQUESTS = "TOO_MANY_REQUESTS"
24
+ }
25
+ export declare class AloreAuthError extends Error {
26
+ type: ErrorTypes;
27
+ code?: number;
28
+ constructor(type: ErrorTypes, message: string, code?: number);
29
+ }
@@ -0,0 +1,36 @@
1
+ /* eslint-disable no-unused-vars */
2
+ export var ErrorCodes;
3
+ (function (ErrorCodes) {
4
+ ErrorCodes[ErrorCodes["BAD_REQUEST"] = 400] = "BAD_REQUEST";
5
+ ErrorCodes[ErrorCodes["FORBIDDEN"] = 403] = "FORBIDDEN";
6
+ ErrorCodes[ErrorCodes["TOO_MANY_REQUESTS"] = 429] = "TOO_MANY_REQUESTS";
7
+ })(ErrorCodes || (ErrorCodes = {}));
8
+ export var ErrorTypes;
9
+ (function (ErrorTypes) {
10
+ ErrorTypes["CLIENT_ID_REQUIRED"] = "CLIENT_ID_REQUIRED";
11
+ ErrorTypes["PASSKEY_NOT_SUPPORTED"] = "PASSKEY_NOT_SUPPORTED";
12
+ ErrorTypes["USER_ALREADY_EXISTS"] = "USER_ALREADY_EXISTS";
13
+ ErrorTypes["FAILED_TO_FETCH"] = "FAILED_TO_FETCH";
14
+ ErrorTypes["SERVER_DOWN"] = "SERVER_DOWN";
15
+ ErrorTypes["BAD_RESPONSE"] = "BAD_RESPONSE";
16
+ ErrorTypes["UNKNOWN_ERROR"] = "UNKNOWN_ERROR";
17
+ ErrorTypes["INVALID_CREDENTIALS"] = "INVALID_CREDENTIALS";
18
+ ErrorTypes["WRONG_2FA_CODE"] = "WRONG_2FA_CODE";
19
+ ErrorTypes["INVALID_EMAIL_PASSWORD"] = "INVALID_EMAIL_PASSWORD";
20
+ ErrorTypes["PUBLIC_KEY_CREATION_OPTIONS_UNDEFINED"] = "PUBLIC_KEY_CREATION_OPTIONS_UNDEFINED";
21
+ ErrorTypes["CREATE_SECRET_FROM_CREDENTIAL_FAILED"] = "CREATE_SECRET_FROM_CREDENTIAL_FAILED";
22
+ ErrorTypes["PASSKEY_GET_ERROR"] = "PASSKEY_GET_ERROR";
23
+ ErrorTypes["PASSKEY_CREATE_ERROR"] = "PASSKEY_CREATE_ERROR";
24
+ ErrorTypes["PRF_EXTENSION_NOT_SUPPORTED"] = "PRF_EXTENSION_NOT_SUPPORTED";
25
+ ErrorTypes["LARGE_BLOB_EXTENSION_NOT_SUPPORTED"] = "LARGE_BLOB_EXTENSION_NOT_SUPPORTED";
26
+ ErrorTypes["TOO_MANY_REQUESTS"] = "TOO_MANY_REQUESTS";
27
+ })(ErrorTypes || (ErrorTypes = {}));
28
+ export class AloreAuthError extends Error {
29
+ constructor(type, message, code) {
30
+ super(message);
31
+ this.name = 'AloreAuthError';
32
+ this.type = type;
33
+ this.code = code;
34
+ Object.setPrototypeOf(this, AloreAuthError.prototype);
35
+ }
36
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alore/auth-react-sdk",
3
- "version": "1.0.0-alpha",
3
+ "version": "1.0.2-alpha",
4
4
  "repository": "https://github.com/0xCarbon/alore-js",
5
5
  "description": "SDK for Alore Auth",
6
6
  "main": "dist/index.js",
@@ -14,6 +14,10 @@
14
14
  "default": "./dist/index.js"
15
15
  }
16
16
  },
17
+ "scripts": {
18
+ "prepare": "pnpm build",
19
+ "build": "rm -rf dist/* && tsc"
20
+ },
17
21
  "author": "0xCarbon",
18
22
  "license": "LGPL-2.1-only",
19
23
  "engines": {
@@ -32,8 +36,5 @@
32
36
  "@types/node": "20.4.8",
33
37
  "typescript": "5.4.5"
34
38
  },
35
- "packageManager": "pnpm@8.15.7+sha512.c85cd21b6da10332156b1ca2aa79c0a61ee7ad2eb0453b88ab299289e9e8ca93e6091232b25c07cbf61f6df77128d9c849e5c9ac6e44854dbd211c49f3a67adc",
36
- "scripts": {
37
- "build": "rm -rf dist/* && tsc"
38
- }
39
- }
39
+ "packageManager": "pnpm@8.15.7+sha512.c85cd21b6da10332156b1ca2aa79c0a61ee7ad2eb0453b88ab299289e9e8ca93e6091232b25c07cbf61f6df77128d9c849e5c9ac6e44854dbd211c49f3a67adc"
40
+ }