Skip to content

Commit f458bec

Browse files
committed
fix(auth): implement SvelteKit authentication experience
1 parent 980c1e3 commit f458bec

11 files changed

Lines changed: 337 additions & 23 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ debug
44
target
55
node_modules
66
.svelte-kit
7+
apps/auth-web/build
78

89
# These are backup files generated by rustfmt
910
**/*.rs.bk

‎apps/auth-service/src/passkey.rs‎

Lines changed: 113 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,10 @@
33
use crate::account::{validate_display_name, validate_username};
44
use axum::{
55
Json, Router,
6-
extract::State,
6+
extract::{Path, State},
77
http::{HeaderMap, HeaderValue, StatusCode, header},
88
response::{IntoResponse, Response},
9-
routing::post,
9+
routing::{get, patch, post},
1010
};
1111
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
1212
use chrono::{Duration, Utc};
@@ -34,6 +34,7 @@ use webauthn_rs::{
3434
pub struct PasskeyApplication {
3535
database: Database,
3636
webauthn: Arc<Webauthn>,
37+
origin: String,
3738
}
3839

3940
#[derive(Debug, Error)]
@@ -62,6 +63,7 @@ impl PasskeyApplication {
6263
Ok(Self {
6364
database,
6465
webauthn: Arc::new(webauthn),
66+
origin: origin.as_str().trim_end_matches('/').to_owned(),
6567
})
6668
}
6769
}
@@ -96,6 +98,11 @@ pub(super) fn routes(application: PasskeyApplication) -> Router {
9698
.route("/webauthn/authenticate/start", post(start_authentication))
9799
.route("/webauthn/authenticate/finish", post(finish_authentication))
98100
.route("/session/logout", post(logout))
101+
.route("/account/passkeys", get(list_passkeys))
102+
.route(
103+
"/account/passkeys/{id}",
104+
patch(rename_passkey).delete(revoke_passkey),
105+
)
99106
.with_state(application)
100107
}
101108

@@ -431,6 +438,110 @@ fn session_secret(headers: &HeaderMap) -> Option<Vec<u8>> {
431438
.filter(|secret| secret.len() == 32)
432439
}
433440

441+
#[derive(Serialize)]
442+
struct PasskeySummary {
443+
id: TokenId,
444+
friendly_name: String,
445+
}
446+
async fn list_passkeys(
447+
State(app): State<PasskeyApplication>,
448+
headers: HeaderMap,
449+
) -> Result<Json<Vec<PasskeySummary>>, ApiError> {
450+
let session = active_browser_session(&app, &headers).await?;
451+
let values = app
452+
.database
453+
.passkeys()
454+
.list_active(session.user_id, 20)
455+
.await
456+
.map_err(|_| ApiError)?
457+
.into_iter()
458+
.map(|passkey| PasskeySummary {
459+
id: passkey.id,
460+
friendly_name: passkey.friendly_name,
461+
})
462+
.collect();
463+
Ok(Json(values))
464+
}
465+
#[derive(Deserialize)]
466+
struct RenamePasskey {
467+
friendly_name: String,
468+
}
469+
async fn rename_passkey(
470+
State(app): State<PasskeyApplication>,
471+
Path(id): Path<TokenId>,
472+
headers: HeaderMap,
473+
Json(input): Json<RenamePasskey>,
474+
) -> Result<StatusCode, ApiError> {
475+
let session = fresh_browser_session(&app, &headers).await?;
476+
validate_mutation_origin(&app, &headers)?;
477+
if input.friendly_name.trim().is_empty() || input.friendly_name.chars().count() > 80 {
478+
return Err(ApiError);
479+
}
480+
app.database
481+
.passkeys()
482+
.rename(id, session.user_id, &input.friendly_name)
483+
.await
484+
.map_err(|_| ApiError)?
485+
.then_some(StatusCode::NO_CONTENT)
486+
.ok_or(ApiError)
487+
}
488+
async fn revoke_passkey(
489+
State(app): State<PasskeyApplication>,
490+
Path(id): Path<TokenId>,
491+
headers: HeaderMap,
492+
) -> Result<StatusCode, ApiError> {
493+
let session = fresh_browser_session(&app, &headers).await?;
494+
validate_mutation_origin(&app, &headers)?;
495+
let active = app
496+
.database
497+
.passkeys()
498+
.list_active(session.user_id, 2)
499+
.await
500+
.map_err(|_| ApiError)?;
501+
if active.len() <= 1 {
502+
return Err(ApiError);
503+
}
504+
app.database
505+
.passkeys()
506+
.revoke(id, session.user_id)
507+
.await
508+
.map_err(|_| ApiError)?
509+
.then_some(StatusCode::NO_CONTENT)
510+
.ok_or(ApiError)
511+
}
512+
async fn active_browser_session(
513+
app: &PasskeyApplication,
514+
headers: &HeaderMap,
515+
) -> Result<piquel_repository::StoredSession, ApiError> {
516+
let secret = session_secret(headers).ok_or(ApiError)?;
517+
app.database
518+
.sessions()
519+
.find_active_by_browser_secret(&Sha256::digest(secret))
520+
.await
521+
.map_err(|_| ApiError)?
522+
.ok_or(ApiError)
523+
}
524+
async fn fresh_browser_session(
525+
app: &PasskeyApplication,
526+
headers: &HeaderMap,
527+
) -> Result<piquel_repository::StoredSession, ApiError> {
528+
let session = active_browser_session(app, headers).await?;
529+
(Utc::now().signed_duration_since(session.authenticated_at) <= Duration::minutes(10))
530+
.then_some(session)
531+
.ok_or(ApiError)
532+
}
533+
fn validate_mutation_origin(app: &PasskeyApplication, headers: &HeaderMap) -> Result<(), ApiError> {
534+
let origin = headers
535+
.get(header::ORIGIN)
536+
.and_then(|value| value.to_str().ok())
537+
.ok_or(ApiError)?;
538+
if origin.trim_end_matches('/') == app.origin {
539+
Ok(())
540+
} else {
541+
Err(ApiError)
542+
}
543+
}
544+
434545
#[derive(Debug)]
435546
struct ApiError;
436547
impl IntoResponse for ApiError {

‎apps/auth-web/package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
"test": "vite build"
1111
},
1212
"devDependencies": {
13-
"@sveltejs/adapter-auto": "^6.0.0",
13+
"@sveltejs/adapter-node": "^5.0.0",
1414
"@sveltejs/kit": "^2.0.0",
1515
"@sveltejs/vite-plugin-svelte": "^6.0.0",
1616
"svelte": "^5.0.0",

‎apps/auth-web/src/hooks.server.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@ import type { Handle } from '@sveltejs/kit';
22

33
export const handle: Handle = async ({ event, resolve }) => {
44
const response = await resolve(event);
5-
response.headers.set('Content-Security-Policy', "default-src 'self'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'; object-src 'none'");
5+
response.headers.set('Content-Security-Policy', "default-src 'self'; connect-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'; object-src 'none'");
66
response.headers.set('Referrer-Policy', 'no-referrer');
77
response.headers.set('X-Content-Type-Options', 'nosniff');
8+
response.headers.set('Permissions-Policy', 'publickey-credentials-get=(self), publickey-credentials-create=(self), camera=(), microphone=(), geolocation=()');
89
response.headers.set('Cache-Control', 'no-store');
910
return response;
1011
};

‎apps/auth-web/src/lib/webauthn.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function decode(value: string): ArrayBuffer {
2+
const padded = value.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - value.length % 4) % 4);
3+
const bytes = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));
4+
return bytes.buffer;
5+
}
6+
function encode(value: ArrayBuffer): string {
7+
const bytes = new Uint8Array(value);
8+
let binary = '';
9+
for (const byte of bytes) binary += String.fromCharCode(byte);
10+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
11+
}
12+
function creationOptions(publicKey: any): PublicKeyCredentialCreationOptions {
13+
return { ...publicKey, challenge: decode(publicKey.challenge), user: { ...publicKey.user, id: decode(publicKey.user.id) }, excludeCredentials: publicKey.excludeCredentials?.map((item:any)=>({...item,id:decode(item.id)})) };
14+
}
15+
function requestOptions(publicKey:any):PublicKeyCredentialRequestOptions {
16+
return { ...publicKey, challenge:decode(publicKey.challenge), allowCredentials:publicKey.allowCredentials?.map((item:any)=>({...item,id:decode(item.id)})) };
17+
}
18+
function registration(credential:PublicKeyCredential){const response=credential.response as AuthenticatorAttestationResponse;return{id:credential.id,rawId:encode(credential.rawId),type:credential.type,response:{attestationObject:encode(response.attestationObject),clientDataJSON:encode(response.clientDataJSON)},clientExtensionResults:credential.getClientExtensionResults()};}
19+
function assertion(credential:PublicKeyCredential){const response=credential.response as AuthenticatorAssertionResponse;return{id:credential.id,rawId:encode(credential.rawId),type:credential.type,response:{authenticatorData:encode(response.authenticatorData),clientDataJSON:encode(response.clientDataJSON),signature:encode(response.signature),userHandle:response.userHandle?encode(response.userHandle):null},clientExtensionResults:credential.getClientExtensionResults()};}
20+
async function json(response:Response){if(!response.ok)throw new Error('authentication failed');return response.json();}
21+
export async function registerPasskey(username:string,displayName:string,friendlyName:string){const start=await json(await fetch('/webauthn/register/start',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({username,display_name:displayName})}));const credential=await navigator.credentials.create({publicKey:creationOptions(start.public_key)}) as PublicKeyCredential|null;if(!credential)throw new Error('authentication failed');const finish=await fetch('/webauthn/register/finish',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({ceremony_id:start.ceremony_id,credential:registration(credential),friendly_name:friendlyName})});if(!finish.ok)throw new Error('authentication failed');}
22+
export async function authenticatePasskey(userId:string){const start=await json(await fetch('/webauthn/authenticate/start',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({user_id:userId})}));const credential=await navigator.credentials.get({publicKey:requestOptions(start.public_key)}) as PublicKeyCredential|null;if(!credential)throw new Error('authentication failed');const finish=await fetch('/webauthn/authenticate/finish',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({ceremony_id:start.ceremony_id,credential:assertion(credential)})});if(!finish.ok)throw new Error('authentication failed');}
23+
export const webauthnAvailable=()=>typeof window!=='undefined'&&window.isSecureContext&&'PublicKeyCredential'in window;
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
<script lang="ts">let { children } = $props();</script>
22
<svelte:head><title>Piquel authentication</title><meta name="robots" content="noindex" /></svelte:head>
33
<main>{@render children()}</main>
4-
<style>main { margin: auto; max-width: 34rem; padding: 2rem 1.25rem; font-family: system-ui, sans-serif; } :global(button), :global(a) { min-height: 2.75rem; } </style>
4+
<style>:global(*){box-sizing:border-box}:global(body){margin:0;background:#f4f1eb;color:#18201d;font-family:Inter,ui-sans-serif,system-ui,sans-serif}:global(a){color:#155c48}:global(section){display:grid;gap:1rem}:global(h1){font-family:ui-serif,Georgia,serif;font-size:clamp(2.25rem,8vw,4rem);line-height:.95;margin:.25rem 0}:global(h2){font-family:ui-serif,Georgia,serif}:global(form){display:grid;gap:.75rem}:global(label){font-weight:700}:global(input){width:100%;padding:.85rem;border:1px solid #8b958f;border-radius:.5rem;font:inherit}:global(button),:global(.provider){min-height:2.75rem;border:0;border-radius:999px;padding:.8rem 1.15rem;background:#155c48;color:white;font:inherit;font-weight:750;text-align:center;text-decoration:none;cursor:pointer}:global(button:disabled){opacity:.6;cursor:wait}:global(.secondary){background:#303936}:global(.alternatives){display:grid;gap:.65rem;border-top:1px solid #cad0cc;padding-top:1rem}:global(.help){color:#59625e;font-size:.92rem}:global(.error){border-left:4px solid #a13232;background:#fff0ee;padding:.8rem}:global(.card){background:#fff;border:1px solid #d9ddd9;border-radius:.8rem;padding:1rem}:global(.eyebrow){color:#155c48;font-size:.75rem;font-weight:800;letter-spacing:.12em;text-transform:uppercase}main{margin:auto;max-width:38rem;padding:clamp(2rem,8vw,5rem) 1.25rem}</style>
Lines changed: 8 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
<script lang="ts">
2-
let submitting = $state(false);
3-
function beginPasskey() { submitting = true; window.location.assign('/webauthn/authenticate/start'); }
2+
import { authenticatePasskey, webauthnAvailable } from '$lib/webauthn';
3+
let accountId=$state('');let submitting=$state(false);let error=$state('');
4+
async function signIn(){if(submitting)return;submitting=true;error='';try{await authenticatePasskey(accountId.trim());window.location.assign('/security');}catch{error='We could not sign you in. Check the account and try again.';submitting=false;}}
45
</script>
5-
6-
<h1>Sign in to Piquel</h1>
7-
<p>Use a passkey or one of the approved identity providers.</p>
8-
<button type="button" onclick={beginPasskey} disabled={submitting}>{submitting ? 'Starting passkey…' : 'Sign in with a passkey'}</button>
9-
<p><a href="/login/github" rel="nofollow">Sign in with GitHub</a></p>
10-
<p><a href="/login/google" rel="nofollow">Sign in with Google</a></p>
11-
<p class="help">Connecting a product-owned GitHub integration is different from signing in with GitHub.</p>
12-
<style>.help { color: #555; font-size: .9rem; }</style>
6+
<svelte:head><title>Sign in · Piquel</title></svelte:head>
7+
<section aria-labelledby="title"><p class="eyebrow">Piquel account</p><h1 id="title">Sign in</h1><p>Use your passkey, or continue with an approved identity provider.</p>
8+
{#if error}<div class="error" role="alert" tabindex="-1">{error}</div>{/if}
9+
{#if webauthnAvailable()}<form onsubmit={async(event)=>{event.preventDefault();await signIn();}}><label for="account">Account ID</label><input id="account" bind:value={accountId} autocomplete="username" required /><button disabled={submitting}>{submitting?'Waiting for your passkey…':'Sign in with a passkey'}</button></form>{:else}<p role="status">Passkeys are unavailable in this browser or insecure context.</p>{/if}
10+
<div class="alternatives" aria-label="Social sign in"><a class="provider" href="/login/github">Sign in with GitHub</a><a class="provider" href="/login/google">Sign in with Google</a></div><p class="help">Need a new account? <a href="/register">Create one with a passkey</a>.</p><p class="help">“Sign in with GitHub” identifies you. Connecting a product-owned GitHub integration is a separate feature.</p></section>
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
<script lang="ts">import{registerPasskey,webauthnAvailable}from'$lib/webauthn';let username=$state('');let displayName=$state('');let friendlyName=$state('This device');let submitting=$state(false);let error=$state('');async function submit(){submitting=true;error='';try{await registerPasskey(username,displayName,friendlyName);window.location.assign('/security');}catch{error='We could not create the account. Nothing was saved; please try again.';submitting=false;}}</script>
2+
<svelte:head><title>Create account · Piquel</title></svelte:head><section><a href="/">← Sign in</a><h1>Create a passkey account</h1>{#if error}<div class="error" role="alert">{error}</div>{/if}{#if webauthnAvailable()}<form onsubmit={async(event)=>{event.preventDefault();await submit();}}><label for="username">Username</label><input id="username" bind:value={username} pattern={'[a-z0-9_]{3,32}'} autocomplete="username" required /><label for="name">Display name</label><input id="name" bind:value={displayName} maxlength="80" autocomplete="name" required /><label for="device">Passkey name</label><input id="device" bind:value={friendlyName} maxlength="80" required /><button disabled={submitting}>{submitting?'Creating passkey…':'Create account and passkey'}</button></form>{:else}<p role="alert">A passkey-capable browser in a secure context is required.</p>{/if}</section>
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
<script lang="ts">
2+
import {onMount} from 'svelte';type Passkey={id:string;friendly_name:string};let passkeys=$state<Passkey[]>([]);let signingOut=$state(false);let error=$state('');let loading=$state(true);
3+
onMount(async()=>{try{const response=await fetch('/account/passkeys',{credentials:'same-origin'});if(response.status===401){window.location.assign('/');return;}if(!response.ok)throw new Error();passkeys=await response.json();}catch{error='We could not load your security settings.';}finally{loading=false;}});
4+
async function rename(passkey:Passkey){const friendly_name=window.prompt('New passkey name',passkey.friendly_name)?.trim();if(!friendly_name)return;const response=await fetch(`/account/passkeys/${passkey.id}`,{method:'PATCH',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({friendly_name})});if(response.ok)passkey.friendly_name=friendly_name;else error='Fresh sign-in is required to change this passkey.';}
5+
async function remove(passkey:Passkey){if(!window.confirm(`Remove “${passkey.friendly_name}”? You cannot undo this.`))return;const response=await fetch(`/account/passkeys/${passkey.id}`,{method:'DELETE',credentials:'same-origin'});if(response.ok)passkeys=passkeys.filter((value)=>value.id!==passkey.id);else error='Keep at least one sign-in method and sign in again before removing a passkey.';}
6+
async function logout(){signingOut=true;const response=await fetch('/session/logout',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'}});if(response.ok)window.location.assign('/');else{error='We could not sign out. Please try again.';signingOut=false;}}
7+
</script>
8+
<svelte:head><title>Account security · Piquel</title></svelte:head><section><p class="eyebrow">Piquel account</p><h1>Account security</h1>{#if error}<div class="error" role="alert">{error}</div>{/if}<div class="card"><h2>Passkeys</h2>{#if loading}<p role="status">Loading passkeys…</p>{:else if passkeys.length}<ul>{#each passkeys as passkey}<li><span>{passkey.friendly_name}</span><span><button class="secondary compact" onclick={()=>rename(passkey)}>Rename</button> <button class="danger compact" onclick={()=>remove(passkey)}>Remove</button></span></li>{/each}</ul>{:else}<p>No passkeys were returned.</p>{/if}<a class="provider" href="/register">Add a passkey</a><p class="help">Changes require a sign-in from the last ten minutes.</p></div><div class="card"><h2>Social sign-in</h2><p>GitHub and Google identities are linked by stable provider identity, never by email alone.</p></div><button class="secondary" onclick={logout} disabled={signingOut}>{signingOut?'Signing out…':'Sign out'}</button></section><style>ul{list-style:none;padding:0;display:grid;gap:.6rem}li{display:flex;align-items:center;justify-content:space-between;gap:1rem}.compact{min-height:2rem;padding:.45rem .7rem}.danger{background:#8b2929}</style>

‎apps/auth-web/svelte.config.js‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
import adapter from '@sveltejs/adapter-auto';
1+
import adapter from '@sveltejs/adapter-node';
22

33
export default { kit: { adapter: adapter() } };

0 commit comments

Comments
 (0)