arks-server 1.3.11

Git server: upload-pack / receive-pack + smart/dumb HTTP + daemon (M11/M25)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
//! Enterprise Admin Dashboard, Audit Log, Actions Artifacts, and Pure-Rust RFC 6238 TOTP 2FA
//! for `arks serve` Web UI (Wave 5 — B6/B7).
//!
//! Zero external crypto crates added for HOTP/TOTP: pure-Rust SHA-1 (FIPS 180-4),
//! HMAC-SHA1 (RFC 2104), HOTP (RFC 4226), and TOTP (RFC 6238).

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())
}

/// Verify the tamper-evident SHA-256 hash chain of `arks-forge/audit.jsonl`.
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)
}

/// Handle `GET /admin/audit/verify` — verifies the SHA-256 hash chain of `audit.jsonl`.
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())],
        },
    }
}

/// Record an audit event into `ForgeStore` and append a hash-chained record to `arks-forge/audit.jsonl`.
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();
}

/// Render `GET /admin` — Admin user role management & filterable/exportable Audit Log viewer.
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 &amp; 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 &amp; 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,
    )
}

/// Handle `POST /admin/users/<username>/role`.
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")
}

/// True when changing `username` to `new_role` would leave the store with zero admins.
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('.')
}

/// Handle `POST /actions/runs/<id>/artifacts` storing a workflow build artifact with SHA-256.
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}"))
}

/// Handle `GET /actions/runs/<id>/artifacts/<name>` serving a stored Actions build artifact.
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()),
        ],
    }
}

/// Encode bytes as RFC 4648 Base32 (uppercase, no padding) for TOTP secret generation.
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
}

/// Generate a pure-Rust inline SVG visual matrix for the `otpauth://` provisioning URI (zero CDN).
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
}

/// Generate 8 one-time recovery codes (`xxxx-xxxx`) from OS CSPRNG.
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
}

/// Render `GET /settings/2fa` — RFC 6238 TOTP Two-Factor Authentication enrollment.
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 &amp; 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,
    )
}

/// Handle `POST /settings/2fa` verifying a live 6-digit TOTP code before enabling 2FA.
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,
    )
}

/// Handle `POST /settings/2fa/disable` — disables TOTP 2FA for the signed-in user.
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")
}

/// Decode RFC 4648 Base32 (ignoring whitespace and `=` padding).
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) }
}

/// Pure-Rust SHA-1 (FIPS 180-4) used exclusively for RFC 4226/6238 HMAC-SHA1 TOTP.
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)
}

/// RFC 4226 6-digit HOTP value.
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)
}

/// RFC 6238 6-digit TOTP value (30-second time step).
#[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)
}

/// Verify a 6-digit TOTP code against a Base32 secret with ±1 step (30s) clock skew tolerance.
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() {
        // RFC 4226 Appendix D: secret = "12345678901234567890"
        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");
        // RFC 6238 Appendix B: t=59 => step=1 => 6-digit suffix of 94287082 is 287082
        assert_eq!(totp_6(secret, 59), "287082");
        // Base32 encoding of "12345678901234567890" is GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ
        assert!(verify_totp_window(
            "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
            "287082",
            59
        ));
        assert!(!verify_totp_window(
            "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
            "000000",
            59
        ));
    }
}