A non-functional draft, saving to allow reverts.

This commit is contained in:
Leo Vasanko 2025-07-03 17:01:41 -06:00
commit 58f7ac61db
13 changed files with 1093 additions and 0 deletions

122
README.md Normal file
View File

@ -0,0 +1,122 @@
# PasskeyAuth
A minimal FastAPI WebAuthn server with WebSocket support for passkey registration. This project demonstrates WebAuthn registration flow with Resident Keys (discoverable credentials) using modern Python tooling.
## Features
- 🔐 WebAuthn registration with Resident Keys support
- 🔌 WebSocket-based communication for real-time interaction
- 🚀 Modern Python packaging with `pyproject.toml`
- 🎨 Clean, responsive HTML interface using @simplewebauthn/browser
- 📦 No database required - challenges stored locally per connection
- 🛠️ Development tools: `ruff` for linting and formatting
- 🧹 Clean architecture with local challenge management
## Requirements
- Python 3.9+
- A WebAuthn-compatible authenticator (security key, biometric device, etc.)
## Quick Start
### Using uv (recommended)
```fish
# Install uv if you haven't already
curl -LsSf https://astral.sh/uv/install.sh | sh
# Clone/navigate to the project directory
cd passkeyauth
# Install dependencies and run
uv run passkeyauth.main:main
```
### Using pip
```fish
# Create and activate virtual environment
python -m venv venv
source venv/bin/activate.fish # or venv/bin/activate for bash
# Install the package in development mode
pip install -e ".[dev]"
# Run the server
python -m passkeyauth.main
```
### Using hatch
```fish
# Install hatch if you haven't already
pip install hatch
# Run the development server
hatch run python -m passkeyauth.main
```
## Usage
1. Start the server using one of the methods above
2. Open your browser to `http://localhost:8000`
3. Enter a username (or use the default)
4. Click "Register Passkey"
5. Follow your authenticator's prompts to create a passkey
The WebSocket connection will show real-time status updates as you progress through the registration flow.
## Development
### Code Quality
```fish
# Run linting and formatting with ruff
uv run ruff check .
uv run ruff format .
# Or with hatch
hatch run ruff check .
hatch run ruff format .
```
### Project Structure
```
passkeyauth/
├── passkeyauth/
│ ├── __init__.py
│ └── main.py # FastAPI server with WebSocket support
├── static/
│ └── index.html # Frontend interface
├── pyproject.toml # Modern Python packaging configuration
└── README.md
```
## Technical Details
### WebAuthn Configuration
- **Relying Party ID**: `localhost` (for development)
- **Resident Keys**: Required (enables discoverable credentials)
- **User Verification**: Preferred
- **Supported Algorithms**: ECDSA-SHA256, RSASSA-PKCS1-v1_5-SHA256
### WebSocket Message Flow
1. Client connects to `/ws/{client_id}`
2. Client sends `registration_challenge` message
3. Server responds with `registration_challenge_response`
4. Client completes WebAuthn ceremony and sends `registration_response`
5. Server verifies and responds with `registration_success` or `error`
### Security Notes
- This is a minimal demo - challenges are stored locally per WebSocket connection
- For production use, implement proper user storage and session management
- Consider using Redis or similar for challenge storage in production with multiple server instances
- Ensure HTTPS in production environments
## License
MIT License - feel free to use this as a starting point for your own WebAuthn implementations!

9
dev.py Normal file
View File

@ -0,0 +1,9 @@
#!/usr/bin/env python3
"""
Development server runner
"""
if __name__ == "__main__":
from passkeyauth.main import main
main()

326
main.py Normal file
View File

