fbi-proxy 1.15.0 → 1.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -4
- package/dist/cli.js +9619 -1772
- package/package.json +4 -1
- package/release/fbi-proxy-linux-arm64 +0 -0
- package/release/fbi-proxy-linux-x64 +0 -0
- package/release/fbi-proxy-macos-arm64 +0 -0
- package/release/fbi-proxy-macos-x64 +0 -0
- package/release/fbi-proxy-windows-arm64.exe +0 -0
- package/release/fbi-proxy-windows-x64.exe +0 -0
- package/rs/fbi-proxy.rs +648 -120
- package/rs/lib.rs +1 -0
- package/rs/routes.rs +226 -31
- package/rs/tls.rs +243 -0
- package/ts/adminClient.ts +124 -0
- package/ts/auth/authConfig.ts +19 -1
- package/ts/cli.ts +158 -2
- package/ts/install-port-forward.ts +152 -0
- package/ts/routes.ts +50 -0
- package/ts/rulesCli.ts +166 -0
- package/ts/setup.ts +374 -0
package/rs/tls.rs
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
//! Self-signed TLS support for `--tls` mode (Phase 1: no system trust
|
|
2
|
+
//! install). Generates a self-signed certificate for the configured
|
|
3
|
+
//! domain (with `*.<domain>` SAN) and persists it under
|
|
4
|
+
//! `~/.config/fbi-proxy/certs/` so the same fingerprint survives
|
|
5
|
+
//! restarts — browsers can "remember the exception" once.
|
|
6
|
+
//!
|
|
7
|
+
//! The browser warning is expected in this phase. Use Phase 2
|
|
8
|
+
//! (`fbi-proxy trust`) to install a local CA into the system trust
|
|
9
|
+
//! store for a clean lock-icon experience.
|
|
10
|
+
|
|
11
|
+
use std::path::{Path, PathBuf};
|
|
12
|
+
use std::sync::Arc;
|
|
13
|
+
|
|
14
|
+
use rcgen::{CertificateParams, DnType, DistinguishedName, KeyPair, SanType};
|
|
15
|
+
use tokio_rustls::TlsAcceptor;
|
|
16
|
+
use tokio_rustls::rustls::ServerConfig;
|
|
17
|
+
use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer, pem::PemObject};
|
|
18
|
+
|
|
19
|
+
pub type BoxError = Box<dyn std::error::Error + Send + Sync>;
|
|
20
|
+
|
|
21
|
+
/// Where on-disk certs live. Layout: `{base}/certs/{domain}.{pem,key}`.
|
|
22
|
+
pub fn default_cert_dir() -> PathBuf {
|
|
23
|
+
let base = std::env::var_os("XDG_CONFIG_HOME")
|
|
24
|
+
.map(PathBuf::from)
|
|
25
|
+
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
|
|
26
|
+
.unwrap_or_else(|| PathBuf::from("."));
|
|
27
|
+
base.join("fbi-proxy").join("certs")
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/// Path to the cert file for a given domain (sibling `.key` lives at
|
|
31
|
+
/// the same stem). Use this when you need to install the cert into a
|
|
32
|
+
/// system trust store after `build_acceptor` has materialized it.
|
|
33
|
+
pub fn cert_pem_path(domain: &str, cert_dir: &Path) -> PathBuf {
|
|
34
|
+
let slug = if domain.is_empty() { "localhost" } else { domain };
|
|
35
|
+
cert_dir.join(format!("{slug}.pem"))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/// Whether the given cert is currently a trusted anchor on this
|
|
39
|
+
/// system. Returns `false` if the check itself can't be performed
|
|
40
|
+
/// (unsupported platform, missing tool) — callers should treat that
|
|
41
|
+
/// as "no, attempt install."
|
|
42
|
+
pub fn is_trusted(cert_path: &Path) -> bool {
|
|
43
|
+
#[cfg(target_os = "macos")]
|
|
44
|
+
{
|
|
45
|
+
std::process::Command::new("security")
|
|
46
|
+
.args(["verify-cert", "-c"])
|
|
47
|
+
.arg(cert_path)
|
|
48
|
+
.stdout(std::process::Stdio::null())
|
|
49
|
+
.stderr(std::process::Stdio::null())
|
|
50
|
+
.status()
|
|
51
|
+
.map(|s| s.success())
|
|
52
|
+
.unwrap_or(false)
|
|
53
|
+
}
|
|
54
|
+
#[cfg(not(target_os = "macos"))]
|
|
55
|
+
{
|
|
56
|
+
let _ = cert_path;
|
|
57
|
+
false
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/// Install `cert_path` as a trusted root anchor in the system trust
|
|
62
|
+
/// store. Idempotent — checks `is_trusted` first and returns `Ok(false)`
|
|
63
|
+
/// if no install was performed.
|
|
64
|
+
///
|
|
65
|
+
/// Requires root on macOS (writes to `/Library/Keychains/System.keychain`).
|
|
66
|
+
/// On other platforms this is a no-op for now (Linux / Windows is a
|
|
67
|
+
/// follow-up — see TODO.md).
|
|
68
|
+
pub fn install_to_system_trust(cert_path: &Path) -> Result<bool, BoxError> {
|
|
69
|
+
if is_trusted(cert_path) {
|
|
70
|
+
return Ok(false);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
#[cfg(target_os = "macos")]
|
|
74
|
+
{
|
|
75
|
+
log::info!("installing {} to System.keychain", cert_path.display());
|
|
76
|
+
let status = std::process::Command::new("security")
|
|
77
|
+
.args([
|
|
78
|
+
"add-trusted-cert",
|
|
79
|
+
"-d",
|
|
80
|
+
"-r",
|
|
81
|
+
"trustRoot",
|
|
82
|
+
"-k",
|
|
83
|
+
"/Library/Keychains/System.keychain",
|
|
84
|
+
])
|
|
85
|
+
.arg(cert_path)
|
|
86
|
+
.status()?;
|
|
87
|
+
if !status.success() {
|
|
88
|
+
return Err(format!(
|
|
89
|
+
"security add-trusted-cert failed (exit {:?}); needs root (sudo)",
|
|
90
|
+
status.code(),
|
|
91
|
+
)
|
|
92
|
+
.into());
|
|
93
|
+
}
|
|
94
|
+
Ok(true)
|
|
95
|
+
}
|
|
96
|
+
#[cfg(not(target_os = "macos"))]
|
|
97
|
+
{
|
|
98
|
+
let _ = cert_path;
|
|
99
|
+
log::warn!("auto-trust-install: only macOS supported in this build");
|
|
100
|
+
Ok(false)
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/// Build a `TlsAcceptor` for the given domain, reusing a persisted
|
|
105
|
+
/// cert if one exists or generating + writing a fresh one if not.
|
|
106
|
+
///
|
|
107
|
+
/// `domain` is the apex (e.g. `"fbi.com"`); the cert SAN includes both
|
|
108
|
+
/// the apex and `*.{domain}` so any subdomain validates. If `domain`
|
|
109
|
+
/// is empty or `"localhost"`, only `localhost` + `127.0.0.1` are
|
|
110
|
+
/// covered.
|
|
111
|
+
pub fn build_acceptor(domain: &str, cert_dir: &Path) -> Result<TlsAcceptor, BoxError> {
|
|
112
|
+
let (cert_pem, key_pem) = load_or_generate(domain, cert_dir)?;
|
|
113
|
+
|
|
114
|
+
let cert_chain: Vec<CertificateDer<'static>> = CertificateDer::pem_slice_iter(cert_pem.as_bytes())
|
|
115
|
+
.collect::<Result<Vec<_>, _>>()?;
|
|
116
|
+
let key = PrivateKeyDer::from_pem_slice(key_pem.as_bytes())?;
|
|
117
|
+
|
|
118
|
+
let config = ServerConfig::builder()
|
|
119
|
+
.with_no_client_auth()
|
|
120
|
+
.with_single_cert(cert_chain, key)?;
|
|
121
|
+
|
|
122
|
+
Ok(TlsAcceptor::from(Arc::new(config)))
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
fn load_or_generate(domain: &str, cert_dir: &Path) -> Result<(String, String), BoxError> {
|
|
126
|
+
let slug = if domain.is_empty() { "localhost" } else { domain };
|
|
127
|
+
let cert_path = cert_dir.join(format!("{slug}.pem"));
|
|
128
|
+
let key_path = cert_dir.join(format!("{slug}.key"));
|
|
129
|
+
|
|
130
|
+
if cert_path.exists() && key_path.exists() {
|
|
131
|
+
let cert = std::fs::read_to_string(&cert_path)?;
|
|
132
|
+
let key = std::fs::read_to_string(&key_path)?;
|
|
133
|
+
return Ok((cert, key));
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
let (cert_pem, key_pem) = generate_self_signed(domain)?;
|
|
137
|
+
std::fs::create_dir_all(cert_dir)?;
|
|
138
|
+
std::fs::write(&cert_path, &cert_pem)?;
|
|
139
|
+
// 0600 on the key — std::fs::write opens 0644 by default
|
|
140
|
+
write_private(&key_path, key_pem.as_bytes())?;
|
|
141
|
+
|
|
142
|
+
Ok((cert_pem, key_pem))
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
#[cfg(unix)]
|
|
146
|
+
fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
|
147
|
+
use std::io::Write;
|
|
148
|
+
use std::os::unix::fs::OpenOptionsExt;
|
|
149
|
+
let mut f = std::fs::OpenOptions::new()
|
|
150
|
+
.write(true)
|
|
151
|
+
.create(true)
|
|
152
|
+
.truncate(true)
|
|
153
|
+
.mode(0o600)
|
|
154
|
+
.open(path)?;
|
|
155
|
+
f.write_all(bytes)?;
|
|
156
|
+
Ok(())
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
#[cfg(not(unix))]
|
|
160
|
+
fn write_private(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
|
|
161
|
+
std::fs::write(path, bytes)
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/// Generate a SAN-only self-signed cert valid for ~1 year. Returns
|
|
165
|
+
/// `(cert_pem, key_pem)`. The Common Name is intentionally left blank
|
|
166
|
+
/// — modern browsers ignore CN and only honor SAN entries.
|
|
167
|
+
pub fn generate_self_signed(domain: &str) -> Result<(String, String), BoxError> {
|
|
168
|
+
let mut sans: Vec<SanType> = Vec::new();
|
|
169
|
+
if domain.is_empty() || domain == "localhost" {
|
|
170
|
+
sans.push(SanType::DnsName("localhost".try_into()?));
|
|
171
|
+
sans.push(SanType::IpAddress("127.0.0.1".parse()?));
|
|
172
|
+
} else {
|
|
173
|
+
sans.push(SanType::DnsName(domain.try_into()?));
|
|
174
|
+
sans.push(SanType::DnsName(format!("*.{domain}").try_into()?));
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
let mut params = CertificateParams::default();
|
|
178
|
+
params.subject_alt_names = sans;
|
|
179
|
+
|
|
180
|
+
// Browsers ignore CN, but a non-empty DN avoids some tooling
|
|
181
|
+
// warnings. Use OrganizationName so the CN stays empty.
|
|
182
|
+
let mut dn = DistinguishedName::new();
|
|
183
|
+
dn.push(DnType::OrganizationName, "fbi-proxy (self-signed)");
|
|
184
|
+
params.distinguished_name = dn;
|
|
185
|
+
|
|
186
|
+
let now = time::OffsetDateTime::now_utc();
|
|
187
|
+
params.not_before = now - time::Duration::days(1);
|
|
188
|
+
params.not_after = now + time::Duration::days(365);
|
|
189
|
+
|
|
190
|
+
let key_pair = KeyPair::generate()?;
|
|
191
|
+
let cert = params.self_signed(&key_pair)?;
|
|
192
|
+
|
|
193
|
+
Ok((cert.pem(), key_pair.serialize_pem()))
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
#[cfg(test)]
|
|
197
|
+
mod tests {
|
|
198
|
+
use super::*;
|
|
199
|
+
|
|
200
|
+
#[test]
|
|
201
|
+
fn generates_pem_with_domain_san() {
|
|
202
|
+
let (cert, key) = generate_self_signed("fbi.com").unwrap();
|
|
203
|
+
assert!(cert.contains("BEGIN CERTIFICATE"));
|
|
204
|
+
assert!(key.contains("BEGIN PRIVATE KEY"));
|
|
205
|
+
|
|
206
|
+
// Parse the cert and check SAN entries
|
|
207
|
+
let der = CertificateDer::pem_slice_iter(cert.as_bytes())
|
|
208
|
+
.next()
|
|
209
|
+
.unwrap()
|
|
210
|
+
.unwrap();
|
|
211
|
+
// We don't fully x509-parse here — but the cert+key should be
|
|
212
|
+
// accepted by rustls' single-cert builder, which is what the
|
|
213
|
+
// real server uses. That's the real-world contract.
|
|
214
|
+
let key_der = PrivateKeyDer::from_pem_slice(key.as_bytes()).unwrap();
|
|
215
|
+
let config = ServerConfig::builder()
|
|
216
|
+
.with_no_client_auth()
|
|
217
|
+
.with_single_cert(vec![der], key_der);
|
|
218
|
+
assert!(config.is_ok(), "rustls should accept generated cert+key");
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
#[test]
|
|
222
|
+
fn generates_for_localhost_fallback() {
|
|
223
|
+
let (cert, _key) = generate_self_signed("").unwrap();
|
|
224
|
+
assert!(cert.contains("BEGIN CERTIFICATE"));
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
#[test]
|
|
228
|
+
fn load_or_generate_round_trips_persisted_certs() {
|
|
229
|
+
let tmp = std::env::temp_dir().join(format!(
|
|
230
|
+
"fbi-tls-test-{}",
|
|
231
|
+
std::process::id()
|
|
232
|
+
));
|
|
233
|
+
let _ = std::fs::remove_dir_all(&tmp);
|
|
234
|
+
|
|
235
|
+
let (cert1, key1) = load_or_generate("test.dev", &tmp).unwrap();
|
|
236
|
+
// Second call should return the same content (loaded from disk)
|
|
237
|
+
let (cert2, key2) = load_or_generate("test.dev", &tmp).unwrap();
|
|
238
|
+
assert_eq!(cert1, cert2);
|
|
239
|
+
assert_eq!(key1, key2);
|
|
240
|
+
|
|
241
|
+
let _ = std::fs::remove_dir_all(&tmp);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tiny client for the fbi-proxy loopback admin/control API.
|
|
3
|
+
*
|
|
4
|
+
* The running proxy publishes its (ephemeral) admin port to
|
|
5
|
+
* `~/.config/fbi-proxy/runtime.json`. The `up` / `down` / `ps` CLI
|
|
6
|
+
* subcommands read that file to find the port, then drive the `/rules`
|
|
7
|
+
* endpoints over loopback HTTP.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import os from "node:os";
|
|
13
|
+
|
|
14
|
+
export type RuntimeInfo = {
|
|
15
|
+
adminPort: number;
|
|
16
|
+
proxyPort: number;
|
|
17
|
+
pid: number;
|
|
18
|
+
confDir: string;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** A rule as reported by `GET /rules`. */
|
|
22
|
+
export type RuleInfo = {
|
|
23
|
+
namespace: string;
|
|
24
|
+
name: string;
|
|
25
|
+
match: string;
|
|
26
|
+
path: string | null;
|
|
27
|
+
target: string;
|
|
28
|
+
headers: Record<string, string>;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** Default config dir, matching the Rust side + setup.ts. */
|
|
32
|
+
export function defaultConfigDir(): string {
|
|
33
|
+
const fromEnv = process.env.FBI_PROXY_CONF_DIR;
|
|
34
|
+
if (fromEnv && fromEnv.length > 0) {
|
|
35
|
+
// FBI_PROXY_CONF_DIR points at conf.d; runtime.json sits beside it.
|
|
36
|
+
return path.dirname(fromEnv);
|
|
37
|
+
}
|
|
38
|
+
return path.join(os.homedir(), ".config/fbi-proxy");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function runtimeJsonPath(): string {
|
|
42
|
+
return path.join(defaultConfigDir(), "runtime.json");
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Locate the running proxy's admin endpoint. Throws a helpful error if
|
|
47
|
+
* the proxy doesn't appear to be running.
|
|
48
|
+
*/
|
|
49
|
+
export function readRuntime(): RuntimeInfo {
|
|
50
|
+
const p = runtimeJsonPath();
|
|
51
|
+
if (!existsSync(p)) {
|
|
52
|
+
throw new Error(
|
|
53
|
+
`[fbi-proxy] no running proxy found (missing ${p}).\n` +
|
|
54
|
+
` Start it first: \`fbi-proxy setup\` (daemon) or \`fbi-proxy --tls --domain <d>\`.`,
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
let info: RuntimeInfo;
|
|
58
|
+
try {
|
|
59
|
+
info = JSON.parse(readFileSync(p, "utf8"));
|
|
60
|
+
} catch (e) {
|
|
61
|
+
throw new Error(`[fbi-proxy] could not parse ${p}: ${e}`);
|
|
62
|
+
}
|
|
63
|
+
if (!info.adminPort) {
|
|
64
|
+
throw new Error(
|
|
65
|
+
`[fbi-proxy] ${p} has no adminPort — is the proxy up to date?`,
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
return info;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function baseUrl(info: RuntimeInfo): string {
|
|
72
|
+
return `http://127.0.0.1:${info.adminPort}`;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function asError(res: Response): Promise<never> {
|
|
76
|
+
let msg = `${res.status} ${res.statusText}`;
|
|
77
|
+
try {
|
|
78
|
+
const body = await res.json();
|
|
79
|
+
if (body?.error) msg = body.error;
|
|
80
|
+
} catch {
|
|
81
|
+
// non-JSON body; keep the status line
|
|
82
|
+
}
|
|
83
|
+
throw new Error(`[fbi-proxy] admin API: ${msg}`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** GET /rules — the full merged rule table. */
|
|
87
|
+
export async function listRules(info = readRuntime()): Promise<RuleInfo[]> {
|
|
88
|
+
const res = await fetch(`${baseUrl(info)}/rules`);
|
|
89
|
+
if (!res.ok) await asError(res);
|
|
90
|
+
return (await res.json()) as RuleInfo[];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** PUT /rules/{namespace} — reconcile a namespace to `yamlBody`. */
|
|
94
|
+
export async function applyRules(
|
|
95
|
+
namespace: string,
|
|
96
|
+
yamlBody: string,
|
|
97
|
+
info = readRuntime(),
|
|
98
|
+
): Promise<RuleInfo[]> {
|
|
99
|
+
const res = await fetch(
|
|
100
|
+
`${baseUrl(info)}/rules/${encodeURIComponent(namespace)}`,
|
|
101
|
+
{
|
|
102
|
+
method: "PUT",
|
|
103
|
+
headers: { "Content-Type": "application/yaml" },
|
|
104
|
+
body: yamlBody,
|
|
105
|
+
},
|
|
106
|
+
);
|
|
107
|
+
if (!res.ok) await asError(res);
|
|
108
|
+
return (await res.json()) as RuleInfo[];
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** DELETE /rules/{namespace} — remove a namespace's fragment. */
|
|
112
|
+
export async function deleteRules(
|
|
113
|
+
namespace: string,
|
|
114
|
+
info = readRuntime(),
|
|
115
|
+
): Promise<{ ok: boolean; removed: boolean }> {
|
|
116
|
+
const res = await fetch(
|
|
117
|
+
`${baseUrl(info)}/rules/${encodeURIComponent(namespace)}`,
|
|
118
|
+
{
|
|
119
|
+
method: "DELETE",
|
|
120
|
+
},
|
|
121
|
+
);
|
|
122
|
+
if (!res.ok) await asError(res);
|
|
123
|
+
return (await res.json()) as { ok: boolean; removed: boolean };
|
|
124
|
+
}
|
package/ts/auth/authConfig.ts
CHANGED
|
@@ -10,15 +10,21 @@ export type FirebaseSubConfig = {
|
|
|
10
10
|
authDomain?: string;
|
|
11
11
|
};
|
|
12
12
|
|
|
13
|
+
export type LocalSubConfig = {
|
|
14
|
+
email: string;
|
|
15
|
+
name?: string;
|
|
16
|
+
};
|
|
17
|
+
|
|
13
18
|
export type AuthConfigShape = {
|
|
14
19
|
version: 1;
|
|
15
20
|
domain: string;
|
|
16
21
|
cookieDomain: string;
|
|
17
22
|
ssoHost: string;
|
|
18
|
-
provider: "google" | "firebase" | "snolab";
|
|
23
|
+
provider: "google" | "firebase" | "snolab" | "local";
|
|
19
24
|
clientId?: string;
|
|
20
25
|
clientSecret?: string;
|
|
21
26
|
firebase?: FirebaseSubConfig;
|
|
27
|
+
local?: LocalSubConfig;
|
|
22
28
|
sessionSecret: string;
|
|
23
29
|
allowlist: {
|
|
24
30
|
emails?: string[];
|
|
@@ -63,10 +69,16 @@ export function configFromEnv(domain: string): AuthConfigShape | null {
|
|
|
63
69
|
(process.env.FBI_AUTH_PROVIDER as AuthConfigShape["provider"]) ?? "google";
|
|
64
70
|
const clientId = process.env.FBI_AUTH_CLIENT_ID;
|
|
65
71
|
const firebaseProjectId = process.env.FBI_AUTH_FIREBASE_PROJECT_ID;
|
|
72
|
+
const localUser = process.env.FBI_AUTH_LOCAL_USER;
|
|
66
73
|
|
|
67
74
|
if (provider === "firebase") {
|
|
68
75
|
if (!firebaseProjectId) return null;
|
|
76
|
+
} else if (provider === "snolab") {
|
|
77
|
+
// snolab uses baked-in defaults; nothing required beyond the provider name
|
|
78
|
+
} else if (provider === "local") {
|
|
79
|
+
if (!localUser) return null;
|
|
69
80
|
} else {
|
|
81
|
+
// google (default)
|
|
70
82
|
if (!clientId) return null;
|
|
71
83
|
}
|
|
72
84
|
|
|
@@ -86,6 +98,12 @@ export function configFromEnv(domain: string): AuthConfigShape | null {
|
|
|
86
98
|
authDomain: process.env.FBI_AUTH_FIREBASE_AUTH_DOMAIN,
|
|
87
99
|
}
|
|
88
100
|
: undefined,
|
|
101
|
+
local: localUser
|
|
102
|
+
? {
|
|
103
|
+
email: localUser,
|
|
104
|
+
name: process.env.FBI_AUTH_LOCAL_NAME,
|
|
105
|
+
}
|
|
106
|
+
: undefined,
|
|
89
107
|
sessionSecret:
|
|
90
108
|
process.env.FBI_AUTH_SESSION_SECRET ??
|
|
91
109
|
randomBytes(32).toString("base64url"),
|
package/ts/cli.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { spawnSync } from "node:child_process";
|
|
2
4
|
import getPort from "get-port";
|
|
3
5
|
import hotMemo from "hot-memo";
|
|
4
6
|
import path from "path";
|
|
@@ -29,6 +31,50 @@ import {
|
|
|
29
31
|
} from "./auth/spawnCaddy";
|
|
30
32
|
|
|
31
33
|
const originalCwd = process.cwd();
|
|
34
|
+
|
|
35
|
+
// Subcommand routing & default behavior
|
|
36
|
+
//
|
|
37
|
+
// `fbi-proxy setup` (or `fbi-proxy` with no escape-hatch flags) runs the
|
|
38
|
+
// one-shot setup orchestrator: registers an oxmgr daemon, generates+trusts
|
|
39
|
+
// a TLS cert, installs a pf :443→:8443 forward, and verifies https://<domain>.
|
|
40
|
+
//
|
|
41
|
+
// Old foreground modes (Caddy, dev, raw TLS, auth wizard) are preserved by
|
|
42
|
+
// flags below — explicit opt-in keeps the existing surface intact for users
|
|
43
|
+
// who rely on it.
|
|
44
|
+
{
|
|
45
|
+
const rawArgs = hideBin(process.argv);
|
|
46
|
+
const firstPositional = rawArgs.find((a) => !a.startsWith("-"));
|
|
47
|
+
|
|
48
|
+
// Rule-management subcommands (compose-style) talk to a running proxy's
|
|
49
|
+
// admin API; they never start a proxy themselves.
|
|
50
|
+
const { RULES_SUBCOMMANDS, runRulesCli } = await import("./rulesCli");
|
|
51
|
+
if (firstPositional && RULES_SUBCOMMANDS.has(firstPositional)) {
|
|
52
|
+
const code = await runRulesCli(rawArgs);
|
|
53
|
+
process.exit(code);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const FOREGROUND_FLAGS = [
|
|
57
|
+
"--dev",
|
|
58
|
+
"--with-caddy",
|
|
59
|
+
"--with-auth",
|
|
60
|
+
"--tls",
|
|
61
|
+
"--reconfigure",
|
|
62
|
+
];
|
|
63
|
+
const wantsForeground = rawArgs.some((a) =>
|
|
64
|
+
FOREGROUND_FLAGS.some((f) => a === f || a.startsWith(`${f}=`)),
|
|
65
|
+
);
|
|
66
|
+
const hasExplicitPortEnv = !!process.env.FBI_PROXY_PORT;
|
|
67
|
+
const isSetupCmd = firstPositional === "setup";
|
|
68
|
+
const isDefault = !firstPositional && !wantsForeground && !hasExplicitPortEnv;
|
|
69
|
+
|
|
70
|
+
if (isSetupCmd || isDefault) {
|
|
71
|
+
const { runSetup } = await import("./setup");
|
|
72
|
+
const passArgs = rawArgs.filter((a) => a !== "setup");
|
|
73
|
+
await runSetup(passArgs, { originalCwd });
|
|
74
|
+
process.exit(0);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
32
78
|
process.chdir(path.resolve(import.meta.dir, ".."));
|
|
33
79
|
|
|
34
80
|
const argv = await yargs(hideBin(process.argv))
|
|
@@ -71,12 +117,33 @@ const argv = await yargs(hideBin(process.argv))
|
|
|
71
117
|
description:
|
|
72
118
|
"TLS strategy for --with-caddy. 'auto' uses ACME (Let's Encrypt); 'internal' uses Caddy's local CA. Defaults to 'internal' for fbi.com, 'auto' otherwise.",
|
|
73
119
|
})
|
|
120
|
+
.option("tls", {
|
|
121
|
+
type: "boolean",
|
|
122
|
+
default: false,
|
|
123
|
+
description:
|
|
124
|
+
"Terminate TLS in the Rust proxy using a self-signed cert (no Caddy). Browser warning expected (Phase 1 — no system trust install). Use with --port 443 + sudo to serve standard HTTPS.",
|
|
125
|
+
})
|
|
74
126
|
.help().argv;
|
|
75
127
|
|
|
76
|
-
|
|
128
|
+
if (argv.tls && argv["with-caddy"]) {
|
|
129
|
+
console.error(
|
|
130
|
+
"[fbi-proxy] --tls and --with-caddy are mutually exclusive (Caddy already terminates TLS).",
|
|
131
|
+
);
|
|
132
|
+
process.exit(2);
|
|
133
|
+
}
|
|
77
134
|
|
|
78
135
|
const FBI_PROXY_PORT =
|
|
79
|
-
process.env.FBI_PROXY_PORT ||
|
|
136
|
+
process.env.FBI_PROXY_PORT ||
|
|
137
|
+
(argv.tls ? "443" : String(await getPort({ port: 2432 })));
|
|
138
|
+
|
|
139
|
+
if (argv.tls) {
|
|
140
|
+
await ensureRootIfTlsNeedsIt({
|
|
141
|
+
domain: argv.domain,
|
|
142
|
+
port: Number(FBI_PROXY_PORT),
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
console.log("Preparing Binaries");
|
|
80
147
|
|
|
81
148
|
const proxyProcess = await hotMemo(async () => {
|
|
82
149
|
const proxy = await getFbiProxyBinary({ originalCwd });
|
|
@@ -85,6 +152,17 @@ const proxyProcess = await hotMemo(async () => {
|
|
|
85
152
|
env: {
|
|
86
153
|
...process.env,
|
|
87
154
|
FBI_PROXY_PORT,
|
|
155
|
+
...(argv.tls
|
|
156
|
+
? {
|
|
157
|
+
FBI_PROXY_TLS: "true",
|
|
158
|
+
FBI_PROXY_DOMAIN: argv.domain,
|
|
159
|
+
// Forward CERT_DIR if the sudo wrapper set it (so the elevated
|
|
160
|
+
// Rust binary writes to the original user's $HOME, not /var/root)
|
|
161
|
+
...(process.env.FBI_PROXY_CERT_DIR
|
|
162
|
+
? { FBI_PROXY_CERT_DIR: process.env.FBI_PROXY_CERT_DIR }
|
|
163
|
+
: {}),
|
|
164
|
+
}
|
|
165
|
+
: {}),
|
|
88
166
|
},
|
|
89
167
|
})`${proxy}`.process;
|
|
90
168
|
|
|
@@ -136,6 +214,84 @@ process.on("uncaughtException", (err) => {
|
|
|
136
214
|
exit();
|
|
137
215
|
});
|
|
138
216
|
|
|
217
|
+
async function ensureRootIfTlsNeedsIt(opts: {
|
|
218
|
+
domain: string;
|
|
219
|
+
port: number;
|
|
220
|
+
}): Promise<void> {
|
|
221
|
+
if (process.platform !== "darwin") {
|
|
222
|
+
// Linux/Windows trust install is a follow-up. The Rust side prints a
|
|
223
|
+
// friendly fallback message if untrusted.
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
if (process.getuid?.() === 0) return;
|
|
227
|
+
|
|
228
|
+
const home = process.env.HOME ?? "";
|
|
229
|
+
const certDir =
|
|
230
|
+
process.env.FBI_PROXY_CERT_DIR ??
|
|
231
|
+
path.join(home, ".config/fbi-proxy/certs");
|
|
232
|
+
const slug = opts.domain || "localhost";
|
|
233
|
+
const certPath = path.join(certDir, `${slug}.pem`);
|
|
234
|
+
|
|
235
|
+
const needsPortBind = opts.port < 1024;
|
|
236
|
+
const certMissing = !existsSync(certPath);
|
|
237
|
+
const certUntrusted = !certMissing && !isMacosCertTrusted(certPath);
|
|
238
|
+
const needsTrustInstall = certMissing || certUntrusted;
|
|
239
|
+
|
|
240
|
+
if (!needsPortBind && !needsTrustInstall) return;
|
|
241
|
+
|
|
242
|
+
const reasons = [
|
|
243
|
+
needsPortBind && `bind :${opts.port}`,
|
|
244
|
+
needsTrustInstall && "install cert to system trust",
|
|
245
|
+
]
|
|
246
|
+
.filter(Boolean)
|
|
247
|
+
.join(" + ");
|
|
248
|
+
console.log(`[fbi-proxy] --tls needs root to: ${reasons}`);
|
|
249
|
+
|
|
250
|
+
// Preserve HOME and CERT_DIR so the elevated process writes cert/auth
|
|
251
|
+
// files into the original user's directory, not /var/root.
|
|
252
|
+
const sudoArgs = [
|
|
253
|
+
`HOME=${home}`,
|
|
254
|
+
`FBI_PROXY_CERT_DIR=${certDir}`,
|
|
255
|
+
process.execPath,
|
|
256
|
+
...process.argv.slice(1),
|
|
257
|
+
];
|
|
258
|
+
|
|
259
|
+
// Prefer terminal sudo when a TTY is attached; otherwise fall back to the
|
|
260
|
+
// macOS GUI authentication dialog via osascript so non-TTY contexts (agent
|
|
261
|
+
// shells, oxmgr-spawned children) can still escalate with a single password
|
|
262
|
+
// prompt instead of erroring out with "a terminal is required".
|
|
263
|
+
const hasTty = !!process.stdin.isTTY;
|
|
264
|
+
if (hasTty) {
|
|
265
|
+
console.log(
|
|
266
|
+
`[fbi-proxy] re-launching via sudo (terminal password prompt)…`,
|
|
267
|
+
);
|
|
268
|
+
const result = spawnSync("sudo", sudoArgs, { stdio: "inherit" });
|
|
269
|
+
process.exit(result.status ?? 1);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
console.log(`[fbi-proxy] no TTY — opening macOS authentication dialog…`);
|
|
273
|
+
const shellCmd = sudoArgs.map(shellQuote).join(" ");
|
|
274
|
+
const prompt = `fbi-proxy needs administrator access to ${reasons} for https://${opts.domain}/.`;
|
|
275
|
+
const script = `do shell script ${appleScriptQuote(shellCmd)} with prompt ${appleScriptQuote(prompt)} with administrator privileges`;
|
|
276
|
+
const result = spawnSync("osascript", ["-e", script], { stdio: "inherit" });
|
|
277
|
+
process.exit(result.status ?? 1);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function shellQuote(s: string): string {
|
|
281
|
+
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function appleScriptQuote(s: string): string {
|
|
285
|
+
return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function isMacosCertTrusted(certPath: string): boolean {
|
|
289
|
+
const result = spawnSync("security", ["verify-cert", "-c", certPath], {
|
|
290
|
+
stdio: "ignore",
|
|
291
|
+
});
|
|
292
|
+
return result.status === 0;
|
|
293
|
+
}
|
|
294
|
+
|
|
139
295
|
async function startFbiAuth(opts: {
|
|
140
296
|
domain: string;
|
|
141
297
|
reconfigure: boolean;
|