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.totp;
018
019import com.google.errorprone.annotations.CheckReturnValue;
020import com.revetsec.ConfigurationDiagnostic;
021import com.revetsec.OperationBinding;
022import com.revetsec.StateSealer;
023import com.revetsec.internal.encoding.StrictUtf8;
024import org.jspecify.annotations.NonNull;
025import org.jspecify.annotations.Nullable;
026import javax.annotation.concurrent.ThreadSafe;
027import javax.annotation.concurrent.NotThreadSafe;
028import java.time.Clock;
029import java.time.Duration;
030import java.util.ArrayList;
031import java.util.List;
032import java.util.Objects;
033
034/**
035 * Standalone TOTP enrollment, once-only verification and recovery codes. Applications own account
036 * authorization, primary authentication, sessions, CSRF, network admission, durable storage and
037 * recovery administration. TOTP is not phishing resistant. Configuration is immutable and building
038 * performs no storage, gate, cryptographic-provider or network work.
039 * <p>
040 * The fixed profile is HMAC-SHA1, six digits and 30-second Unix-epoch steps, accepting the previous,
041 * current or next step exactly once. Five failed or unsettled attempts per account in five minutes
042 * are shared by confirmation, TOTP and recovery codes. Six-digit confirmation and verification
043 * also share a durable limit of ten failed or unsettled attempts per rolling 24 hours. Recovery
044 * codes have 128 bits of entropy and remain subject to the five-minute shared limit, so they can
045 * provide fallback after that cooldown. Malformed submitted codes of at most 128 characters count
046 * as attempts; longer inputs are rejected before recovery admission or storage access. A successful
047 * attempt removes only its own reservations; earlier failed or unsettled attempts remain charged
048 * until their respective windows expire.
049 * A confirmed factor has ten random 128-bit recovery codes from separate draws. Pending enrollment
050 * lasts five minutes; starting replacement leaves the old factor active until confirmation commits.
051 * <p>
052 * Only confirmed, timely, recovery-admitted operations release proofs or secrets. Unknown writes
053 * are never retried automatically. An indeterminate verification cannot be reconciled into a login;
054 * require a fresh code. Status can reconcile management generations but never reveals secret material.
055 * Instances are safe to share across threads with thread-safe application dependencies.
056 * @since 1.0.0
057 */
058@ThreadSafe
059public final class TotpAuthenticator {
060    private final @NonNull TotpEngine engine;
061    private final @NonNull String namespace;
062    private final @NonNull String recoveryEpoch;
063    private TotpAuthenticator(@NonNull TotpEngine engine, @NonNull String namespace, @NonNull String recoveryEpoch) {
064        this.engine = engine; this.namespace = namespace; this.recoveryEpoch = recoveryEpoch;
065    }
066    /** Starts configuration with a trusted authenticator display issuer, not an OAuth issuer URL.
067     * @param issuer well-formed display issuer, 1–128 UTF-16 units, without colons, ISO controls,
068     * Unicode format/line/paragraph controls or leading/trailing whitespace
069     * @return a builder
070     * @since 1.0.0 */
071    public static @NonNull Builder withIssuer(@NonNull String issuer) { return new Builder(issuer); }
072    /** Returns the configured credential namespace.
073     * @return the namespace
074     * @since 1.0.0 */
075    public @NonNull String getCredentialNamespace() { return this.namespace; }
076    /** Returns the fixed external recovery generation.
077     * @return the recovery epoch
078     * @since 1.0.0 */
079    public @NonNull String getRecoveryEpoch() { return this.recoveryEpoch; }
080    /** Persist a browser-bound pending secret before releasing provisioning information. Management authorization is application-owned.
081     * @param options approved account, display label and optional exact replacement generation;
082     * the complete percent-encoded provisioning URI must fit 512 ASCII bytes
083     * @param browserBinding unpredictable server-owned browser binding
084     * @return the canonical operation outcome
085     * @throws IllegalArgumentException if the encoded provisioning URI exceeds 512 bytes;
086     * validation precedes recovery admission, storage and entropy
087     * @since 1.0.0 */
088    @CheckReturnValue
089    public @NonNull TotpEnrollmentRequestResult beginEnrollmentResult(@NonNull TotpEnrollmentOptions options, @NonNull OperationBinding browserBinding) {
090        return beginEnrollmentResult(options, Objects.requireNonNull(browserBinding).toSecretString());
091    }
092    @CheckReturnValue
093    @NonNull TotpEnrollmentRequestResult beginEnrollmentResult(@NonNull TotpEnrollmentOptions options, @NonNull String browserBinding) {
094        Objects.requireNonNull(options); account(options.getAccountId()); binding(browserBinding);
095        this.engine.validateEnrollment(options);
096        TotpEngine.Result result = this.engine.execute(new TotpEngine.Command(TotpEngine.Action.BEGIN,
097                options.getAccountId(), "", "", browserBinding, options, null));
098        return switch (result.status) {
099            case SUCCEEDED -> TotpEnrollmentRequestResult.prepared(Objects.requireNonNull(result.enrollment));
100            case REJECTED -> TotpEnrollmentRequestResult.rejected(result.rejection);
101            case THROTTLED -> TotpEnrollmentRequestResult.throttled(result.retryAfter);
102            case UNAVAILABLE -> TotpEnrollmentRequestResult.unavailable(result.unavailable);
103            case INDETERMINATE -> TotpEnrollmentRequestResult.indeterminate();
104                        case RECONCILIATION_REQUIRED -> TotpEnrollmentRequestResult.reconciliationRequired();
105            default -> throw new IllegalStateException("Unexpected TOTP operation outcome");
106        };
107    }
108    /** Atomically consumes pending enrollment, activates the factor, consumes its confirmation step and installs recovery verifiers.
109     * @param accountId approved stable account identifier
110     * @param enrollmentId pending enrollment identifier
111     * @param code submitted six ASCII digits, preserving leading zeros
112     * @param browserBinding the original server-owned browser binding
113     * @return the canonical operation outcome
114     * @since 1.0.0 */
115    @CheckReturnValue
116    public @NonNull TotpEnrollmentResult confirmEnrollmentResult(@NonNull String accountId, @NonNull String enrollmentId, @NonNull String code, @NonNull OperationBinding browserBinding) {
117        return confirmEnrollmentResult(accountId, enrollmentId, code, Objects.requireNonNull(browserBinding).toSecretString());
118    }
119    @CheckReturnValue
120    @NonNull TotpEnrollmentResult confirmEnrollmentResult(@NonNull String accountId, @NonNull String enrollmentId, @NonNull String code, @NonNull String browserBinding) {
121        account(accountId); binding(browserBinding); Objects.requireNonNull(enrollmentId); Objects.requireNonNull(code);
122        if (enrollmentId.length() > 128 || code.length() > 128) return TotpEnrollmentResult.rejected(TotpRejectionReason.INVALID_CODE);
123        TotpEngine.Result result = execute(TotpEngine.Action.CONFIRM, accountId, enrollmentId, code, browserBinding);
124        return switch (result.status) {
125            case SUCCEEDED -> TotpEnrollmentResult.succeeded(Objects.requireNonNull(result.factor), Objects.requireNonNull(result.codes));
126            case REJECTED -> TotpEnrollmentResult.rejected(result.rejection);
127            case THROTTLED -> TotpEnrollmentResult.throttled(result.retryAfter);
128            case UNAVAILABLE -> TotpEnrollmentResult.unavailable(result.unavailable);
129            case INDETERMINATE -> TotpEnrollmentResult.indeterminate();
130                        case RECONCILIATION_REQUIRED -> TotpEnrollmentResult.reconciliationRequired();
131            default -> throw new IllegalStateException("Unexpected TOTP operation outcome");
132        };
133    }
134    /** Verifies one code and commits replay consumption before releasing a TOTP proof. The application must atomically complete its current bound operation under recovery admission.
135     * @param accountId approved stable account identifier
136     * @param code submitted six ASCII digits
137     * @param operationBinding server-owned pending login or approved action binding
138     * @return the canonical operation outcome
139     * @since 1.0.0 */
140    @CheckReturnValue
141    public @NonNull TotpVerificationResult verifyResult(@NonNull String accountId, @NonNull String code, @NonNull OperationBinding operationBinding) {
142        return verifyResult(accountId, code, Objects.requireNonNull(operationBinding).toSecretString());
143    }
144    @CheckReturnValue
145    @NonNull TotpVerificationResult verifyResult(@NonNull String accountId, @NonNull String code, @NonNull String operationBinding) {
146        account(accountId); binding(operationBinding); Objects.requireNonNull(code);
147        if (code.length() > 128) return TotpVerificationResult.rejected(TotpRejectionReason.INVALID_CODE);
148        TotpEngine.Result result = execute(TotpEngine.Action.VERIFY, accountId, "", code, operationBinding);
149        return switch (result.status) {
150            case SUCCEEDED -> TotpVerificationResult.succeeded(Objects.requireNonNull(result.verification));
151            case REJECTED -> TotpVerificationResult.rejected(result.rejection);
152            case THROTTLED -> TotpVerificationResult.throttled(result.retryAfter);
153            case UNAVAILABLE -> TotpVerificationResult.unavailable(result.unavailable);
154            case INDETERMINATE -> TotpVerificationResult.indeterminate();
155                        case RECONCILIATION_REQUIRED -> TotpVerificationResult.reconciliationRequired();
156            default -> throw new IllegalStateException("Unexpected TOTP operation outcome");
157        };
158    }
159    /** Atomically consumes one recovery code and releases distinct recovery-method provenance. It does not prove current TOTP possession.
160     * @param accountId approved stable account identifier
161     * @param recoveryCode submitted recovery code, accepting ASCII case folding and hyphens
162     * @param operationBinding server-owned pending login or recovery action binding
163     * @return the canonical operation outcome
164     * @since 1.0.0 */
165    @CheckReturnValue
166    public @NonNull RecoveryCodeUseResult consumeRecoveryCodeResult(@NonNull String accountId, @NonNull String recoveryCode, @NonNull OperationBinding operationBinding) {
167        return consumeRecoveryCodeResult(accountId, recoveryCode, Objects.requireNonNull(operationBinding).toSecretString());
168    }
169    @CheckReturnValue
170    @NonNull RecoveryCodeUseResult consumeRecoveryCodeResult(@NonNull String accountId, @NonNull String recoveryCode, @NonNull String operationBinding) {
171        account(accountId); binding(operationBinding); Objects.requireNonNull(recoveryCode);
172        if (recoveryCode.length() > 128) return RecoveryCodeUseResult.rejected(TotpRejectionReason.INVALID_CODE);
173        TotpEngine.Result result = execute(TotpEngine.Action.RECOVERY, accountId, "", recoveryCode, operationBinding);
174        return switch (result.status) {
175            case SUCCEEDED -> RecoveryCodeUseResult.succeeded(Objects.requireNonNull(result.recoveryUse));
176            case REJECTED -> RecoveryCodeUseResult.rejected(result.rejection);
177            case THROTTLED -> RecoveryCodeUseResult.throttled(result.retryAfter);
178            case UNAVAILABLE -> RecoveryCodeUseResult.unavailable(result.unavailable);
179            case INDETERMINATE -> RecoveryCodeUseResult.indeterminate();
180                        case RECONCILIATION_REQUIRED -> RecoveryCodeUseResult.reconciliationRequired();
181            default -> throw new IllegalStateException("Unexpected TOTP operation outcome");
182        };
183    }
184    /** Replaces the entire recovery batch only for the exact approved factor and batch generations. New plaintext is released only after a confirmed commit.
185     * @param accountId approved stable account identifier
186     * @param expectedFactorId current factor generation from the authorized management context
187     * @param expectedBatchId current recovery batch from that same context
188     * @return the canonical operation outcome
189     * @since 1.0.0 */
190    @CheckReturnValue
191    public @NonNull RecoveryCodeRotationResult rotateRecoveryCodesResult(@NonNull String accountId, @NonNull String expectedFactorId, @NonNull String expectedBatchId) {
192        account(accountId); identifier(expectedFactorId); identifier(expectedBatchId);
193        TotpEngine.Result result = execute(TotpEngine.Action.ROTATE, accountId, expectedFactorId, expectedBatchId, "");
194        return switch (result.status) {
195            case SUCCEEDED -> RecoveryCodeRotationResult.succeeded(Objects.requireNonNull(result.codes));
196            case REJECTED -> RecoveryCodeRotationResult.rejected(result.rejection);
197            case UNAVAILABLE -> RecoveryCodeRotationResult.unavailable(result.unavailable);
198            case INDETERMINATE -> RecoveryCodeRotationResult.indeterminate();
199                        case RECONCILIATION_REQUIRED -> RecoveryCodeRotationResult.reconciliationRequired();
200            default -> throw new IllegalStateException("Unexpected TOTP operation outcome");
201        };
202    }
203    /** Removes the exact approved factor, pending enrollment and recovery batch while retaining permanent account and admission fences.
204     * @param accountId approved stable account identifier
205     * @param expectedFactorId current factor generation from the approved management context
206     * @return the canonical operation outcome
207     * @since 1.0.0 */
208    @CheckReturnValue
209    public @NonNull TotpFactorRemovalResult removeFactorResult(@NonNull String accountId, @NonNull String expectedFactorId) {
210        account(accountId); identifier(expectedFactorId);
211        TotpEngine.Result result = execute(TotpEngine.Action.REMOVE, accountId, expectedFactorId, "", "");
212        return switch (result.status) {
213            case SUCCEEDED -> TotpFactorRemovalResult.succeeded();
214            case REJECTED -> TotpFactorRemovalResult.rejected(result.rejection);
215            case UNAVAILABLE -> TotpFactorRemovalResult.unavailable(result.unavailable);
216            case INDETERMINATE -> TotpFactorRemovalResult.indeterminate();
217                        case RECONCILIATION_REQUIRED -> TotpFactorRemovalResult.reconciliationRequired();
218            default -> throw new IllegalStateException("Unexpected TOTP operation outcome");
219        };
220    }
221    /** Cancels only the named browser-bound pending enrollment, preserving the active factor and attempt accounting.
222     * @param accountId approved stable account identifier
223     * @param enrollmentId approved pending enrollment identifier
224     * @param browserBinding original server-owned browser binding
225     * @return the canonical operation outcome
226     * @since 1.0.0 */
227    @CheckReturnValue
228    public @NonNull TotpEnrollmentCancellationResult cancelEnrollmentResult(@NonNull String accountId, @NonNull String enrollmentId, @NonNull OperationBinding browserBinding) {
229        return cancelEnrollmentResult(accountId, enrollmentId, Objects.requireNonNull(browserBinding).toSecretString());
230    }
231    @CheckReturnValue
232    @NonNull TotpEnrollmentCancellationResult cancelEnrollmentResult(@NonNull String accountId, @NonNull String enrollmentId, @NonNull String browserBinding) {
233        account(accountId); identifier(enrollmentId); binding(browserBinding);
234        TotpEngine.Result result = execute(TotpEngine.Action.CANCEL, accountId, enrollmentId, "", browserBinding);
235        return switch (result.status) {
236            case SUCCEEDED -> TotpEnrollmentCancellationResult.succeeded();
237            case REJECTED -> TotpEnrollmentCancellationResult.rejected(result.rejection);
238            case UNAVAILABLE -> TotpEnrollmentCancellationResult.unavailable(result.unavailable);
239            case INDETERMINATE -> TotpEnrollmentCancellationResult.indeterminate();
240                        case RECONCILIATION_REQUIRED -> TotpEnrollmentCancellationResult.reconciliationRequired();
241            default -> throw new IllegalStateException("Unexpected TOTP operation outcome");
242        };
243    }
244    /** Reads active and pending generations and recovery counts without exposing secrets. Absence never authorizes a password-only fallback after namespace recovery.
245     * @param accountId authorized stable account identifier
246     * @return the canonical operation outcome
247     * @since 1.0.0 */
248    @CheckReturnValue
249    public @NonNull TotpStatusResult getStatusResult(@NonNull String accountId) {
250        account(accountId);
251        TotpEngine.Result result = execute(TotpEngine.Action.STATUS, accountId, "", "", "");
252        return switch (result.status) {
253            case SUCCEEDED -> TotpStatusResult.present(Objects.requireNonNull(result.accountStatus));
254            case ABSENT -> TotpStatusResult.absent();
255            case UNAVAILABLE -> TotpStatusResult.unavailable(result.unavailable);
256            default -> TotpStatusResult.unavailable(result.unavailable);
257        };
258    }
259    /** Initializes only a newly provisioned recovery generation under an explicit initialization permit. Normal operations never recreate a missing namespace root.
260     * @return the canonical operation outcome
261     * @since 1.0.0 */
262    @CheckReturnValue
263    public @NonNull TotpNamespaceInitializationResult initializeNamespaceResult() {
264        TotpEngine.Result result = execute(TotpEngine.Action.INITIALIZE, null, "", "", "");
265        return switch (result.status) {
266            case SUCCEEDED -> TotpNamespaceInitializationResult.initialized();
267            case ALREADY_CURRENT -> TotpNamespaceInitializationResult.alreadyInitialized();
268            case UNAVAILABLE -> TotpNamespaceInitializationResult.unavailable(result.unavailable);
269            case INDETERMINATE -> TotpNamespaceInitializationResult.indeterminate();
270                        case RECONCILIATION_REQUIRED -> TotpNamespaceInitializationResult.reconciliationRequired();
271            default -> throw new IllegalStateException("Unexpected TOTP operation outcome");
272        };
273    }
274    /** Authenticates and reseals one permanent record with the active key under exact row and namespace predicates, preserving all semantic state and deadlines.
275     * @param key application-authorized maintenance address within this configured scope
276     * @return the canonical operation outcome
277     * @since 1.0.0 */
278    @CheckReturnValue
279    public @NonNull TotpStoreResealResult resealStoreEntryResult(@NonNull TotpStoreKey key) {
280        Objects.requireNonNull(key);
281        if (!key.getCredentialNamespace().equals(this.namespace) || !key.getRecoveryEpoch().equals(this.recoveryEpoch))
282            throw new IllegalArgumentException("Foreign TOTP maintenance scope");
283        TotpEngine.Result result = this.engine.execute(new TotpEngine.Command(TotpEngine.Action.RESEAL,
284                null, "", "", "", null, key));
285        return switch (result.status) {
286            case SUCCEEDED -> TotpStoreResealResult.resealed();
287            case ALREADY_CURRENT -> TotpStoreResealResult.alreadyCurrent();
288            case ABSENT -> TotpStoreResealResult.absent();
289            case UNAVAILABLE -> TotpStoreResealResult.unavailable(result.unavailable);
290            case INDETERMINATE -> TotpStoreResealResult.indeterminate();
291                        case RECONCILIATION_REQUIRED -> TotpStoreResealResult.reconciliationRequired();
292            default -> throw new IllegalStateException("Unexpected TOTP operation outcome");
293        };
294    }
295    private TotpEngine.@NonNull Result execute(TotpEngine.@NonNull Action action, @Nullable String accountId,
296            @NonNull String first, @NonNull String second, @NonNull String third) {
297        return this.engine.execute(new TotpEngine.Command(action, accountId, first, second, third, null, null));
298    }
299    private void account(@NonNull String accountId) { TotpStoreKey.validateAccount(accountId); }
300    private static void identifier(@NonNull String value) {
301        Objects.requireNonNull(value);
302        if (value.isEmpty() || value.length() > 1024 || !StrictUtf8.isWellFormed(value))
303            throw new IllegalArgumentException("Invalid TOTP identifier");
304    }
305    private static void binding(@NonNull String value) { identifier(value); }
306    /** Redacts application configuration and identifiers.
307     * @return a fixed description
308     * @since 1.0.0 */
309    @Override public @NonNull String toString() { return "TotpAuthenticator{configuration=<redacted>}"; }
310
311    /** Caller-thread configuration builder. Required dependencies have no permissive defaults.
312     * @since 1.0.0 */
313    @NotThreadSafe
314    @CheckReturnValue
315    public static final class Builder {
316        private final @NonNull String issuer;
317        private @Nullable String namespace;
318        private @Nullable String epoch;
319        private @Nullable TotpStore store;
320        private @Nullable StateSealer sealer;
321        private @Nullable TotpRecoveryGate gate;
322        private @NonNull Clock clock = Clock.systemUTC();
323        private @NonNull Duration timeout = Duration.ofSeconds(5);
324        private Builder(@NonNull String issuer) {
325            Objects.requireNonNull(issuer);
326            if (issuer.isEmpty() || issuer.length() > 128 || !StrictUtf8.isWellFormed(issuer))
327                throw new IllegalArgumentException("Invalid TOTP issuer");
328            TotpProvisioning.validateLabel(issuer);
329            this.issuer = issuer;
330        }
331        /** Sets the stable account storage namespace.
332         * @param credentialNamespace visible ASCII namespace, 1–128 characters; null clears this required setting
333         * @return this builder
334         * @since 1.0.0 */
335        public @NonNull Builder credentialNamespace(@Nullable String credentialNamespace) {
336            if (credentialNamespace != null) TotpStoreKey.validateScope(credentialNamespace); this.namespace = credentialNamespace; return this;
337        }
338        /** Sets the externally durable, never-reused recovery generation.
339         * @param recoveryEpoch visible ASCII epoch, 1–128 characters; null clears this required setting
340         * @return this builder
341         * @since 1.0.0 */
342        public @NonNull Builder recoveryEpoch(@Nullable String recoveryEpoch) {
343            if (recoveryEpoch != null) TotpStoreKey.validateScope(recoveryEpoch); this.epoch = recoveryEpoch; return this;
344        }
345        /** Sets authoritative storage with atomic recovery fencing.
346         * @param store application-owned thread-safe store; null clears this required setting
347         * @return this builder
348         * @since 1.0.0 */
349        public @NonNull Builder store(@Nullable TotpStore store) { this.store = store; return this; }
350        /** Sets immutable sealing-key configuration for typed permanent records.
351         * @param stateSealer the sealer; null clears this required setting. Retain old opening keys until records are migrated
352         * @return this builder
353         * @since 1.0.0 */
354        public @NonNull Builder stateSealer(@Nullable StateSealer stateSealer) { this.sealer = stateSealer; return this; }
355        /** Sets externally durable deployment/recovery admission.
356         * @param recoveryGate application-owned thread-safe gate; null clears this required setting
357         * @return this builder
358         * @since 1.0.0 */
359        public @NonNull Builder recoveryGate(@Nullable TotpRecoveryGate recoveryGate) { this.gate = recoveryGate; return this; }
360        /** Sets the worker UTC source used only to confirm bounded clock health against store time.
361         * @param clock the clock, or null for the system UTC clock
362         * @return this builder
363         * @since 1.0.0 */
364        public @NonNull Builder clock(@Nullable Clock clock) { this.clock = clock == null ? Clock.systemUTC() : clock; return this; }
365        /** Sets one shrinking caller-thread deadline for admission, crypto, storage and conflict retries.
366         * @param operationTimeout from one second to 30 seconds, or null for five seconds
367         * @return this builder
368         * @since 1.0.0 */
369        public @NonNull Builder operationTimeout(@Nullable Duration operationTimeout) {
370            Duration timeout = operationTimeout == null ? Duration.ofSeconds(5) : operationTimeout;
371            if (timeout.compareTo(Duration.ofSeconds(1)) < 0 || timeout.compareTo(Duration.ofSeconds(30)) > 0)
372                throw new IllegalArgumentException("Invalid TOTP operation timeout");
373            this.timeout = timeout; return this;
374        }
375        /** Inspects only the current configuration shape. The immutable, ordered result contains
376         * fixed codes and no supplied values; it does not call application dependencies.
377         * @return every missing required setting, or an empty list
378         * @since 1.0.0 */
379        @CheckReturnValue public @NonNull List<@NonNull ConfigurationDiagnostic> configurationDiagnostics() {
380            List<ConfigurationDiagnostic> issues = new ArrayList<>(5);
381            if (this.namespace == null) issues.add(ConfigurationDiagnostic.TOTP_CREDENTIAL_NAMESPACE_REQUIRED);
382            if (this.epoch == null) issues.add(ConfigurationDiagnostic.TOTP_RECOVERY_EPOCH_REQUIRED);
383            if (this.store == null) issues.add(ConfigurationDiagnostic.TOTP_STORE_REQUIRED);
384            if (this.sealer == null) issues.add(ConfigurationDiagnostic.TOTP_STATE_SEALER_REQUIRED);
385            if (this.gate == null) issues.add(ConfigurationDiagnostic.TOTP_RECOVERY_GATE_REQUIRED);
386            return List.copyOf(issues);
387        }
388        /** Checks configuration without admission, storage, cryptographic-provider calls or thread startup.
389         * @return the immutable authenticator
390         * @since 1.0.0 */
391        public @NonNull TotpAuthenticator build() {
392            List<ConfigurationDiagnostic> issues = configurationDiagnostics();
393            if (!issues.isEmpty()) throw new NullPointerException(issues.get(0).getFieldCode());
394            String ns = Objects.requireNonNull(this.namespace, "credentialNamespace");
395            String recoveryEpoch = Objects.requireNonNull(this.epoch, "recoveryEpoch");
396            return new TotpAuthenticator(new TotpEngine(this.issuer, ns, recoveryEpoch,
397                    Objects.requireNonNull(this.store, "store"), Objects.requireNonNull(this.sealer, "stateSealer"),
398                    Objects.requireNonNull(this.gate, "recoveryGate"), this.clock, this.timeout), ns, recoveryEpoch);
399        }
400        /** Redacts builder contents.
401         * @return a fixed description
402         * @since 1.0.0 */
403        @Override public @NonNull String toString() { return "TotpAuthenticator.Builder{configuration=<redacted>}"; }
404    }
405}