zkauth-client
v1.4.5
Published
Official JavaScript/TypeScript SDK for ZKAuth - Zero-Knowledge Proof Authentication
Maintainers
Readme
@zkauth/sdk
Official JavaScript/TypeScript SDK for ZKAuth - Zero-Knowledge Proof Authentication
🚀 Features
- Zero-Knowledge Proofs: Authenticate without ever sending passwords
- Privacy-First: Passwords never leave the client
- Device Management: Secure multi-device authentication
- MFA Support: Optional multi-factor authentication
- TypeScript: Full type safety with TypeScript definitions
- Easy Integration: Simple API with async/await
- Event System: React to authentication events
- Production Ready: Battle-tested and secure
📦 Installation
npm install @zkauth/sdkor
yarn add @zkauth/sdk🔑 Getting Started
1. Get Your API Key
Visit the ZKAuth Developer Platform to:
- Create an account
- Create a new project
- Get your API keys (live and test)
2. Initialize the SDK
import { ZKAuthSDK } from '@zkauth/sdk';
const zkauth = new ZKAuthSDK({
apiKey: 'your-api-key', // From developer platform
baseUrl: 'https://zkauth.vercel.app', // Optional, defaults to production
debug: false, // Optional, enable debug logs
});3. Register a User
const result = await zkauth.register({
email: '[email protected]',
password: 'secure-password',
deviceInfo: {
deviceName: 'Chrome on MacBook',
deviceType: 'desktop',
browserName: 'Chrome',
osName: 'macOS',
},
cognitiveQuestion: 'What is your favorite color?',
cognitiveAnswer: 'blue',
});
console.log('User registered:', result.data.userId);4. Login a User
const result = await zkauth.login({
email: '[email protected]',
password: 'secure-password',
});
console.log('Logged in:', result.data.user);
console.log('Session token:', result.data.session.token);5. Check Authentication Status
if (zkauth.isAuthenticated()) {
const user = await zkauth.getCurrentUser();
console.log('Current user:', user);
}6. Logout
await zkauth.logout();📚 API Reference
Core Methods
register(params: RegisterParams): Promise<RegisterResponse>
Register a new user with ZKP commitment.
const result = await zkauth.register({
email: '[email protected]',
password: 'secure-password',
deviceInfo: {
deviceName: 'My Device',
deviceType: 'desktop',
},
});login(params: LoginParams): Promise<LoginResponse>
Login user with ZKP proof.
const result = await zkauth.login({
email: '[email protected]',
password: 'secure-password',
});logout(): Promise<void>
Logout current user.
await zkauth.logout();getCurrentUser(): Promise<User | null>
Get currently authenticated user.
const user = await zkauth.getCurrentUser();isAuthenticated(): boolean
Check if user is authenticated.
if (zkauth.isAuthenticated()) {
// User is logged in
}Password Reset
forgotPassword(params: ForgotPasswordParams): Promise<ForgotPasswordResponse>
Request password reset.
await zkauth.forgotPassword({
email: '[email protected]',
});verifyResetToken(token: string): Promise<VerifyResetTokenResponse>
Verify password reset token.
const result = await zkauth.verifyResetToken(token);resetPassword(params: ResetPasswordParams): Promise<ResetPasswordResponse>
Complete password reset.
await zkauth.resetPassword({
token: 'reset-token',
newPassword: 'new-secure-password',
});Device Management
registerDevice(params: RegisterDeviceParams): Promise<RegisterDeviceResponse>
Register a new trusted device.
const result = await zkauth.registerDevice({
deviceInfo: {
deviceName: 'iPhone 13',
deviceType: 'mobile',
},
});verifyDevice(params: VerifyDeviceParams): Promise<VerifyDeviceResponse>
Verify device access with ZKP proof.
const result = await zkauth.verifyDevice({
deviceId: 'device-id',
proof: proof,
publicSignals: signals,
proofNonce: nonce,
proofTimestamp: timestamp,
});getDevices(): Promise<Device[]>
Get list of user's devices.
const devices = await zkauth.getDevices();removeDevice(deviceId: string): Promise<void>
Remove a device.
await zkauth.removeDevice('device-id');MFA
getMFAStatus(): Promise<MFAStatus>
Get MFA status for current user.
const status = await zkauth.getMFAStatus();
console.log('MFA enabled:', status.mfaEnabled);Events
on(event: ZKAuthEvent, callback: EventCallback): () => void
Subscribe to events.
const unsubscribe = zkauth.on('login', (user) => {
console.log('User logged in:', user);
});
// Later, unsubscribe
unsubscribe();Available events:
login- User logged inlogout- User logged outregister- User registeredsession_expired- Session expiredmfa_required- MFA requireddevice_approval_required- Device approval requirederror- Error occurred
🔒 Security
How It Works
- Password Hashing: Passwords are hashed client-side using Argon2id
- Commitment Generation: A cryptographic commitment is created from the password hash
- ZKP Generation: A zero-knowledge proof is generated to prove knowledge of the password
- Proof Verification: Backend verifies the proof without ever seeing the password
Security Features
- ✅ Passwords never sent over the network
- ✅ Zero-knowledge proof authentication
- ✅ Argon2id password hashing (64 MB, 3 iterations, 4 parallelism)
- ✅ Replay attack protection
- ✅ Device fingerprinting
- ✅ Session management
- ✅ MFA support
🎨 Examples
React Integration
import { useState, useEffect } from 'react';
import { ZKAuthSDK } from '@zkauth/sdk';
const zkauth = new ZKAuthSDK({
apiKey: process.env.REACT_APP_ZKAUTH_API_KEY!,
});
function App() {
const [user, setUser] = useState(null);
useEffect(() => {
// Subscribe to login events
const unsubscribe = zkauth.on('login', (userData) => {
setUser(userData);
});
// Check if already authenticated
zkauth.getCurrentUser().then(setUser);
return () => unsubscribe();
}, []);
const handleLogin = async (email: string, password: string) => {
try {
const result = await zkauth.login({ email, password });
setUser(result.data.user);
} catch (error) {
console.error('Login failed:', error);
}
};
const handleLogout = async () => {
await zkauth.logout();
setUser(null);
};
return (
<div>
{user ? (
<div>
<p>Welcome, {user.email}!</p>
<button onClick={handleLogout}>Logout</button>
</div>
) : (
<LoginForm onSubmit={handleLogin} />
)}
</div>
);
}Vue Integration
import { ref, onMounted } from 'vue';
import { ZKAuthSDK } from '@zkauth/sdk';
export default {
setup() {
const zkauth = new ZKAuthSDK({
apiKey: import.meta.env.VITE_ZKAUTH_API_KEY,
});
const user = ref(null);
onMounted(async () => {
zkauth.on('login', (userData) => {
user.value = userData;
});
user.value = await zkauth.getCurrentUser();
});
const login = async (email, password) => {
const result = await zkauth.login({ email, password });
user.value = result.data.user;
};
const logout = async () => {
await zkauth.logout();
user.value = null;
};
return { user, login, logout };
},
};Next.js Integration
// lib/zkauth.ts
import { ZKAuthSDK } from '@zkauth/sdk';
export const zkauth = new ZKAuthSDK({
apiKey: process.env.NEXT_PUBLIC_ZKAUTH_API_KEY!,
});
// pages/login.tsx
import { useState } from 'react';
import { useRouter } from 'next/router';
import { zkauth } from '@/lib/zkauth';
export default function LoginPage() {
const router = useRouter();
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
const formData = new FormData(e.currentTarget);
try {
await zkauth.login({
email: formData.get('email') as string,
password: formData.get('password') as string,
});
router.push('/dashboard');
} catch (err) {
setError(err.message);
}
};
return (
<form onSubmit={handleSubmit}>
<input name="email" type="email" required />
<input name="password" type="password" required />
<button type="submit">Login</button>
{error && <p>{error}</p>}
</form>
);
}🐛 Error Handling
import { ZKAuthError, ZKAuthErrorCode } from '@zkauth/sdk';
try {
await zkauth.login({ email, password });
} catch (error) {
if (error instanceof ZKAuthError) {
switch (error.code) {
case ZKAuthErrorCode.AUTHENTICATION_ERROR:
console.error('Invalid credentials');
break;
case ZKAuthErrorCode.NETWORK_ERROR:
console.error('Network error, please try again');
break;
case ZKAuthErrorCode.MFA_REQUIRED:
console.error('MFA verification required');
break;
default:
console.error('An error occurred:', error.message);
}
}
}📖 TypeScript Support
The SDK is written in TypeScript and includes full type definitions.
import type {
User,
Session,
RegisterParams,
LoginParams,
Device,
} from '@zkauth/sdk';🤝 Contributing
Contributions are welcome! Please see our Contributing Guide.
📄 License
MIT License - see LICENSE file for details.
🔗 Links
💬 Support
- Email: [email protected]
- Discord: Join our community
- GitHub Issues: Report a bug