@ -0,0 +1,326 @@
import json
import uuid
from typing import Dict
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from webauthn import generate_registration_options, verify_registration_response
from webauthn.helpers.cose import COSEAlgorithmIdentifier
from webauthn.helpers.structs import (
AuthenticatorSelectionCriteria,
ResidentKeyRequirement,
UserVerificationRequirement,
)
app = FastAPI(title="WebAuthn Registration Server")
# In-memory storage for challenges (in production, use Redis or similar)
active_challenges: Dict[str, str] = {}
# WebAuthn configuration
RP_ID = "localhost"
RP_NAME = "WebAuthn Demo"
ORIGIN = "http://localhost:8000"
class ConnectionManager:
def __init__(self):
self.active_connections: Dict[str, WebSocket] = {}
async def connect(self, websocket: WebSocket, client_id: str):
await websocket.accept()
self.active_connections[client_id] = websocket
def disconnect(self, client_id: str):
if client_id in self.active_connections:
del self.active_connections[client_id]
async def send_message(self, message: dict, client_id: str):
if client_id in self.active_connections:
await self.active_connections[client_id].send_text(json.dumps(message))
manager = ConnectionManager()
@app.websocket("/ws/{client_id}")
async def websocket_endpoint(websocket: WebSocket, client_id: str):
await manager.connect(websocket, client_id)
try:
while True:
data = await websocket.receive_text()
message = json.loads(data)
if message["type"] == "registration_challenge":
await handle_registration_challenge(message, client_id)
elif message["type"] == "registration_response":
await handle_registration_response(message, client_id)
else:
await manager.send_message(
{
"type": "error",
"message": f"Unknown message type: {message['type']}",
},
client_id,
)
except WebSocketDisconnect:
manager.disconnect(client_id)
async def handle_registration_challenge(message: dict, client_id: str):
"""Handle registration challenge request"""
try:
username = message.get("username", "user@example.com")
user_id = str(uuid.uuid4()).encode()
# Generate registration options with Resident Key support
options = generate_registration_options(
rp_id=RP_ID,
rp_name=RP_NAME,
user_id=user_id,
user_name=username,
user_display_name=username,
# Enable Resident Keys (discoverable credentials)
authenticator_selection=AuthenticatorSelectionCriteria(
resident_key=ResidentKeyRequirement.REQUIRED,
user_verification=UserVerificationRequirement.PREFERRED,
),
# Support common algorithms
supported_pub_key_algs=[
COSEAlgorithmIdentifier.ECDSA_SHA_256,
COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_256,
],
)
# Store challenge for this client
active_challenges[client_id] = options.challenge
# Convert options to dict for JSON serialization
options_dict = {
"challenge": options.challenge,
"rp": {
"name": options.rp.name,
"id": options.rp.id,
},
"user": {
"id": options.user.id,
"name": options.user.name,
"displayName": options.user.display_name,
},
"pubKeyCredParams": [
{"alg": param.alg, "type": param.type}
for param in options.pub_key_cred_params
],
"timeout": options.timeout,
"attestation": options.attestation,
"authenticatorSelection": {
"residentKey": options.authenticator_selection.resident_key.value,
"userVerification": options.authenticator_selection.user_verification.value,
},
}
await manager.send_message(
{"type": "registration_challenge_response", "options": options_dict},
client_id,
)
except Exception as e:
await manager.send_message(
{"type": "error", "message": f"Failed to generate challenge: {str(e)}"},
client_id,
)
async def handle_registration_response(message: dict, client_id: str):
"""Handle registration response verification"""
try:
# Get the stored challenge
if client_id not in active_challenges:
await manager.send_message(
{"type": "error", "message": "No active challenge found"}, client_id
)
return
expected_challenge = active_challenges[client_id]
credential = message["credential"]
# Verify the registration response
verification = verify_registration_response(
credential=credential,
expected_challenge=expected_challenge,
expected_origin=ORIGIN,
expected_rp_id=RP_ID,
)
if verification.verified:
# Clean up the challenge
del active_challenges[client_id]
await manager.send_message(
{
"type": "registration_success",
"message": "Registration successful!",
"credentialId": verification.credential_id,
"credentialPublicKey": verification.credential_public_key,
},
client_id,
)
else:
await manager.send_message(
{"type": "error", "message": "Registration verification failed"},
client_id,
)
except Exception as e:
await manager.send_message(
{"type": "error", "message": f"Registration failed: {str(e)}"}, client_id
)
# Serve static files
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")
async def get_index():
return HTMLResponse(
content="""
<!DOCTYPE html>
<html>
<head>
<title>WebAuthn Registration Demo</title>
<script src="https://unpkg.com/@simplewebauthn/browser/dist/bundle/index.umd.min.js"></script>
<style>
body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; }
.container { text-align: center; }
button { padding: 10px 20px; margin: 10px; font-size: 16px; cursor: pointer; }
.success { color: green; }
.error { color: red; }
.info { color: blue; }
#log { text-align: left; background: #f5f5f5; padding: 10px; margin: 20px 0; border-radius: 5px; }
</style>
</head>
<body>
<div class="container">
<h1>WebAuthn Registration Demo</h1>
<p>Test WebAuthn registration with Resident Keys support</p>
<div>
<label for="username">Username:</label>
<input type="text" id="username" value="user@example.com" style="margin: 10px; padding: 5px;">
</div>
<button id="registerBtn">Register Passkey</button>
<div id="status"></div>
<div id="log"></div>
</div>
<script>
const { startRegistration } = SimpleWebAuthnBrowser;
// Generate a unique client ID
const clientId = Math.random().toString(36).substring(7);
// WebSocket connection
const ws = new WebSocket(`ws://localhost:8000/ws/${clientId}`);
const statusDiv = document.getElementById('status');
const logDiv = document.getElementById('log');
const registerBtn = document.getElementById('registerBtn');
const usernameInput = document.getElementById('username');
function log(message, type = 'info') {
const timestamp = new Date().toLocaleTimeString();
logDiv.innerHTML += `<div class="${type}">[${timestamp}] ${message}</div>`;
logDiv.scrollTop = logDiv.scrollHeight;
}
function setStatus(message, type = 'info') {
statusDiv.innerHTML = `<div class="${type}">${message}</div>`;
}
ws.onopen = function() {
log('Connected to WebSocket server', 'success');
setStatus('Ready for registration', 'success');
registerBtn.disabled = false;
};
ws.onmessage = async function(event) {
const message = JSON.parse(event.data);
log(`Received: ${message.type}`);
if (message.type === 'registration_challenge_response') {
try {
log('Starting WebAuthn registration...');
setStatus('Touch your authenticator...', 'info');
const attResp = await startRegistration(message.options);
log('WebAuthn registration completed, verifying...');
setStatus('Verifying registration...', 'info');
ws.send(JSON.stringify({
type: 'registration_response',
credential: attResp
}));
} catch (error) {
log(`Registration failed: ${error.message}`, 'error');
setStatus('Registration failed', 'error');
registerBtn.disabled = false;
}
} else if (message.type === 'registration_success') {
log('Registration verified successfully!', 'success');
setStatus('Registration successful! Passkey created.', 'success');
registerBtn.disabled = false;
} else if (message.type === 'error') {
log(`Error: ${message.message}`, 'error');
setStatus(`Error: ${message.message}`, 'error');
registerBtn.disabled = false;
}
};
ws.onerror = function(error) {
log('WebSocket error: ' + error, 'error');
setStatus('Connection error', 'error');
};
ws.onclose = function() {
log('WebSocket connection closed', 'info');
setStatus('Disconnected', 'error');
registerBtn.disabled = true;
};
registerBtn.addEventListener('click', function() {
const username = usernameInput.value.trim();
if (!username) {
alert('Please enter a username');
return;
}
registerBtn.disabled = true;
setStatus('Requesting registration challenge...', 'info');
log(`Starting registration for: ${username}`);
ws.send(JSON.stringify({
type: 'registration_challenge',
username: username
}));
});
// Disable button until connection is ready
registerBtn.disabled = true;
</script>
</body>
</html>
"""
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)

