@nauth-toolkit/client 0.1.3
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/LICENSE +90 -0
- package/README.md +92 -0
- package/dist/angular/index.cjs +1958 -0
- package/dist/angular/index.cjs.map +1 -0
- package/dist/angular/index.d.mts +623 -0
- package/dist/angular/index.d.ts +623 -0
- package/dist/angular/index.mjs +1926 -0
- package/dist/angular/index.mjs.map +1 -0
- package/dist/index.cjs +1473 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.mts +638 -0
- package/dist/index.d.ts +638 -0
- package/dist/index.mjs +1433 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +62 -0
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,1473 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
21
|
+
|
|
22
|
+
// src/index.ts
|
|
23
|
+
var index_exports = {};
|
|
24
|
+
__export(index_exports, {
|
|
25
|
+
AuthAuditEventType: () => AuthAuditEventType,
|
|
26
|
+
AuthChallenge: () => AuthChallenge,
|
|
27
|
+
BrowserStorage: () => BrowserStorage,
|
|
28
|
+
EventEmitter: () => EventEmitter,
|
|
29
|
+
FetchAdapter: () => FetchAdapter,
|
|
30
|
+
InMemoryStorage: () => InMemoryStorage,
|
|
31
|
+
NAuthClient: () => NAuthClient,
|
|
32
|
+
NAuthClientError: () => NAuthClientError,
|
|
33
|
+
NAuthErrorCode: () => NAuthErrorCode,
|
|
34
|
+
defaultEndpoints: () => defaultEndpoints,
|
|
35
|
+
getChallengeInstructions: () => getChallengeInstructions,
|
|
36
|
+
getMFAMethod: () => getMFAMethod,
|
|
37
|
+
getMaskedDestination: () => getMaskedDestination,
|
|
38
|
+
isOTPChallenge: () => isOTPChallenge,
|
|
39
|
+
requiresPhoneCollection: () => requiresPhoneCollection,
|
|
40
|
+
resolveConfig: () => resolveConfig
|
|
41
|
+
});
|
|
42
|
+
module.exports = __toCommonJS(index_exports);
|
|
43
|
+
|
|
44
|
+
// src/types/auth.types.ts
|
|
45
|
+
var AuthChallenge = /* @__PURE__ */ ((AuthChallenge2) => {
|
|
46
|
+
AuthChallenge2["VERIFY_EMAIL"] = "VERIFY_EMAIL";
|
|
47
|
+
AuthChallenge2["VERIFY_PHONE"] = "VERIFY_PHONE";
|
|
48
|
+
AuthChallenge2["MFA_REQUIRED"] = "MFA_REQUIRED";
|
|
49
|
+
AuthChallenge2["MFA_SETUP_REQUIRED"] = "MFA_SETUP_REQUIRED";
|
|
50
|
+
AuthChallenge2["FORCE_CHANGE_PASSWORD"] = "FORCE_CHANGE_PASSWORD";
|
|
51
|
+
return AuthChallenge2;
|
|
52
|
+
})(AuthChallenge || {});
|
|
53
|
+
|
|
54
|
+
// src/types/error.types.ts
|
|
55
|
+
var NAuthErrorCode = /* @__PURE__ */ ((NAuthErrorCode2) => {
|
|
56
|
+
NAuthErrorCode2["AUTH_INVALID_CREDENTIALS"] = "AUTH_INVALID_CREDENTIALS";
|
|
57
|
+
NAuthErrorCode2["AUTH_ACCOUNT_LOCKED"] = "AUTH_ACCOUNT_LOCKED";
|
|
58
|
+
NAuthErrorCode2["AUTH_ACCOUNT_INACTIVE"] = "AUTH_ACCOUNT_INACTIVE";
|
|
59
|
+
NAuthErrorCode2["AUTH_TOKEN_EXPIRED"] = "AUTH_TOKEN_EXPIRED";
|
|
60
|
+
NAuthErrorCode2["AUTH_TOKEN_INVALID"] = "AUTH_TOKEN_INVALID";
|
|
61
|
+
NAuthErrorCode2["AUTH_BEARER_NOT_ALLOWED"] = "AUTH_BEARER_NOT_ALLOWED";
|
|
62
|
+
NAuthErrorCode2["AUTH_COOKIES_NOT_ALLOWED"] = "AUTH_COOKIES_NOT_ALLOWED";
|
|
63
|
+
NAuthErrorCode2["AUTH_CSRF_TOKEN_INVALID"] = "AUTH_CSRF_TOKEN_INVALID";
|
|
64
|
+
NAuthErrorCode2["AUTH_CSRF_TOKEN_MISSING"] = "AUTH_CSRF_TOKEN_MISSING";
|
|
65
|
+
NAuthErrorCode2["AUTH_TOKEN_REUSE_DETECTED"] = "AUTH_TOKEN_REUSE_DETECTED";
|
|
66
|
+
NAuthErrorCode2["AUTH_SESSION_NOT_FOUND"] = "AUTH_SESSION_NOT_FOUND";
|
|
67
|
+
NAuthErrorCode2["AUTH_SESSION_EXPIRED"] = "AUTH_SESSION_EXPIRED";
|
|
68
|
+
NAuthErrorCode2["SIGNUP_DISABLED"] = "SIGNUP_DISABLED";
|
|
69
|
+
NAuthErrorCode2["SIGNUP_EMAIL_EXISTS"] = "SIGNUP_EMAIL_EXISTS";
|
|
70
|
+
NAuthErrorCode2["SIGNUP_USERNAME_EXISTS"] = "SIGNUP_USERNAME_EXISTS";
|
|
71
|
+
NAuthErrorCode2["SIGNUP_PHONE_EXISTS"] = "SIGNUP_PHONE_EXISTS";
|
|
72
|
+
NAuthErrorCode2["SIGNUP_WEAK_PASSWORD"] = "SIGNUP_WEAK_PASSWORD";
|
|
73
|
+
NAuthErrorCode2["SIGNUP_PHONE_REQUIRED"] = "SIGNUP_PHONE_REQUIRED";
|
|
74
|
+
NAuthErrorCode2["SIGNUP_NOT_ALLOWED"] = "SIGNUP_NOT_ALLOWED";
|
|
75
|
+
NAuthErrorCode2["VERIFY_CODE_INVALID"] = "VERIFY_CODE_INVALID";
|
|
76
|
+
NAuthErrorCode2["VERIFY_CODE_EXPIRED"] = "VERIFY_CODE_EXPIRED";
|
|
77
|
+
NAuthErrorCode2["VERIFY_TOO_MANY_ATTEMPTS"] = "VERIFY_TOO_MANY_ATTEMPTS";
|
|
78
|
+
NAuthErrorCode2["VERIFY_ALREADY_VERIFIED"] = "VERIFY_ALREADY_VERIFIED";
|
|
79
|
+
NAuthErrorCode2["MFA_SETUP_REQUIRED"] = "MFA_SETUP_REQUIRED";
|
|
80
|
+
NAuthErrorCode2["RATE_LIMIT_SMS"] = "RATE_LIMIT_SMS";
|
|
81
|
+
NAuthErrorCode2["RATE_LIMIT_EMAIL"] = "RATE_LIMIT_EMAIL";
|
|
82
|
+
NAuthErrorCode2["RATE_LIMIT_LOGIN"] = "RATE_LIMIT_LOGIN";
|
|
83
|
+
NAuthErrorCode2["RATE_LIMIT_RESEND"] = "RATE_LIMIT_RESEND";
|
|
84
|
+
NAuthErrorCode2["SOCIAL_TOKEN_INVALID"] = "SOCIAL_TOKEN_INVALID";
|
|
85
|
+
NAuthErrorCode2["SOCIAL_ACCOUNT_LINKED"] = "SOCIAL_ACCOUNT_LINKED";
|
|
86
|
+
NAuthErrorCode2["SOCIAL_CONFIG_MISSING"] = "SOCIAL_CONFIG_MISSING";
|
|
87
|
+
NAuthErrorCode2["SOCIAL_EMAIL_REQUIRED"] = "SOCIAL_EMAIL_REQUIRED";
|
|
88
|
+
NAuthErrorCode2["SOCIAL_ACCOUNT_NOT_FOUND"] = "SOCIAL_ACCOUNT_NOT_FOUND";
|
|
89
|
+
NAuthErrorCode2["CHALLENGE_EXPIRED"] = "CHALLENGE_EXPIRED";
|
|
90
|
+
NAuthErrorCode2["CHALLENGE_INVALID"] = "CHALLENGE_INVALID";
|
|
91
|
+
NAuthErrorCode2["CHALLENGE_TYPE_MISMATCH"] = "CHALLENGE_TYPE_MISMATCH";
|
|
92
|
+
NAuthErrorCode2["CHALLENGE_MAX_ATTEMPTS"] = "CHALLENGE_MAX_ATTEMPTS";
|
|
93
|
+
NAuthErrorCode2["CHALLENGE_ALREADY_COMPLETED"] = "CHALLENGE_ALREADY_COMPLETED";
|
|
94
|
+
NAuthErrorCode2["VALIDATION_FAILED"] = "VALIDATION_FAILED";
|
|
95
|
+
NAuthErrorCode2["VALIDATION_INVALID_PHONE"] = "VALIDATION_INVALID_PHONE";
|
|
96
|
+
NAuthErrorCode2["VALIDATION_INVALID_EMAIL"] = "VALIDATION_INVALID_EMAIL";
|
|
97
|
+
NAuthErrorCode2["VALIDATION_INVALID_PASSWORD"] = "VALIDATION_INVALID_PASSWORD";
|
|
98
|
+
NAuthErrorCode2["PASSWORD_INCORRECT"] = "PASSWORD_INCORRECT";
|
|
99
|
+
NAuthErrorCode2["PASSWORD_REUSED"] = "PASSWORD_REUSED";
|
|
100
|
+
NAuthErrorCode2["PASSWORD_CHANGE_NOT_ALLOWED"] = "PASSWORD_CHANGE_NOT_ALLOWED";
|
|
101
|
+
NAuthErrorCode2["SIGNIN_BLOCKED_HIGH_RISK"] = "SIGNIN_BLOCKED_HIGH_RISK";
|
|
102
|
+
NAuthErrorCode2["RESOURCE_NOT_FOUND"] = "RESOURCE_NOT_FOUND";
|
|
103
|
+
NAuthErrorCode2["FORBIDDEN"] = "FORBIDDEN";
|
|
104
|
+
NAuthErrorCode2["INTERNAL_ERROR"] = "INTERNAL_ERROR";
|
|
105
|
+
NAuthErrorCode2["SERVICE_UNAVAILABLE"] = "SERVICE_UNAVAILABLE";
|
|
106
|
+
return NAuthErrorCode2;
|
|
107
|
+
})(NAuthErrorCode || {});
|
|
108
|
+
|
|
109
|
+
// src/types/audit.types.ts
|
|
110
|
+
var AuthAuditEventType = /* @__PURE__ */ ((AuthAuditEventType2) => {
|
|
111
|
+
AuthAuditEventType2["LOGIN_SUCCESS"] = "LOGIN_SUCCESS";
|
|
112
|
+
AuthAuditEventType2["LOGIN_FAILED"] = "LOGIN_FAILED";
|
|
113
|
+
AuthAuditEventType2["LOGOUT"] = "LOGOUT";
|
|
114
|
+
AuthAuditEventType2["TOKEN_REFRESH"] = "TOKEN_REFRESH";
|
|
115
|
+
AuthAuditEventType2["TOKEN_REVOKED"] = "TOKEN_REVOKED";
|
|
116
|
+
AuthAuditEventType2["SIGNUP_SUCCESS"] = "SIGNUP_SUCCESS";
|
|
117
|
+
AuthAuditEventType2["SIGNUP_FAILED"] = "SIGNUP_FAILED";
|
|
118
|
+
AuthAuditEventType2["EMAIL_VERIFIED"] = "EMAIL_VERIFIED";
|
|
119
|
+
AuthAuditEventType2["PHONE_VERIFIED"] = "PHONE_VERIFIED";
|
|
120
|
+
AuthAuditEventType2["VERIFICATION_FAILED"] = "VERIFICATION_FAILED";
|
|
121
|
+
AuthAuditEventType2["MFA_ENABLED"] = "MFA_ENABLED";
|
|
122
|
+
AuthAuditEventType2["MFA_DISABLED"] = "MFA_DISABLED";
|
|
123
|
+
AuthAuditEventType2["MFA_VERIFIED"] = "MFA_VERIFIED";
|
|
124
|
+
AuthAuditEventType2["MFA_FAILED"] = "MFA_FAILED";
|
|
125
|
+
AuthAuditEventType2["MFA_BACKUP_CODE_USED"] = "MFA_BACKUP_CODE_USED";
|
|
126
|
+
AuthAuditEventType2["PASSWORD_CHANGED"] = "PASSWORD_CHANGED";
|
|
127
|
+
AuthAuditEventType2["PASSWORD_RESET_REQUESTED"] = "PASSWORD_RESET_REQUESTED";
|
|
128
|
+
AuthAuditEventType2["PASSWORD_RESET_COMPLETED"] = "PASSWORD_RESET_COMPLETED";
|
|
129
|
+
AuthAuditEventType2["ACCOUNT_LOCKED"] = "ACCOUNT_LOCKED";
|
|
130
|
+
AuthAuditEventType2["ACCOUNT_UNLOCKED"] = "ACCOUNT_UNLOCKED";
|
|
131
|
+
AuthAuditEventType2["SUSPICIOUS_ACTIVITY"] = "SUSPICIOUS_ACTIVITY";
|
|
132
|
+
AuthAuditEventType2["ADAPTIVE_MFA_TRIGGERED"] = "ADAPTIVE_MFA_TRIGGERED";
|
|
133
|
+
AuthAuditEventType2["SOCIAL_LINK_SUCCESS"] = "SOCIAL_LINK_SUCCESS";
|
|
134
|
+
AuthAuditEventType2["SOCIAL_LINK_FAILED"] = "SOCIAL_LINK_FAILED";
|
|
135
|
+
AuthAuditEventType2["SOCIAL_UNLINK"] = "SOCIAL_UNLINK";
|
|
136
|
+
return AuthAuditEventType2;
|
|
137
|
+
})(AuthAuditEventType || {});
|
|
138
|
+
|
|
139
|
+
// src/core/config.ts
|
|
140
|
+
var defaultEndpoints = {
|
|
141
|
+
login: "/login",
|
|
142
|
+
signup: "/signup",
|
|
143
|
+
logout: "/logout",
|
|
144
|
+
logoutAll: "/logout/all",
|
|
145
|
+
refresh: "/refresh",
|
|
146
|
+
respondChallenge: "/respond-challenge",
|
|
147
|
+
resendCode: "/challenge/resend",
|
|
148
|
+
getSetupData: "/challenge/setup-data",
|
|
149
|
+
getChallengeData: "/challenge/challenge-data",
|
|
150
|
+
profile: "/profile",
|
|
151
|
+
changePassword: "/change-password",
|
|
152
|
+
requestPasswordChange: "/request-password-change",
|
|
153
|
+
mfaStatus: "/mfa/status",
|
|
154
|
+
mfaDevices: "/mfa/devices",
|
|
155
|
+
mfaSetupData: "/mfa/setup-data",
|
|
156
|
+
mfaVerifySetup: "/mfa/verify-setup",
|
|
157
|
+
mfaRemove: "/mfa/method",
|
|
158
|
+
mfaPreferred: "/mfa/preferred-method",
|
|
159
|
+
mfaBackupCodes: "/mfa/backup-codes/generate",
|
|
160
|
+
mfaExemption: "/mfa/exemption",
|
|
161
|
+
socialAuthUrl: "/social/auth-url",
|
|
162
|
+
socialCallback: "/social/callback",
|
|
163
|
+
socialLinked: "/social/linked",
|
|
164
|
+
socialLink: "/social/link",
|
|
165
|
+
socialUnlink: "/social/unlink",
|
|
166
|
+
socialVerify: "/social/:provider/verify",
|
|
167
|
+
trustDevice: "/trust-device",
|
|
168
|
+
isTrustedDevice: "/is-trusted-device",
|
|
169
|
+
auditHistory: "/audit/history",
|
|
170
|
+
updateProfile: "/profile"
|
|
171
|
+
};
|
|
172
|
+
var resolveConfig = (config, defaultAdapter) => {
|
|
173
|
+
const resolvedEndpoints = {
|
|
174
|
+
...defaultEndpoints,
|
|
175
|
+
...config.endpoints ?? {}
|
|
176
|
+
};
|
|
177
|
+
return {
|
|
178
|
+
...config,
|
|
179
|
+
csrf: {
|
|
180
|
+
cookieName: config.csrf?.cookieName ?? "nauth_csrf_token",
|
|
181
|
+
headerName: config.csrf?.headerName ?? "x-csrf-token"
|
|
182
|
+
},
|
|
183
|
+
deviceTrust: {
|
|
184
|
+
headerName: config.deviceTrust?.headerName ?? "X-Device-Token",
|
|
185
|
+
storageKey: config.deviceTrust?.storageKey ?? "nauth_device_token"
|
|
186
|
+
},
|
|
187
|
+
headers: config.headers ?? {},
|
|
188
|
+
timeout: config.timeout ?? 3e4,
|
|
189
|
+
endpoints: resolvedEndpoints,
|
|
190
|
+
storage: config.storage,
|
|
191
|
+
httpAdapter: config.httpAdapter ?? defaultAdapter
|
|
192
|
+
};
|
|
193
|
+
};
|
|
194
|
+
|
|
195
|
+
// src/core/errors.ts
|
|
196
|
+
var NAuthClientError = class _NAuthClientError extends Error {
|
|
197
|
+
/**
|
|
198
|
+
* Create a new client error.
|
|
199
|
+
*
|
|
200
|
+
* @param code - Error code from NAuthErrorCode enum
|
|
201
|
+
* @param message - Human-readable error message
|
|
202
|
+
* @param options - Optional metadata including details, statusCode, timestamp, and network error flag
|
|
203
|
+
*/
|
|
204
|
+
constructor(code, message, options) {
|
|
205
|
+
super(message);
|
|
206
|
+
__publicField(this, "code");
|
|
207
|
+
__publicField(this, "details");
|
|
208
|
+
__publicField(this, "statusCode");
|
|
209
|
+
__publicField(this, "timestamp");
|
|
210
|
+
__publicField(this, "isNetworkError");
|
|
211
|
+
this.code = code;
|
|
212
|
+
this.details = options?.details;
|
|
213
|
+
this.statusCode = options?.statusCode;
|
|
214
|
+
this.timestamp = options?.timestamp || (/* @__PURE__ */ new Date()).toISOString();
|
|
215
|
+
this.isNetworkError = options?.isNetworkError ?? false;
|
|
216
|
+
this.name = "NAuthClientError";
|
|
217
|
+
Object.setPrototypeOf(this, _NAuthClientError.prototype);
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Check if error matches a specific error code.
|
|
221
|
+
*
|
|
222
|
+
* @param code - Error code to check against
|
|
223
|
+
* @returns True if the error code matches
|
|
224
|
+
*
|
|
225
|
+
* @example
|
|
226
|
+
* ```typescript
|
|
227
|
+
* if (error.isCode(NAuthErrorCode.RATE_LIMIT_SMS)) {
|
|
228
|
+
* // Handle SMS rate limit
|
|
229
|
+
* }
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
232
|
+
isCode(code) {
|
|
233
|
+
return this.code === code;
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Get error details/metadata.
|
|
237
|
+
*
|
|
238
|
+
* @returns Error details object or undefined
|
|
239
|
+
*
|
|
240
|
+
* @example
|
|
241
|
+
* ```typescript
|
|
242
|
+
* const details = error.getDetails();
|
|
243
|
+
* if (details?.retryAfter) {
|
|
244
|
+
* console.log(`Retry after ${details.retryAfter} seconds`);
|
|
245
|
+
* }
|
|
246
|
+
* ```
|
|
247
|
+
*/
|
|
248
|
+
getDetails() {
|
|
249
|
+
return this.details;
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Get the error code.
|
|
253
|
+
*
|
|
254
|
+
* @returns The error code enum value
|
|
255
|
+
*/
|
|
256
|
+
getCode() {
|
|
257
|
+
return this.code;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Serialize error to JSON object.
|
|
261
|
+
*
|
|
262
|
+
* @returns Plain object representation
|
|
263
|
+
*
|
|
264
|
+
* @example
|
|
265
|
+
* ```typescript
|
|
266
|
+
* const errorJson = error.toJSON();
|
|
267
|
+
* // { code: 'AUTH_INVALID_CREDENTIALS', message: '...', timestamp: '...', details: {...} }
|
|
268
|
+
* ```
|
|
269
|
+
*/
|
|
270
|
+
toJSON() {
|
|
271
|
+
return {
|
|
272
|
+
code: this.code,
|
|
273
|
+
message: this.message,
|
|
274
|
+
timestamp: this.timestamp,
|
|
275
|
+
details: this.details,
|
|
276
|
+
statusCode: this.statusCode
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
// src/core/refresh.ts
|
|
282
|
+
var ACCESS_TOKEN_KEY = "nauth_access_token";
|
|
283
|
+
var REFRESH_TOKEN_KEY = "nauth_refresh_token";
|
|
284
|
+
var ACCESS_EXPIRES_AT_KEY = "nauth_access_token_expires_at";
|
|
285
|
+
var REFRESH_EXPIRES_AT_KEY = "nauth_refresh_token_expires_at";
|
|
286
|
+
var USER_KEY = "nauth_user";
|
|
287
|
+
var CHALLENGE_KEY = "nauth_challenge_session";
|
|
288
|
+
var TokenManager = class {
|
|
289
|
+
/**
|
|
290
|
+
* @param storage - storage adapter
|
|
291
|
+
*/
|
|
292
|
+
constructor(storage) {
|
|
293
|
+
__publicField(this, "storage");
|
|
294
|
+
__publicField(this, "refreshPromise", null);
|
|
295
|
+
__publicField(this, "isBrowser", typeof window !== "undefined");
|
|
296
|
+
this.storage = storage;
|
|
297
|
+
}
|
|
298
|
+
/**
|
|
299
|
+
* Load tokens from storage.
|
|
300
|
+
*/
|
|
301
|
+
async getTokens() {
|
|
302
|
+
const [accessToken, refreshToken, accessExpRaw, refreshExpRaw] = await Promise.all([
|
|
303
|
+
this.storage.getItem(ACCESS_TOKEN_KEY),
|
|
304
|
+
this.storage.getItem(REFRESH_TOKEN_KEY),
|
|
305
|
+
this.storage.getItem(ACCESS_EXPIRES_AT_KEY),
|
|
306
|
+
this.storage.getItem(REFRESH_EXPIRES_AT_KEY)
|
|
307
|
+
]);
|
|
308
|
+
return {
|
|
309
|
+
accessToken,
|
|
310
|
+
refreshToken,
|
|
311
|
+
accessTokenExpiresAt: accessExpRaw ? Number(accessExpRaw) : null,
|
|
312
|
+
refreshTokenExpiresAt: refreshExpRaw ? Number(refreshExpRaw) : null
|
|
313
|
+
};
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Persist tokens.
|
|
317
|
+
*
|
|
318
|
+
* @param tokens - new token pair
|
|
319
|
+
*/
|
|
320
|
+
async setTokens(tokens) {
|
|
321
|
+
await Promise.all([
|
|
322
|
+
this.storage.setItem(ACCESS_TOKEN_KEY, tokens.accessToken),
|
|
323
|
+
this.storage.setItem(REFRESH_TOKEN_KEY, tokens.refreshToken),
|
|
324
|
+
this.storage.setItem(ACCESS_EXPIRES_AT_KEY, tokens.accessTokenExpiresAt.toString()),
|
|
325
|
+
this.storage.setItem(REFRESH_EXPIRES_AT_KEY, tokens.refreshTokenExpiresAt.toString())
|
|
326
|
+
]);
|
|
327
|
+
this.broadcastStorage();
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Clear tokens and related auth state.
|
|
331
|
+
*/
|
|
332
|
+
async clearTokens() {
|
|
333
|
+
await Promise.all([
|
|
334
|
+
this.storage.removeItem(ACCESS_TOKEN_KEY),
|
|
335
|
+
this.storage.removeItem(REFRESH_TOKEN_KEY),
|
|
336
|
+
this.storage.removeItem(ACCESS_EXPIRES_AT_KEY),
|
|
337
|
+
this.storage.removeItem(REFRESH_EXPIRES_AT_KEY),
|
|
338
|
+
this.storage.removeItem(USER_KEY),
|
|
339
|
+
this.storage.removeItem(CHALLENGE_KEY)
|
|
340
|
+
]);
|
|
341
|
+
this.broadcastStorage();
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
344
|
+
* Ensure only one refresh in flight.
|
|
345
|
+
*
|
|
346
|
+
* @param refreshFn - function performing refresh request
|
|
347
|
+
*/
|
|
348
|
+
async refreshOnce(refreshFn) {
|
|
349
|
+
if (!this.refreshPromise) {
|
|
350
|
+
this.refreshPromise = refreshFn().then(async (tokens) => {
|
|
351
|
+
await this.setTokens(tokens);
|
|
352
|
+
return tokens;
|
|
353
|
+
}).catch((error) => {
|
|
354
|
+
throw error;
|
|
355
|
+
}).finally(() => {
|
|
356
|
+
this.refreshPromise = null;
|
|
357
|
+
});
|
|
358
|
+
}
|
|
359
|
+
return this.refreshPromise;
|
|
360
|
+
}
|
|
361
|
+
/**
|
|
362
|
+
* Validate that a refresh token exists before attempting refresh.
|
|
363
|
+
*/
|
|
364
|
+
async assertHasRefreshToken() {
|
|
365
|
+
const state = await this.getTokens();
|
|
366
|
+
if (!state.refreshToken) {
|
|
367
|
+
throw new NAuthClientError("AUTH_SESSION_NOT_FOUND" /* AUTH_SESSION_NOT_FOUND */, "No refresh token available");
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Broadcast a no-op write to trigger storage listeners in other tabs.
|
|
372
|
+
*/
|
|
373
|
+
broadcastStorage() {
|
|
374
|
+
if (!this.isBrowser) return;
|
|
375
|
+
try {
|
|
376
|
+
window.localStorage.setItem("nauth_sync", Date.now().toString());
|
|
377
|
+
} catch {
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
};
|
|
381
|
+
|
|
382
|
+
// src/storage/browser.ts
|
|
383
|
+
var BrowserStorage = class {
|
|
384
|
+
/**
|
|
385
|
+
* Create a browser storage adapter.
|
|
386
|
+
*
|
|
387
|
+
* @param storage - Storage implementation (localStorage by default)
|
|
388
|
+
*/
|
|
389
|
+
constructor(storage = window.localStorage) {
|
|
390
|
+
__publicField(this, "storage");
|
|
391
|
+
this.storage = storage;
|
|
392
|
+
}
|
|
393
|
+
async getItem(key) {
|
|
394
|
+
return this.storage.getItem(key);
|
|
395
|
+
}
|
|
396
|
+
async setItem(key, value) {
|
|
397
|
+
this.storage.setItem(key, value);
|
|
398
|
+
}
|
|
399
|
+
async removeItem(key) {
|
|
400
|
+
this.storage.removeItem(key);
|
|
401
|
+
}
|
|
402
|
+
};
|
|
403
|
+
|
|
404
|
+
// src/storage/memory.ts
|
|
405
|
+
var InMemoryStorage = class {
|
|
406
|
+
constructor() {
|
|
407
|
+
__publicField(this, "store", /* @__PURE__ */ new Map());
|
|
408
|
+
}
|
|
409
|
+
async getItem(key) {
|
|
410
|
+
return this.store.has(key) ? this.store.get(key) : null;
|
|
411
|
+
}
|
|
412
|
+
async setItem(key, value) {
|
|
413
|
+
this.store.set(key, value);
|
|
414
|
+
}
|
|
415
|
+
async removeItem(key) {
|
|
416
|
+
this.store.delete(key);
|
|
417
|
+
}
|
|
418
|
+
};
|
|
419
|
+
|
|
420
|
+
// src/core/events.ts
|
|
421
|
+
var EventEmitter = class {
|
|
422
|
+
constructor() {
|
|
423
|
+
__publicField(this, "listeners", /* @__PURE__ */ new Map());
|
|
424
|
+
}
|
|
425
|
+
/**
|
|
426
|
+
* Subscribe to an authentication event
|
|
427
|
+
*
|
|
428
|
+
* @param event - Event type or '*' for all events
|
|
429
|
+
* @param listener - Callback function
|
|
430
|
+
* @returns Unsubscribe function
|
|
431
|
+
*
|
|
432
|
+
* @example
|
|
433
|
+
* ```typescript
|
|
434
|
+
* const unsubscribe = emitter.on('auth:success', (event) => {
|
|
435
|
+
* console.log('User logged in:', event.data);
|
|
436
|
+
* });
|
|
437
|
+
*
|
|
438
|
+
* // Later
|
|
439
|
+
* unsubscribe();
|
|
440
|
+
* ```
|
|
441
|
+
*/
|
|
442
|
+
on(event, listener) {
|
|
443
|
+
if (!this.listeners.has(event)) {
|
|
444
|
+
this.listeners.set(event, /* @__PURE__ */ new Set());
|
|
445
|
+
}
|
|
446
|
+
this.listeners.get(event).add(listener);
|
|
447
|
+
return () => this.off(event, listener);
|
|
448
|
+
}
|
|
449
|
+
/**
|
|
450
|
+
* Unsubscribe from an authentication event
|
|
451
|
+
*
|
|
452
|
+
* @param event - Event type or '*'
|
|
453
|
+
* @param listener - Callback function to remove
|
|
454
|
+
*/
|
|
455
|
+
off(event, listener) {
|
|
456
|
+
this.listeners.get(event)?.delete(listener);
|
|
457
|
+
}
|
|
458
|
+
/**
|
|
459
|
+
* Emit an authentication event
|
|
460
|
+
*
|
|
461
|
+
* Notifies all listeners for the specific event type and wildcard listeners.
|
|
462
|
+
*
|
|
463
|
+
* @param event - Event to emit
|
|
464
|
+
* @internal
|
|
465
|
+
*/
|
|
466
|
+
emit(event) {
|
|
467
|
+
const specificListeners = this.listeners.get(event.type);
|
|
468
|
+
const wildcardListeners = this.listeners.get("*");
|
|
469
|
+
specificListeners?.forEach((listener) => {
|
|
470
|
+
try {
|
|
471
|
+
listener(event);
|
|
472
|
+
} catch (error) {
|
|
473
|
+
console.error(`Error in ${event.type} event listener:`, error);
|
|
474
|
+
}
|
|
475
|
+
});
|
|
476
|
+
wildcardListeners?.forEach((listener) => {
|
|
477
|
+
try {
|
|
478
|
+
listener(event);
|
|
479
|
+
} catch (error) {
|
|
480
|
+
console.error(`Error in wildcard event listener:`, error);
|
|
481
|
+
}
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
/**
|
|
485
|
+
* Remove all listeners
|
|
486
|
+
*
|
|
487
|
+
* @internal
|
|
488
|
+
*/
|
|
489
|
+
clear() {
|
|
490
|
+
this.listeners.clear();
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
// src/adapters/fetch-adapter.ts
|
|
495
|
+
var FetchAdapter = class {
|
|
496
|
+
/**
|
|
497
|
+
* Execute HTTP request using native fetch.
|
|
498
|
+
*
|
|
499
|
+
* @param config - Request configuration
|
|
500
|
+
* @returns Response with parsed data
|
|
501
|
+
* @throws NAuthClientError if request fails
|
|
502
|
+
*/
|
|
503
|
+
async request(config) {
|
|
504
|
+
const fetchOptions = {
|
|
505
|
+
method: config.method,
|
|
506
|
+
headers: config.headers,
|
|
507
|
+
signal: config.signal,
|
|
508
|
+
credentials: config.credentials
|
|
509
|
+
};
|
|
510
|
+
if (config.body !== void 0) {
|
|
511
|
+
fetchOptions.body = JSON.stringify(config.body);
|
|
512
|
+
}
|
|
513
|
+
let response;
|
|
514
|
+
try {
|
|
515
|
+
response = await fetch(config.url, fetchOptions);
|
|
516
|
+
} catch (error) {
|
|
517
|
+
throw new NAuthClientError("INTERNAL_ERROR" /* INTERNAL_ERROR */, "Network request failed", {
|
|
518
|
+
isNetworkError: true,
|
|
519
|
+
details: { url: config.url, message: error.message }
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
const status = response.status;
|
|
523
|
+
let data = null;
|
|
524
|
+
const text = await response.text();
|
|
525
|
+
if (text) {
|
|
526
|
+
try {
|
|
527
|
+
data = JSON.parse(text);
|
|
528
|
+
} catch {
|
|
529
|
+
data = text;
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
const headers = {};
|
|
533
|
+
response.headers.forEach((value, key) => {
|
|
534
|
+
headers[key] = value;
|
|
535
|
+
});
|
|
536
|
+
if (!response.ok) {
|
|
537
|
+
const errorData = typeof data === "object" && data !== null ? data : {};
|
|
538
|
+
const code = typeof errorData["code"] === "string" ? errorData.code : "INTERNAL_ERROR" /* INTERNAL_ERROR */;
|
|
539
|
+
const message = typeof errorData["message"] === "string" ? errorData.message : `Request failed with status ${status}`;
|
|
540
|
+
const timestamp = typeof errorData["timestamp"] === "string" ? errorData.timestamp : void 0;
|
|
541
|
+
const details = errorData["details"];
|
|
542
|
+
throw new NAuthClientError(code, message, {
|
|
543
|
+
statusCode: status,
|
|
544
|
+
timestamp,
|
|
545
|
+
details
|
|
546
|
+
});
|
|
547
|
+
}
|
|
548
|
+
return { data, status, headers };
|
|
549
|
+
}
|
|
550
|
+
};
|
|
551
|
+
|
|
552
|
+
// src/core/client.ts
|
|
553
|
+
var USER_KEY2 = "nauth_user";
|
|
554
|
+
var CHALLENGE_KEY2 = "nauth_challenge_session";
|
|
555
|
+
var hasWindow = () => typeof globalThis !== "undefined" && typeof globalThis.window !== "undefined";
|
|
556
|
+
var defaultStorage = () => {
|
|
557
|
+
if (hasWindow() && typeof window.localStorage !== "undefined") {
|
|
558
|
+
return new BrowserStorage();
|
|
559
|
+
}
|
|
560
|
+
return new InMemoryStorage();
|
|
561
|
+
};
|
|
562
|
+
var NAuthClient = class {
|
|
563
|
+
/**
|
|
564
|
+
* Create a new client instance.
|
|
565
|
+
*
|
|
566
|
+
* @param userConfig - Client configuration
|
|
567
|
+
*/
|
|
568
|
+
constructor(userConfig) {
|
|
569
|
+
__publicField(this, "config");
|
|
570
|
+
__publicField(this, "tokenManager");
|
|
571
|
+
__publicField(this, "eventEmitter");
|
|
572
|
+
__publicField(this, "currentUser", null);
|
|
573
|
+
/**
|
|
574
|
+
* Handle cross-tab storage updates.
|
|
575
|
+
*/
|
|
576
|
+
__publicField(this, "handleStorageEvent", (event) => {
|
|
577
|
+
if (event.key === "nauth_sync") {
|
|
578
|
+
this.config.storage.getItem(USER_KEY2).then((value) => value ? JSON.parse(value) : null).then((user) => {
|
|
579
|
+
this.currentUser = user;
|
|
580
|
+
this.config.onAuthStateChange?.(user);
|
|
581
|
+
}).catch(() => {
|
|
582
|
+
});
|
|
583
|
+
}
|
|
584
|
+
});
|
|
585
|
+
const storage = userConfig.storage ?? defaultStorage();
|
|
586
|
+
const defaultAdapter = userConfig.httpAdapter ?? new FetchAdapter();
|
|
587
|
+
this.config = resolveConfig({ ...userConfig, storage }, defaultAdapter);
|
|
588
|
+
this.tokenManager = new TokenManager(storage);
|
|
589
|
+
this.eventEmitter = new EventEmitter();
|
|
590
|
+
if (hasWindow()) {
|
|
591
|
+
window.addEventListener("storage", this.handleStorageEvent);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
/**
|
|
595
|
+
* Clean up resources.
|
|
596
|
+
*/
|
|
597
|
+
dispose() {
|
|
598
|
+
if (hasWindow()) {
|
|
599
|
+
window.removeEventListener("storage", this.handleStorageEvent);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
/**
|
|
603
|
+
* Login with identifier and password.
|
|
604
|
+
*/
|
|
605
|
+
async login(identifier, password) {
|
|
606
|
+
const loginEvent = { type: "auth:login", data: { identifier }, timestamp: Date.now() };
|
|
607
|
+
this.eventEmitter.emit(loginEvent);
|
|
608
|
+
try {
|
|
609
|
+
const body = { identifier, password };
|
|
610
|
+
const response = await this.post(this.config.endpoints.login, body);
|
|
611
|
+
await this.handleAuthResponse(response);
|
|
612
|
+
if (response.challengeName) {
|
|
613
|
+
const challengeEvent = { type: "auth:challenge", data: response, timestamp: Date.now() };
|
|
614
|
+
this.eventEmitter.emit(challengeEvent);
|
|
615
|
+
} else {
|
|
616
|
+
const successEvent = { type: "auth:success", data: response, timestamp: Date.now() };
|
|
617
|
+
this.eventEmitter.emit(successEvent);
|
|
618
|
+
}
|
|
619
|
+
return response;
|
|
620
|
+
} catch (error) {
|
|
621
|
+
const authError = error instanceof NAuthClientError ? error : new NAuthClientError("AUTH_INVALID_CREDENTIALS" /* AUTH_INVALID_CREDENTIALS */, error.message || "Login failed");
|
|
622
|
+
const errorEvent = { type: "auth:error", data: authError, timestamp: Date.now() };
|
|
623
|
+
this.eventEmitter.emit(errorEvent);
|
|
624
|
+
throw authError;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
/**
|
|
628
|
+
* Signup with credentials.
|
|
629
|
+
*/
|
|
630
|
+
async signup(payload) {
|
|
631
|
+
this.eventEmitter.emit({ type: "auth:signup", data: { email: payload.email }, timestamp: Date.now() });
|
|
632
|
+
try {
|
|
633
|
+
const response = await this.post(this.config.endpoints.signup, payload);
|
|
634
|
+
await this.handleAuthResponse(response);
|
|
635
|
+
if (response.challengeName) {
|
|
636
|
+
this.eventEmitter.emit({ type: "auth:challenge", data: response, timestamp: Date.now() });
|
|
637
|
+
} else {
|
|
638
|
+
this.eventEmitter.emit({ type: "auth:success", data: response, timestamp: Date.now() });
|
|
639
|
+
}
|
|
640
|
+
return response;
|
|
641
|
+
} catch (error) {
|
|
642
|
+
const authError = error instanceof NAuthClientError ? error : new NAuthClientError("AUTH_INVALID_CREDENTIALS" /* AUTH_INVALID_CREDENTIALS */, error.message || "Signup failed");
|
|
643
|
+
this.eventEmitter.emit({ type: "auth:error", data: authError, timestamp: Date.now() });
|
|
644
|
+
throw authError;
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
/**
|
|
648
|
+
* Refresh tokens manually.
|
|
649
|
+
*/
|
|
650
|
+
async refreshTokens() {
|
|
651
|
+
const tokenDelivery = this.getTokenDeliveryMode();
|
|
652
|
+
if (tokenDelivery === "json") {
|
|
653
|
+
await this.tokenManager.assertHasRefreshToken();
|
|
654
|
+
}
|
|
655
|
+
const body = tokenDelivery === "json" ? { refreshToken: (await this.tokenManager.getTokens()).refreshToken } : { refreshToken: "" };
|
|
656
|
+
const refreshFn = async () => {
|
|
657
|
+
return this.post(this.config.endpoints.refresh, body, false);
|
|
658
|
+
};
|
|
659
|
+
const tokens = await this.tokenManager.refreshOnce(refreshFn);
|
|
660
|
+
this.config.onTokenRefresh?.();
|
|
661
|
+
this.eventEmitter.emit({ type: "auth:refresh", data: { success: true }, timestamp: Date.now() });
|
|
662
|
+
return tokens;
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Logout current session.
|
|
666
|
+
*
|
|
667
|
+
* Uses GET request to avoid CSRF token issues.
|
|
668
|
+
*
|
|
669
|
+
* @param forgetDevice - If true, also untrust the device (require MFA on next login)
|
|
670
|
+
*/
|
|
671
|
+
async logout(forgetDevice) {
|
|
672
|
+
const queryParams = forgetDevice ? "?forgetMe=true" : "";
|
|
673
|
+
try {
|
|
674
|
+
await this.get(this.config.endpoints.logout + queryParams, true);
|
|
675
|
+
} catch (error) {
|
|
676
|
+
console.warn("[nauth] Logout request failed (session may already be invalid):", error);
|
|
677
|
+
} finally {
|
|
678
|
+
await this.clearAuthState(forgetDevice);
|
|
679
|
+
this.eventEmitter.emit({
|
|
680
|
+
type: "auth:logout",
|
|
681
|
+
data: { forgetDevice: !!forgetDevice, global: false },
|
|
682
|
+
timestamp: Date.now()
|
|
683
|
+
});
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
/**
|
|
687
|
+
* Logout all sessions.
|
|
688
|
+
*
|
|
689
|
+
* Revokes all active sessions for the current user across all devices.
|
|
690
|
+
* Optionally revokes all trusted devices if forgetDevices is true.
|
|
691
|
+
*
|
|
692
|
+
* @param forgetDevices - If true, also revokes all trusted devices (default: false)
|
|
693
|
+
* @returns Number of sessions revoked
|
|
694
|
+
*/
|
|
695
|
+
async logoutAll(forgetDevices) {
|
|
696
|
+
try {
|
|
697
|
+
const payload = {
|
|
698
|
+
forgetDevices: forgetDevices ?? false
|
|
699
|
+
};
|
|
700
|
+
const result = await this.post(
|
|
701
|
+
this.config.endpoints.logoutAll,
|
|
702
|
+
payload,
|
|
703
|
+
true
|
|
704
|
+
);
|
|
705
|
+
await this.clearAuthState(forgetDevices);
|
|
706
|
+
this.eventEmitter.emit({
|
|
707
|
+
type: "auth:logout",
|
|
708
|
+
data: { forgetDevice: !!forgetDevices, global: true },
|
|
709
|
+
timestamp: Date.now()
|
|
710
|
+
});
|
|
711
|
+
return { revokedCount: result.revokedCount };
|
|
712
|
+
} catch (error) {
|
|
713
|
+
await this.clearAuthState(forgetDevices);
|
|
714
|
+
this.eventEmitter.emit({
|
|
715
|
+
type: "auth:logout",
|
|
716
|
+
data: { forgetDevice: !!forgetDevices, global: true },
|
|
717
|
+
timestamp: Date.now()
|
|
718
|
+
});
|
|
719
|
+
throw error;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Respond to a challenge.
|
|
724
|
+
*
|
|
725
|
+
* Validates challenge response data before sending to backend.
|
|
726
|
+
* Provides helpful error messages for common validation issues.
|
|
727
|
+
*
|
|
728
|
+
* @param response - Challenge response data
|
|
729
|
+
* @returns Auth response from backend
|
|
730
|
+
* @throws {NAuthClientError} If validation fails
|
|
731
|
+
*/
|
|
732
|
+
async respondToChallenge(response) {
|
|
733
|
+
if (response.type === "MFA_SETUP_REQUIRED" /* MFA_SETUP_REQUIRED */ && response.method === "totp") {
|
|
734
|
+
const setupData = response.setupData;
|
|
735
|
+
if (!setupData || typeof setupData !== "object") {
|
|
736
|
+
throw new NAuthClientError(
|
|
737
|
+
"VALIDATION_FAILED" /* VALIDATION_FAILED */,
|
|
738
|
+
"TOTP setup requires setupData with both secret and code",
|
|
739
|
+
{ details: { field: "setupData" } }
|
|
740
|
+
);
|
|
741
|
+
}
|
|
742
|
+
const secret = setupData["secret"];
|
|
743
|
+
const code = setupData["code"];
|
|
744
|
+
if (!secret || typeof secret !== "string") {
|
|
745
|
+
throw new NAuthClientError(
|
|
746
|
+
"VALIDATION_FAILED" /* VALIDATION_FAILED */,
|
|
747
|
+
"TOTP setup requires secret in setupData. Make sure to include the secret from getSetupData() response.",
|
|
748
|
+
{ details: { field: "secret" } }
|
|
749
|
+
);
|
|
750
|
+
}
|
|
751
|
+
if (!code || typeof code !== "string") {
|
|
752
|
+
throw new NAuthClientError(
|
|
753
|
+
"VALIDATION_FAILED" /* VALIDATION_FAILED */,
|
|
754
|
+
"TOTP setup requires code in setupData. Please enter the verification code from your authenticator app.",
|
|
755
|
+
{ details: { field: "code" } }
|
|
756
|
+
);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
try {
|
|
760
|
+
const result = await this.post(this.config.endpoints.respondChallenge, response);
|
|
761
|
+
await this.handleAuthResponse(result);
|
|
762
|
+
if (result.challengeName) {
|
|
763
|
+
const challengeEvent = { type: "auth:challenge", data: result, timestamp: Date.now() };
|
|
764
|
+
this.eventEmitter.emit(challengeEvent);
|
|
765
|
+
} else {
|
|
766
|
+
const successEvent = { type: "auth:success", data: result, timestamp: Date.now() };
|
|
767
|
+
this.eventEmitter.emit(successEvent);
|
|
768
|
+
}
|
|
769
|
+
return result;
|
|
770
|
+
} catch (error) {
|
|
771
|
+
const authError = error instanceof NAuthClientError ? error : new NAuthClientError(
|
|
772
|
+
"CHALLENGE_INVALID" /* CHALLENGE_INVALID */,
|
|
773
|
+
error.message || "Challenge response failed"
|
|
774
|
+
);
|
|
775
|
+
const errorEvent = { type: "auth:error", data: authError, timestamp: Date.now() };
|
|
776
|
+
this.eventEmitter.emit(errorEvent);
|
|
777
|
+
throw authError;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
/**
|
|
781
|
+
* Resend a challenge code.
|
|
782
|
+
*/
|
|
783
|
+
async resendCode(session) {
|
|
784
|
+
const payload = { session };
|
|
785
|
+
return this.post(this.config.endpoints.resendCode, payload);
|
|
786
|
+
}
|
|
787
|
+
/**
|
|
788
|
+
* Get setup data for MFA.
|
|
789
|
+
*
|
|
790
|
+
* Returns method-specific setup information:
|
|
791
|
+
* - TOTP: { secret, qrCode, manualEntryKey }
|
|
792
|
+
* - SMS: { maskedPhone }
|
|
793
|
+
* - Email: { maskedEmail }
|
|
794
|
+
* - Passkey: WebAuthn registration options
|
|
795
|
+
*
|
|
796
|
+
* @param session - Challenge session token
|
|
797
|
+
* @param method - MFA method to set up
|
|
798
|
+
* @returns Setup data wrapped in GetSetupDataResponse
|
|
799
|
+
*/
|
|
800
|
+
async getSetupData(session, method) {
|
|
801
|
+
const payload = { session, method };
|
|
802
|
+
return this.post(this.config.endpoints.getSetupData, payload);
|
|
803
|
+
}
|
|
804
|
+
/**
|
|
805
|
+
* Get challenge data (e.g., WebAuthn options).
|
|
806
|
+
*
|
|
807
|
+
* Returns challenge-specific data for verification flows.
|
|
808
|
+
*
|
|
809
|
+
* @param session - Challenge session token
|
|
810
|
+
* @param method - Challenge method to get data for
|
|
811
|
+
* @returns Challenge data wrapped in GetChallengeDataResponse
|
|
812
|
+
*/
|
|
813
|
+
async getChallengeData(session, method) {
|
|
814
|
+
const payload = { session, method };
|
|
815
|
+
return this.post(this.config.endpoints.getChallengeData, payload);
|
|
816
|
+
}
|
|
817
|
+
/**
|
|
818
|
+
* Get current user profile.
|
|
819
|
+
*/
|
|
820
|
+
async getProfile() {
|
|
821
|
+
const profile = await this.get(this.config.endpoints.profile, true);
|
|
822
|
+
await this.setUser(profile);
|
|
823
|
+
return profile;
|
|
824
|
+
}
|
|
825
|
+
/**
|
|
826
|
+
* Update user profile.
|
|
827
|
+
*/
|
|
828
|
+
async updateProfile(updates) {
|
|
829
|
+
const updated = await this.put(this.config.endpoints.updateProfile, updates, true);
|
|
830
|
+
await this.setUser(updated);
|
|
831
|
+
return updated;
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Change user password.
|
|
835
|
+
*/
|
|
836
|
+
async changePassword(oldPassword, newPassword) {
|
|
837
|
+
const payload = { currentPassword: oldPassword, newPassword };
|
|
838
|
+
await this.post(this.config.endpoints.changePassword, payload, true);
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Request password change (must change on next login).
|
|
842
|
+
*/
|
|
843
|
+
async requestPasswordChange() {
|
|
844
|
+
await this.post(this.config.endpoints.requestPasswordChange, {}, true);
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* Get MFA status.
|
|
848
|
+
*/
|
|
849
|
+
async getMfaStatus() {
|
|
850
|
+
return this.get(this.config.endpoints.mfaStatus, true);
|
|
851
|
+
}
|
|
852
|
+
/**
|
|
853
|
+
* Get MFA devices.
|
|
854
|
+
*/
|
|
855
|
+
async getMfaDevices() {
|
|
856
|
+
return this.get(this.config.endpoints.mfaDevices, true);
|
|
857
|
+
}
|
|
858
|
+
/**
|
|
859
|
+
* Setup MFA device (authenticated user).
|
|
860
|
+
*/
|
|
861
|
+
async setupMfaDevice(method) {
|
|
862
|
+
return this.post(this.config.endpoints.mfaSetupData, { method }, true);
|
|
863
|
+
}
|
|
864
|
+
/**
|
|
865
|
+
* Verify MFA setup (authenticated user).
|
|
866
|
+
*/
|
|
867
|
+
async verifyMfaSetup(method, setupData, deviceName) {
|
|
868
|
+
return this.post(
|
|
869
|
+
this.config.endpoints.mfaVerifySetup,
|
|
870
|
+
{ method, setupData, deviceName },
|
|
871
|
+
true
|
|
872
|
+
);
|
|
873
|
+
}
|
|
874
|
+
/**
|
|
875
|
+
* Remove MFA method.
|
|
876
|
+
*/
|
|
877
|
+
async removeMfaDevice(method) {
|
|
878
|
+
const path = `${this.config.endpoints.mfaRemove}/${method}`;
|
|
879
|
+
return this.delete(path, true);
|
|
880
|
+
}
|
|
881
|
+
/**
|
|
882
|
+
* Set preferred MFA method.
|
|
883
|
+
*
|
|
884
|
+
* @param method - Device method to set as preferred ('totp', 'sms', 'email', or 'passkey'). Cannot be 'backup'.
|
|
885
|
+
* @returns Success message
|
|
886
|
+
*/
|
|
887
|
+
async setPreferredMfaMethod(method) {
|
|
888
|
+
return this.post(this.config.endpoints.mfaPreferred, { method }, true);
|
|
889
|
+
}
|
|
890
|
+
/**
|
|
891
|
+
* Generate backup codes.
|
|
892
|
+
*/
|
|
893
|
+
async generateBackupCodes() {
|
|
894
|
+
const result = await this.post(this.config.endpoints.mfaBackupCodes, {}, true);
|
|
895
|
+
return result.codes;
|
|
896
|
+
}
|
|
897
|
+
/**
|
|
898
|
+
* Set MFA exemption (admin/test scenarios).
|
|
899
|
+
*/
|
|
900
|
+
async setMfaExemption(exempt, reason) {
|
|
901
|
+
await this.post(this.config.endpoints.mfaExemption, { exempt, reason }, true);
|
|
902
|
+
}
|
|
903
|
+
// ============================================================================
|
|
904
|
+
// Event System
|
|
905
|
+
// ============================================================================
|
|
906
|
+
/**
|
|
907
|
+
* Subscribe to authentication events.
|
|
908
|
+
*
|
|
909
|
+
* Emits events throughout the auth lifecycle for custom logic, analytics, or UI updates.
|
|
910
|
+
*
|
|
911
|
+
* @param event - Event type to listen for, or '*' for all events
|
|
912
|
+
* @param listener - Callback function to handle the event
|
|
913
|
+
* @returns Unsubscribe function
|
|
914
|
+
*
|
|
915
|
+
* @example
|
|
916
|
+
* ```typescript
|
|
917
|
+
* // Listen to successful authentication
|
|
918
|
+
* const unsubscribe = client.on('auth:success', (event) => {
|
|
919
|
+
* console.log('User logged in:', event.data.user);
|
|
920
|
+
* analytics.track('login_success');
|
|
921
|
+
* });
|
|
922
|
+
*
|
|
923
|
+
* // Listen to all events
|
|
924
|
+
* client.on('*', (event) => {
|
|
925
|
+
* console.log('Auth event:', event.type, event.data);
|
|
926
|
+
* });
|
|
927
|
+
*
|
|
928
|
+
* // Unsubscribe when done
|
|
929
|
+
* unsubscribe();
|
|
930
|
+
* ```
|
|
931
|
+
*/
|
|
932
|
+
on(event, listener) {
|
|
933
|
+
return this.eventEmitter.on(event, listener);
|
|
934
|
+
}
|
|
935
|
+
/**
|
|
936
|
+
* Unsubscribe from authentication events.
|
|
937
|
+
*
|
|
938
|
+
* @param event - Event type
|
|
939
|
+
* @param listener - Callback function to remove
|
|
940
|
+
*/
|
|
941
|
+
off(event, listener) {
|
|
942
|
+
this.eventEmitter.off(event, listener);
|
|
943
|
+
}
|
|
944
|
+
// ============================================================================
|
|
945
|
+
// Social Authentication
|
|
946
|
+
// ============================================================================
|
|
947
|
+
/**
|
|
948
|
+
* Start social OAuth flow with automatic state management.
|
|
949
|
+
*
|
|
950
|
+
* Generates a secure state token, stores OAuth context, and redirects to the OAuth provider.
|
|
951
|
+
* After OAuth callback, use `handleOAuthCallback()` to complete authentication.
|
|
952
|
+
*
|
|
953
|
+
* @param provider - OAuth provider ('google', 'apple', 'facebook')
|
|
954
|
+
* @param options - Optional configuration
|
|
955
|
+
*
|
|
956
|
+
* @example
|
|
957
|
+
* ```typescript
|
|
958
|
+
* // Simple usage
|
|
959
|
+
* await client.loginWithSocial('google');
|
|
960
|
+
*
|
|
961
|
+
* // With custom redirect URI
|
|
962
|
+
* await client.loginWithSocial('apple', {
|
|
963
|
+
* redirectUri: 'https://example.com/auth/callback'
|
|
964
|
+
* });
|
|
965
|
+
* ```
|
|
966
|
+
*/
|
|
967
|
+
async loginWithSocial(provider, _options) {
|
|
968
|
+
this.eventEmitter.emit({ type: "oauth:started", data: { provider }, timestamp: Date.now() });
|
|
969
|
+
const { url } = await this.getSocialAuthUrl({ provider });
|
|
970
|
+
if (hasWindow()) {
|
|
971
|
+
window.location.href = url;
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
/**
|
|
975
|
+
* Auto-detect and handle OAuth callback.
|
|
976
|
+
*
|
|
977
|
+
* Call this on app initialization or in callback route.
|
|
978
|
+
* Returns null if not an OAuth callback (no provider/code params).
|
|
979
|
+
*
|
|
980
|
+
* The SDK validates the state token, completes authentication via backend,
|
|
981
|
+
* and emits appropriate events.
|
|
982
|
+
*
|
|
983
|
+
* @param urlOrParams - Optional URL string or URLSearchParams (auto-detects from window.location if not provided)
|
|
984
|
+
* @returns AuthResponse if OAuth callback detected, null otherwise
|
|
985
|
+
*
|
|
986
|
+
* @example
|
|
987
|
+
* ```typescript
|
|
988
|
+
* // Auto-detect on app init
|
|
989
|
+
* const response = await client.handleOAuthCallback();
|
|
990
|
+
* if (response) {
|
|
991
|
+
* if (response.challengeName) {
|
|
992
|
+
* router.navigate(['/challenge', response.challengeName]);
|
|
993
|
+
* } else {
|
|
994
|
+
* router.navigate(['/']); // Navigate to your app's home route
|
|
995
|
+
* }
|
|
996
|
+
* }
|
|
997
|
+
*
|
|
998
|
+
* // In callback route
|
|
999
|
+
* const response = await client.handleOAuthCallback(window.location.search);
|
|
1000
|
+
* ```
|
|
1001
|
+
*/
|
|
1002
|
+
async handleOAuthCallback(urlOrParams) {
|
|
1003
|
+
let params;
|
|
1004
|
+
if (urlOrParams instanceof URLSearchParams) {
|
|
1005
|
+
params = urlOrParams;
|
|
1006
|
+
} else if (typeof urlOrParams === "string") {
|
|
1007
|
+
params = new URLSearchParams(urlOrParams);
|
|
1008
|
+
} else if (hasWindow()) {
|
|
1009
|
+
params = new URLSearchParams(window.location.search);
|
|
1010
|
+
} else {
|
|
1011
|
+
return null;
|
|
1012
|
+
}
|
|
1013
|
+
const provider = params.get("provider");
|
|
1014
|
+
const code = params.get("code");
|
|
1015
|
+
const state = params.get("state");
|
|
1016
|
+
const error = params.get("error");
|
|
1017
|
+
if (!provider || !code && !error) {
|
|
1018
|
+
return null;
|
|
1019
|
+
}
|
|
1020
|
+
this.eventEmitter.emit({ type: "oauth:callback", data: { provider }, timestamp: Date.now() });
|
|
1021
|
+
try {
|
|
1022
|
+
if (error) {
|
|
1023
|
+
const authError = new NAuthClientError(
|
|
1024
|
+
"SOCIAL_TOKEN_INVALID" /* SOCIAL_TOKEN_INVALID */,
|
|
1025
|
+
params.get("error_description") || error,
|
|
1026
|
+
{ details: { error, provider } }
|
|
1027
|
+
);
|
|
1028
|
+
this.eventEmitter.emit({ type: "oauth:error", data: authError, timestamp: Date.now() });
|
|
1029
|
+
throw authError;
|
|
1030
|
+
}
|
|
1031
|
+
if (!state) {
|
|
1032
|
+
throw new NAuthClientError("CHALLENGE_INVALID" /* CHALLENGE_INVALID */, "Missing OAuth state parameter");
|
|
1033
|
+
}
|
|
1034
|
+
const response = await this.handleSocialCallback({
|
|
1035
|
+
provider,
|
|
1036
|
+
code,
|
|
1037
|
+
state
|
|
1038
|
+
});
|
|
1039
|
+
if (response.challengeName) {
|
|
1040
|
+
this.eventEmitter.emit({ type: "auth:challenge", data: response, timestamp: Date.now() });
|
|
1041
|
+
} else {
|
|
1042
|
+
this.eventEmitter.emit({ type: "auth:success", data: response, timestamp: Date.now() });
|
|
1043
|
+
}
|
|
1044
|
+
this.eventEmitter.emit({ type: "oauth:completed", data: response, timestamp: Date.now() });
|
|
1045
|
+
return response;
|
|
1046
|
+
} catch (error2) {
|
|
1047
|
+
const authError = error2 instanceof NAuthClientError ? error2 : new NAuthClientError(
|
|
1048
|
+
"SOCIAL_TOKEN_INVALID" /* SOCIAL_TOKEN_INVALID */,
|
|
1049
|
+
error2.message || "OAuth callback failed"
|
|
1050
|
+
);
|
|
1051
|
+
this.eventEmitter.emit({ type: "oauth:error", data: authError, timestamp: Date.now() });
|
|
1052
|
+
throw authError;
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Get social auth URL (low-level API).
|
|
1057
|
+
*
|
|
1058
|
+
* For most cases, use `loginWithSocial()` which handles state management automatically.
|
|
1059
|
+
*/
|
|
1060
|
+
async getSocialAuthUrl(request) {
|
|
1061
|
+
return this.post(this.config.endpoints.socialAuthUrl, request);
|
|
1062
|
+
}
|
|
1063
|
+
/**
|
|
1064
|
+
* Handle social callback.
|
|
1065
|
+
*/
|
|
1066
|
+
async handleSocialCallback(request) {
|
|
1067
|
+
const result = await this.post(this.config.endpoints.socialCallback, request);
|
|
1068
|
+
await this.handleAuthResponse(result);
|
|
1069
|
+
return result;
|
|
1070
|
+
}
|
|
1071
|
+
/**
|
|
1072
|
+
* Verify native social token (mobile).
|
|
1073
|
+
*/
|
|
1074
|
+
async verifyNativeSocial(request) {
|
|
1075
|
+
try {
|
|
1076
|
+
const path = this.config.endpoints.socialVerify.replace(":provider", request.provider);
|
|
1077
|
+
const result = await this.post(path, request);
|
|
1078
|
+
await this.handleAuthResponse(result);
|
|
1079
|
+
if (result.challengeName) {
|
|
1080
|
+
const challengeEvent = { type: "auth:challenge", data: result, timestamp: Date.now() };
|
|
1081
|
+
this.eventEmitter.emit(challengeEvent);
|
|
1082
|
+
} else {
|
|
1083
|
+
const successEvent = { type: "auth:success", data: result, timestamp: Date.now() };
|
|
1084
|
+
this.eventEmitter.emit(successEvent);
|
|
1085
|
+
}
|
|
1086
|
+
return result;
|
|
1087
|
+
} catch (error) {
|
|
1088
|
+
const authError = error instanceof NAuthClientError ? error : new NAuthClientError(
|
|
1089
|
+
"SOCIAL_TOKEN_INVALID" /* SOCIAL_TOKEN_INVALID */,
|
|
1090
|
+
error.message || "Social verification failed"
|
|
1091
|
+
);
|
|
1092
|
+
const errorEvent = { type: "auth:error", data: authError, timestamp: Date.now() };
|
|
1093
|
+
this.eventEmitter.emit(errorEvent);
|
|
1094
|
+
throw authError;
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
/**
|
|
1098
|
+
* Get linked accounts.
|
|
1099
|
+
*/
|
|
1100
|
+
async getLinkedAccounts() {
|
|
1101
|
+
return this.get(this.config.endpoints.socialLinked, true);
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* Link social account.
|
|
1105
|
+
*/
|
|
1106
|
+
async linkSocialAccount(provider, code, state) {
|
|
1107
|
+
return this.post(this.config.endpoints.socialLink, { provider, code, state }, true);
|
|
1108
|
+
}
|
|
1109
|
+
/**
|
|
1110
|
+
* Unlink social account.
|
|
1111
|
+
*/
|
|
1112
|
+
async unlinkSocialAccount(provider) {
|
|
1113
|
+
return this.post(this.config.endpoints.socialUnlink, { provider }, true);
|
|
1114
|
+
}
|
|
1115
|
+
/**
|
|
1116
|
+
* Trust current device.
|
|
1117
|
+
*/
|
|
1118
|
+
async trustDevice() {
|
|
1119
|
+
const result = await this.post(this.config.endpoints.trustDevice, {}, true);
|
|
1120
|
+
await this.setDeviceToken(result.deviceToken);
|
|
1121
|
+
return result;
|
|
1122
|
+
}
|
|
1123
|
+
/**
|
|
1124
|
+
* Check if the current device is trusted.
|
|
1125
|
+
*
|
|
1126
|
+
* Returns whether the current device is trusted based on the device token
|
|
1127
|
+
* (from cookie in cookies mode, or header in JSON mode).
|
|
1128
|
+
*
|
|
1129
|
+
* This performs a server-side validation of the device token and checks:
|
|
1130
|
+
* - Device token exists and is valid
|
|
1131
|
+
* - Device token matches a trusted device record in the database
|
|
1132
|
+
* - Trust has not expired
|
|
1133
|
+
*
|
|
1134
|
+
* @returns Object with trusted status
|
|
1135
|
+
*
|
|
1136
|
+
* @example
|
|
1137
|
+
* ```typescript
|
|
1138
|
+
* const result = await client.isTrustedDevice();
|
|
1139
|
+
* if (result.trusted) {
|
|
1140
|
+
* console.log('This device is trusted');
|
|
1141
|
+
* }
|
|
1142
|
+
* ```
|
|
1143
|
+
*/
|
|
1144
|
+
async isTrustedDevice() {
|
|
1145
|
+
return this.get(this.config.endpoints.isTrustedDevice, true);
|
|
1146
|
+
}
|
|
1147
|
+
/**
|
|
1148
|
+
* Get paginated audit history for the current user.
|
|
1149
|
+
*
|
|
1150
|
+
* Returns authentication and security events with full audit details including:
|
|
1151
|
+
* - Event type (login, logout, MFA, etc.)
|
|
1152
|
+
* - Event status (success, failure, suspicious)
|
|
1153
|
+
* - Device information, location, risk factors
|
|
1154
|
+
*
|
|
1155
|
+
* @param params - Query parameters for filtering and pagination
|
|
1156
|
+
* @returns Paginated audit history response
|
|
1157
|
+
*
|
|
1158
|
+
* @example
|
|
1159
|
+
* ```typescript
|
|
1160
|
+
* const history = await client.getAuditHistory({
|
|
1161
|
+
* page: 1,
|
|
1162
|
+
* limit: 20,
|
|
1163
|
+
* eventType: 'LOGIN_SUCCESS'
|
|
1164
|
+
* });
|
|
1165
|
+
* ```
|
|
1166
|
+
*/
|
|
1167
|
+
async getAuditHistory(params) {
|
|
1168
|
+
const entries = Object.entries(params ?? {}).map(([k, v]) => [k, String(v)]);
|
|
1169
|
+
const query = entries.length > 0 ? `?${new URLSearchParams(entries).toString()}` : "";
|
|
1170
|
+
const path = `${this.config.endpoints.auditHistory}${query}`;
|
|
1171
|
+
return this.get(path, true);
|
|
1172
|
+
}
|
|
1173
|
+
/**
|
|
1174
|
+
* Initialize client by hydrating state from storage.
|
|
1175
|
+
* Call this on app startup to restore auth state.
|
|
1176
|
+
*/
|
|
1177
|
+
async initialize() {
|
|
1178
|
+
const userJson = await this.config.storage.getItem(USER_KEY2);
|
|
1179
|
+
if (userJson) {
|
|
1180
|
+
try {
|
|
1181
|
+
this.currentUser = JSON.parse(userJson);
|
|
1182
|
+
this.config.onAuthStateChange?.(this.currentUser);
|
|
1183
|
+
} catch {
|
|
1184
|
+
await this.config.storage.removeItem(USER_KEY2);
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
}
|
|
1188
|
+
/**
|
|
1189
|
+
* Determine if user is authenticated (async - checks tokens).
|
|
1190
|
+
*/
|
|
1191
|
+
async isAuthenticated() {
|
|
1192
|
+
const tokens = await this.tokenManager.getTokens();
|
|
1193
|
+
return Boolean(tokens.accessToken);
|
|
1194
|
+
}
|
|
1195
|
+
/**
|
|
1196
|
+
* Determine if user is authenticated (sync - checks cached user).
|
|
1197
|
+
* Use this for guards and sync checks. Use `isAuthenticated()` for definitive check.
|
|
1198
|
+
*/
|
|
1199
|
+
isAuthenticatedSync() {
|
|
1200
|
+
return this.currentUser !== null;
|
|
1201
|
+
}
|
|
1202
|
+
/**
|
|
1203
|
+
* Get current access token (may be null).
|
|
1204
|
+
*/
|
|
1205
|
+
async getAccessToken() {
|
|
1206
|
+
const tokens = await this.tokenManager.getTokens();
|
|
1207
|
+
return tokens.accessToken ?? null;
|
|
1208
|
+
}
|
|
1209
|
+
/**
|
|
1210
|
+
* Get current user (cached, sync).
|
|
1211
|
+
*/
|
|
1212
|
+
getCurrentUser() {
|
|
1213
|
+
return this.currentUser;
|
|
1214
|
+
}
|
|
1215
|
+
/**
|
|
1216
|
+
* Get stored challenge session (for resuming challenge flows).
|
|
1217
|
+
*/
|
|
1218
|
+
async getStoredChallenge() {
|
|
1219
|
+
const raw = await this.config.storage.getItem(CHALLENGE_KEY2);
|
|
1220
|
+
if (!raw) return null;
|
|
1221
|
+
try {
|
|
1222
|
+
return JSON.parse(raw);
|
|
1223
|
+
} catch {
|
|
1224
|
+
return null;
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* Clear stored challenge session.
|
|
1229
|
+
*/
|
|
1230
|
+
async clearStoredChallenge() {
|
|
1231
|
+
await this.config.storage.removeItem(CHALLENGE_KEY2);
|
|
1232
|
+
}
|
|
1233
|
+
/**
|
|
1234
|
+
* Internal: handle auth response (tokens or challenge).
|
|
1235
|
+
*
|
|
1236
|
+
* In cookies mode: Tokens are set as httpOnly cookies by backend, not stored in client storage.
|
|
1237
|
+
* In JSON mode: Tokens are stored in tokenManager for Authorization header.
|
|
1238
|
+
*/
|
|
1239
|
+
async handleAuthResponse(response) {
|
|
1240
|
+
if (response.challengeName) {
|
|
1241
|
+
await this.persistChallenge(response);
|
|
1242
|
+
return;
|
|
1243
|
+
}
|
|
1244
|
+
if (this.config.tokenDelivery === "json" && response.accessToken && response.refreshToken) {
|
|
1245
|
+
await this.tokenManager.setTokens({
|
|
1246
|
+
accessToken: response.accessToken,
|
|
1247
|
+
refreshToken: response.refreshToken,
|
|
1248
|
+
accessTokenExpiresAt: response.accessTokenExpiresAt ?? 0,
|
|
1249
|
+
refreshTokenExpiresAt: response.refreshTokenExpiresAt ?? 0
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
if (this.config.tokenDelivery === "json" && response.deviceToken) {
|
|
1253
|
+
await this.setDeviceToken(response.deviceToken);
|
|
1254
|
+
}
|
|
1255
|
+
if (response.user) {
|
|
1256
|
+
await this.setUser(response.user);
|
|
1257
|
+
}
|
|
1258
|
+
await this.clearChallenge();
|
|
1259
|
+
}
|
|
1260
|
+
/**
|
|
1261
|
+
* Persist challenge state.
|
|
1262
|
+
*/
|
|
1263
|
+
async persistChallenge(challenge) {
|
|
1264
|
+
await this.config.storage.setItem(CHALLENGE_KEY2, JSON.stringify(challenge));
|
|
1265
|
+
}
|
|
1266
|
+
/**
|
|
1267
|
+
* Clear challenge state.
|
|
1268
|
+
*/
|
|
1269
|
+
async clearChallenge() {
|
|
1270
|
+
await this.config.storage.removeItem(CHALLENGE_KEY2);
|
|
1271
|
+
}
|
|
1272
|
+
/**
|
|
1273
|
+
* Persist user.
|
|
1274
|
+
*/
|
|
1275
|
+
async setUser(user) {
|
|
1276
|
+
this.currentUser = user;
|
|
1277
|
+
await this.config.storage.setItem(USER_KEY2, JSON.stringify(user));
|
|
1278
|
+
this.config.onAuthStateChange?.(user);
|
|
1279
|
+
}
|
|
1280
|
+
/**
|
|
1281
|
+
* Clear all auth state.
|
|
1282
|
+
*
|
|
1283
|
+
* @param forgetDevice - If true, also clear device token (for JSON mode)
|
|
1284
|
+
*/
|
|
1285
|
+
async clearAuthState(forgetDevice) {
|
|
1286
|
+
this.currentUser = null;
|
|
1287
|
+
await this.tokenManager.clearTokens();
|
|
1288
|
+
await this.config.storage.removeItem(USER_KEY2);
|
|
1289
|
+
if (forgetDevice && this.config.tokenDelivery === "json") {
|
|
1290
|
+
await this.config.storage.removeItem(this.config.deviceTrust.storageKey);
|
|
1291
|
+
}
|
|
1292
|
+
this.config.onAuthStateChange?.(null);
|
|
1293
|
+
}
|
|
1294
|
+
/**
|
|
1295
|
+
* Persist device token (json mode mobile).
|
|
1296
|
+
*/
|
|
1297
|
+
async setDeviceToken(token) {
|
|
1298
|
+
await this.config.storage.setItem(this.config.deviceTrust.storageKey, token);
|
|
1299
|
+
}
|
|
1300
|
+
/**
|
|
1301
|
+
* Determine token delivery mode for this environment.
|
|
1302
|
+
*/
|
|
1303
|
+
getTokenDeliveryMode() {
|
|
1304
|
+
return this.config.tokenDelivery;
|
|
1305
|
+
}
|
|
1306
|
+
/**
|
|
1307
|
+
* Build request URL by combining baseUrl with path.
|
|
1308
|
+
* @private
|
|
1309
|
+
*/
|
|
1310
|
+
buildUrl(path) {
|
|
1311
|
+
return `${this.config.baseUrl}${path}`;
|
|
1312
|
+
}
|
|
1313
|
+
/**
|
|
1314
|
+
* Build request headers for authentication.
|
|
1315
|
+
* @private
|
|
1316
|
+
*/
|
|
1317
|
+
async buildHeaders(auth) {
|
|
1318
|
+
const headers = {
|
|
1319
|
+
"Content-Type": "application/json",
|
|
1320
|
+
...this.config.headers
|
|
1321
|
+
};
|
|
1322
|
+
if (auth && this.config.tokenDelivery === "json") {
|
|
1323
|
+
const accessToken = (await this.tokenManager.getTokens()).accessToken;
|
|
1324
|
+
if (accessToken) {
|
|
1325
|
+
headers["Authorization"] = `Bearer ${accessToken}`;
|
|
1326
|
+
}
|
|
1327
|
+
}
|
|
1328
|
+
if (this.config.tokenDelivery === "cookies" && hasWindow()) {
|
|
1329
|
+
const csrfToken = this.getCsrfToken();
|
|
1330
|
+
if (csrfToken) {
|
|
1331
|
+
headers[this.config.csrf.headerName] = csrfToken;
|
|
1332
|
+
}
|
|
1333
|
+
}
|
|
1334
|
+
return headers;
|
|
1335
|
+
}
|
|
1336
|
+
/**
|
|
1337
|
+
* Get CSRF token from cookie (browser only).
|
|
1338
|
+
* @private
|
|
1339
|
+
*/
|
|
1340
|
+
getCsrfToken() {
|
|
1341
|
+
if (!hasWindow() || typeof document === "undefined") return null;
|
|
1342
|
+
const match = document.cookie.match(new RegExp(`(^| )${this.config.csrf.cookieName}=([^;]+)`));
|
|
1343
|
+
return match ? decodeURIComponent(match[2]) : null;
|
|
1344
|
+
}
|
|
1345
|
+
/**
|
|
1346
|
+
* Execute GET request.
|
|
1347
|
+
* Note: 401 refresh is handled by framework interceptors (Angular) or manually.
|
|
1348
|
+
*/
|
|
1349
|
+
async get(path, auth = false) {
|
|
1350
|
+
const url = this.buildUrl(path);
|
|
1351
|
+
const headers = await this.buildHeaders(auth);
|
|
1352
|
+
const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
|
|
1353
|
+
const response = await this.config.httpAdapter.request({
|
|
1354
|
+
method: "GET",
|
|
1355
|
+
url,
|
|
1356
|
+
headers,
|
|
1357
|
+
credentials
|
|
1358
|
+
});
|
|
1359
|
+
return response.data;
|
|
1360
|
+
}
|
|
1361
|
+
/**
|
|
1362
|
+
* Execute POST request.
|
|
1363
|
+
* Note: 401 refresh is handled by framework interceptors (Angular) or manually.
|
|
1364
|
+
*/
|
|
1365
|
+
async post(path, body, auth = false) {
|
|
1366
|
+
const url = this.buildUrl(path);
|
|
1367
|
+
const headers = await this.buildHeaders(auth);
|
|
1368
|
+
const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
|
|
1369
|
+
const response = await this.config.httpAdapter.request({
|
|
1370
|
+
method: "POST",
|
|
1371
|
+
url,
|
|
1372
|
+
headers,
|
|
1373
|
+
body,
|
|
1374
|
+
credentials
|
|
1375
|
+
});
|
|
1376
|
+
return response.data;
|
|
1377
|
+
}
|
|
1378
|
+
/**
|
|
1379
|
+
* Execute PUT request.
|
|
1380
|
+
* Note: 401 refresh is handled by framework interceptors (Angular) or manually.
|
|
1381
|
+
*/
|
|
1382
|
+
async put(path, body, auth = false) {
|
|
1383
|
+
const url = this.buildUrl(path);
|
|
1384
|
+
const headers = await this.buildHeaders(auth);
|
|
1385
|
+
const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
|
|
1386
|
+
const response = await this.config.httpAdapter.request({
|
|
1387
|
+
method: "PUT",
|
|
1388
|
+
url,
|
|
1389
|
+
headers,
|
|
1390
|
+
body,
|
|
1391
|
+
credentials
|
|
1392
|
+
});
|
|
1393
|
+
return response.data;
|
|
1394
|
+
}
|
|
1395
|
+
/**
|
|
1396
|
+
* Execute DELETE request.
|
|
1397
|
+
* Note: 401 refresh is handled by framework interceptors (Angular) or manually.
|
|
1398
|
+
*/
|
|
1399
|
+
async delete(path, auth = false) {
|
|
1400
|
+
const url = this.buildUrl(path);
|
|
1401
|
+
const headers = await this.buildHeaders(auth);
|
|
1402
|
+
const credentials = this.config.tokenDelivery === "cookies" ? "include" : "omit";
|
|
1403
|
+
const response = await this.config.httpAdapter.request({
|
|
1404
|
+
method: "DELETE",
|
|
1405
|
+
url,
|
|
1406
|
+
headers,
|
|
1407
|
+
credentials
|
|
1408
|
+
});
|
|
1409
|
+
return response.data;
|
|
1410
|
+
}
|
|
1411
|
+
};
|
|
1412
|
+
|
|
1413
|
+
// src/core/challenge-helpers.ts
|
|
1414
|
+
function requiresPhoneCollection(challenge) {
|
|
1415
|
+
if (challenge.challengeName !== "VERIFY_PHONE" /* VERIFY_PHONE */) {
|
|
1416
|
+
return false;
|
|
1417
|
+
}
|
|
1418
|
+
const params = challenge.challengeParameters;
|
|
1419
|
+
return params?.["requiresPhoneCollection"] === "true";
|
|
1420
|
+
}
|
|
1421
|
+
function getMaskedDestination(challenge) {
|
|
1422
|
+
const params = challenge.challengeParameters;
|
|
1423
|
+
if (!params) {
|
|
1424
|
+
return null;
|
|
1425
|
+
}
|
|
1426
|
+
const challengeName = challenge.challengeName;
|
|
1427
|
+
if (challengeName === "MFA_REQUIRED" /* MFA_REQUIRED */) {
|
|
1428
|
+
const method = params?.["preferredMethod"] || params?.["method"];
|
|
1429
|
+
if (method === "sms") {
|
|
1430
|
+
return params["maskedPhone"] || null;
|
|
1431
|
+
}
|
|
1432
|
+
if (method === "email") {
|
|
1433
|
+
return params["maskedEmail"] || null;
|
|
1434
|
+
}
|
|
1435
|
+
return params["maskedPhone"] || params["maskedEmail"] || null;
|
|
1436
|
+
}
|
|
1437
|
+
return params["codeDeliveryDestination"] || null;
|
|
1438
|
+
}
|
|
1439
|
+
function getMFAMethod(challenge) {
|
|
1440
|
+
if (challenge.challengeName !== "MFA_REQUIRED" /* MFA_REQUIRED */) {
|
|
1441
|
+
return void 0;
|
|
1442
|
+
}
|
|
1443
|
+
const params = challenge.challengeParameters;
|
|
1444
|
+
return params?.["preferredMethod"] || params?.["method"];
|
|
1445
|
+
}
|
|
1446
|
+
function getChallengeInstructions(challenge) {
|
|
1447
|
+
const params = challenge.challengeParameters;
|
|
1448
|
+
return params?.["instructions"];
|
|
1449
|
+
}
|
|
1450
|
+
function isOTPChallenge(challenge) {
|
|
1451
|
+
const challengeName = challenge.challengeName;
|
|
1452
|
+
return challengeName === "VERIFY_EMAIL" /* VERIFY_EMAIL */ || challengeName === "VERIFY_PHONE" /* VERIFY_PHONE */ || challengeName === "MFA_REQUIRED" /* MFA_REQUIRED */;
|
|
1453
|
+
}
|
|
1454
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1455
|
+
0 && (module.exports = {
|
|
1456
|
+
AuthAuditEventType,
|
|
1457
|
+
AuthChallenge,
|
|
1458
|
+
BrowserStorage,
|
|
1459
|
+
EventEmitter,
|
|
1460
|
+
FetchAdapter,
|
|
1461
|
+
InMemoryStorage,
|
|
1462
|
+
NAuthClient,
|
|
1463
|
+
NAuthClientError,
|
|
1464
|
+
NAuthErrorCode,
|
|
1465
|
+
defaultEndpoints,
|
|
1466
|
+
getChallengeInstructions,
|
|
1467
|
+
getMFAMethod,
|
|
1468
|
+
getMaskedDestination,
|
|
1469
|
+
isOTPChallenge,
|
|
1470
|
+
requiresPhoneCollection,
|
|
1471
|
+
resolveConfig
|
|
1472
|
+
});
|
|
1473
|
+
//# sourceMappingURL=index.cjs.map
|