tsafe-cli 1.2.0

Local-first secrets runtime for developers — inject credentials via exec, never shell history or .env files
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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
//! One-time secret (OTS) share and receive command handlers.
//!
//! Implements `tsafe share-once` and `tsafe receive-once` — ephemeral secret
//! sharing via any HTTPS service that implements the OTS contract (POST /create,
//! GET/POST /consume).
//!
//! # OTS trust models
//!
//! Two contracts share this module:
//!
//! **1. Default — trusted-service plaintext transport (ADR-014).** The OTS
//! service receives the secret value in transit over HTTPS. There is no
//! client-side encryption on this path. Appropriate for moderate-trust use
//! cases where you control or trust the OTS service. Do not use it for secrets
//! that must not be readable by the OTS service. Proof coverage: HTTPS
//! enforcement only (`resolve_ots_base_url` rejects non-HTTPS origins;
//! `cmd_receive_once` rejects non-HTTPS consume URLs).
//!
//! **2. `--e2e` — tsnap zero-knowledge.** The secret is encrypted client-side
//! with a random AES-256-GCM key *before* upload; the service stores only
//! ciphertext + nonce + `SHA-256(key)` and never receives the content key,
//! which lives solely in the URL fragment (`#k=`). This targets the tsnap
//! contract (default `https://tsnap.algol.cc`, override `TSAFE_TSNAP_BASE_URL`)
//! and is wire-compatible with the browser client. `receive-once --e2e` writes
//! the decrypted value into the vault (requires `--store`) and never prints it.
//! See the `tsnap_e2e` module below for the exact wire format.

use std::collections::HashMap;

use anyhow::{Context, Result};
use colored::Colorize;
use tsafe_core::{audit::AuditEntry, events::emit_event};

use crate::helpers::*;

const MAX_OTS_TRANSIENT_RETRIES: u32 = 3;
const DEFAULT_OTS_RETRY_SECS: u64 = 2;

type OtsHttpResult<T> = std::result::Result<T, Box<ureq::Error>>;

#[derive(Clone, Copy)]
struct OtsRetryPolicy {
    max_transient_retries: u32,
    base_retry_secs: u64,
}

impl OtsRetryPolicy {
    fn default_policy() -> Self {
        Self {
            max_transient_retries: MAX_OTS_TRANSIENT_RETRIES,
            base_retry_secs: DEFAULT_OTS_RETRY_SECS,
        }
    }
}

// ── OTS URL helpers ───────────────────────────────────────────────────────────

fn resolve_ots_base_url() -> Result<String> {
    let url = std::env::var("TSAFE_OTS_BASE_URL")
        .or_else(|_| std::env::var("TSAFE_OTS_URL"))
        .map_err(|_| {
            anyhow::anyhow!(
                "TSAFE_OTS_BASE_URL is not set. Export it to your one-time secret (OTS) service HTTPS origin, \
                 e.g. https://ots.example.com (no path). The CLI POSTs JSON to {{origin}}{{TSAFE_OTS_CREATE_PATH}} (default /create)."
            )
        })?;
    let trimmed = url.trim_end_matches('/');
    if trimmed.is_empty() {
        anyhow::bail!("TSAFE_OTS_BASE_URL must not be empty");
    }
    let allow_insecure = std::env::var("TSAFE_OTS_ALLOW_INSECURE")
        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
        .unwrap_or(false);
    if !allow_insecure && !trimmed.starts_with("https://") {
        anyhow::bail!("TSAFE_OTS_BASE_URL must start with https:// — secrets must not be sent over plain HTTP");
    }
    Ok(trimmed.to_string())
}

fn ots_create_url(base: &str) -> String {
    let path = std::env::var("TSAFE_OTS_CREATE_PATH").unwrap_or_else(|_| "/create".into());
    let path = if path.starts_with('/') {
        path
    } else {
        format!("/{path}")
    };
    format!("{base}{path}")
}

/// Parse OTS consume response: JSON (`secret` / `plaintext` / `value`) or HTML `#secret-content`.
fn parse_ots_response_body(body: &str) -> Option<String> {
    let trimmed = body.trim();
    if let Ok(v) = serde_json::from_str::<serde_json::Value>(trimmed) {
        if let Some(s) = v.get("secret").and_then(|x| x.as_str()) {
            return Some(s.to_string());
        }
        if let Some(s) = v.get("plaintext").and_then(|x| x.as_str()) {
            return Some(s.to_string());
        }
        if let Some(s) = v.get("value").and_then(|x| x.as_str()) {
            return Some(s.to_string());
        }
    }
    trimmed
        .split_once("id=\"secret-content\"")
        .and_then(|(_, after)| after.split_once('>'))
        .and_then(|(_, after)| after.split_once('<'))
        .map(|(val, _)| val.trim().to_owned())
}

