HTTPS injection for --secret, ai-jail 3.7.1 (from the fork's
feat/secret-tls-inject, on branch zeo/ebuild-371): a per-launch CA, kept in
memory and name-constrained to the bound hosts, lets the egress proxy put the
real value into HTTPS requests to them; --secret KEY=host[,host...], a
per-launch placeholder, Basic auth, chunked bodies, smuggling-safe framing.
Adds rcgen. Must follow ai-jail-host-ports.patch.

kekkai 3.7.1-r1 adds one test, carried from the fork's chore/webpki-roots
(ba27211, written against v3.2.0 and never merged anywhere):
e2e_http_termination_rejects_an_unbundled_root_with_502. The TLS tests only
proved that a chain to an extra root is accepted (danger_extra_roots); this one
proves the converse. Without danger_extra_roots the fixture's self-signed root
is not in webpki-roots, so the upstream handshake fails, the client gets a 502,
and the real secret is never sent. It guards the trust store across rustls and
webpki-roots bumps: a dependency resolution that silently accepted any chain
would turn it into a 200 carrying the secret. Verified on the 3.7.1 tree:
passes; mutation-checked by trusting the fixture root in the test, which makes
it fail at the 502 assertion. It is the only change to this patch since
sys-apps/ai-jail-3.7.1-r2, so that ebuild's copy of the patch now differs from
this one by that test alone.

diff --git a/Cargo.lock b/Cargo.lock
index 1dd4b78..688bb23 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -11,6 +11,7 @@ dependencies = [
  "lexopt",
  "nix",
  "ratatui",
+ "rcgen",
  "ring",
  "rustls",
  "seccompiler",
@@ -44,12 +45,66 @@ version = "0.7.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
 
+[[package]]
+name = "asn1-rs"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8"
+dependencies = [
+ "asn1-rs-derive",
+ "asn1-rs-impl",
+ "displaydoc",
+ "nom",
+ "num-traits",
+ "rusticata-macros",
+ "thiserror",
+ "time",
+]
+
+[[package]]
+name = "asn1-rs-derive"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+ "synstructure",
+]
+
+[[package]]
+name = "asn1-rs-impl"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
 [[package]]
 name = "autocfg"
 version = "1.5.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
 
+[[package]]
+name = "base64"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+
+[[package]]
+name = "bit-vec"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51"
+dependencies = [
+ "serde",
+]
+
 [[package]]
 name = "bitflags"
 version = "2.13.2"
@@ -205,6 +260,26 @@ dependencies = [
  "syn 3.0.9",
 ]
 
+[[package]]
+name = "data-encoding"
+version = "2.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06"
+
+[[package]]
+name = "der-parser"
+version = "10.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6"
+dependencies = [
+ "asn1-rs",
+ "displaydoc",
+ "nom",
+ "num-bigint",
+ "num-traits",
+ "rusticata-macros",
+]
+
 [[package]]
 name = "deranged"
 version = "0.5.9"
@@ -243,6 +318,17 @@ dependencies = [
  "crypto-common",
 ]
 
+[[package]]
+name = "displaydoc"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.9",
+]
+
 [[package]]
 name = "document-features"
 version = "0.2.12"
@@ -291,7 +377,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
 dependencies = [
  "libc",
- "windows-sys 0.52.0",
+ "windows-sys 0.61.2",
 ]
 
 [[package]]
@@ -425,6 +511,12 @@ dependencies = [
  "thiserror",
 ]
 
+[[package]]
+name = "lazy_static"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
+
 [[package]]
 name = "lexopt"
 version = "0.3.2"
@@ -494,6 +586,12 @@ version = "2.8.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
 
+[[package]]
+name = "minimal-lexical"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
+
 [[package]]
 name = "mio"
 version = "1.2.4"
@@ -518,12 +616,41 @@ dependencies = [
  "libc",
 ]
 
+[[package]]
+name = "nom"
+version = "7.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
+dependencies = [
+ "memchr",
+ "minimal-lexical",
+]
+
+[[package]]
+name = "num-bigint"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"
+dependencies = [
+ "num-integer",
+ "num-traits",
+]
+
 [[package]]
 name = "num-conv"
 version = "0.2.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
 
+[[package]]
+name = "num-integer"
+version = "0.1.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
+dependencies = [
+ "num-traits",
+]
+
 [[package]]
 name = "num-traits"
 version = "0.2.19"
@@ -542,6 +669,15 @@ dependencies = [
  "libc",
 ]
 
+[[package]]
+name = "oid-registry"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7"
+dependencies = [
+ "asn1-rs",
+]
+
 [[package]]
 name = "once_cell"
 version = "1.21.4"
@@ -604,6 +740,16 @@ dependencies = [
  "windows-link",
 ]
 
+[[package]]
+name = "pem"
+version = "4.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d354a98a3d1251555de99e8fdd8afda05573c31b82f59063a7b0a29b5527f120"
+dependencies = [
+ "base64",
+ "serde_core",
+]
+
 [[package]]
 name = "portable-atomic"
 version = "1.15.0"
@@ -700,6 +846,20 @@ dependencies = [
  "unicode-width",
 ]
 
+[[package]]
+name = "rcgen"
+version = "0.14.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8774e05a7d0de114588e6a28fe7e71694b82614ed569d86d8b389dfbc98b8ad8"
+dependencies = [
+ "pem",
+ "ring",
+ "rustls-pki-types",
+ "time",
+ "x509-parser",
+ "yasna",
+]
+
 [[package]]
 name = "redox_syscall"
 version = "0.5.18"
@@ -732,6 +892,15 @@ dependencies = [
  "semver",
 ]
 
+[[package]]
+name = "rusticata-macros"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632"
+dependencies = [
+ "nom",
+]
+
 [[package]]
 name = "rustix"
 version = "1.1.6"
@@ -742,7 +911,7 @@ dependencies = [
  "errno",
  "libc",
  "linux-raw-sys",
- "windows-sys 0.52.0",
+ "windows-sys 0.61.2",
 ]
 
 [[package]]
@@ -979,6 +1148,17 @@ dependencies = [
  "unicode-ident",
 ]
 
+[[package]]
+name = "synstructure"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.117",
+]
+
 [[package]]
 name = "thiserror"
 version = "2.0.18"
@@ -1012,6 +1192,7 @@ dependencies = [
  "powerfmt",
  "serde_core",
  "time-core",
+ "time-macros",
 ]
 
 [[package]]
@@ -1020,6 +1201,16 @@ version = "0.1.9"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
 
+[[package]]
+name = "time-macros"
+version = "0.2.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
+dependencies = [
+ "num-conv",
+ "time-core",
+]
+
 [[package]]
 name = "toml"
 version = "0.8.23"
@@ -1272,6 +1463,34 @@ dependencies = [
  "memchr",
 ]
 
+[[package]]
+name = "x509-parser"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202"
+dependencies = [
+ "asn1-rs",
+ "data-encoding",
+ "der-parser",
+ "lazy_static",
+ "nom",
+ "oid-registry",
+ "ring",
+ "rusticata-macros",
+ "thiserror",
+ "time",
+]
+
+[[package]]
+name = "yasna"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b5f6765e852b9b4dc8e2a76843e4d64d1cea8e79bcde0b6901aea8e7c7f08282"
+dependencies = [
+ "bit-vec",
+ "time",
+]
+
 [[package]]
 name = "zeroize"
 version = "1.9.0"
diff --git a/Cargo.toml b/Cargo.toml
index 91e9681..19e0421 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -45,6 +45,7 @@ rustls = { version = "0.23", default-features = false, features = [
   "tls12",
 ] }
 webpki-roots = "0.26"
