mirror of
https://github.com/we-promise/sure.git
synced 2026-09-02 21:31:07 +00:00
* feat(auth): sign in with a passkey, without a password Passkeys could only ever replace the TOTP code: registration required 2FA to already be on, and the WebAuthn ceremony was reachable only after User.authenticate_by had succeeded. A registered passkey can now complete sign-in on its own, from the login page. The ceremony requests userVerification: "required", so the authenticator has to confirm the person as well as the device. That makes a lone passkey two independent factors, the same bar as the password plus TOTP flow it replaces, which is why this path deliberately skips the TOTP step. A credential that can only prove presence is rejected here and still works as a second factor. Sign-in is usernameless: no email is submitted, because the browser returns the account handle with the assertion. Nothing on this path can be probed to learn whether an account exists. Registration now asks for a discoverable credential with residentKey: "preferred" so the key is offered by the picker, while authenticators without a free resident-key slot still register as a second factor. Where conditional mediation is available, saved passkeys appear in the email field's autofill menu; everywhere else the button covers it. The automatic challenge request that conditional mediation makes on every page load gets its own looser Rack::Attack budget, so ordinary page views can no longer exhaust the limit that protects the MFA endpoints. Set AUTH_PASSKEY_LOGIN_ENABLED=false to keep passkeys as a second factor only. Passkey sign-in follows the same policy as local login, so it stays closed to regular users when AUTH_LOCAL_LOGIN_ENABLED is false. * refactor(auth): group the passkey button with the other sign-in methods It sat directly under the password fields, so the forgot-password link split it from the identical SSO buttons. It is an alternative to the credential form rather than part of it. * fix(auth): close the passkey challenge races and document the upgrade Three review passes converged on the conditional-mediation flow. The AbortController was created after `isConditionalMediationAvailable()` resolved, so a button click or a Turbo disconnect landing in that window found nothing to abort: the conditional task carried on, re-minted the challenge, and the assertion the user was about to produce verified against a challenge the server had already replaced. It is created before the first await now, and held in a local, because `abortConditionalMediation()` nulls the field. Checking that one signal after each await covers both triggers, so no separate connected flag is needed. The same symptom had a second cause nobody flagged: `authenticate()` was not re-entrant. A double-click minted a fresh challenge under an open authenticator prompt and rejected a perfectly valid passkey, with no race window at all — and it was live on the MFA step-up too, which shares the method. The conditional catch was silent for every failure, including a rejected assertion the user had deliberately chosen from the autofill menu. Splitting the try draws the line where it belongs: silence before the user has been asked anything, feedback once they have picked a passkey. Filtering on `error.name` cannot draw it, since `fetchOptions` and `verifyCredential` both raise a plain Error. Also documents the upgrade: passwordless is on by default and applies to already-registered credentials, so a passkey added purely as a second factor can now sign its owner in alone. Nothing in the schema marks a credential discoverable — the authenticator decides — and the opt-out is instance-wide. The invitation test is a guard, not coverage for this change. The pending token lives in the Rack session and `complete_sign_in` reads it right after creating the session, so a `reset_session` dropped in between strands the invitee in their own family, silently and with every existing test still green. * fix(auth): cancel the in-flight conditional options request Aborting the conditional flow did not cancel its options request, because `fetchOptions` never received the signal. A click landing while that POST was in flight left it to finish, and its response could apply last. The challenge rides in the session cookie, so "the server wrote it" only counts if the Set-Cookie reaches the browser. Threading the signal means an aborted request's response is discarded, which closes the window without needing the server to hold two challenges open. Also drops the absolute claim about which existing credentials gain passwordless sign-in. `residentKey: "preferred"` is a request an authenticator may decline, and nothing records what it decided, so the honest statement is that password managers and platform authenticators generally store discoverable credentials rather than always.
138 lines
4.3 KiB
JavaScript
138 lines
4.3 KiB
JavaScript
import WebauthnController from "controllers/webauthn_controller";
|
|
import {
|
|
prepareCredentialRequestOptions,
|
|
serializePublicKeyCredential,
|
|
} from "utils/webauthn";
|
|
|
|
export default class extends WebauthnController {
|
|
static targets = ["error"];
|
|
static values = {
|
|
optionsUrl: String,
|
|
verifyUrl: String,
|
|
unsupportedMessage: String,
|
|
errorFallback: String,
|
|
// Opt in to browser autofill ("conditional mediation"): passkeys are
|
|
// offered from the username field instead of behind a button click. Only
|
|
// passwordless sign-in enables this; the MFA step-up does not.
|
|
conditional: Boolean,
|
|
};
|
|
|
|
connect() {
|
|
if (this.conditionalValue) this.#startConditionalMediation();
|
|
}
|
|
|
|
disconnect() {
|
|
this.abortConditionalMediation();
|
|
}
|
|
|
|
async authenticate(event) {
|
|
event.preventDefault();
|
|
this.clearError();
|
|
|
|
if (!window.PublicKeyCredential) {
|
|
this.showError(this.unsupportedMessageValue);
|
|
return;
|
|
}
|
|
|
|
// A second click would mint a fresh challenge while the first
|
|
// authenticator prompt is still open, so the assertion the user is about
|
|
// to produce would verify against a challenge the server has replaced.
|
|
if (this.authenticating) return;
|
|
this.authenticating = true;
|
|
|
|
// A pending conditional request holds the challenge minted on connect.
|
|
// Fetching options below replaces it server-side, so the stale request has
|
|
// to go first or its assertion would verify against a challenge that no
|
|
// longer exists.
|
|
this.abortConditionalMediation();
|
|
|
|
try {
|
|
const options = await this.fetchOptions();
|
|
const credential = await navigator.credentials.get({
|
|
publicKey: prepareCredentialRequestOptions(options),
|
|
});
|
|
|
|
await this.verifyCredential(serializePublicKeyCredential(credential));
|
|
} catch (error) {
|
|
this.showError(error.message);
|
|
} finally {
|
|
this.authenticating = false;
|
|
}
|
|
}
|
|
|
|
async #startConditionalMediation() {
|
|
// Created before the first await so a button click or a Turbo disconnect
|
|
// in the meantime has something to abort. Held in a local because
|
|
// abortConditionalMediation() nulls the field.
|
|
const controller = new AbortController();
|
|
this.abortController = controller;
|
|
|
|
const available =
|
|
await window.PublicKeyCredential?.isConditionalMediationAvailable?.();
|
|
if (!available || controller.signal.aborted) return;
|
|
|
|
let credential;
|
|
|
|
try {
|
|
const options = await this.fetchOptions(controller.signal);
|
|
if (controller.signal.aborted) return;
|
|
|
|
credential = await navigator.credentials.get({
|
|
publicKey: prepareCredentialRequestOptions(options),
|
|
mediation: "conditional",
|
|
signal: controller.signal,
|
|
});
|
|
} catch (_error) {
|
|
// Nothing has been asked of the user yet: aborted, dismissed, or the
|
|
// background options request failed. Surfacing that would paint an error
|
|
// on a login page nobody has touched.
|
|
return;
|
|
}
|
|
|
|
if (controller.signal.aborted || !credential) return;
|
|
|
|
try {
|
|
await this.verifyCredential(serializePublicKeyCredential(credential));
|
|
} catch (error) {
|
|
// The user did pick a passkey from the autofill menu, so a rejection
|
|
// here has to be visible.
|
|
this.showError(error.message);
|
|
}
|
|
}
|
|
|
|
abortConditionalMediation() {
|
|
this.abortController?.abort();
|
|
this.abortController = null;
|
|
}
|
|
|
|
// Takes a signal so the conditional flow's request can be cancelled. The
|
|
// challenge rides in the session cookie, so a response whose Set-Cookie never
|
|
// lands cannot overwrite the challenge a manual click just minted.
|
|
async fetchOptions(signal) {
|
|
const response = await fetch(this.optionsUrlValue, {
|
|
method: "POST",
|
|
headers: this.headers,
|
|
credentials: "same-origin",
|
|
signal,
|
|
});
|
|
|
|
if (!response.ok) throw new Error(await this.errorMessage(response));
|
|
|
|
return response.json();
|
|
}
|
|
|
|
async verifyCredential(credential) {
|
|
const response = await fetch(this.verifyUrlValue, {
|
|
method: "POST",
|
|
headers: this.headers,
|
|
credentials: "same-origin",
|
|
body: JSON.stringify({ credential }),
|
|
});
|
|
|
|
if (!response.ok) throw new Error(await this.errorMessage(response));
|
|
|
|
const result = await response.json();
|
|
window.location.href = result.redirect_url;
|
|
}
|
|
}
|