fn read_ots_response_body(response: ureq::Response) -> Result<String> {
    response
        .into_string()
        .context("failed to read OTS service response")
}

fn is_retryable_ots_transport_error(message: &str) -> bool {
    let msg = message.to_ascii_lowercase();
    msg.contains("timed out")
        || msg.contains("timeout")
        || msg.contains("connection reset")
        || msg.contains("connection refused")
        || msg.contains("econnreset")
        || msg.contains("econnrefused")
        || msg.contains("temporar")
        // Windows WSA error wording — the substring "connection refused" never
        // appears in WSAECONNREFUSED messages, so add the platform-specific
        // signals: "actively refused" (WSAECONNREFUSED), "forcibly closed"
        // (WSAECONNRESET), and the os-error-code form. Without these the
        // retry/fallback path silently no-ops on Windows callers.
        || msg.contains("actively refused")
        || msg.contains("forcibly closed")
        || msg.contains("os error 10054") // WSAECONNRESET
        || msg.contains("os error 10060") // WSAETIMEDOUT
        || msg.contains("os error 10061") // WSAECONNREFUSED
        || msg.contains("os error 10065") // WSAEHOSTUNREACH
}

fn jittered_ots_delay_secs(base_secs: u64) -> u64 {
    if base_secs == 0 {
        return 0;
    }
    let jitter_cap = std::cmp::max(1, base_secs / 4);
    let nanos = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.subsec_nanos() as u64)
        .unwrap_or(0);
    base_secs + (nanos % (jitter_cap + 1))
}

fn call_ots_with_transport_retry(
    make_request: impl FnMut() -> OtsHttpResult<ureq::Response>,
) -> OtsHttpResult<ureq::Response> {
    call_ots_with_transport_retry_policy(OtsRetryPolicy::default_policy(), make_request)
}

fn call_ots_with_transport_retry_policy(
    policy: OtsRetryPolicy,
    mut make_request: impl FnMut() -> OtsHttpResult<ureq::Response>,
) -> OtsHttpResult<ureq::Response> {
    let mut transient_attempt = 0u32;
    loop {
        match make_request() {
            Ok(resp) => return Ok(resp),
            Err(err)
                if matches!(err.as_ref(), ureq::Error::Transport(t) if transient_attempt < policy.max_transient_retries
                    && is_retryable_ots_transport_error(t.to_string().as_str())) =>
            {
                let backoff = policy.base_retry_secs * 2u64.pow(transient_attempt);
                let wait = std::cmp::min(jittered_ots_delay_secs(backoff), 30);
                std::thread::sleep(std::time::Duration::from_secs(wait));
                transient_attempt += 1;
            }
            Err(err) => return Err(err),
        }
    }
}

fn consume_ots_via_get_with(
    policy: OtsRetryPolicy,
    mut get_call: impl FnMut() -> OtsHttpResult<ureq::Response>,
) -> Result<String> {
    match call_ots_with_transport_retry_policy(policy, &mut get_call) {
        Ok(response) => read_ots_response_body(response),
        Err(err) => match *err {
            ureq::Error::Status(404 | 405 | 501, _) => {
                anyhow::bail!("secret not found — already consumed or expired")
            }
            ureq::Error::Status(code, response) => {
                let body = response.into_string().unwrap_or_default();
                anyhow::bail!("OTS service returned HTTP {code} — {body}");
            }
            other => Err(anyhow::Error::new(other).context("failed to reach OTS service")),
        },
    }
}