6
passkeyauth/.gitignore vendored Normal file
View File

@ -0,0 +1,6 @@
__pycache__/
dist/
.*
!.gitignore
*.lock
*.db

6
passkeyauth/TODO.txt Normal file
View File

@ -0,0 +1,6 @@
Practical checks:
- Check how user verification works
Details:
- Extract authenticator type
- Extract user verified flag (present always required)

1
passkeyauth/__init__.py Normal file
View File

@ -0,0 +1 @@
# passkeyauth package

149
passkeyauth/db.py Normal file
View File

@ -0,0 +1,149 @@
import sqlite3
DB_PATH = "webauthn.db"
def init_database():
"""Initialize the SQLite database with required tables"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
# Create users table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
user_id BLOB NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
"""
)
# Create credentials table
cursor.execute(
"""
CREATE TABLE IF NOT EXISTS credentials (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
credential_id BLOB NOT NULL,
public_key BLOB NOT NULL,
sign_count INTEGER DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id),
UNIQUE(credential_id)
)
"""
)
conn.commit()
conn.close()
def get_user_by_username(username: str) -> dict | None:
"""Get user record by username"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
"SELECT id, username, user_id FROM users WHERE username = ?", (username,)
)
row = cursor.fetchone()
conn.close()
if row:
return {"id": row[0], "username": row[1], "user_id": row[2]}
return None
def get_user_by_user_id(user_id: bytes) -> dict | None:
"""Get user record by WebAuthn user ID"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
"SELECT id, username, user_id FROM users WHERE user_id = ?", (user_id,)
)
row = cursor.fetchone()
conn.close()
if row:
return {"id": row[0], "username": row[1], "user_id": row[2]}
return None
def create_user(username: str, user_id: bytes) -> int:
"""Create a new user and return the user ID"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
"INSERT INTO users (username, user_id) VALUES (?, ?)", (username, user_id)
)
user_db_id = cursor.lastrowid
conn.commit()
conn.close()
if user_db_id is None:
raise RuntimeError("Failed to create user")
return user_db_id
def store_credential(user_db_id: int, credential_id: bytes, public_key: bytes) -> None:
"""Store a credential for a user"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
"INSERT INTO credentials (user_id, credential_id, public_key) VALUES (?, ?, ?)",
(user_db_id, credential_id, public_key),
)
conn.commit()
conn.close()
def get_credential_by_id(credential_id: bytes) -> dict | None:
"""Get credential by credential ID"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
"""
SELECT c.public_key, c.sign_count, u.username
FROM credentials c
JOIN users u ON c.user_id = u.id
WHERE c.credential_id = ?
""",
(credential_id,),
)
row = cursor.fetchone()
conn.close()
if row:
return {"public_key": row[0], "sign_count": row[1], "username": row[2]}
return None
def get_user_credentials(username: str) -> list[bytes]:
"""Get all credential IDs for a user"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
"""
SELECT c.credential_id
FROM credentials c
JOIN users u ON c.user_id = u.id
WHERE u.username = ?
""",
(username,),
)
rows = cursor.fetchall()
conn.close()
return [row[0] for row in rows]
def update_credential_sign_count(credential_id: bytes, sign_count: int) -> None:
"""Update the sign count for a credential"""
conn = sqlite3.connect(DB_PATH)
cursor = conn.cursor()
cursor.execute(
"UPDATE credentials SET sign_count = ? WHERE credential_id = ?",
(sign_count, credential_id),
)
conn.commit()
conn.close()

