lamarge 0.5.1

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! Sign-In with Ethereum challenge checks.

use alloy_primitives::Address;
use chrono::{DateTime, Duration, Utc};

use super::{
    checks::details::{self, differs, stale},
    eip712,
    signing::Verified,
};
use crate::error::VerificationError;

/// Tolerated clock skew between the client and the server.
const SKEW: Duration = Duration::seconds(120);
/// The longest a challenge may be valid.
const LIFETIME: Duration = Duration::seconds(600);

/// Checks a sign-in challenge (`POST /v1/auth/challenge`) for `address` and the app `origin`
/// at `now`: the exact EIP-4361 text the server writes, its nonce and expiry, issued no later
/// than two minutes ahead, not expired more than two minutes ago, valid ten minutes at most.
/// Returns the text to sign with `personal_sign`, signable until two minutes after expiry.
pub(crate) fn check_login_challenge(
    message: &str,
    nonce: &str,
    expires_at: DateTime<Utc>,
    address: Address,
    origin: &str,
    now: DateTime<Utc>,
) -> Result<Verified, VerificationError> {
    let lines: Vec<&str> = message.split('\n').collect();
    let (_, host) = origin.split_once("://").ok_or(differs(details::CHALLENGE))?;
    let [
        intro,
        signer,
        "",
        "Sign in to LaMarge.",
        "",
        uri,
        "Version: 1",
        "Chain ID: 1",
        nonce_line,
        issued,
        expires,
    ] = lines[..]
    else {
        return Err(differs(details::CHALLENGE));
    };
    let time = |line: &str, label: &str| {
        line.strip_prefix(label)
            .and_then(|text| DateTime::parse_from_rfc3339(text).ok())
            .map(|time| time.with_timezone(&Utc))
    };
    let issued = time(issued, "Issued At: ");
    let shaped = intro.strip_suffix(" wants you to sign in with your Ethereum account:")
        == Some(host)
        && eip712::address_text(signer) == Some(address)
        && uri.strip_prefix("URI: ") == Some(origin)
        && nonce_line.strip_prefix("Nonce: ") == Some(nonce)
        && time(expires, "Expiration Time: ") == Some(expires_at);
    let Some(issued) = issued.filter(|_| shaped) else {
        return Err(differs(details::CHALLENGE));
    };
    if issued > now + SKEW
        || expires_at <= now - SKEW
        || expires_at <= issued
        || expires_at - issued > LIFETIME
    {
        return Err(stale(details::CHALLENGE_WINDOW));
    }
    let not_after = (expires_at + SKEW).timestamp() - 1;
    Ok(Verified::text(message.to_owned(), address, Some(not_after)))
}

#[cfg(test)]
mod tests;