fn consume_ots_response_body_with(
    policy: OtsRetryPolicy,
    mut post_call: impl FnMut() -> OtsHttpResult<ureq::Response>,
    mut get_call: impl FnMut() -> OtsHttpResult<ureq::Response>,
) -> Result<String> {
    // Try POST first (standard OTS contract). Fall back to GET on 404/405/501:
    // some OTS server variants (e.g. onetimesecret.com) only expose a GET endpoint
    // and return 405 on POST; others return 404 or 501 for unsupported methods.
    match call_ots_with_transport_retry_policy(policy, &mut post_call) {
        Ok(response) => return read_ots_response_body(response),
        Err(err) => match *err {
            ureq::Error::Status(404, _) => {
                return consume_ots_via_get_with(policy, &mut get_call);
            }
            ureq::Error::Status(405 | 501, _) => {}
            ureq::Error::Status(code, response) => {
                let body = response.into_string().unwrap_or_default();
                anyhow::bail!("OTS service returned HTTP {code} — {body}");
            }
            ureq::Error::Transport(t)
                if is_retryable_ots_transport_error(t.to_string().as_str()) =>
            {
                return consume_ots_via_get_with(policy, &mut get_call);
            }
            other => return Err(anyhow::Error::new(other).context("failed to reach OTS service")),
        },
    }

    consume_ots_via_get_with(policy, get_call)
}

fn consume_ots_response_body(agent: &ureq::Agent, consume_url: &str) -> Result<String> {
    consume_ots_response_body_with(
        OtsRetryPolicy::default_policy(),
        || agent.post(consume_url).call().map_err(Box::new),
        || agent.get(consume_url).call().map_err(Box::new),
    )
}

// ── Command handlers ──────────────────────────────────────────────────────────

pub(crate) fn cmd_share_once(profile: &str, key: &str, ttl: &str, e2e: bool) -> Result<()> {
    let vault = open_vault(profile)?;
    let value = vault.get(key)?;

    if e2e {
        #[cfg(feature = "ots-sharing")]
        {
            return tsnap_share_once(profile, key, ttl, value.as_bytes());
        }
        #[cfg(not(feature = "ots-sharing"))]
        {
            let _ = (ttl, &value);
            anyhow::bail!("--e2e (tsnap zero-knowledge) requires the 'ots-sharing' feature");
        }
    }

    let base = resolve_ots_base_url()?;
    let url = ots_create_url(&base);
    let body = serde_json::json!({ "secret": &*value, "ttl": ttl });
    let agent = build_http_agent();

    let resp = match call_ots_with_transport_retry(|| {
        agent
            .post(&url)
            .set("Content-Type", "application/json")
            .send_json(body.clone())
            .map_err(Box::new)
    }) {
        Ok(r) => r,
        Err(err) => match *err {
            ureq::Error::Status(code, response) => {
                let server_msg = response.into_string().unwrap_or_default();
                anyhow::bail!("OTS service returned HTTP {code} — {server_msg}");
            }
            other => {
                return Err(anyhow::Error::new(other).context(format!(
                    "failed to reach OTS service at {url} — check TSAFE_OTS_BASE_URL"
                )));
            }
        },
    };

    let payload: serde_json::Value = resp.into_json().context(
        "OTS service returned an unexpected response (expected JSON with a \"url\" field)",
    )?;

    let one_time_url = payload["url"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("OTS response missing 'url' field"))?;

    audit(profile)
        .append(&AuditEntry::success(profile, "share-once", Some(key)))
        .ok();
    emit_event(profile, "share-once", Some(key));
    println!("{} One-time link (expires: {ttl}):", "".green());
    println!("{one_time_url}");
    println!(
        "{} Share this URL — retrieve once per your OTS server policy.",
        "i".blue()
    );
    Ok(())
}

pub(crate) fn cmd_receive_once(
    profile: &str,
    url: &str,
    store: Option<&str>,
    e2e: bool,
) -> Result<()> {
    if e2e {
        #[cfg(feature = "ots-sharing")]
        {
            return tsnap_receive_once(profile, url, store);
        }
        #[cfg(not(feature = "ots-sharing"))]
        {
            let _ = (url, store);
            anyhow::bail!("--e2e (tsnap zero-knowledge) requires the 'ots-sharing' feature");
        }
    }

    let consume_url = url.split_once('#').map(|(b, _)| b).unwrap_or(url);

    let allow_insecure = std::env::var("TSAFE_OTS_ALLOW_INSECURE")
        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
        .unwrap_or(false);
    if !allow_insecure && !consume_url.starts_with("https://") {
        anyhow::bail!("URL must use https://");
    }

    let agent = build_http_agent();
    let body = consume_ots_response_body(&agent, consume_url)?;

    let plaintext = parse_ots_response_body(&body).ok_or_else(|| {
        anyhow::anyhow!(
            "could not parse secret from response (expected JSON with \"secret\" or HTML id=\"secret-content\") — link may already be consumed"
        )
    })?;

    match store {
        Some(key) => {
            let mut vault = open_vault(profile)?;
            vault.set(key, &plaintext, HashMap::new())?;
            audit(profile)
                .append(&AuditEntry::success(profile, "receive-once", Some(key)))
                .ok();
            emit_event(profile, "receive-once", Some(key));
            println!("{} Stored received secret under key '{key}'.", "".green());
        }
        None => {
            audit(profile)
                .append(&AuditEntry::success(profile, "receive-once", None))
                .ok();
            emit_event(profile, "receive-once", None);
            println!("{plaintext}");
        }
    }
    Ok(())
}