106
passkeyauth/main.py Normal file
View File

@ -0,0 +1,106 @@
"""
Minimal FastAPI WebAuthn server with WebSocket support for passkey registration and authentication.
This module provides a simple WebAuthn implementation that:
- Uses WebSocket for real-time communication
- Supports Resident Keys (discoverable credentials) for passwordless authentication
- Maintains challenges locally per connection
- Uses SQLite database for persistent storage of users and credentials
- Enables true passwordless authentication where users don't need to enter a username
"""
from pathlib import Path
import db
import uuid7
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from passkeyauth.passkey import Passkey
STATIC_DIR = Path(__file__).parent.parent / "static"
passkey = Passkey(
rp_id="localhost",
rp_name="Passkey Auth",
origin="http://localhost:8000",
)
app = FastAPI(title="Passkey Auth")
@app.websocket("/ws/new_user_registration")
async def websocket_register_new(ws: WebSocket):
"""Register a new user and with a new passkey credential."""
await ws.accept()
try:
form = await ws.receive_json()
user_id = uuid7.create().bytes
user_name = form["user_name"]
await register_chat(ws, user_id, username)
# Store the user in the database
await db.create_user(user_name, user_id)
await ws.send_json({"status": "success", "user_id": user_id.hex()})
except WebSocketDisconnect:
pass
async def register_chat(ws: WebSocket, user_id: bytes, username: str):
"""Generate registration options and send them to the client."""
options, challenge = passkey.reg_generate_options(
user_id=user_id,
username=username,
)
await ws.send_text(options)
# Wait for the client to use his authenticator to register
credential = passkey.reg_credential(await ws.receive_json())
passkey.reg_verify(credential, challenge)
@app.websocket("/ws/authenticate")
async def websocket_authenticate(ws: WebSocket):
await ws.accept()
try:
options = passkey.auth_generate_options()
await ws.send_json(options)
# Wait for the client to use his authenticator to authenticate
credential = passkey.auth_credential(await ws.receive_json())
# Fetch from the database by credential ID
stored_cred = await db.fetch_credential(credential.raw_id)
# Verify the credential matches the stored data, that is also updated
passkey.auth_verify(credential, stored_cred)
# Update the credential in the database
await db.update_credential(stored_cred)
except WebSocketDisconnect:
pass
# Serve static files
app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
@app.get("/")
async def get_index():
"""Serve the main HTML page"""
return FileResponse(STATIC_DIR / "index.html")
def main():
"""Entry point for the application"""
import uvicorn
uvicorn.run(
"passkeyauth.main:app",
host="0.0.0.0",
port=8000,
reload=True,
log_level="info",
)
# Initialize database on startup
db.init_database()
if __name__ == "__main__":
main()

