Passkeys: the registration page (#334) #469

Merged
jcoffey-dev merged 1 commits from feat/334-passkey-register into main 2026-11-19 03:27:22 +00:00
15 changed files with 2383 additions and 78 deletions

No files matched your search

Generated
+602 -63
View File
File diff suppressed because it is too large. Load diff
+2
View File
@@ -150,6 +150,8 @@ pub const KV_PORT_REACHABILITY: u8 = 200;
pub const KV_OAUTH_DEVICE: u8 = 201;
// inbuxa: K-S4: revoked OAuth tokens, one list per account
pub const KV_OAUTH_REVOKED: u8 = 202;
// inbuxa: passkeys: a registration or sign-in between its two steps
pub const KV_PASSKEY_CEREMONY: u8 = 203;
#[derive(Clone)]
pub struct Server {
+80 -4
View File
@@ -11,8 +11,8 @@
//! - `p` + account id + number: the passkey's `Passkey` record.
//! - `c` + credential id: the account and number it belongs to, so sign-in
//! finds a passkey without loading accounts.
//! - `h` + account id: the account's user handle, 32 random bytes the
//! authenticator keeps as the user id.
//! - `h` + account id: the account's user handle, 16 random bytes the
//! authenticator keeps as the user id (a UUID, as webauthn-rs wants it).
//! - `u` + user handle: the account it belongs to.
//! - `t` + SHA-256 of a registration ticket: the pending passkey it opens
//! (PK-6).
@@ -46,7 +46,7 @@ pub const TICKET_SECONDS: u64 = 600;
/// The longest name (PK-5).
pub const MAX_NAME: usize = 64;
/// The length of a user handle.
pub const HANDLE_LEN: usize = 32;
pub const HANDLE_LEN: usize = 16;
const CREATE_ATTEMPTS: usize = 5;
#[derive(Debug, Clone, Copy, PartialEq, Eq, SerdeSerialize, SerdeDeserialize)]
@@ -85,7 +85,8 @@ pub struct Passkey {
/// The authenticator's credential id.
#[serde(default)]
pub credential_id: Vec<u8>,
/// The public key, as COSE.
/// The credential as the WebAuthn library keeps it (JSON): the COSE
/// public key, the counter and the flags it checks at sign-in.
#[serde(default)]
pub public_key: Vec<u8>,
#[serde(default)]
@@ -380,6 +381,81 @@ pub async fn account_of_handle(data: &Store, handle: &[u8]) -> trc::Result<Optio
.caused_by(trc::location!())?)
}
/// The account's user handle, made from `fresh` the first time. Two
/// registrations at once agree on one handle.
pub async fn ensure_user_handle(
data: &Store,
account_id: u32,
fresh: [u8; HANDLE_LEN],
) -> trc::Result<Vec<u8>> {
if let Some(handle) = user_handle(data, account_id).await? {
return Ok(handle);
}
let record = class(KIND_HANDLE, &account_id.to_be_bytes());
let mut batch = BatchBuilder::new();
batch.assert_value(record.clone(), AssertValue::None);
batch.set(record, fresh.to_vec());
batch.set(
class(KIND_HANDLE_ACCOUNT, &fresh),
account_id.to_be_bytes().to_vec(),
);
match data.write(batch.build_all()).await {
Ok(_) => Ok(fresh.to_vec()),
Err(err)
if matches!(
err.as_ref(),
trc::EventType::Store(trc::StoreEvent::AssertValueFailed)
) =>
{
user_handle(data, account_id)
.await?
.ok_or_else(|| err.caused_by(trc::location!()))
}
Err(err) => Err(err.caused_by(trc::location!())),
}
}
pub enum Activated {
Done(Passkey),
/// The credential id is already registered, to this or another account.
Taken,
}
/// Finishes a registration (PK-7): the pending passkey turns active with
/// what the authenticator gave, its credential id is indexed, and the ticket
/// is spent. A credential id registered before is refused.
pub async fn activate(data: &Store, ticket: &str, passkey: Passkey) -> trc::Result<Activated> {
let credential = class(KIND_CREDENTIAL, &passkey.credential_id);
if passkey.credential_id.is_empty()
|| by_credential(data, &passkey.credential_id).await?.is_some()
{
return Ok(Activated::Taken);
}
let mut batch = BatchBuilder::new();
batch.assert_value(credential.clone(), AssertValue::None);
batch.set(
credential,
pair(passkey.account_id, passkey.number).to_vec(),
);
batch.set(
class(KIND_PASSKEY, &pair(passkey.account_id, passkey.number)),
to_json(&passkey)?,
);
batch.clear(class(KIND_TICKET, &ticket_hash(ticket)));
match data.write(batch.build_all()).await {
Ok(_) => Ok(Activated::Done(passkey)),
Err(err)
if matches!(
err.as_ref(),
trc::EventType::Store(trc::StoreEvent::AssertValueFailed)
) =>
{
Ok(Activated::Taken)
}
Err(err) => Err(err.caused_by(trc::location!())),
}
}
/// How many times the account's passkeys were removed (PK-15).
pub async fn epoch(data: &Store, account_id: u32) -> trc::Result<u64> {
Ok(data
+2
View File
@@ -40,6 +40,8 @@ form-data = { version = "0.6.0", features = ["sync"], default-features = false }
mime = "0.3.17"
percent-encoding = "2.3.2"
hashify = { version = "0.2" }
webauthn-rs = { version = "0.6.2", features = ["danger-allow-state-serialisation", "danger-credential-internals", "conditional-ui"] } # inbuxa: passkeys
webauthn-rs-proto = "0.6.2" # inbuxa: passkeys
[dev-dependencies]
flate2 = "1.1"
+12 -1
View File
@@ -11,7 +11,8 @@ pub mod diagnose;
use crate::{
api::diagnose::{DeliveryStage, parse_delivery_target, spawn_delivery_diagnose},
auth::{
authenticate::Authenticator, oauth::auth::OAuthApiHandler, permissions::AccountApiHandler,
authenticate::Authenticator, oauth::auth::OAuthApiHandler,
passkey::PasskeyRegistrationHandler, permissions::AccountApiHandler,
},
};
use common::{
@@ -74,6 +75,16 @@ impl ManagementApi for Server {
))
.await
}
// inbuxa: passkeys: the registration page's two steps (PK-6 to PK-8)
"passkey" if is_post && path.get(1).copied() == Some("register") => {
self.is_http_anonymous_request_allowed(session.remote_ip)
.await?;
Box::pin(self.handle_passkey_registration(
session,
body.ok_or_else(|| trc::LimitEvent::SizeRequest.into_err())?,
))
.await
}
"calendar"
if is_post
&& path.get(1).copied() == Some("rsvp")
+1
View File
@@ -8,5 +8,6 @@
pub mod authenticate;
pub mod oauth;
pub mod passkey; // inbuxa: passkeys
pub mod permissions;
pub mod token_only;
+356
View File
@@ -0,0 +1,356 @@
/*
* SPDX-FileCopyrightText: 2026 Coffey Labs LLC
*
* SPDX-License-Identifier: AGPL-3.0-only
*/
//! inbuxa: passkey registration (passkeys spec, PK-6 to PK-8).
//!
//! `inbuxa:Passkey/set` create hands back a URL to `/passkey/register` with
//! a single-use ticket. That page posts here twice:
//!
//! 1. `start`, with the ticket and the account's password (and TOTP code
//! when it has one). The answer is the options for the browser's
//! `navigator.credentials.create`. A stolen session token can start a
//! registration, but without the password it can't get this far (PK-8).
//! 2. `finish`, with the ticket and what the browser made. The passkey
//! turns active (PK-7).
//!
//! What `start` began waits in the in-memory store under the ticket, so any
//! node can answer `finish`, and it's deleted as it's read: it's good once.
use common::{
KV_PASSKEY_CEREMONY, Server,
auth::{AccessToken, AuthRequest},
};
use directory::Credentials;
use http_proto::{HttpResponse, HttpSessionData, JsonResponse, ToHttpResponse};
use inbuxa_features::passkey::{self, Activated, HANDLE_LEN, Passkey};
use serde::{Deserialize, Serialize};
use store::{
dispatch::lookup::KeyValue,
rand::{RngExt, rng},
write::now,
};
use trc::AddContext;
use webauthn_rs::prelude::{
CreationChallengeResponse, Credential, CredentialID, PasskeyRegistration,
RegisterPublicKeyCredential, Url, Uuid, Webauthn, WebauthnBuilder,
};
use webauthn_rs_proto::ResidentKeyRequirement;
/// How long the browser has between `start` and `finish`.
const CEREMONY_SECONDS: u64 = 300;
#[derive(Debug, Deserialize)]
#[serde(tag = "step", rename_all = "camelCase")]
pub enum RegisterRequest {
#[serde(rename_all = "camelCase")]
Start {
ticket: String,
password: String,
#[serde(default)]
mfa_token: Option<String>,
},
#[serde(rename_all = "camelCase")]
Finish {
ticket: String,
credential: Box<RegisterPublicKeyCredential>,
},
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum RegisterResponse {
/// The options for `navigator.credentials.create`.
#[serde(rename_all = "camelCase")]
Options {
name: String,
account_name: String,
options: Box<CreationChallengeResponse>,
},
#[serde(rename_all = "camelCase")]
Registered {
name: String,
},
/// The ticket is unknown, used or out of time.
Expired,
MfaRequired,
/// The password or code was wrong.
Failure,
/// The authenticator's answer didn't check out, or that passkey is
/// already registered.
#[serde(rename_all = "camelCase")]
Refused {
reason: String,
},
}
/// What waits between `start` and `finish`.
#[derive(Serialize, Deserialize)]
struct Ceremony {
account_id: u32,
number: u32,
rp_id: String,
state: PasskeyRegistration,
}
/// The WebAuthn relying party for this server (PK-3): the host of its public
/// HTTPS URL, which is also the only origin it accepts.
pub fn relying_party(server: &Server) -> trc::Result<(Webauthn, String)> {
let rp_id = jmap::inbuxa::passkey::current_rp_id(server);
let origin = Url::parse(&server.core.network.http.url_https).map_err(|err| {
trc::AuthEvent::Error
.into_err()
.details("The server's public URL isn't a URL.")
.reason(err)
})?;
let webauthn = WebauthnBuilder::new(&rp_id, &origin)
.and_then(|builder| builder.rp_name("inbuxa").build())
.map_err(|err| {
trc::AuthEvent::Error
.into_err()
.details("Passkeys need the server's public URL to name a host.")
.reason(err)
})?;
Ok((webauthn, rp_id))
}
fn ceremony_key(ticket: &str) -> Vec<u8> {
KeyValue::<()>::build_key(KV_PASSKEY_CEREMONY, passkey::ticket_hash(ticket))
}
pub trait PasskeyRegistrationHandler: Sync + Send {
fn handle_passkey_registration(
&self,
session: &HttpSessionData,
body: Vec<u8>,
) -> impl Future<Output = trc::Result<HttpResponse>> + Send;
}
impl PasskeyRegistrationHandler for Server {
async fn handle_passkey_registration(
&self,
session: &HttpSessionData,
body: Vec<u8>,
) -> trc::Result<HttpResponse> {
let request = serde_json::from_slice::<RegisterRequest>(&body).map_err(|err| {
trc::EventType::Resource(trc::ResourceEvent::BadParameters).from_json_error(err)
})?;
let response = match request {
RegisterRequest::Start {
ticket,
password,
mfa_token,
} => start(self, session, &ticket, password, mfa_token).await?,
RegisterRequest::Finish { ticket, credential } => {
finish(self, &ticket, &credential).await?
}
};
Ok(JsonResponse::new(response).no_cache().into_http_response())
}
}
async fn start(
server: &Server,
session: &HttpSessionData,
ticket: &str,
password: String,
mfa_token: Option<String>,
) -> trc::Result<RegisterResponse> {
let Some(pending) = passkey::by_ticket(server.store(), ticket, now()).await? else {
return Ok(RegisterResponse::Expired);
};
let account = server
.account(pending.account_id)
.await
.caused_by(trc::location!())?;
// PK-8: the password (and code) first. The sign-in limits and the
// failure counting are the ones every sign-in goes through.
let access_token: AccessToken = match server
.authenticate(&AuthRequest {
credentials: Credentials::Basic {
username: account.name.to_string(),
secret: password,
mfa_token,
},
session_id: session.session_id,
remote_ip: session.remote_ip,
})
.await
{
Ok(access_token) => access_token,
Err(err) => {
return match *err.as_ref() {
trc::EventType::Auth(trc::AuthEvent::MfaRequired) => {
trc::error!(err.span_id(session.session_id));
Ok(RegisterResponse::MfaRequired)
}
trc::EventType::Auth(_) | trc::EventType::Security(_) => {
trc::error!(err.span_id(session.session_id));
Ok(RegisterResponse::Failure)
}
_ => Err(err),
};
}
};
if access_token.account_id() != pending.account_id {
return Ok(RegisterResponse::Failure);
}
let (webauthn, rp_id) = relying_party(server)?;
let fresh = rng().random::<[u8; HANDLE_LEN]>();
let handle = passkey::ensure_user_handle(server.store(), pending.account_id, fresh).await?;
let user_id = Uuid::from_slice(&handle).map_err(|err| {
trc::StoreEvent::DataCorruption
.into_err()
.details("Invalid passkey user handle")
.reason(err)
})?;
// Registering the same authenticator twice is refused by the browser
let exclude = passkey::all(server.store(), pending.account_id)
.await?
.into_iter()
.filter(|p| !p.credential_id.is_empty())
.map(|p| CredentialID::from(p.credential_id))
.collect::<Vec<_>>();
let display_name = account
.description
.as_deref()
.filter(|name| !name.trim().is_empty())
.unwrap_or(&account.name);
let (mut options, state) = webauthn
.start_passkey_registration(
user_id,
&account.name,
display_name,
(!exclude.is_empty()).then_some(exclude),
)
.map_err(|err| {
trc::AuthEvent::Error
.into_err()
.details("Failed to start a passkey registration")
.reason(err)
})?;
// PK-1: discoverable, so the login page can offer it before anyone
// types a name. The library leaves it optional.
let selection = options
.public_key
.authenticator_selection
.get_or_insert_with(Default::default);
selection.resident_key = Some(ResidentKeyRequirement::Required);
selection.require_resident_key = true;
let ceremony = serde_json::to_string(&Ceremony {
account_id: pending.account_id,
number: pending.number,
rp_id,
state,
})
.map_err(|err| {
trc::StoreEvent::UnexpectedError
.into_err()
.details("Failed to serialize a passkey registration")
.reason(err)
})?;
let left = pending.ticket_expires.saturating_sub(now()).max(1);
server
.in_memory_store()
.key_set(
KeyValue::new(ceremony_key(ticket), ceremony.into_bytes())
.expires(left.min(CEREMONY_SECONDS)),
)
.await?;
Ok(RegisterResponse::Options {
name: pending.name,
account_name: account.name.to_string(),
options: Box::new(options),
})
}
async fn finish(
server: &Server,
ticket: &str,
credential: &RegisterPublicKeyCredential,
) -> trc::Result<RegisterResponse> {
// Good once: read and deleted
let key = ceremony_key(ticket);
let Some(ceremony) = server
.in_memory_store()
.key_get::<String>(key.clone())
.await?
else {
return Ok(RegisterResponse::Expired);
};
server.in_memory_store().key_delete(key).await?;
let ceremony = serde_json::from_str::<Ceremony>(&ceremony).map_err(|err| {
trc::StoreEvent::DataCorruption
.into_err()
.details("Invalid passkey registration")
.reason(err)
})?;
let Some(pending) = passkey::by_ticket(server.store(), ticket, now())
.await?
.filter(|p| p.account_id == ceremony.account_id && p.number == ceremony.number)
else {
return Ok(RegisterResponse::Expired);
};
let (webauthn, rp_id) = relying_party(server)?;
if rp_id != ceremony.rp_id {
return Ok(RegisterResponse::Expired);
}
let made = match webauthn.finish_passkey_registration(credential, &ceremony.state) {
Ok(made) => made,
Err(err) => {
trc::event!(
Auth(trc::AuthEvent::Failed),
AccountId = pending.account_id,
Details = "Passkey registration refused",
Reason = err.to_string(),
);
return Ok(RegisterResponse::Refused {
reason: "The passkey couldn't be checked. Try again.".to_string(),
});
}
};
let public_key = serde_json::to_vec(&made).map_err(|err| {
trc::StoreEvent::UnexpectedError
.into_err()
.details("Failed to serialize a passkey")
.reason(err)
})?;
// The attestation isn't asked for (PK-2), so there's no AAGUID to keep
let backed_up = Credential::from(made.clone()).backup_state;
let transports = credential
.response
.transports
.iter()
.flatten()
.filter_map(|t| serde_json::to_value(t).ok())
.filter_map(|t| t.as_str().map(str::to_string))
.collect();
let name = pending.name.clone();
let active = Passkey {
state: passkey::State::Active,
ticket_expires: 0,
rp_id,
credential_id: made.cred_id().to_vec(),
public_key,
sign_count: 0,
transports,
backed_up,
aaguid: Vec::new(),
..pending
};
match passkey::activate(server.store(), ticket, active).await? {
Activated::Done(_) => Ok(RegisterResponse::Registered { name }),
Activated::Taken => Ok(RegisterResponse::Refused {
reason: "That passkey is already registered.".to_string(),
}),
}
}
+21 -1
View File
@@ -62,6 +62,12 @@ static RSVP_PAGE: &[u8] = include_bytes!(concat!(
"/../../resources/html-templates/calendar-rsvp.html.min.gz"
));
// inbuxa: passkeys: where a passkey is registered (PK-6)
static PASSKEY_PAGE: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../resources/html-templates/passkey.html.min.gz"
));
static LOGIN_PAGE: &[u8] = include_bytes!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../resources/html-templates/login.html.min.gz"
@@ -681,6 +687,12 @@ impl ParseHttp for Server {
}
}
}
"passkey" if path.next() == Some("register") => {
return Ok(HttpResponse::new(StatusCode::OK)
.with_content_type("text/html; charset=utf-8")
.with_header(CONTENT_ENCODING, "gzip")
.with_binary_body(PASSKEY_PAGE));
}
"login" | "device" => {
return Ok(HttpResponse::new(StatusCode::OK)
.with_content_type("text/html; charset=utf-8")
@@ -981,7 +993,7 @@ mod tests {
use flate2::read::GzDecoder;
use std::io::Read;
const PAGES: [(&str, &[u8], &str); 2] = [
const PAGES: [(&str, &[u8], &str); 3] = [
(
"calendar-rsvp.html",
super::RSVP_PAGE,
@@ -990,6 +1002,14 @@ mod tests {
"/../../resources/html-templates/calendar-rsvp.html.min"
)),
),
(
"passkey.html",
super::PASSKEY_PAGE,
include_str!(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../resources/html-templates/passkey.html.min"
)),
),
(
"login.html",
super::LOGIN_PAGE,
+9 -2
View File
@@ -88,7 +88,8 @@ passwords.
- **PK-1.** Registration and sign-in use discoverable credentials
(`residentKey: required`) with user verification required. Attestation is
`none`. Algorithms: ES256, EdDSA, RS256, in that order.
`none`. Algorithms: ES256, ES384, RS256, in that order: the set the
WebAuthn library (webauthn-rs) calls tested. EdDSA waits until it does.
- **PK-2.** The origin of every ceremony must be `https://` with a host that
equals the relying-party id or ends with `.` plus it, and is one of the
server's own HTTP hostnames. Anything else is refused.
@@ -263,7 +264,13 @@ Building, one PR each:
default), removal ending the account's sessions through the credential
version, and account deletion. Pending ones expire after 10 minutes. The
limit is fixed at 10 until the settings arrive (step 4).
2. The registration page.
2. The registration page: `/passkey/register` served by the server, and
`POST /api/passkey/register` with a `start` step (ticket and password,
plus the TOTP code when the account has one; anonymous, limited like the
other sign-in requests) and a `finish` step. What `start` began waits in
the in-memory store for up to 5 minutes and is good once. Until sign-in
with a passkey exists (step 3), the page asks for the password only; the
"or an active passkey" of PK-8 comes with it.
3. Sign-in in the authorization-code flow, with autofill.
4. The device flow, the settings and policy, and the sign-in events.
+531
View File
@@ -0,0 +1,531 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="referrer" content="no-referrer">
<script>
// INBUXA (#375): the app that opened this page can pass theme=light or
// theme=dark so the page matches it; anything else follows the OS.
(function () {
var t = new URLSearchParams(window.location.search).get('theme');
if (t === 'light' || t === 'dark') document.documentElement.setAttribute('data-theme', t);
})();
</script>
<title>Add a passkey · inbuxa</title>
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAR4ElEQVRo3u1aeXSV1bXf+5xvuHNyczOQGCAhCQQSEQEBEX3ocqJWUVwq8Vmxdnhaq3ZZO9hnW95qV63Vqu/J66CV95xaZBAFRHEqYAUEBFFAQsIQyUBC5tzc77v3O+fs98d37+UifXAjWavteu+srKzcm+87Z//23mcPv3OQiOAfebC/tQD/D+BvLcDfAgARKaWGcfOcyYQ41NeUUowlYUulECD98QsMpRQB8IwJ+RBnG9rTShFjzLasg4cPRwcGOGOMMSm/iPKISErJGOOM9fX2Nhw4KByHM6bU0KYaggVc9Wz5cNcdCx9v6ooWhkOXTKm+q25u7fhxACCl4vy4Ok6eFhEzFe/a7eDhpidfWLnm/Y86+gbGl0Ye+e4dF06fnGnkYQNARIiYiMdn3PStjvbWWyb5P+2S7zTaXDfvnHfpg3fdFggEhJQMURExxliGuKkZQKrkAxrnAPDvz7zws8Wvx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jrh7/yOL86WcToLQTqB0/zMNksZesODLXOjMARJnGTa9GUnKvCULt//WzzLine truncated
<style>
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0
}
:root {
--bg: #f6f8fa;
--card: #ffffff;
--border: #e3e7ec;
--text: #111827;
--muted: #5b6472;
--accent: #0f766e;
--accent-fg: #ffffff;
--info: #0e7490;
--success: #15803d;
--radius: 10px;
--input-bg: #ffffff;
--brand-ink: #1C4053;
--danger: #b91c1c;
}
:root {
color-scheme: light dark;
}
:root[data-theme="light"] {
color-scheme: light;
}
@media(prefers-color-scheme:dark) {
:root:not([data-theme="light"]) {
--bg: #0b1220;
--card: #111a2b;
--border: #1f2a3d;
--text: #e5e9f0;
--muted: #9aa5b8;
--accent: #2dd4bf;
--accent-fg: #052e2b;
--info: #67e8f9;
--success: #4ade80;
--input-bg: #0d1524;
--brand-ink: #e5e9f0;
--danger: #f87171;
}
}
:root[data-theme="dark"] {
color-scheme: dark;
--bg: #0b1220;
--card: #111a2b;
--border: #1f2a3d;
--text: #e5e9f0;
--muted: #9aa5b8;
--accent: #2dd4bf;
--accent-fg: #052e2b;
--info: #67e8f9;
--success: #4ade80;
--input-bg: #0d1524;
--brand-ink: #e5e9f0;
--danger: #f87171;
}
body {
font-family: "Inter", system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
}
.card {
background: var(--card);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 0.5rem 2.25rem 2rem;
width: 100%;
max-width: 384px;
}
.logo-wrap {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
min-height: 72px;
margin: 0.25rem auto 0.5rem;
}
.logo-wrap svg.default-logo {
display: block;
width: calc(100% + 1rem);
height: auto;
margin: -0.25rem auto 0.1rem;
max-width: 320px;
}
.logo-wrap[data-loading] .default-logo {
visibility: hidden;
}
.logo-wrap img.custom-logo {
display: block;
max-width: 220px;
max-height: 96px;
width: auto;
height: auto;
object-fit: contain;
}
.default-logo .wordmark {
fill: var(--brand-ink)
}
h1 {
font-size: 1.125rem;
font-weight: 600;
letter-spacing: -.015em;
margin-bottom: .25rem
}
.sub {
font-size: .8125rem;
color: var(--muted);
margin-bottom: 1.75rem
}
.alert {
display: flex;
align-items: flex-start;
gap: .625rem;
padding: .625rem .75rem;
background: color-mix(in srgb, var(--danger, #dc2626) 10%, transparent);
border: 1px solid color-mix(in srgb, var(--danger, #dc2626) 30%, transparent);
border-radius: 8px;
font-size: .8125rem;
color: var(--danger, #b91c1c);
margin-bottom: .875rem;
}
.alert.success {
background: color-mix(in srgb, #0f7a3c 10%, transparent);
border-color: color-mix(in srgb, #0f7a3c 30%, transparent);
color: #0f7a3c;
}
@media(prefers-color-scheme:dark) {
:root:not([data-theme="light"]) .alert {
color: #f4839a
}
:root:not([data-theme="light"]) .alert.success {
color: #58c98a;
}
}
:root[data-theme="dark"] .alert {
color: #f4839a
}
:root[data-theme="dark"] .alert.success {
color: #58c98a;
}
.alert svg {
flex-shrink: 0;
margin-top: 1px
}
.fields {
display: flex;
flex-direction: column;
gap: .875rem
}
.field label {
font-size: .75rem;
font-weight: 500;
color: var(--muted);
letter-spacing: .03em;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: .3125rem;
}
input[type=text],
input[type=password],
input[type=email] {
width: 100%;
padding: .5625rem .75rem;
font-size: .9375rem;
font-family: inherit;
background: var(--input-bg);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
outline: none;
transition: border-color .15s;
-webkit-appearance: none;
}
input[type=text]:focus,
input[type=password]:focus,
input[type=email]:focus {
border-color: color-mix(in srgb, var(--info) 60%, transparent);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--info) 12%, transparent);
}
input[type=text]::placeholder,
input[type=password]::placeholder,
input[type=email]::placeholder {
color: var(--muted);
opacity: .7
}
#otp {
letter-spacing: .2em;
font-size: 1.0625rem;
text-align: center;
font-variant-numeric: tabular-nums
}
#device-code {
letter-spacing: .15em;
font-size: 1.0625rem;
text-align: center;
text-transform: uppercase;
font-variant-numeric: tabular-nums;
}
.btn {
width: 100%;
margin-top: .375rem;
padding: .625rem 0;
font-size: .9375rem;
font-weight: 500;
font-family: inherit;
background: var(--accent);
color: var(--accent-fg);
border: none;
border-radius: 8px;
cursor: pointer;
letter-spacing: -.01em;
transition: opacity .15s;
}
.btn:hover {
opacity: .88
}
.btn:active {
opacity: .75;
transform: scale(.99)
}
.btn[disabled] {
opacity: .55;
cursor: not-allowed;
transform: none;
}
[hidden] {
display: none !important;
}
</style>
</head>
<body>
<div class="card">
<div class="logo-wrap" id="logo-wrap" data-loading>
<svg class="default-logo" xmlns="http://www.w3.org/2000/svg" viewBox="165 35 616 130" role="img" aria-label="inbuxa">
<g class="symbol" transform="translate(156.02,30.31) scale(1.0082)"><g stroke="#1C4053" stroke-linecap="round" stroke-linejoin="round"><g transform="translate(0 -12)"><path d="M18 58 L32 60 M19 67 L32 65 M110 58 L96 60 M109 67 L96 65" stroke-width="3" fill="none"/><g transform="translate(64 62) scale(0.9) translate(-64 -60)"><path d="M31 64 C30 50 31 38 34 27 Q36 20 42 23 L55 32 Q64 29.5 73 32 L86 23 Q92 20 94 27 C97 38 98 50 97 64 C96 83 82 92 64 92 C46 92 32 83 31 64 Z" fill="#F9A34C" stroke-width="5"/><path d="M38 30 L50 37.5 L40 45.5 Z M90 30 L78 37.5 L88 45.5 Z" fill="#F47F35" stroke="none"/><path d="M44 60 Q49.5 53 55 60 M73 60 Q78.5 53 84 60" stroke-width="4.2" fill="none"/><path d="M60.8 65.5 h6.4 l-3.2 3.6 z" fill="#1C4053" stroke-width="2"/><path d="M56 71.5 Q60 76.5 64 71.5 Q68 76.5 72 71.5" stroke-width="3.5" fill="none"/></g></g><rect x="12" y="73" width="104" height="51" rx="9" fill="#46CAC3" stroke-width="4.5"/><rect x="21" y="89" width="86" height="10" rx="2.5" fill="#1C4053" stroke="none"/><rect x="27" y="85.5" width="26" height="14" rx="2" fill="#FFFFFF" stroke-width="2.8"/><path d="M28.5 87 L40 93.5 L51.5 87" stroke-width="2.3" fill="none"/><circle cx="99" cy="94" r="2.5" fill="#9FF0E9" stroke="none"/><rect x="21" y="103" width="86" height="9" rx="2.5" fill="#1C4053" stroke="none"/><path d="M28 104.8 L31.8 107.5 L28 110.2 M34.8 110.2 H41" stroke="#9FF0E9" stroke-width="1.9" fill="none"/><circle cx="99" cy="107.5" r="2.5" fill="#9FF0E9" stroke="none"/><rect x="21" y="115.5" width="86" height="4.5" rx="2" fill="#2B8A86" stroke="none"/><circle cx="28" cy="117.75" r="1.6" fill="#F9A34C" stroke="none"/><circle cx="34" cy="117.75" r="1.6" fill="#9FF0E9" stroke="none"/><circle cx="40" cy="117.75" r="1.6" fill="#9FF0E9" stroke="none"/><g transform="translate(0 -12)"><path d="M36.5 90 C36 81 40 76.5 46 76.5 C52 76.5 56 81 55.5 90 C55.5 94 51 96 46 96 C41 96 36.5 94 36.5 90 Z" fill="#F9A34C" stroke-width="4"/><path d="M91.5 90 C92 81 88 76.5 82 76.5 C76 76.5 72 81 72.5 90 C72.5 94 77 96 82 96 C87 96 91.5 94 91.5 90 Z" fill="#F9A34C" stroke-width="4"/><path d="M43 88.5 V93 M49 88.5 V93 M79 88.5 V93 M85 88.5 V93" stroke-width="2.4" fill="none"/></g></g></g>
<g class="wordmark"><path d="M70 0V496H196V0ZM133 554Q99 554 75.5 576.0Q52 598 52 634Q52 670 75.5 692.0Q99 714 133 714Q168 714 191.0 692.0Q214 670 214 634Q214 598 191.0 576.0Q168 554 133 554Z" transform="translate(303.25,151.90) scale(0.150000,-0.150000)"/><path d="M70 0V496H194V431H212Q224 457 257.0 480.5Q290 504 357 504Q415 504 458.5 477.5Q502 451 526.0 404.5Q550 358 550 296V0H424V286Q424 342 396.5 370.0Q369 398 318 398Q260 398 228.0 359.5Q196 321 196 252V0Z" transform="translate(340.15,151.90) scale(0.150000,-0.150000)"/><path d="M368 -14Q301 -14 265.0 9.0Q229 32 212 60H194V0H70V700H196V439H214Q225 457 243.5 473.0Q262 489 292.5 499.5Q323 510 368 510Q428 510 479.0 480.5Q530 451 561.0 394.0Q592 337 592 256V240Q592 159 561.0 102.0Q530 45 479.0 15.5Q428 -14 368 -14ZM330 96Q388 96 427.0 133.5Q466 171 466 243V253Q466 325 427.5 362.5Q389 400 330 400Q272 400 233.0 362.5Q194 325 194 253V243Q194 171 233.0 133.5Q272 96 330 96Z" transform="translate(429.55,151.90) scale(0.150000,-0.150000)"/><path d="M259 -8Q201 -8 157.5 18.5Q114 45 90.0 92.0Q66 139 66 200V496H192V210Q192 154 219.5 126.0Q247 98 298 98Q356 98 388.0 136.5Q420 175 420 244V496H546V0H422V65H404Q392 40 359.0 16.0Q326 -8 259 -8Z" transform="translate(522.25,151.90) scale(0.150000,-0.150000)"/><path d="M26 0 206 250 28 496H174L287 331H305L418 496H564L386 250L566 0H418L305 167H287L174 0Z" transform="translate(611.65,151.90) scale(0.150000,-0.150000)"/><path d="M224 -14Q171 -14 129.0 4.5Q87 23 62.5 58.5Q38 94 38 145Q38 196 62.5 230.5Q87 265 130.5 282.5Q174 300 230 300H366V328Q366 363 344.0 385.5Q322 408 274 408Q227 408 204.0 386.5Q181 365 174 331L58 370Q70 408 96.5 439.5Q123 471 167.5 490.5Q212 510 276 510Q374 510 431.0 461.0Q488 412 488 319V134Q488 104 516 104H556V0H472Q435 0 411.0 18.0Q387 36 387 66V67H368Q364 55 350.0 35.5Q336 16 306.0 1.0Q276 -14 224 -14ZM246 88Q299 88 332.5 117.5Q366 147 366 196V206H239Q204 206 184.0 191.0Q164 176 164 149Q164 122 185.0 105.0Q206 88 246 88Z" transform="translate(697.45,151.90) scale(0.150000,-0.150000)"/></g>
</svg>
</div>
<h1 id="title">Add a passkey</h1>
<p class="sub" id="subtitle">Confirm it's you, then create the passkey on this device.</p>
<div class="alert" id="alert" hidden aria-live="polite">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10" />
<line x1="12" y1="8" x2="12" y2="12" />
<line x1="12" y1="16" x2="12.01" y2="16" />
</svg>
<span id="alert-msg"></span>
</div>
<form class="fields" id="passkey-form" novalidate>
<div class="field" id="field-account" hidden>
<label for="account">Account</label>
<input id="account" name="username" type="text" autocomplete="username" readonly>
</div>
<div class="field" id="field-password">
<label for="password">Password</label>
<input id="password" name="password" type="password" placeholder="••••••••"
autocomplete="current-password" required>
</div>
<div class="field" id="field-otp" hidden>
<label for="otp">One-time code</label>
<input id="otp" name="otp" type="text" placeholder="000000" maxlength="6" inputmode="numeric"
pattern="\d{6}" autocomplete="one-time-code">
</div>
<button type="submit" class="btn" id="submit-btn">Continue</button>
</form>
</div>
<script>
// INBUXA (#334): registers a passkey for the ticket in this page's URL
// (passkeys spec PK-6 to PK-8). The password (and code) comes first;
// then the browser's own dialog makes the passkey.
(function () {
'use strict';
var $ = function (id) { return document.getElementById(id); };
function setText(el, text) { el.textContent = text == null ? '' : String(text); }
function show(el) { if (el) el.hidden = false; }
function hide(el) { if (el) el.hidden = true; }
function showError(msg) {
var a = $('alert');
a.classList.remove('success');
setText($('alert-msg'), msg);
show(a);
}
function showSuccess(msg) {
var a = $('alert');
a.classList.add('success');
setText($('alert-msg'), msg);
show(a);
}
function clearAlert() { hide($('alert')); }
var params = new URL(window.location.href).searchParams;
var ticket = params.get('ticket') || '';
var loginHint = null;
(function loadCustomLogo() {
var wrap = $('logo-wrap');
function showDefault() { wrap.removeAttribute('data-loading'); }
var params = [];
if (loginHint) {
var at = loginHint.lastIndexOf('@');
if (at !== -1 && at < loginHint.length - 1) {
params.push('domain=' + encodeURIComponent(loginHint.slice(at + 1).toLowerCase()));
}
}
// The dark-mode logo when this page shows dark (branding BT-27)
var theme = document.documentElement.getAttribute('data-theme');
if (theme === 'dark' || (theme !== 'light' && window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches)) {
params.push('theme=dark');
}
var target = '/logo' + (params.length ? '?' + params.join('&') : '');
// An image element, not fetch: it can follow /logo's redirect to
// a URL logo on another origin (branding BT-26)
var img = new Image();
img.className = 'custom-logo';
img.alt = 'Logo';
img.onload = function () {
while (wrap.firstChild) wrap.removeChild(wrap.firstChild);
wrap.appendChild(img);
wrap.removeAttribute('data-loading');
};
img.onerror = showDefault;
img.src = target;
})();
function finished(title, subtitle) {
hide($('passkey-form'));
setText($('title'), title);
setText($('subtitle'), subtitle);
}
if (!ticket) {
finished('Add a passkey', 'This page is opened by your mail app when you add a passkey.');
showError('Start adding the passkey from your mail app\'s settings.');
return;
}
if (!window.PublicKeyCredential || !navigator.credentials || !navigator.credentials.create) {
finished('Add a passkey', 'This browser can\'t make passkeys.');
showError('Open this page in a browser that supports passkeys, or use another device.');
return;
}
// WebAuthn's binary fields travel as base64url text
function fromB64(s) {
s = s.replace(/-/g, '+').replace(/_/g, '/');
while (s.length % 4) s += '=';
var bin = atob(s), out = new Uint8Array(bin.length);
for (var i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out.buffer;
}
function toB64(buf) {
var bytes = new Uint8Array(buf), bin = '';
for (var i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function post(body) {
return fetch('/api/passkey/register', {
method: 'POST',
credentials: 'omit',
cache: 'no-store',
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify(body)
}).then(function (res) {
if (res.status !== 200) throw new Error('http ' + res.status);
return res.json();
});
}
function expired() {
finished('Add a passkey', 'This link has run out or was already used.');
showError('Start again from your mail app\'s settings.');
}
function create(json) {
var pk = json.options.publicKey;
pk.challenge = fromB64(pk.challenge);
pk.user.id = fromB64(pk.user.id);
(pk.excludeCredentials || []).forEach(function (c) { c.id = fromB64(c.id); });
setText($('subtitle'), 'Follow your browser\'s steps to create the passkey "' + json.name + '".');
return navigator.credentials.create({ publicKey: pk }).then(function (cred) {
var response = {
attestationObject: toB64(cred.response.attestationObject),
clientDataJSON: toB64(cred.response.clientDataJSON)
};
if (cred.response.getTransports) response.transports = cred.response.getTransports();
return post({
step: 'finish',
ticket: ticket,
credential: {
id: cred.id,
rawId: toB64(cred.rawId),
type: cred.type,
response: response,
extensions: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}
}
});
}, function (err) {
console.log('navigator.credentials.create failed:', err);
throw { cancelled: true, name: err && err.name };
});
}
function submit(e) {
if (e) e.preventDefault();
clearAlert();
var password = $('password').value;
if (!password) { showError('Enter your password.'); return; }
var otp = $('otp').value.trim();
var body = { step: 'start', ticket: ticket, password: password };
if (!$('field-otp').hidden) {
if (!/^\d{6}$/.test(otp)) { showError('Enter the 6-digit code.'); return; }
body.mfaToken = otp;
}
var btn = $('submit-btn');
btn.disabled = true;
post(body).then(function (json) {
switch (json.type) {
case 'options':
$('account').value = json.accountName;
return create(json).then(function (done) {
if (done.type === 'registered') {
finished('Passkey added', 'You can close this window.');
showSuccess('"' + done.name + '" is ready. Use it the next time you sign in.');
} else if (done.type === 'expired') {
expired();
} else {
finished('Add a passkey', 'The passkey wasn\'t added.');
showError(done.reason || 'Start again from your mail app\'s settings.');
}
});
case 'mfaRequired':
show($('field-otp'));
setText($('subtitle'), 'Enter the 6-digit code from your authenticator app.');
setTimeout(function () { $('otp').focus(); }, 0);
return;
case 'expired':
expired();
return;
default:
showError(!$('field-otp').hidden ? 'The password or code is wrong.' : 'The password is wrong.');
$('otp').value = '';
}
}).catch(function (err) {
if (err && err.cancelled) {
// Nothing was used up: Continue asks again
setText($('subtitle'), 'The passkey wasn\'t created.');
showError(err.name === 'InvalidStateError'
? 'This device already has a passkey for your account.'
: 'Choose Continue to try again.');
return;
}
console.log('Passkey registration failed:', err);
showError('Temporary server failure. If the problem persists, contact your administrator.');
}).then(function () { btn.disabled = false; });
}
$('passkey-form').addEventListener('submit', submit);
$('otp').addEventListener('input', function () { this.value = this.value.replace(/\D/g, ''); });
setTimeout(function () { $('password').focus(); }, 0);
})();
</script>
</body>
</html>
+481
View File
@@ -0,0 +1,481 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<meta name="referrer" content="no-referrer">
<script>
// INBUXA (#375): the app that opened this page can pass theme=light or
// theme=dark so the page matches it; anything else follows the OS.
(function () {
var t = new URLSearchParams(window.location.search).get('theme');
if (t === 'light' || t === 'dark') document.documentElement.setAttribute('data-theme', t);
})();
</script>
<title>Add a passkey · inbuxa</title>
<link rel="icon" type="image/png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAR4ElEQVRo3u1aeXSV1bXf+5xvuHNyczOQGCAhCQQSEQEBEX3ocqJWUVwq8Vmxdnhaq3ZZO9hnW95qV63Vqu/J66CV95xaZBAFRHEqYAUEBFFAQsIQyUBC5tzc77v3O+fs98d37+UifXAjWavteu+srKzcm+87Z//23mcPv3OQiOAfebC/tQD/D+BvLcDfAgARKaWGcfOcyYQ41NeUUowlYUulECD98QsMpRQB8IwJ+RBnG9rTShFjzLasg4cPRwcGOGOMMSm/iPKISErJGOOM9fX2Nhw4KByHM6bU0KYaggVc9Wz5cNcdCx9v6ooWhkOXTKm+q25u7fhxACCl4vy4Ok6eFhEzFe/a7eDhpidfWLnm/Y86+gbGl0Ye+e4dF06fnGnkYQNARIiYiMdn3PStjvbWWyb5P+2S7zTaXDfvnHfpg3fdFggEhJQMURExxliGuKkZQKrkAxrnAPDvz7zws8WvxCzrskpzTC5butvyB3M+WPLbcDjHXS4bwbQsgSqlOOdvvrdpZ2Pzf80L3jYlRjG2s8t8fJv+8Auvvbt913O/+EF1VWXaKUXC7u0fUEQAYOq63+fTDNOVmwF0d3ff+W+PLn37w2tqAz+dZUyKxJmXzi32LXi5542Nm+rmznGXG04Arpk+2NMQMuDCEiF7yBJyciE8/2VxzVj/PWv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DcmOh5UcYlHEvrKPWzJR07IQx/s2X9HFhRdVrSKEgJ1vfzSKas37lz+iTOlzPv4pc4on3hyG3urQfgNUXntReaoYmnHkfMUc5KWPCNJEAACKgKPUTlv9o7fLJv524THY8ws5Wf51c+2eJbvEo4UJdNrWusP2Jadgn7GAAhACafoyll5syYdfXPzri17r3xehULeATLKLigOnz8pNLFK2vEkX/X5V9NunCp6GJNWPHjOuNrvL+j64OPe+sPXr4yBcLqi8cIJI0dcOj189rjWHz7mcvGn2wLZAUAiApSWZRTljb71mqLZU5tXbzi2c1+opKD46ot9laVWRzfjLE0wEJzEzFFK/pRh5GAsWFPhH11iP/li95H2wJjSSbdfFJxYTRoTAzFIlqqnH9lZwO3RGVcJQY5tlhZVfrsuvHFH0/J1u366qOzGKwsvP1/EE+AI4IwydZZBraS+SwZuIzfU93HDgWdWxLv7Sq+eXXzVLOYxxaAFyDgiEYFSwwYgvTQwhpxLOwEI+bOn+itHNr2w5sCzrw40tY6aP0cLeMWghYylo8/JDkBSMtNgmtb2+l+aXnrdCOdUf+fWnEljRTQmohYwBIYgKeV5ZxxGU8vS8USaOn1w+qNmUd7Y+25tW/veZy+/HT1wpPzWq3NqK51BCxTBSYdkRASKtKA/cayn6YU1x7Z+UnDBuWU3f0kLhxJ9UcYYcnacxsianMsOADIAlhlcABA5l7YDDEquvcRfXvrZ8rf2P7mk+IrzR8yZxQwurThkpFBSinHO/Wbv9r2Hl7xOjhh7502RmeeQIhm1WIq5ydR2llV+lsycWxKklZo6tuAMFMmYFZ5akzuhQknx2Yq36x99Nt58zAgF3bqHFJBUms+DipqeW12/6I+Jrh7/yOL86WcToLQTqB0/zMNksZesODLXOjMARJnGTa9GUnKvCULt//WzzaveLLine truncated
<style>
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0
}
:root {
--bg: #f6f8fa;
--card: #ffffff;
--border: #e3e7ec;
--text: #111827;
--muted: #5b6472;
--accent: #0f766e;
--accent-fg: #ffffff;
--info: #0e7490;
--success: #15803d;
--radius: 10px;
--input-bg: #ffffff;
--brand-ink: #1C4053;
--danger: #b91c1c;
}
:root {
color-scheme: light dark;
}
:root[data-theme="light"] {
color-scheme: light;
}
@media(prefers-color-scheme:dark) {
:root:not([data-theme="light"]) {
--bg: #0b1220;
--card: #111a2b;
--border: #1f2a3d;
--text: #e5e9f0;
--muted: #9aa5b8;
--accent: #2dd4bf;
--accent-fg: #052e2b;
--info: #67e8f9;
--success: #4ade80;
--input-bg: #0d1524;
--brand-ink: #e5e9f0;
--danger: #f87171;
}
}
:root[data-theme="dark"] {
color-scheme: dark;
--bg: #0b1220;
--card: #111a2b;
--border: #1f2a3d;
--text: #e5e9f0;
--muted: #9aa5b8;
--accent: #2dd4bf;
--accent-fg: #052e2b;
--info: #67e8f9;
--success: #4ade80;
--input-bg: #0d1524;
--brand-ink: #e5e9f0;
--danger: #f87171;
}
body {
font-family: "Inter", system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif;
background: var(--bg);
color: var(--text);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 1rem;
}
.card {
background: var(--card);
border: 1px solid var(--border);
border-radius: var(--radius);
padding: 0.5rem 2.25rem 2rem;
width: 100%;
max-width: 384px;
}
.logo-wrap {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
min-height: 72px;
margin: 0.25rem auto 0.5rem;
}
.logo-wrap svg.default-logo {
display: block;
width: calc(100% + 1rem);
height: auto;
margin: -0.25rem auto 0.1rem;
max-width: 320px;
}
.logo-wrap[data-loading] .default-logo {
visibility: hidden;
}
.logo-wrap img.custom-logo {
display: block;
max-width: 220px;
max-height: 96px;
width: auto;
height: auto;
object-fit: contain;
}
.default-logo .wordmark {
fill: var(--brand-ink)
}
h1 {
font-size: 1.125rem;
font-weight: 600;
letter-spacing: -.015em;
margin-bottom: .25rem
}
.sub {
font-size: .8125rem;
color: var(--muted);
margin-bottom: 1.75rem
}
.alert {
display: flex;
align-items: flex-start;
gap: .625rem;
padding: .625rem .75rem;
background: color-mix(in srgb, var(--danger, #dc2626) 10%, transparent);
border: 1px solid color-mix(in srgb, var(--danger, #dc2626) 30%, transparent);
border-radius: 8px;
font-size: .8125rem;
color: var(--danger, #b91c1c);
margin-bottom: .875rem;
}
.alert.success {
background: color-mix(in srgb, #0f7a3c 10%, transparent);
border-color: color-mix(in srgb, #0f7a3c 30%, transparent);
color: #0f7a3c;
}
@media(prefers-color-scheme:dark) {
:root:not([data-theme="light"]) .alert {
color: #f4839a
}
:root:not([data-theme="light"]) .alert.success {
color: #58c98a;
}
}
:root[data-theme="dark"] .alert {
color: #f4839a
}
:root[data-theme="dark"] .alert.success {
color: #58c98a;
}
.alert svg {
flex-shrink: 0;
margin-top: 1px
}
.fields {
display: flex;
flex-direction: column;
gap: .875rem
}
.field label {
font-size: .75rem;
font-weight: 500;
color: var(--muted);
letter-spacing: .03em;
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: .3125rem;
}
input[type=text],
input[type=password],
input[type=email] {
width: 100%;
padding: .5625rem .75rem;
font-size: .9375rem;
font-family: inherit;
background: var(--input-bg);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
outline: none;
transition: border-color .15s;
-webkit-appearance: none;
}
input[type=text]:focus,
input[type=password]:focus,
input[type=email]:focus {
border-color: color-mix(in srgb, var(--info) 60%, transparent);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--info) 12%, transparent);
}
input[type=text]::placeholder,
input[type=password]::placeholder,
input[type=email]::placeholder {
color: var(--muted);
opacity: .7
}
#otp {
letter-spacing: .2em;
font-size: 1.0625rem;
text-align: center;
font-variant-numeric: tabular-nums
}
#device-code {
letter-spacing: .15em;
font-size: 1.0625rem;
text-align: center;
text-transform: uppercase;
font-variant-numeric: tabular-nums;
}
.btn {
width: 100%;
margin-top: .375rem;
padding: .625rem 0;
font-size: .9375rem;
font-weight: 500;
font-family: inherit;
background: var(--accent);
color: var(--accent-fg);
border: none;
border-radius: 8px;
cursor: pointer;
letter-spacing: -.01em;
transition: opacity .15s;
}
.btn:hover {
opacity: .88
}
.btn:active {
opacity: .75;
transform: scale(.99)
}
.btn[disabled] {
opacity: .55;
cursor: not-allowed;
transform: none;
}
[hidden] {
display: none !important;
}
</style>
</head>
<body>
<div class="card">
<div class="logo-wrap" id="logo-wrap" data-loading>
<svg class="default-logo" xmlns="http://www.w3.org/2000/svg" viewBox="165 35 616 130" role="img" aria-label="inbuxa">
<g class="symbol" transform="translate(156.02,30.31) scale(1.0082)"><g stroke="#1C4053" stroke-linecap="round" stroke-linejoin="round"><g transform="translate(0 -12)"><path d="M18 58 L32 60 M19 67 L32 65 M110 58 L96 60 M109 67 L96 65" stroke-width="3" fill="none"/><g transform="translate(64 62) scale(0.9) translate(-64 -60)"><path d="M31 64 C30 50 31 38 34 27 Q36 20 42 23 L55 32 Q64 29.5 73 32 L86 23 Q92 20 94 27 C97 38 98 50 97 64 C96 83 82 92 64 92 C46 92 32 83 31 64 Z" fill="#F9A34C" stroke-width="5"/><path d="M38 30 L50 37.5 L40 45.5 Z M90 30 L78 37.5 L88 45.5 Z" fill="#F47F35" stroke="none"/><path d="M44 60 Q49.5 53 55 60 M73 60 Q78.5 53 84 60" stroke-width="4.2" fill="none"/><path d="M60.8 65.5 h6.4 l-3.2 3.6 z" fill="#1C4053" stroke-width="2"/><path d="M56 71.5 Q60 76.5 64 71.5 Q68 76.5 72 71.5" stroke-width="3.5" fill="none"/></g></g><rect x="12" y="73" width="104" height="51" rx="9" fill="#46CAC3" stroke-width="4.5"/><rect x="21" y="89" width="86" height="10" rx="2.5" fill="#1C4053" stroke="none"/><rect x="27" y="85.5" width="26" height="14" rx="2" fill="#FFFFFF" stroke-width="2.8"/><path d="M28.5 87 L40 93.5 L51.5 87" stroke-width="2.3" fill="none"/><circle cx="99" cy="94" r="2.5" fill="#9FF0E9" stroke="none"/><rect x="21" y="103" width="86" height="9" rx="2.5" fill="#1C4053" stroke="none"/><path d="M28 104.8 L31.8 107.5 L28 110.2 M34.8 110.2 H41" stroke="#9FF0E9" stroke-width="1.9" fill="none"/><circle cx="99" cy="107.5" r="2.5" fill="#9FF0E9" stroke="none"/><rect x="21" y="115.5" width="86" height="4.5" rx="2" fill="#2B8A86" stroke="none"/><circle cx="28" cy="117.75" r="1.6" fill="#F9A34C" stroke="none"/><circle cx="34" cy="117.75" r="1.6" fill="#9FF0E9" stroke="none"/><circle cx="40" cy="117.75" r="1.6" fill="#9FF0E9" stroke="none"/><g transform="translate(0 -12)"><path d="M36.5 90 C36 81 40 76.5 46 76.5 C52 76.5 56 81 55.5 90 C55.5 94 51 96 46 96 C41 96 36.5 94 36.5 90 Z" fill="#F9A34C" stroke-width="4"/><path d="M91.5 90 C92 81 88 76.5 82 76.5 C76 76.5 72 81 72.5 90 C72.5 94 77 96 82 96 C87 96 91.5 94 91.5 90 Z" fill="#F9A34C" stroke-width="4"/><path d="M43 88.5 V93 M49 88.5 V93 M79 88.5 V93 M85 88.5 V93" stroke-width="2.4" fill="none"/></g></g></g>
<g class="wordmark"><path d="M70 0V496H196V0ZM133 554Q99 554 75.5 576.0Q52 598 52 634Q52 670 75.5 692.0Q99 714 133 714Q168 714 191.0 692.0Q214 670 214 634Q214 598 191.0 576.0Q168 554 133 554Z" transform="translate(303.25,151.90) scale(0.150000,-0.150000)"/><path d="M70 0V496H194V431H212Q224 457 257.0 480.5Q290 504 357 504Q415 504 458.5 477.5Q502 451 526.0 404.5Q550 358 550 296V0H424V286Q424 342 396.5 370.0Q369 398 318 398Q260 398 228.0 359.5Q196 321 196 252V0Z" transform="translate(340.15,151.90) scale(0.150000,-0.150000)"/><path d="M368 -14Q301 -14 265.0 9.0Q229 32 212 60H194V0H70V700H196V439H214Q225 457 243.5 473.0Q262 489 292.5 499.5Q323 510 368 510Q428 510 479.0 480.5Q530 451 561.0 394.0Q592 337 592 256V240Q592 159 561.0 102.0Q530 45 479.0 15.5Q428 -14 368 -14ZM330 96Q388 96 427.0 133.5Q466 171 466 243V253Q466 325 427.5 362.5Q389 400 330 400Q272 400 233.0 362.5Q194 325 194 253V243Q194 171 233.0 133.5Q272 96 330 96Z" transform="translate(429.55,151.90) scale(0.150000,-0.150000)"/><path d="M259 -8Q201 -8 157.5 18.5Q114 45 90.0 92.0Q66 139 66 200V496H192V210Q192 154 219.5 126.0Q247 98 298 98Q356 98 388.0 136.5Q420 175 420 244V496H546V0H422V65H404Q392 40 359.0 16.0Q326 -8 259 -8Z" transform="translate(522.25,151.90) scale(0.150000,-0.150000)"/><path d="M26 0 206 250 28 496H174L287 331H305L418 496H564L386 250L566 0H418L305 167H287L174 0Z" transform="translate(611.65,151.90) scale(0.150000,-0.150000)"/><path d="M224 -14Q171 -14 129.0 4.5Q87 23 62.5 58.5Q38 94 38 145Q38 196 62.5 230.5Q87 265 130.5 282.5Q174 300 230 300H366V328Q366 363 344.0 385.5Q322 408 274 408Q227 408 204.0 386.5Q181 365 174 331L58 370Q70 408 96.5 439.5Q123 471 167.5 490.5Q212 510 276 510Q374 510 431.0 461.0Q488 412 488 319V134Q488 104 516 104H556V0H472Q435 0 411.0 18.0Q387 36 387 66V67H368Q364 55 350.0 35.5Q336 16 306.0 1.0Q276 -14 224 -14ZM246 88Q299 88 332.5 117.5Q366 147 366 196V206H239Q204 206 184.0 191.0Q164 176 164 149Q164 122 185.0 105.0Q206 88 246 88Z" transform="translate(697.45,151.90) scale(0.150000,-0.150000)"/></g>
</svg>
</div>
<h1 id="title">Add a passkey</h1>
<p class="sub" id="subtitle">Confirm it's you, then create the passkey on this device.</p>
<div class="alert" id="alert" hidden aria-live="polite">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round">
<circle cx="12" cy="12" r="10" />
<line x1="12" y1="8" x2="12" y2="12" />
<line x1="12" y1="16" x2="12.01" y2="16" />
</svg>
<span id="alert-msg"></span>
</div>
<form class="fields" id="passkey-form" novalidate>
<div class="field" id="field-account" hidden>
<label for="account">Account</label>
<input id="account" name="username" type="text" autocomplete="username" readonly>
</div>
<div class="field" id="field-password">
<label for="password">Password</label>
<input id="password" name="password" type="password" placeholder="••••••••"
autocomplete="current-password" required>
</div>
<div class="field" id="field-otp" hidden>
<label for="otp">One-time code</label>
<input id="otp" name="otp" type="text" placeholder="000000" maxlength="6" inputmode="numeric"
pattern="\d{6}" autocomplete="one-time-code">
</div>
<button type="submit" class="btn" id="submit-btn">Continue</button>
</form>
</div>
<script>
// INBUXA (#334): registers a passkey for the ticket in this page's URL
// (passkeys spec PK-6 to PK-8). The password (and code) comes first;
// then the browser's own dialog makes the passkey.
(function () {
'use strict';
var $ = function (id) { return document.getElementById(id); };
function setText(el, text) { el.textContent = text == null ? '' : String(text); }
function show(el) { if (el) el.hidden = false; }
function hide(el) { if (el) el.hidden = true; }
function showError(msg) {
var a = $('alert');
a.classList.remove('success');
setText($('alert-msg'), msg);
show(a);
}
function showSuccess(msg) {
var a = $('alert');
a.classList.add('success');
setText($('alert-msg'), msg);
show(a);
}
function clearAlert() { hide($('alert')); }
var params = new URL(window.location.href).searchParams;
var ticket = params.get('ticket') || '';
var loginHint = null;
(function loadCustomLogo() {
var wrap = $('logo-wrap');
function showDefault() { wrap.removeAttribute('data-loading'); }
var params = [];
if (loginHint) {
var at = loginHint.lastIndexOf('@');
if (at !== -1 && at < loginHint.length - 1) {
params.push('domain=' + encodeURIComponent(loginHint.slice(at + 1).toLowerCase()));
}
}
// The dark-mode logo when this page shows dark (branding BT-27)
var theme = document.documentElement.getAttribute('data-theme');
if (theme === 'dark' || (theme !== 'light' && window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches)) {
params.push('theme=dark');
}
var target = '/logo' + (params.length ? '?' + params.join('&') : '');
// An image element, not fetch: it can follow /logo's redirect to
// a URL logo on another origin (branding BT-26)
var img = new Image();
img.className = 'custom-logo';
img.alt = 'Logo';
img.onload = function () {
while (wrap.firstChild) wrap.removeChild(wrap.firstChild);
wrap.appendChild(img);
wrap.removeAttribute('data-loading');
};
img.onerror = showDefault;
img.src = target;
})();
function finished(title, subtitle) {
hide($('passkey-form'));
setText($('title'), title);
setText($('subtitle'), subtitle);
}
if (!ticket) {
finished('Add a passkey', 'This page is opened by your mail app when you add a passkey.');
showError('Start adding the passkey from your mail app\'s settings.');
return;
}
if (!window.PublicKeyCredential || !navigator.credentials || !navigator.credentials.create) {
finished('Add a passkey', 'This browser can\'t make passkeys.');
showError('Open this page in a browser that supports passkeys, or use another device.');
return;
}
// WebAuthn's binary fields travel as base64url text
function fromB64(s) {
s = s.replace(/-/g, '+').replace(/_/g, '/');
while (s.length % 4) s += '=';
var bin = atob(s), out = new Uint8Array(bin.length);
for (var i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
return out.buffer;
}
function toB64(buf) {
var bytes = new Uint8Array(buf), bin = '';
for (var i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]);
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}
function post(body) {
return fetch('/api/passkey/register', {
method: 'POST',
credentials: 'omit',
cache: 'no-store',
headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
body: JSON.stringify(body)
}).then(function (res) {
if (res.status !== 200) throw new Error('http ' + res.status);
return res.json();
});
}
function expired() {
finished('Add a passkey', 'This link has run out or was already used.');
showError('Start again from your mail app\'s settings.');
}
function create(json) {
var pk = json.options.publicKey;
pk.challenge = fromB64(pk.challenge);
pk.user.id = fromB64(pk.user.id);
(pk.excludeCredentials || []).forEach(function (c) { c.id = fromB64(c.id); });
setText($('subtitle'), 'Follow your browser\'s steps to create the passkey "' + json.name + '".');
return navigator.credentials.create({ publicKey: pk }).then(function (cred) {
var response = {
attestationObject: toB64(cred.response.attestationObject),
clientDataJSON: toB64(cred.response.clientDataJSON)
};
if (cred.response.getTransports) response.transports = cred.response.getTransports();
return post({
step: 'finish',
ticket: ticket,
credential: {
id: cred.id,
rawId: toB64(cred.rawId),
type: cred.type,
response: response,
extensions: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}
}
});
}, function (err) {
console.log('navigator.credentials.create failed:', err);
throw { cancelled: true, name: err && err.name };
});
}
function submit(e) {
if (e) e.preventDefault();
clearAlert();
var password = $('password').value;
if (!password) { showError('Enter your password.'); return; }
var otp = $('otp').value.trim();
var body = { step: 'start', ticket: ticket, password: password };
if (!$('field-otp').hidden) {
if (!/^\d{6}$/.test(otp)) { showError('Enter the 6-digit code.'); return; }
body.mfaToken = otp;
}
var btn = $('submit-btn');
btn.disabled = true;
post(body).then(function (json) {
switch (json.type) {
case 'options':
$('account').value = json.accountName;
return create(json).then(function (done) {
if (done.type === 'registered') {
finished('Passkey added', 'You can close this window.');
showSuccess('"' + done.name + '" is ready. Use it the next time you sign in.');
} else if (done.type === 'expired') {
expired();
} else {
finished('Add a passkey', 'The passkey wasn\'t added.');
showError(done.reason || 'Start again from your mail app\'s settings.');
}
});
case 'mfaRequired':
show($('field-otp'));
setText($('subtitle'), 'Enter the 6-digit code from your authenticator app.');
setTimeout(function () { $('otp').focus(); }, 0);
return;
case 'expired':
expired();
return;
default:
showError(!$('field-otp').hidden ? 'The password or code is wrong.' : 'The password is wrong.');
$('otp').value = '';
}
}).catch(function (err) {
if (err && err.cancelled) {
// Nothing was used up: Continue asks again
setText($('subtitle'), 'The passkey wasn\'t created.');
showError(err.name === 'InvalidStateError'
? 'This device already has a passkey for your account.'
: 'Choose Continue to try again.');
return;
}
console.log('Passkey registration failed:', err);
showError('Temporary server failure. If the problem persists, contact your administrator.');
}).then(function () { btn.disabled = false; });
}
$('passkey-form').addEventListener('submit', submit);
$('otp').addEventListener('input', function () { this.value = this.value.replace(/\D/g, ''); });
setTimeout(function () { $('password').focus(); }, 0);
})();
</script>
</body>
</html>
Binary file not shown.
+1
View File
@@ -87,6 +87,7 @@ dns-update = { version = "0.6", features = ["test_provider"] }
x509-parser = "0.18"
rcgen = "0.14"
sha2 = "0.11"
ring = "0.17" # inbuxa: a software authenticator for the passkey tests
zip = "8.6" # inbuxa: reading legal hold exports
time = "0.3"
testcontainers = { version = "0.28", features = ["reusable-containers"] }
+272 -3
View File
@@ -4,15 +4,27 @@
* SPDX-License-Identifier: AGPL-3.0-only
*/
//! `inbuxa:Passkey` management (passkeys spec, PK-5, PK-14 to PK-17):
//! starting a registration, the limit per account, renaming, removing, who
//! reaches whose passkeys, and the audit log.
//! Passkeys (passkeys spec): `inbuxa:Passkey` management (PK-5, PK-14 to
//! PK-17): starting a registration, the limit per account, renaming,
//! removing, who reaches whose passkeys, and the audit log. Registration on
//! the server's page (PK-6 to PK-8), with a software authenticator.
use crate::utils::{
account::Account,
http::HttpRequest,
server::{TestServer, TestServerBuilder},
};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD};
use ring::{
rand::SystemRandom,
signature::{ECDSA_P256_SHA256_ASN1_SIGNING, EcdsaKeyPair, KeyPair},
};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
/// The page's origin: the test server's public URL.
const ORIGIN: &str = "https://localhost:8899";
const RP_ID: &str = "localhost";
const USING: &[&str] = &[
"urn:ietf:params:jmap:core",
@@ -231,6 +243,262 @@ pub async fn test(test: &mut TestServer) {
.any(|e| e["action"] == "destroy" && e["target"]["name"] == "Work phone"),
"no removal recorded by name: {response}"
);
registration(&user).await;
}
/// A software authenticator: one P-256 key, user verification always done.
pub struct SoftKey {
pub key: EcdsaKeyPair,
pub credential_id: Vec<u8>,
}
impl SoftKey {
pub fn new(credential_id: &[u8]) -> Self {
let rng = SystemRandom::new();
let pkcs8 = EcdsaKeyPair::generate_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, &rng).unwrap();
SoftKey {
key: EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8.as_ref(), &rng)
.unwrap(),
credential_id: credential_id.to_vec(),
}
}
/// What `navigator.credentials.create` hands the page, for `options`.
pub fn create(&self, options: &Value) -> Value {
let challenge = options["publicKey"]["challenge"].as_str().unwrap();
let client_data = json!({
"type": "webauthn.create",
"challenge": challenge,
"origin": ORIGIN,
"crossOrigin": false
})
.to_string();
// COSE EC2 key: kty 2, alg -7 (ES256), crv 1 (P-256), x, y
let point = self.key.public_key().as_ref();
let mut cose = Vec::new();
cbor_head(&mut cose, 5, 5);
cbor_int(&mut cose, 1);
cbor_int(&mut cose, 2);
cbor_int(&mut cose, 3);
cbor_int(&mut cose, -7);
cbor_int(&mut cose, -1);
cbor_int(&mut cose, 1);
cbor_int(&mut cose, -2);
cbor_bytes(&mut cose, &point[1..33]);
cbor_int(&mut cose, -3);
cbor_bytes(&mut cose, &point[33..65]);
let mut auth_data = Sha256::digest(RP_ID.as_bytes()).to_vec();
// UP, UV, backup eligible, backed up, attested credential data
auth_data.push(0x01 | 0x04 | 0x08 | 0x10 | 0x40);
auth_data.extend_from_slice(&0u32.to_be_bytes());
auth_data.extend_from_slice(&[0u8; 16]);
auth_data.extend_from_slice(&(self.credential_id.len() as u16).to_be_bytes());
auth_data.extend_from_slice(&self.credential_id);
auth_data.extend_from_slice(&cose);
// Attestation `none` (PK-1)
let mut attestation = Vec::new();
cbor_head(&mut attestation, 5, 3);
cbor_text(&mut attestation, "fmt");
cbor_text(&mut attestation, "none");
cbor_text(&mut attestation, "attStmt");
cbor_head(&mut attestation, 5, 0);
cbor_text(&mut attestation, "authData");
cbor_bytes(&mut attestation, &auth_data);
let id = URL_SAFE_NO_PAD.encode(&self.credential_id);
json!({
"id": id,
"rawId": id,
"type": "public-key",
"response": {
"attestationObject": URL_SAFE_NO_PAD.encode(&attestation),
"clientDataJSON": URL_SAFE_NO_PAD.encode(client_data.as_bytes()),
"transports": ["internal"]
},
"extensions": {}
})
}
}
fn cbor_head(out: &mut Vec<u8>, major: u8, len: u64) {
let major = major << 5;
match len {
0..=23 => out.push(major | len as u8),
24..=0xff => out.extend_from_slice(&[major | 24, len as u8]),
0x100..=0xffff => {
out.push(major | 25);
out.extend_from_slice(&(len as u16).to_be_bytes());
}
_ => {
out.push(major | 26);
out.extend_from_slice(&(len as u32).to_be_bytes());
}
}
}
fn cbor_int(out: &mut Vec<u8>, n: i64) {
if n >= 0 {
cbor_head(out, 0, n as u64);
} else {
cbor_head(out, 1, (-1 - n) as u64);
}
}
fn cbor_bytes(out: &mut Vec<u8>, bytes: &[u8]) {
cbor_head(out, 2, bytes.len() as u64);
out.extend_from_slice(bytes);
}
fn cbor_text(out: &mut Vec<u8>, text: &str) {
cbor_head(out, 3, text.len() as u64);
out.extend_from_slice(text.as_bytes());
}
async fn register(body: Value) -> Value {
HttpRequest::new()
.post::<Value>("/api/passkey/register", &body)
.await
.unwrap_or_else(|err| panic!("{body}: {err}"))
}
/// Starts a registration through JMAP and returns its id and ticket.
async fn start_registration(user: &Account, name: &str) -> (String, String) {
let (_, response) = call(
user,
"inbuxa:Passkey/set",
json!({"create": {"k": {"name": name}}}),
)
.await;
let created = &response["created"]["k"];
let url = created["registrationUrl"]
.as_str()
.unwrap_or_else(|| panic!("{response}"));
assert!(url.starts_with(ORIGIN), "{url}");
(
created["id"].as_str().unwrap().to_string(),
url.split_once("ticket=").unwrap().1.to_string(),
)
}
/// PK-6 to PK-8: the registration page's two steps.
async fn registration(user: &Account) {
let (laptop_id, ticket) = start_registration(user, "Laptop").await;
// The server serves the page itself
let page = reqwest::Client::builder()
.danger_accept_invalid_certs(true)
.build()
.unwrap()
.get(format!(
"https://127.0.0.1:8899/passkey/register?ticket={ticket}"
))
.send()
.await
.unwrap();
assert_eq!(page.status(), 200);
assert!(page.text().await.unwrap().contains("/api/passkey/register"));
// PK-8: nothing without the password
let response = register(json!({
"step": "start", "ticket": ticket, "password": "wrong-password"
}))
.await;
assert_eq!(response["type"], "failure", "{response}");
let key = SoftKey::new(b"soft-key-laptop-0001");
let response = register(json!({
"step": "finish", "ticket": ticket, "credential": key.create(&json!({
"publicKey": {"challenge": URL_SAFE_NO_PAD.encode(b"made-up")}
}))
}))
.await;
assert_eq!(response["type"], "expired", "{response}");
let response = register(json!({
"step": "start", "ticket": "not-a-ticket", "password": "passkey-secret-5521"
}))
.await;
assert_eq!(response["type"], "expired", "{response}");
// PK-1: discoverable, user verification, attestation none
let response = register(json!({
"step": "start", "ticket": ticket, "password": "passkey-secret-5521"
}))
.await;
assert_eq!(response["type"], "options", "{response}");
assert_eq!(response["name"], "Laptop");
assert_eq!(response["accountName"], "[email protected]");
let options = &response["options"];
let selection = &options["publicKey"]["authenticatorSelection"];
assert_eq!(selection["residentKey"], "required", "{options}");
assert_eq!(selection["userVerification"], "required", "{options}");
assert_eq!(options["publicKey"]["rp"]["id"], RP_ID, "{options}");
assert_eq!(options["publicKey"]["attestation"], "none", "{options}");
// A wrong origin is refused, and the step is used up
let mut forged = key.create(options);
forged["response"]["clientDataJSON"] = URL_SAFE_NO_PAD
.encode(
json!({
"type": "webauthn.create",
"challenge": options["publicKey"]["challenge"],
"origin": "https://evil.example",
"crossOrigin": false
})
.to_string(),
)
.into();
let response =
register(json!({"step": "finish", "ticket": ticket, "credential": forged})).await;
assert_eq!(response["type"], "refused", "{response}");
assert_eq!(list(user, user).await[0]["state"], "pending");
// PK-7: done, the passkey is active
let response = register(json!({
"step": "start", "ticket": ticket, "password": "passkey-secret-5521"
}))
.await;
let response = register(json!({
"step": "finish", "ticket": ticket, "credential": key.create(&response["options"])
}))
.await;
assert_eq!(response["type"], "registered", "{response}");
assert_eq!(response["name"], "Laptop");
let mine = list(user, user).await;
let laptop = mine.iter().find(|p| p["id"] == laptop_id.as_str()).unwrap();
assert_eq!(laptop["state"], "active", "{laptop}");
assert_eq!(laptop["usable"], true, "{laptop}");
assert_eq!(laptop["rpId"], RP_ID, "{laptop}");
assert_eq!(laptop["backedUp"], true, "{laptop}");
assert_eq!(laptop["transports"], json!(["internal"]), "{laptop}");
// The ticket is good once
let response = register(json!({
"step": "start", "ticket": ticket, "password": "passkey-secret-5521"
}))
.await;
assert_eq!(response["type"], "expired", "{response}");
// PK-7: a credential id already registered is refused; the browser is
// told which ones the account has
let (_, ticket) = start_registration(user, "Again").await;
let response = register(json!({
"step": "start", "ticket": ticket, "password": "passkey-secret-5521"
}))
.await;
let excluded = &response["options"]["publicKey"]["excludeCredentials"];
assert_eq!(
excluded[0]["id"],
URL_SAFE_NO_PAD.encode(b"soft-key-laptop-0001"),
"{response}"
);
let response = register(json!({
"step": "finish", "ticket": ticket, "credential": key.create(&response["options"])
}))
.await;
assert_eq!(response["type"], "refused", "{response}");
}
#[ignore]
@@ -238,6 +506,7 @@ pub async fn test(test: &mut TestServer) {
pub async fn passkey_tests() {
let mut test = TestServerBuilder::new("passkey_tests")
.await
.with_public_host("localhost")
.with_default_listeners()
.await
.build()
+13 -4
View File
@@ -94,6 +94,8 @@ pub struct TestServerBuilder {
capture_queue: bool,
capture_reporting: bool,
disable_services: bool,
// inbuxa: the host in the public URL; WebAuthn wants a name, not an IP
public_host: &'static str,
}
impl TestServerBuilder {
@@ -138,6 +140,7 @@ impl TestServerBuilder {
capture_queue: false,
capture_reporting: false,
disable_services: false,
public_host: "127.0.0.1",
}
}
@@ -259,6 +262,12 @@ impl TestServerBuilder {
self
}
// inbuxa: passkeys need a host name in the public URL
pub fn with_public_host(mut self, host: &'static str) -> Self {
self.public_host = host;
self
}
pub async fn insert_object(&self, object: impl Into<Object>) -> Id {
self.bootstrap
.registry
@@ -331,10 +340,10 @@ impl TestServerBuilder {
servers.bind_and_drop_priv(&mut self.bootstrap);
// Set HTTP port
self.bootstrap.registry = self
.bootstrap
.registry
.clone_with_public_url(format!("https://127.0.0.1:{}", self.http_listener_port));
self.bootstrap.registry = self.bootstrap.registry.clone_with_public_url(format!(
"https://{}:{}",
self.public_host, self.http_listener_port
));
if init_store {
// Add safe defaults if missing