// ── tsnap zero-knowledge (e2e) path ───────────────────────────────────────────
//
// Unlike the plaintext OTS contract above, the tsnap path encrypts the secret
// with a random AES-256-GCM key *before* upload. The server stores only
// ciphertext + nonce + SHA-256(key); the 256-bit content key travels solely in
// the URL fragment (`#k=`), which browsers and `receive-once --e2e` keep
// client-side and never transmit. The wire format matches tsnap.algol.cc
// exactly — see `C:/Users/0ryant/prj/tsnap/docs/api.md` and
// `tsnap/src/index.ts` (`encryptForCreate` / `decryptPayload`): base64url
// (no padding), 12-byte nonce, ciphertext with the 16-byte GCM tag appended,
// `keyHash = SHA-256(raw 32 key bytes)`.
#[cfg(feature = "ots-sharing")]
mod tsnap_e2e {
    use aes_gcm::aead::{Aead, KeyInit};
    use aes_gcm::{Aes256Gcm, Key, Nonce};
    use anyhow::{anyhow, Context, Result};
    use base64::engine::general_purpose::URL_SAFE_NO_PAD;
    use base64::Engine as _;
    use rand::rngs::OsRng;
    use rand::RngCore;
    use sha2::{Digest, Sha256};
    use zeroize::Zeroize;

    pub(super) const TSNAP_DEFAULT_BASE_URL: &str = "https://tsnap.algol.cc";
    /// tsnap's enforced plaintext cap (16 KiB) — fail fast before encrypting.
    pub(super) const MAX_SECRET_BYTES: usize = 16 * 1024;

    pub(super) fn resolve_base_url() -> Result<String> {
        let url = std::env::var("TSAFE_TSNAP_BASE_URL")
            .unwrap_or_else(|_| TSNAP_DEFAULT_BASE_URL.to_string());
        let trimmed = url.trim_end_matches('/').to_string();
        if trimmed.is_empty() {
            anyhow::bail!("TSAFE_TSNAP_BASE_URL must not be empty");
        }
        let allow_insecure = std::env::var("TSAFE_OTS_ALLOW_INSECURE")
            .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
            .unwrap_or(false);
        if !allow_insecure && !trimmed.starts_with("https://") {
            anyhow::bail!(
                "tsnap base URL must start with https:// — the ciphertext upload must not go over plain HTTP"
            );
        }
        Ok(trimmed)
    }

    /// Map a `--ttl` string to one of tsnap's allowed `ttlSeconds` buckets.
    pub(super) fn ttl_to_seconds(ttl: &str) -> Result<u64> {
        let t = ttl.trim().to_ascii_lowercase();
        let secs = match t.as_str() {
            "5m" | "300" | "300s" => 300,
            "10m" | "600" | "600s" => 600,
            "1h" | "60m" | "3600" | "3600s" => 3600,
            "24h" | "1d" | "86400" | "86400s" => 86400,
            other => anyhow::bail!(
                "tsnap (--e2e) accepts only --ttl 5m, 10m, 1h, or 24h (got '{other}')"
            ),
        };
        Ok(secs)
    }

