feat(sync): paginate Android sync with change tokens
This commit is contained in:
1 parent
0ff94f9b10
commit
97c237be80
76 files changed
+3401
-851
No files matched your search
@@ -13,7 +13,6 @@ public final class Totp {
|
||||
private static final String BASE32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
|
||||
private static final int SECRET_BYTES = 20;
|
||||
private static final int PERIOD_SECONDS = 30;
|
||||
private static final int WINDOW = 1;
|
||||
private static final int DIGITS = 6;
|
||||
private static final SecureRandom RANDOM = new SecureRandom();
|
||||
|
||||
@@ -43,22 +42,28 @@ public final class Totp {
|
||||
}
|
||||
|
||||
public static boolean verify(String secret, String token, long nowMillis) {
|
||||
return verifyStep(secret, token, nowMillis) >= 0;
|
||||
}
|
||||
|
||||
/** Returns the matching 30-second step, or {@code -1} when no code matches. */
|
||||
public static long verifyStep(String secret, String token, long nowMillis) {
|
||||
String normalizedSecret = normalizeSecret(secret);
|
||||
String normalizedToken = token == null ? "" : token.trim();
|
||||
if (normalizedSecret.isEmpty() || !normalizedToken.matches("\\d{" + DIGITS + "}")) {
|
||||
return false;
|
||||
return -1;
|
||||
}
|
||||
byte[] key;
|
||||
try {
|
||||
key = decodeBase32(normalizedSecret);
|
||||
} catch (IllegalArgumentException ex) {
|
||||
return false;
|
||||
return -1;
|
||||
}
|
||||
if (key.length == 0) {
|
||||
return false;
|
||||
return -1;
|
||||
}
|
||||
long counter = Math.floorDiv(nowMillis, PERIOD_SECONDS * 1000L);
|
||||
for (long offset = -WINDOW; offset <= WINDOW; offset++) {
|
||||
// Prefer the current step if a six-digit collision occurs in the window.
|
||||
for (long offset : new long[] {0, -1, 1}) {
|
||||
if (counter + offset < 0) {
|
||||
continue;
|
||||
}
|
||||
@@ -80,13 +85,13 @@ public final class Totp {
|
||||
String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000);
|
||||
if (MessageDigest.isEqual(candidate.getBytes(StandardCharsets.US_ASCII),
|
||||
normalizedToken.getBytes(StandardCharsets.US_ASCII))) {
|
||||
return true;
|
||||
return counter + offset;
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
return false;
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
return -1;
|
||||
}
|
||||
|
||||
private static String normalizeSecret(String value) {
|
||||
|
||||
@@ -15,6 +15,7 @@ class TotpTest {
|
||||
void verifyAcceptsTheRfc6238Vectors() {
|
||||
// The RFC lists 8-digit codes; these are their last six digits.
|
||||
assertTrue(Totp.verify(RFC_SECRET, "287082", 59_000L));
|
||||
assertEquals(1L, Totp.verifyStep(RFC_SECRET, "287082", 59_000L));
|
||||
assertTrue(Totp.verify(RFC_SECRET, "081804", 1_111_111_109_000L));
|
||||
assertTrue(Totp.verify(RFC_SECRET, "050471", 1_111_111_111_000L));
|
||||
assertTrue(Totp.verify(RFC_SECRET, "005924", 1_234_567_890_000L));
|
||||
|
||||
Reference in new issue
Block a user