feat(release): stage GitWorkshop and next node updates
This commit is contained in:
@@ -64,6 +64,11 @@ pub(super) fn sanitize_error_message(msg: &str) -> String {
|
||||
"must be",
|
||||
"cannot",
|
||||
"Password",
|
||||
// auth.changePassword verifies the existing node password before it
|
||||
// writes either the web hash or the optional Linux/SSH password. This
|
||||
// is safe, actionable validation text; masking it as an internal
|
||||
// failure sent operators to the server logs for a simple typo.
|
||||
"Current password is incorrect",
|
||||
// OTA apply/download errors are all operator-actionable ("download it
|
||||
// again", "download first") — sanitizing them to "Operation failed"
|
||||
// left users stuck with no idea what to do, and hid the "already
|
||||
@@ -242,6 +247,12 @@ mod sanitize_tests {
|
||||
assert_eq!(sanitize_error_message(msg), msg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn change_password_rejection_reaches_the_operator() {
|
||||
let msg = "Current password is incorrect";
|
||||
assert_eq!(sanitize_error_message(msg), msg);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tor_unavailable_precondition_passes_through() {
|
||||
let msg = "Tor address not available. Tor may not be running.";
|
||||
@@ -306,7 +317,7 @@ mod sanitize_tests {
|
||||
/// Deterministic: same session token always produces the same CSRF token.
|
||||
/// Survives backend restarts because it depends only on the session token
|
||||
/// and the on-disk remember secret (not ephemeral state).
|
||||
pub(super) async fn derive_csrf_token(session_token: &str) -> String {
|
||||
pub(crate) async fn derive_csrf_token(session_token: &str) -> String {
|
||||
use hmac::{Hmac, Mac};
|
||||
use sha2::Sha256;
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
@@ -34,6 +34,7 @@ mod nostr;
|
||||
mod onboarding_gate;
|
||||
mod openwrt;
|
||||
mod package;
|
||||
pub(crate) use package::patch_indeedhub_nostr_provider;
|
||||
pub(crate) use package::wyoming_satellite_keeper;
|
||||
mod peers;
|
||||
mod pine_status;
|
||||
@@ -71,12 +72,53 @@ pub use middleware::PeerAddr;
|
||||
// never added to it — the Phase-10 hard constraint this crate must hold.
|
||||
// The list's *contents* are unchanged; only its read-visibility widens from
|
||||
// "this module" to "this crate".
|
||||
pub(crate) use middleware::UNAUTHENTICATED_METHODS;
|
||||
use middleware::{
|
||||
derive_csrf_token, extract_client_ip, extract_cookie, sanitize_error_message, CACHEABLE_METHODS,
|
||||
};
|
||||
pub(crate) use middleware::{derive_csrf_token, UNAUTHENTICATED_METHODS};
|
||||
use middleware::{extract_client_ip, extract_cookie, sanitize_error_message, CACHEABLE_METHODS};
|
||||
use response::{cookie_header, json_response, ResponseCache, RpcError, RpcRequest, RpcResponse};
|
||||
|
||||
/// Browser apps run on dedicated high ports and can share the authenticated
|
||||
/// node cookie. Nostr signing must therefore be callable by the dashboard
|
||||
/// bridge (ports 80/443), not directly by an iframe that could bypass its
|
||||
/// consent dialog. Requests without Origin remain available to authenticated
|
||||
/// local CLI/integration clients. Development permits loopback origins.
|
||||
fn nostr_signing_origin_allowed(headers: &hyper::HeaderMap, dev_mode: bool) -> bool {
|
||||
let Some(origin) = headers.get("origin").and_then(|value| value.to_str().ok()) else {
|
||||
return true;
|
||||
};
|
||||
let Ok(url) = reqwest::Url::parse(origin) else {
|
||||
return false;
|
||||
};
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||
return false;
|
||||
}
|
||||
if dev_mode && matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "::1")) {
|
||||
return true;
|
||||
}
|
||||
matches!(url.port_or_known_default(), Some(80 | 443))
|
||||
}
|
||||
|
||||
/// Read-only authenticated methods may skip CSRF, but they must still exist in
|
||||
/// the dispatcher. The tab signer uses `system.get-hostname` as its lightweight
|
||||
/// session probe, so keeping the policy in one testable function protects that
|
||||
/// cross-origin app-gate bootstrap contract.
|
||||
fn csrf_exempt_method(method: &str) -> bool {
|
||||
matches!(
|
||||
method,
|
||||
"node-messages-received"
|
||||
| "server.echo"
|
||||
| "server.get-state"
|
||||
| "system.stats"
|
||||
| "tor.status"
|
||||
| "tor.onion-addresses"
|
||||
| "bitcoin.relay-status"
|
||||
| "federation.list-nodes"
|
||||
| "system.get-settings"
|
||||
| "system.get-node-key"
|
||||
| "system.get-metrics"
|
||||
| "system.get-hostname"
|
||||
)
|
||||
}
|
||||
|
||||
/// Default dev password when no user is set up (matches mock-backend).
|
||||
/// Dev builds only — the pre-setup login bypass that reads this is
|
||||
/// cfg-gated out of release binaries.
|
||||
@@ -291,6 +333,18 @@ impl RpcHandler {
|
||||
|
||||
debug!("RPC method: {}", rpc_req.method);
|
||||
|
||||
if matches!(
|
||||
rpc_req.method.as_str(),
|
||||
"node.nostr-sign" | "identity.nostr-sign"
|
||||
) && !nostr_signing_origin_allowed(&parts.headers, self.config.dev_mode)
|
||||
{
|
||||
return Ok(self.error_response(
|
||||
403,
|
||||
"Nostr signing from app origins requires the dashboard consent bridge",
|
||||
StatusCode::FORBIDDEN,
|
||||
));
|
||||
}
|
||||
|
||||
// Enforce authentication for non-allowlisted methods
|
||||
let is_unauthenticated = UNAUTHENTICATED_METHODS.contains(&rpc_req.method.as_str());
|
||||
let mut new_session_cookies: Option<(String, String)> = None;
|
||||
@@ -340,21 +394,7 @@ impl RpcHandler {
|
||||
// CSRF protection: validate X-CSRF-Token header via HMAC derivation from session token.
|
||||
// Skip CSRF for read-only methods (polling, status) — CSRF prevents state-changing forgery.
|
||||
// Skip when session was just auto-restored from remember-me (browser has stale CSRF cookie).
|
||||
let csrf_exempt = matches!(
|
||||
rpc_req.method.as_str(),
|
||||
"node-messages-received"
|
||||
| "server.echo"
|
||||
| "server.get-state"
|
||||
| "system.stats"
|
||||
| "tor.status"
|
||||
| "tor.onion-addresses"
|
||||
| "bitcoin.relay-status"
|
||||
| "federation.list-nodes"
|
||||
| "system.get-settings"
|
||||
| "system.get-node-key"
|
||||
| "system.get-metrics"
|
||||
| "system.get-version"
|
||||
);
|
||||
let csrf_exempt = csrf_exempt_method(&rpc_req.method);
|
||||
if !is_unauthenticated && new_session_cookies.is_none() && !csrf_exempt {
|
||||
let csrf_header = parts
|
||||
.headers
|
||||
@@ -735,3 +775,62 @@ impl RpcHandler {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod nostr_signing_origin_tests {
|
||||
use super::*;
|
||||
use hyper::header::{HeaderMap, HeaderValue, ORIGIN};
|
||||
|
||||
fn headers(origin: Option<&str>) -> HeaderMap {
|
||||
let mut headers = HeaderMap::new();
|
||||
if let Some(origin) = origin {
|
||||
headers.insert(ORIGIN, HeaderValue::from_str(origin).unwrap());
|
||||
}
|
||||
headers
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_accepts_dashboard_and_authenticated_non_browser_clients() {
|
||||
assert!(nostr_signing_origin_allowed(&headers(None), false));
|
||||
assert!(nostr_signing_origin_allowed(
|
||||
&headers(Some("https://node.local")),
|
||||
false
|
||||
));
|
||||
assert!(nostr_signing_origin_allowed(
|
||||
&headers(Some("http://192.0.2.10")),
|
||||
false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signing_rejects_app_ports_but_allows_loopback_dev_server() {
|
||||
assert!(!nostr_signing_origin_allowed(
|
||||
&headers(Some("https://node.local:8337")),
|
||||
false
|
||||
));
|
||||
assert!(!nostr_signing_origin_allowed(
|
||||
&headers(Some("https://node.local:7778")),
|
||||
false
|
||||
));
|
||||
assert!(nostr_signing_origin_allowed(
|
||||
&headers(Some("http://localhost:5173")),
|
||||
true
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod session_probe_contract_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn signer_session_probe_is_implemented_authenticated_and_read_only() {
|
||||
const PROBE: &str = "system.get-hostname";
|
||||
const DISPATCHER: &str = include_str!("dispatcher.rs");
|
||||
|
||||
assert!(csrf_exempt_method(PROBE));
|
||||
assert!(!UNAUTHENTICATED_METHODS.contains(&PROBE));
|
||||
assert!(DISPATCHER.contains("\"system.get-hostname\" =>"));
|
||||
assert!(!DISPATCHER.contains("\"system.get-version\" =>"));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -74,110 +74,178 @@ async fn local_podman_image_exists(image: &str) -> Result<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn patch_indeedhub_nostr_provider() {
|
||||
fn patched_indeedhub_nginx_config(original: &str) -> String {
|
||||
let mut conf = original
|
||||
.lines()
|
||||
.filter(|line| !line.contains("X-Frame-Options"))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
conf.push('\n');
|
||||
if !conf.contains("location = /nostr-provider.js {") {
|
||||
conf = conf.replace(
|
||||
"location = /sw.js {",
|
||||
"location = /nostr-provider.js {\n\
|
||||
add_header Cache-Control \"no-cache, no-store, must-revalidate\";\n\
|
||||
expires off;\n\
|
||||
}\n\n\
|
||||
location = /sw.js {",
|
||||
);
|
||||
}
|
||||
if conf.contains("try_files") && !conf.contains("sub_filter") {
|
||||
conf = conf.replacen(
|
||||
"try_files $uri $uri/ /index.html;",
|
||||
"try_files $uri $uri/ /index.html;\n\
|
||||
sub_filter_once on;\n\
|
||||
sub_filter '</head>' '<script src=\"/nostr-provider.js?v=tab-signer-v4\"></script></head>';",
|
||||
1,
|
||||
);
|
||||
}
|
||||
conf = conf.replace(
|
||||
"src=\"/nostr-provider.js\"",
|
||||
"src=\"/nostr-provider.js?v=tab-signer-v4\"",
|
||||
);
|
||||
conf = conf.replace("tab-signer-v2", "tab-signer-v4");
|
||||
conf = conf.replace("tab-signer-v3", "tab-signer-v4");
|
||||
conf.replace(
|
||||
"proxy_set_header X-Forwarded-Prefix /api;",
|
||||
"proxy_set_header X-Forwarded-Prefix $http_x_forwarded_prefix/api;",
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn patch_indeedhub_nostr_provider() {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
|
||||
|
||||
let _ = tokio::process::Command::new("podman")
|
||||
.args([
|
||||
"exec",
|
||||
"indeedhub",
|
||||
"sed",
|
||||
"-i",
|
||||
"/X-Frame-Options/d",
|
||||
"/etc/nginx/conf.d/default.conf",
|
||||
])
|
||||
// Frontend assets can change during a dashboard-only OTA while the
|
||||
// IndeedHub container keeps running. Reconcile the injected provider on
|
||||
// daemon startup as well as app install/start, but stay quiet when the app
|
||||
// is not installed or is intentionally stopped.
|
||||
let running = tokio::process::Command::new("podman")
|
||||
.args(["inspect", "-f", "{{.State.Running}}", "indeedhub"])
|
||||
.output()
|
||||
.await;
|
||||
|
||||
let provider_src = "/opt/archipelago/web-ui/nostr-provider.js";
|
||||
if tokio::fs::metadata(provider_src).await.is_ok() {
|
||||
let _ = tokio::process::Command::new("podman")
|
||||
.args([
|
||||
"cp",
|
||||
provider_src,
|
||||
"indeedhub:/usr/share/nginx/html/nostr-provider.js",
|
||||
])
|
||||
.output()
|
||||
.await;
|
||||
.await
|
||||
.map(|out| out.status.success() && String::from_utf8_lossy(&out.stdout).trim() == "true")
|
||||
.unwrap_or(false);
|
||||
if !running {
|
||||
return;
|
||||
}
|
||||
|
||||
let check = tokio::process::Command::new("podman")
|
||||
.args([
|
||||
"exec",
|
||||
"indeedhub",
|
||||
"grep",
|
||||
"-q",
|
||||
"nostr-provider",
|
||||
"/etc/nginx/conf.d/default.conf",
|
||||
])
|
||||
// `podman exec` cannot always join a rootless container's delegated cgroup
|
||||
// from the system service, while Podman 5's copier refuses to overwrite an
|
||||
// existing regular file. Mount the rootless storage namespace instead;
|
||||
// this replaces both files without entering the container's cgroup.
|
||||
let unique = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|duration| duration.as_nanos())
|
||||
.unwrap_or(0);
|
||||
let tmp_dir = format!("/tmp/indeedhub-nginx-patch-{}-{unique}", std::process::id());
|
||||
let tmp_path = format!("{tmp_dir}/default.conf");
|
||||
if tokio::fs::create_dir(&tmp_dir).await.is_err() {
|
||||
tracing::warn!("IndeeHub signer reconciliation could not create its temporary directory");
|
||||
return;
|
||||
}
|
||||
|
||||
let mount_out = tokio::process::Command::new("podman")
|
||||
.args(["unshare", "podman", "mount", "indeedhub"])
|
||||
.output()
|
||||
.await;
|
||||
let already_patched = check.map(|o| o.status.success()).unwrap_or(false);
|
||||
let container_root = mount_out
|
||||
.ok()
|
||||
.filter(|out| out.status.success())
|
||||
.map(|out| String::from_utf8_lossy(&out.stdout).trim().to_string())
|
||||
.filter(|path| {
|
||||
std::path::Path::new(path).is_absolute()
|
||||
&& path.contains("/containers/storage/overlay/")
|
||||
&& path.ends_with("/merged")
|
||||
});
|
||||
let Some(container_root) = container_root else {
|
||||
let _ = tokio::fs::remove_dir(&tmp_dir).await;
|
||||
tracing::warn!("IndeeHub signer reconciliation could not mount rootless storage");
|
||||
return;
|
||||
};
|
||||
|
||||
if !already_patched {
|
||||
let cat_out = tokio::process::Command::new("podman")
|
||||
.args(["exec", "indeedhub", "cat", "/etc/nginx/conf.d/default.conf"])
|
||||
let provider_src = "/opt/archipelago/web-ui/nostr-provider.js";
|
||||
let provider_dest = format!("{container_root}/usr/share/nginx/html/nostr-provider.js");
|
||||
let provider_copied = tokio::fs::metadata(provider_src).await.is_ok()
|
||||
&& tokio::process::Command::new("podman")
|
||||
.args([
|
||||
"unshare",
|
||||
"install",
|
||||
"-m",
|
||||
"644",
|
||||
provider_src,
|
||||
&provider_dest,
|
||||
])
|
||||
.output()
|
||||
.await;
|
||||
.await
|
||||
.map(|out| out.status.success())
|
||||
.unwrap_or(false);
|
||||
|
||||
if let Ok(out) = cat_out {
|
||||
if out.status.success() {
|
||||
let conf = String::from_utf8_lossy(&out.stdout).to_string();
|
||||
let conf = conf.replace(
|
||||
"location = /sw.js {",
|
||||
"location = /nostr-provider.js {\n\
|
||||
add_header Cache-Control \"no-cache, no-store, must-revalidate\";\n\
|
||||
expires off;\n\
|
||||
}\n\n\
|
||||
location = /sw.js {",
|
||||
);
|
||||
let conf = if conf.contains("try_files") && !conf.contains("sub_filter") {
|
||||
conf.replacen(
|
||||
"try_files $uri $uri/ /index.html;",
|
||||
"try_files $uri $uri/ /index.html;\n\
|
||||
sub_filter_once on;\n\
|
||||
sub_filter '</head>' '<script src=\"/nostr-provider.js\"></script></head>';",
|
||||
1,
|
||||
)
|
||||
} else {
|
||||
conf
|
||||
};
|
||||
let copy_out = tokio::process::Command::new("podman")
|
||||
.args(["cp", "indeedhub:/etc/nginx/conf.d/default.conf", &tmp_path])
|
||||
.output()
|
||||
.await;
|
||||
|
||||
let tmp_path = "/tmp/indeedhub-nginx-patch.conf";
|
||||
if tokio::fs::write(tmp_path, &conf).await.is_ok() {
|
||||
let _ = tokio::process::Command::new("podman")
|
||||
.args(["cp", tmp_path, "indeedhub:/etc/nginx/conf.d/default.conf"])
|
||||
let mut config_copied = false;
|
||||
if let Ok(out) = copy_out {
|
||||
if out.status.success() {
|
||||
if let Ok(original) = tokio::fs::read_to_string(&tmp_path).await {
|
||||
let conf = patched_indeedhub_nginx_config(&original);
|
||||
if conf != original && tokio::fs::write(&tmp_path, &conf).await.is_ok() {
|
||||
config_copied = tokio::process::Command::new("podman")
|
||||
.args([
|
||||
"unshare",
|
||||
"install",
|
||||
"-m",
|
||||
"644",
|
||||
&tmp_path,
|
||||
&format!("{container_root}/etc/nginx/conf.d/default.conf"),
|
||||
])
|
||||
.output()
|
||||
.await;
|
||||
let _ = tokio::fs::remove_file(tmp_path).await;
|
||||
.await
|
||||
.map(|out| out.status.success())
|
||||
.unwrap_or(false);
|
||||
if config_copied {
|
||||
let _ = tokio::fs::remove_file(&tmp_path).await;
|
||||
config_copied = tokio::process::Command::new("podman")
|
||||
.args(["cp", "indeedhub:/etc/nginx/conf.d/default.conf", &tmp_path])
|
||||
.output()
|
||||
.await
|
||||
.map(|out| out.status.success())
|
||||
.unwrap_or(false)
|
||||
&& tokio::fs::read_to_string(&tmp_path)
|
||||
.await
|
||||
.map(|actual| actual == conf)
|
||||
.unwrap_or(false);
|
||||
}
|
||||
} else if conf == original
|
||||
&& conf.contains("location = /nostr-provider.js {")
|
||||
&& conf.contains("src=\"/nostr-provider.js?v=tab-signer-v4\"")
|
||||
{
|
||||
config_copied = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let _ = tokio::fs::remove_file(&tmp_path).await;
|
||||
let _ = tokio::fs::remove_dir(&tmp_dir).await;
|
||||
let _ = tokio::process::Command::new("podman")
|
||||
.args([
|
||||
"exec",
|
||||
"indeedhub",
|
||||
"sed",
|
||||
"-i",
|
||||
"s|proxy_set_header X-Forwarded-Prefix /api;|proxy_set_header X-Forwarded-Prefix $http_x_forwarded_prefix/api;|",
|
||||
"/etc/nginx/conf.d/default.conf",
|
||||
])
|
||||
.args(["unshare", "podman", "unmount", "indeedhub"])
|
||||
.output()
|
||||
.await;
|
||||
|
||||
let reload = tokio::process::Command::new("podman")
|
||||
.args(["exec", "indeedhub", "nginx", "-s", "reload"])
|
||||
.args(["kill", "--signal", "HUP", "indeedhub"])
|
||||
.output()
|
||||
.await;
|
||||
match reload {
|
||||
Ok(o) if o.status.success() => {
|
||||
Ok(o) if o.status.success() && provider_copied && config_copied => {
|
||||
info!("IndeeHub: NIP-07 provider injected, nginx patched and reloaded");
|
||||
}
|
||||
Ok(o) => {
|
||||
tracing::warn!(
|
||||
"IndeeHub nginx reload failed: {}",
|
||||
"IndeeHub signer reconciliation incomplete (provider_copied={}, config_copied={}): {}",
|
||||
provider_copied,
|
||||
config_copied,
|
||||
String::from_utf8_lossy(&o.stderr)
|
||||
);
|
||||
}
|
||||
@@ -1620,124 +1688,10 @@ autopilot.active=false\n",
|
||||
}
|
||||
}
|
||||
|
||||
// IndeeHub: inject nostr-provider.js and patch container nginx for NIP-07 signing
|
||||
// IndeeHub: inject the current consent-gated provider and make it work
|
||||
// in both the dashboard frame and a direct browser tab.
|
||||
if package_id == "indeedhub" {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
|
||||
|
||||
// 1. Remove X-Frame-Options so iframe embedding works
|
||||
let _ = tokio::process::Command::new("podman")
|
||||
.args([
|
||||
"exec",
|
||||
"indeedhub",
|
||||
"sed",
|
||||
"-i",
|
||||
"/X-Frame-Options/d",
|
||||
"/etc/nginx/conf.d/default.conf",
|
||||
])
|
||||
.output()
|
||||
.await;
|
||||
|
||||
// 2. Copy nostr-provider.js into container
|
||||
let provider_src = "/opt/archipelago/web-ui/nostr-provider.js";
|
||||
if tokio::fs::metadata(provider_src).await.is_ok() {
|
||||
let _ = tokio::process::Command::new("podman")
|
||||
.args([
|
||||
"cp",
|
||||
provider_src,
|
||||
"indeedhub:/usr/share/nginx/html/nostr-provider.js",
|
||||
])
|
||||
.output()
|
||||
.await;
|
||||
}
|
||||
|
||||
// 3. Add nostr-provider.js location block + sub_filter injection
|
||||
let check = tokio::process::Command::new("podman")
|
||||
.args([
|
||||
"exec",
|
||||
"indeedhub",
|
||||
"grep",
|
||||
"-q",
|
||||
"nostr-provider",
|
||||
"/etc/nginx/conf.d/default.conf",
|
||||
])
|
||||
.output()
|
||||
.await;
|
||||
let already_patched = check.map(|o| o.status.success()).unwrap_or(false);
|
||||
|
||||
if !already_patched {
|
||||
// Read current nginx config from container
|
||||
let cat_out = tokio::process::Command::new("podman")
|
||||
.args(["exec", "indeedhub", "cat", "/etc/nginx/conf.d/default.conf"])
|
||||
.output()
|
||||
.await;
|
||||
|
||||
if let Ok(out) = cat_out {
|
||||
if out.status.success() {
|
||||
let conf = String::from_utf8_lossy(&out.stdout).to_string();
|
||||
|
||||
// Insert provider location block before the sw.js location
|
||||
let conf = conf.replace(
|
||||
"location = /sw.js {",
|
||||
"location = /nostr-provider.js {\n\
|
||||
\x20 add_header Cache-Control \"no-cache, no-store, must-revalidate\";\n\
|
||||
\x20 expires off;\n\
|
||||
\x20 }\n\n\
|
||||
\x20 location = /sw.js {"
|
||||
);
|
||||
|
||||
// Inject script tag into HTML via sub_filter
|
||||
let conf = if conf.contains("try_files") && !conf.contains("sub_filter") {
|
||||
conf.replacen(
|
||||
"try_files $uri $uri/ /index.html;",
|
||||
"try_files $uri $uri/ /index.html;\n\
|
||||
\x20 sub_filter_once on;\n\
|
||||
\x20 sub_filter '</head>' '<script src=\"/nostr-provider.js\"></script></head>';",
|
||||
1,
|
||||
)
|
||||
} else {
|
||||
conf
|
||||
};
|
||||
|
||||
// Write patched config back into container
|
||||
let tmp_path = "/tmp/indeedhub-nginx-patch.conf";
|
||||
if tokio::fs::write(tmp_path, &conf).await.is_ok() {
|
||||
let _ = tokio::process::Command::new("podman")
|
||||
.args(["cp", tmp_path, "indeedhub:/etc/nginx/conf.d/default.conf"])
|
||||
.output()
|
||||
.await;
|
||||
let _ = tokio::fs::remove_file(tmp_path).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Fix X-Forwarded-Prefix for NIP-98 URL reconstruction in iframe context
|
||||
let _ = tokio::process::Command::new("podman")
|
||||
.args(["exec", "indeedhub", "sed", "-i",
|
||||
"s|proxy_set_header X-Forwarded-Prefix /api;|proxy_set_header X-Forwarded-Prefix $http_x_forwarded_prefix/api;|",
|
||||
"/etc/nginx/conf.d/default.conf"])
|
||||
.output()
|
||||
.await;
|
||||
|
||||
// 5. Reload nginx to apply changes
|
||||
let reload = tokio::process::Command::new("podman")
|
||||
.args(["exec", "indeedhub", "nginx", "-s", "reload"])
|
||||
.output()
|
||||
.await;
|
||||
match reload {
|
||||
Ok(o) if o.status.success() => {
|
||||
info!("IndeeHub: NIP-07 provider injected, nginx patched and reloaded");
|
||||
}
|
||||
Ok(o) => {
|
||||
tracing::warn!(
|
||||
"IndeeHub nginx reload failed: {}",
|
||||
String::from_utf8_lossy(&o.stderr)
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("IndeeHub nginx reload error: {}", e);
|
||||
}
|
||||
}
|
||||
patch_indeedhub_nostr_provider().await;
|
||||
}
|
||||
|
||||
// Gitea: keep it on its native host port (3001). The UI opens Gitea
|
||||
@@ -2800,11 +2754,43 @@ fn is_unknown_app_id_error(err: &anyhow::Error) -> bool {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{
|
||||
orchestrator_install_app_id, parse_setup_token, should_try_orchestrator_install,
|
||||
uses_orchestrator_install_flow,
|
||||
orchestrator_install_app_id, parse_setup_token, patched_indeedhub_nginx_config,
|
||||
should_try_orchestrator_install, uses_orchestrator_install_flow,
|
||||
};
|
||||
use crate::api::rpc::package::runtime::orchestrator_uninstall_app_ids;
|
||||
|
||||
#[test]
|
||||
fn indeedhub_nginx_patch_is_complete_and_idempotent() {
|
||||
let original = r#"server {
|
||||
add_header X-Frame-Options SAMEORIGIN;
|
||||
location = /sw.js {
|
||||
expires off;
|
||||
}
|
||||
location /api/ {
|
||||
proxy_set_header X-Forwarded-Prefix /api;
|
||||
}
|
||||
location / {
|
||||
try_files $uri $uri/ /index.html;
|
||||
sub_filter_once on;
|
||||
sub_filter '</head>' '<script src="/nostr-provider.js"></script></head>';
|
||||
}
|
||||
}
|
||||
"#;
|
||||
let patched = patched_indeedhub_nginx_config(original);
|
||||
assert!(!patched.contains("X-Frame-Options"));
|
||||
assert!(patched.contains("location = /nostr-provider.js {"));
|
||||
assert!(patched.contains("Cache-Control \"no-cache, no-store, must-revalidate\""));
|
||||
assert!(patched.contains("src=\"/nostr-provider.js?v=tab-signer-v4\""));
|
||||
assert!(patched.contains("X-Forwarded-Prefix $http_x_forwarded_prefix/api"));
|
||||
assert_eq!(patched_indeedhub_nginx_config(&patched), patched);
|
||||
|
||||
let previous_broker = patched.replace("tab-signer-v4", "tab-signer-v3");
|
||||
let migrated = patched_indeedhub_nginx_config(&previous_broker);
|
||||
assert!(migrated.contains("tab-signer-v4"));
|
||||
assert!(!migrated.contains("tab-signer-v3"));
|
||||
assert_eq!(patched_indeedhub_nginx_config(&migrated), migrated);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn orchestrator_install_allowlist_includes_ported_backends() {
|
||||
for app in [
|
||||
|
||||
@@ -4,6 +4,7 @@ mod dependencies;
|
||||
mod install;
|
||||
mod lifecycle;
|
||||
mod pine_ha;
|
||||
pub(crate) use install::patch_indeedhub_nostr_provider;
|
||||
pub(crate) use pine_ha::wyoming_satellite_keeper;
|
||||
mod progress;
|
||||
mod runtime;
|
||||
|
||||
@@ -442,6 +442,9 @@ impl RpcHandler {
|
||||
"claimed_count": outcome.claimed_count,
|
||||
"received_sats": outcome.received_sats,
|
||||
"failed_count": outcome.failed_count,
|
||||
"receipt_id": outcome.receipt_id,
|
||||
"receipt_sats": outcome.receipt_sats,
|
||||
"receipt_at": outcome.receipt_at,
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
@@ -148,9 +148,16 @@ impl AppGate {
|
||||
let app = live.as_ref().unwrap_or(app);
|
||||
|
||||
let path = req.uri().path().to_string();
|
||||
// A dashboard same-origin proxy strips `/app/<id>/` before this gate
|
||||
// sees the URI. Carry that trusted proxy mount into the challenge's
|
||||
// form/assets and its post-login redirect so the browser stays inside
|
||||
// the mounted app instead of posting to the dashboard root.
|
||||
let mount_prefix = forwarded_mount_prefix(req.headers());
|
||||
|
||||
if let Some(action) = path.strip_prefix(GATE_PREFIX) {
|
||||
return self.handle_gate_action(req, app, action, client_ip).await;
|
||||
return self
|
||||
.handle_gate_action(req, app, action, client_ip, &mount_prefix)
|
||||
.await;
|
||||
}
|
||||
|
||||
// A browser fetches a few subresources WITHOUT credentials by
|
||||
@@ -188,10 +195,25 @@ impl AppGate {
|
||||
return proxy_to_app(req, app, false).await;
|
||||
}
|
||||
|
||||
// Capture the platform session before the request is moved into the
|
||||
// upstream proxy. Older app-gate sessions (issued before the paired
|
||||
// CSRF-cookie fix) can then repair themselves on the very next app
|
||||
// response, before the app's provider creates its signer iframe.
|
||||
let session_for_csrf = crate::session::extract_session_cookie(req.headers());
|
||||
let needs_csrf_cookie = cookie_value(req.headers(), "csrf_token").is_none();
|
||||
|
||||
match self.authorize(req.headers(), &app.app_id).await {
|
||||
// The credential was a cookie (or none was needed): the
|
||||
// Authorization header, if any, belongs to the app. Forward it.
|
||||
Authorization::Allow => proxy_to_app(req, app, false).await,
|
||||
Authorization::Allow => {
|
||||
let mut response = proxy_to_app(req, app, false).await;
|
||||
if needs_csrf_cookie {
|
||||
if let Some(token) = session_for_csrf {
|
||||
set_csrf_cookie(&mut response, &token).await;
|
||||
}
|
||||
}
|
||||
response
|
||||
}
|
||||
// The credential WAS the Authorization header, and it was ours.
|
||||
Authorization::AllowGateToken => proxy_to_app(req, app, true).await,
|
||||
// 401 rather than a redirect: a redirect to a login page is
|
||||
@@ -199,7 +221,9 @@ impl AppGate {
|
||||
// clients would follow it and parse HTML as if it were their API
|
||||
// response. The status says "you are not authenticated" in a way
|
||||
// every client understands, and browsers still render the body.
|
||||
Authorization::Challenge => login_page(app, None, StatusCode::UNAUTHORIZED),
|
||||
Authorization::Challenge => {
|
||||
login_page(app, None, StatusCode::UNAUTHORIZED, &mount_prefix)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,6 +253,7 @@ impl AppGate {
|
||||
app: &GatedPort,
|
||||
action: &str,
|
||||
client_ip: IpAddr,
|
||||
mount_prefix: &str,
|
||||
) -> Response<Body> {
|
||||
// Assets are GET and pre-auth by nature: the login page cannot
|
||||
// render its own background or logo without them.
|
||||
@@ -236,7 +261,7 @@ impl AppGate {
|
||||
return self.serve_asset(name);
|
||||
}
|
||||
if req.method() != Method::POST {
|
||||
return login_page(app, None, StatusCode::OK);
|
||||
return login_page(app, None, StatusCode::OK, mount_prefix);
|
||||
}
|
||||
|
||||
// Captured before the body is consumed. The pending-2FA session
|
||||
@@ -253,17 +278,28 @@ impl AppGate {
|
||||
app,
|
||||
Some("Too many attempts. Wait a minute and try again."),
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
mount_prefix,
|
||||
);
|
||||
}
|
||||
|
||||
let form = match read_form(req).await {
|
||||
Some(form) => form,
|
||||
None => return login_page(app, Some("Malformed request."), StatusCode::BAD_REQUEST),
|
||||
None => {
|
||||
return login_page(
|
||||
app,
|
||||
Some("Malformed request."),
|
||||
StatusCode::BAD_REQUEST,
|
||||
mount_prefix,
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
match action {
|
||||
"login" => self.do_login(app, &form, client_ip).await,
|
||||
"totp" => self.do_totp(app, &form, pending, client_ip).await,
|
||||
"login" => self.do_login(app, &form, client_ip, mount_prefix).await,
|
||||
"totp" => {
|
||||
self.do_totp(app, &form, pending, client_ip, mount_prefix)
|
||||
.await
|
||||
}
|
||||
_ => not_found(),
|
||||
}
|
||||
}
|
||||
@@ -288,14 +324,25 @@ impl AppGate {
|
||||
.expect("asset response builds")
|
||||
}
|
||||
|
||||
async fn do_login(&self, app: &GatedPort, form: &Form, client_ip: IpAddr) -> Response<Body> {
|
||||
async fn do_login(
|
||||
&self,
|
||||
app: &GatedPort,
|
||||
form: &Form,
|
||||
client_ip: IpAddr,
|
||||
mount_prefix: &str,
|
||||
) -> Response<Body> {
|
||||
let password = field(form, "password").unwrap_or_default();
|
||||
|
||||
match self.auth.verify_password(&password).await {
|
||||
Ok(true) => {}
|
||||
_ => {
|
||||
self.limiter.record_failure(client_ip).await;
|
||||
return login_page(app, Some("Incorrect password."), StatusCode::UNAUTHORIZED);
|
||||
return login_page(
|
||||
app,
|
||||
Some("Incorrect password."),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
mount_prefix,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -307,8 +354,8 @@ impl AppGate {
|
||||
if let Ok(Some(totp_data)) = self.auth.get_totp_data().await {
|
||||
if let Ok(secret) = crate::totp::decrypt_secret(&totp_data, &password) {
|
||||
let pending = self.sessions.create_pending(secret).await;
|
||||
let mut resp = totp_page(app, None, StatusCode::OK);
|
||||
set_session_cookie(&mut resp, &pending);
|
||||
let mut resp = totp_page(app, None, StatusCode::OK, mount_prefix);
|
||||
set_session_cookie(&mut resp, &pending).await;
|
||||
return resp;
|
||||
}
|
||||
}
|
||||
@@ -319,12 +366,13 @@ impl AppGate {
|
||||
app,
|
||||
Some("Two-factor data could not be read. Sign in from the dashboard."),
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
mount_prefix,
|
||||
);
|
||||
}
|
||||
|
||||
let token = self.sessions.create().await;
|
||||
let mut resp = redirect_to_app();
|
||||
set_session_cookie(&mut resp, &token);
|
||||
let mut resp = redirect_to_app(mount_prefix);
|
||||
set_session_cookie(&mut resp, &token).await;
|
||||
resp
|
||||
}
|
||||
|
||||
@@ -334,10 +382,16 @@ impl AppGate {
|
||||
form: &Form,
|
||||
pending: Option<String>,
|
||||
client_ip: IpAddr,
|
||||
mount_prefix: &str,
|
||||
) -> Response<Body> {
|
||||
let code = field(form, "code").unwrap_or_default();
|
||||
let Some(pending) = pending.filter(|s| !s.is_empty()) else {
|
||||
return login_page(app, Some("Session expired."), StatusCode::UNAUTHORIZED);
|
||||
return login_page(
|
||||
app,
|
||||
Some("Session expired."),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
mount_prefix,
|
||||
);
|
||||
};
|
||||
|
||||
let Some(secret) = self.sessions.get_pending_secret(&pending).await else {
|
||||
@@ -345,6 +399,7 @@ impl AppGate {
|
||||
app,
|
||||
Some("Session expired. Start again."),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
mount_prefix,
|
||||
);
|
||||
};
|
||||
|
||||
@@ -371,17 +426,27 @@ impl AppGate {
|
||||
}
|
||||
match self.sessions.upgrade_to_full(&pending).await {
|
||||
Some(full) => {
|
||||
let mut resp = redirect_to_app();
|
||||
set_session_cookie(&mut resp, &full);
|
||||
let mut resp = redirect_to_app(mount_prefix);
|
||||
set_session_cookie(&mut resp, &full).await;
|
||||
resp
|
||||
}
|
||||
None => login_page(app, Some("Session expired."), StatusCode::UNAUTHORIZED),
|
||||
None => login_page(
|
||||
app,
|
||||
Some("Session expired."),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
mount_prefix,
|
||||
),
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
self.limiter.record_failure(client_ip).await;
|
||||
let mut resp = totp_page(app, Some("Incorrect code."), StatusCode::UNAUTHORIZED);
|
||||
set_session_cookie(&mut resp, &pending);
|
||||
let mut resp = totp_page(
|
||||
app,
|
||||
Some("Incorrect code."),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
mount_prefix,
|
||||
);
|
||||
set_session_cookie(&mut resp, &pending).await;
|
||||
resp
|
||||
}
|
||||
}
|
||||
@@ -634,7 +699,7 @@ fn strip_gate_cookies(headers: &mut hyper::HeaderMap) {
|
||||
}
|
||||
}
|
||||
|
||||
fn set_session_cookie(resp: &mut Response<Body>, token: &str) {
|
||||
async fn set_session_cookie(resp: &mut Response<Body>, token: &str) {
|
||||
// No Domain attribute, so the cookie is host-only. Cookies ignore port,
|
||||
// which is what makes one sign-in cover the dashboard and every app port
|
||||
// on the same host — and equally why an app on a *different* host (its
|
||||
@@ -644,12 +709,82 @@ fn set_session_cookie(resp: &mut Response<Body>, token: &str) {
|
||||
{
|
||||
resp.headers_mut().append(header::SET_COOKIE, value);
|
||||
}
|
||||
|
||||
// The dashboard RPC layer requires a readable CSRF cookie as well as the
|
||||
// HttpOnly session cookie. An app-gate login is a complete node login, so
|
||||
// it must establish the same pair as auth.login; otherwise a fresh browser
|
||||
// can open the signer broker but every identity/signing RPC is rejected
|
||||
// with `has_session=true, has_header=false`.
|
||||
set_csrf_cookie(resp, token).await;
|
||||
}
|
||||
|
||||
fn redirect_to_app() -> Response<Body> {
|
||||
async fn set_csrf_cookie(resp: &mut Response<Body>, token: &str) {
|
||||
let csrf = crate::api::rpc::derive_csrf_token(token).await;
|
||||
if let Ok(value) =
|
||||
header::HeaderValue::from_str(&format!("csrf_token={csrf}; SameSite=Lax; Path=/"))
|
||||
{
|
||||
resp.headers_mut().append(header::SET_COOKIE, value);
|
||||
}
|
||||
}
|
||||
|
||||
fn cookie_value(headers: &HeaderMap, name: &str) -> Option<String> {
|
||||
let prefix = format!("{name}=");
|
||||
headers
|
||||
.get_all(header::COOKIE)
|
||||
.iter()
|
||||
.filter_map(|value| value.to_str().ok())
|
||||
.flat_map(|value| value.split(';'))
|
||||
.map(str::trim)
|
||||
.find_map(|pair| pair.strip_prefix(&prefix))
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(str::to_owned)
|
||||
}
|
||||
|
||||
/// Validate the mount supplied by the node's own nginx proxy.
|
||||
///
|
||||
/// Treat this as untrusted input even though our canonical proxy sets it: a
|
||||
/// client can reach an app-gate port directly and forge request headers. Only
|
||||
/// a short absolute path made from ordinary URL-path characters is accepted;
|
||||
/// protocol-relative URLs, dot segments, escaping and query/fragment syntax
|
||||
/// all fall back to the direct-port root.
|
||||
fn forwarded_mount_prefix(headers: &HeaderMap) -> String {
|
||||
let Some(raw) = headers
|
||||
.get("x-forwarded-prefix")
|
||||
.and_then(|value| value.to_str().ok())
|
||||
else {
|
||||
return String::new();
|
||||
};
|
||||
let value = raw.trim_end_matches('/');
|
||||
if value.is_empty()
|
||||
|| value.len() > 256
|
||||
|| !value.starts_with('/')
|
||||
|| value.starts_with("//")
|
||||
|| value
|
||||
.bytes()
|
||||
.any(|b| !(b.is_ascii_alphanumeric() || matches!(b, b'/' | b'-' | b'_' | b'.')))
|
||||
|| value
|
||||
.split('/')
|
||||
.skip(1)
|
||||
.any(|segment| segment.is_empty() || segment == "." || segment == "..")
|
||||
{
|
||||
return String::new();
|
||||
}
|
||||
value.to_owned()
|
||||
}
|
||||
|
||||
fn gate_url(mount_prefix: &str, action: &str) -> String {
|
||||
format!("{mount_prefix}{GATE_PREFIX}{action}")
|
||||
}
|
||||
|
||||
fn redirect_to_app(mount_prefix: &str) -> Response<Body> {
|
||||
let location = if mount_prefix.is_empty() {
|
||||
"/".to_owned()
|
||||
} else {
|
||||
format!("{mount_prefix}/")
|
||||
};
|
||||
Response::builder()
|
||||
.status(StatusCode::SEE_OTHER)
|
||||
.header(header::LOCATION, "/")
|
||||
.header(header::LOCATION, location)
|
||||
.body(Body::empty())
|
||||
.expect("static response builds")
|
||||
}
|
||||
@@ -674,7 +809,13 @@ dashboard and check {name} under My Apps.</p>"#,
|
||||
icon = icon_markup(app),
|
||||
name = esc(&app.app_name),
|
||||
);
|
||||
let mut resp = page("App not responding", app, &body, StatusCode::BAD_GATEWAY);
|
||||
let mut resp = page(
|
||||
"App not responding",
|
||||
app,
|
||||
&body,
|
||||
StatusCode::BAD_GATEWAY,
|
||||
"",
|
||||
);
|
||||
// Header-based refresh, not <meta> or script: page()'s CSP allows no
|
||||
// script, and the header keeps the retry out of the document entirely.
|
||||
resp.headers_mut()
|
||||
@@ -707,7 +848,7 @@ fn esc(s: &str) -> String {
|
||||
/// the app's own port, so any asset URL would either hit the unauthenticated
|
||||
/// app behind it or a different origin the browser may not reach.
|
||||
/// One stacked layer per background, each delayed so they cross-fade in turn.
|
||||
fn background_layers() -> String {
|
||||
fn background_layers(mount_prefix: &str) -> String {
|
||||
let step = LOGIN_BACKGROUNDS.len() as u32 * 9 / LOGIN_BACKGROUNDS.len() as u32;
|
||||
LOGIN_BACKGROUNDS
|
||||
.iter()
|
||||
@@ -715,7 +856,7 @@ fn background_layers() -> String {
|
||||
.map(|(i, name)| {
|
||||
format!(
|
||||
r#"<div class="bg" style="background-image:url('{prefix}asset/{name}');animation-delay:{delay}s"></div>"#,
|
||||
prefix = GATE_PREFIX,
|
||||
prefix = gate_url(mount_prefix, ""),
|
||||
delay = i as u32 * step,
|
||||
)
|
||||
})
|
||||
@@ -938,7 +1079,13 @@ fn base64_encode(bytes: &[u8]) -> String {
|
||||
base64::engine::general_purpose::STANDARD.encode(bytes)
|
||||
}
|
||||
|
||||
fn page(title: &str, app: &GatedPort, body: &str, status: StatusCode) -> Response<Body> {
|
||||
fn page(
|
||||
title: &str,
|
||||
app: &GatedPort,
|
||||
body: &str,
|
||||
status: StatusCode,
|
||||
mount_prefix: &str,
|
||||
) -> Response<Body> {
|
||||
let html = format!(
|
||||
r#"<!doctype html>
|
||||
<html lang="en"><head>
|
||||
@@ -1055,7 +1202,7 @@ button.loading .busy {{ display:inline-flex; align-items:center; gap:.5rem; }}
|
||||
app_name = esc(&app.app_name),
|
||||
body = body,
|
||||
submit_feedback = SUBMIT_FEEDBACK_JS,
|
||||
backgrounds = background_layers(),
|
||||
backgrounds = background_layers(mount_prefix),
|
||||
cycle = LOGIN_BACKGROUNDS.len() as u32 * 9,
|
||||
hold = 100 / LOGIN_BACKGROUNDS.len() as u32,
|
||||
fade = 100 / LOGIN_BACKGROUNDS.len() as u32 + 4,
|
||||
@@ -1092,7 +1239,12 @@ button.loading .busy {{ display:inline-flex; align-items:center; gap:.5rem; }}
|
||||
/// The challenge. Names and pictures the app being opened, so the visitor can
|
||||
/// confirm what they are authenticating to rather than being asked for a
|
||||
/// password by an unexplained page.
|
||||
fn login_page(app: &GatedPort, error: Option<&str>, status: StatusCode) -> Response<Body> {
|
||||
fn login_page(
|
||||
app: &GatedPort,
|
||||
error: Option<&str>,
|
||||
status: StatusCode,
|
||||
mount_prefix: &str,
|
||||
) -> Response<Body> {
|
||||
let body = format!(
|
||||
r#"{logo}
|
||||
{icon}
|
||||
@@ -1110,14 +1262,19 @@ fn login_page(app: &GatedPort, error: Option<&str>, status: StatusCode) -> Respo
|
||||
err = error
|
||||
.map(|e| format!(r#"<div class="err">{}</div>"#, esc(e)))
|
||||
.unwrap_or_default(),
|
||||
prefix = GATE_PREFIX,
|
||||
prefix = gate_url(mount_prefix, ""),
|
||||
);
|
||||
page("Sign in", app, &body, status)
|
||||
page("Sign in", app, &body, status, mount_prefix)
|
||||
}
|
||||
|
||||
/// Second factor. Reached only after the password verified, and the session
|
||||
/// backing it cannot authorise anything until this completes.
|
||||
fn totp_page(app: &GatedPort, error: Option<&str>, status: StatusCode) -> Response<Body> {
|
||||
fn totp_page(
|
||||
app: &GatedPort,
|
||||
error: Option<&str>,
|
||||
status: StatusCode,
|
||||
mount_prefix: &str,
|
||||
) -> Response<Body> {
|
||||
let body = format!(
|
||||
r#"{icon}
|
||||
<h1>Two-factor code</h1>
|
||||
@@ -1133,9 +1290,9 @@ fn totp_page(app: &GatedPort, error: Option<&str>, status: StatusCode) -> Respon
|
||||
err = error
|
||||
.map(|e| format!(r#"<div class="err">{}</div>"#, esc(e)))
|
||||
.unwrap_or_default(),
|
||||
prefix = GATE_PREFIX,
|
||||
prefix = gate_url(mount_prefix, ""),
|
||||
);
|
||||
page("Two-factor", app, &body, status)
|
||||
page("Two-factor", app, &body, status, mount_prefix)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1207,9 +1364,35 @@ mod tests {
|
||||
assert_eq!(bearer_token(&headers), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forwarded_mount_prefix_accepts_only_a_safe_absolute_path() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
"x-forwarded-prefix",
|
||||
"/app/archipelago-source/".parse().unwrap(),
|
||||
);
|
||||
assert_eq!(forwarded_mount_prefix(&headers), "/app/archipelago-source");
|
||||
|
||||
for unsafe_value in [
|
||||
"//other.example/app",
|
||||
"/app/../admin",
|
||||
"/app//source",
|
||||
"/app/source?next=//other.example",
|
||||
"https://other.example/app",
|
||||
"/app/%2e%2e/admin",
|
||||
] {
|
||||
headers.insert("x-forwarded-prefix", unsafe_value.parse().unwrap());
|
||||
assert_eq!(
|
||||
forwarded_mount_prefix(&headers),
|
||||
"",
|
||||
"accepted {unsafe_value}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn login_page_names_the_app() {
|
||||
let resp = login_page(&app(), None, StatusCode::UNAUTHORIZED);
|
||||
let resp = login_page(&app(), None, StatusCode::UNAUTHORIZED, "");
|
||||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
|
||||
let body = hyper::body::to_bytes(resp.into_body()).await.unwrap();
|
||||
let html = String::from_utf8_lossy(&body);
|
||||
@@ -1222,7 +1405,7 @@ mod tests {
|
||||
async fn page_escapes_app_names() {
|
||||
let mut app = app();
|
||||
app.app_name = r#"<script>alert(1)</script>"#.to_string();
|
||||
let resp = login_page(&app, None, StatusCode::UNAUTHORIZED);
|
||||
let resp = login_page(&app, None, StatusCode::UNAUTHORIZED, "");
|
||||
let body = hyper::body::to_bytes(resp.into_body()).await.unwrap();
|
||||
let html = String::from_utf8_lossy(&body);
|
||||
assert!(!html.contains("<script>alert"));
|
||||
@@ -1235,6 +1418,7 @@ mod tests {
|
||||
&app(),
|
||||
Some("<img src=x onerror=1>"),
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"",
|
||||
);
|
||||
let body = hyper::body::to_bytes(resp.into_body()).await.unwrap();
|
||||
let html = String::from_utf8_lossy(&body);
|
||||
@@ -1293,7 +1477,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn challenge_pages_are_uncacheable_and_framable_only_by_this_node() {
|
||||
let resp = login_page(&app(), None, StatusCode::UNAUTHORIZED);
|
||||
let resp = login_page(&app(), None, StatusCode::UNAUTHORIZED, "");
|
||||
assert_eq!(resp.headers()[header::CACHE_CONTROL], "no-store");
|
||||
assert!(
|
||||
!resp.headers().contains_key("X-Frame-Options"),
|
||||
@@ -1329,7 +1513,7 @@ mod tests {
|
||||
/// never 404 at all.
|
||||
#[tokio::test]
|
||||
async fn login_page_sources_its_art_from_the_gate() {
|
||||
let resp = login_page(&app(), None, StatusCode::UNAUTHORIZED);
|
||||
let resp = login_page(&app(), None, StatusCode::UNAUTHORIZED, "");
|
||||
let body = hyper::body::to_bytes(resp.into_body()).await.unwrap();
|
||||
let html = String::from_utf8_lossy(&body).to_string();
|
||||
assert_eq!(
|
||||
@@ -1345,13 +1529,32 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mounted_login_keeps_forms_assets_and_redirect_inside_the_app() {
|
||||
let mount = "/app/archipelago-source";
|
||||
let resp = login_page(&app(), None, StatusCode::UNAUTHORIZED, mount);
|
||||
let body = hyper::body::to_bytes(resp.into_body()).await.unwrap();
|
||||
let html = String::from_utf8_lossy(&body);
|
||||
assert!(html.contains(r#"action="/app/archipelago-source/__archipelago-gate/login""#));
|
||||
for name in LOGIN_BACKGROUNDS {
|
||||
assert!(html.contains(&format!("/app/archipelago-source{GATE_PREFIX}asset/{name}")));
|
||||
}
|
||||
|
||||
let redirect = redirect_to_app(mount);
|
||||
assert_eq!(redirect.status(), StatusCode::SEE_OTHER);
|
||||
assert_eq!(
|
||||
redirect.headers()[header::LOCATION],
|
||||
"/app/archipelago-source/"
|
||||
);
|
||||
}
|
||||
|
||||
/// The only script the challenge pages may run is the submit-feedback
|
||||
/// snippet, admitted by hash. The page must carry exactly that script,
|
||||
/// and the CSP must name its hash — anything injected has a different
|
||||
/// hash and stays inert.
|
||||
#[tokio::test]
|
||||
async fn submit_feedback_script_is_present_and_hash_pinned() {
|
||||
let resp = login_page(&app(), None, StatusCode::UNAUTHORIZED);
|
||||
let resp = login_page(&app(), None, StatusCode::UNAUTHORIZED, "");
|
||||
let csp = resp.headers()["Content-Security-Policy"]
|
||||
.to_str()
|
||||
.unwrap()
|
||||
@@ -1455,6 +1658,54 @@ mod tests {
|
||||
assert!(headers.get(header::COOKIE).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookie_value_finds_only_a_nonempty_named_cookie() {
|
||||
let mut headers = HeaderMap::new();
|
||||
headers.insert(
|
||||
header::COOKIE,
|
||||
"app_session=keep; csrf_token=csrf123; empty="
|
||||
.parse()
|
||||
.unwrap(),
|
||||
);
|
||||
assert_eq!(
|
||||
cookie_value(&headers, "csrf_token"),
|
||||
Some("csrf123".to_string())
|
||||
);
|
||||
assert_eq!(cookie_value(&headers, "session"), None);
|
||||
assert_eq!(cookie_value(&headers, "empty"), None);
|
||||
}
|
||||
|
||||
/// An app-gate login must be equivalent to a dashboard login. The session
|
||||
/// cookie alone can load the broker route, but every identity/signing RPC
|
||||
/// also needs the matching readable CSRF cookie.
|
||||
#[tokio::test]
|
||||
async fn app_gate_login_establishes_the_dashboard_csrf_cookie() {
|
||||
let token = "app-gate-session-token";
|
||||
let mut resp = redirect_to_app("");
|
||||
|
||||
set_session_cookie(&mut resp, token).await;
|
||||
|
||||
let cookies: Vec<_> = resp
|
||||
.headers()
|
||||
.get_all(header::SET_COOKIE)
|
||||
.iter()
|
||||
.filter_map(|value| value.to_str().ok())
|
||||
.collect();
|
||||
let expected_csrf = crate::api::rpc::derive_csrf_token(token).await;
|
||||
assert!(cookies
|
||||
.iter()
|
||||
.any(|cookie| cookie.starts_with(&format!("session={token};"))));
|
||||
assert!(cookies
|
||||
.iter()
|
||||
.any(|cookie| cookie.starts_with(&format!("csrf_token={expected_csrf};"))));
|
||||
assert!(cookies
|
||||
.iter()
|
||||
.any(|cookie| cookie.starts_with("session=") && cookie.contains("HttpOnly")));
|
||||
assert!(cookies
|
||||
.iter()
|
||||
.any(|cookie| cookie.starts_with("csrf_token=") && !cookie.contains("HttpOnly")));
|
||||
}
|
||||
|
||||
/// The regression that killed every Nostr login on 2026-08-06.
|
||||
///
|
||||
/// IndeeHub's NIP-98 credential rides in `Authorization: Nostr <event>`
|
||||
|
||||
@@ -26,7 +26,7 @@ const DOCTOR_SERVICE: &str =
|
||||
include_str!("../../../image-recipe/configs/archipelago-doctor.service");
|
||||
const DOCTOR_TIMER: &str = include_str!("../../../image-recipe/configs/archipelago-doctor.timer");
|
||||
|
||||
const DOCTOR_SH_PATH: &str = "/home/archipelago/archy/scripts/container-doctor.sh";
|
||||
const DOCTOR_SH_PATH: &str = "/opt/archipelago/scripts/container-doctor.sh";
|
||||
const DOCTOR_SERVICE_PATH: &str = "/etc/systemd/system/archipelago-doctor.service";
|
||||
const DOCTOR_TIMER_PATH: &str = "/etc/systemd/system/archipelago-doctor.timer";
|
||||
|
||||
@@ -85,6 +85,15 @@ const RUNTIME_ASSETS_DIR: &str = "/opt/archipelago/web-ui/archipelago-runtime";
|
||||
/// image-recipe/configs/nginx-archipelago.conf.
|
||||
const NGINX_APP_CATALOG_BLOCK: &str = "\n # App Store catalog proxy — backend fetches from configured registries\n # so the browser doesn't hit CORS/CSP. Without this block nginx falls\n # through to the SPA index.html and the frontend gets HTML back instead\n # of JSON.\n location /api/app-catalog {\n proxy_pass http://127.0.0.1:5678;\n proxy_http_version 1.1;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header Cookie $http_cookie;\n proxy_connect_timeout 15s;\n proxy_read_timeout 30s;\n proxy_send_timeout 15s;\n error_page 502 503 = @backend_unavailable;\n error_page 504 = @backend_timeout;\n }\n\n";
|
||||
|
||||
const NGINX_SOURCE_PROXY_BLOCK: &str = " # GitWorkshop follows the dashboard origin so LAN, Tailscale, FIPS, Tor,\n # hostnames and reverse proxies all use the connection that already works.\n location /app/archipelago-source/ {\n proxy_pass http://127.0.0.2:8337/;\n proxy_http_version 1.1;\n proxy_set_header Host $http_host;\n proxy_set_header Cookie $http_cookie;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_set_header X-Forwarded-Prefix /app/archipelago-source;\n proxy_hide_header X-Frame-Options;\n add_header X-Frame-Options \"SAMEORIGIN\" always;\n add_header X-Content-Type-Options \"nosniff\" always;\n proxy_read_timeout 300s;\n }\n";
|
||||
|
||||
const NGINX_SOURCE_PROXY_BLOCK_SNIPPET: &str = "# GitWorkshop follows the dashboard origin; the app gate keeps the route\n# session-authenticated before it reaches the loopback-only container.\nlocation /app/archipelago-source/ {\n proxy_pass http://127.0.0.2:8337/;\n proxy_http_version 1.1;\n proxy_set_header Host $http_host;\n proxy_set_header Cookie $http_cookie;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_set_header X-Forwarded-Prefix /app/archipelago-source;\n proxy_hide_header X-Frame-Options;\n add_header X-Frame-Options \"SAMEORIGIN\" always;\n add_header X-Content-Type-Options \"nosniff\" always;\n proxy_read_timeout 300s;\n}\n";
|
||||
|
||||
/// The normal dashboard sends X-Frame-Options SAMEORIGIN. This one document
|
||||
/// must be frameable by an app on another port of the same node so tabs and
|
||||
/// companion WebViews can use the same authenticated signer UI.
|
||||
const NGINX_NOSTR_SIGNER_BLOCK: &str = " # Dashboard-origin Nostr signer for tab/WebView apps.\n location = /nostr-signer {\n try_files /index.html =404;\n add_header Cache-Control \"no-store\" always;\n add_header X-Content-Type-Options \"nosniff\" always;\n add_header Referrer-Policy \"no-referrer\" always;\n add_header Content-Security-Policy \"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'self' http://$host:* https://$host:*; base-uri 'none'; form-action 'none';\" always;\n }\n\n";
|
||||
|
||||
const NGINX_BITCOIN_STATUS_BLOCK: &str = "\n location /bitcoin-status {\n proxy_pass http://127.0.0.1:5678/bitcoin-status;\n proxy_http_version 1.1;\n proxy_set_header Host $host;\n proxy_connect_timeout 10s;\n proxy_read_timeout 10s;\n proxy_send_timeout 5s;\n error_page 502 503 = @backend_unavailable;\n error_page 504 = @backend_timeout;\n }\n";
|
||||
|
||||
/// Inserted into every server block that lacks the `/proxy/lnd/` proxy. Nodes
|
||||
@@ -1231,7 +1240,7 @@ async fn run() -> Result<bool> {
|
||||
|
||||
let mut changed = false;
|
||||
|
||||
// 1. Script — lives in archipelago's home dir, user-writable.
|
||||
// 1. Script — lives in the canonical OTA runtime scripts directory.
|
||||
if needs_write(DOCTOR_SH_PATH, DOCTOR_SH).await {
|
||||
fs::write(DOCTOR_SH_PATH, DOCTOR_SH)
|
||||
.await
|
||||
@@ -1580,6 +1589,62 @@ fn heal_stale_web_search_block(content: &str) -> Option<String> {
|
||||
))
|
||||
}
|
||||
|
||||
fn heal_missing_source_proxy(content: &str) -> Option<String> {
|
||||
if content.contains("location /app/archipelago-source/") {
|
||||
return None;
|
||||
}
|
||||
let indented_anchor = " location /app/gitea/ {";
|
||||
if content.contains(indented_anchor) {
|
||||
return Some(content.replace(
|
||||
indented_anchor,
|
||||
&format!("{}{}", NGINX_SOURCE_PROXY_BLOCK, indented_anchor),
|
||||
));
|
||||
}
|
||||
let snippet_anchor = "location /app/gitea/ {";
|
||||
content.contains(snippet_anchor).then(|| {
|
||||
content.replace(
|
||||
snippet_anchor,
|
||||
&format!("{}{}", NGINX_SOURCE_PROXY_BLOCK_SNIPPET, snippet_anchor),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/// Older same-origin GitWorkshop blocks stripped the app mount but did not
|
||||
/// tell the app gate what was stripped. Its challenge therefore posted to
|
||||
/// `/__archipelago-gate/login` on the dashboard and nginx returned 405. Add
|
||||
/// the mount header to every canonical source block (HTTP and HTTPS snippet).
|
||||
fn heal_source_forwarded_prefix(content: &str) -> Option<String> {
|
||||
if !content.contains("proxy_pass http://127.0.0.2:8337/;") {
|
||||
return None;
|
||||
}
|
||||
let mut healed = content.to_owned();
|
||||
for indent in [" ", " "] {
|
||||
let old = format!(
|
||||
"proxy_pass http://127.0.0.2:8337/;\n{indent}proxy_http_version 1.1;\n{indent}proxy_set_header Host $http_host;\n{indent}proxy_set_header Cookie $http_cookie;\n{indent}proxy_set_header X-Real-IP $remote_addr;\n{indent}proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n{indent}proxy_set_header X-Forwarded-Proto $scheme;\n{indent}proxy_hide_header X-Frame-Options;"
|
||||
);
|
||||
let new = old.replace(
|
||||
&format!("\n{indent}proxy_hide_header X-Frame-Options;"),
|
||||
&format!(
|
||||
"\n{indent}proxy_set_header X-Forwarded-Prefix /app/archipelago-source;\n{indent}proxy_hide_header X-Frame-Options;"
|
||||
),
|
||||
);
|
||||
healed = healed.replace(&old, &new);
|
||||
}
|
||||
(healed != content).then_some(healed)
|
||||
}
|
||||
|
||||
fn heal_missing_nostr_signer(content: &str) -> Option<String> {
|
||||
if content.contains("location = /nostr-signer") {
|
||||
return None;
|
||||
}
|
||||
// The anchor occurs once in each complete HTTP/HTTPS dashboard server and
|
||||
// does not occur in the separate app-proxy snippet.
|
||||
let anchor = " location /aiui/ {";
|
||||
content
|
||||
.contains(anchor)
|
||||
.then(|| content.replace(anchor, &format!("{}{}", NGINX_NOSTR_SIGNER_BLOCK, anchor)))
|
||||
}
|
||||
|
||||
async fn patch_nginx_conf(path: &str) -> Result<bool> {
|
||||
let content = fs::read_to_string(path)
|
||||
.await
|
||||
@@ -1610,6 +1675,9 @@ async fn patch_nginx_conf(path: &str) -> Result<bool> {
|
||||
let missing_v6_https =
|
||||
content.contains("listen 443 ssl default_server;") && !content.contains("listen [::]:443");
|
||||
let stale_web_search = heal_stale_web_search_block(&content).is_some();
|
||||
let missing_source_proxy = heal_missing_source_proxy(&content).is_some();
|
||||
let missing_source_prefix = heal_source_forwarded_prefix(&content).is_some();
|
||||
let missing_nostr_signer = heal_missing_nostr_signer(&content).is_some();
|
||||
if !missing_app_catalog
|
||||
&& !missing_bitcoin_status
|
||||
&& !missing_lnd_proxy
|
||||
@@ -1620,6 +1688,9 @@ async fn patch_nginx_conf(path: &str) -> Result<bool> {
|
||||
&& !missing_v6_http
|
||||
&& !missing_v6_https
|
||||
&& !stale_web_search
|
||||
&& !missing_source_proxy
|
||||
&& !missing_source_prefix
|
||||
&& !missing_nostr_signer
|
||||
{
|
||||
return Ok(false);
|
||||
}
|
||||
@@ -1629,6 +1700,15 @@ async fn patch_nginx_conf(path: &str) -> Result<bool> {
|
||||
if let Some(p) = heal_stale_web_search_block(&patched) {
|
||||
patched = p;
|
||||
}
|
||||
if let Some(p) = heal_missing_source_proxy(&patched) {
|
||||
patched = p;
|
||||
}
|
||||
if let Some(p) = heal_source_forwarded_prefix(&patched) {
|
||||
patched = p;
|
||||
}
|
||||
if let Some(p) = heal_missing_nostr_signer(&patched) {
|
||||
patched = p;
|
||||
}
|
||||
|
||||
if missing_v6_http {
|
||||
patched = patched.replace(
|
||||
@@ -1796,6 +1876,17 @@ async fn patch_nginx_conf(path: &str) -> Result<bool> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn doctor_service_uses_the_canonical_ota_script_path() {
|
||||
let expected = format!("ExecStart={} --local", DOCTOR_SH_PATH);
|
||||
assert!(DOCTOR_SERVICE.lines().any(|line| line == expected));
|
||||
assert_eq!(
|
||||
DOCTOR_SH_PATH,
|
||||
"/opt/archipelago/scripts/container-doctor.sh"
|
||||
);
|
||||
assert!(!DOCTOR_SERVICE.contains("/home/archipelago/archy/"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn podman_heal_outcome_no_longer_has_cleanup_variant() {
|
||||
let outcome = PodmanHealOutcome::Unhealthy;
|
||||
@@ -1817,6 +1908,48 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn source_proxy_uses_same_origin_through_authenticated_app_gate() {
|
||||
let main = "server {\n location /app/gitea/ {\n }\n}\nserver {\n location /app/gitea/ {\n }\n}";
|
||||
let healed = heal_missing_source_proxy(main).expect("source proxy must be added");
|
||||
assert_eq!(
|
||||
healed.matches("location /app/archipelago-source/").count(),
|
||||
2
|
||||
);
|
||||
assert!(healed.contains("proxy_pass http://127.0.0.2:8337/;"));
|
||||
assert!(healed.contains("proxy_set_header Cookie $http_cookie;"));
|
||||
assert!(healed.contains("proxy_set_header X-Forwarded-Prefix /app/archipelago-source;"));
|
||||
assert!(heal_missing_source_proxy(&healed).is_none());
|
||||
|
||||
let snippet = "location /app/gitea/ {\n}";
|
||||
let healed = heal_missing_source_proxy(snippet).expect("snippet must be patched");
|
||||
assert!(healed.starts_with("# GitWorkshop follows the dashboard origin"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn existing_source_proxy_gets_the_forwarded_mount_once() {
|
||||
let stale = "location /app/archipelago-source/ {\n proxy_pass http://127.0.0.2:8337/;\n proxy_http_version 1.1;\n proxy_set_header Host $http_host;\n proxy_set_header Cookie $http_cookie;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n proxy_set_header X-Forwarded-Proto $scheme;\n proxy_hide_header X-Frame-Options;\n}";
|
||||
let healed = heal_source_forwarded_prefix(stale).expect("mount header must be added");
|
||||
assert_eq!(
|
||||
healed
|
||||
.matches("X-Forwarded-Prefix /app/archipelago-source")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(heal_source_forwarded_prefix(&healed).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nostr_signer_is_added_to_each_dashboard_server_only_once() {
|
||||
let main =
|
||||
"server {\n location /aiui/ {\n }\n}\nserver {\n location /aiui/ {\n }\n}";
|
||||
let healed = heal_missing_nostr_signer(main).expect("signer route must be added");
|
||||
assert_eq!(healed.matches("location = /nostr-signer").count(), 2);
|
||||
assert!(healed.contains("frame-ancestors 'self' http://$host:* https://$host:*"));
|
||||
assert!(heal_missing_nostr_signer(&healed).is_none());
|
||||
assert!(heal_missing_nostr_signer("location /app/gitea/ {}\n").is_none());
|
||||
}
|
||||
|
||||
/// The exact ExecStart framework-pt shipped with must parse, and the
|
||||
/// rewrite must preserve its listen port and forward target.
|
||||
#[test]
|
||||
|
||||
@@ -7,6 +7,6 @@
|
||||
|
||||
pub const APP_LAUNCH_PORTS: &[u16] = &[
|
||||
2283, 2342, 3000, 3001, 3002, 3030, 4080, 5180, 7778, 8080, 8081, 8082, 8083, 8084, 8085, 8087,
|
||||
8090, 8096, 8123, 8175, 8176, 8187, 8240, 8334, 8336, 8888, 8999, 9000, 9100, 10380, 11434,
|
||||
18081, 18083, 23000, 32838, 50002,
|
||||
8090, 8096, 8123, 8175, 8176, 8187, 8240, 8334, 8336, 8337, 8888, 8999, 9000, 9100, 10380,
|
||||
11434, 18081, 18083, 23000, 32838, 50002,
|
||||
];
|
||||
|
||||
@@ -413,6 +413,11 @@ async fn main() -> Result<()> {
|
||||
// delays server readiness; best-effort, warnings only.
|
||||
tokio::spawn(bootstrap::ensure_doctor_installed());
|
||||
|
||||
// Dashboard-only updates can replace the NIP-07 provider without
|
||||
// recreating a running IndeedHub container. Reconcile its injected copy on
|
||||
// every daemon start so tab signing never remains pinned to an old asset.
|
||||
tokio::spawn(api::rpc::patch_indeedhub_nostr_provider());
|
||||
|
||||
// B17: heal already-deployed nodes whose archipelago.service lacks a mount
|
||||
// dependency on the data volume, so cold boots stop flapping. Boot-ordering
|
||||
// only — effective next reboot; never restarts the running service.
|
||||
|
||||
@@ -64,6 +64,7 @@ use rand::seq::SliceRandom;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::path::Path;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use tokio::fs;
|
||||
use tracing::{debug, info, warn};
|
||||
|
||||
@@ -73,6 +74,12 @@ use tracing::{debug, info, warn};
|
||||
// lasts longer than the UI's poll interval; serialise them so two polls cannot
|
||||
// consume the same claim and race each other's state file writes.
|
||||
static MINIBITS_STATE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
|
||||
// A Companion WebView, its external browser tab, and a desktop dashboard can
|
||||
// all watch the same address. Once one caller has completed the expensive
|
||||
// relay fetch, callers already queued behind it should return the durable
|
||||
// receipt immediately instead of each opening another relay subscription.
|
||||
static LAST_MINIBITS_POLL_COMPLETED_AT: AtomicU64 = AtomicU64::new(0);
|
||||
const MINIBITS_POLL_COALESCE_SECS: u64 = 2;
|
||||
|
||||
/// Minibits profile/LNURL API. Confirmed live: `/v3/auth/challenge`,
|
||||
/// `/v3/profile`, `/v3/claim` (the older `/v2` host no longer serves profiles).
|
||||
@@ -166,6 +173,16 @@ pub struct MinibitsState {
|
||||
/// We query the boundary second inclusively and deduplicate by event id.
|
||||
#[serde(default)]
|
||||
pub seen_dm_ids: Vec<String>,
|
||||
/// Monotonic id for the latest successfully redeemed claim batch. Claim
|
||||
/// polling may come from several browser/Companion contexts; keeping the
|
||||
/// latest receipt here lets every caller observe the result instead of
|
||||
/// only whichever request happened to acquire the claim lock first.
|
||||
#[serde(default)]
|
||||
pub last_receipt_id: u64,
|
||||
#[serde(default)]
|
||||
pub last_receipt_sats: u64,
|
||||
#[serde(default)]
|
||||
pub last_receipt_at: u64,
|
||||
}
|
||||
|
||||
/// A retryable encrypted token and the server key that encrypted it. The
|
||||
@@ -611,6 +628,9 @@ async fn register_new_state(
|
||||
pending_claims: Vec::new(),
|
||||
last_dm_seen_at: 0,
|
||||
seen_dm_ids: Vec::new(),
|
||||
last_receipt_id: 0,
|
||||
last_receipt_sats: 0,
|
||||
last_receipt_at: 0,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -625,14 +645,38 @@ pub struct ClaimOutcome {
|
||||
/// dropped. Non-zero here means real, unswept value the operator should
|
||||
/// know about.
|
||||
pub failed_count: usize,
|
||||
/// Most recent successful receipt, including one redeemed by another
|
||||
/// concurrent UI poll. Zero means this wallet has no recorded receipt.
|
||||
pub receipt_id: u64,
|
||||
pub receipt_sats: u64,
|
||||
pub receipt_at: u64,
|
||||
}
|
||||
|
||||
const NO_CLAIMS: ClaimOutcome = ClaimOutcome {
|
||||
claimed_count: 0,
|
||||
received_sats: 0,
|
||||
failed_count: 0,
|
||||
receipt_id: 0,
|
||||
receipt_sats: 0,
|
||||
receipt_at: 0,
|
||||
};
|
||||
|
||||
fn outcome_with_latest_receipt(
|
||||
state: &MinibitsState,
|
||||
claimed_count: usize,
|
||||
received_sats: u64,
|
||||
failed_count: usize,
|
||||
) -> ClaimOutcome {
|
||||
ClaimOutcome {
|
||||
claimed_count,
|
||||
received_sats,
|
||||
failed_count,
|
||||
receipt_id: state.last_receipt_id,
|
||||
receipt_sats: state.last_receipt_sats,
|
||||
receipt_at: state.last_receipt_at,
|
||||
}
|
||||
}
|
||||
|
||||
/// Make sure the Minibits mint is on the accepted-mints allow-list.
|
||||
///
|
||||
/// `ecash::receive_token` checks the raw accepted-mints file directly (not
|
||||
@@ -667,7 +711,7 @@ async fn fetch_relay_dms(
|
||||
client.connect().await;
|
||||
// Give relays a moment to finish the WebSocket handshake before the
|
||||
// fetch's own timeout starts consuming that time.
|
||||
tokio::time::sleep(std::time::Duration::from_millis(800)).await;
|
||||
tokio::time::sleep(std::time::Duration::from_millis(400)).await;
|
||||
|
||||
// Nostr timestamps have one-second resolution. Query the boundary second
|
||||
// inclusively: a later-published payment may legitimately share that
|
||||
@@ -680,7 +724,7 @@ async fn fetch_relay_dms(
|
||||
.limit(200);
|
||||
|
||||
let result = match client
|
||||
.fetch_events(filter, std::time::Duration::from_secs(10))
|
||||
.fetch_events(filter, std::time::Duration::from_secs(5))
|
||||
.await
|
||||
{
|
||||
Ok(events) => {
|
||||
@@ -782,6 +826,21 @@ pub async fn claim_and_redeem(data_dir: &Path) -> Result<ClaimOutcome> {
|
||||
// means a payment could not have arrived, so claiming is a no-op.
|
||||
None => return Ok(NO_CLAIMS),
|
||||
};
|
||||
|
||||
// The global lock serialises claim redemption, but without this fast path
|
||||
// every browser waiting on that lock performed its own five-to-ten-second
|
||||
// relay fetch in turn. Reuse the just-completed durable result for the
|
||||
// short coalescing window; a later UI poll performs the next real fetch.
|
||||
let now = chrono::Utc::now().timestamp().max(0) as u64;
|
||||
let last_completed = LAST_MINIBITS_POLL_COMPLETED_AT.load(Ordering::Acquire);
|
||||
if last_completed > 0 && now.saturating_sub(last_completed) <= MINIBITS_POLL_COALESCE_SECS {
|
||||
return Ok(outcome_with_latest_receipt(
|
||||
&state,
|
||||
0,
|
||||
0,
|
||||
state.pending_claims.len(),
|
||||
));
|
||||
}
|
||||
ensure_token(&client, &mut state, &identity.keys).await?;
|
||||
|
||||
// Refresh the service key that authors and encrypts claim DMs. Keeping the
|
||||
@@ -864,7 +923,11 @@ pub async fn claim_and_redeem(data_dir: &Path) -> Result<ClaimOutcome> {
|
||||
save_state(data_dir, &state).await?;
|
||||
|
||||
if state.pending_claims.is_empty() {
|
||||
return Ok(NO_CLAIMS);
|
||||
LAST_MINIBITS_POLL_COMPLETED_AT.store(
|
||||
chrono::Utc::now().timestamp().max(0) as u64,
|
||||
Ordering::Release,
|
||||
);
|
||||
return Ok(outcome_with_latest_receipt(&state, 0, 0, 0));
|
||||
}
|
||||
|
||||
let to_process = std::mem::take(&mut state.pending_claims);
|
||||
@@ -910,13 +973,23 @@ pub async fn claim_and_redeem(data_dir: &Path) -> Result<ClaimOutcome> {
|
||||
|
||||
let failed_count = still_pending.len();
|
||||
state.pending_claims = still_pending;
|
||||
if sats > 0 {
|
||||
state.last_receipt_id = state.last_receipt_id.saturating_add(1).max(1);
|
||||
state.last_receipt_sats = sats;
|
||||
state.last_receipt_at = chrono::Utc::now().timestamp().max(0) as u64;
|
||||
}
|
||||
save_state(data_dir, &state).await?;
|
||||
LAST_MINIBITS_POLL_COMPLETED_AT.store(
|
||||
chrono::Utc::now().timestamp().max(0) as u64,
|
||||
Ordering::Release,
|
||||
);
|
||||
|
||||
Ok(ClaimOutcome {
|
||||
claimed_count: redeemed,
|
||||
received_sats: sats,
|
||||
Ok(outcome_with_latest_receipt(
|
||||
&state,
|
||||
redeemed,
|
||||
sats,
|
||||
failed_count,
|
||||
})
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1117,6 +1190,24 @@ mod tests {
|
||||
state.pending_claims[0].sender_pubkey("cached-server-key"),
|
||||
"cached-server-key"
|
||||
);
|
||||
assert_eq!(state.last_receipt_id, 0);
|
||||
assert_eq!(state.last_receipt_sats, 0);
|
||||
assert_eq!(state.last_receipt_at, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn latest_receipt_survives_a_zero_claim_poll() {
|
||||
let state = MinibitsState {
|
||||
last_receipt_id: 9,
|
||||
last_receipt_sats: 1_000,
|
||||
last_receipt_at: 1_789_000_000,
|
||||
..Default::default()
|
||||
};
|
||||
let outcome = outcome_with_latest_receipt(&state, 0, 0, 0);
|
||||
assert_eq!(outcome.received_sats, 0);
|
||||
assert_eq!(outcome.receipt_id, 9);
|
||||
assert_eq!(outcome.receipt_sats, 1_000);
|
||||
assert_eq!(outcome.receipt_at, 1_789_000_000);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
Reference in New Issue
Block a user