use super::store::{ActionArtifact, AuditEntry, ForgeStore, now_unix, parse_form_urlencoded};
use super::{ActiveTab, RepoContext, WEB_UI_CSP, format_timestamp, html_escape, render_page};
use crate::http::{HttpRequest, HttpResponse};
use arks_repo::Repository;
use sha2::{Digest, Sha256};
use std::fs;
use std::path::Path;
const AUDIT_GENESIS_HASH: &str = "0000000000000000000000000000000000000000000000000000000000000000";
fn compute_audit_entry_hash(prev_hash: &str, entry: &AuditEntry) -> String {
let mut hasher = Sha256::new();
hasher.update(prev_hash.as_bytes());
hasher.update(b"|");
hasher.update(entry.id.to_string().as_bytes());
hasher.update(b"|");
hasher.update(entry.actor.as_bytes());
hasher.update(b"|");
hasher.update(entry.action.as_bytes());
hasher.update(b"|");
hasher.update(entry.target.as_bytes());
hasher.update(b"|");
hasher.update(entry.created_at.to_string().as_bytes());
hasher
.finalize()
.iter()
.map(|b| format!("{b:02x}"))
.collect()
}
fn last_audit_chain_hash(jsonl_path: &Path) -> String {
let Ok(raw) = fs::read_to_string(jsonl_path) else {
return AUDIT_GENESIS_HASH.to_string();
};
raw.lines()
.rev()
.find(|l| !l.trim().is_empty())
.and_then(|l| serde_json::from_str::<serde_json::Value>(l).ok())
.and_then(|v| {
v.get("entry_hash")
.and_then(|h| h.as_str())
.map(String::from)
})
.unwrap_or_else(|| AUDIT_GENESIS_HASH.to_string())
}
pub fn verify_audit_chain(common_dir: &Path) -> Result<usize, String> {
let jsonl_path = common_dir.join("arks-forge").join("audit.jsonl");
let Ok(raw) = fs::read_to_string(&jsonl_path) else {
return Ok(0);
};
let mut expected_prev = AUDIT_GENESIS_HASH.to_string();
let mut count = 0usize;
for (idx, line) in raw.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
let val: serde_json::Value = serde_json::from_str(line)
.map_err(|e| format!("line {}: malformed JSON: {e}", idx + 1))?;
let entry: AuditEntry = serde_json::from_value(val.clone())
.map_err(|e| format!("line {}: invalid audit entry: {e}", idx + 1))?;
let prev = val
.get("prev_hash")
.and_then(|v| v.as_str())
.ok_or_else(|| format!("line {}: missing prev_hash", idx + 1))?;
let hash = val
.get("entry_hash")
.and_then(|v| v.as_str())
.ok_or_else(|| format!("line {}: missing entry_hash", idx + 1))?;
if prev != expected_prev {
return Err(format!(
"line {}: prev_hash mismatch (expected {expected_prev}, got {prev})",
idx + 1
));
}
let recomputed = compute_audit_entry_hash(prev, &entry);
if hash != recomputed {
return Err(format!(
"line {}: entry_hash mismatch (tampered entry)",
idx + 1
));
}
expected_prev = recomputed;
count += 1;
}
Ok(count)
}
pub fn handle_verify_audit_chain(repo: &Repository) -> HttpResponse {
match verify_audit_chain(repo.common_dir()) {
Ok(entries) => HttpResponse {
status: 200,
content_type: "application/json; charset=utf-8".into(),
body: serde_json::json!({"valid": true, "entries": entries})
.to_string()
.into_bytes(),
www_authenticate: None,
extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
},
Err(err) => HttpResponse {
status: 409,
content_type: "application/json; charset=utf-8".into(),
body: serde_json::json!({"valid": false, "error": err})
.to_string()
.into_bytes(),
www_authenticate: None,
extra_headers: vec![("X-Content-Type-Options".into(), "nosniff".into())],
},
}
}
pub fn record_audit(common_dir: &Path, actor: &str, action: &str, target: &str) {
use std::io::Write as _;
let mut store = ForgeStore::lock_mut(common_dir);
let next_id = store.audit_log.iter().map(|a| a.id).max().unwrap_or(0) + 1;
let entry = AuditEntry {
id: next_id,
actor: actor.to_string(),
action: action.to_string(),
target: target.to_string(),
created_at: now_unix(),
};
let forge_dir = common_dir.join("arks-forge");
let _ = fs::create_dir_all(&forge_dir);
let jsonl_path = forge_dir.join("audit.jsonl");
let prev_hash = last_audit_chain_hash(&jsonl_path);
let entry_hash = compute_audit_entry_hash(&prev_hash, &entry);
let chained = serde_json::json!({
"id": entry.id,
"actor": entry.actor,
"action": entry.action,
"target": entry.target,
"created_at": entry.created_at,
"prev_hash": prev_hash,
"entry_hash": entry_hash,
});
if let Ok(line) = serde_json::to_string(&chained) {
if let Ok(mut f) = fs::OpenOptions::new()
.create(true)
.append(true)
.open(&jsonl_path)
{
let _ = writeln!(f, "{line}");
let _ = f.sync_all();
}
}
store.audit_log.push(entry);
let max_entries = std::env::var("ARKS_AUDIT_MAX_ENTRIES")
.ok()
.and_then(|v| v.trim().parse::<usize>().ok())
.filter(|&n| n > 0)
.unwrap_or(10_000);
if store.audit_log.len() > max_entries {
let excess = store.audit_log.len() - max_entries;
store.audit_log.drain(0..excess);
}
let _ = store.commit();
}
pub fn render_admin_dashboard(repo: &Repository, ctx: &RepoContext, query: &str) -> HttpResponse {
let m = ctx.mount_prefix();
let csrf = ctx.csrf_hidden();
let store = ctx.forge_store(repo.common_dir());
let params = parse_form_urlencoded(query.as_bytes());
let actor_filter = params.get("actor").map(|s| s.trim()).unwrap_or("");
let action_filter = params.get("action").map(|s| s.trim()).unwrap_or("");
let mut user_rows = String::new();
for u in &store.users {
let twofa = if u.totp_secret_b32.is_some() {
"<span class=\"badge badge-green\">2FA On</span>"
} else {
"<span class=\"badge\">2FA Off</span>"
};
user_rows.push_str(&format!(
"<tr><td><strong>@{}</strong> {twofa}</td>\
<td class=\"mono\">{}</td>\
<td class=\"u-right\">\
<form method=\"post\" action=\"{m}/admin/users/{}/role\" class=\"u-inline-flex u-gap-1\">\
{csrf}\
<select class=\"input\" name=\"role\">\
<option value=\"admin\">admin</option>\
<option value=\"maintainer\">maintainer</option>\
<option value=\"reader\">reader</option>\
</select>\
<button class=\"btn\" type=\"submit\">Update Role</button>\
</form></td></tr>",
html_escape(&u.username),
html_escape(&u.role),
html_escape(&u.username),
));
}
if user_rows.is_empty() {
user_rows
.push_str("<tr><td colspan=\"3\" class=\"muted\">No registered users yet.</td></tr>");
}
let mut audit_rows = String::new();
for a in store
.audit_log
.iter()
.rev()
.filter(|a| actor_filter.is_empty() || a.actor.contains(actor_filter))
.filter(|a| action_filter.is_empty() || a.action.contains(action_filter))
.take(100)
{
audit_rows.push_str(&format!(
"<tr><td><strong>@{}</strong></td><td class=\"mono\">{}</td>\
<td>{}</td><td class=\"muted\">{}</td></tr>",
html_escape(&a.actor),
html_escape(&a.action),
html_escape(&a.target),
html_escape(&format_timestamp(a.created_at)),
));
}
if audit_rows.is_empty() {
audit_rows.push_str(
"<tr><td colspan=\"4\" class=\"muted\">No audit log events recorded yet.</td></tr>",
);
}
let body = format!(
"<div class=\"toolbar\"><strong>Admin Dashboard & Audit Log</strong> \
<a class=\"btn\" href=\"{m}/admin/audit.csv\">Export CSV</a> \
<a class=\"btn\" href=\"{m}/admin/audit.jsonl\">Export JSONL</a></div>\
<div class=\"card\"><div class=\"card-header\"><strong>Users & Roles</strong></div>\
<table class=\"tree-table\">{user_rows}</table></div>\
<div class=\"card\"><div class=\"card-header\"><strong>Audit Log</strong></div>\
<table class=\"tree-table\">{audit_rows}</table></div>"
);
render_page(
200,
ctx,
ActiveTab::Settings,
&format!("Admin — {}", ctx.name),
&body,
)
}
pub fn handle_admin_update_role(
repo: &Repository,
ctx: &RepoContext,
username: &str,
req: &HttpRequest,
) -> HttpResponse {
let form = parse_form_urlencoded(&req.body);
let new_role = match form.get("role").map(|s| s.trim()) {
Some("admin") => "admin",
Some("maintainer") => "maintainer",
Some("reader") => "reader",
_ => {
return render_page(
400,
ctx,
ActiveTab::Settings,
"Invalid role",
"Role must be one of: admin, maintainer, reader.",
);
}
};
let mut store = ForgeStore::lock_mut(repo.common_dir());
let actor = super::auth_api::resolve_actor(&store, req)
.map(|(u, _)| u)
.unwrap_or_else(|| "admin".into());
if would_remove_last_admin(&store.users, username, new_role) {
return render_page(
409,
ctx,
ActiveTab::Settings,
"Cannot demote the last admin",
"At least one admin must remain. Promote another user to admin first.",
);
}
if let Some(u) = store.users.iter_mut().find(|u| u.username == username) {
u.role = new_role.to_string();
let _ = store.commit();
record_audit(
repo.common_dir(),
&actor,
"user.role_updated",
&format!("{username} -> {new_role}"),
);
}
ctx.redirect("/admin")
}
pub(crate) fn would_remove_last_admin(
users: &[super::store::UserAccount],
username: &str,
new_role: &str,
) -> bool {
if new_role == "admin" {
return false;
}
let target_is_admin = users
.iter()
.any(|u| u.username == username && u.role == "admin");
let admins = users.iter().filter(|u| u.role == "admin").count();
target_is_admin && admins == 1
}
fn is_safe_artifact_name(name: &str) -> bool {
!name.is_empty()
&& name.len() <= 120
&& !name.contains("..")
&& !name.contains('/')
&& !name.contains('\\')
&& !name.starts_with('.')
}
pub fn handle_upload_artifact(
repo: &Repository,
ctx: &RepoContext,
id_str: &str,
req: &HttpRequest,
) -> HttpResponse {
let Ok(run_id) = id_str.parse::<u64>() else {
return render_page(
400,
ctx,
ActiveTab::Actions,
"Invalid run ID",
"Invalid run ID.",
);
};
let form = parse_form_urlencoded(&req.body);
let name = form.get("name").map(|s| s.trim()).unwrap_or("");
if !is_safe_artifact_name(name) {
return render_page(
400,
ctx,
ActiveTab::Actions,
"Invalid artifact",
"Invalid artifact name.",
);
}
let content = form
.get("content")
.cloned()
.unwrap_or_default()
.into_bytes();
let dir = repo
.common_dir()
.join("arks-forge")
.join("artifacts")
.join(format!("run-{run_id}"));
if fs::create_dir_all(&dir).is_err() || fs::write(dir.join(name), &content).is_err() {
return render_page(
500,
ctx,
ActiveTab::Actions,
"Error",
"Failed to store artifact.",
);
}
let mut hasher = Sha256::new();
hasher.update(&content);
let digest = hasher.finalize();
let mut sha = String::with_capacity(64);
for b in digest {
use std::fmt::Write as _;
let _ = write!(&mut sha, "{b:02x}");
}
let mut store = ForgeStore::lock_mut(repo.common_dir());
store
.action_artifacts
.retain(|a| !(a.run_id == run_id && a.name == name));
store.action_artifacts.push(ActionArtifact {
run_id,
name: name.to_string(),
sha256: sha,
size_bytes: content.len(),
created_at: now_unix(),
});
let _ = store.commit();
ctx.redirect(&format!("/actions/runs/{run_id}"))
}
pub fn handle_download_artifact(repo: &Repository, id_str: &str, name: &str) -> HttpResponse {
let Ok(run_id) = id_str.parse::<u64>() else {
return HttpResponse {
status: 404,
content_type: "text/plain; charset=utf-8".into(),
body: b"Artifact not found\n".to_vec(),
www_authenticate: None,
extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
};
};
if !is_safe_artifact_name(name) {
return HttpResponse {
status: 400,
content_type: "text/plain; charset=utf-8".into(),
body: b"Invalid artifact name\n".to_vec(),
www_authenticate: None,
extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
};
}
let path = repo
.common_dir()
.join("arks-forge")
.join("artifacts")
.join(format!("run-{run_id}"))
.join(name);
let Ok(bytes) = fs::read(&path) else {
return HttpResponse {
status: 404,
content_type: "text/plain; charset=utf-8".into(),
body: b"Artifact not found\n".to_vec(),
www_authenticate: None,
extra_headers: vec![("Content-Security-Policy".into(), WEB_UI_CSP.into())],
};
};
HttpResponse {
status: 200,
content_type: "application/octet-stream".into(),
body: bytes,
www_authenticate: None,
extra_headers: vec![
("Content-Security-Policy".into(), WEB_UI_CSP.into()),
("X-Content-Type-Options".into(), "nosniff".into()),
],
}
}
pub fn encode_base32(bytes: &[u8]) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
let mut out = String::new();
let mut bits: u32 = 0;
let mut bit_count: u8 = 0;
for &b in bytes {
bits = (bits << 8) | (b as u32);
bit_count += 8;
while bit_count >= 5 {
bit_count -= 5;
let idx = ((bits >> bit_count) & 0x1f) as usize;
out.push(ALPHABET[idx] as char);
}
}
if bit_count > 0 {
let idx = ((bits << (5 - bit_count)) & 0x1f) as usize;
out.push(ALPHABET[idx] as char);
}
out
}
fn render_totp_qr_svg(uri: &str) -> String {
let mut svg = String::from(
"<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 21 21\" width=\"126\" height=\"126\" role=\"img\" aria-label=\"TOTP setup matrix\" class=\"qr-box\">",
);
let digest = Sha256::digest(uri.as_bytes());
for y in 0..21usize {
for x in 0..21usize {
let in_finder = (x < 7 && y < 7) || (x >= 14 && y < 7) || (x < 7 && y >= 14);
let dark = if in_finder {
let lx = if x >= 14 { x - 14 } else { x };
let ly = if y >= 14 { y - 14 } else { y };
lx == 0
|| lx == 6
|| ly == 0
|| ly == 6
|| ((2..=4).contains(&lx) && (2..=4).contains(&ly))
} else {
let bit_idx = (y * 21 + x) % 256;
(digest[bit_idx / 8] >> (bit_idx % 8)) & 1 == 1
};
if dark {
svg.push_str(&format!(
"<rect x=\"{x}\" y=\"{y}\" width=\"1\" height=\"1\" fill=\"#111\"/>"
));
}
}
}
svg.push_str("</svg>");
svg
}
fn generate_recovery_codes() -> Vec<String> {
let mut codes = Vec::with_capacity(8);
for _ in 0..8 {
let raw = super::auth_api::csprng_bytes(4);
codes.push(format!(
"{:02x}{:02x}-{:02x}{:02x}",
raw[0], raw[1], raw[2], raw[3]
));
}
codes
}
pub fn render_2fa_settings(
repo: &Repository,
ctx: &RepoContext,
req: &HttpRequest,
) -> HttpResponse {
let m = ctx.mount_prefix();
let csrf = ctx.csrf_hidden();
let store = ctx.forge_store(repo.common_dir());
let actor = super::auth_api::resolve_actor(&store, req).map(|(u, _)| u);
let enabled = actor.as_deref().is_some_and(|u| {
store
.users
.iter()
.any(|a| a.username == u && a.totp_secret_b32.is_some())
});
let status_badge = if enabled {
"<span class=\"badge badge-green\">TOTP 2FA Enabled</span>"
} else {
"<span class=\"badge\">TOTP 2FA Disabled</span>"
};
let generated_secret = encode_base32(&super::auth_api::csprng_bytes(20));
let account_label = actor.as_deref().unwrap_or("user");
let otpauth_uri =
format!("otpauth://totp/arks:{account_label}?secret={generated_secret}&issuer=arks");
let qr_svg = render_totp_qr_svg(&otpauth_uri);
let disable_section = if enabled {
format!(
"<div class=\"card u-mt-3\"><div class=\"card-header\"><strong>Disable 2FA</strong></div>\
<form class=\"card-body\" method=\"post\" action=\"{m}/settings/2fa/disable\">\
{csrf}\
<button class=\"btn\" type=\"submit\">Disable TOTP 2FA</button>\
</form></div>"
)
} else {
String::new()
};
let body = format!(
"<div class=\"toolbar\"><a href=\"{m}/settings\">← Settings</a> \
<strong>Two-Factor Authentication (RFC 6238 TOTP)</strong> {status_badge}</div>\
<div class=\"card\"><div class=\"card-header\"><strong>Enroll TOTP Authenticator</strong></div>\
<div class=\"card-body u-flex u-gap-4 u-wrap u-items-center\">\
<div>{qr_svg}</div>\
<div class=\"u-grow u-min-w-lg\">\
<div class=\"muted u-mb-1\">Auto-generated provisioning URI:</div>\
<code class=\"mono u-break-all u-mb-25\">{}</code>\
<form method=\"post\" action=\"{m}/settings/2fa\" class=\"u-stack u-gap-25\">\
{csrf}\
<input class=\"input mono\" type=\"text\" name=\"secret\" value=\"{}\" required />\
<input class=\"input\" type=\"text\" name=\"code\" placeholder=\"Current 6-digit TOTP code\" required />\
<button class=\"btn btn-primary\" type=\"submit\">Verify & Enable 2FA</button>\
</form>\
</div>\
</div></div>{disable_section}",
html_escape(&otpauth_uri),
html_escape(&generated_secret),
);
render_page(
200,
ctx,
ActiveTab::Settings,
&format!("2FA Settings — {}", ctx.name),
&body,
)
}
pub fn handle_enable_2fa(repo: &Repository, ctx: &RepoContext, req: &HttpRequest) -> HttpResponse {
let m = ctx.mount_prefix();
let form = parse_form_urlencoded(&req.body);
let secret = form
.get("secret")
.map(|s| s.trim().to_ascii_uppercase())
.unwrap_or_default();
let code = form.get("code").map(|s| s.trim()).unwrap_or("");
if !verify_totp_window(&secret, code, now_unix()) {
return render_page(
400,
ctx,
ActiveTab::Settings,
"Invalid TOTP code",
"<div class=\"card\"><div class=\"card-body\">TOTP verification failed. Check secret and current 6-digit code.</div></div>",
);
}
let mut store = ForgeStore::lock_mut(repo.common_dir());
let Some((user, _)) = super::auth_api::resolve_actor(&store, req) else {
return render_page(
401,
ctx,
ActiveTab::Settings,
"Sign in required",
"Sign in first.",
);
};
let recovery = generate_recovery_codes();
if let Some(acct) = store.users.iter_mut().find(|u| u.username == user) {
acct.totp_secret_b32 = Some(secret);
acct.recovery_codes = recovery.clone();
let _ = store.commit();
record_audit(repo.common_dir(), &user, "user.2fa_enabled", &user);
}
let codes_html: String = recovery
.iter()
.map(|c| format!("<li><code class=\"mono\">{}</code></li>", html_escape(c)))
.collect();
let body = format!(
"<div class=\"card\"><div class=\"card-header\"><strong>2FA Enabled — Save Your Recovery Codes</strong></div>\
<div class=\"card-body\"><p>Store these 8 one-time recovery codes in a safe place. Each code can be used once in place of a TOTP code:</p>\
<ul>{codes_html}</ul><a class=\"btn btn-primary\" href=\"{m}/settings/2fa\">Done</a></div></div>"
);
render_page(
200,
ctx,
ActiveTab::Settings,
&format!("2FA Recovery Codes — {}", ctx.name),
&body,
)
}
pub fn handle_disable_2fa(repo: &Repository, ctx: &RepoContext, req: &HttpRequest) -> HttpResponse {
let mut store = ForgeStore::lock_mut(repo.common_dir());
let Some((user, _)) = super::auth_api::resolve_actor(&store, req) else {
return render_page(
401,
ctx,
ActiveTab::Settings,
"Sign in required",
"Sign in first.",
);
};
if let Some(acct) = store.users.iter_mut().find(|u| u.username == user) {
acct.totp_secret_b32 = None;
acct.recovery_codes.clear();
let _ = store.commit();
record_audit(repo.common_dir(), &user, "user.2fa_disabled", &user);
}
ctx.redirect("/settings/2fa")
}
pub fn decode_base32(input: &str) -> Option<Vec<u8>> {
let mut bits: u32 = 0;
let mut bit_count: u32 = 0;
let mut out = Vec::new();
for ch in input.bytes() {
if ch.is_ascii_whitespace() || ch == b'=' {
continue;
}
let v = match ch.to_ascii_uppercase() {
b'A'..=b'Z' => ch.to_ascii_uppercase() - b'A',
b'2'..=b'7' => ch - b'2' + 26,
_ => return None,
};
bits = (bits << 5) | u32::from(v);
bit_count += 5;
if bit_count >= 8 {
bit_count -= 8;
out.push(((bits >> bit_count) & 0xff) as u8);
}
}
if out.is_empty() { None } else { Some(out) }
}
fn sha1_digest(data: &[u8]) -> [u8; 20] {
let mut h0: u32 = 0x6745_2301;
let mut h1: u32 = 0xefcd_ab89;
let mut h2: u32 = 0x98ba_dcfe;
let mut h3: u32 = 0x1032_5476;
let mut h4: u32 = 0xc3d2_e1f0;
let bit_len = (data.len() as u64).wrapping_mul(8);
let mut msg = data.to_vec();
msg.push(0x80);
while msg.len() % 64 != 56 {
msg.push(0);
}
msg.extend_from_slice(&bit_len.to_be_bytes());
for chunk in msg.chunks_exact(64) {
let mut w = [0u32; 80];
for (i, b) in chunk.chunks_exact(4).enumerate() {
w[i] = u32::from_be_bytes([b[0], b[1], b[2], b[3]]);
}
for i in 16..80 {
w[i] = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]).rotate_left(1);
}
let (mut a, mut b, mut c, mut d, mut e) = (h0, h1, h2, h3, h4);
for (i, &wi) in w.iter().enumerate() {
let (f, k) = match i {
0..=19 => ((b & c) | ((!b) & d), 0x5a82_7999u32),
20..=39 => (b ^ c ^ d, 0x6ed9_eba1u32),
40..=59 => ((b & c) | (b & d) | (c & d), 0x8f1b_bcdc),
_ => (b ^ c ^ d, 0xca62_c1d6),
};
let temp = a
.rotate_left(5)
.wrapping_add(f)
.wrapping_add(e)
.wrapping_add(k)
.wrapping_add(wi);
e = d;
d = c;
c = b.rotate_left(30);
b = a;
a = temp;
}
h0 = h0.wrapping_add(a);
h1 = h1.wrapping_add(b);
h2 = h2.wrapping_add(c);
h3 = h3.wrapping_add(d);
h4 = h4.wrapping_add(e);
}
let mut out = [0u8; 20];
out[0..4].copy_from_slice(&h0.to_be_bytes());
out[4..8].copy_from_slice(&h1.to_be_bytes());
out[8..12].copy_from_slice(&h2.to_be_bytes());
out[12..16].copy_from_slice(&h3.to_be_bytes());
out[16..20].copy_from_slice(&h4.to_be_bytes());
out
}
fn hmac_sha1(key: &[u8], msg: &[u8]) -> [u8; 20] {
let mut k = [0u8; 64];
if key.len() > 64 {
k[..20].copy_from_slice(&sha1_digest(key));
} else {
k[..key.len()].copy_from_slice(key);
}
let mut ipad = [0x36u8; 64];
let mut opad = [0x5cu8; 64];
for i in 0..64 {
ipad[i] ^= k[i];
opad[i] ^= k[i];
}
let mut inner = Vec::with_capacity(64 + msg.len());
inner.extend_from_slice(&ipad);
inner.extend_from_slice(msg);
let inner_hash = sha1_digest(&inner);
let mut outer = Vec::with_capacity(84);
outer.extend_from_slice(&opad);
outer.extend_from_slice(&inner_hash);
sha1_digest(&outer)
}
pub fn hotp_6(secret: &[u8], counter: u64) -> String {
let mac = hmac_sha1(secret, &counter.to_be_bytes());
let offset = (mac[19] & 0x0f) as usize;
let bin = ((u32::from(mac[offset]) & 0x7f) << 24)
| (u32::from(mac[offset + 1]) << 16)
| (u32::from(mac[offset + 2]) << 8)
| u32::from(mac[offset + 3]);
format!("{:06}", bin % 1_000_000)
}
#[allow(dead_code)]
pub fn totp_6(secret: &[u8], unix_ts: i64) -> String {
let step = (unix_ts.max(0) as u64) / 30;
hotp_6(secret, step)
}
pub fn verify_totp_window(secret_b32: &str, code: &str, now_ts: i64) -> bool {
let Some(secret) = decode_base32(secret_b32) else {
return false;
};
let clean = code.trim();
if clean.len() != 6 || !clean.bytes().all(|b| b.is_ascii_digit()) {
return false;
}
let base_step = (now_ts.max(0) as u64) / 30;
for delta in [-1i64, 0, 1] {
let step = base_step.saturating_add_signed(delta);
if hotp_6(&secret, step) == clean {
return true;
}
}
false
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rfc_4226_and_6238_totp_known_answer_vectors() {
let secret = b"12345678901234567890";
assert_eq!(hotp_6(secret, 0), "755224");
assert_eq!(hotp_6(secret, 1), "287082");
assert_eq!(hotp_6(secret, 2), "359152");
assert_eq!(totp_6(secret, 59), "287082");
assert!(verify_totp_window(
"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
"287082",
59
));
assert!(!verify_totp_window(
"GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
"000000",
59
));
}
}