nacf-web-sdk
v0.1.1
Published
Web SDK for Neural Authentication Component Framework (NACF)
Downloads
5
Maintainers
Readme
NACF Web SDK
JavaScript/TypeScript SDK for Neural Authentication Control Framework (NACF)
The NACF Web SDK provides a comprehensive client library for integrating neural authentication into web applications. Built with TypeScript, it offers type-safe APIs for EEG-based authentication, real-time signal processing, and secure token management.
🌟 Features
- 🔐 Neural Authentication: EEG-based biometric authentication
- ⚡ Real-time Processing: Sub-millisecond signal processing
- 🔒 Secure Token Management: JWT handling with automatic refresh
- 📡 WebSocket Support: Real-time communication with NACF servers
- 🎯 TypeScript Support: Full type definitions and IntelliSense
- 🛡️ Error Handling: Comprehensive error classes and recovery
- 📊 Signal Processing: Built-in FFT and signal quality analysis
- 🔄 Reactive Programming: RxJS-based event handling
📦 Installation
npm
npm install nacf-web-sdkyarn
yarn add nacf-web-sdkCDN
<script src="https://cdn.jsdelivr.net/npm/nacf-web-sdk@latest/dist/index.js"></script>🚀 Quick Start
Basic Authentication
import { NeuroAuthClient } from 'nacf-web-sdk';
// Initialize the client
const client = new NeuroAuthClient({
apiUrl: 'https://api.nacf.example.com/v1',
autoRefresh: true,
});
// Authenticate with EEG data
const credentials = {
identifier: '[email protected]',
eegData: {
samples: [/* EEG channel data */],
sampleRate: 256,
}
};
try {
const result = await client.authenticate(credentials);
console.log('Authentication successful:', result);
} catch (error) {
console.error('Authentication failed:', error);
}Browser Usage (CDN)
<!DOCTYPE html>
<html>
<head>
<title>NACF Auth Demo</title>
<script src="https://cdn.jsdelivr.net/npm/nacf-web-sdk@latest/dist/index.js"></script>
</head>
<body>
<script>
const client = new NACF.NeuroAuthClient({
apiUrl: 'https://api.nacf.example.com/v1'
});
// Use the client...
</script>
</body>
</html>📖 Live Example - Interactive browser demo
React Integration
import React, { useState, useEffect } from 'react';
import { NeuroAuthClient } from 'nacf-web-sdk';
function AuthComponent() {
const [client] = useState(() => new NeuroAuthClient({
apiUrl: process.env.REACT_APP_NACF_API_URL,
}));
const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => {
client.on('authStateChange', (state) => {
setIsAuthenticated(state.isAuthenticated);
});
return () => {
client.removeAllListeners();
};
}, [client]);
const handleAuth = async (eegData: any) => {
try {
await client.authenticate({
identifier: '[email protected]',
eegData,
});
} catch (error) {
console.error('Auth failed:', error);
}
};
return (
<div>
{isAuthenticated ? (
<p>Welcome! You are authenticated.</p>
) : (
<button onClick={() => handleAuth(/* EEG data */)}>
Authenticate with EEG
</button>
)}
</div>
);
}📚 API Reference
NeuroAuthClient
The main client class for interacting with NACF services.
Constructor Options
interface AuthConfig {
apiUrl?: string; // API base URL
timeout?: number; // Request timeout in ms
autoRefresh?: boolean; // Auto-refresh tokens
refreshThreshold?: number; // Token refresh threshold in ms
headers?: Record<string, string>; // Additional headers
onAuthStateChange?: (state: AuthState) => void;
onTokenRefresh?: (token: string) => void;
onError?: (error: Error) => void;
}Methods
authenticate(credentials: AuthCredentials): Promise<AuthResult>
Authenticates a user with EEG data.
interface AuthCredentials {
identifier: string;
password?: string;
eegData?: {
samples: number[][];
sampleRate: number;
channels?: string[];
metadata?: Record<string, any>;
};
deviceId?: string;
}
interface AuthResult {
success: boolean;
token?: string;
refreshToken?: string;
user?: User;
session?: AuthSession;
}verify(token: string): Promise<boolean>
Verifies a JWT token.
refresh(): Promise<AuthResult>
Refreshes the authentication token.
logout(): Promise<void>
Logs out the current user.
getAuthState(): AuthState
Returns the current authentication state.
Events
client.on('authStateChange', (state: AuthState) => {
console.log('Auth state changed:', state);
});
client.on('tokenRefresh', (token: string) => {
console.log('Token refreshed:', token);
});
client.on('error', (error: Error) => {
console.error('Auth error:', error);
});Signal Processing
EEG Data Validation
import { validateEEGData } from 'nacf-web-sdk';
const eegData = {
samples: [[1, 2, 3], [4, 5, 6]], // Channel data
sampleRate: 256,
};
try {
validateEEGData(eegData);
console.log('EEG data is valid');
} catch (error) {
console.error('Invalid EEG data:', error);
}Signal Processing Utilities
import { processEEGSamples } from 'nacf-web-sdk';
const rawSamples = [[/* channel 1 data */], [/* channel 2 data */]];
const processedSamples = processEEGSamples(rawSamples, 256);🔧 Configuration
Environment Variables
// .env
REACT_APP_NACF_API_URL=https://api.nacf.example.com/v1
REACT_APP_NACF_TIMEOUT=30000Advanced Configuration
const client = new NeuroAuthClient({
apiUrl: 'https://api.nacf.example.com/v1',
timeout: 30000,
autoRefresh: true,
refreshThreshold: 300000, // 5 minutes
headers: {
'X-API-Key': 'your-api-key',
},
onAuthStateChange: (state) => {
console.log('Auth state:', state);
},
onError: (error) => {
console.error('Auth error:', error);
},
});🛠️ Development
Building from Source
# Clone the repository
git clone https://github.com/pratikacharya1234/NAFC.git
cd nacf/web_sdk
# Install dependencies
npm install
# Build the SDK
npm run build
# Run tests
npm test
# Run linting
npm run lintProject Structure
src/
├── client.ts # Main client implementation
├── index.ts # Public API exports
├── constants.ts # Configuration constants
├── errors/ # Error classes
│ ├── index.ts
│ ├── auth-errors.ts
│ ├── network-errors.ts
│ └── validation-errors.ts
├── types/ # TypeScript definitions
│ ├── index.ts
│ ├── authentication.ts
│ ├── signal.ts
│ └── session.ts
└── utils/ # Utility functions
├── signal.ts
└── validation.ts📋 Requirements
- Node.js: 16.0+ (for development)
- Browser: Modern browsers with ES6 support
- TypeScript: 4.5+ (for TypeScript projects)
🧪 Testing
# Run unit tests
npm test
# Run tests with coverage
npm run test:coverage
# Run tests in watch mode
npm run test:watch🤝 Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
📄 License
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
🆘 Support
- Documentation: NACF Documentation
- Issues: GitHub Issues
- Discussions: GitHub Discussions
🔗 Related Links
Built with ❤️ by the NACF Team