166
passkeyauth/passkey.py Normal file
View File

@ -0,0 +1,166 @@
"""
WebAuthn handler class that combines registration and authentication functionality.
This module provides a unified interface for WebAuthn operations including:
- Registration challenge generation and verification
- Authentication challenge generation and verification
- Credential validation
"""
from webauthn import (
generate_authentication_options,
generate_registration_options,
verify_authentication_response,
verify_registration_response,
)
from webauthn.helpers import (
options_to_json,
parse_authentication_credential_json,
parse_registration_credential_json,
)
from webauthn.helpers.cose import COSEAlgorithmIdentifier
from webauthn.helpers.structs import (
AuthenticationCredential,
AuthenticatorSelectionCriteria,
RegistrationCredential,
ResidentKeyRequirement,
UserVerificationRequirement,
)
from webauthn.registration.verify_registration_response import VerifiedRegistration
class Passkey:
"""WebAuthn handler for registration and authentication operations."""
def __init__(
self,
rp_id: str,
rp_name: str,
origin: str,
supported_pub_key_algs: list[COSEAlgorithmIdentifier] | None = None,
):
"""
Initialize the WebAuthn handler.
Args:
rp_id: The relying party identifier
rp_name: The relying party name
origin: The origin URL of the application
supported_pub_key_algs: List of supported COSE algorithms
"""
self.rp_id = rp_id
self.rp_name = rp_name
self.origin = origin
self.supported_pub_key_algs = supported_pub_key_algs or [
COSEAlgorithmIdentifier.EDDSA,
# COSEAlgorithmIdentifier.ECDSA_SHA_256,
# COSEAlgorithmIdentifier.RSASSA_PKCS1_v1_5_SHA_256,
]
### Registration Methods ###
def reg_generate_options(
self, user_id: bytes, username: str, display_name="", **regopts
) -> tuple[str, bytes]:
"""
Generate registration options for WebAuthn registration.
Args:
user_id: The user ID as bytes
username: The username
display_name: The display name (defaults to username if empty)
Returns:
JSON string containing registration options
"""
options = generate_registration_options(
rp_id=self.rp_id,
rp_name=self.rp_name,
user_id=user_id,
user_name=username,
user_display_name=display_name or username,
authenticator_selection=AuthenticatorSelectionCriteria(
resident_key=ResidentKeyRequirement.REQUIRED,
user_verification=UserVerificationRequirement.PREFERRED,
),
supported_pub_key_algs=self.supported_pub_key_algs,
**regopts,
)
return options_to_json(options), options.challenge
@staticmethod
def reg_credential(credential: dict | str) -> RegistrationCredential:
return parse_registration_credential_json(credential)
def reg_verify(
self,
credential: RegistrationCredential,
expected_challenge: bytes,
) -> VerifiedRegistration:
"""
Verify registration response.
Args:
credential: The credential response from the client
expected_challenge: The expected challenge bytes
Returns:
Registration verification result
"""
registration = verify_registration_response(
credential=credential,
expected_challenge=expected_challenge,
expected_origin=self.origin,
expected_rp_id=self.rp_id,
)
return registration
### Authentication Methods ###
async def auth_generate_options(
self, user_verification_required=False, **kwopts
) -> str:
"""
Generate authentication options for WebAuthn authentication.
Args:
user_verification_required: The user will have to re-enter PIN or use biometrics for this operation. Useful when accessing security settings etc.
Returns:
JSON string containing authentication options
"""
options = generate_authentication_options(
rp_id=self.rp_id,
user_verification=(
UserVerificationRequirement.REQUIRED
if user_verification_required
else UserVerificationRequirement.PREFERRED
),
**kwopts,
)
return options_to_json(options)
@staticmethod
def auth_credential(credential: dict | str) -> AuthenticationCredential:
"""Convert the authentication credential from JSON to a dataclass instance."""
return parse_authentication_credential_json(credential)
async def auth_verify(
self,
credential: AuthenticationCredential,
expected_challenge: bytes,
stored_cred: dict,
):
"""
Verify authentication response against locally stored credential data.
"""
# Verify the authentication response
verification = verify_authentication_response(
credential=credential,
expected_challenge=expected_challenge,
expected_origin=self.origin,
expected_rp_id=self.rp_id,
credential_public_key=stored_cred["public_key"],
credential_current_sign_count=stored_cred["sign_count"],
)
stored_cred["sign_count"] = verification.new_sign_count
return verification

