aegis-auth-navchetna 1.0.0

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/README.md ADDED
@@ -0,0 +1,383 @@
1
+ # Aegis Auth - JavaScript SDK
2
+
3
+ **Aegis Auth is a unified identity management system providing memory-safe Rust-based authentication. Consolidation of disparate identity providers into a single canonical source.**
4
+
5
+ *Aegis Auth by Navchetna Technologies.*
6
+ *Securing the future of decentralized identity.*
7
+ *© 2026 Standard Core v3.*
8
+
9
+ ---
10
+
11
+ Official JavaScript SDK for the Aegis Authentication System. Supports traditional authentication, WebAuthn/Passkeys, MFA, and more.
12
+
13
+ ## Installation
14
+
15
+ ### Via CDN
16
+ ```html
17
+ <script src="https://cdn.jsdelivr.net/npm/aegis-auth-navchetna@latest/aegis-sdk.min.js"></script>
18
+ ```
19
+
20
+ ### Via npm
21
+ ```bash
22
+ npm install aegis-auth-navchetna
23
+ ```
24
+
25
+ ### Via yarn
26
+ ```bash
27
+ yarn add aegis-auth-navchetna
28
+ ```
29
+
30
+ ## Quick Start
31
+
32
+ ### CDN Usage
33
+ ```html
34
+ <!DOCTYPE html>
35
+ <html>
36
+ <head>
37
+ <script src="https://cdn.jsdelivr.net/npm/@aegis/auth-sdk@latest/aegis-sdk.min.js"></script>
38
+ </head>
39
+ <body>
40
+ <script>
41
+ const aegis = Aegis.create({
42
+ apiKey: 'your-api-key-here'
43
+ });
44
+
45
+ // Login example
46
+ aegis.login('user@example.com', 'password')
47
+ .then(response => {
48
+ console.log('Logged in:', response.user);
49
+ })
50
+ .catch(error => {
51
+ console.error('Login failed:', error);
52
+ });
53
+ </script>
54
+ </body>
55
+ </html>
56
+ ```
57
+
58
+ ### ES6 Module Usage
59
+ ```javascript
60
+ import Aegis from 'aegis-auth-navchetna';
61
+
62
+ const aegis = Aegis.create({
63
+ apiKey: 'your-api-key-here',
64
+ baseURL: 'https://your-aegis-instance.com' // Optional
65
+ });
66
+ ```
67
+
68
+ ### CommonJS Usage
69
+ ```javascript
70
+ const Aegis = require('aegis-auth-navchetna');
71
+
72
+ const aegis = Aegis.create({
73
+ apiKey: 'your-api-key-here'
74
+ });
75
+ ```
76
+
77
+ ## Configuration
78
+
79
+ ```javascript
80
+ const aegis = Aegis.create({
81
+ apiKey: 'your-api-key-here', // Required: Your project API key
82
+ baseURL: 'https://your-instance.com' // Optional: Custom Aegis instance URL
83
+ });
84
+ ```
85
+
86
+ ## Authentication Methods
87
+
88
+ ### Email/Password Authentication
89
+
90
+ #### Login
91
+ ```javascript
92
+ try {
93
+ const response = await aegis.login('user@example.com', 'password');
94
+ console.log('User:', response.user);
95
+ console.log('Access Token:', response.access_token);
96
+ } catch (error) {
97
+ console.error('Login failed:', error.message);
98
+ }
99
+ ```
100
+
101
+ #### Register
102
+ ```javascript
103
+ try {
104
+ const response = await aegis.register({
105
+ email: 'user@example.com',
106
+ password: 'securePassword123',
107
+ first_name: 'John',
108
+ last_name: 'Doe'
109
+ });
110
+ console.log('Registration successful:', response);
111
+ } catch (error) {
112
+ console.error('Registration failed:', error.message);
113
+ }
114
+ ```
115
+
116
+ #### Logout
117
+ ```javascript
118
+ await aegis.logout();
119
+ ```
120
+
121
+ ### WebAuthn/Passkeys
122
+
123
+ #### Check WebAuthn Support
124
+ ```javascript
125
+ if (aegis.isWebAuthnSupported()) {
126
+ console.log('WebAuthn is supported');
127
+ } else {
128
+ console.log('WebAuthn is not supported');
129
+ }
130
+ ```
131
+
132
+ #### Register WebAuthn Credential
133
+ ```javascript
134
+ try {
135
+ const response = await aegis.startWebAuthnRegistration();
136
+ console.log('WebAuthn credential registered:', response);
137
+ } catch (error) {
138
+ console.error('WebAuthn registration failed:', error.message);
139
+ }
140
+ ```
141
+
142
+ #### Login with WebAuthn
143
+ ```javascript
144
+ try {
145
+ const response = await aegis.startWebAuthnLogin();
146
+ console.log('WebAuthn login successful:', response.user);
147
+ } catch (error) {
148
+ console.error('WebAuthn login failed:', error.message);
149
+ }
150
+ ```
151
+
152
+ ### Multi-Factor Authentication (MFA)
153
+
154
+ #### Enable MFA
155
+ ```javascript
156
+ try {
157
+ const response = await aegis.enableMFA();
158
+ console.log('QR Code:', response.qr_code);
159
+ console.log('Secret:', response.secret);
160
+ console.log('Backup Codes:', response.backup_codes);
161
+ } catch (error) {
162
+ console.error('MFA enable failed:', error.message);
163
+ }
164
+ ```
165
+
166
+ #### Verify MFA Code
167
+ ```javascript
168
+ try {
169
+ const response = await aegis.verifyMFA('123456');
170
+ console.log('MFA verified:', response);
171
+ } catch (error) {
172
+ console.error('MFA verification failed:', error.message);
173
+ }
174
+ ```
175
+
176
+ #### Disable MFA
177
+ ```javascript
178
+ try {
179
+ await aegis.disableMFA('123456');
180
+ console.log('MFA disabled');
181
+ } catch (error) {
182
+ console.error('MFA disable failed:', error.message);
183
+ }
184
+ ```
185
+
186
+ ### Password Reset
187
+
188
+ #### Request Password Reset
189
+ ```javascript
190
+ try {
191
+ await aegis.forgotPassword('user@example.com');
192
+ console.log('Password reset email sent');
193
+ } catch (error) {
194
+ console.error('Password reset request failed:', error.message);
195
+ }
196
+ ```
197
+
198
+ #### Reset Password
199
+ ```javascript
200
+ try {
201
+ await aegis.resetPassword('reset-token', 'newPassword123');
202
+ console.log('Password reset successful');
203
+ } catch (error) {
204
+ console.error('Password reset failed:', error.message);
205
+ }
206
+ ```
207
+
208
+ ## User Profile Management
209
+
210
+ ### Get User Profile
211
+ ```javascript
212
+ try {
213
+ const profile = await aegis.getProfile();
214
+ console.log('User profile:', profile);
215
+ } catch (error) {
216
+ console.error('Failed to get profile:', error.message);
217
+ }
218
+ ```
219
+
220
+ ### Update User Profile
221
+ ```javascript
222
+ try {
223
+ const response = await aegis.updateProfile({
224
+ first_name: 'Jane',
225
+ last_name: 'Smith',
226
+ phone: '+1234567890'
227
+ });
228
+ console.log('Profile updated:', response);
229
+ } catch (error) {
230
+ console.error('Profile update failed:', error.message);
231
+ }
232
+ ```
233
+
234
+ ## Token Management
235
+
236
+ ### Check Authentication Status
237
+ ```javascript
238
+ if (aegis.isAuthenticated()) {
239
+ console.log('User is authenticated');
240
+ console.log('Current user:', aegis.getUser());
241
+ } else {
242
+ console.log('User is not authenticated');
243
+ }
244
+ ```
245
+
246
+ ### Get Access Token
247
+ ```javascript
248
+ const token = aegis.getAccessToken();
249
+ if (token) {
250
+ console.log('Access token:', token);
251
+ }
252
+ ```
253
+
254
+ ### Manual Token Refresh
255
+ ```javascript
256
+ try {
257
+ const response = await aegis.refreshAccessToken();
258
+ console.log('Token refreshed:', response);
259
+ } catch (error) {
260
+ console.error('Token refresh failed:', error.message);
261
+ }
262
+ ```
263
+
264
+ ## Event Handling
265
+
266
+ The SDK emits events for various authentication states:
267
+
268
+ ```javascript
269
+ // Listen for login events
270
+ aegis.on('login', (user) => {
271
+ console.log('User logged in:', user);
272
+ });
273
+
274
+ // Listen for logout events
275
+ aegis.on('logout', () => {
276
+ console.log('User logged out');
277
+ });
278
+
279
+ // Listen for token refresh events
280
+ aegis.on('tokenRefresh', (user) => {
281
+ console.log('Token refreshed for user:', user);
282
+ });
283
+
284
+ // Listen for error events
285
+ aegis.on('error', (errorData) => {
286
+ console.error('SDK Error:', errorData.error);
287
+ console.error('Endpoint:', errorData.endpoint);
288
+ });
289
+ ```
290
+
291
+ ## Advanced Usage
292
+
293
+ ### Custom Request Headers
294
+ ```javascript
295
+ const response = await aegis.request('/custom/endpoint', {
296
+ method: 'POST',
297
+ headers: {
298
+ 'Custom-Header': 'value'
299
+ },
300
+ body: { data: 'example' }
301
+ });
302
+ ```
303
+
304
+ ### Skip Authentication for Public Endpoints
305
+ ```javascript
306
+ const response = await aegis.request('/public/endpoint', {
307
+ skipAuth: true
308
+ });
309
+ ```
310
+
311
+ ## Error Handling
312
+
313
+ The SDK throws descriptive errors that you can catch and handle:
314
+
315
+ ```javascript
316
+ try {
317
+ await aegis.login('user@example.com', 'wrongpassword');
318
+ } catch (error) {
319
+ if (error.message.includes('Invalid credentials')) {
320
+ // Handle invalid credentials
321
+ console.log('Please check your email and password');
322
+ } else if (error.message.includes('Network')) {
323
+ // Handle network errors
324
+ console.log('Please check your internet connection');
325
+ } else {
326
+ // Handle other errors
327
+ console.log('An unexpected error occurred');
328
+ }
329
+ }
330
+ ```
331
+
332
+ ## Browser Compatibility
333
+
334
+ - Chrome 67+
335
+ - Firefox 60+
336
+ - Safari 13+
337
+ - Edge 79+
338
+
339
+ WebAuthn features require HTTPS in production.
340
+
341
+ ## TypeScript Support
342
+
343
+ The SDK includes TypeScript definitions:
344
+
345
+ ```typescript
346
+ import Aegis, { AegisConfig, User, AuthResponse } from 'aegis-auth-navchetna';
347
+
348
+ const config: AegisConfig = {
349
+ apiKey: 'your-api-key'
350
+ };
351
+
352
+ const aegis = Aegis.create(config);
353
+
354
+ aegis.login('user@example.com', 'password')
355
+ .then((response: AuthResponse) => {
356
+ const user: User = response.user;
357
+ console.log('Logged in user:', user);
358
+ });
359
+ ```
360
+
361
+ ## Security Best Practices
362
+
363
+ 1. **Never expose your API key** in client-side code in production
364
+ 2. **Use HTTPS** in production environments
365
+ 3. **Implement proper error handling** to avoid exposing sensitive information
366
+ 4. **Store tokens securely** - the SDK uses localStorage by default
367
+ 5. **Implement logout functionality** to clear tokens when users sign out
368
+
369
+ ## Support
370
+
371
+ - Documentation: [https://docs.aegis.com](https://docs.aegis.com)
372
+ - Issues: [https://github.com/navchetna/aegis-auth-sdk/issues](https://github.com/navchetna/aegis-auth-sdk/issues)
373
+ - Email: support@navchetna.com
374
+
375
+ ---
376
+
377
+ **Aegis Auth by Navchetna Technologies**
378
+ *Securing the future of decentralized identity*
379
+ © 2026 Standard Core v3
380
+
381
+ ## License
382
+
383
+ MIT License - see LICENSE file for details.
package/aegis-sdk.d.ts ADDED
@@ -0,0 +1,133 @@
1
+ export interface AegisConfig {
2
+ apiKey: string;
3
+ baseURL?: string;
4
+ }
5
+
6
+ export interface User {
7
+ id: string;
8
+ email: string;
9
+ first_name?: string;
10
+ last_name?: string;
11
+ role?: string;
12
+ organization_id?: string;
13
+ permissions?: string[];
14
+ }
15
+
16
+ export interface AuthResponse {
17
+ access_token: string;
18
+ refresh_token: string;
19
+ expires_in: number;
20
+ token_type: string;
21
+ user: User;
22
+ }
23
+
24
+ export interface RegisterData {
25
+ email: string;
26
+ password: string;
27
+ first_name?: string;
28
+ last_name?: string;
29
+ }
30
+
31
+ export interface ProfileData {
32
+ first_name?: string;
33
+ last_name?: string;
34
+ phone?: string;
35
+ }
36
+
37
+ export interface WebAuthnCredential {
38
+ id: string;
39
+ rawId: number[];
40
+ response: {
41
+ attestationObject: number[];
42
+ clientDataJSON: number[];
43
+ };
44
+ type: string;
45
+ }
46
+
47
+ export interface WebAuthnAssertion {
48
+ id: string;
49
+ rawId: number[];
50
+ response: {
51
+ authenticatorData: number[];
52
+ clientDataJSON: number[];
53
+ signature: number[];
54
+ userHandle: number[] | null;
55
+ };
56
+ type: string;
57
+ }
58
+
59
+ export interface MFAResponse {
60
+ qr_code?: string;
61
+ secret?: string;
62
+ backup_codes?: string[];
63
+ }
64
+
65
+ export type EventType = 'login' | 'logout' | 'tokenRefresh' | 'error';
66
+
67
+ export interface ErrorEvent {
68
+ error: Error;
69
+ endpoint?: string;
70
+ type?: string;
71
+ }
72
+
73
+ export class AegisSDK {
74
+ constructor(config: AegisConfig);
75
+
76
+ // Event handling
77
+ on(event: EventType, callback: (data: any) => void): void;
78
+ emit(event: EventType, data: any): void;
79
+
80
+ // HTTP requests
81
+ request(endpoint: string, options?: {
82
+ method?: string;
83
+ headers?: Record<string, string>;
84
+ body?: any;
85
+ skipAuth?: boolean;
86
+ fetchOptions?: RequestInit;
87
+ }): Promise<any>;
88
+
89
+ // Authentication
90
+ login(email: string, password: string): Promise<AuthResponse>;
91
+ register(userData: RegisterData): Promise<any>;
92
+ logout(): Promise<void>;
93
+ refreshAccessToken(): Promise<AuthResponse>;
94
+
95
+ // WebAuthn
96
+ startWebAuthnRegistration(): Promise<any>;
97
+ completeWebAuthnRegistration(credential: PublicKeyCredential): Promise<any>;
98
+ startWebAuthnLogin(): Promise<AuthResponse>;
99
+ completeWebAuthnLogin(assertion: PublicKeyCredential): Promise<AuthResponse>;
100
+
101
+ // MFA
102
+ enableMFA(): Promise<MFAResponse>;
103
+ verifyMFA(code: string): Promise<any>;
104
+ disableMFA(code: string): Promise<any>;
105
+
106
+ // Password reset
107
+ forgotPassword(email: string): Promise<any>;
108
+ resetPassword(token: string, newPassword: string): Promise<any>;
109
+
110
+ // Profile
111
+ getProfile(): Promise<User>;
112
+ updateProfile(profileData: ProfileData): Promise<any>;
113
+
114
+ // Token management
115
+ setTokens(authData: AuthResponse): void;
116
+ clearTokens(): void;
117
+ loadTokensFromStorage(): boolean;
118
+ setupTokenRefresh(): void;
119
+
120
+ // Utility methods
121
+ isAuthenticated(): boolean;
122
+ getUser(): User | null;
123
+ getAccessToken(): string | null;
124
+ isWebAuthnSupported(): boolean;
125
+ }
126
+
127
+ export interface AegisFactory {
128
+ create(config: AegisConfig): AegisSDK;
129
+ AegisSDK: typeof AegisSDK;
130
+ }
131
+
132
+ declare const Aegis: AegisFactory;
133
+ export default Aegis;
package/aegis-sdk.js ADDED
@@ -0,0 +1,404 @@
1
+ /**
2
+ * Aegis Authentication SDK
3
+ * Client-side JavaScript SDK for Aegis Authentication System
4
+ * Version: 1.0.0
5
+ */
6
+
7
+ (function(global, factory) {
8
+ if (typeof exports === 'object' && typeof module !== 'undefined') {
9
+ module.exports = factory();
10
+ } else if (typeof define === 'function' && define.amd) {
11
+ define(factory);
12
+ } else {
13
+ global.Aegis = factory();
14
+ }
15
+ }(typeof self !== 'undefined' ? self : this, function() {
16
+ 'use strict';
17
+
18
+ class AegisSDK {
19
+ constructor(config) {
20
+ this.apiKey = config.apiKey;
21
+ this.baseURL = config.baseURL || 'https://05card1j5b.execute-api.ap-south-1.amazonaws.com/prod';
22
+ this.accessToken = null;
23
+ this.refreshToken = null;
24
+ this.user = null;
25
+ this.tokenExpiry = null;
26
+
27
+ // Event listeners
28
+ this.listeners = {
29
+ login: [],
30
+ logout: [],
31
+ tokenRefresh: [],
32
+ error: []
33
+ };
34
+
35
+ // Auto-refresh token setup
36
+ this.refreshInterval = null;
37
+ this.setupTokenRefresh();
38
+ }
39
+
40
+ // Event handling
41
+ on(event, callback) {
42
+ if (this.listeners[event]) {
43
+ this.listeners[event].push(callback);
44
+ }
45
+ }
46
+
47
+ emit(event, data) {
48
+ if (this.listeners[event]) {
49
+ this.listeners[event].forEach(callback => callback(data));
50
+ }
51
+ }
52
+
53
+ // HTTP request helper
54
+ async request(endpoint, options = {}) {
55
+ const url = `${this.baseURL}${endpoint}`;
56
+ const headers = {
57
+ 'Content-Type': 'application/json',
58
+ ...options.headers
59
+ };
60
+
61
+ if (this.apiKey) {
62
+ headers['X-API-Key'] = this.apiKey;
63
+ }
64
+
65
+ if (this.accessToken && !options.skipAuth) {
66
+ headers['Authorization'] = `Bearer ${this.accessToken}`;
67
+ }
68
+
69
+ try {
70
+ const response = await fetch(url, {
71
+ method: options.method || 'GET',
72
+ headers,
73
+ body: options.body ? JSON.stringify(options.body) : undefined,
74
+ ...options.fetchOptions
75
+ });
76
+
77
+ const data = await response.json();
78
+
79
+ if (!response.ok) {
80
+ throw new Error(data.message || `HTTP ${response.status}`);
81
+ }
82
+
83
+ return data;
84
+ } catch (error) {
85
+ this.emit('error', { error, endpoint });
86
+ throw error;
87
+ }
88
+ }
89
+
90
+ // Authentication methods
91
+ async login(email, password) {
92
+ try {
93
+ const response = await this.request('/auth/login', {
94
+ method: 'POST',
95
+ body: { email, password },
96
+ skipAuth: true
97
+ });
98
+
99
+ this.setTokens(response.data);
100
+ this.emit('login', this.user);
101
+ return response.data;
102
+ } catch (error) {
103
+ throw new Error(`Login failed: ${error.message}`);
104
+ }
105
+ }
106
+
107
+ async register(userData) {
108
+ try {
109
+ const response = await this.request('/auth/register', {
110
+ method: 'POST',
111
+ body: userData,
112
+ skipAuth: true
113
+ });
114
+
115
+ return response.data;
116
+ } catch (error) {
117
+ throw new Error(`Registration failed: ${error.message}`);
118
+ }
119
+ }
120
+
121
+ async logout() {
122
+ try {
123
+ if (this.accessToken) {
124
+ await this.request('/auth/logout', {
125
+ method: 'POST'
126
+ });
127
+ }
128
+ } catch (error) {
129
+ console.warn('Logout request failed:', error.message);
130
+ } finally {
131
+ this.clearTokens();
132
+ this.emit('logout');
133
+ }
134
+ }
135
+
136
+ async refreshAccessToken() {
137
+ if (!this.refreshToken) {
138
+ throw new Error('No refresh token available');
139
+ }
140
+
141
+ try {
142
+ const response = await this.request('/auth/refresh', {
143
+ method: 'POST',
144
+ body: { refresh_token: this.refreshToken },
145
+ skipAuth: true
146
+ });
147
+
148
+ this.setTokens(response.data);
149
+ this.emit('tokenRefresh', this.user);
150
+ return response.data;
151
+ } catch (error) {
152
+ this.clearTokens();
153
+ throw new Error(`Token refresh failed: ${error.message}`);
154
+ }
155
+ }
156
+
157
+ // WebAuthn methods
158
+ async startWebAuthnRegistration() {
159
+ try {
160
+ const response = await this.request('/auth/webauthn/register/start', {
161
+ method: 'POST'
162
+ });
163
+
164
+ const credential = await navigator.credentials.create({
165
+ publicKey: response.data.options
166
+ });
167
+
168
+ return await this.completeWebAuthnRegistration(credential);
169
+ } catch (error) {
170
+ throw new Error(`WebAuthn registration failed: ${error.message}`);
171
+ }
172
+ }
173
+
174
+ async completeWebAuthnRegistration(credential) {
175
+ const credentialData = {
176
+ id: credential.id,
177
+ rawId: Array.from(new Uint8Array(credential.rawId)),
178
+ response: {
179
+ attestationObject: Array.from(new Uint8Array(credential.response.attestationObject)),
180
+ clientDataJSON: Array.from(new Uint8Array(credential.response.clientDataJSON))
181
+ },
182
+ type: credential.type
183
+ };
184
+
185
+ return await this.request('/auth/webauthn/register/complete', {
186
+ method: 'POST',
187
+ body: { credential: credentialData }
188
+ });
189
+ }
190
+
191
+ async startWebAuthnLogin() {
192
+ try {
193
+ const response = await this.request('/auth/webauthn/login/start', {
194
+ method: 'POST',
195
+ skipAuth: true
196
+ });
197
+
198
+ const assertion = await navigator.credentials.get({
199
+ publicKey: response.data.options
200
+ });
201
+
202
+ return await this.completeWebAuthnLogin(assertion);
203
+ } catch (error) {
204
+ throw new Error(`WebAuthn login failed: ${error.message}`);
205
+ }
206
+ }
207
+
208
+ async completeWebAuthnLogin(assertion) {
209
+ const assertionData = {
210
+ id: assertion.id,
211
+ rawId: Array.from(new Uint8Array(assertion.rawId)),
212
+ response: {
213
+ authenticatorData: Array.from(new Uint8Array(assertion.response.authenticatorData)),
214
+ clientDataJSON: Array.from(new Uint8Array(assertion.response.clientDataJSON)),
215
+ signature: Array.from(new Uint8Array(assertion.response.signature)),
216
+ userHandle: assertion.response.userHandle ? Array.from(new Uint8Array(assertion.response.userHandle)) : null
217
+ },
218
+ type: assertion.type
219
+ };
220
+
221
+ const response = await this.request('/auth/webauthn/login/complete', {
222
+ method: 'POST',
223
+ body: { assertion: assertionData },
224
+ skipAuth: true
225
+ });
226
+
227
+ this.setTokens(response.data);
228
+ this.emit('login', this.user);
229
+ return response.data;
230
+ }
231
+
232
+ // MFA methods
233
+ async enableMFA() {
234
+ return await this.request('/auth/mfa/enable', {
235
+ method: 'POST'
236
+ });
237
+ }
238
+
239
+ async verifyMFA(code) {
240
+ return await this.request('/auth/mfa/verify', {
241
+ method: 'POST',
242
+ body: { code }
243
+ });
244
+ }
245
+
246
+ async disableMFA(code) {
247
+ return await this.request('/auth/mfa/disable', {
248
+ method: 'POST',
249
+ body: { code }
250
+ });
251
+ }
252
+
253
+ // Password reset
254
+ async forgotPassword(email) {
255
+ return await this.request('/auth/forgot-password', {
256
+ method: 'POST',
257
+ body: { email },
258
+ skipAuth: true
259
+ });
260
+ }
261
+
262
+ async resetPassword(token, newPassword) {
263
+ return await this.request('/auth/reset-password', {
264
+ method: 'POST',
265
+ body: { token, new_password: newPassword },
266
+ skipAuth: true
267
+ });
268
+ }
269
+
270
+ // User profile
271
+ async getProfile() {
272
+ return await this.request('/auth/profile');
273
+ }
274
+
275
+ async updateProfile(profileData) {
276
+ return await this.request('/auth/profile', {
277
+ method: 'PATCH',
278
+ body: profileData
279
+ });
280
+ }
281
+
282
+ // Token management
283
+ setTokens(authData) {
284
+ this.accessToken = authData.access_token;
285
+ this.refreshToken = authData.refresh_token;
286
+ this.user = authData.user;
287
+ this.tokenExpiry = Date.now() + (authData.expires_in * 1000);
288
+
289
+ // Store in localStorage
290
+ if (typeof localStorage !== 'undefined') {
291
+ localStorage.setItem('aegis_access_token', this.accessToken);
292
+ localStorage.setItem('aegis_refresh_token', this.refreshToken);
293
+ localStorage.setItem('aegis_user', JSON.stringify(this.user));
294
+ localStorage.setItem('aegis_token_expiry', this.tokenExpiry.toString());
295
+ }
296
+
297
+ this.setupTokenRefresh();
298
+ }
299
+
300
+ clearTokens() {
301
+ this.accessToken = null;
302
+ this.refreshToken = null;
303
+ this.user = null;
304
+ this.tokenExpiry = null;
305
+
306
+ if (this.refreshInterval) {
307
+ clearInterval(this.refreshInterval);
308
+ this.refreshInterval = null;
309
+ }
310
+
311
+ // Clear from localStorage
312
+ if (typeof localStorage !== 'undefined') {
313
+ localStorage.removeItem('aegis_access_token');
314
+ localStorage.removeItem('aegis_refresh_token');
315
+ localStorage.removeItem('aegis_user');
316
+ localStorage.removeItem('aegis_token_expiry');
317
+ }
318
+ }
319
+
320
+ loadTokensFromStorage() {
321
+ if (typeof localStorage === 'undefined') return false;
322
+
323
+ const accessToken = localStorage.getItem('aegis_access_token');
324
+ const refreshToken = localStorage.getItem('aegis_refresh_token');
325
+ const user = localStorage.getItem('aegis_user');
326
+ const tokenExpiry = localStorage.getItem('aegis_token_expiry');
327
+
328
+ if (accessToken && refreshToken && user && tokenExpiry) {
329
+ this.accessToken = accessToken;
330
+ this.refreshToken = refreshToken;
331
+ this.user = JSON.parse(user);
332
+ this.tokenExpiry = parseInt(tokenExpiry);
333
+
334
+ // Check if token is expired
335
+ if (Date.now() >= this.tokenExpiry) {
336
+ this.clearTokens();
337
+ return false;
338
+ }
339
+
340
+ this.setupTokenRefresh();
341
+ return true;
342
+ }
343
+
344
+ return false;
345
+ }
346
+
347
+ setupTokenRefresh() {
348
+ if (this.refreshInterval) {
349
+ clearInterval(this.refreshInterval);
350
+ }
351
+
352
+ if (this.tokenExpiry) {
353
+ const refreshTime = this.tokenExpiry - Date.now() - 60000; // Refresh 1 minute before expiry
354
+ if (refreshTime > 0) {
355
+ this.refreshInterval = setTimeout(async () => {
356
+ try {
357
+ await this.refreshAccessToken();
358
+ } catch (error) {
359
+ this.emit('error', { error, type: 'token_refresh' });
360
+ }
361
+ }, refreshTime);
362
+ }
363
+ }
364
+ }
365
+
366
+ // Utility methods
367
+ isAuthenticated() {
368
+ return !!(this.accessToken && this.tokenExpiry && Date.now() < this.tokenExpiry);
369
+ }
370
+
371
+ getUser() {
372
+ return this.user;
373
+ }
374
+
375
+ getAccessToken() {
376
+ return this.accessToken;
377
+ }
378
+
379
+ // WebAuthn support check
380
+ isWebAuthnSupported() {
381
+ return !!(navigator.credentials && navigator.credentials.create && navigator.credentials.get);
382
+ }
383
+ }
384
+
385
+ // Factory function
386
+ function createAegisSDK(config) {
387
+ if (!config || !config.apiKey) {
388
+ throw new Error('Aegis SDK requires an API key');
389
+ }
390
+
391
+ const sdk = new AegisSDK(config);
392
+
393
+ // Try to load existing tokens
394
+ sdk.loadTokensFromStorage();
395
+
396
+ return sdk;
397
+ }
398
+
399
+ // Export
400
+ return {
401
+ create: createAegisSDK,
402
+ AegisSDK
403
+ };
404
+ }));
@@ -0,0 +1 @@
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):e.Aegis=t()}("undefined"!=typeof self?self:this,function(){"use strict";class e{constructor(e){this.apiKey=e.apiKey,this.baseURL=e.baseURL||"https://05card1j5b.execute-api.ap-south-1.amazonaws.com/prod",this.accessToken=null,this.refreshToken=null,this.user=null,this.tokenExpiry=null,this.listeners={login:[],logout:[],tokenRefresh:[],error:[]},this.refreshInterval=null,this.setupTokenRefresh()}on(e,t){this.listeners[e]&&this.listeners[e].push(t)}emit(e,t){this.listeners[e]&&this.listeners[e].forEach(e=>e(t))}async request(e,t={}){const n=`${this.baseURL}${e}`,s={"Content-Type":"application/json",...t.headers};this.apiKey&&(s["X-API-Key"]=this.apiKey),this.accessToken&&!t.skipAuth&&(s.Authorization=`Bearer ${this.accessToken}`);try{const e=await fetch(n,{method:t.method||"GET",headers:s,body:t.body?JSON.stringify(t.body):void 0,...t.fetchOptions}),r=await e.json();if(!e.ok)throw new Error(r.message||`HTTP ${e.status}`);return r}catch(t){throw this.emit("error",{error:t,endpoint:e}),t}}async login(e,t){try{const n=await this.request("/auth/login",{method:"POST",body:{email:e,password:t},skipAuth:!0});return this.setTokens(n.data),this.emit("login",this.user),n.data}catch(e){throw new Error(`Login failed: ${e.message}`)}}async register(e){try{return(await this.request("/auth/register",{method:"POST",body:e,skipAuth:!0})).data}catch(e){throw new Error(`Registration failed: ${e.message}`)}}async logout(){try{this.accessToken&&await this.request("/auth/logout",{method:"POST"})}catch(e){console.warn("Logout request failed:",e.message)}finally{this.clearTokens(),this.emit("logout")}}async refreshAccessToken(){if(!this.refreshToken)throw new Error("No refresh token available");try{const e=await this.request("/auth/refresh",{method:"POST",body:{refresh_token:this.refreshToken},skipAuth:!0});return this.setTokens(e.data),this.emit("tokenRefresh",this.user),e.data}catch(e){throw this.clearTokens(),new Error(`Token refresh failed: ${e.message}`)}}async startWebAuthnRegistration(){try{const e=await this.request("/auth/webauthn/register/start",{method:"POST"}),t=await navigator.credentials.create({publicKey:e.data.options});return await this.completeWebAuthnRegistration(t)}catch(e){throw new Error(`WebAuthn registration failed: ${e.message}`)}}async completeWebAuthnRegistration(e){const t={id:e.id,rawId:Array.from(new Uint8Array(e.rawId)),response:{attestationObject:Array.from(new Uint8Array(e.response.attestationObject)),clientDataJSON:Array.from(new Uint8Array(e.response.clientDataJSON))},type:e.type};return await this.request("/auth/webauthn/register/complete",{method:"POST",body:{credential:t}})}async startWebAuthnLogin(){try{const e=await this.request("/auth/webauthn/login/start",{method:"POST",skipAuth:!0}),t=await navigator.credentials.get({publicKey:e.data.options});return await this.completeWebAuthnLogin(t)}catch(e){throw new Error(`WebAuthn login failed: ${e.message}`)}}async completeWebAuthnLogin(e){const t={id:e.id,rawId:Array.from(new Uint8Array(e.rawId)),response:{authenticatorData:Array.from(new Uint8Array(e.response.authenticatorData)),clientDataJSON:Array.from(new Uint8Array(e.response.clientDataJSON)),signature:Array.from(new Uint8Array(e.response.signature)),userHandle:e.response.userHandle?Array.from(new Uint8Array(e.response.userHandle)):null},type:e.type},n=await this.request("/auth/webauthn/login/complete",{method:"POST",body:{assertion:t},skipAuth:!0});return this.setTokens(n.data),this.emit("login",this.user),n.data}async enableMFA(){return await this.request("/auth/mfa/enable",{method:"POST"})}async verifyMFA(e){return await this.request("/auth/mfa/verify",{method:"POST",body:{code:e}})}async disableMFA(e){return await this.request("/auth/mfa/disable",{method:"POST",body:{code:e}})}async forgotPassword(e){return await this.request("/auth/forgot-password",{method:"POST",body:{email:e},skipAuth:!0})}async resetPassword(e,t){return await this.request("/auth/reset-password",{method:"POST",body:{token:e,new_password:t},skipAuth:!0})}async getProfile(){return await this.request("/auth/profile")}async updateProfile(e){return await this.request("/auth/profile",{method:"PATCH",body:e})}setTokens(e){this.accessToken=e.access_token,this.refreshToken=e.refresh_token,this.user=e.user,this.tokenExpiry=Date.now()+1e3*e.expires_in,"undefined"!=typeof localStorage&&(localStorage.setItem("aegis_access_token",this.accessToken),localStorage.setItem("aegis_refresh_token",this.refreshToken),localStorage.setItem("aegis_user",JSON.stringify(this.user)),localStorage.setItem("aegis_token_expiry",this.tokenExpiry.toString())),this.setupTokenRefresh()}clearTokens(){this.accessToken=null,this.refreshToken=null,this.user=null,this.tokenExpiry=null,this.refreshInterval&&(clearInterval(this.refreshInterval),this.refreshInterval=null),"undefined"!=typeof localStorage&&(localStorage.removeItem("aegis_access_token"),localStorage.removeItem("aegis_refresh_token"),localStorage.removeItem("aegis_user"),localStorage.removeItem("aegis_token_expiry"))}loadTokensFromStorage(){if("undefined"==typeof localStorage)return!1;const e=localStorage.getItem("aegis_access_token"),t=localStorage.getItem("aegis_refresh_token"),n=localStorage.getItem("aegis_user"),s=localStorage.getItem("aegis_token_expiry");return!!(e&&t&&n&&s)&&(this.accessToken=e,this.refreshToken=t,this.user=JSON.parse(n),this.tokenExpiry=parseInt(s),!(Date.now()>=this.tokenExpiry)||(this.clearTokens(),!1)&&(this.setupTokenRefresh(),!0))}setupTokenRefresh(){this.refreshInterval&&clearInterval(this.refreshInterval),this.tokenExpiry&&(e=>{e>0&&(this.refreshInterval=setTimeout(async()=>{try{await this.refreshAccessToken()}catch(e){this.emit("error",{error:e,type:"token_refresh"})}},e))})(this.tokenExpiry-Date.now()-6e4)}isAuthenticated(){return!!(this.accessToken&&this.tokenExpiry&&Date.now()<this.tokenExpiry)}getUser(){return this.user}getAccessToken(){return this.accessToken}isWebAuthnSupported(){return!!(navigator.credentials&&navigator.credentials.create&&navigator.credentials.get)}}return{create:function(t){if(!t||!t.apiKey)throw new Error("Aegis SDK requires an API key");const n=new e(t);return n.loadTokensFromStorage(),n},AegisSDK:e}});
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "aegis-auth-navchetna",
3
+ "version": "1.0.0",
4
+ "description": "Aegis Auth is a unified identity management system providing memory-safe Rust-based authentication. Consolidation of disparate identity providers into a single canonical source.",
5
+ "main": "aegis-sdk.js",
6
+ "types": "aegis-sdk.d.ts",
7
+ "files": [
8
+ "aegis-sdk.js",
9
+ "aegis-sdk.min.js",
10
+ "aegis-sdk.d.ts",
11
+ "README.md"
12
+ ],
13
+ "scripts": {
14
+ "build": "npm run minify",
15
+ "minify": "terser aegis-sdk.js -o aegis-sdk.min.js -c -m",
16
+ "test": "echo \"Error: no test specified\" && exit 1"
17
+ },
18
+ "keywords": [
19
+ "authentication",
20
+ "auth",
21
+ "webauthn",
22
+ "mfa",
23
+ "jwt",
24
+ "aegis",
25
+ "sdk",
26
+ "security",
27
+ "rust",
28
+ "identity",
29
+ "decentralized",
30
+ "navchetna"
31
+ ],
32
+ "author": "Navchetna Technologies",
33
+ "license": "MIT",
34
+ "repository": {
35
+ "type": "git",
36
+ "url": "git+https://github.com/navchetna/aegis-auth-sdk.git"
37
+ },
38
+ "bugs": {
39
+ "url": "https://github.com/navchetna/aegis-auth-sdk/issues"
40
+ },
41
+ "homepage": "https://github.com/navchetna/aegis-auth-sdk#readme",
42
+ "devDependencies": {
43
+ "terser": "^5.16.0"
44
+ },
45
+ "browser": "aegis-sdk.min.js",
46
+ "cdn": "https://cdn.jsdelivr.net/npm/aegis-auth-navchetna@latest/aegis-sdk.min.js",
47
+ "publishConfig": {
48
+ "access": "public"
49
+ }
50
+ }