    /// Encrypt plaintext for the tsnap create contract.
    /// Returns `(ciphertext_b64url, nonce_b64url, key_b64url, key_hash_b64url)`.
    pub(super) fn encrypt(plaintext: &[u8]) -> Result<(String, String, String, String)> {
        let mut key_bytes = [0u8; 32];
        let mut nonce_bytes = [0u8; 12];
        OsRng.fill_bytes(&mut key_bytes);
        OsRng.fill_bytes(&mut nonce_bytes);

        let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&key_bytes));
        let ciphertext = cipher
            .encrypt(Nonce::from_slice(&nonce_bytes), plaintext)
            .map_err(|_| anyhow!("AES-256-GCM encryption failed"))?;
        let key_hash = Sha256::digest(key_bytes);

        let out = (
            URL_SAFE_NO_PAD.encode(&ciphertext),
            URL_SAFE_NO_PAD.encode(nonce_bytes),
            URL_SAFE_NO_PAD.encode(key_bytes),
            URL_SAFE_NO_PAD.encode(key_hash),
        );
        key_bytes.zeroize();
        nonce_bytes.zeroize();
        Ok(out)
    }

    /// From a tsnap share URL `https://host/s/<token>#k=<key>`, derive the
    /// consume endpoint URL and the raw 32-byte content key.
    pub(super) fn parse_share_url(url: &str) -> Result<(String, Vec<u8>)> {
        let (base, frag) = url
            .split_once('#')
            .ok_or_else(|| anyhow!("tsnap link is missing its '#k=' decryption-key fragment"))?;
        let key_b64 = frag
            .trim_start_matches('#')
            .split('&')
            .find_map(|kv| kv.strip_prefix("k="))
            .ok_or_else(|| anyhow!("tsnap link fragment has no 'k=' key parameter"))?;
        let key_bytes = URL_SAFE_NO_PAD
            .decode(key_b64.trim())
            .context("tsnap fragment key is not valid base64url")?;
        if key_bytes.len() != 32 {
            anyhow::bail!(
                "tsnap fragment key must decode to 32 bytes (got {})",
                key_bytes.len()
            );
        }
        let (origin, token) = base
            .rsplit_once("/s/")
            .ok_or_else(|| anyhow!("tsnap link path must look like /s/<token>"))?;
        let token = token.trim_end_matches('/');
        if token.is_empty() {
            anyhow::bail!("tsnap link has an empty token");
        }
        Ok((format!("{origin}/api/secrets/{token}/consume"), key_bytes))
    }

    pub(super) fn key_hash_b64(key_bytes: &[u8]) -> String {
        URL_SAFE_NO_PAD.encode(Sha256::digest(key_bytes))
    }

    pub(super) fn decrypt(
        key_bytes: &[u8],
        nonce_b64: &str,
        ciphertext_b64: &str,
    ) -> Result<Vec<u8>> {
        if key_bytes.len() != 32 {
            anyhow::bail!("tsnap content key must be 32 bytes");
        }
        let nonce = URL_SAFE_NO_PAD
            .decode(nonce_b64.trim())
            .context("tsnap nonce is not valid base64url")?;
        if nonce.len() != 12 {
            anyhow::bail!("tsnap nonce must be 12 bytes (got {})", nonce.len());
        }
        let ciphertext = URL_SAFE_NO_PAD
            .decode(ciphertext_b64.trim())
            .context("tsnap ciphertext is not valid base64url")?;
        let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(key_bytes));
        cipher
            .decrypt(Nonce::from_slice(&nonce), ciphertext.as_ref())
            .map_err(|_| {
                anyhow!("AES-256-GCM decryption failed — wrong key or corrupted ciphertext")
            })
    }
}

