Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ debug
target
node_modules
.svelte-kit
apps/auth-web/build

# These are backup files generated by rustfmt
**/*.rs.bk
Expand Down
6 changes: 5 additions & 1 deletion apps/auth-service/src/oidc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -779,7 +779,11 @@ fn require_same_origin(app: &OidcApplication, headers: &HeaderMap) -> Result<(),
.get("x-piquel-csrf")
.and_then(|value| value.to_str().ok())
== Some("1");
(origin_matches && csrf_header)
let same_origin_fetch = headers
.get("sec-fetch-site")
.and_then(|value| value.to_str().ok())
== Some("same-origin");
(origin_matches && (csrf_header || same_origin_fetch))
.then_some(())
.ok_or_else(ApiError::request)
}
Expand Down
29 changes: 24 additions & 5 deletions apps/auth-service/src/passkey.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ use webauthn_rs::{
pub struct PasskeyApplication {
database: Database,
webauthn: Arc<Webauthn>,
issuer: Arc<str>,
origin: Arc<str>,
purpose_keys: Arc<Es256KeyProvider>,
}

Expand Down Expand Up @@ -73,7 +73,7 @@ impl PasskeyApplication {
Ok(Self {
database,
webauthn: Arc::new(webauthn),
issuer: origin.as_str().trim_end_matches('/').into(),
origin: origin.as_str().trim_end_matches('/').into(),
purpose_keys,
})
}
Expand Down Expand Up @@ -514,7 +514,7 @@ async fn finish_purpose_authorization(
let now = Utc::now();
let authorization_id = TokenId::new();
let claims = PurposeTokenClaims {
iss: app.issuer.to_string(),
iss: app.origin.to_string(),
sub: session.user_id,
aud: PURPOSE_AUDIENCE.into(),
purpose: MANAGE_PASSKEYS_PURPOSE.into(),
Expand Down Expand Up @@ -598,6 +598,7 @@ async fn start_enrollment(
State(app): State<PasskeyApplication>,
headers: HeaderMap,
) -> Result<Json<RegistrationStarted>, ApiError> {
validate_mutation_origin(&app, &headers)?;
let session = active_session(&app.database, &headers).await?;
let authorization = require_purpose_authorization(&app, &headers, &session).await?;
let user = app
Expand Down Expand Up @@ -644,6 +645,7 @@ async fn finish_enrollment(
headers: HeaderMap,
Json(input): Json<RegistrationFinish>,
) -> Result<StatusCode, ApiError> {
validate_mutation_origin(&app, &headers)?;
if input.friendly_name.trim().is_empty() || input.friendly_name.chars().count() > 80 {
return Err(ApiError);
}
Expand Down Expand Up @@ -747,6 +749,7 @@ async fn rename_passkey(
if input.friendly_name.trim().is_empty() || input.friendly_name.chars().count() > 80 {
return Err(ApiError);
}
validate_mutation_origin(&app, &headers)?;
let session = active_session(&app.database, &headers).await?;
app.database
.passkeys()
Expand All @@ -762,6 +765,7 @@ async fn revoke_passkey(
headers: HeaderMap,
Path(id): Path<TokenId>,
) -> Result<StatusCode, ApiError> {
validate_mutation_origin(&app, &headers)?;
let session = active_session(&app.database, &headers).await?;
let authorization = require_purpose_authorization(&app, &headers, &session).await?;
let mut transaction = app.database.begin().await.map_err(|_| ApiError)?;
Expand Down Expand Up @@ -825,7 +829,7 @@ async fn require_purpose_authorization(
.verify(PURPOSE_TOKEN_TYPE, token)
.map_err(|()| ApiError)?;
if !claims.is_valid_for(
&app.issuer,
&app.origin,
session.user_id,
session.id,
Utc::now().timestamp(),
Expand Down Expand Up @@ -896,6 +900,7 @@ async fn logout(
State(app): State<PasskeyApplication>,
headers: HeaderMap,
) -> Result<Response, ApiError> {
validate_mutation_origin(&app, &headers)?;
let secret = session_secret(&headers).ok_or(ApiError)?;
if let Some(session) = app
.database
Expand Down Expand Up @@ -927,6 +932,18 @@ fn session_secret(headers: &HeaderMap) -> Option<Vec<u8>> {
.filter(|secret| secret.len() == 32)
}

fn validate_mutation_origin(app: &PasskeyApplication, headers: &HeaderMap) -> Result<(), ApiError> {
let origin = headers
.get(header::ORIGIN)
.and_then(|value| value.to_str().ok())
.ok_or(ApiError)?;
if origin.trim_end_matches('/') == app.origin.as_ref() {
Ok(())
} else {
Err(ApiError)
}
}

#[derive(Debug)]
struct ApiError;
impl IntoResponse for ApiError {
Expand Down Expand Up @@ -965,7 +982,9 @@ mod tests {
) -> Request<Body> {
let mut builder = Request::builder().method(method).uri(uri);
if let Some(cookie) = cookie {
builder = builder.header(header::COOKIE, cookie);
builder = builder
.header(header::COOKIE, cookie)
.header(header::ORIGIN, "https://auth.example.com");
}
if let Some(token) = purpose_token {
builder = builder.header(header::AUTHORIZATION, format!("Bearer {token}"));
Expand Down
22 changes: 22 additions & 0 deletions apps/auth-web/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "@piquel/auth-web",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"test": "vitest run"
},
"devDependencies": {
"@sveltejs/adapter-node": "^5.0.0",
"@sveltejs/kit": "^2.0.0",
"@sveltejs/vite-plugin-svelte": "^6.0.0",
"svelte": "^5.0.0",
"svelte-check": "^4.0.0",
"typescript": "^5.0.0",
"vite": "^7.0.0",
"vitest": "^3.2.4"
}
}
2 changes: 2 additions & 0 deletions apps/auth-web/src/app.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
declare global { namespace App {} }
export {};
9 changes: 9 additions & 0 deletions apps/auth-web/src/app.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover"><div style="display: contents">%sveltekit.body%</div></body>
</html>
11 changes: 11 additions & 0 deletions apps/auth-web/src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { Handle } from '@sveltejs/kit';

export const handle: Handle = async ({ event, resolve }) => {
const response = await resolve(event);
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'");
response.headers.set('Referrer-Policy', 'no-referrer');
response.headers.set('X-Content-Type-Options', 'nosniff');
response.headers.set('Permissions-Policy', 'publickey-credentials-get=(self), publickey-credentials-create=(self), camera=(), microphone=(), geolocation=()');
response.headers.set('Cache-Control', 'no-store');
return response;
};
62 changes: 62 additions & 0 deletions apps/auth-web/src/lib/Login.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
<script lang="ts">
import { onMount } from 'svelte';
import { authenticatePasskey, webauthnAvailable } from '$lib/webauthn';
import { authorizationDestination, safeReturnTo } from '$lib/navigation';

let username = $state('');
let transaction = $state('');
let returnTo = $state('');
let submitting = $state(false);
let error = $state('');

onMount(() => {
const query = new URLSearchParams(window.location.search);
transaction = query.get('transaction') ?? '';
const requested = query.get('return_to') ?? '';
returnTo = safeReturnTo(requested);
});

function destination() {
return authorizationDestination(transaction, returnTo);
}

function providerUrl(provider: 'github' | 'google') {
return `/login/${provider}?return_to=${encodeURIComponent(destination())}`;
}

async function signIn() {
if (submitting) return;
submitting = true;
error = '';
try {
await authenticatePasskey(username.trim());
window.location.assign(destination());
} catch {
error = 'We could not sign you in. Check the username and try again.';
submitting = false;
}
}
</script>

<svelte:head><title>Sign in · Piquel</title></svelte:head>
<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>
{#if error}<div class="error" role="alert" tabindex="-1">{error}</div>{/if}
{#if webauthnAvailable()}
<form onsubmit={async (event) => { event.preventDefault(); await signIn(); }}>
<label for="username">Username</label>
<input id="username" bind:value={username} autocomplete="username webauthn" pattern={'[a-z0-9_]{3,32}'} 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}
<div class="alternatives" aria-label="Social sign in">
<a class="provider" href={providerUrl('github')}>Sign in with GitHub</a>
<a class="provider" href={providerUrl('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>
14 changes: 14 additions & 0 deletions apps/auth-web/src/lib/navigation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { describe, expect, it } from 'vitest';
import { authorizationDestination, safeReturnTo } from './navigation';

describe('authorization navigation', () => {
it('carries only an opaque transaction to the authorization page', () => {
expect(authorizationDestination('par_v1_value', '')).toBe('/authorize?transaction=par_v1_value');
});

it('rejects cross-origin and fragment return targets', () => {
expect(safeReturnTo('//evil.example')).toBe('');
expect(safeReturnTo('/security#token')).toBe('');
expect(safeReturnTo('/security')).toBe('/security');
});
});
9 changes: 9 additions & 0 deletions apps/auth-web/src/lib/navigation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export function safeReturnTo(value: string | null): string {
if (!value || value.length > 512 || !value.startsWith('/') || value.startsWith('//') || value.includes('#')) return '';
return value;
}

export function authorizationDestination(transaction: string, returnTo: string): string {
if (transaction) return `/authorize?transaction=${encodeURIComponent(transaction)}`;
return safeReturnTo(returnTo) || '/security';
}
24 changes: 24 additions & 0 deletions apps/auth-web/src/lib/webauthn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
function decode(value: string): ArrayBuffer {
const padded = value.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - value.length % 4) % 4);
const bytes = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));
return bytes.buffer;
}
function encode(value: ArrayBuffer): string {
const bytes = new Uint8Array(value);
let binary = '';
for (const byte of bytes) binary += String.fromCharCode(byte);
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function creationOptions(publicKey: any): PublicKeyCredentialCreationOptions {
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)})) };
}
function requestOptions(publicKey:any):PublicKeyCredentialRequestOptions {
return { ...publicKey, challenge:decode(publicKey.challenge), allowCredentials:publicKey.allowCredentials?.map((item:any)=>({...item,id:decode(item.id)})) };
}
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()};}
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()};}
async function json(response:Response){if(!response.ok)throw new Error('authentication failed');return response.json();}
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');}
export async function authenticatePasskey(username:string){const start=await json(await fetch('/webauthn/authenticate/start',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json'},body:JSON.stringify({username})}));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');}
export async function enrollPasskey(friendlyName:string){const start=await json(await fetch('/account/passkeys/enroll/start',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json','x-piquel-csrf':'1'},body:'{}'}));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('/account/passkeys/enroll/finish',{method:'POST',credentials:'same-origin',headers:{'content-type':'application/json','x-piquel-csrf':'1'},body:JSON.stringify({ceremony_id:start.ceremony_id,credential:registration(credential),friendly_name:friendlyName})});if(!finish.ok)throw new Error('authentication failed');}
export const webauthnAvailable=()=>typeof window!=='undefined'&&window.isSecureContext&&'PublicKeyCredential'in window;
4 changes: 4 additions & 0 deletions apps/auth-web/src/routes/+layout.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
<script lang="ts">let { children } = $props();</script>
<svelte:head><title>Piquel authentication</title><meta name="robots" content="noindex" /></svelte:head>
<main>{@render children()}</main>
<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>
2 changes: 2 additions & 0 deletions apps/auth-web/src/routes/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<script lang="ts">import Login from '$lib/Login.svelte';</script>
<Login />
46 changes: 46 additions & 0 deletions apps/auth-web/src/routes/authorize/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<script lang="ts">
import { onMount } from 'svelte';
type Transaction = { client_name: string; scopes: string[]; audience: string };
let transaction = $state('');
let details = $state<Transaction | null>(null);
let error = $state('');

onMount(async () => {
transaction = new URLSearchParams(window.location.search).get('transaction') ?? '';
if (!transaction) { error = 'This authorization request is missing or expired.'; return; }
try {
const response = await fetch(`/oauth/authorize/transaction/${encodeURIComponent(transaction)}`, { credentials: 'same-origin' });
if (response.status === 401) {
window.location.assign(`/login?transaction=${encodeURIComponent(transaction)}`);
return;
}
if (!response.ok) throw new Error();
details = await response.json();
} catch {
error = 'This authorization request is invalid or has expired.';
}
});
</script>

<svelte:head><title>Authorize application · Piquel</title></svelte:head>
<section aria-labelledby="title">
<p class="eyebrow">Authorization</p>
<h1 id="title">Continue to {details?.client_name ?? 'the application'}</h1>
{#if error}
<div class="error" role="alert">{error}</div>
<a href="/login">Return to sign in</a>
{:else if !details}
<p role="status">Loading the authorization request…</p>
{:else}
<div class="card">
<p><strong>{details.client_name}</strong> is requesting access to <code>{details.audience}</code>.</p>
<h2>Requested permissions</h2>
<ul>{#each details.scopes as scope}<li><code>{scope}</code></li>{/each}</ul>
</div>
<form method="POST" action="/oauth/authorize/decision">
<input type="hidden" name="transaction" value={transaction} />
<button name="decision" value="approve">Continue</button>
<button class="secondary" name="decision" value="deny">Cancel</button>
</form>
{/if}
</section>
2 changes: 2 additions & 0 deletions apps/auth-web/src/routes/login/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<script lang="ts">import Login from '$lib/Login.svelte';</script>
<Login />
2 changes: 2 additions & 0 deletions apps/auth-web/src/routes/register/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<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>
<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>
Loading