001/*
002 * Copyright 2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.revetsec.webauthn;
018
019import com.google.errorprone.annotations.CheckReturnValue;
020import com.revetsec.ConfigurationDiagnostic;
021import com.revetsec.OperationBinding;
022import com.revetsec.StateSealer;
023import com.revetsec.internal.encoding.Base64Url;
024import com.revetsec.internal.encoding.EncodingException;
025import com.revetsec.internal.webauthn.WebAuthnEngine;
026import com.revetsec.json.JsonArray;
027import com.revetsec.json.JsonNumber;
028import com.revetsec.json.JsonObject;
029import org.jspecify.annotations.NonNull;
030import org.jspecify.annotations.Nullable;
031
032import javax.annotation.concurrent.NotThreadSafe;
033import javax.annotation.concurrent.ThreadSafe;
034import java.net.URI;
035import java.security.MessageDigest;
036import java.time.Clock;
037import java.util.ArrayList;
038import java.util.Arrays;
039import java.util.List;
040import java.util.Set;
041
042import static java.util.Objects.requireNonNull;
043
044/**
045 * Immutable WebAuthn relying party for discoverable, user-verified passkeys and security keys.
046 * The app owns account approval, sessions, CSRF, durable storage, and the external recovery
047 * barrier. Only confirmed, admitted store transitions can produce a browser request or proof.
048 * Construction performs no application callback or storage I/O.
049 * The current browser profile requires exactly {@code credProps: {rk: true}} client-extension
050 * output during registration and an empty client-extension object during authentication.
051 * Additional outputs reject; submit the browser's unmodified JSON rather than stripping fields.
052 * Browser/provider compatibility and origin support require the documented profile checks.
053 *
054 * @since 1.0.0
055 */
056@ThreadSafe
057public final class WebAuthnRelyingParty {
058    private static final @NonNull WebAuthnSettings DEFAULT_SETTINGS = WebAuthnSettings.builder().build();
059
060    private final @NonNull String relyingPartyId;
061    private final @NonNull String relyingPartyName;
062    private final @NonNull String credentialNamespace;
063    private final @NonNull WebAuthnSettings settings;
064    private final @NonNull WebAuthnEngine engine;
065
066    private WebAuthnRelyingParty(@NonNull Builder builder) {
067        this.relyingPartyId = builder.relyingPartyId;
068        this.relyingPartyName = requireNonNull(builder.relyingPartyName, "relyingPartyName");
069        this.credentialNamespace = requireNonNull(builder.credentialNamespace, "credentialNamespace");
070        this.settings = builder.settings == null ? DEFAULT_SETTINGS : builder.settings;
071        Set<String> origins = requireNonNull(builder.allowedOrigins, "allowedOrigins");
072        this.engine = new WebAuthnEngine(this.credentialNamespace, this.relyingPartyId,
073                origins, requireNonNull(builder.store, "store"),
074                requireNonNull(builder.stateSealer, "stateSealer"),
075                requireNonNull(builder.recoveryGate, "recoveryGate"), builder.clock,
076                this.settings);
077    }
078
079    /** Starts trusted RP configuration. The ID must be canonical lower-case DNS with at least
080     * two labels. The application must select a registrable domain it controls.
081     * @param relyingPartyId trusted RP ID
082     * @return builder
083     * @since 1.0.0 */
084    @CheckReturnValue public static @NonNull Builder withRelyingPartyId(@NonNull String relyingPartyId) {
085        WebAuthnStoreKey.forNamespaceClock("main", requireNonNull(relyingPartyId));
086        return new Builder(relyingPartyId);
087    }
088
089    /** Creates and commits account-approved enrollment options in an expiring ceremony.
090     * An absent account fence remains absent until the first credential completion atomically
091     * establishes its active fence and index. An existing disabled fence remains disabled.
092     * @param options approved account display data and handle
093     * @param browserBinding application-held random browser-session binding
094     * @return a committed browser request or fixed failure
095     * @since 1.0.0 */
096    @CheckReturnValue public @NonNull WebAuthnRegistrationRequestResult beginRegistrationResult(
097            @NonNull WebAuthnRegistrationOptions options, @NonNull OperationBinding browserBinding) {
098        return beginRegistrationResult(options, requireNonNull(browserBinding).toSecretString());
099    }
100    @CheckReturnValue @NonNull WebAuthnRegistrationRequestResult beginRegistrationResult(
101            @NonNull WebAuthnRegistrationOptions options, @NonNull String browserBinding) {
102        requireNonNull(options);
103        byte[] binding = parseBinding(browserBinding);
104        WebAuthnEngine.Start start = this.engine.beginRegistration(options.getUserHandle(), binding);
105        return switch (start.status()) {
106            case PREPARED -> WebAuthnRegistrationRequestResult.prepared(
107                    registrationRequest(requireNonNull(start.request()), options));
108            case REJECTED -> WebAuthnRegistrationRequestResult.rejected();
109            case UNAVAILABLE -> WebAuthnRegistrationRequestResult.unavailable();
110            case INDETERMINATE -> WebAuthnRegistrationRequestResult.indeterminate();
111            case RECONCILIATION_REQUIRED -> WebAuthnRegistrationRequestResult.reconciliationRequired();
112            case SUCCEEDED, COUNTER_RISK -> throw new IllegalStateException("Invalid begin outcome");
113        };
114    }
115
116    /** Creates and commits discoverable sign-in options, without an allowCredentials list.
117     * @param browserBinding application-held random browser-session binding
118     * @return a committed browser request or fixed failure
119     * @since 1.0.0 */
120    @CheckReturnValue public @NonNull WebAuthnAuthenticationRequestResult beginAuthenticationResult(
121            @NonNull OperationBinding browserBinding) {
122        return beginAuthenticationResult(requireNonNull(browserBinding).toSecretString());
123    }
124    @CheckReturnValue @NonNull WebAuthnAuthenticationRequestResult beginAuthenticationResult(
125            @NonNull String browserBinding) {
126        WebAuthnEngine.Start start = this.engine.beginAuthentication(parseBinding(browserBinding));
127        return authenticationRequestResult(start);
128    }
129
130    /** Creates account-pinned reauthentication options for a specific sensitive action.
131     * @param expectedUserHandle app-approved account handle
132     * @param actionPurpose bounded application action label
133     * @param browserBinding application-held random browser-session binding
134     * @return a committed browser request or fixed failure
135     * @since 1.0.0 */
136    @CheckReturnValue public @NonNull WebAuthnAuthenticationRequestResult beginReauthenticationResult(
137            byte @NonNull [] expectedUserHandle, @NonNull String actionPurpose,
138            @NonNull OperationBinding browserBinding) {
139        return beginReauthenticationResult(expectedUserHandle, actionPurpose,
140                requireNonNull(browserBinding).toSecretString());
141    }
142    @CheckReturnValue @NonNull WebAuthnAuthenticationRequestResult beginReauthenticationResult(
143            byte @NonNull [] expectedUserHandle, @NonNull String actionPurpose,
144            @NonNull String browserBinding) {
145        WebAuthnStoreKey.forAccountFence(this.credentialNamespace, this.relyingPartyId,
146                requireNonNull(expectedUserHandle));
147        validateActionPurpose(actionPurpose);
148        byte[] binding = parseBinding(browserBinding);
149        return authenticationRequestResult(this.engine.beginReauthentication(
150                expectedUserHandle.clone(), actionPurpose, binding));
151    }
152
153    /** Consumes a raw browser registration response under its single-use ceremony.
154     * @param ceremonyId opaque request handle
155     * @param responseBody browser {@code PublicKeyCredential.toJSON()} bytes
156     * @param browserBinding application-held browser-session binding
157     * @return verified registration only after a confirmed admitted write
158     * @since 1.0.0 */
159    @CheckReturnValue public @NonNull WebAuthnRegistrationResult completeRegistrationResult(
160            @NonNull String ceremonyId, byte @NonNull [] responseBody,
161            @NonNull OperationBinding browserBinding) {
162        return completeRegistrationResult(ceremonyId, responseBody,
163                requireNonNull(browserBinding).toSecretString());
164    }
165    @CheckReturnValue @NonNull WebAuthnRegistrationResult completeRegistrationResult(
166            @NonNull String ceremonyId, byte @NonNull [] responseBody,
167            @NonNull String browserBinding) {
168        requireNonNull(ceremonyId);
169        requireNonNull(responseBody);
170        byte[] binding = parseBinding(browserBinding);
171        byte[] id = parseCeremonyId(ceremonyId);
172        if (id == null || responseBody.length == 0
173                || responseBody.length > this.settings.getMaximumResponseBodyBytes())
174            return WebAuthnRegistrationResult.rejected(WebAuthnRejectionReason.REJECTED);
175        WebAuthnEngine.Finish finished = this.engine.completeRegistration(id, binding, responseBody);
176        return switch (finished.status()) {
177            case SUCCEEDED -> {
178                WebAuthnEngine.Verified verified = requireNonNull(finished.verified());
179                if (verified.kind() != WebAuthnEngine.Kind.REGISTRATION)
180                    throw new IllegalStateException("Invalid registration fact");
181                yield WebAuthnRegistrationResult.succeeded(new WebAuthnRegistration(
182                        this.credentialNamespace, this.relyingPartyId,
183                        verified.userHandle(), verified.credentialId(), requireNonNull(verified.aaguid()),
184                        verified.backupEligible(), verified.backedUp(),
185                        verified.userVerifiedAtRegistration()));
186            }
187            case REJECTED, COUNTER_RISK -> WebAuthnRegistrationResult.rejected(WebAuthnRejectionReason.REJECTED);
188            case UNAVAILABLE -> WebAuthnRegistrationResult.unavailable();
189            case INDETERMINATE -> WebAuthnRegistrationResult.indeterminate();
190            case RECONCILIATION_REQUIRED -> WebAuthnRegistrationResult.reconciliationRequired();
191            case PREPARED -> throw new IllegalStateException("Invalid completion outcome");
192        };
193    }
194
195    /** Consumes a raw browser sign-in or account-pinned reauthentication response. Applications
196     * using this general result for a sensitive action must check the proof's kind, account
197     * handle and action purpose. The checked reauthentication completion method
198     * enforces those checks before returning a successful result.
199     * @param ceremonyId opaque request handle
200     * @param responseBody browser {@code PublicKeyCredential.toJSON()} bytes
201     * @param browserBinding application-held browser-session binding
202     * @return verified authentication only after a confirmed admitted write
203     * @since 1.0.0 */
204    @CheckReturnValue public @NonNull WebAuthnAuthenticationResult completeAuthenticationResult(
205            @NonNull String ceremonyId, byte @NonNull [] responseBody,
206            @NonNull OperationBinding browserBinding) {
207        return completeAuthenticationResult(ceremonyId, responseBody,
208                requireNonNull(browserBinding).toSecretString());
209    }
210    @CheckReturnValue @NonNull WebAuthnAuthenticationResult completeAuthenticationResult(
211            @NonNull String ceremonyId, byte @NonNull [] responseBody,
212            @NonNull String browserBinding) {
213        requireNonNull(ceremonyId);
214        requireNonNull(responseBody);
215        byte[] binding = parseBinding(browserBinding);
216        byte[] id = parseCeremonyId(ceremonyId);
217        if (id == null || responseBody.length == 0
218                || responseBody.length > this.settings.getMaximumResponseBodyBytes())
219            return WebAuthnAuthenticationResult.rejected(WebAuthnRejectionReason.REJECTED);
220        WebAuthnEngine.Finish finished = this.engine.completeAuthentication(id, binding, responseBody);
221        return switch (finished.status()) {
222            case SUCCEEDED -> {
223                WebAuthnEngine.Verified verified = requireNonNull(finished.verified());
224                WebAuthnAuthentication.Kind kind = switch (verified.kind()) {
225                    case AUTHENTICATION -> WebAuthnAuthentication.Kind.SIGN_IN;
226                    case REAUTHENTICATION -> WebAuthnAuthentication.Kind.REAUTHENTICATION;
227                    case REGISTRATION -> throw new IllegalStateException("Invalid authentication fact");
228                };
229                yield WebAuthnAuthenticationResult.succeeded(new WebAuthnAuthentication(
230                        this.credentialNamespace, this.relyingPartyId, verified.userHandle(),
231                        verified.credentialId(), verified.backupEligible(), verified.backedUp(),
232                        kind, verified.purpose()));
233            }
234            case REJECTED -> WebAuthnAuthenticationResult.rejected(WebAuthnRejectionReason.REJECTED);
235            case COUNTER_RISK -> WebAuthnAuthenticationResult.rejected(WebAuthnRejectionReason.COUNTER_RISK);
236            case UNAVAILABLE -> WebAuthnAuthenticationResult.unavailable();
237            case INDETERMINATE -> WebAuthnAuthenticationResult.indeterminate();
238            case RECONCILIATION_REQUIRED -> WebAuthnAuthenticationResult.reconciliationRequired();
239            case PREPARED -> throw new IllegalStateException("Invalid completion outcome");
240        };
241    }
242
243    /** Completes a sensitive action only for the expected account and action purpose. A
244     * discoverable sign-in ceremony, or a reauthentication for another account or purpose,
245     * cannot return a successful result here. The application still authorizes the current
246     * browser session and consumes its own one-use action before applying the operation.
247     * The exact completed ceremony ID is included in the restricted proof so the application
248     * can match its original pending action. A rejected checked context may follow a known
249     * committed ceremony consumption; it does not imply that completion had no effects.
250     * @param expectedUserHandle app-approved current account handle
251     * @param actionPurpose app-approved action label used when beginning reauthentication
252     * @param ceremonyId opaque request handle
253     * @param responseBody browser {@code PublicKeyCredential.toJSON()} bytes
254     * @param browserBinding application-held browser-session binding
255     * @return a matching restricted reauthentication proof or fixed failure
256     * @since 1.0.0 */
257    @CheckReturnValue public @NonNull WebAuthnReauthenticationResult completeReauthenticationResult(
258            byte @NonNull [] expectedUserHandle, @NonNull String actionPurpose,
259            @NonNull String ceremonyId, byte @NonNull [] responseBody,
260            @NonNull OperationBinding browserBinding) {
261        return completeReauthenticationResult(expectedUserHandle, actionPurpose, ceremonyId, responseBody,
262                requireNonNull(browserBinding).toSecretString());
263    }
264    @CheckReturnValue @NonNull WebAuthnReauthenticationResult completeReauthenticationResult(
265            byte @NonNull [] expectedUserHandle, @NonNull String actionPurpose,
266            @NonNull String ceremonyId, byte @NonNull [] responseBody,
267            @NonNull String browserBinding) {
268        WebAuthnStoreKey.forAccountFence(this.credentialNamespace, this.relyingPartyId,
269                requireNonNull(expectedUserHandle));
270        byte[] expectedHandle = expectedUserHandle.clone();
271        try {
272            validateActionPurpose(actionPurpose);
273            WebAuthnAuthenticationResult result = completeAuthenticationResult(ceremonyId, responseBody, browserBinding);
274            if (result instanceof WebAuthnAuthenticationResult.Succeeded succeeded) {
275                WebAuthnAuthentication proof = succeeded.getAuthentication();
276                if (proof.getKind() != WebAuthnAuthentication.Kind.REAUTHENTICATION
277                        || !MessageDigest.isEqual(proof.getUserHandle(), expectedHandle)
278                        || !proof.getActionPurpose().filter(actionPurpose::equals).isPresent())
279                    return WebAuthnReauthenticationResult.rejected(WebAuthnRejectionReason.REJECTED);
280                return WebAuthnReauthenticationResult.succeeded(new WebAuthnReauthentication(
281                        this.credentialNamespace, this.relyingPartyId, proof.getUserHandle(),
282                        proof.getCredentialId(), proof.isBackupEligible().booleanValue(),
283                        proof.isBackedUp().booleanValue(), actionPurpose, ceremonyId));
284            }
285            if (result instanceof WebAuthnAuthenticationResult.Rejected rejected)
286                return WebAuthnReauthenticationResult.rejected(rejected.getReason());
287            if (result instanceof WebAuthnAuthenticationResult.Unavailable)
288                return WebAuthnReauthenticationResult.unavailable();
289            if (result instanceof WebAuthnAuthenticationResult.Indeterminate)
290                return WebAuthnReauthenticationResult.indeterminate();
291            if (result instanceof WebAuthnAuthenticationResult.ReconciliationRequired)
292                return WebAuthnReauthenticationResult.reconciliationRequired();
293            throw new IllegalStateException("Invalid checked reauthentication outcome");
294        } finally {
295            Arrays.fill(expectedHandle, (byte) 0);
296        }
297    }
298
299    /** Lists active credential IDs for an app-approved account. The application must authorize
300     * the current session and enforce CSRF and management policy before calling this method.
301     * A listed ID is not an authentication proof.
302     * @param approvedUserHandle app-approved account handle
303     * @return authoritative listing or unavailable
304     * @since 1.0.0 */
305    @CheckReturnValue public @NonNull WebAuthnCredentialListResult listCredentialsResult(
306            byte @NonNull [] approvedUserHandle) {
307        WebAuthnEngine.Management result = this.engine.listCredentials(requireNonNull(approvedUserHandle).clone());
308        return switch (result.status()) {
309            case LISTED -> WebAuthnCredentialListResult.listed(result.credentialIds());
310            case UNAVAILABLE -> WebAuthnCredentialListResult.unavailable();
311            case REMOVED, ABSENT, DISABLED, INDETERMINATE, RECONCILIATION_REQUIRED ->
312                    throw new IllegalStateException("Invalid listing outcome");
313        };
314    }
315
316    /** Permanently revokes a credential ID belonging to an app-approved account. The application
317     * must authorize the current session and enforce CSRF and management policy. An uncertain
318     * write requires authoritative reconciliation before another management action.
319     * @param approvedUserHandle app-approved account handle
320     * @param credentialId credential ID to revoke
321     * @return confirmed removal, absence or fixed failure
322     * @since 1.0.0 */
323    @CheckReturnValue public @NonNull WebAuthnCredentialRemovalResult removeCredentialResult(
324            byte @NonNull [] approvedUserHandle, byte @NonNull [] credentialId) {
325        WebAuthnEngine.Management result = this.engine.removeCredential(
326                requireNonNull(approvedUserHandle).clone(), requireNonNull(credentialId).clone());
327        return switch (result.status()) {
328            case REMOVED -> WebAuthnCredentialRemovalResult.removed();
329            case ABSENT -> WebAuthnCredentialRemovalResult.absent();
330            case UNAVAILABLE -> WebAuthnCredentialRemovalResult.unavailable();
331            case INDETERMINATE -> WebAuthnCredentialRemovalResult.indeterminate();
332            case RECONCILIATION_REQUIRED -> WebAuthnCredentialRemovalResult.reconciliationRequired();
333            case LISTED, DISABLED -> throw new IllegalStateException("Invalid removal outcome");
334        };
335    }
336
337    /** Permanently disables the passkey fence for an app-approved namespace/RP/account handle,
338     * including completions of pending ceremonies. There is no account-enable transition in
339     * this API. Reopening {@link WebAuthnRecoveryGate} traffic admission, rebuilding the relying
340     * party, repeating disable, or resealing records does not reenable the account.
341     * The app must authorize this action, coordinate its own account state and existing sessions,
342     * and reconcile uncertain effects. Disable retains credentials and ownership tombstones;
343     * authorized listing, removal and permanent-record reseal remain available under admission.
344     * A discoverable authentication begin has no account identity to reject; completion still
345     * enforces the disabled fence. This operation does not terminate app sessions or revoke a
346     * verification fact already returned to the application.
347     * @param approvedUserHandle app-approved account handle
348     * @return confirmed disabled state or fixed failure
349     * @since 1.0.0 */
350    @CheckReturnValue public @NonNull WebAuthnAccountDisableResult disableAccountResult(
351            byte @NonNull [] approvedUserHandle) {
352        WebAuthnEngine.Management result = this.engine.disableAccount(requireNonNull(approvedUserHandle).clone());
353        return switch (result.status()) {
354            case DISABLED -> WebAuthnAccountDisableResult.disabled();
355            case UNAVAILABLE -> WebAuthnAccountDisableResult.unavailable();
356            case INDETERMINATE -> WebAuthnAccountDisableResult.indeterminate();
357            case RECONCILIATION_REQUIRED -> WebAuthnAccountDisableResult.reconciliationRequired();
358            case LISTED, REMOVED, ABSENT -> throw new IllegalStateException("Invalid disable outcome");
359        };
360    }
361
362    /** Reseals one permanent, namespace-bound record with the current active sealing key.
363     * Use {@link WebAuthnStoreKey#fromStoredForm(String)} with a trusted complete persistence
364     * inventory to address revoked-credential tombstones as well as active records. The active
365     * account credential list alone is not a complete key-rotation inventory.
366     * The application must coordinate key rotation, retain the old key until every permanent
367     * row has been resealed, and close admission during restore or uncertain outcomes. Ceremony
368     * rows are short lived and are not eligible. Absence returns CONFLICT; an uncertain commit
369     * returns UNKNOWN and requires authoritative reconciliation before proceeding. Healthy admitted
370     * time is required before the timed attempt. This effect-only acknowledgement preserves a known
371     * COMMITTED receipt after deadline, optional-completion or permit-close failure; it releases no
372     * verification proof and performs no post-commit service-admission read.
373     * @param key privileged credential, index, account-fence or namespace-clock address
374     * @return the factual contextual compare-and-commit receipt
375     * @since 1.0.0 */
376    @CheckReturnValue public @NonNull WebAuthnStoreCommitReceipt resealStoreEntry(
377            @NonNull WebAuthnStoreKey key) {
378        return this.engine.resealStoreEntry(requireNonNull(key));
379    }
380
381    private @NonNull WebAuthnAuthenticationRequestResult authenticationRequestResult(
382            WebAuthnEngine.@NonNull Start start) {
383        return switch (start.status()) {
384            case PREPARED -> WebAuthnAuthenticationRequestResult.prepared(
385                    authenticationRequest(requireNonNull(start.request())));
386            case REJECTED -> WebAuthnAuthenticationRequestResult.rejected();
387            case UNAVAILABLE -> WebAuthnAuthenticationRequestResult.unavailable();
388            case INDETERMINATE -> WebAuthnAuthenticationRequestResult.indeterminate();
389            case RECONCILIATION_REQUIRED -> WebAuthnAuthenticationRequestResult.reconciliationRequired();
390            case SUCCEEDED, COUNTER_RISK -> throw new IllegalStateException("Invalid begin outcome");
391        };
392    }
393
394    private @NonNull WebAuthnBrowserRequest registrationRequest(WebAuthnEngine.@NonNull Request request,
395            @NonNull WebAuthnRegistrationOptions options) {
396        JsonObject rp = JsonObject.builder().put("id", this.relyingPartyId)
397                .put("name", this.relyingPartyName).build();
398        JsonObject user = JsonObject.builder().put("id", Base64Url.encode(options.getUserHandle()))
399                .put("name", options.getUserName()).put("displayName", options.getUserDisplayName()).build();
400        JsonArray parameters = JsonArray.fromElements(List.of(
401                algorithm(-7), algorithm(-8), algorithm(-257)));
402        List<JsonObject> exclusions = new ArrayList<>();
403        for (byte[] id : request.excludedIds()) exclusions.add(JsonObject.builder()
404                .put("type", "public-key").put("id", Base64Url.encode(id)).build());
405        JsonObject selection = JsonObject.builder().put("residentKey", "required")
406                .put("requireResidentKey", true).put("userVerification", "required").build();
407        JsonObject publicKey = JsonObject.builder().put("rp", rp).put("user", user)
408                .put("challenge", Base64Url.encode(request.challenge()))
409                .put("pubKeyCredParams", parameters)
410                .put("timeout", Long.valueOf(this.settings.getCeremonyLifetime().toMillis()))
411                .put("excludeCredentials", JsonArray.fromElements(exclusions))
412                .put("authenticatorSelection", selection)
413                .put("attestation", "none")
414                .put("extensions", JsonObject.builder().put("credProps", true).build())
415                .build();
416        return new WebAuthnBrowserRequest(Base64Url.encode(request.ceremonyId()), publicKey);
417    }
418
419    private @NonNull WebAuthnBrowserRequest authenticationRequest(WebAuthnEngine.@NonNull Request request) {
420        JsonObject publicKey = JsonObject.builder()
421                .put("challenge", Base64Url.encode(request.challenge()))
422                .put("rpId", this.relyingPartyId)
423                .put("timeout", Long.valueOf(this.settings.getCeremonyLifetime().toMillis()))
424                .put("userVerification", "required").build();
425        return new WebAuthnBrowserRequest(Base64Url.encode(request.ceremonyId()), publicKey);
426    }
427
428    private static @NonNull JsonObject algorithm(int identifier) {
429        return JsonObject.builder().put("type", "public-key")
430                .put("alg", JsonNumber.fromValue(Long.valueOf(identifier))).build();
431    }
432
433    private static byte @NonNull [] parseBinding(@NonNull String binding) {
434        requireNonNull(binding);
435        if (binding.length() != 43) throw new IllegalArgumentException("Invalid browser binding");
436        try {
437            byte[] decoded = Base64Url.decode(binding);
438            if (decoded.length != 32) throw new IllegalArgumentException("Invalid browser binding");
439            return decoded;
440        } catch (EncodingException failure) {
441            throw new IllegalArgumentException("Invalid browser binding");
442        }
443    }
444
445    private static byte @Nullable [] parseCeremonyId(@NonNull String value) {
446        if (value.length() != 43) return null;
447        try {
448            byte[] decoded = Base64Url.decode(value);
449            return decoded.length == 32 ? decoded : null;
450        } catch (EncodingException failure) {
451            return null;
452        }
453    }
454
455    private static void validateActionPurpose(@NonNull String actionPurpose) {
456        requireNonNull(actionPurpose);
457        if (actionPurpose.isEmpty() || actionPurpose.length() > 128)
458            throw new IllegalArgumentException("Invalid WebAuthn action purpose");
459        for (int i = 0; i < actionPurpose.length(); i++)
460            if (actionPurpose.charAt(i) < 0x20 || actionPurpose.charAt(i) > 0x7e)
461                throw new IllegalArgumentException("Invalid WebAuthn action purpose");
462    }
463
464    /** Redacts configuration and protocol state.
465     * @return a fixed description
466     * @since 1.0.0 */
467    @Override public @NonNull String toString() { return "WebAuthnRelyingParty{<redacted>}"; }
468
469    /** One caller-thread trusted configuration builder.
470     * @since 1.0.0 */
471    @NotThreadSafe @CheckReturnValue
472    public static final class Builder {
473        private final @NonNull String relyingPartyId;
474        private @Nullable String relyingPartyName;
475        private @Nullable Set<@NonNull String> allowedOrigins;
476        private @Nullable String credentialNamespace;
477        private @Nullable WebAuthnStore store;
478        private @Nullable StateSealer stateSealer;
479        private @Nullable WebAuthnRecoveryGate recoveryGate;
480        private @Nullable WebAuthnSettings settings;
481        private @NonNull Clock clock = Clock.systemUTC();
482        private Builder(@NonNull String relyingPartyId) { this.relyingPartyId = relyingPartyId; }
483
484        /** Sets a bounded RP display name.
485         * @param name RP name, or null to clear the required name
486         * @return this builder
487         * @since 1.0.0 */
488        public @NonNull Builder relyingPartyName(@Nullable String name) {
489            this.relyingPartyName = name == null ? null : displayName(name); return this;
490        }
491        /** Sets exact trusted HTTPS origins on the configured RP ID or its dot-delimited
492         * canonical subdomains. Eligibility is not a wildcard allowlist: each origin and port
493         * must be explicitly configured and is snapshotted into prepared ceremonies.
494         * Use canonical lowercase DNS names; omit the default HTTPS port.
495         * @param origins one to eight canonical origins, or null to clear the required set
496         * @return this builder
497         * @since 1.0.0 */
498        public @NonNull Builder allowedOrigins(@Nullable Set<@NonNull String> origins) {
499            if (origins == null) {
500                this.allowedOrigins = null;
501                return this;
502            }
503            if (origins.isEmpty() || origins.size() > 8)
504                throw new IllegalArgumentException("Invalid WebAuthn origin count");
505            Set<String> copy = Set.copyOf(origins);
506            for (String origin : copy) validOrigin(origin, this.relyingPartyId);
507            this.allowedOrigins = copy; return this;
508        }
509        /** Sets the app-controlled credential namespace.
510         * @param namespace namespace, or null to clear the required namespace
511         * @return this builder
512         * @since 1.0.0 */
513        public @NonNull Builder credentialNamespace(@Nullable String namespace) {
514            if (namespace != null)
515                WebAuthnStoreKey.forNamespaceClock(namespace, this.relyingPartyId);
516            this.credentialNamespace = namespace; return this;
517        }
518        /** Selects the app-owned authoritative store.
519         * @param store store, or null to clear the required store
520         * @return this builder
521         * @since 1.0.0 */
522        public @NonNull Builder store(@Nullable WebAuthnStore store) {
523            this.store = store; return this;
524        }
525        /** Selects the app-provisioned record sealer.
526         * @param sealer sealer, or null to clear the required sealer
527         * @return this builder
528         * @since 1.0.0 */
529        public @NonNull Builder stateSealer(@Nullable StateSealer sealer) {
530            this.stateSealer = sealer; return this;
531        }
532        /** Selects the app-owned durable restore admission barrier.
533         * @param gate gate, or null to clear the required gate
534         * @return this builder
535         * @since 1.0.0 */
536        public @NonNull Builder recoveryGate(@Nullable WebAuthnRecoveryGate gate) {
537            this.recoveryGate = gate; return this;
538        }
539        /** Selects bounded WebAuthn settings. Null restores the selected defaults.
540         * @param settings settings or null for defaults
541         * @return this builder
542         * @since 1.0.0 */
543        public @NonNull Builder settings(@Nullable WebAuthnSettings settings) {
544            this.settings = settings; return this;
545        }
546        @NonNull Builder clockForTesting(@NonNull Clock clock) {
547            this.clock = requireNonNull(clock); return this;
548        }
549        /** Inspects only the current configuration shape. The immutable, ordered result contains
550         * fixed codes and no supplied values; it does not call application dependencies.
551         * @return every missing required setting, or an empty list
552         * @since 1.0.0 */
553        @CheckReturnValue public @NonNull List<@NonNull ConfigurationDiagnostic> configurationDiagnostics() {
554            List<ConfigurationDiagnostic> issues = new ArrayList<>(6);
555            if (this.relyingPartyName == null) issues.add(ConfigurationDiagnostic.WEBAUTHN_RELYING_PARTY_NAME_REQUIRED);
556            if (this.credentialNamespace == null) issues.add(ConfigurationDiagnostic.WEBAUTHN_CREDENTIAL_NAMESPACE_REQUIRED);
557            if (this.allowedOrigins == null) issues.add(ConfigurationDiagnostic.WEBAUTHN_ALLOWED_ORIGINS_REQUIRED);
558            if (this.store == null) issues.add(ConfigurationDiagnostic.WEBAUTHN_STORE_REQUIRED);
559            if (this.stateSealer == null) issues.add(ConfigurationDiagnostic.WEBAUTHN_STATE_SEALER_REQUIRED);
560            if (this.recoveryGate == null) issues.add(ConfigurationDiagnostic.WEBAUTHN_RECOVERY_GATE_REQUIRED);
561            return List.copyOf(issues);
562        }
563        /** Builds the immutable RP without performing a store or gate callback.
564         * @return configured relying party
565         * @since 1.0.0 */
566        @CheckReturnValue public @NonNull WebAuthnRelyingParty build() {
567            List<ConfigurationDiagnostic> issues = configurationDiagnostics();
568            if (!issues.isEmpty()) throw new NullPointerException(issues.get(0).getFieldCode());
569            return new WebAuthnRelyingParty(this);
570        }
571        /** Redacts configuration.
572         * @return a fixed description
573         * @since 1.0.0 */
574        @Override public @NonNull String toString() { return "WebAuthnRelyingParty.Builder{<redacted>}"; }
575    }
576
577    private static @NonNull String displayName(@NonNull String name) {
578        requireNonNull(name);
579        com.revetsec.json.JsonString.fromValue(name);
580        if (name.isEmpty() || name.codePointCount(0, name.length()) > 64)
581            throw new IllegalArgumentException("Invalid WebAuthn RP name");
582        for (int offset = 0; offset < name.length();) {
583            int point = name.codePointAt(offset);
584            if (Character.isISOControl(point)) throw new IllegalArgumentException("Invalid WebAuthn RP name");
585            offset += Character.charCount(point);
586        }
587        return name;
588    }
589
590    private static void validOrigin(@NonNull String value, @NonNull String relyingPartyId) {
591        requireNonNull(value);
592        if (value.length() > 267) throw new IllegalArgumentException("Invalid WebAuthn origin");
593        URI uri;
594        try { uri = URI.create(value); }
595        catch (IllegalArgumentException failure) { throw new IllegalArgumentException("Invalid WebAuthn origin"); }
596        int port = uri.getPort();
597        String host = uri.getHost();
598        if (host == null) throw new IllegalArgumentException("Invalid WebAuthn origin");
599        // Reuse the same bounded canonical DNS validation as the configured RP ID.
600        WebAuthnStoreKey.forNamespaceClock("origin", host);
601        String expected = "https://" + host + (port == -1 ? "" : ":" + port);
602        if (!"https".equals(uri.getScheme())
603                || !(relyingPartyId.equals(host) || host.endsWith("." + relyingPartyId))
604                || uri.getRawUserInfo() != null || uri.getRawQuery() != null
605                || uri.getRawFragment() != null || port == 0 || port == 443 || port > 65_535
606                || (uri.getRawPath() != null && !uri.getRawPath().isEmpty())
607                || !value.equals(expected))
608            throw new IllegalArgumentException("Invalid WebAuthn origin");
609    }
610}