bit-twiddler 0.2.1

Cross-platform developer toolbox: bit manipulation, hashing, YAML/JSON/SQL, QR, Markdown, cron, and 40+ more tools — Tauri v2, no Node.js
use jsonwebtoken::errors::ErrorKind;
use jsonwebtoken::{decode, decode_header, Algorithm, DecodingKey, Validation};
use serde_json::Value;

#[tauri::command]
pub fn verify_jwt(token: String, secret_or_pem: String) -> Result<bool, String> {
    let header = decode_header(&token).map_err(|e| e.to_string())?;
    let alg = header.alg;

    let key = match alg {
        Algorithm::HS256 | Algorithm::HS384 | Algorithm::HS512 => {
            DecodingKey::from_secret(secret_or_pem.as_bytes())
        }
        Algorithm::RS256
        | Algorithm::RS384
        | Algorithm::RS512
        | Algorithm::PS256
        | Algorithm::PS384
        | Algorithm::PS512 => {
            DecodingKey::from_rsa_pem(secret_or_pem.as_bytes()).map_err(|e| e.to_string())?
        }
        Algorithm::ES256 | Algorithm::ES384 => {
            DecodingKey::from_ec_pem(secret_or_pem.as_bytes()).map_err(|e| e.to_string())?
        }
        Algorithm::EdDSA => {
            DecodingKey::from_ed_pem(secret_or_pem.as_bytes()).map_err(|e| e.to_string())?
        }
        other => return Err(format!("Unsupported algorithm: {other:?}")),
    };

    // We only care whether the signature is genuine here — claim expiry/audience/
    // issuer are a separate concern the frontend already surfaces from the decoded
    // payload, and shouldn't make a validly-signed-but-expired token look "invalid".
    let mut validation = Validation::new(alg);
    validation.validate_exp = false;
    validation.validate_nbf = false;
    validation.required_spec_claims.clear();

    match decode::<Value>(&token, &key, &validation) {
        Ok(_) => Ok(true),
        Err(e) => match e.kind() {
            ErrorKind::InvalidSignature => Ok(false),
            _ => Err(e.to_string()),
        },
    }
}