+rcgen = { version = "0.14.10", default-features = false, features = ["crypto", "ring", "pem"] }
 
 [target.'cfg(unix)'.dependencies]
 nix = { version = "0.29", features = [
diff --git a/README.md b/README.md
index a32268c..f8e19cf 100644
--- a/README.md
+++ b/README.md
@@ -344,19 +344,40 @@ like `--allow-private-host`. Loopback, link-local, multicast, unspecified, and
 cloud-metadata answers are refused without asking. Repository policy cannot
 enable it, and `--lockdown` disables it.
 
-### Phantom credentials: `--secret KEY=host`
+### Phantom credentials: `--secret KEY=host[,host...]`
 
 With filtered egress on, `--secret ANTHROPIC_API_KEY=api.anthropic.com`
 (repeatable, or `secret_hosts = { ... }` in trusted global config) keeps the real
 value out of the sandbox: the child env carries an `AIJAIL-PHANTOM-…`
-placeholder, and the egress proxy swaps in the real value only for requests
-terminating at the bound host. The key must already be passed via `--env` or
-`--env-from-file`. One honest caveat: CONNECT tunnels stay opaque — this only
-covers clients that can speak plain HTTP to the proxy (e.g. an
-`ANTHROPIC_BASE_URL=http://…` override); those requests are terminated and
-re-originated over TLS by the supervisor, which therefore sees that plaintext
-for secret-bound hosts. HTTPS clients that only CONNECT keep working exactly
-as before, with no substitution.
+placeholder, drawn anew for every launch, and the egress proxy swaps in the
+real value only in requests to the bound hosts — several, comma-separated
+(`GITHUB_TOKEN=github.com,api.github.com`), each also in `--allow-host` and
+without a port. The key must already be passed via `--env` or
+`--env-from-file`. A placeholder used as the password of `Authorization: Basic`
+(how `git push` sends a token) is substituted too.
+
+Both transports are covered:
+
+- **Plain HTTP** to the proxy (an `ANTHROPIC_BASE_URL=http://…` override) is
+  terminated and re-originated over TLS, as before.
+- **HTTPS (Linux).** For each launch with a secret, the supervisor makes a CA
+  whose private key lives only in its memory and whose X.509 name constraints
+  permit the bound hosts alone — never another name and never an IP address
+  unless one is bound. The sandbox trusts it through a bundle (the system roots
+  plus that CA) mounted read-only at `/tmp/.ai-jail-ca-bundle.pem` and named by
+  `SSL_CERT_FILE`, `CURL_CA_BUNDLE`, `REQUESTS_CA_BUNDLE` and `GIT_SSL_CAINFO`;
+  Node gets the CA alone through `NODE_EXTRA_CA_CERTS`. A CONNECT to a bound
+  host is answered by the proxy with a short-lived certificate for that host;
+  it reads one request, rewrites its head, and re-originates it over real,
+  verified TLS to the same host and port. Every other tunnel stays opaque.
+
+Request bodies may use `Content-Length` or `chunked`; a request whose framing
+the upstream could read differently (Transfer-Encoding with Content-Length,
+any coding but `chunked`, conflicting lengths, whitespace before a colon, line
+folding) is refused with `400` before anything is dialed. Limits of this first
+version: one request per connection (`Connection: close`), no WebSocket or
+other upgrade on a bound host, and no HTTPS injection on macOS. The supervisor
+sees the plaintext of requests to bound hosts, by construction.
 
 ### Host loopback services: `--forward-port PORT`
 
@@ -778,10 +799,10 @@ flag is CLI-only; no configuration key enables it.
 | `run_id`                         | 32 hex characters, the same for every line of one launch                                                                                                                                                                                                                                           |
 | `host`, `port`                   | the requested target; `null` when no request was parsed                                                                                                                                                                                                                                            |
 | `verdict`                        | `allow`, `deny` (refused by policy) or `error` (the connection failed: a malformed or oversized request, or an upstream or client that could not be reached or written to)                                                                                                                         |
-| `reason`                         | why: `in-allowlist`, `secret-termination`, `prompt-allow`; `not-in-allowlist`, `port-not-allowed`, `forbidden-address-range`, `prompt-deny`, `prompt-no-answer`; `connection-cap`, `request-too-large`, `malformed-request`, `method-not-allowed`, `client-read-failed`, `upstream-unreachable`, `client-write-failed` |
+| `reason`                         | why: `in-allowlist`, `secret-termination`, `secret-injection`, `prompt-allow`; `not-in-allowlist`, `port-not-allowed`, `forbidden-address-range`, `prompt-deny`, `prompt-no-answer`; `connection-cap`, `request-too-large`, `malformed-request`, `ambiguous-framing`, `method-not-allowed`, `client-read-failed`, `upstream-unreachable`, `client-write-failed`, `inject-ca-failed` |
 | `bytes_up`, `bytes_down`         | bytes relayed to and from the upstream, counted even when the transfer ends early                                                                                                                                                                                                                  |
 | `duration_ms`                    | from accept to close                                                                                                                                                                                                                                                                               |
-| `upstream_host`, `upstream_port` | only on a `secret-termination` line: the host and port the proxy itself dialed over TLS                                                                                                                                                                                                            |
+| `upstream_host`, `upstream_port` | only on a `secret-termination` or `secret-injection` line: the host and port the proxy itself dialed over TLS                                                                                                                                                                                       |
 
 Adding a field keeps `v`; removing, renaming, retyping or re-meaning one
 increments it. No request content is ever logged: no path, query, method,
diff --git a/docs/SECURITY.md b/docs/SECURITY.md
index 042b4f7..ce3599d 100644
--- a/docs/SECURITY.md
+++ b/docs/SECURITY.md
@@ -324,22 +324,44 @@ kernel does (32-bit) so a high-bit variant cannot slip past the filter.
 On kernels ≥ 6.12 Landlock also scopes abstract Unix sockets and signals
 (best-effort) as a further backstop.
 
-Phantom credentials (`--secret KEY=host`, filtered egress only) shift part of
-the trust boundary to the supervisor: the sandbox env holds an
-`AIJAIL-PHANTOM-…` placeholder, and the egress proxy substitutes the real
-value only in the request head of plain-HTTP proxy requests terminating at the
-bound host, re-originating them over TLS. Placeholders are not credentials —
-knowing one authorizes nothing — and real values live only in supervisor
-memory, never in any config file, the audit log, or the sandbox. The cost:
-for secret-bound hosts the supervisor (and the proxy's TLS endpoint) sees the
-request plaintext, by construction. CONNECT tunnels to any host stay opaque
-and carry no substitution.
+Phantom credentials (`--secret KEY=host[,host...]`, filtered egress only)
+shift part of the trust boundary to the supervisor: the sandbox env holds an
+`AIJAIL-PHANTOM-…` placeholder, new for every launch, and the egress proxy
+substitutes the real value only in the request head — `Authorization: Basic`
+decoded and re-encoded — of requests to a bound host: plain-HTTP proxy
+requests, and on Linux HTTPS through CONNECT. Placeholders are not credentials
+— knowing one authorizes nothing — and real values live only in supervisor
+memory, never in any config file, the audit log, or the sandbox. Substitution
+is scoped per host: a placeholder sent to a host its key is not bound to goes
+out unchanged.
+
+HTTPS injection works by interception, and its trust anchor is narrow on
+purpose. The supervisor makes one CA per launch; its private key and every
+leaf key stay in supervisor memory and are never written anywhere. The CA
+carries X.509 name constraints permitting the bound hosts only (and their
+subdomains, which is how a DNS constraint reads — the proxy still intercepts
+the exact bound hosts alone), and excluding every IP address unless one is
+bound, so even a stolen key could not vouch for another site. The files the
+sandbox mounts read-only — the bundle (system roots plus the CA) and the CA —
+hold public certificates only, are created `O_EXCL | O_NOFOLLOW` mode `0600`
+beside the proxy socket, and are removed with it; a launch with a secret
+whose files are missing is refused. Upstream TLS is verified against the
+built-in web PKI roots with DNS pinning and the address-range guard, as for
+any tunnel. A request whose body framing the upstream could read differently
+from the proxy — Transfer-Encoding with Content-Length, a coding other than
+exactly `chunked`, conflicting lengths, whitespace before a header colon,
+obsolete line folding — is refused before any dial; a chunked body is
+checked chunk by chunk and nothing past its end is forwarded. The cost: for
+bound hosts the supervisor sees the request plaintext, by construction.
+Tunnels to every other host stay opaque and carry no substitution. Not
+covered: macOS (no interception), WebSocket and other upgrades on a bound
+host, and more than one request per connection.
 
 The egress log (`--egress-log PATH`, Linux only, CLI-only) is written by the
 supervisor, never by the sandbox. What a line **can** contain: the line
 version, a UTC timestamp, the run id, the requested host and port, the verdict
-and its reason, the byte counts and the duration. For a terminated `--secret`
-request it adds the host and port the proxy itself dialed (`upstream_host`,
+and its reason, the byte counts and the duration. For a terminated or injected
+`--secret` request it adds the host and port the proxy itself dialed (`upstream_host`,
 `upstream_port`). What it **cannot** contain: any request content — no path,
 query, method, header, body, credential, `--secret` placeholder, key name, or
 real value — and nothing from inside a CONNECT tunnel, which stays opaque. The
diff --git a/src/cli.rs b/src/cli.rs
index 697a450..43f6112 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -145,10 +145,13 @@ OPTIONS:
     --env-from-file <PATH>          Read KEY=VALUE lines from PATH (repeatable; file
                                     must be user-owned, mode 0600, outside the project;
                                     applies like --env, which wins on conflicts)
-    --secret <KEY=host>             Keep KEY's real value out of the sandbox: the child
-                                    sees a placeholder; the egress proxy substitutes the
-                                    real value only for requests to host (repeatable;
-                                    requires filtered egress via --allow-host)
+    --secret <KEY=host[,host...]>   Keep KEY's real value out of the sandbox: the child
+                                    sees a per-launch placeholder; the egress proxy
+                                    substitutes the real value only in requests to the
+                                    named hosts, over HTTP or HTTPS (it trusts a CA made
+                                    for this launch and those hosts alone; Linux), Basic
+                                    auth included (repeatable; every host must be in
+                                    --allow-host, no port; requires filtered egress)
     --inherit-env / --no-inherit-env
                                     Inherit the full host environment (default: off —
                                     only a safe allowlist is passed)
diff --git a/src/main.rs b/src/main.rs
index 1d8eb29..e0026e2 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -30,6 +30,7 @@ mod state_root;
 mod statusbar;
 #[cfg(target_os = "linux")]
 mod teardown;
+mod tls_inject;
 
 #[cfg(test)]
 mod test_utils;
@@ -199,18 +200,28 @@ fn prepare_secrets(
     }
     let bindings_spec: Vec<(String, String)> =
         config.secret_hosts.clone().into_iter().collect();
+    // One nonce per launch: every placeholder of this session derives
+    // from it, so no two sessions share a placeholder.
+    let session = secret::session_nonce();
     let mut bindings = Vec::new();
-    for (key, host) in bindings_spec {
-        if host.contains("://") || host.contains('/') {
-            return Err(format!(
-                "--secret {key}: host must be a bare hostname, not {host:?}"
-            ));
+    for (key, hosts_value) in bindings_spec {
+        let hosts = secret::split_hosts(&hosts_value);
+        if hosts.is_empty() {
+            return Err(format!("--secret {key}: names no host"));
         }
-        if !config.host_is_allowlisted(&host) {
-            return Err(format!(
-                "--secret {key}: {host} is not in allow_hosts or allow_private_hosts \
-                 (pass --allow-host {host} or --allow-private-host {host})"
-            ));
+        for host in &hosts {
+            if host.contains("://") || host.contains('/') || host.contains(':')
+            {
+                return Err(format!(
+                    "--secret {key}: host must be a bare hostname, not {host:?}"
+                ));
+            }
+            if !config.host_is_allowlisted(host) {
+                return Err(format!(
+                    "--secret {key}: {host} is not in allow_hosts or allow_private_hosts \
+                     (pass --allow-host {host} or --allow-private-host {host})"
+                ));
+            }
         }
         // Resolve the value the child would actually receive. apply_env_pass
         // applies entries in order, skipping bare variables absent from the
@@ -242,9 +253,15 @@ fn prepare_secrets(
                 )
             });
         };
-        let binding = secret::SecretBinding::new(&key, &real, &host);
+        let key_bindings: Vec<secret::SecretBinding> = hosts
+            .iter()
+            .map(|host| {
+                secret::SecretBinding::with_session(&key, &real, host, &session)
+            })
+            .collect();
         // Remove EVERY entry for this key, then insert exactly one placeholder,
-        // so no later duplicate can reintroduce the real value.
+        // so no later duplicate can reintroduce the real value. Every host's
+        // binding shares it (same key, value and session).
         config.env_pass.retain(|entry| {
             config::parse_env_entry(entry)
                 .map(|(name, _)| name != key.as_str())
@@ -252,8 +269,8 @@ fn prepare_secrets(
         });
         config
             .env_pass
-            .push(format!("{key}={}", binding.placeholder));
-        bindings.push(binding);
+            .push(format!("{key}={}", key_bindings[0].placeholder));
+        bindings.extend(key_bindings);
     }
     Ok(bindings)
 }
@@ -2295,7 +2312,20 @@ fn run(
         proxy_config.stats = std::sync::Arc::clone(&egress_stats);
         proxy_config.drain_on_exit = egress_log.is_some() || summary.is_some();
         proxy_config.prompt = host_prompt(config);
-        let proxy_config = launch_runner.finish_proxy_config(proxy_config);
+        let mut proxy_config = launch_runner.finish_proxy_config(proxy_config);
+        // HTTPS injection (Linux): one CA per launch, constrained to the
+        // secret-bound hosts; Proxy::start writes its trust bundle beside
+        // the socket for the sandbox to mount.
+        if !proxy_config.secrets.is_empty() {
+            let hosts: Vec<String> = proxy_config
+                .secrets
+                .iter()
+                .map(|b| b.host.clone())
+                .collect();
+            let ca = tls_inject::InjectCa::generate(&hosts)
+                .map_err(|e| format!("--secret over HTTPS: {e}"))?;
+            proxy_config.inject_ca = Some(std::sync::Arc::new(ca));
+        }
         let socket = proxy::default_socket_path();
         let proxy = proxy::Proxy::start(proxy_config, Some(&socket))
             .map_err(|e| format!("Failed to start the egress proxy: {e}"))?;
@@ -3380,6 +3410,60 @@ mod tests {
         assert!(super::prepare_secrets(&mut config).is_err());
     }
 
+    #[test]
+    fn a_secret_bound_to_several_hosts_shares_one_placeholder() {
+        let mut config = Config {
+            allow_hosts: vec!["api.example.com".into(), "example.com".into()],
+            env_pass: vec!["KEY=real-value".into()],
+            secret_hosts: [(
+                "KEY".into(),
+                "api.example.com, example.com".into(),
+            )]
+            .into_iter()
+            .collect(),
+            ..Config::default()
+        };
+        let bindings = super::prepare_secrets(&mut config).unwrap();
+        let hosts: Vec<&str> =
+            bindings.iter().map(|b| b.host.as_str()).collect();
+        assert_eq!(hosts, ["api.example.com", "example.com"]);
+        assert_eq!(bindings[0].placeholder, bindings[1].placeholder);
+        assert_eq!(
+            config.env_pass,
+            vec![format!("KEY={}", bindings[0].placeholder)],
+            "one placeholder entry, never the value"
+        );
+
+        // A second launch draws a new session nonce: a new placeholder.
+        let mut again = Config {
+            allow_hosts: vec!["api.example.com".into(), "example.com".into()],
+            env_pass: vec!["KEY=real-value".into()],
+            secret_hosts: [("KEY".into(), "api.example.com".into())]
+                .into_iter()
+                .collect(),
+            ..Config::default()
+        };
+        let next = super::prepare_secrets(&mut again).unwrap();
+        assert_ne!(next[0].placeholder, bindings[0].placeholder);
+
+        // Every host must be allowlisted, and none may carry a port.
+        for value in ["api.example.com,evil.example", "example.com:443", " , "]
+        {
+            let mut bad = Config {
+                allow_hosts: vec![
+                    "api.example.com".into(),
+                    "example.com".into(),
+                ],
+                env_pass: vec!["KEY=real-value".into()],
+                secret_hosts: [("KEY".into(), value.into())]
+                    .into_iter()
+                    .collect(),
+                ..Config::default()
+            };
+            assert!(super::prepare_secrets(&mut bad).is_err(), "{value:?}");
+        }
+    }
+
     #[test]
     fn secrets_swap_env_pass_for_placeholders() {
         let _env = ENV_LOCK.lock().unwrap();
diff --git a/src/proxy.rs b/src/proxy.rs
index 01f97bb..774215a 100644
--- a/src/proxy.rs
+++ b/src/proxy.rs
@@ -105,6 +105,13 @@ pub(crate) struct ProxyConfig {
     /// placeholders rewritten to the real values, and re-originated
     /// over TLS.
     pub secrets: Vec<crate::secret::SecretBinding>,
+    /// The launch's HTTPS injection CA (Linux): a CONNECT to a host it
+    /// covers -- a secret-bound host -- is terminated with a leaf it
+    /// mints, its request head rewritten like the plain-HTTP path's, and
+    /// re-originated over real TLS. `None` keeps every tunnel opaque.
+    /// When set with a Unix socket, [`Proxy::start`] writes the trust
+    /// bundle beside the socket and `Drop` removes it.
+    pub inject_ca: Option<Arc<crate::tls_inject::InjectCa>>,
     /// Test-only escape hatch: extra TLS trust roots for the
     /// self-signed fixture in tests/. Same rule as
     /// `danger_allow_private`: never config- or CLI-exposable.
@@ -145,6 +152,7 @@ impl ProxyConfig {
             danger_any_port: false,
             audit: None,
             secrets: Vec::new(),
+            inject_ca: None,
             danger_extra_roots: Vec::new(),
             prompt: None,
             egress: None,
@@ -387,6 +395,14 @@ impl Proxy {
                 path,
                 std::fs::Permissions::from_mode(0o600),
             )?;
+            // The injection trust bundle lives beside the socket and shares
+            // its lifetime: the sandbox mounts both, and Drop removes both.
+            if let Some(ca) = &shared.config.inject_ca
+                && let Err(e) = crate::tls_inject::write_bundle(ca, path)
+            {
+                let _ = std::fs::remove_file(path);
+                return Err(io::Error::other(e));
+            }
             shared.keep_listener(
                 unix_listener.try_clone().map(DrainListener::Unix),
             );
@@ -491,6 +507,7 @@ impl Drop for Proxy {
     fn drop(&mut self) {
         if let Some(path) = &self.unix_path {
             let _ = std::fs::remove_file(path);
+            crate::tls_inject::remove_bundle(path);
         }
     }
 }
@@ -932,6 +949,18 @@ fn handle_conn<S: ClientStream>(
         return;
     }
 
+    // HTTPS injection: only an allowlisted (never a prompted) host that
+    // the launch's CA covers, which is to say a secret-bound one. Every
+    // other tunnel below stays opaque.
+    if allowlisted
+        && let Some(ca) = shared.config.inject_ca.clone()
+        && ca.covers(&host)
+    {
+        let _ = client.set_read_timeout(Some(shared.config.read_timeout));
+        handle_tls_injection(client, &host, port, &shared, &mut conn, &ca);
+        return;
+    }
+
     // One resolution serves both the prompt and the dial (DNS pinning):
     // the addresses the user approves are the ones dialed.
     let addrs = match resolve(&host, port) {
@@ -1138,8 +1167,8 @@ enum ReadFail {
 /// Read one CONNECT request through its `\r\n\r\n` terminator, capped
 /// at `cap` bytes. Headers after the request line are consumed but
 /// ignored -- nothing beyond the CONNECT line is ever forwarded.
-fn read_request<S: ClientStream>(
-    stream: &mut S,
+fn read_request<R: Read>(
+    stream: &mut R,
     cap: usize,
 ) -> Result<Vec<u8>, ReadFail> {
     let mut buf = Vec::with_capacity(1024);
@@ -1523,32 +1552,177 @@ fn parse_absolute_form(buf: &[u8]) -> Option<(String, u16)> {
     }
 }
 
-/// One header field parsed from a request head: whether the request
-/// body is chunked, and the Content-Length when present.
-fn head_body_framing(head: &[u8]) -> (bool, Option<u64>) {
-    let mut chunked = false;
-    let mut content_length = None;
+/// How a terminated request's body is delimited.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum BodyFraming {
+    None,
+    Length(u64),
+    Chunked,
+}
+
+/// Longest chunk-size or trailer line accepted in a chunked body.
+const CHUNK_LINE_CAP: u64 = 4096;
+
+/// Read a request head's body framing, refusing every shape on which the
+/// proxy and the upstream server could disagree -- the classic request
+/// smuggling ambiguities (RFC 9112 §6.3): Transfer-Encoding together
+/// with Content-Length, a transfer coding other than exactly `chunked`,
+/// Content-Length values that conflict or do not parse, a header name
+/// with whitespace before its colon, and obsolete line folding. The
+/// proxy forwards the head as received, so the upstream must read the
+/// same framing this returns. The `Err` is the egress reason.
+fn body_framing(head: &[u8]) -> Result<BodyFraming, &'static str> {
     // read_request may include body bytes from the same socket read. They
     // can be binary or look like headers, but cannot define HTTP framing.
     let end = head
         .windows(4)
         .position(|w| w == b"\r\n\r\n")
         .unwrap_or(head.len());
-    let head = &head[..end];
-    let Ok(text) = std::str::from_utf8(head) else {
-        return (chunked, content_length);
-    };
+    let text =
+        std::str::from_utf8(&head[..end]).map_err(|_| "malformed-request")?;
+    let mut codings = Vec::new();
+    let mut length: Option<u64> = None;
     for line in text.split("\r\n").skip(1) {
+        if line.starts_with([' ', '\t']) {
+            return Err("ambiguous-framing");
+        }
         let Some((name, value)) = line.split_once(':') else {
-            continue;
+            return Err("malformed-request");
         };
-        if name.trim().eq_ignore_ascii_case("transfer-encoding") {
-            chunked = true;
-        } else if name.trim().eq_ignore_ascii_case("content-length") {
-            content_length = value.trim().parse().ok();
+        if name.is_empty() || name.contains(|c: char| c.is_ascii_whitespace()) {
+            return Err("ambiguous-framing");
+        }
+        if name.eq_ignore_ascii_case("transfer-encoding") {
+            codings.extend(
+                value.split(',').map(|c| c.trim().to_ascii_lowercase()),
+            );
+        } else if name.eq_ignore_ascii_case("content-length") {
+            for item in value.split(',') {
+                let item = item.trim();
+                if item.is_empty() || !item.bytes().all(|b| b.is_ascii_digit())
+                {
+                    return Err("ambiguous-framing");
+                }
+                let parsed: u64 =
+                    item.parse().map_err(|_| "ambiguous-framing")?;
+                if length.is_some_and(|known| known != parsed) {
+                    return Err("ambiguous-framing");
+                }
+                length = Some(parsed);
+            }
         }
     }
-    (chunked, content_length)
+    match (codings.as_slice(), length) {
+        ([], None) => Ok(BodyFraming::None),
+        ([], Some(n)) => Ok(BodyFraming::Length(n)),
+        ([only], None) if only == "chunked" => Ok(BodyFraming::Chunked),
+        _ => Err("ambiguous-framing"),
+    }
+}
+
+/// Forward a request body to `out` exactly as framed: `already` is what
+/// the head read took past the terminator, `rest` the client stream it
+/// continues on. A chunked body is checked chunk by chunk and passed
+/// through byte for byte, so the upstream sees the framing
+/// [`body_framing`] agreed to and nothing past its end -- bytes after it
+/// (a pipelined second request) are dropped, the connection being
+/// `Connection: close`. Every forwarded byte is added to `count`.
+fn forward_body<R: Read, W: Write>(
+    framing: BodyFraming,
+    already: &[u8],
+    rest: R,
+    out: &mut W,
+    count: &AtomicU64,
+) -> io::Result<()> {
+    let mut source = io::BufReader::new(already.chain(rest));
+    match framing {
+        BodyFraming::None => Ok(()),
+        BodyFraming::Length(n) => copy_exact(&mut source, out, n, count),
+        BodyFraming::Chunked => forward_chunked(&mut source, out, count),
+    }
+}
+
+fn copy_exact<R: Read, W: Write>(
+    source: &mut R,
+    out: &mut W,
+    n: u64,
+    count: &AtomicU64,
+) -> io::Result<()> {
+    let copied = io::copy(&mut source.take(n), out)?;
+    count.fetch_add(copied, Ordering::Relaxed);
+    if copied < n {
+        return Err(io::ErrorKind::UnexpectedEof.into());
+    }
+    Ok(())
+}
+
+fn forward_chunked<R: io::BufRead, W: Write>(
+    source: &mut R,
+    out: &mut W,
+    count: &AtomicU64,
+) -> io::Result<()> {
+    let invalid = |what: &str| io::Error::new(io::ErrorKind::InvalidData, what);
+    loop {
+        let line = read_crlf_line(source)?;
+        let size_text = &line[..line.len() - 2];
+        let size_text =
+            size_text.split(|b| *b == b';').next().unwrap_or_default();
+        if size_text.is_empty()
+            || size_text.len() > 16
+            || !size_text.iter().all(u8::is_ascii_hexdigit)
+        {
+            return Err(invalid("bad chunk size"));
+        }
+        let size = u64::from_str_radix(
+            std::str::from_utf8(size_text).map_err(|_| invalid("chunk"))?,
+            16,
+        )
+        .map_err(|_| invalid("bad chunk size"))?;
+        out.write_all(&line)?;
+        count.fetch_add(line.len() as u64, Ordering::Relaxed);
+        if size == 0 {
+            // Trailer section, ended by an empty line; capped as a whole.
+            let mut trailer_bytes = 0_usize;
+            loop {
+                let trailer = read_crlf_line(source)?;
+                trailer_bytes += trailer.len();
+                if trailer_bytes > REQUEST_CAP {
+                    return Err(invalid("trailers too large"));
+                }
+                out.write_all(&trailer)?;
+                count.fetch_add(trailer.len() as u64, Ordering::Relaxed);
+                if trailer == b"\r\n" {
+                    return Ok(());
+                }
+            }
+        }
+        copy_exact(source, out, size, count)?;
+        let mut crlf = [0_u8; 2];
+        source.read_exact(&mut crlf)?;
+        if crlf != *b"\r\n" {
+            return Err(invalid("chunk data not followed by CRLF"));
+        }
+        out.write_all(&crlf)?;
+        count.fetch_add(2, Ordering::Relaxed);
+    }
+}
+
+/// One line ending in CRLF, at most [`CHUNK_LINE_CAP`] bytes. A bare LF
+/// or a line that runs past the cap is refused.
+fn read_crlf_line<R: io::BufRead>(source: &mut R) -> io::Result<Vec<u8>> {
+    let mut line = Vec::new();
+    io::BufRead::read_until(
+        &mut source.by_ref().take(CHUNK_LINE_CAP),
+        b'\n',
+        &mut line,
+    )?;
+    if !line.ends_with(b"\r\n") {
+        return Err(io::Error::new(
+            io::ErrorKind::InvalidData,
+            "chunk line without CRLF",
+        ));
+    }
+    Ok(line)
 }
 
 /// Strip any client `Connection:` header and pin `Connection: close`:
@@ -1619,15 +1793,16 @@ fn handle_http_termination<S: ClientStream>(
     }
     let binding = binding.expect("binding checked above");
 
-    let (chunked, content_length) = head_body_framing(&request);
-    if chunked {
-        // Unsupported framing: the request is refused before any dial.
-        conn.record.verdict(Verdict::Error, "malformed-request");
-        // API clients send Content-Length; chunked bodies are out of
-        // scope for v1 rather than silently mishandled.
-        reject(&mut client, &Reject::NotImplemented);
-        return;
-    }
+    let framing = match body_framing(&request) {
+        Ok(framing) => framing,
+        Err(reason) => {
+            // Refused before any dial: the upstream never sees a request
+            // whose framing it could read differently.
+            conn.record.verdict(Verdict::Error, reason);
+            reject(&mut client, &Reject::BadRequest);
+            return;
+        }
+    };
 
     // Split head from any body bytes already read (read_request reads
     // in 1 KiB chunks and can overshoot into the body).
@@ -1668,27 +1843,18 @@ fn handle_http_termination<S: ClientStream>(
     conn.record.verdict(Verdict::Allow, "secret-termination");
     let (up, down) = conn.record.counters();
 
-    // The forwarded head, body bytes already read and the rest of the
-    // body all go through one counting reader: the record gets a byte
-    // count, never the bytes.
-    let body_len = content_length.unwrap_or(0) as usize;
+    // The forwarded head and body are counted as they go: the record
+    // gets a byte count, never the bytes.
     let write_result = (|| -> io::Result<()> {
-        let rest = body_len.saturating_sub(body_so_far.len()) as u64;
-        let body_rest: Box<dyn Read> = if rest > 0 {
-            Box::new(client.try_clone_stream()?.take(rest))
-        } else {
-            Box::new(io::empty())
-        };
-        let mut forwarded = CountingReader::new(
-            rewritten.as_slice().chain(body_so_far).chain(body_rest),
-            up,
-        );
-        io::copy(&mut forwarded, &mut upstream)?;
+        upstream.write_all(&rewritten)?;
+        up.fetch_add(rewritten.len() as u64, Ordering::Relaxed);
+        let body_rest = client.try_clone_stream()?;
+        forward_body(framing, body_so_far, body_rest, &mut upstream, &up)?;
         upstream.flush()?;
         Ok(())
     })();
     if write_result.is_err() {
-        return;
+        finish_request_early(&mut upstream, shared.config.read_timeout);
     }
 
     // Upstream closes at the end of the response (Connection: close),
@@ -1701,6 +1867,164 @@ fn handle_http_termination<S: ClientStream>(
     let _ = client_writer.shutdown_both();
 }
 
+/// Rewrite a request head for `host` with every binding of that host and
+/// nothing else, auditing each key's substitution count (never a value).
+/// Scoped like the plain-HTTP path: a placeholder of a key bound to
+/// another host passes through untouched.
+fn rewrite_for_host(head: &[u8], host: &str, shared: &Shared) -> Vec<u8> {
+    let mut out = head.to_vec();
+    for binding in shared
+        .config
+        .secrets
+        .iter()
+        .filter(|b| b.host.eq_ignore_ascii_case(host))
+    {
+        let (rewritten, substitutions) =
+            crate::secret::rewrite_head(&out, std::slice::from_ref(binding));
+        out = rewritten;
+        if let Some(log) = &shared.config.audit {
+            log.record(crate::audit::secret_inject_record(
+                host,
+                &binding.key,
+                substitutions,
+            ));
+        }
+    }
+    force_connection_close(&out)
+}
+
+/// Answer a reply on the decrypted side of an intercepted tunnel and end
+/// it: the same minimal replies `reject` writes on a plain stream.
+fn reject_tls<S: ClientStream>(
+    tls: &mut rustls::StreamOwned<rustls::ServerConnection, S>,
+    why: &Reject,
+) {
+    let (code, reason) = why.status();
+    let _ =
+        tls.write_all(format!("HTTP/1.1 {code} {reason}\r\n\r\n").as_bytes());
+    tls.conn.send_close_notify();
+    let _ = tls.flush();
+    let _ = tls.sock.shutdown_both();
+}
+
+/// HTTPS credential injection (§6.53): the CONNECT target is a
+/// secret-bound allowlisted host, so instead of an opaque tunnel the
+/// proxy answers the TLS handshake itself with a leaf from the launch's
+/// CA, reads one request, rewrites its head with that host's bindings,
+/// and re-originates it over real, verified TLS to the same host and
+/// port -- DNS pinning and the SSRF guard come with `tls_connect`. One
+/// request per connection (`Connection: close`), as on the plain-HTTP
+/// path; an upgrade (WebSocket) is not carried.
+fn handle_tls_injection<S: ClientStream>(
+    mut client: S,
+    host: &str,
+    port: u16,
+    shared: &Shared,
+    conn: &mut Conn,
+    ca: &crate::tls_inject::InjectCa,
+) {
+    let server_config = match ca.server_config(host) {
+        Ok(config) => config,
+        Err(_) => {
+            conn.record.verdict(Verdict::Error, "inject-ca-failed");
+            reject(&mut client, &Reject::BadGateway);
+            return;
+        }
+    };
+    let server = match rustls::ServerConnection::new(server_config) {
+        Ok(server) => server,
+        Err(_) => {
+            conn.record.verdict(Verdict::Error, "inject-ca-failed");
+            reject(&mut client, &Reject::BadGateway);
+            return;
+        }
+    };
+    if client.write_all(REPLY_OK.as_bytes()).is_err() {
+        conn.record.verdict(Verdict::Error, "client-write-failed");
+        return;
+    }
+    let mut tls = rustls::StreamOwned::new(server, client);
+
+    // The handshake and the head share the slowloris read timeout set by
+    // the caller; the body does not, as on the plain-HTTP path.
+    let request = match read_request(&mut tls, REQUEST_CAP) {
+        Ok(request) => request,
+        Err(ReadFail::TooLarge) => {
+            conn.record.verdict(Verdict::Error, "request-too-large");
+            reject_tls(&mut tls, &Reject::TooLarge);
+            return;
+        }
+        Err(ReadFail::Io) => {
+            conn.record.verdict(Verdict::Error, "client-read-failed");
+            return;
+        }
+    };
+    let _ = tls.sock.set_read_timeout(None);
+    let framing = match body_framing(&request) {
+        Ok(framing) => framing,
+        Err(reason) => {
+            conn.record.verdict(Verdict::Error, reason);
+            reject_tls(&mut tls, &Reject::BadRequest);
+            return;
+        }
+    };
+    let head_end = request
+        .windows(4)
+        .position(|w| w == b"\r\n\r\n")
+        .map(|p| p + 4)
+        .unwrap_or(request.len());
+    let (head, body_so_far) = request.split_at(head_end);
+    let rewritten = rewrite_for_host(head, host, shared);
+
+    conn.record.upstream(host, port);
+    let mut upstream = match tls_connect(host, port, &shared.config) {
+        Ok(stream) => stream,
+        Err(why) => {
+            let (verdict, reason) = dial_failure_verdict(&why);
+            conn.record.verdict(verdict, reason);
+            reject_tls(&mut tls, &why);
+            return;
+        }
+    };
+    audit_verdict(shared, host, port, "allow", "secret-injection");
+    conn.register_tcp(&upstream.sock);
+    conn.record.verdict(Verdict::Allow, "secret-injection");
+    let (up, down) = conn.record.counters();
+
+    let sent = (|| -> io::Result<()> {
+        upstream.write_all(&rewritten)?;
+        up.fetch_add(rewritten.len() as u64, Ordering::Relaxed);
+        forward_body(framing, body_so_far, &mut tls, &mut upstream, &up)?;
+        upstream.flush()
+    })();
+    if sent.is_err() {
+        finish_request_early(&mut upstream, shared.config.read_timeout);
+    }
+    // Upstream closes at the end of the response (Connection: close). A
+    // server that drops TCP without close_notify still delivered what it
+    // sent, so the copy's error is not a failure of this exchange.
+    let _ = io::copy(&mut CountingReader::new(&mut upstream, down), &mut tls);
+    tls.conn.send_close_notify();
+    let _ = tls.flush();
+    let _ = tls.sock.shutdown_both();
+}
+
+/// The request could not be sent whole -- the client's body ended or
+/// broke, or the server stopped reading. A server that answers before
+/// the body ends (a 401 or 413 is the usual case) has already written
+/// its reply, so it is still relayed: end the upstream's write half,
+/// then read with the slowloris timeout, because the request the server
+/// holds may be incomplete and it could otherwise wait for it forever.
+fn finish_request_early(
+    upstream: &mut rustls::StreamOwned<rustls::ClientConnection, TcpStream>,
+    timeout: Duration,
+) {
+    upstream.conn.send_close_notify();
+    let _ = upstream.flush();
+    let _ = upstream.sock.shutdown(Shutdown::Write);
+    let _ = upstream.sock.set_read_timeout(Some(timeout));
+}
+
 /// TLS to the checked upstream: DNS pinning and the SSRF guard are
 /// inherited from connect_upstream (resolve once, dial the checked
 /// address); the original host name is the TLS SNI/ServerName. Roots
@@ -3386,23 +3710,59 @@ mod tests {
     }
 
     #[test]
-    fn head_body_framing_parses_content_length_and_chunked() {
-        let (chunked, len) =
-            head_body_framing(b"POST / HTTP/1.1\r\nContent-Length: 42\r\n\r\n");
-        assert!(!chunked);
-        assert_eq!(len, Some(42));
-        let (chunked, len) = head_body_framing(
-            b"POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n",
+    fn body_framing_reads_length_chunked_and_none() {
+        assert_eq!(
+            body_framing(b"POST / HTTP/1.1\r\nContent-Length: 42\r\n\r\n"),
+            Ok(BodyFraming::Length(42))
+        );
+        assert_eq!(
+            body_framing(
+                b"POST / HTTP/1.1\r\nTransfer-Encoding: Chunked\r\n\r\n"
+            ),
+            Ok(BodyFraming::Chunked)
+        );
+        assert_eq!(
+            body_framing(b"GET / HTTP/1.1\r\n\r\n"),
+            Ok(BodyFraming::None)
+        );
+        // Repeated identical lengths are one length (RFC 9112 §6.3).
+        assert_eq!(
+            body_framing(
+                b"POST / HTTP/1.1\r\nContent-Length: 5\r\n\
+                  Content-Length: 5, 5\r\n\r\n"
+            ),
+            Ok(BodyFraming::Length(5))
         );
-        assert!(chunked);
-        assert_eq!(len, None);
-        let (chunked, len) = head_body_framing(b"GET / HTTP/1.1\r\n\r\n");
-        assert!(!chunked);
-        assert_eq!(len, None);
     }
 
     #[test]
-    fn head_body_framing_ignores_bytes_after_the_header_terminator() {
+    fn body_framing_refuses_every_smuggling_ambiguity() {
+        for head in [
+            // TE and CL together.
+            "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\
+             Content-Length: 4\r\n\r\n",
+            // A coding other than exactly chunked, or chunked twice.
+            "POST / HTTP/1.1\r\nTransfer-Encoding: gzip, chunked\r\n\r\n",
+            "POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\
+             Transfer-Encoding: chunked\r\n\r\n",
+            "POST / HTTP/1.1\r\nTransfer-Encoding: identity\r\n\r\n",
+            // Conflicting or unparsable lengths.
+            "POST / HTTP/1.1\r\nContent-Length: 4\r\nContent-Length: 5\r\n\r\n",
+            "POST / HTTP/1.1\r\nContent-Length: +4\r\n\r\n",
+            "POST / HTTP/1.1\r\nContent-Length: 4x\r\n\r\n",
+            "POST / HTTP/1.1\r\nContent-Length: 99999999999999999999999\r\n\r\n",
+            // Whitespace before the colon, and obsolete line folding.
+            "POST / HTTP/1.1\r\nTransfer-Encoding : chunked\r\n\r\n",
+            "POST / HTTP/1.1\r\nX-A: 1\r\n Transfer-Encoding: chunked\r\n\r\n",
+            // A header line without a colon.
+            "POST / HTTP/1.1\r\nTransfer-Encoding chunked\r\n\r\n",
+        ] {
+            assert!(body_framing(head.as_bytes()).is_err(), "{head:?}");
+        }
+    }
+
+    #[test]
+    fn body_framing_ignores_bytes_after_the_header_terminator() {
         for body in [
             b"\xff\x00\xfe".as_slice(),
             b"Transfer-Encoding: chunked\r\n".as_slice(),
@@ -3415,12 +3775,65 @@ mod tests {
             .into_bytes();
             request.extend_from_slice(body);
             assert_eq!(
-                head_body_framing(&request),
-                (false, Some(body.len() as u64))
+                body_framing(&request),
+                Ok(BodyFraming::Length(body.len() as u64))
             );
         }
     }
 
+    fn forwarded(
+        framing: BodyFraming,
+        already: &[u8],
+        rest: &[u8],
+    ) -> (io::Result<()>, Vec<u8>, u64) {
+        let count = AtomicU64::new(0);
+        let mut out = Vec::new();
+        let result = forward_body(framing, already, rest, &mut out, &count);
+        (result, out, count.load(Ordering::Relaxed))
+    }
+
+    #[test]
+    fn forward_body_passes_a_chunked_body_through_and_stops_at_its_end() {
+        let body = b"4;ext=1\r\nWiki\r\n5\r\npedia\r\n0\r\nX-T: 1\r\n\r\n";
+        let mut rest = body[6..].to_vec();
+        // A pipelined second request after the body is not forwarded.
+        rest.extend_from_slice(b"GET /smuggled HTTP/1.1\r\n\r\n");
+        let (result, out, count) =
+            forwarded(BodyFraming::Chunked, &body[..6], &rest);
+        result.unwrap();
+        assert_eq!(out, body);
+        assert_eq!(count, body.len() as u64);
+    }
+
+    #[test]
+    fn forward_body_refuses_a_malformed_chunked_body() {
+        for body in [
+            b"z\r\n".as_slice(),        // not hex
+            b"4\nWiki\r\n0\r\n\r\n",    // bare LF
+            b"4\r\nWikiXX0\r\n\r\n",    // data not followed by CRLF
+            b"4\r\nWi",                 // truncated
+            b"11111111111111111\r\n",   // 17 hex digits
+            b" 4\r\nWiki\r\n0\r\n\r\n", // whitespace before the size
+        ] {
+            let (result, _, _) = forwarded(BodyFraming::Chunked, &[], body);
+            assert!(result.is_err(), "{:?}", String::from_utf8_lossy(body));
+        }
+    }
+
+    #[test]
+    fn forward_body_copies_exactly_content_length() {
+        let (result, out, count) =
+            forwarded(BodyFraming::Length(5), b"he", b"lloEXTRA");
+        result.unwrap();
+        assert_eq!(out, b"hello");
+        assert_eq!(count, 5);
+        let (result, _, _) = forwarded(BodyFraming::Length(9), b"he", b"llo");
+        assert!(result.is_err(), "a short body is an error, not a pad");
+        let (result, out, _) = forwarded(BodyFraming::None, b"", b"ignored");
+        result.unwrap();
+        assert!(out.is_empty());
+    }
+
     #[test]
     fn force_connection_close_rewrites_and_appends() {
         let head = b"GET / HTTP/1.1\r\nHost: x\r\n\r\n";
@@ -3498,6 +3911,18 @@ mod tests {
                         )
                         .as_bytes(),
                     );
+                    // The fixture answers on the head alone. Closing with
+                    // request body bytes still unread would make the kernel
+                    // reset the connection, and a reset can discard the
+                    // reply before the proxy reads it -- TCP, not the code
+                    // under test. So end cleanly and drain what is left.
+                    tls.conn.send_close_notify();
+                    let _ = tls.flush();
+                    let _ = tls.sock.shutdown(std::net::Shutdown::Write);
+                    let _ =
+                        tls.sock.set_read_timeout(Some(Duration::from_secs(2)));
+                    let mut sink = [0_u8; 4096];
+                    while matches!(tls.sock.read(&mut sink), Ok(n) if n > 0) {}
                 });
             }
         });
@@ -3546,6 +3971,39 @@ mod tests {
         assert!(!response.contains(&placeholder), "{response}");
     }
 
+    /// The converse of the test above: the fixture's self-signed root is
+    /// not in webpki-roots, so without danger_extra_roots the upstream
+    /// handshake must fail and surface as a 502, and the secret is never
+    /// sent. Guards the trust store across rustls/webpki-roots bumps: a
+    /// resolution that silently accepted any chain would turn this into a
+    /// 200 carrying the real value.
+    #[test]
+    fn e2e_http_termination_rejects_an_unbundled_root_with_502() {
+        let fixture = tls_fixture();
+        let binding = crate::secret::SecretBinding::new(
+            "X_KEY",
+            "real-secret",
+            "127.0.0.1",
+        );
+        let placeholder = binding.placeholder.clone();
+        let mut config = test_config(&["127.0.0.1"]);
+        config.secrets = vec![binding];
+        let proxy = Proxy::start(config, None).unwrap();
+
+        let request = format!(
+            "GET http://127.0.0.1:{fixture}/v1/test HTTP/1.1\r\n\
+             Host: 127.0.0.1:{fixture}\r\n\
+             x-api-key: {placeholder}\r\n\
+             \r\n"
+        );
+        let stream = connect_and_send(proxy.port(), request.as_bytes());
+        let mut response = Vec::new();
+        (&mut &stream).read_to_end(&mut response).unwrap();
+        let response = String::from_utf8_lossy(&response);
+        assert!(response.starts_with("HTTP/1.1 502"), "{response}");
+        assert!(!response.contains("real-secret"), "{response}");
+    }
+
     #[test]
     fn e2e_http_termination_substitutes_only_the_matched_host_binding() {
         // Two bindings, KEY_A -> host A (the fixture) and KEY_B ->
@@ -3673,23 +4131,206 @@ mod tests {
     }
 
     #[test]
-    fn e2e_http_termination_rejects_chunked_with_501() {
+    fn e2e_http_termination_forwards_a_chunked_body() {
         let fixture = tls_fixture();
         let binding =
             crate::secret::SecretBinding::new("X_KEY", "real", "127.0.0.1");
+        let placeholder = binding.placeholder.clone();
+        let mut config = test_config(&["127.0.0.1"]);
+        config.secrets = vec![binding];
+        config.danger_extra_roots = vec![fixture_root()];
+        let proxy = Proxy::start(config, None).unwrap();
+        let request = format!(
+            "POST http://127.0.0.1:{fixture}/ HTTP/1.1\r\n\
+             x-test-key: {placeholder}\r\n\
+             Transfer-Encoding: chunked\r\n\r\n3\r\nabc\r\n0\r\n\r\n"
+        );
+        let stream = connect_and_send(proxy.port(), request.as_bytes());
+        let mut response = Vec::new();
+        (&mut &stream).read_to_end(&mut response).unwrap();
+        let response = String::from_utf8_lossy(&response);
+        assert!(response.starts_with("HTTP/1.1 200 OK"), "{response}");
+        assert!(response.contains("key=real"), "{response}");
+    }
+
+    #[test]
+    fn e2e_http_termination_relays_a_reply_sent_before_the_body_ended() {
+        // The client promises 100 bytes and stops after 3: the request
+        // cannot be sent whole, but the server already answered on the
+        // head, and that answer still reaches the client.
+        let fixture = tls_fixture();
+        let binding =
+            crate::secret::SecretBinding::new("X_KEY", "real", "127.0.0.1");
+        let placeholder = binding.placeholder.clone();
         let mut config = test_config(&["127.0.0.1"]);
         config.secrets = vec![binding];
         config.danger_extra_roots = vec![fixture_root()];
         let proxy = Proxy::start(config, None).unwrap();
         let request = format!(
             "POST http://127.0.0.1:{fixture}/ HTTP/1.1\r\n\
-             Transfer-Encoding: chunked\r\n\r\n0\r\n\r\n"
+             x-test-key: {placeholder}\r\nContent-Length: 100\r\n\r\nabc"
         );
         let stream = connect_and_send(proxy.port(), request.as_bytes());
+        stream.shutdown(Shutdown::Write).unwrap();
+        let mut response = Vec::new();
+        (&mut &stream).read_to_end(&mut response).unwrap();
+        let response = String::from_utf8_lossy(&response);
+        assert!(response.starts_with("HTTP/1.1 200 OK"), "{response}");
+        assert!(response.contains("key=real"), "{response}");
+    }
+
+    #[test]
+    fn e2e_http_termination_refuses_ambiguous_framing_with_400() {
+        let binding =
+            crate::secret::SecretBinding::new("X_KEY", "real", "127.0.0.1");
+        let mut config = test_config(&["127.0.0.1"]);
+        config.secrets = vec![binding];
+        let proxy = Proxy::start(config, None).unwrap();
+        // Refused before any dial: port 1 would otherwise be a 502.
+        let stream = connect_and_send(
+            proxy.port(),
+            b"POST http://127.0.0.1:1/ HTTP/1.1\r\n\
+              Transfer-Encoding: chunked\r\nContent-Length: 4\r\n\r\n",
+        );
         assert_eq!(
             read_reply_head(&stream),
-            "HTTP/1.1 501 Not Implemented\r\n\r\n"
+            "HTTP/1.1 400 Bad Request\r\n\r\n"
+        );
+    }
+
+    /// CONNECT through the proxy, then speak TLS on the tunnel trusting
+    /// `root` only, send `request`, and return the whole response.
+    fn https_through_proxy(
+        proxy_port: u16,
+        target: u16,
+        root: rustls::pki_types::CertificateDer<'static>,
+        request: &[u8],
+    ) -> String {
+        let stream = connect_and_send(
+            proxy_port,
+            &connect_request(&format!("127.0.0.1:{target}")),
+        );
+        let head = read_reply_head(&stream);
+        assert!(head.starts_with("HTTP/1.1 200"), "{head}");
+        let mut roots = rustls::RootCertStore::empty();
+        roots.add(root).unwrap();
+        let client_config = rustls::ClientConfig::builder()
+            .with_root_certificates(roots)
+            .with_no_client_auth();
+        let name =
+            rustls::pki_types::ServerName::try_from("127.0.0.1").unwrap();
+        let conn = rustls::ClientConnection::new(Arc::new(client_config), name)
+            .unwrap();
+        let mut tls = rustls::StreamOwned::new(conn, stream);
+        tls.write_all(request).unwrap();
+        let mut response = Vec::new();
+        // A peer closing without close_notify still sent its bytes.
+        let _ = tls.read_to_end(&mut response);
+        String::from_utf8_lossy(&response).into_owned()
+    }
+
+    fn inject_ca_pem_root(
+        ca: &crate::tls_inject::InjectCa,
+    ) -> rustls::pki_types::CertificateDer<'static> {
+        use rustls::pki_types::pem::PemObject;
+        rustls::pki_types::CertificateDer::from_pem_slice(
+            ca.cert_pem().as_bytes(),
+        )
+        .unwrap()
+    }
+
+    #[test]
+    fn e2e_https_injection_substitutes_secret_inside_the_tunnel() {
+        let fixture = tls_fixture();
+        let binding = crate::secret::SecretBinding::new(
+            "X_KEY",
+            "real-secret",
+            "127.0.0.1",
+        );
+        let placeholder = binding.placeholder.clone();
+        let ca = Arc::new(
+            crate::tls_inject::InjectCa::generate(&["127.0.0.1".into()])
+                .unwrap(),
+        );
+        let root = inject_ca_pem_root(&ca);
+        let mut config = test_config(&["127.0.0.1"]);
+        config.secrets = vec![binding];
+        config.inject_ca = Some(ca);
+        config.danger_extra_roots = vec![fixture_root()];
+        let proxy = Proxy::start(config, None).unwrap();
+
+        // The child sends its placeholder in a chunked POST; the fixture
+        // (the real host, behind real TLS) receives the real value.
+        let request = format!(
+            "POST /v1/test HTTP/1.1\r\nHost: 127.0.0.1\r\n\
+             x-test-key: {placeholder}\r\nConnection: keep-alive\r\n\
+             Transfer-Encoding: chunked\r\n\r\n2\r\nhi\r\n0\r\n\r\n"
+        );
+        let response = https_through_proxy(
+            proxy.port(),
+            fixture,
+            root,
+            request.as_bytes(),
+        );
+        assert!(response.starts_with("HTTP/1.1 200 OK"), "{response}");
+        assert!(response.contains("key=real-secret"), "{response}");
+        assert!(!response.contains(&placeholder), "{response}");
+    }
+
+    #[test]
+    fn e2e_https_injection_leaves_an_uncovered_tunnel_opaque() {
+        // The CA covers another host, so the tunnel to the fixture is
+        // the usual opaque one: the client must trust the fixture's own
+        // certificate, and the placeholder goes through untouched.
+        let fixture = tls_fixture();
+        let binding =
+            crate::secret::SecretBinding::new("X_KEY", "real", "api.example");
+        let placeholder = binding.placeholder.clone();
+        let ca = Arc::new(
+            crate::tls_inject::InjectCa::generate(&["api.example".into()])
+                .unwrap(),
+        );
+        let mut config = test_config(&["127.0.0.1"]);
+        config.secrets = vec![binding];
+        config.inject_ca = Some(ca);
+        let proxy = Proxy::start(config, None).unwrap();
+        let request = format!(
+            "GET / HTTP/1.1\r\nHost: 127.0.0.1\r\nx-test-key: {placeholder}\r\n\r\n"
+        );
+        let response = https_through_proxy(
+            proxy.port(),
+            fixture,
+            fixture_root(),
+            request.as_bytes(),
+        );
+        assert!(
+            response.contains(&format!("key={placeholder}")),
+            "{response}"
+        );
+    }
+
+    #[test]
+    fn e2e_https_injection_refuses_ambiguous_framing_inside_the_tunnel() {
+        let binding =
+            crate::secret::SecretBinding::new("X_KEY", "real", "127.0.0.1");
+        let ca = Arc::new(
+            crate::tls_inject::InjectCa::generate(&["127.0.0.1".into()])
+                .unwrap(),
+        );
+        let root = inject_ca_pem_root(&ca);
+        let mut config = test_config(&["127.0.0.1"]);
+        config.secrets = vec![binding];
+        config.inject_ca = Some(ca);
+        let proxy = Proxy::start(config, None).unwrap();
+        // Port 1: nothing listens, so a dial would answer 502, not 400.
+        let response = https_through_proxy(
+            proxy.port(),
+            1,
+            root,
+            b"POST / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\
+              Content-Length: 4\r\n\r\n",
         );
+        assert_eq!(response, "HTTP/1.1 400 Bad Request\r\n\r\n");
     }
 
     #[test]
diff --git a/src/sandbox/bwrap.rs b/src/sandbox/bwrap.rs
index 0455512..dcd046b 100644
--- a/src/sandbox/bwrap.rs
+++ b/src/sandbox/bwrap.rs
@@ -1853,7 +1853,7 @@ pub fn build(
         opt_args.extend(m.to_args());
     }
 
-    opt_args.extend(proxy_socket_mount_args(config, proxy_socket)?);
+    opt_args.extend(proxy_socket_mount_args(config, proxy_socket, true)?);
     opt_args.extend(bridge_socket_mount_args(config, bridge_sockets)?);
 
     opt_args.extend(mount_set.isolation_args(
@@ -2224,18 +2224,53 @@ fn write_bwrap_args_fd(args: &[String]) -> Result<std::os::fd::RawFd, String> {
 /// the /tmp tmpfs already exists (the same constraint as the Landlock
 /// wrapper binary mount above). Writable bind: the bridge connect()s to
 /// it, and Unix socket connect does not cross network namespaces.
+///
+/// `launch` is false for a dry run, which shows the mounts a launch would
+/// make without a proxy having written the CA files.
 fn proxy_socket_mount_args(
     config: &Config,
     proxy_socket: Option<&Path>,
+    launch: bool,
 ) -> Result<Vec<String>, String> {
     let filtered =
         config.network_mode() == crate::config::NetworkMode::Filtered;
     match (filtered, proxy_socket) {
-        (true, Some(sock)) => Ok(Mount::Bind {
-            src: sock.to_path_buf(),
-            dest: PathBuf::from(crate::proxy::IN_SANDBOX_SOCK_PATH),
+        (true, Some(sock)) => {
+            let mut args = Mount::Bind {
+                src: sock.to_path_buf(),
+                dest: PathBuf::from(crate::proxy::IN_SANDBOX_SOCK_PATH),
+            }
+            .to_args();
+            // HTTPS injection: the trust bundle and the CA the proxy wrote
+            // beside its socket, read-only. A secret without them would
+            // send its placeholder over an unverifiable tunnel, so a
+            // missing file refuses the sandbox rather than dropping it.
+            if !config.secret_hosts.is_empty() {
+                let (bundle, ca) = crate::tls_inject::bundle_paths(sock);
+                for (src, dest) in [
+                    (bundle, crate::tls_inject::IN_SANDBOX_BUNDLE_PATH),
+                    (ca, crate::tls_inject::IN_SANDBOX_CA_PATH),
+                ] {
+                    if launch
+                        && std::fs::symlink_metadata(&src)
+                            .map_or(true, |m| !m.file_type().is_file())
+                    {
+                        return Err(format!(
+                            "--secret needs the proxy's CA file {}",
+                            src.display()
+                        ));
+                    }
+                    args.extend(
+                        Mount::RoBind {
+                            src,
+                            dest: PathBuf::from(dest),
+                        }
+                        .to_args(),
+                    );
+                }
+            }
+            Ok(args)
         }
-        .to_args()),
         // Filtered egress without the outer proxy would silently mean
         // "no egress at all" -- refuse to build the sandbox instead.
         (true, None) => {
@@ -2392,7 +2427,7 @@ fn build_dry_run_args_forwarded(
         args.extend(m.to_args());
     }
 
-    args.extend(proxy_socket_mount_args(config, proxy_socket)?);
+    args.extend(proxy_socket_mount_args(config, proxy_socket, false)?);
     args.extend(bridge_socket_mount_args(config, bridge_sockets)?);
 
     args.extend(mount_set.isolation_args(
@@ -2571,6 +2606,11 @@ fn discover_mounts_full(
                 }
             }
         }
+        // HTTPS injection: point the child's TLS clients at the mounted
+        // bundle (system roots plus the launch's CA).
+        if !config.secret_hosts.is_empty() {
+            vars.extend(crate::tls_inject::env_vars());
+        }
         vars
     } else {
         vec![]
@@ -6122,6 +6162,36 @@ mod tests {
                 && w[1] == "KEY"
                 && !w[2].starts_with("AIJAIL-PHANTOM-")
         }));
+        // HTTPS injection: the CA files are mounted read-only and named
+        // by the TLS clients' environment.
+        assert!(args.windows(3).any(|w| {
+            w[0] == "--ro-bind"
+                && w[1] == "/tmp/ai-jail-proxy-test.sock.ca-bundle.pem"
+                && w[2] == crate::tls_inject::IN_SANDBOX_BUNDLE_PATH
+        }));
+        assert!(args.windows(3).any(|w| {
+            w[0] == "--setenv"
+                && w[1] == "NODE_EXTRA_CA_CERTS"
+                && w[2] == crate::tls_inject::IN_SANDBOX_CA_PATH
+        }));
+    }
+
+    #[test]
+    fn a_launch_with_a_secret_refuses_missing_ca_files() {
+        let mut config = Config {
+            allow_hosts: vec!["api.anthropic.com".into()],
+            ..minimal_test_config()
+        };
+        config
+            .secret_hosts
+            .insert("KEY".into(), "api.anthropic.com".into());
+        let sock = std::env::temp_dir()
+            .join(format!("ai-jail-no-ca-{}.sock", std::process::id()));
+        let error =
+            proxy_socket_mount_args(&config, Some(&sock), true).unwrap_err();
+        assert!(error.contains("CA file"), "{error}");
+        // A dry run shows the mounts without the files.
+        assert!(proxy_socket_mount_args(&config, Some(&sock), false).is_ok());
     }
 
     #[test]
diff --git a/src/secret.rs b/src/secret.rs
index 8d236c8..a6cd775 100644
--- a/src/secret.rs
+++ b/src/secret.rs
@@ -3,14 +3,21 @@
 //!
 //! The sandbox environment holds a *placeholder* for each bound secret;
 //! the real value exists only in supervisor memory. The egress proxy
-//! substitutes placeholder -> real only inside the request head of
-//! absolute-form plain-HTTP requests that terminate at the binding's
-//! allowlisted host. CONNECT tunnels stay opaque and untouched.
+//! substitutes placeholder -> real only inside the request head of a
+//! request that terminates at one of the binding's allowlisted hosts:
+//! an absolute-form plain-HTTP request, or (Linux) an HTTPS request the
+//! proxy decrypts with a per-launch CA ([`crate::tls_inject`]). Every
+//! other CONNECT tunnel stays opaque and untouched.
 //!
-//! A placeholder is `AIJAIL-PHANTOM-<16 hex>`: deterministic per launch
-//! inputs, shaped so it can never collide with a real token, and
+//! A placeholder is `AIJAIL-PHANTOM-<16 hex>`, derived from the key, the
+//! value and a per-launch session nonce: two launches never share one,
+//! so a placeholder seen in one session's logs says nothing about the
+//! next. It is shaped so it can never collide with a real token, and is
 //! harmless when printed by dry-run or `ai-jail status`. It is not a
 //! credential -- knowing it authorizes nothing.
+//!
+//! A key may name several hosts (`--secret KEY=a.example,b.example`):
+//! each host gets its own binding, all sharing the key's placeholder.
 
 /// One bound secret: the env var `key`, the `placeholder` the sandbox
 /// sees, the `real` value that never leaves the supervisor, and the
@@ -24,9 +31,23 @@ pub(crate) struct SecretBinding {
 }
 
 impl SecretBinding {
+    #[cfg(test)]
     pub(crate) fn new(key: &str, real: &str, host: &str) -> Self {
-        let digest =
-            crate::audit::sha256_hex(format!("{key}:{real}").as_bytes());
+        Self::with_session(key, real, host, "")
+    }
+
+    /// The binding for one launch: `session` is that launch's random
+    /// nonce ([`session_nonce`]), so the same key and value get a
+    /// different placeholder in every session.
+    pub(crate) fn with_session(
+        key: &str,
+        real: &str,
+        host: &str,
+        session: &str,
+    ) -> Self {
+        let digest = crate::audit::sha256_hex(
+            format!("{key}:{real}:{session}").as_bytes(),
+        );
         SecretBinding {
             key: key.to_string(),
             placeholder: format!("AIJAIL-PHANTOM-{}", &digest[..16]),
@@ -48,6 +69,34 @@ impl std::fmt::Debug for SecretBinding {
     }
 }
 
+/// A random per-launch nonce for [`SecretBinding::with_session`]: 16
+/// bytes from the system RNG, hex-encoded. Falls back to the clock only
+/// if the RNG fails, which on Linux and macOS it does not.
+pub(crate) fn session_nonce() -> String {
+    use ring::rand::SecureRandom as _;
+    let mut bytes = [0_u8; 16];
+    if ring::rand::SystemRandom::new().fill(&mut bytes).is_err() {
+        let now = std::time::SystemTime::now()
+            .duration_since(std::time::UNIX_EPOCH)
+            .map_or(0, |d| d.as_nanos());
+        bytes = now.to_le_bytes();
+    }
+    bytes.iter().map(|b| format!("{b:02x}")).collect()
+}
+
+/// The hosts a `secret_hosts` value names: one host, or several
+/// separated by commas (`api.github.com,github.com`). Empty items and
+/// surrounding spaces are dropped; order is kept and duplicates removed.
+pub(crate) fn split_hosts(value: &str) -> Vec<String> {
+    let mut hosts: Vec<String> = Vec::new();
+    for host in value.split(',').map(str::trim).filter(|h| !h.is_empty()) {
+        if !hosts.iter().any(|h| h.eq_ignore_ascii_case(host)) {
+            hosts.push(host.to_string());
+        }
+    }
+    hosts
+}
+
 /// Byte-replace every placeholder occurrence in `head` (the request
 /// line and headers only -- never the body) with the real value,
 /// returning the rewritten bytes and the substitution count for
@@ -57,8 +106,7 @@ pub(crate) fn rewrite_head(
     head: &[u8],
     bindings: &[SecretBinding],
 ) -> (Vec<u8>, usize) {
-    let mut out = head.to_vec();
-    let mut substitutions = 0;
+    let (mut out, mut substitutions) = rewrite_basic_auth(head, bindings);
     for binding in bindings {
         let (rewritten, count) = replace_all(
             &out,
@@ -71,6 +119,132 @@ pub(crate) fn rewrite_head(
     (out, substitutions)
 }
 
+/// `Authorization: Basic` carries `base64(user:password)`, so a
+/// placeholder used as the password -- `git push` over HTTPS with a token
+/// does exactly that -- is invisible to a byte search. Decode each Basic
+/// credential in the head, substitute, and re-encode it. Any other
+/// header passes through unchanged; a credential that does not decode,
+/// or holds no placeholder, is left byte for byte.
+fn rewrite_basic_auth(
+    head: &[u8],
+    bindings: &[SecretBinding],
+) -> (Vec<u8>, usize) {
+    let mut out = Vec::with_capacity(head.len());
+    let mut substitutions = 0;
+    let mut rest = head;
+    loop {
+        let line_end = find_subslice(rest, b"\r\n").unwrap_or(rest.len());
+        let line = &rest[..line_end];
+        out.extend_from_slice(&rewrite_basic_line(
+            line,
+            bindings,
+            &mut substitutions,
+        ));
+        if line_end == rest.len() {
+            break;
+        }
+        out.extend_from_slice(b"\r\n");
+        rest = &rest[line_end + 2..];
+    }
+    (out, substitutions)
+}
+
+fn rewrite_basic_line(
+    line: &[u8],
+    bindings: &[SecretBinding],
+    substitutions: &mut usize,
+) -> Vec<u8> {
+    let Some(colon) = line.iter().position(|b| *b == b':') else {
+        return line.to_vec();
+    };
+    let (name, value) = (&line[..colon], &line[colon + 1..]);
+    let is_auth = name.eq_ignore_ascii_case(b"authorization")
+        || name.eq_ignore_ascii_case(b"proxy-authorization");
+    let trimmed = value.trim_ascii_start();
+    let scheme_len = b"basic ".len();
+    if !is_auth
+        || trimmed.len() <= scheme_len
+        || !trimmed[..scheme_len].eq_ignore_ascii_case(b"basic ")
+    {
+        return line.to_vec();
+    }
+    let encoded = trimmed[scheme_len..].trim_ascii();
+    let Some(decoded) = base64_decode(encoded) else {
+        return line.to_vec();
+    };
+    let mut credential = decoded;
+    let mut count = 0;
+    for binding in bindings {
+        let (rewritten, n) = replace_all(
+            &credential,
+            binding.placeholder.as_bytes(),
+            binding.real.as_bytes(),
+        );
+        credential = rewritten;
+        count += n;
+    }
+    if count == 0 {
+        return line.to_vec();
+    }
+    *substitutions += count;
+    let mut rebuilt = name.to_vec();
+    rebuilt.extend_from_slice(b": Basic ");
+    rebuilt.extend_from_slice(base64_encode(&credential).as_bytes());
+    rebuilt
+}
+
+const BASE64: &[u8; 64] =
+    b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+/// Standard base64 with padding (RFC 4648 §4), the alphabet Basic auth
+/// uses. Small enough to keep here rather than add a dependency.
+fn base64_encode(input: &[u8]) -> String {
+    let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
+    for chunk in input.chunks(3) {
+        let b = [
+            chunk[0],
+            chunk.get(1).copied().unwrap_or(0),
+            chunk.get(2).copied().unwrap_or(0),
+        ];
+        let n =
+            (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
+        for i in 0..4 {
+            if i <= chunk.len() {
+                out.push(char::from(BASE64[(n >> (18 - 6 * i)) as usize & 63]));
+            } else {
+                out.push('=');
+            }
+        }
+    }
+    out
+}
+
+/// The inverse of [`base64_encode`]; `None` for anything that is not
+/// canonical padded base64.
+fn base64_decode(input: &[u8]) -> Option<Vec<u8>> {
+    if input.is_empty() || !input.len().is_multiple_of(4) {
+        return None;
+    }
+    let value = |c: u8| BASE64.iter().position(|a| *a == c).map(|p| p as u32);
+    let mut out = Vec::with_capacity(input.len() / 4 * 3);
+    let quads = input.len() / 4;
+    for (index, quad) in input.chunks(4).enumerate() {
+        let last = index + 1 == quads;
+        let pad = quad.iter().rev().take_while(|c| **c == b'=').count();
+        if pad > 2 || (pad > 0 && !last) {
+            return None;
+        }
+        let mut n = 0_u32;
+        for (i, c) in quad.iter().enumerate() {
+            let v = if i >= 4 - pad { 0 } else { value(*c)? };
+            n |= v << (18 - 6 * i);
+        }
+        let bytes = [(n >> 16) as u8, (n >> 8) as u8, n as u8];
+        out.extend_from_slice(&bytes[..3 - pad]);
+    }
+    Some(out)
+}
+
 /// Replace every non-overlapping occurrence of `needle` in `haystack`
 /// with `replacement`.
 fn replace_all(
@@ -149,6 +323,81 @@ mod tests {
         assert_eq!(out, head);
     }
 
+    #[test]
+    fn a_session_nonce_changes_the_placeholder() {
+        let a = SecretBinding::with_session("KEY", "v", "h.example", "s1");
+        let b = SecretBinding::with_session("KEY", "v", "h.example", "s1");
+        let c = SecretBinding::with_session("KEY", "v", "h.example", "s2");
+        assert_eq!(a.placeholder, b.placeholder);
+        assert_ne!(a.placeholder, c.placeholder);
+        let (n1, n2) = (session_nonce(), session_nonce());
+        assert_eq!(n1.len(), 32);
+        assert_ne!(n1, n2);
+    }
+
+    #[test]
+    fn secret_hosts_value_splits_on_commas() {
+        assert_eq!(split_hosts("api.github.com"), ["api.github.com"]);
+        assert_eq!(
+            split_hosts(" api.github.com, github.com ,,GitHub.com"),
+            ["api.github.com", "github.com"]
+        );
+        assert!(split_hosts(" , ").is_empty());
+    }
+
+    #[test]
+    fn base64_round_trips_and_refuses_garbage() {
+        for raw in [
+            &b""[..],
+            b"f",
+            b"fo",
+            b"foo",
+            b"foob",
+            b"x-access-token:abc",
+        ] {
+            if raw.is_empty() {
+                continue;
+            }
+            let encoded = base64_encode(raw);
+            assert_eq!(base64_decode(encoded.as_bytes()).as_deref(), Some(raw));
+        }
+        assert_eq!(base64_encode(b"user:pass"), "dXNlcjpwYXNz");
+        for bad in [&b"abc"[..], b"a===", b"ab=c", b"ab!c", b"YQ==YQ=="] {
+            assert_eq!(base64_decode(bad), None, "{bad:?}");
+        }
+    }
+
+    #[test]
+    fn basic_auth_carrying_a_placeholder_is_rewritten() {
+        // git push over HTTPS: the token is the Basic password.
+        let b = binding();
+        let credential = base64_encode(
+            format!("x-access-token:{}", b.placeholder).as_bytes(),
+        );
+        let head = format!(
+            "POST /org/repo.git/git-receive-pack HTTP/1.1\r\n\
+             Host: github.com\r\n\
+             Authorization: Basic {credential}\r\n\r\n"
+        );
+        let (out, count) = rewrite_head(head.as_bytes(), &[binding()]);
+        let out = String::from_utf8(out).unwrap();
+        assert_eq!(count, 1);
+        let expected = base64_encode(b"x-access-token:sk-ant-real");
+        assert!(
+            out.contains(&format!("Authorization: Basic {expected}\r\n")),
+            "{out}"
+        );
+        assert!(out.ends_with("\r\n\r\n"));
+    }
+
+    #[test]
+    fn basic_auth_without_a_placeholder_is_left_byte_for_byte() {
+        let head = b"GET / HTTP/1.1\r\nAuthorization: Basic dXNlcjpwYXNz\r\nX-Other: Basic AIJAIL\r\n\r\n";
+        let (out, count) = rewrite_head(head, &[binding()]);
+        assert_eq!(count, 0);
+        assert_eq!(out, head);
+    }
+
     #[test]
     fn rewrite_head_treats_head_as_bytes() {
         // A placeholder straddling a multibyte boundary still matches;
diff --git a/src/tls_inject.rs b/src/tls_inject.rs
new file mode 100644
index 0000000..b386d9c
--- /dev/null
+++ b/src/tls_inject.rs
@@ -0,0 +1,444 @@
+//! HTTPS credential injection (Zeo proposal §6.53, 2026-11-27).
+//!
+//! `--secret` keeps a credential out of the sandbox: the child sees a
+//! placeholder, and the egress proxy puts the real value into requests
+//! to the binding's hosts. Plain HTTP was enough to see the request head;
+//! HTTPS was not -- a CONNECT tunnel is opaque, so a placeholder sent over
+//! TLS went out unchanged and authentication failed.
+//!
+//! This module lets the proxy open exactly those tunnels. At launch it
+//! generates a CA whose key lives only in this process's memory and whose
+//! name constraints permit the secret-bound hosts alone, so even a copy of
+//! the key could not impersonate any other site. The sandbox trusts that
+//! CA through a bundle file (the system roots plus the CA) mounted next to
+//! the proxy socket and named by the usual CA environment variables. For a
+//! CONNECT to a secret-bound host the proxy answers as that host with a
+//! short-lived leaf certificate, decrypts one request, rewrites its head,
+//! and re-originates it over real TLS to the real host. Every other tunnel
+//! stays opaque and untouched.
+//!
+//! The private keys never reach disk, a log or the sandbox; the files
+//! written here hold public certificates only.
+
+use std::{
+    collections::HashMap,
+    fs::OpenOptions,
+    io::Write as _,
+    os::unix::fs::OpenOptionsExt as _,
+    path::{Path, PathBuf},
+    sync::{Arc, Mutex},
+    time::{Duration, SystemTime},
+};
+
+use rcgen::{
+    BasicConstraints, CertificateParams, CidrSubnet, DistinguishedName, DnType,
+    ExtendedKeyUsagePurpose, GeneralSubtree, IsCa, Issuer, KeyPair,
+    KeyUsagePurpose, NameConstraints,
+};
+use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
+
+/// How long a leaf certificate is valid. Short, because nothing outside
+/// this launch ever needs it; re-minted when it runs out.
+const LEAF_LIFETIME: Duration = Duration::from_secs(24 * 60 * 60);
+/// How long the CA is valid: well past any session, and it dies with the
+/// process anyway.
+const CA_LIFETIME: Duration = Duration::from_secs(30 * 24 * 60 * 60);
+/// Clock skew allowed between the supervisor and the sandbox.
+const BACKDATE: Duration = Duration::from_secs(5 * 60);
+
+/// Where the sandbox finds the CA, relative to the proxy socket's
+/// host-side path ([`bundle_paths`]) and inside the sandbox.
+pub(crate) const IN_SANDBOX_BUNDLE_PATH: &str = "/tmp/.ai-jail-ca-bundle.pem";
+pub(crate) const IN_SANDBOX_CA_PATH: &str = "/tmp/.ai-jail-ca.pem";
+
+/// System trust bundles, in the order the common distributions place
+/// them. The first that exists is copied into the sandbox's bundle so
+/// every tunnel that is not intercepted keeps verifying as before.
+const SYSTEM_BUNDLES: &[&str] = &[
+    "/etc/ssl/certs/ca-certificates.crt",
+    "/etc/pki/tls/certs/ca-bundle.crt",
+    "/etc/ssl/ca-bundle.pem",
+    "/etc/ssl/cert.pem",
+];
+
+/// The launch's injection CA and the leaf configurations minted from it.
+pub(crate) struct InjectCa {
+    params: CertificateParams,
+    key: KeyPair,
+    cert_pem: String,
+    hosts: Vec<String>,
+    leaves: Mutex<HashMap<String, (SystemTime, Arc<rustls::ServerConfig>)>>,
+}
+
+impl std::fmt::Debug for InjectCa {
+    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+        f.debug_struct("InjectCa")
+            .field("hosts", &self.hosts)
+            .field("key", &"[in memory only]")
+            .finish()
+    }
+}
+
+impl InjectCa {
+    /// A CA that may sign certificates for `hosts` (and their
+    /// subdomains, which is how name constraints read a DNS name) and
+    /// nothing else.
+    pub(crate) fn generate(hosts: &[String]) -> Result<Self, String> {
+        let mut hosts: Vec<String> = hosts
+            .iter()
+            .map(|h| h.trim_end_matches('.').to_lowercase())
+            .collect();
+        hosts.sort();
+        hosts.dedup();
+        if hosts.is_empty() {
+            return Err("the injection CA needs at least one host".into());
+        }
+        let key = KeyPair::generate().map_err(|e| {
+            format!("cannot generate the injection CA key: {e}")
+        })?;
+        let mut params = CertificateParams::new(Vec::<String>::new())
+            .map_err(|e| format!("injection CA parameters: {e}"))?;
+        let mut name = DistinguishedName::new();
+        name.push(DnType::CommonName, "ai-jail per-launch secret injection CA");
+        params.distinguished_name = name;
+        params.is_ca = IsCa::Ca(BasicConstraints::Constrained(0));
+        params.key_usages =
+            vec![KeyUsagePurpose::KeyCertSign, KeyUsagePurpose::CrlSign];
+        params.name_constraints = Some(name_constraints(&hosts));
+        let now = SystemTime::now();
+        params.not_before = (now - BACKDATE).into();
+        params.not_after = (now + CA_LIFETIME).into();
+        let cert = params
+            .self_signed(&key)
+            .map_err(|e| format!("cannot sign the injection CA: {e}"))?;
+        Ok(InjectCa {
+            cert_pem: cert.pem(),
+            params,
+            key,
+            hosts,
+            leaves: Mutex::new(HashMap::new()),
+        })
+    }
+
+    /// The CA certificate (public), PEM.
+    pub(crate) fn cert_pem(&self) -> &str {
+        &self.cert_pem
+    }
+
+    /// Whether the CA may speak for `host`: only the secret-bound hosts
+    /// themselves, never a sibling the name constraint would also allow.
+    pub(crate) fn covers(&self, host: &str) -> bool {
+        let host = host.trim_end_matches('.').to_lowercase();
+        self.hosts.contains(&host)
+    }
+
+    /// A TLS server configuration presenting a fresh leaf for `host`,
+    /// minted on first use and reused until it nears expiry. HTTP/1.1
+    /// only, so the decrypted stream is a request head the proxy can read
+    /// (an HTTP/2 client falls back, as ALPN allows).
+    pub(crate) fn server_config(
+        &self,
+        host: &str,
+    ) -> Result<Arc<rustls::ServerConfig>, String> {
+        let host = host.trim_end_matches('.').to_lowercase();
+        if !self.covers(&host) {
+            return Err(format!("{host} is not a secret-bound host"));
+        }
+        let now = SystemTime::now();
+        let mut leaves =
+            self.leaves.lock().map_err(|_| "leaf cache poisoned")?;
+        if let Some((expires, config)) = leaves.get(&host)
+            && *expires > now + BACKDATE
+        {
+            return Ok(Arc::clone(config));
+        }
+        let (expires, config) = self.mint(&host, now)?;
+        let config = Arc::new(config);
+        leaves.insert(host, (expires, Arc::clone(&config)));
+        Ok(config)
+    }
+
+    fn mint(
+        &self,
+        host: &str,
+        now: SystemTime,
+    ) -> Result<(SystemTime, rustls::ServerConfig), String> {
+        let leaf_key = KeyPair::generate()
+            .map_err(|e| format!("cannot generate a leaf key: {e}"))?;
+        let mut params = CertificateParams::new(vec![host.to_string()])
+            .map_err(|e| format!("leaf parameters for {host}: {e}"))?;
+        let mut name = DistinguishedName::new();
+        name.push(DnType::CommonName, host);
+        params.distinguished_name = name;
+        params.is_ca = IsCa::ExplicitNoCa;
+        params.key_usages = vec![KeyUsagePurpose::DigitalSignature];
+        params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth];
+        params.use_authority_key_identifier_extension = true;
+        let expires = now + LEAF_LIFETIME;
+        params.not_before = (now - BACKDATE).into();
+        params.not_after = expires.into();
+        let issuer = Issuer::from_params(&self.params, &self.key);
+        let leaf = params
+            .signed_by(&leaf_key, &issuer)
+            .map_err(|e| format!("cannot sign the leaf for {host}: {e}"))?;
+        let chain: Vec<CertificateDer<'static>> = vec![leaf.der().clone()];
+        let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(
+            leaf_key.serialize_der(),
+        ));
+        let mut config = rustls::ServerConfig::builder()
+            .with_no_client_auth()
+            .with_single_cert(chain, key)
+            .map_err(|e| format!("TLS server configuration for {host}: {e}"))?;
+        config.alpn_protocols = vec![b"http/1.1".to_vec()];
+        Ok((expires, config))
+    }
+}
+
+/// The CA may sign for the bound hosts and nothing else. A DNS name
+/// permits that name and its subdomains (RFC 5280 §4.2.1.10; `covers`
+/// narrows interception to the exact hosts); an IP literal permits that
+/// one address. A name form with no permitted entry is otherwise
+/// unconstrained, so when no IP literal is bound every address is
+/// excluded outright -- the CA can never vouch for an IP.
+fn name_constraints(hosts: &[String]) -> NameConstraints {
+    let mut permitted = Vec::new();
+    let mut any_ip = false;
+    for host in hosts {
+        match host.parse::<std::net::IpAddr>() {
+            Ok(ip) => {
+                any_ip = true;
+                let prefix = if ip.is_ipv4() { 32 } else { 128 };
+                permitted.push(GeneralSubtree::IpAddress(
+                    CidrSubnet::from_addr_prefix(ip, prefix),
+                ));
+            }
+            Err(_) => permitted.push(GeneralSubtree::DnsName(host.clone())),
+        }
+    }
+    let excluded = if any_ip {
+        Vec::new()
+    } else {
+        vec![
+            GeneralSubtree::IpAddress(CidrSubnet::from_v4_prefix([0; 4], 0)),
+            GeneralSubtree::IpAddress(CidrSubnet::from_v6_prefix([0; 16], 0)),
+        ]
+    };
+    NameConstraints {
+        permitted_subtrees: permitted,
+        excluded_subtrees: excluded,
+    }
+}
+
+/// Host-side paths of the two files the sandbox mounts, derived from the
+/// proxy socket's path so they share its per-launch nonce and its
+/// lifetime: (bundle = system roots + CA, CA alone).
+pub(crate) fn bundle_paths(proxy_socket: &Path) -> (PathBuf, PathBuf) {
+    let base = proxy_socket.as_os_str().to_string_lossy();
+    (
+        PathBuf::from(format!("{base}.ca-bundle.pem")),
+        PathBuf::from(format!("{base}.ca.pem")),
+    )
+}
+
+/// Write the bundle and the CA certificate next to the proxy socket,
+/// mode 0600 and refusing to follow or reuse an existing path, so a
+/// planted file or symlink in the temp directory cannot stand in for
+/// them. The bundle starts with the first system bundle found; without
+/// one, the sandbox's non-intercepted tunnels would fail verification,
+/// so that is an error rather than a silent CA-only bundle.
+pub(crate) fn write_bundle(
+    ca: &InjectCa,
+    proxy_socket: &Path,
+) -> Result<(PathBuf, PathBuf), String> {
+    let system = SYSTEM_BUNDLES
+        .iter()
+        .find_map(|path| std::fs::read_to_string(path).ok())
+        .ok_or_else(|| {
+            format!(
+                "--secret over HTTPS needs the system CA bundle, found none of {}",
+                SYSTEM_BUNDLES.join(", ")
+            )
+        })?;
+    let (bundle_path, ca_path) = bundle_paths(proxy_socket);
+    let mut bundle = system;
+    if !bundle.ends_with('\n') {
+        bundle.push('\n');
+    }
+    bundle.push_str(ca.cert_pem());
+    write_new_private(&bundle_path, bundle.as_bytes())?;
+    if let Err(e) = write_new_private(&ca_path, ca.cert_pem().as_bytes()) {
+        let _ = std::fs::remove_file(&bundle_path);
+        return Err(e);
+    }
+    Ok((bundle_path, ca_path))
+}
+
+fn write_new_private(path: &Path, bytes: &[u8]) -> Result<(), String> {
+    let mut file = OpenOptions::new()
+        .write(true)
+        .create_new(true)
+        .mode(0o600)
+        .custom_flags(nix::fcntl::OFlag::O_NOFOLLOW.bits())
+        .open(path)
+        .map_err(|e| format!("cannot create {}: {e}", path.display()))?;
+    file.write_all(bytes)
+        .and_then(|()| file.sync_all())
+        .map_err(|e| format!("cannot write {}: {e}", path.display()))
+}
+
+/// Remove the two files ([`write_bundle`]); quiet, it runs on teardown.
+pub(crate) fn remove_bundle(proxy_socket: &Path) {
+    let (bundle, ca) = bundle_paths(proxy_socket);
+    let _ = std::fs::remove_file(bundle);
+    let _ = std::fs::remove_file(ca);
+}
+
+/// The environment that points the sandbox's TLS clients at the bundle:
+/// OpenSSL, curl, Python requests and git read a whole bundle; Node adds
+/// extra CAs to its built-in roots, so it gets the CA alone.
+pub(crate) fn env_vars() -> Vec<(String, String)> {
+    let bundle = IN_SANDBOX_BUNDLE_PATH.to_string();
+    vec![
+        ("SSL_CERT_FILE".into(), bundle.clone()),
+        ("CURL_CA_BUNDLE".into(), bundle.clone()),
+        ("REQUESTS_CA_BUNDLE".into(), bundle.clone()),
+        ("GIT_SSL_CAINFO".into(), bundle),
+        ("NODE_EXTRA_CA_CERTS".into(), IN_SANDBOX_CA_PATH.into()),
+    ]
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    fn hosts(list: &[&str]) -> Vec<String> {
+        list.iter().map(|h| h.to_string()).collect()
+    }
+
+    #[test]
+    fn the_ca_covers_its_hosts_alone() {
+        let ca = InjectCa::generate(&hosts(&["API.github.com.", "github.com"]))
+            .unwrap();
+        assert!(ca.covers("api.github.com"));
+        assert!(ca.covers("github.com"));
+        // A subdomain the name constraint would allow is still refused:
+        // the proxy intercepts exactly the bound hosts.
+        assert!(!ca.covers("evil.github.com"));
+        assert!(!ca.covers("example.com"));
+        assert!(ca.server_config("example.com").is_err());
+        assert!(ca.cert_pem().starts_with("-----BEGIN CERTIFICATE-----"));
+        assert!(!format!("{ca:?}").contains("PRIVATE"));
+        assert!(InjectCa::generate(&[]).is_err());
+    }
+
+    #[test]
+    fn a_leaf_is_minted_once_and_speaks_http_1_1_only() {
+        let ca = InjectCa::generate(&hosts(&["api.example.com"])).unwrap();
+        let first = ca.server_config("api.example.com").unwrap();
+        let again = ca.server_config("API.example.com.").unwrap();
+        assert!(Arc::ptr_eq(&first, &again), "cached per host");
+        assert_eq!(first.alpn_protocols, vec![b"http/1.1".to_vec()]);
+    }
+
+    #[test]
+    fn a_client_trusting_the_ca_completes_a_handshake_with_the_leaf() {
+        // The whole chain, in memory: a rustls client that trusts only the
+        // CA connects to the leaf's server config for the bound host.
+        let ca = InjectCa::generate(&hosts(&["api.example.com"])).unwrap();
+        let server_config = ca.server_config("api.example.com").unwrap();
+        let ca_der = rustls_pemfile_like(ca.cert_pem());
+        let mut roots = rustls::RootCertStore::empty();
+        roots.add(ca_der).unwrap();
+        let client_config = rustls::ClientConfig::builder()
+            .with_root_certificates(roots)
+            .with_no_client_auth();
+        let name =
+            rustls::pki_types::ServerName::try_from("api.example.com").unwrap();
+        let mut client =
+            rustls::ClientConnection::new(Arc::new(client_config), name)
+                .unwrap();
+        let mut server = rustls::ServerConnection::new(server_config).unwrap();
+        for _ in 0..10 {
+            let mut buf = Vec::new();
+            client.write_tls(&mut buf).unwrap();
+            if !buf.is_empty() {
+                server.read_tls(&mut buf.as_slice()).unwrap();
+                server.process_new_packets().unwrap();
+            }
+            let mut buf = Vec::new();
+            server.write_tls(&mut buf).unwrap();
+            if !buf.is_empty() {
+                client.read_tls(&mut buf.as_slice()).unwrap();
+                client.process_new_packets().unwrap();
+            }
+            if !client.is_handshaking() && !server.is_handshaking() {
+                return;
+            }
+        }
+        panic!("the handshake did not complete");
+    }
+
+    /// The one certificate in a PEM string, as DER (tests only).
+    fn rustls_pemfile_like(pem: &str) -> CertificateDer<'static> {
+        let body: String =
+            pem.lines().filter(|l| !l.starts_with("-----")).collect();
+        CertificateDer::from(decode_b64(&body))
+    }
+
+    fn decode_b64(text: &str) -> Vec<u8> {
+        const A: &[u8; 64] =
+            b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+        let mut bits = 0_u32;
+        let mut n = 0;
+        let mut out = Vec::new();
+        for c in text.bytes().filter(|c| *c != b'=') {
+            let v = A.iter().position(|a| *a == c).unwrap() as u32;
+            bits = (bits << 6) | v;
+            n += 6;
+            if n >= 8 {
+                n -= 8;
+                out.push((bits >> n) as u8);
+            }
+        }
+        out
+    }
+
+    #[test]
+    fn the_bundle_files_are_private_new_and_removed() {
+        let dir = std::env::temp_dir()
+            .join(format!("ai-jail-tls-inject-test-{}", std::process::id()));
+        let _ = std::fs::remove_dir_all(&dir);
+        std::fs::create_dir_all(&dir).unwrap();
+        let socket = dir.join("proxy.sock");
+        let ca = InjectCa::generate(&hosts(&["api.example.com"])).unwrap();
+        if SYSTEM_BUNDLES.iter().all(|p| !Path::new(p).exists()) {
+            assert!(write_bundle(&ca, &socket).is_err());
+            return;
+        }
+        let (bundle, ca_file) = write_bundle(&ca, &socket).unwrap();
+        use std::os::unix::fs::PermissionsExt as _;
+        for path in [&bundle, &ca_file] {
+            let mode = std::fs::metadata(path).unwrap().permissions().mode();
+            assert_eq!(mode & 0o777, 0o600, "{}", path.display());
+        }
+        let text = std::fs::read_to_string(&bundle).unwrap();
+        assert!(text.ends_with(ca.cert_pem()));
+        assert!(!text.contains("PRIVATE KEY"));
+        // A second write never reuses an existing path.
+        assert!(write_bundle(&ca, &socket).is_err());
+        remove_bundle(&socket);
+        assert!(!bundle.exists() && !ca_file.exists());
+        let _ = std::fs::remove_dir_all(&dir);
+    }
+
+    #[test]
+    fn the_sandbox_env_names_the_mounted_files() {
+        let vars = env_vars();
+        let get = |k: &str| {
+            vars.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str())
+        };
+        assert_eq!(get("SSL_CERT_FILE"), Some(IN_SANDBOX_BUNDLE_PATH));
+        assert_eq!(get("GIT_SSL_CAINFO"), Some(IN_SANDBOX_BUNDLE_PATH));
+        assert_eq!(get("NODE_EXTRA_CA_CERTS"), Some(IN_SANDBOX_CA_PATH));
+    }
+}
diff --git a/tests/phantom_secrets.rs b/tests/phantom_secrets.rs
index 4578404..6f14381 100644
--- a/tests/phantom_secrets.rs
+++ b/tests/phantom_secrets.rs
@@ -179,6 +179,39 @@ fn phantom_proxy_substitutes_real_value_over_tls() {
     );
 }
 
+#[test]
+fn phantom_https_is_injected_inside_the_tunnel() {
+    // The usual client path: HTTPS through CONNECT, trusting only what
+    // ai-jail mounted. curl reads CURL_CA_BUNDLE (system roots plus the
+    // launch's CA); the proxy answers the bound host with a leaf from that
+    // CA and puts the real value in before re-originating the request.
+    // `--noproxy ''`: loopback is in no_proxy, and the fixture listens on
+    // it. Basic auth is checked by the proxy's own tests.
+    require_sandbox!();
+    let fixture = tls_fixture();
+    let script = format!(
+        "test \"$CURL_CA_BUNDLE\" = /tmp/.ai-jail-ca-bundle.pem || exit 3; \
+         curl --noproxy '' -sS --retry 20 --retry-delay 0 \
+         --retry-connrefused --max-time 20 -H \"x-test-key: $X_TEST_KEY\" \
+         https://127.0.0.1:{fixture}/v1/models"
+    );
+    let output = phantom_run(fixture, false, &script);
+    let stdout = String::from_utf8_lossy(&output.stdout);
+    let stderr = String::from_utf8_lossy(&output.stderr);
+    assert!(
+        output.status.success(),
+        "run failed: stdout={stdout:?} stderr={stderr:?}"
+    );
+    assert!(
+        stdout.contains(&format!("key={REAL}")),
+        "real value not substituted over HTTPS: {stdout:?}"
+    );
+    assert!(
+        !stdout.contains("AIJAIL-PHANTOM"),
+        "placeholder reached upstream: {stdout:?}"
+    );
+}
+
 #[test]
 fn phantom_lockdown_still_substitutes() {
     require_sandbox!();