#[cfg(feature = "ots-sharing")]
fn tsnap_share_once(profile: &str, key: &str, ttl: &str, plaintext: &[u8]) -> Result<()> {
    if plaintext.len() > tsnap_e2e::MAX_SECRET_BYTES {
        anyhow::bail!(
            "tsnap secrets are capped at 16 KiB (got {} bytes) — share larger payloads another way",
            plaintext.len()
        );
    }
    let base = tsnap_e2e::resolve_base_url()?;
    let ttl_seconds = tsnap_e2e::ttl_to_seconds(ttl)?;
    let (ciphertext, nonce, key_b64, key_hash) = tsnap_e2e::encrypt(plaintext)?;

    let create_url = format!("{base}/api/secrets");
    let body = serde_json::json!({
        "ciphertext": ciphertext,
        "nonce": nonce,
        "keyHash": key_hash,
        "algorithm": "AES-256-GCM",
        "ttlSeconds": ttl_seconds,
    });
    let agent = build_http_agent();

    let resp = match call_ots_with_transport_retry(|| {
        agent
            .post(&create_url)
            .set("Content-Type", "application/json")
            .send_json(body.clone())
            .map_err(Box::new)
    }) {
        Ok(r) => r,
        Err(err) => match *err {
            ureq::Error::Status(code, response) => {
                let server_msg = response.into_string().unwrap_or_default();
                anyhow::bail!("tsnap returned HTTP {code} — {server_msg}");
            }
            other => {
                return Err(anyhow::Error::new(other).context(format!(
                    "failed to reach tsnap at {create_url} — override with TSAFE_TSNAP_BASE_URL"
                )));
            }
        },
    };

    let payload: serde_json::Value = resp
        .into_json()
        .context("tsnap returned an unexpected response (expected JSON with a \"url\" field)")?;
    let one_time_url = payload["url"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("tsnap response missing 'url' field"))?;
    // The content key is appended to the fragment exactly as the browser client
    // does (`result.url + "#k=" + key`); tsnap never sees it.
    let full = format!("{one_time_url}#k={key_b64}");

    audit(profile)
        .append(&AuditEntry::success(profile, "share-once", Some(key)))
        .ok();
    emit_event(profile, "share-once", Some(key));
    println!(
        "{} tsnap one-time link (zero-knowledge, expires: {ttl}):",
        "".green()
    );
    println!("{full}");
    println!(
        "{} The decryption key lives only in the URL fragment — tsnap never receives it. Retrieve with: tsafe receive-once --e2e '<URL>' --store <KEY>",
        "i".blue()
    );
    Ok(())
}