36
pyproject.toml Normal file
View File

@ -0,0 +1,36 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"
[project]
name = "passkeyauth"
version = "0.1.0"
description = "Minimal FastAPI WebAuthn server with WebSocket support"
authors = [
{name = "User", email = "user@example.com"},
]
dependencies = [
"fastapi[standard]>=0.104.1",
"uvicorn[standard]>=0.24.0",
"websockets>=12.0",
"webauthn>=1.11.1",
"base64url>=1.0.0",
]
requires-python = ">=3.10"
[project.optional-dependencies]
dev = [
"ruff>=0.1.0",
]
[tool.ruff]
target-version = "py39"
line-length = 88
select = ["E", "F", "I", "N", "W", "UP"]
ignore = ["E501"] # Line too long
[tool.ruff.isort]
known-first-party = ["passkeyauth"]
[project.scripts]
serve = "passkeyauth.main:main"

55
static/app.js Normal file
View File

@ -0,0 +1,55 @@
const { startRegistration, startAuthentication } = SimpleWebAuthnBrowser
async function register(username) {
// Registration chat
const ws = await aWebSocket('/ws/register')
ws.send(username)
const optionsJSON = JSON.parse(await ws.recv())
if (optionsJSON.error) throw new Error(optionsJSON.error)
ws.send(JSON.stringify(await startRegistration({optionsJSON})))
const result = JSON.parse(await ws.recv())
if (result.error) throw new Error(`Server: ${result.error}`)
}
async function authenticate() {
// Authentication chat
const ws = await aWebSocket('/ws/authenticate')
ws.send('') // Send empty string to trigger authentication
const optionsJSON = JSON.parse(await ws.recv())
if (optionsJSON.error) throw new Error(optionsJSON.error)
ws.send(JSON.stringify(await startAuthentication({optionsJSON})))
const result = JSON.parse(await ws.recv())
if (result.error) throw new Error(`Server: ${result.error}`)
return result
}
(function() {
const regForm = document.getElementById('registrationForm')
const regSubmitBtn = regForm.querySelector('button[type="submit"]')
regForm.addEventListener('submit', ev => {
ev.preventDefault()
regSubmitBtn.disabled = true
const username = (new FormData(regForm)).get('username')
register(username).then(() => {
alert(`Registration successful for ${username}!`)
}).catch(err => {
alert(`Registration failed: ${err.message}`)
}).finally(() => {
regSubmitBtn.disabled = false
})
})
const authForm = document.getElementById('authenticationForm')
const authSubmitBtn = authForm.querySelector('button[type="submit"]')
authForm.addEventListener('submit', ev => {
ev.preventDefault()
authSubmitBtn.disabled = true
authenticate().then(result => {
alert(`Authentication successful! Welcome ${result.username}`)
}).catch(err => {
alert(`Authentication failed: ${err.message}`)
}).finally(() => {
authSubmitBtn.disabled = false
})
})
})()

