Sync shared snapshot from df68167

This commit is contained in:
Gabriel20xx committed 2026-08-06 16:53:48 +02:00
1 parent 588ef139a6
commit 06efc832ca
79 files changed
+10035 -3

No files matched your search

@@ -0,0 +1,58 @@
package com.gabriel20xx.shared.auth;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.SecureRandom;
import java.util.Locale;
/** Shared short-lived, one-time admin reset-code primitive for Java services. */
public final class ResetManager {
private static final long RESET_CODE_TTL_MILLIS = 5L * 60L * 1000L;
private static final SecureRandom RANDOM = new SecureRandom();
private String code;
private long expiresAtMillis;
/** Creates and prints a new reset code, invalidating any previous code. */
public synchronized String request() {
byte[] raw = new byte[4];
RANDOM.nextBytes(raw);
StringBuilder generated = new StringBuilder(raw.length * 2);
for (byte value : raw) {
generated.append(String.format(Locale.ROOT, "%02X", value & 0xff));
}
code = generated.toString();
expiresAtMillis = System.currentTimeMillis() + RESET_CODE_TTL_MILLIS;
System.out.println("\n==================================================\n"
+ "ADMIN RESET CODE: " + code + "\n"
+ "Expires in 5 minutes. Enter it on the login page.\n"
+ "==================================================\n");
return code;
}
/** Validates and consumes the current code. Invalid codes remain retryable. */
public synchronized boolean confirm(String candidate) {
if (code == null) {
return false;
}
if (System.currentTimeMillis() > expiresAtMillis) {
clear();
return false;
}
String normalized = candidate == null ? "" : candidate.trim().toUpperCase(Locale.ROOT);
boolean matches = MessageDigest.isEqual(
code.getBytes(StandardCharsets.US_ASCII),
normalized.getBytes(StandardCharsets.US_ASCII));
if (matches) {
clear();
}
return matches;
}
private void clear() {
code = null;
expiresAtMillis = 0L;
}
}
@@ -0,0 +1,29 @@
package com.gabriel20xx.shared.auth;
import java.util.Locale;
/** Shared account-management roles used by Java web services. */
public final class Roles {
public static final String SUPERADMIN = "superadmin";
public static final String ADMIN = "admin";
public static final String USER = "user";
private Roles() {
}
public static String normalize(String value) {
String normalized = value == null ? "" : value.trim().toLowerCase(Locale.ROOT);
if (SUPERADMIN.equals(normalized)) return SUPERADMIN;
if (ADMIN.equals(normalized)) return ADMIN;
return USER;
}
public static boolean canManageUsers(String role) {
String normalized = normalize(role);
return SUPERADMIN.equals(normalized) || ADMIN.equals(normalized);
}
public static boolean canAssignRole(String actorRole, String targetRole) {
return SUPERADMIN.equals(normalize(actorRole)) && !SUPERADMIN.equals(normalize(targetRole));
}
}
@@ -0,0 +1,143 @@
package com.gabriel20xx.shared.auth;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.util.Locale;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
/** RFC 6238 TOTP primitives shared by Java services. */
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();
private Totp() {
}
public static String generateSecret() {
byte[] raw = new byte[SECRET_BYTES];
RANDOM.nextBytes(raw);
return encodeBase32(raw);
}
public static String provisioningUri(String issuer, String account, String secret) {
String normalizedIssuer = issuer == null ? "" : issuer.trim();
String normalizedAccount = account == null ? "" : account.trim();
String label = normalizedIssuer.isEmpty()
? normalizedAccount
: normalizedIssuer + ":" + normalizedAccount;
StringBuilder uri = new StringBuilder("otpauth://totp/")
.append(urlEncode(label))
.append("?secret=").append(normalizeSecret(secret));
if (!normalizedIssuer.isEmpty()) {
uri.append("&issuer=").append(urlEncode(normalizedIssuer));
}
return uri.append("&algorithm=SHA1&digits=").append(DIGITS)
.append("&period=").append(PERIOD_SECONDS).toString();
}
public static boolean verify(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;
}
byte[] key;
try {
key = decodeBase32(normalizedSecret);
} catch (IllegalArgumentException ex) {
return false;
}
if (key.length == 0) {
return false;
}
long counter = Math.floorDiv(nowMillis, PERIOD_SECONDS * 1000L);
for (long offset = -WINDOW; offset <= WINDOW; offset++) {
if (counter + offset < 0) {
continue;
}
try {
byte[] message = new byte[8];
long value = counter + offset;
for (int index = 7; index >= 0; index--) {
message[index] = (byte) (value & 0xff);
value >>>= 8;
}
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(new SecretKeySpec(key, "HmacSHA1"));
byte[] hash = mac.doFinal(message);
int index = hash[hash.length - 1] & 0x0f;
int code = ((hash[index] & 0x7f) << 24)
| ((hash[index + 1] & 0xff) << 16)
| ((hash[index + 2] & 0xff) << 8)
| (hash[index + 3] & 0xff);
String candidate = String.format(Locale.ROOT, "%06d", code % 1_000_000);
if (candidate.equals(normalizedToken)) {
return true;
}
} catch (Exception ex) {
return false;
}
}
return false;
}
private static String normalizeSecret(String value) {
return value == null ? "" : value.trim().replace(" ", "").replace("=", "").toUpperCase(Locale.ROOT);
}
private static String encodeBase32(byte[] bytes) {
StringBuilder result = new StringBuilder((bytes.length * 8 + 4) / 5);
int buffer = 0;
int bits = 0;
for (byte value : bytes) {
buffer = (buffer << 8) | (value & 0xff);
bits += 8;
while (bits >= 5) {
bits -= 5;
result.append(BASE32.charAt((buffer >>> bits) & 31));
}
}
if (bits > 0) {
result.append(BASE32.charAt((buffer << (5 - bits)) & 31));
}
return result.toString();
}
private static byte[] decodeBase32(String value) {
int outputLength = value.length() * 5 / 8;
byte[] result = new byte[outputLength];
int buffer = 0;
int bits = 0;
int output = 0;
for (int index = 0; index < value.length(); index++) {
int digit = BASE32.indexOf(value.charAt(index));
if (digit < 0) {
throw new IllegalArgumentException("Invalid base32 secret");
}
buffer = (buffer << 5) | digit;
bits += 5;
while (bits >= 8) {
bits -= 8;
if (output < result.length) {
result[output++] = (byte) ((buffer >>> bits) & 0xff);
}
}
buffer &= bits == 0 ? 0 : (1 << bits) - 1;
}
return result;
}
private static String urlEncode(String value) {
try {
return URLEncoder.encode(value, StandardCharsets.UTF_8.name()).replace("+", "%20");
} catch (Exception ex) {
throw new IllegalArgumentException("Unable to encode provisioning URI", ex);
}
}
}