#[cfg(feature = "ots-sharing")]
fn tsnap_receive_once(profile: &str, url: &str, store: Option<&str>) -> Result<()> {
    let store_key = store.ok_or_else(|| {
        anyhow::anyhow!(
            "receive-once --e2e writes the secret into the vault and will not print it — re-run with --store <KEY>"
        )
    })?;

    let (consume_url, key_bytes) = tsnap_e2e::parse_share_url(url)?;

    let allow_insecure = std::env::var("TSAFE_OTS_ALLOW_INSECURE")
        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
        .unwrap_or(false);
    if !allow_insecure && !consume_url.starts_with("https://") {
        anyhow::bail!("tsnap consume URL must use https://");
    }

    let body = serde_json::json!({ "keyHash": tsnap_e2e::key_hash_b64(&key_bytes) });
    let agent = build_http_agent();

    let resp = match call_ots_with_transport_retry(|| {
        agent
            .post(&consume_url)
            .set("Content-Type", "application/json")
            .send_json(body.clone())
            .map_err(Box::new)
    }) {
        Ok(r) => r,
        Err(err) => match *err {
            ureq::Error::Status(404, _) => {
                anyhow::bail!("tsnap secret not found — already consumed, expired, or wrong key")
            }
            ureq::Error::Status(code, response) => {
                let server_msg = response.into_string().unwrap_or_default();
                anyhow::bail!("tsnap returned HTTP {code} — {server_msg}");
            }
            other => {
                return Err(anyhow::Error::new(other)
                    .context(format!("failed to reach tsnap at {consume_url}")));
            }
        },
    };

    let payload: serde_json::Value = resp
        .into_json()
        .context("tsnap consume returned an unexpected response (expected ciphertext + nonce)")?;
    let ciphertext = payload["ciphertext"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("tsnap consume response missing 'ciphertext'"))?;
    let nonce = payload["nonce"]
        .as_str()
        .ok_or_else(|| anyhow::anyhow!("tsnap consume response missing 'nonce'"))?;

    let plaintext_bytes = tsnap_e2e::decrypt(&key_bytes, nonce, ciphertext)?;
    let plaintext =
        String::from_utf8(plaintext_bytes).context("decrypted tsnap secret is not valid UTF-8")?;

    let mut vault = open_vault(profile)?;
    vault.set(store_key, &plaintext, HashMap::new())?;
    audit(profile)
        .append(&AuditEntry::success(
            profile,
            "receive-once",
            Some(store_key),
        ))
        .ok();
    emit_event(profile, "receive-once", Some(store_key));
    println!(
        "{} Decrypted tsnap secret stored under key '{store_key}'.",
        "".green()
    );
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(feature = "ots-sharing")]
    #[test]
    fn tsnap_encrypt_decrypt_round_trips() {
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        use base64::Engine as _;

        let secret = b"hunter2-correct-horse-battery-staple";
        let (ciphertext, nonce, key_b64, key_hash) = tsnap_e2e::encrypt(secret).unwrap();

        // key_hash is SHA-256 over the raw 32 key bytes, matching the browser client.
        let key_bytes = URL_SAFE_NO_PAD.decode(&key_b64).unwrap();
        assert_eq!(key_bytes.len(), 32);
        assert_eq!(tsnap_e2e::key_hash_b64(&key_bytes), key_hash);
        assert_eq!(URL_SAFE_NO_PAD.decode(&nonce).unwrap().len(), 12);

        let recovered = tsnap_e2e::decrypt(&key_bytes, &nonce, &ciphertext).unwrap();
        assert_eq!(recovered, secret);
    }

    #[cfg(feature = "ots-sharing")]
    #[test]
    fn tsnap_decrypt_rejects_wrong_key() {
        let (ciphertext, nonce, _key_b64, _key_hash) = tsnap_e2e::encrypt(b"top secret").unwrap();
        let wrong_key = [7u8; 32];
        assert!(tsnap_e2e::decrypt(&wrong_key, &nonce, &ciphertext).is_err());
    }

    #[cfg(feature = "ots-sharing")]
    #[test]
    fn tsnap_parse_share_url_derives_consume_endpoint_and_key() {
        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
        use base64::Engine as _;

        let key = URL_SAFE_NO_PAD.encode([3u8; 32]);
        let url = format!("https://tsnap.algol.cc/s/abc123#k={key}");
        let (consume_url, key_bytes) = tsnap_e2e::parse_share_url(&url).unwrap();
        assert_eq!(
            consume_url,
            "https://tsnap.algol.cc/api/secrets/abc123/consume"
        );
        assert_eq!(key_bytes, vec![3u8; 32]);
    }

    #[cfg(feature = "ots-sharing")]
    #[test]
    fn tsnap_parse_share_url_requires_fragment_key() {
        use base64::Engine as _;
        assert!(tsnap_e2e::parse_share_url("https://tsnap.algol.cc/s/abc123").is_err());
        // wrong-length key must be rejected
        let short = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([1u8; 16]);
        assert!(
            tsnap_e2e::parse_share_url(&format!("https://tsnap.algol.cc/s/abc123#k={short}"))
                .is_err()
        );
    }

    #[cfg(feature = "ots-sharing")]
    #[test]
    fn tsnap_ttl_buckets_map_and_reject() {
        assert_eq!(tsnap_e2e::ttl_to_seconds("5m").unwrap(), 300);
        assert_eq!(tsnap_e2e::ttl_to_seconds("10m").unwrap(), 600);
        assert_eq!(tsnap_e2e::ttl_to_seconds("1h").unwrap(), 3600);
        assert_eq!(tsnap_e2e::ttl_to_seconds("24h").unwrap(), 86400);
        assert_eq!(tsnap_e2e::ttl_to_seconds("86400").unwrap(), 86400);
        assert!(tsnap_e2e::ttl_to_seconds("7m").is_err());
    }

    #[test]
    fn retryable_ots_transport_classifier_detects_timeout() {
        assert!(is_retryable_ots_transport_error("operation timed out"));
        assert!(is_retryable_ots_transport_error("Connection reset by peer"));
        assert!(!is_retryable_ots_transport_error("invalid request payload"));
    }

    /// Regression guard for the Windows WSA wording the classifier missed
    /// across the entire 1.0.0–1.0.17 line. Without these inputs matching,
    /// `tsafe share` retried zero times on Windows transient failures even
    /// though the documented retry behaviour promised otherwise.
    /// See `RESEARCH-adversarial-2026-05-07-014523.md` §4 item 2 and the
    /// b6fb26d hygiene-pass commit. The strings are inputs to the classifier
    /// (not platform-generated), so this test is platform-portable.
    #[test]
    fn retryable_ots_transport_classifier_detects_windows_wsa_wording() {
        // Wording forms surfaced by `std::io::Error::Display` on Windows.
        assert!(is_retryable_ots_transport_error(
            "No connection could be made because the target machine actively refused it."
        ));
        assert!(is_retryable_ots_transport_error(
            "An existing connection was forcibly closed by the remote host."
        ));

        // os-error-code form — surfaces from `ureq`/`hyper` Display impls when
        // the underlying winsock error code is included in the formatted error.
        assert!(is_retryable_ots_transport_error(
            "transport error: io error: os error 10054"
        )); // WSAECONNRESET
        assert!(is_retryable_ots_transport_error(
            "transport error: io error: os error 10060"
        )); // WSAETIMEDOUT
        assert!(is_retryable_ots_transport_error(
            "transport error: io error: os error 10061"
        )); // WSAECONNREFUSED
        assert!(is_retryable_ots_transport_error(
            "transport error: io error: os error 10065"
        )); // WSAEHOSTUNREACH

        // Negative case — an unrelated 4xx/5xx error must NOT be classified
        // as a transport-retryable error.
        assert!(!is_retryable_ots_transport_error(
            "HTTP 401 Unauthorized: token expired"
        ));
        assert!(!is_retryable_ots_transport_error(
            "HTTP 422 Unprocessable Entity: invalid TTL"
        ));
    }

    #[test]
    fn jittered_ots_delay_stays_within_25_percent_bound() {
        let base = 20;
        let jittered = jittered_ots_delay_secs(base);
        assert!(jittered >= base);
        assert!(jittered <= base + (base / 4));
    }

    #[test]
    fn ots_transport_retry_succeeds_after_transient_failure() {
        let mut server = mockito::Server::new();
        let mock = server
            .mock("GET", "/ok")
            .with_status(200)
            .with_body("ok")
            .create();

        let mut attempts = 0usize;
        let result = call_ots_with_transport_retry_policy(
            OtsRetryPolicy {
                max_transient_retries: 1,
                base_retry_secs: 0,
            },
            || {
                attempts += 1;
                if attempts == 1 {
                    // Closed localhost port -> deterministic transport error.
                    ureq::get("http://127.0.0.1:1/retry-test")
                        .call()
                        .map_err(Box::new)
                } else {
                    let url = format!("{}/ok", server.url());
                    ureq::get(&url).call().map_err(Box::new)
                }
            },
        );

        assert!(result.is_ok());
        assert_eq!(attempts, 2);
        mock.assert();
    }

    #[test]
    fn ots_transport_retry_exhaustion_returns_transport_error() {
        let mut attempts = 0usize;
        let result = call_ots_with_transport_retry_policy(
            OtsRetryPolicy {
                max_transient_retries: 2,
                base_retry_secs: 0,
            },
            || {
                attempts += 1;
                ureq::get("http://127.0.0.1:1/exhaustion")
                    .call()
                    .map_err(Box::new)
            },
        );

        assert!(matches!(result, Err(err) if matches!(err.as_ref(), ureq::Error::Transport(_))));
        assert_eq!(attempts, 3);
    }

    #[test]
    fn consume_ots_falls_back_to_get_after_post_transport_exhaustion() {
        let mut server = mockito::Server::new();
        let get_url = format!("{}/s/fallback", server.url());
        let get_mock = server
            .mock("GET", "/s/fallback")
            .with_status(200)
            .with_header("Content-Type", "application/json")
            .with_body(r#"{"secret":"via-get"}"#)
            .create();

        let body = consume_ots_response_body_with(
            OtsRetryPolicy {
                max_transient_retries: 0,
                base_retry_secs: 0,
            },
            || {
                ureq::get("http://127.0.0.1:1/post-fail")
                    .call()
                    .map_err(Box::new)
            },
            || ureq::get(&get_url).call().map_err(Box::new),
        )
        .unwrap();

        assert_eq!(body, r#"{"secret":"via-get"}"#);
        get_mock.assert();
    }

    #[test]
    fn consume_ots_reports_get_fallback_http_error_after_post_transport_exhaustion() {
        let mut server = mockito::Server::new();
        let get_url = format!("{}/s/fallback-error", server.url());
        let get_mock = server
            .mock("GET", "/s/fallback-error")
            .with_status(500)
            .with_body("backend failure")
            .create();

        let err = consume_ots_response_body_with(
            OtsRetryPolicy {
                max_transient_retries: 0,
                base_retry_secs: 0,
            },
            || {
                ureq::get("http://127.0.0.1:1/post-fail")
                    .call()
                    .map_err(Box::new)
            },
            || ureq::get(&get_url).call().map_err(Box::new),
        )
        .unwrap_err();

        let msg = err.to_string();
        assert!(msg.contains("OTS service returned HTTP 500"));
        assert!(msg.contains("backend failure"));
        get_mock.assert();
    }
}