Files
passkey-auth/web/index.html
T
junv 9427c36b8b feat: initial commit - WebAuthn passkey authentication service
- Complete WebAuthn/FIDO2 authentication implementation
- SQLite database with user and credential management
- Email-based user identification with allowlist support
- Admin approval workflow for new users
- Session management with secure cookies
- Docker containerization with Debian base for SQLite compatibility
- Kubernetes deployment manifests with nginx ingress support
- Web-based admin interface for user management
- Comprehensive documentation and deployment guides
- Standard open source project structure with CI/CD
2025-08-04 18:35:44 +10:00

702 lines
25 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;
}
.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>Admin Dashboard</p>
</div>
<div class="tabs">
<button class="tab active" onclick="showTab('register')">Register User</button>
<button class="tab" onclick="showTab('login')">Test Login</button>
<button class="tab" onclick="showTab('users')">Manage Users</button>
</div>
<!-- Register Tab -->
<div id="register" class="tab-content active">
<h2>Register New User</h2>
<form id="registerForm">
<div class="form-group">
<label for="email">Email Address:</label>
<input type="email" id="email" name="email" required>
</div>
<div class="form-group">
<label for="displayName">Display Name:</label>
<input type="text" id="displayName" name="displayName" required>
</div>
<button type="submit" class="btn">Register with Passkey</button>
</form>
</div>
<!-- Login Tab -->
<div id="login" class="tab-content">
<h2>Test Login</h2>
<form id="loginForm">
<div class="form-group">
<label for="loginEmail">Email Address:</label>
<input type="email" id="loginEmail" name="email" required>
</div>
<button type="submit" class="btn">Login with Passkey</button>
</form>
<div id="loginStatus"></div>
</div>
<!-- Users Tab -->
<div id="users" class="tab-content">
<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;
}
// 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();
}
}
// 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);
} // Register functionality
document.getElementById('registerForm').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const email = formData.get('email');
const displayName = formData.get('displayName');
try {
console.log('Starting registration for email:', email);
// 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('User registered successfully!');
e.target.reset();
} catch (error) {
showAlert(`Registration failed: ${error.message}`, 'error');
}
}); // Login functionality
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const formData = new FormData(e.target);
const email = formData.get('email');
try {
// 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(`Login successful! Welcome, ${result.user.display_name}`);
document.getElementById('loginStatus').innerHTML = `
<div class="alert alert-success">
<strong>Logged in as:</strong> ${result.user.display_name} (${result.user.email})
</div>
`;
} catch (error) {
showAlert(`Login failed: ${error.message}`, 'error');
document.getElementById('loginStatus').innerHTML = `
<div class="alert alert-error">
Login failed: ${error.message}
</div>
`;
}
});
// 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');
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');
}
}
// Load users when page loads
document.addEventListener('DOMContentLoaded', () => {
loadUsers();
});
</script>
</body>
</html>