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 java.nio.charset.StandardCharsets; 020import java.security.MessageDigest; 021import java.security.NoSuchAlgorithmException; 022import com.revetsec.internal.encoding.Base64Url; 023import com.revetsec.internal.encoding.EncodingException; 024import java.util.Objects; 025import org.jspecify.annotations.NonNull; 026import org.jspecify.annotations.Nullable; 027 028/** 029 * Canonical, namespace- and recovery-epoch-bound address of permanent TOTP state. Account IDs 030 * appear only as domain-separated SHA-256 digests. Constructing an address confers no authority. 031 * Storage addresses are sensitive and must not be logged. 032 * @since 1.0.0 033 */ 034@javax.annotation.concurrent.Immutable 035public final class TotpStoreKey { 036 private static final @NonNull String NAMESPACE_DIGEST = "imuTRYmFK91EEVQacqvPSOwL9Fiy6uV9Dlqs7_LkszQ"; 037 private final @NonNull String storageKey; 038 private final @NonNull String credentialNamespace; 039 private final @NonNull String recoveryEpoch; 040 private final TotpStoreKey.@NonNull Kind kind; 041 042 private TotpStoreKey(@NonNull String namespace, @NonNull String epoch, 043 TotpStoreKey.@NonNull Kind kind, @NonNull String digest) { 044 validateScope(namespace); validateScope(epoch); 045 this.credentialNamespace = namespace; 046 this.recoveryEpoch = epoch; 047 this.kind = kind; 048 this.storageKey = "totp1:" + encode(namespace.getBytes(StandardCharsets.US_ASCII)) + ':' 049 + encode(epoch.getBytes(StandardCharsets.US_ASCII)) + ':' + kind.name() + ':' + digest; 050 } 051 052 /** 053 * Addresses the permanent namespace clock and initialization fence. 054 * @param credentialNamespace the visible ASCII namespace, from 1 to 128 characters 055 * @param recoveryEpoch the never-reused visible ASCII recovery epoch, from 1 to 128 characters 056 * @return the namespace address 057 * @since 1.0.0 058 */ 059 public static @NonNull TotpStoreKey forNamespace(@NonNull String credentialNamespace, 060 @NonNull String recoveryEpoch) { 061 return new TotpStoreKey(credentialNamespace, recoveryEpoch, Kind.NAMESPACE_STATE, 062 NAMESPACE_DIGEST); 063 } 064 065 /** 066 * Addresses the permanent account aggregate without disclosing its identifier in the address. 067 * @param credentialNamespace the visible ASCII namespace 068 * @param recoveryEpoch the never-reused recovery epoch 069 * @param accountId the nonempty, well-formed account identifier, at most 1024 UTF-8 bytes 070 * @return the account address 071 * @since 1.0.0 072 */ 073 public static @NonNull TotpStoreKey forAccount(@NonNull String credentialNamespace, 074 @NonNull String recoveryEpoch, @NonNull String accountId) { 075 validateAccount(accountId); 076 return new TotpStoreKey(credentialNamespace, recoveryEpoch, Kind.ACCOUNT_STATE, 077 digest("revetsec-totp-account-v1\0" + accountId)); 078 } 079 080 /** 081 * Parses a bounded canonical persistence address; authenticity is checked when opening its record. 082 * @param storageKey the exact stored address 083 * @return the parsed address 084 * @since 1.0.0 085 */ 086 public static @NonNull TotpStoreKey fromStoredForm(@NonNull String storageKey) { 087 Objects.requireNonNull(storageKey); 088 if (storageKey.length() > 430) throw new IllegalArgumentException("Invalid TOTP store address"); 089 String[] parts = storageKey.split(":", -1); 090 if (parts.length != 5 || !parts[0].equals("totp1")) 091 throw new IllegalArgumentException("Invalid TOTP store address"); 092 String namespace = decodeScope(parts[1]); 093 String epoch = decodeScope(parts[2]); 094 Kind kind; 095 try { kind = Kind.valueOf(parts[3]); } 096 catch (IllegalArgumentException invalid) { throw new IllegalArgumentException("Invalid TOTP store address"); } 097 validateDigest(parts[4]); 098 TotpStoreKey key = new TotpStoreKey(namespace, epoch, kind, parts[4]); 099 if (!storageKey.equals(key.storageKey) 100 || (kind == Kind.NAMESPACE_STATE && !key.equals(forNamespace(namespace, epoch)))) 101 throw new IllegalArgumentException("Invalid TOTP store address"); 102 return key; 103 } 104 105 /** 106 * Returns the exact sensitive persistence address. 107 * @return the address; never log it 108 * @since 1.0.0 109 */ 110 public @NonNull String getStorageKey() { return this.storageKey; } 111 /** 112 * Returns the credential namespace. 113 * @return the namespace 114 * @since 1.0.0 115 */ 116 public @NonNull String getCredentialNamespace() { return this.credentialNamespace; } 117 /** 118 * Returns the recovery epoch. 119 * @return the epoch 120 * @since 1.0.0 121 */ 122 public @NonNull String getRecoveryEpoch() { return this.recoveryEpoch; } 123 /** 124 * Returns the permanent record kind. 125 * @return the kind 126 * @since 1.0.0 127 */ 128 public TotpStoreKey.@NonNull Kind getKind() { return this.kind; } 129 /** 130 * Compares the complete persistence address. 131 * @since 1.0.0 132 */ 133 @Override public boolean equals(@Nullable Object other) { 134 return other instanceof TotpStoreKey key && this.storageKey.equals(key.storageKey); 135 } 136 /** 137 * Returns the complete address hash. 138 * @since 1.0.0 139 */ 140 @Override public int hashCode() { return this.storageKey.hashCode(); } 141 /** 142 * Redacts the address. 143 * @since 1.0.0 144 */ 145 @Override public @NonNull String toString() { return "TotpStoreKey{address=<redacted>}"; } 146 147 static void validateScope(@NonNull String value) { 148 Objects.requireNonNull(value); 149 if (value.isEmpty() || value.length() > 128) throw new IllegalArgumentException("Invalid TOTP scope"); 150 for (int i = 0; i < value.length(); i++) 151 if (value.charAt(i) < 0x21 || value.charAt(i) > 0x7e) 152 throw new IllegalArgumentException("Invalid TOTP scope"); 153 } 154 static void validateAccount(@NonNull String value) { 155 Objects.requireNonNull(value); 156 if (value.isEmpty() || value.length() > 1024) 157 throw new IllegalArgumentException("Invalid TOTP account identifier"); 158 for (int i = 0; i < value.length(); i++) { 159 char character = value.charAt(i); 160 if (Character.isHighSurrogate(character)) { 161 if (i + 1 >= value.length() || !Character.isLowSurrogate(value.charAt(++i))) 162 throw new IllegalArgumentException("Invalid TOTP account identifier"); 163 } else if (Character.isLowSurrogate(character)) 164 throw new IllegalArgumentException("Invalid TOTP account identifier"); 165 } 166 if (value.getBytes(StandardCharsets.UTF_8).length > 1024) 167 throw new IllegalArgumentException("Invalid TOTP account identifier"); 168 } 169 static void validateDigest(@NonNull String value) { 170 Objects.requireNonNull(value); 171 if (value.length() != 43) throw new IllegalArgumentException("Invalid TOTP digest"); 172 try { 173 byte[] decoded = Base64Url.decode(value); 174 if (decoded.length != 32 || !encode(decoded).equals(value)) 175 throw new IllegalArgumentException("Invalid TOTP digest"); 176 } catch (EncodingException invalid) { throw new IllegalArgumentException("Invalid TOTP digest"); } 177 } 178 private static @NonNull String decodeScope(@NonNull String value) { 179 if (value.length() > 171) throw new IllegalArgumentException("Invalid TOTP scope"); 180 byte[] decoded; 181 try { decoded = Base64Url.decode(value); } 182 catch (EncodingException invalid) { throw new IllegalArgumentException("Invalid TOTP scope"); } 183 for (byte character : decoded) if (character < 0x21 || character > 0x7e) 184 throw new IllegalArgumentException("Invalid TOTP scope"); 185 String scope = new String(decoded, StandardCharsets.US_ASCII); 186 validateScope(scope); 187 if (!encode(decoded).equals(value)) throw new IllegalArgumentException("Invalid TOTP scope"); 188 return scope; 189 } 190 private static @NonNull String encode(byte @NonNull [] bytes) { 191 return Base64Url.encode(bytes); 192 } 193 private static @NonNull String digest(@NonNull String text) { 194 try { return encode(MessageDigest.getInstance("SHA-256").digest(text.getBytes(StandardCharsets.UTF_8))); } 195 catch (NoSuchAlgorithmException unavailable) { throw new IllegalStateException("SHA-256 unavailable", unavailable); } 196 } 197 /** 198 * Permanent record kinds. Neither kind may carry a backend TTL or be evicted. 199 * @since 1.0.0 200 */ 201 @javax.annotation.concurrent.Immutable 202 public enum Kind { 203 /** 204 * Namespace initialization and observed-time fences. 205 */ NAMESPACE_STATE, 206 /** 207 * Factor, pending enrollment, replay mark, recovery verifiers and account fences. 208 */ ACCOUNT_STATE 209 } 210}