Files
passkey-auth/web/index.html
T

872 lines
30 KiB
HTML

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Passkey Auth - Admin</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
background: white;
border-radius: 16px;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
padding: 2rem;
width: 100%;
max-width: 800px;
margin: 1rem;
}
.header {
text-align: center;
margin-bottom: 2rem;
}
.header h1 {
color: #333;
font-size: 2rem;
margin-bottom: 0.5rem;
}
.header p {
color: #666;
font-size: 1rem;
}
.tabs {
display: flex;
margin-bottom: 2rem;
border-bottom: 1px solid #eee;
}
.tab {
background: none;
border: none;
padding: 1rem 2rem;
cursor: pointer;
font-size: 1rem;
color: #666;
border-bottom: 2px solid transparent;
transition: all 0.3s ease;
}
.tab.active {
color: #667eea;
border-bottom-color: #667eea;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.auth-panel, .welcome-panel, .admin-panel {
margin-bottom: 2rem;
}
.auth-toggle {
text-align: center;
margin-top: 1rem;
}
.link-btn {
background: none;
border: none;
color: #667eea;
cursor: pointer;
text-decoration: underline;
font-size: 0.9rem;
}
.link-btn:hover {
color: #764ba2;
}
.welcome-panel {
text-align: center;
}
.welcome-actions {
margin-top: 1.5rem;
}
.admin-panel {
border-top: 1px solid #eee;
padding-top: 2rem;
}
.form-group {
margin-bottom: 1.5rem;
}
label {
display: block;
margin-bottom: 0.5rem;
color: #333;
font-weight: 500;
}
input[type="text"], input[type="email"] {
width: 100%;
padding: 0.75rem;
border: 2px solid #eee;
border-radius: 8px;
font-size: 1rem;
transition: border-color 0.3s ease;
}
input[type="text"]:focus, input[type="email"]:focus {
outline: none;
border-color: #667eea;
}
.btn {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 0.75rem 2rem;
border-radius: 8px;
font-size: 1rem;
cursor: pointer;
transition: transform 0.2s ease;
}
.btn:hover {
transform: translateY(-2px);
}
.btn:disabled {
opacity: 0.6;
cursor: not-allowed;
transform: none;
}
.btn-danger {
background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
}
.users-list {
margin-top: 2rem;
}
.user-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
border: 1px solid #eee;
border-radius: 8px;
margin-bottom: 1rem;
}
.user-info {
flex-grow: 1;
}
.user-info h3 {
color: #333;
margin-bottom: 0.25rem;
}
.user-info p {
color: #666;
font-size: 0.9rem;
}
.user-actions {
display: flex;
align-items: center;
gap: 0.5rem;
}
.status-badge {
padding: 0.25rem 0.75rem;
border-radius: 12px;
font-size: 0.8rem;
font-weight: 500;
margin-right: 1rem;
}
.status-approved {
background: #d4edda;
color: #155724;
}
.status-pending {
background: #fff3cd;
color: #856404;
}
.alert {
padding: 1rem;
border-radius: 8px;
margin-bottom: 1rem;
}
.alert-success {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.alert-error {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
.loading {
text-align: center;
padding: 2rem;
color: #666;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>🔐 Passkey Auth</h1>
<p id="headerSubtitle">Secure Authentication</p>
</div>
<!-- Initial Auth Panel -->
<div id="authPanel" class="auth-panel">
<h2 id="authTitle">Sign In</h2>
<form id="authForm">
<div class="form-group">
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" required>
</div>
<button type="submit" class="btn" id="authSubmitBtn">Sign In with Passkey</button>
</form>
<div class="auth-toggle">
<button type="button" class="link-btn" id="toggleModeBtn">Don't have an account? Sign up</button>
</div>
</div>
<!-- Welcome Panel (shown after auth) -->
<div id="welcomePanel" class="welcome-panel" style="display: none;">
<h2>Welcome!</h2>
<div id="welcomeMessage"></div>
<div class="welcome-actions">
<button type="button" class="btn btn-danger" id="logoutBtn">Logout</button>
</div>
</div>
<!-- Admin Panel (shown for admin users) -->
<div id="adminPanel" class="admin-panel" style="display: none;">
<h2>Manage Users</h2>
<button class="btn" onclick="loadUsers()">Refresh Users</button>
<div id="usersList" class="users-list">
<div class="loading">Loading users...</div>
</div>
</div>
<div id="alerts"></div>
</div>
<script>
// Base64/Base64URL decoding functions for WebAuthn
function base64ToArrayBuffer(base64) {
if (!base64 || typeof base64 !== 'string') {
console.error('Invalid base64 input:', base64);
throw new Error('Invalid base64 input');
}
console.log('Converting base64 to ArrayBuffer:', base64);
try {
// If it looks like base64url, convert to base64 first
let base64String = base64;
if (base64.includes('-') || base64.includes('_')) {
// This is base64url, convert to base64
base64String = base64.replace(/-/g, '+').replace(/_/g, '/');
// Add padding if needed
const padding = base64String.length % 4;
if (padding) {
base64String += '='.repeat(4 - padding);
}
} else {
// This is standard base64, add padding if needed
const padding = base64String.length % 4;
if (padding) {
base64String += '='.repeat(4 - padding);
}
}
// Decode base64
const binary = atob(base64String);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
console.log('Converted to ArrayBuffer, length:', bytes.buffer.byteLength);
return bytes.buffer;
} catch (error) {
console.error('Error converting base64 to ArrayBuffer:', error);
throw error;
}
}
// For backwards compatibility, keep the old function name but make it handle both
function base64urlToArrayBuffer(base64url) {
return base64ToArrayBuffer(base64url);
}
function arrayBufferToBase64url(buffer) {
const bytes = new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
const base64 = btoa(binary);
return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
} // Convert WebAuthn options from base64url to ArrayBuffer
function prepareWebAuthnOptions(options) {
console.log('prepareWebAuthnOptions called with:', options);
// Handle both registration and login options (both use publicKey wrapper)
if (options.publicKey) {
console.log('Processing WebAuthn options (has publicKey)');
const publicKey = { ...options.publicKey };
// Convert challenge (common to both registration and login)
if (publicKey.challenge) {
console.log('Original challenge:', publicKey.challenge, 'type:', typeof publicKey.challenge);
if (typeof publicKey.challenge === 'string') {
publicKey.challenge = base64ToArrayBuffer(publicKey.challenge);
console.log('Converted challenge to ArrayBuffer, byteLength:', publicKey.challenge.byteLength);
} else {
console.error('Challenge is not a string:', publicKey.challenge);
throw new Error('Challenge must be a base64 or base64url string');
}
}
// Convert user ID (registration only)
if (publicKey.user && publicKey.user.id) {
console.log('Original user ID:', publicKey.user.id, 'type:', typeof publicKey.user.id);
if (typeof publicKey.user.id === 'string') {
publicKey.user.id = base64ToArrayBuffer(publicKey.user.id);
console.log('Converted user ID to ArrayBuffer, byteLength:', publicKey.user.id.byteLength);
} else {
console.error('User ID is not a string:', publicKey.user.id);
throw new Error('User ID must be a base64 or base64url string');
}
}
// Convert excludeCredentials (registration)
if (publicKey.excludeCredentials) {
console.log('Converting excludeCredentials for registration');
publicKey.excludeCredentials = publicKey.excludeCredentials.map(cred => ({
...cred,
id: base64ToArrayBuffer(cred.id)
}));
}
// Convert allowCredentials (login/authentication)
if (publicKey.allowCredentials) {
console.log('Converting allowCredentials for login:', publicKey.allowCredentials);
publicKey.allowCredentials = publicKey.allowCredentials.map(cred => {
console.log('Converting credential ID:', cred.id, 'type:', typeof cred.id);
return {
...cred,
id: base64ToArrayBuffer(cred.id)
};
});
console.log('Converted allowCredentials:', publicKey.allowCredentials);
}
const result = { publicKey };
console.log('Returning prepared WebAuthn options:', result);
return result;
}
console.log('No publicKey property found, returning as-is');
return options;
}
// Convert WebAuthn response from ArrayBuffer to base64url
function prepareWebAuthnResponse(credential) {
console.log('prepareWebAuthnResponse input:', credential);
const response = {
id: '',
rawId: '',
type: credential.type || 'public-key',
response: {}
};
// Convert credential ID
if (credential.rawId) {
const credentialId = arrayBufferToBase64url(credential.rawId);
response.id = credentialId;
response.rawId = credentialId;
console.log('Converted credential ID:', credentialId);
} else if (credential.id) {
// Some browsers might provide id as string already
response.id = credential.id;
response.rawId = credential.id;
console.log('Using existing credential ID:', credential.id);
}
// Convert response data
if (credential.response) {
console.log('Processing credential.response:', credential.response);
if (credential.response.clientDataJSON) {
response.response.clientDataJSON = arrayBufferToBase64url(credential.response.clientDataJSON);
console.log('Converted clientDataJSON');
}
// For registration (attestationObject)
if (credential.response.attestationObject) {
response.response.attestationObject = arrayBufferToBase64url(credential.response.attestationObject);
console.log('Converted attestationObject');
}
// For authentication (authenticatorData, signature)
if (credential.response.authenticatorData) {
response.response.authenticatorData = arrayBufferToBase64url(credential.response.authenticatorData);
console.log('Converted authenticatorData');
}
if (credential.response.signature) {
response.response.signature = arrayBufferToBase64url(credential.response.signature);
console.log('Converted signature');
}
if (credential.response.userHandle) {
response.response.userHandle = arrayBufferToBase64url(credential.response.userHandle);
console.log('Converted userHandle');
}
}
console.log('Final prepared response:', response);
return response;
}
// UI State Management
let isSignUpMode = false;
let currentUser = null;
// Tab functionality
function showTab(tabName) {
// Hide all tab contents
document.querySelectorAll('.tab-content').forEach(content => {
content.classList.remove('active');
});
// Remove active class from all tabs
document.querySelectorAll('.tab').forEach(tab => {
tab.classList.remove('active');
});
// Show selected tab content
document.getElementById(tabName).classList.add('active');
// Add active class to clicked tab
event.target.classList.add('active');
// Load users when users tab is selected
if (tabName === 'users') {
loadUsers();
}
}
// UI State Functions
function showAuthPanel() {
document.getElementById('authPanel').style.display = 'block';
document.getElementById('welcomePanel').style.display = 'none';
document.getElementById('adminPanel').style.display = 'none';
document.getElementById('headerSubtitle').textContent = 'Secure Authentication';
}
function showWelcomePanel(user) {
document.getElementById('authPanel').style.display = 'none';
document.getElementById('welcomePanel').style.display = 'block';
document.getElementById('headerSubtitle').textContent = 'Dashboard';
const welcomeMessage = document.getElementById('welcomeMessage');
welcomeMessage.innerHTML = `
<div class="alert alert-success">
<strong>Welcome back, ${user.display_name}!</strong><br>
<small>${user.email}</small>
</div>
`;
// Show admin panel if user is admin
if (user.is_admin) {
document.getElementById('adminPanel').style.display = 'block';
loadUsers();
} else {
document.getElementById('adminPanel').style.display = 'none';
}
}
function toggleSignUpMode() {
isSignUpMode = !isSignUpMode;
const authTitle = document.getElementById('authTitle');
const authSubmitBtn = document.getElementById('authSubmitBtn');
const toggleModeBtn = document.getElementById('toggleModeBtn');
if (isSignUpMode) {
authTitle.textContent = 'Sign Up';
authSubmitBtn.textContent = 'Sign Up with Passkey';
toggleModeBtn.textContent = 'Already have an account? Sign in';
} else {
authTitle.textContent = 'Sign In';
authSubmitBtn.textContent = 'Sign In with Passkey';
toggleModeBtn.textContent = "Don't have an account? Sign up";
}
}
function logout() {
fetch('/api/logout', {
method: 'POST',
credentials: 'include'
}).then(() => {
currentUser = null;
showAuthPanel();
showAlert('Logged out successfully');
// Clear email input
document.getElementById('email').value = '';
}).catch(error => {
showAlert('Logout failed: ' + error.message, 'error');
});
}
// Event Listeners
document.getElementById('toggleModeBtn').addEventListener('click', toggleSignUpMode);
document.getElementById('logoutBtn').addEventListener('click', logout);
// Alert functions
function showAlert(message, type = 'success') {
const alertsContainer = document.getElementById('alerts');
const alert = document.createElement('div');
alert.className = `alert alert-${type}`;
alert.textContent = message;
alertsContainer.appendChild(alert);
setTimeout(() => {
alert.remove();
}, 5000);
}
// Authentication status management
async function checkAuthStatus() {
try {
console.log('Checking authentication status...');
const response = await fetch('/api/auth/status', {
credentials: 'include'
});
console.log('Auth status response:', response.status, response.statusText);
if (response.ok) {
const userData = await response.json();
console.log('User is authenticated:', userData);
currentUser = userData.user;
showWelcomePanel(userData.user);
return userData;
} else {
console.log('User is not authenticated');
currentUser = null;
showAuthPanel();
return null;
}
} catch (error) {
console.log('Auth status check failed:', error);
currentUser = null;
showAuthPanel();
return null;
}
}
function showUsersTab() {
console.log('showUsersTab called');
const usersTab = document.getElementById('usersTab');
if (usersTab) {
usersTab.style.display = 'block';
console.log('Users tab is now visible');
} else {
console.log('Could not find usersTab element');
}
}
function hideUsersTab() {
console.log('hideUsersTab called');
const usersTab = document.getElementById('usersTab');
const usersContent = document.getElementById('users');
if (usersTab) {
usersTab.style.display = 'none';
console.log('Users tab is now hidden');
}
// If users tab is currently active, switch to register tab
if (usersContent && usersContent.classList.contains('active')) {
console.log('Users tab was active, switching to register tab');
showTab('register');
}
} // Unified Auth Form Handler
document.getElementById('authForm').addEventListener('submit', async (e) => {
e.preventDefault();
const email = document.getElementById('email').value;
const submitBtn = document.getElementById('authSubmitBtn');
// Disable submit button during processing
submitBtn.disabled = true;
const originalText = submitBtn.textContent;
submitBtn.textContent = isSignUpMode ? 'Signing up...' : 'Signing in...';
try {
if (isSignUpMode) {
await handleSignUp(email);
} else {
await handleSignIn(email);
}
} catch (error) {
showAlert(`${isSignUpMode ? 'Sign up' : 'Sign in'} failed: ${error.message}`, 'error');
} finally {
// Re-enable submit button
submitBtn.disabled = false;
submitBtn.textContent = originalText;
}
});
// Sign Up Handler
async function handleSignUp(email) {
console.log('Starting registration for email:', email);
// Use email as display name (extract name part before @)
const displayName = email.split('@')[0];
// Begin registration
const beginResponse = await fetch('/api/register/begin', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
display_name: displayName
}),
credentials: 'include'
});
if (!beginResponse.ok) {
throw new Error(await beginResponse.text());
}
const options = await beginResponse.json();
console.log('Raw options from server:', JSON.stringify(options, null, 2));
// Convert base64url encoded fields to ArrayBuffers
const webAuthnOptions = prepareWebAuthnOptions(options);
console.log('Final webAuthnOptions for navigator.credentials.create:', webAuthnOptions);
// Create credential
const credential = await navigator.credentials.create(webAuthnOptions);
console.log('Raw credential from navigator.credentials.create:', credential);
// Convert ArrayBuffers back to base64url for JSON
const credentialResponse = prepareWebAuthnResponse(credential);
console.log('Prepared credential response to send to server:', JSON.stringify(credentialResponse, null, 2));
// Finish registration
const finishResponse = await fetch('/api/register/finish', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(credentialResponse),
credentials: 'include'
});
console.log('Finish registration response status:', finishResponse.status);
if (!finishResponse.ok) {
const errorText = await finishResponse.text();
console.error('Finish registration error:', errorText);
throw new Error(errorText);
}
showAlert('Account created successfully!');
// Check auth status to show welcome panel
setTimeout(checkAuthStatus, 100);
}
// Sign In Handler
async function handleSignIn(email) {
// Begin login
const beginResponse = await fetch('/api/login/begin', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email
}),
credentials: 'include'
});
if (!beginResponse.ok) {
throw new Error(await beginResponse.text());
}
const options = await beginResponse.json();
console.log('Raw login options from server:', JSON.stringify(options, null, 2));
// Convert base64url encoded fields to ArrayBuffers
const webAuthnOptions = prepareWebAuthnOptions(options);
console.log('Final login webAuthnOptions for navigator.credentials.get:', webAuthnOptions);
// Get credential
const credential = await navigator.credentials.get(webAuthnOptions);
// Convert ArrayBuffers back to base64url for JSON
const credentialResponse = prepareWebAuthnResponse(credential);
// Finish login
const finishResponse = await fetch('/api/login/finish', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(credentialResponse),
credentials: 'include'
});
if (!finishResponse.ok) {
throw new Error(await finishResponse.text());
}
const result = await finishResponse.json();
showAlert(`Welcome back, ${result.user.display_name}!`);
// Check auth status to show welcome panel
setTimeout(checkAuthStatus, 100);
}
// Users management
async function loadUsers() {
const usersList = document.getElementById('usersList');
usersList.innerHTML = '<div class="loading">Loading users...</div>';
try {
const response = await fetch('/api/users', {
credentials: 'include'
});
if (response.status === 403) {
// User is not admin, hide the tab
hideUsersTab();
showAlert('Access denied: Admin privileges required', 'error');
return;
}
if (!response.ok) {
throw new Error('Failed to load users');
}
const users = await response.json();
if (users.length === 0) {
usersList.innerHTML = '<p>No users found.</p>';
return;
}
usersList.innerHTML = users.map(user => `
<div class="user-item">
<div class="user-info">
<h3>${user.display_name}</h3>
<p>${user.email} • Created: ${new Date(user.created_at).toLocaleDateString()}</p>
</div>
<div class="user-actions">
<span class="status-badge ${user.approved ? 'status-approved' : 'status-pending'}">
${user.approved ? 'Approved' : 'Pending'}
</span>
${!user.approved ? `<button class="btn" onclick="approveUser(${user.id})">Approve</button>` : ''}
<button class="btn btn-danger" onclick="deleteUser(${user.id})">Delete</button>
</div>
</div>
`).join('');
} catch (error) {
usersList.innerHTML = `<div class="alert alert-error">Failed to load users: ${error.message}</div>`;
}
}
async function approveUser(userId) {
if (!confirm('Are you sure you want to approve this user?')) {
return;
}
try {
const response = await fetch(`/api/users/${userId}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
approved: true
})
});
if (!response.ok) {
throw new Error('Failed to approve user');
}
showAlert('User approved successfully', 'success');
loadUsers(); // Refresh the users list
} catch (error) {
showAlert(`Failed to approve user: ${error.message}`, 'error');
}
}
async function deleteUser(userId) {
if (!confirm('Are you sure you want to delete this user?')) {
return;
}
try {
const response = await fetch(`/api/users/${userId}`, {
method: 'DELETE'
});
if (!response.ok) {
throw new Error('Failed to delete user');
}
showAlert('User deleted successfully!');
loadUsers();
} catch (error) {
showAlert(`Failed to delete user: ${error.message}`, 'error');
}
}
// Initialize page
document.addEventListener('DOMContentLoaded', async () => {
// Check authentication status to determine initial UI state
await checkAuthStatus();
});
</script>
</body>
</html>