View File

@ -0,0 +1,43 @@
class AwaitableWebSocket extends WebSocket {
#received = []
#waiting = []
#err = null
#opened = false
constructor(resolve, reject, url, protocols) {
super(url, protocols)
this.onopen = () => {
this.#opened = true
resolve(this)
}
this.onmessage = e => {
if (this.#waiting.length) this.#waiting.shift().resolve(e.data)
else this.#received.push(e.data)
}
this.onclose = e => {
if (!this.#opened) {
reject(new Error(`WebSocket ${this.url} failed to connect, code ${e.code}`))
return
}
this.#err = e.wasClean
? new Error(`Websocket ${this.url} closed ${e.code}`)
: new Error(`WebSocket ${this.url} closed with error ${e.code}`)
this.#waiting.splice(0).forEach(p => p.reject(this.#err))
}
}
recv() {
// If we have a message already received, return it immediately
if (this.#received.length) return Promise.resolve(this.#received.shift())
// Wait for incoming messages, if we have an error, reject immediately
if (this.#err) return Promise.reject(this.#err)
return new Promise((resolve, reject) => this.#waiting.push({ resolve, reject }))
}
}
// Construct an async WebSocket with await aWebSocket(url)
function aWebSocket(url, protocols) {
return new Promise((resolve, reject) => {
new AwaitableWebSocket(resolve, reject, url, protocols)
})
}

68
static/index.html Normal file
View File

@ -0,0 +1,68 @@
<!DOCTYPE html>
<html>
<head>
<title>WebAuthn Registration Demo</title>
<script src="https://unpkg.com/@simplewebauthn/browser/dist/bundle/index.umd.min.js"></script>
<script src="/static/awaitable-websocket.js"></script>
<style>
body {
font-family: Arial, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
}
.container {
text-align: center;
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
input[type="text"] {
padding: 10px;
border: 2px solid #ddd;
border-radius: 5px;
font-size: 16px;
margin: 10px;
width: 250px;
}
button {
padding: 12px 24px;
margin: 10px;
font-size: 16px;
cursor: pointer;
background: #007bff;
color: white;
border: none;
border-radius: 5px;
}
button:disabled {
background: #ccc;
cursor: not-allowed;
}
</style>
</head>
<body>
<div class="container">
<h1>WebAuthn Demo</h1>
<div style="margin-bottom: 30px;">
<h2>Register</h2>
<form id="registrationForm">
<input type="text" name="username" placeholder="Username" required>
<br>
<button type="submit">Register Passkey</button>
</form>
</div>
<div>
<h2>Authenticate</h2>
<form id="authenticationForm">
<button type="submit">Authenticate with Passkey</button>
</form>
</div>
</div>
<script src="static/app.js"></script>
</body>
</html>