Skip to content

Commit e80e4d7

Browse files
wpfleger96Hayt
andcommitted
Pick Builderlab's sign-in by what the server offers and keep the browser sign-in
The built-in server probes v1/session at each Builderlab sign-in: 404 uses the browser sign-in, saved in the OS keychain; anything else uses the native NIP-FI session, which the plugin prefers whenever one exists. Servers the build adds stay NIP-FI only. Communities require NIP-FI by requires_nip_fi, falling back to limitation.federated_identity. Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
1 parent 5af191f commit e80e4d7

25 files changed

Lines changed: 796 additions & 98 deletions

‎crates/plugin-manager/build.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,16 @@ fn main() {
131131
println!("cargo:rerun-if-env-changed={FI}");
132132
println!("cargo:rerun-if-env-changed={DEV_VIEWER}");
133133
let fi = federated_identity(&local, process);
134+
// Whether that server is one the build adds (so Builderlab is NIP-FI
135+
// only) rather than the built-in one (so its plugin can use either).
136+
println!(
137+
"cargo:rustc-env=BUZZ_BUILD_FEDERATED_IDENTITY_ADDED={}",
138+
if process(FI).is_some_and(|raw| !raw.is_empty()) {
139+
"1"
140+
} else {
141+
""
142+
}
143+
);
134144
println!(
135145
"cargo:rustc-env={FI}={}",
136146
fi.as_ref()

‎crates/plugin-manager/src/lib.rs‎

Lines changed: 30 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -375,22 +375,26 @@ pub fn bundled_manifests() -> Vec<Manifest> {
375375
.expect("builderlab manifest");
376376
let origin = BUILDERLAB_ORIGIN;
377377
let descriptor = env!("BUZZ_BUILD_FEDERATED_IDENTITY_CONFIG");
378+
// The browser sign-in's renderer network origins.
379+
let network = || HostGrants {
380+
files: apps_control_plane(origin).is_some(),
381+
network_origins: if origin.is_empty() {
382+
vec![]
383+
} else {
384+
std::iter::once(origin)
385+
.chain(apps_control_plane(origin))
386+
.map(Into::into)
387+
.collect()
388+
},
389+
..HostGrants::default()
390+
};
378391
builderlab.host = Some(if descriptor.is_empty() {
379-
HostGrants {
380-
files: apps_control_plane(origin).is_some(),
381-
network_origins: if origin.is_empty() {
382-
vec![]
383-
} else {
384-
std::iter::once(origin)
385-
.chain(apps_control_plane(origin))
386-
.map(Into::into)
387-
.collect()
388-
},
389-
..HostGrants::default()
390-
}
392+
network()
391393
} else {
392-
// An FI build reaches Builderlab only through the native session
393-
// forwarder: no renderer network or file access.
394+
// The native session forwarder. A server the build adds is reached
395+
// only through it: no renderer network or file access. The built-in
396+
// server may not offer NIP-FI sign-in, so the browser sign-in keeps
397+
// its origins beside it.
394398
let config: serde_json::Value =
395399
serde_json::from_str(descriptor).expect("validated FI descriptor");
396400
let base = config["apiBasePath"].as_str().expect("API base");
@@ -409,7 +413,11 @@ pub fn bundled_manifests() -> Vec<Manifest> {
409413
})
410414
.collect(),
411415
}),
412-
..HostGrants::default()
416+
..if env!("BUZZ_BUILD_FEDERATED_IDENTITY_ADDED").is_empty() {
417+
network()
418+
} else {
419+
HostGrants::default()
420+
}
413421
}
414422
});
415423
vec![
@@ -2347,9 +2355,13 @@ mod tests {
23472355
);
23482356
assert_eq!(grants.federated_identity, None);
23492357
} else {
2350-
// An FI build grants only the native session's Builderlab routes.
2351-
assert!(!grants.files);
2352-
assert!(grants.network_origins.is_empty());
2358+
// A build that adds a server grants only the native session's
2359+
// Builderlab routes; the built-in one keeps the browser origins.
2360+
let network = !env!("BUZZ_BUILD_FEDERATED_IDENTITY_ADDED").is_empty();
2361+
assert_eq!(grants.network_origins.is_empty(), network);
2362+
if network {
2363+
assert!(!grants.files);
2364+
}
23532365
let grant = grants.federated_identity.clone().unwrap();
23542366
let base = super::BUILDERLAB_API_BASE_PATH;
23552367
let operations: Vec<_> = grant

‎docs/configuration.md‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,11 @@ BUZZ_BUILDERLAB_URL=https://app.builderlab.xyz bin/pnpm tauri build
9595

9696
Builderlab is the build's first sign-in server below: its identity origin with
9797
`apiBasePath` less its `/api/goose/` suffix (another API base leaves Builderlab
98-
unconfigured), and sign-in uses that server's native session, which is kept in
99-
the system keyring and survives a restart. Unset or set to
98+
unconfigured). A server the build adds signs in with its native session. The
99+
built-in server signs in with its native session only when its
100+
`v1/session` answers anything but 404, and otherwise with the browser sign-in
101+
(`/v1/auth/login`); both are kept in the system keyring and survive a restart
102+
(see [identity](identity.md)). Unset or set to
100103
`https://app.builderlab.xyz`, `BUZZ_BUILDERLAB_URL` keeps the built-in server.
101104
Another origin, or an empty value, turns it off when nothing is added, and the
102105
bundled Builderlab plugin keeps its own in-memory login against this origin.

‎docs/identity.md‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,21 @@ wireframes. When a page replaces another, focus moves to the new page's
1616
heading unless the page focuses a field itself, and **Back** returns focus to
1717
the choice that opened the page.
1818

19-
In builds with a sign-in server, which is every build unless it opts out or
20-
names another Builderlab deployment (see
21-
[configuration](configuration.md#federated-identity-build-input)), the
22-
bundled Builderlab plugin has no network grant of its own: its Builderlab calls
23-
go through the native FI session (#1461). There, **Sign in with Builderlab** is the
24-
native [organization sign-in](#native-federated-session-module), whose browser
19+
With only the built-in sign-in server (see
20+
[configuration](configuration.md#federated-identity-build-input)), each
21+
Builderlab sign-in first sends an uncredentialed `GET {adapterBase}/v1/session`.
22+
A 404 means the server has no NIP-FI sign-in, so **Sign in with Builderlab** is
23+
the browser sign-in above, whose credential the plugin keeps in the system
24+
keychain across restarts (deleted on sign-out or when Builderlab rejects it at
25+
launch). Any other answer means NIP-FI sign-in, as below; a network error or
26+
5xx shows the retryable sign-in error and never falls back to the browser. The
27+
plugin uses the server's native session whenever one exists, such as after a
28+
community that requires NIP-FI asked for sign-in, and the browser credential
29+
otherwise, so it holds both grants.
30+
31+
In builds that add a sign-in server, the bundled Builderlab plugin has no
32+
network grant of its own: its Builderlab calls go through the native FI session
33+
(#1461). There, **Sign in with Builderlab** is always the native [organization sign-in](#native-federated-session-module), whose browser
2534
step, code exchange and token stay native. A session that already exists,
2635
including one saved by an earlier run, signs in again, so the browser can
2736
choose the account; if that sign-in is canceled, first run stops rather than
@@ -872,8 +881,12 @@ The app's `federatedIdentity` service exposes this public state to the shared
872881
sign-in UI. Session record revision survives restore and scopes account caches
873882
without inventing a NIP-FA subject.
874883

875-
NIP-11 discovery from the exact relay carries no FI credential. Valid absent or
876-
false FI flags retain ordinary Nostr transport. A true flag requires the supported
884+
NIP-11 discovery from the exact relay carries no FI credential. The community
885+
requires NIP-FI when its top-level `requires_nip_fi` is true; when that flag is
886+
absent, `limitation.federated_identity` decides, as before it existed. A false
887+
`requires_nip_fi` means not required even where the host supports NIP-FI (as a
888+
shadow-mode host advertises), and a non-boolean one is invalid discovery. Not
889+
required retains ordinary Nostr transport. Required needs the supported
877890
client-attached/offline-jwt descriptor and compiled authority mapping. Assertions
878891
are acquired with native same-key NIP-98 proof and checked for exact audience,
879892
key, and lifetime. Native HTTP, media, repository Git reads/imports, and socket

‎src-tauri/build.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,9 @@ fn main() {
210210
"jev_classifier_status",
211211
"jev_classifier_set_key",
212212
"jev_classifier_clear_key",
213+
"builderlab_session_load",
214+
"builderlab_session_save",
215+
"builderlab_session_clear",
213216
"app_agent_state_load",
214217
"app_agent_state_set",
215218
"decide",

‎src-tauri/src/browser_permissions_tests.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,9 @@ fn native_command_permissions_isolate_webviews() {
194194
"jev_classifier_status",
195195
"jev_classifier_set_key",
196196
"jev_classifier_clear_key",
197+
"builderlab_session_load",
198+
"builderlab_session_save",
199+
"builderlab_session_clear",
197200
"app_agent_state_load",
198201
"app_agent_state_set",
199202
"decide",
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
//! The saved Builderlab browser sign-in credential of a build whose
2+
//! Builderlab plugin does not use NIP-FI, so that sign-in survives restarts.
3+
//! It is one OS secure item of its own per profile, never another item.
4+
use zeroize::Zeroizing;
5+
6+
#[cfg_attr(test, allow(dead_code))]
7+
const SERVICE: &str = if cfg!(debug_assertions) {
8+
"xyz.block.buzz.desktop.builderlab-session.debug"
9+
} else {
10+
"xyz.block.buzz.desktop.builderlab-session"
11+
};
12+
const LIMIT: usize = 4096;
13+
14+
#[cfg_attr(test, allow(dead_code))]
15+
fn account() -> String {
16+
std::env::var("BUZZODZ_PROFILE").unwrap_or_else(|_| "default".into())
17+
}
18+
19+
#[cfg(all(
20+
any(target_os = "macos", target_os = "windows", target_os = "linux"),
21+
not(test)
22+
))]
23+
mod platform {
24+
use super::*;
25+
use buzz_credential_store::{self as credentials, Error};
26+
fn error(error: Error) -> String {
27+
match error {
28+
Error::Denied => "Secure storage access was denied",
29+
Error::Busy => "Another Buzz app is using secure storage",
30+
_ => "Secure storage is unavailable",
31+
}
32+
.into()
33+
}
34+
pub(super) fn read() -> Result<Option<Zeroizing<Vec<u8>>>, String> {
35+
match credentials::read(SERVICE, &account()) {
36+
Ok(value) => Ok(Some(value)),
37+
Err(Error::Absent) => Ok(None),
38+
Err(e) => Err(error(e)),
39+
}
40+
}
41+
pub(super) fn replace(value: &[u8]) -> Result<(), String> {
42+
#[cfg(target_os = "macos")]
43+
return security_framework::os::macos::keychain::SecKeychain::default()
44+
.and_then(|keychain| keychain.set_generic_password(SERVICE, &account(), value))
45+
.map_err(|_| "Secure storage is unavailable".to_string());
46+
#[cfg(not(target_os = "macos"))]
47+
credentials::replace(SERVICE, &account(), value).map_err(error)
48+
}
49+
pub(super) fn delete() -> Result<(), String> {
50+
match credentials::delete(SERVICE, &account()) {
51+
Ok(()) | Err(Error::Absent) => Ok(()),
52+
Err(e) => Err(error(e)),
53+
}
54+
}
55+
}
56+
57+
// Native tests and other platforms never touch an OS credential store.
58+
#[cfg(any(
59+
not(any(target_os = "macos", target_os = "windows", target_os = "linux")),
60+
test
61+
))]
62+
mod platform {
63+
use super::*;
64+
const NONE: &str = "Secure storage is not available here";
65+
pub(super) fn read() -> Result<Option<Zeroizing<Vec<u8>>>, String> {
66+
Err(NONE.into())
67+
}
68+
pub(super) fn replace(_: &[u8]) -> Result<(), String> {
69+
Err(NONE.into())
70+
}
71+
pub(super) fn delete() -> Result<(), String> {
72+
Err(NONE.into())
73+
}
74+
}
75+
76+
async fn blocking<T: Send + 'static>(
77+
run: impl FnOnce() -> Result<T, String> + Send + 'static,
78+
) -> Result<T, String> {
79+
tokio::task::spawn_blocking(run)
80+
.await
81+
.map_err(|_| "Secure storage is unavailable".to_string())?
82+
}
83+
84+
/// The saved credential record, or `None` when there is none.
85+
#[tauri::command]
86+
pub(crate) async fn builderlab_session_load() -> Result<Option<String>, String> {
87+
let value = blocking(platform::read).await?;
88+
value
89+
.map(|bytes| {
90+
String::from_utf8(bytes.to_vec()).map_err(|_| "The saved sign-in is damaged".into())
91+
})
92+
.transpose()
93+
}
94+
95+
#[tauri::command]
96+
pub(crate) async fn builderlab_session_save(value: String) -> Result<(), String> {
97+
let value = Zeroizing::new(value);
98+
if value.is_empty() || value.len() > LIMIT {
99+
return Err("Invalid Builderlab sign-in".into());
100+
}
101+
blocking(move || platform::replace(value.as_bytes())).await
102+
}
103+
104+
#[tauri::command]
105+
pub(crate) async fn builderlab_session_clear() -> Result<(), String> {
106+
blocking(platform::delete).await
107+
}

‎src-tauri/src/federated_identity/assertion.rs‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,14 +193,22 @@ fn evaluate_discovery(document: &serde_json::Value) -> Result<bool, &'static str
193193
if !document.is_object() {
194194
return Err("Invalid federated community discovery");
195195
}
196-
let requires = match document.get("limitation") {
196+
let supports = match document.get("limitation") {
197197
Some(value) if !value.is_object() => return Err("Invalid federated community discovery"),
198198
value => match value.and_then(|v| v.get("federated_identity")) {
199199
None | Some(serde_json::Value::Bool(false)) => false,
200200
Some(serde_json::Value::Bool(true)) => true,
201201
_ => return Err("Invalid federated community discovery"),
202202
},
203203
};
204+
// `limitation.federated_identity` says a host supports NIP-FI, as a
205+
// shadow-mode host does too; `requires_nip_fi` says this community
206+
// requires it. A relay without the flag requires what it supports.
207+
let requires = match document.get("requires_nip_fi") {
208+
None => supports,
209+
Some(serde_json::Value::Bool(requires)) => *requires,
210+
Some(_) => return Err("Invalid federated community discovery"),
211+
};
204212
if !requires {
205213
return Ok(false);
206214
}
@@ -1133,6 +1141,31 @@ mod tests {
11331141
assert!(evaluate_discovery(&doc).is_err());
11341142
}
11351143
}
1144+
#[test]
1145+
fn requires_nip_fi_decides_when_present_and_capability_otherwise() {
1146+
let supported = serde_json::json!({"limitation":{"federated_identity":true},"federated_identity":{"core":"client-attached","assertion_freshness":{"class":"offline-jwt"}}});
1147+
let with = |flag: serde_json::Value| {
1148+
let mut doc = supported.clone();
1149+
doc["requires_nip_fi"] = flag;
1150+
doc
1151+
};
1152+
// Required: the descriptor checks still apply.
1153+
assert!(evaluate_discovery(&with(serde_json::json!(true))).unwrap());
1154+
let mut bare = with(serde_json::json!(true));
1155+
bare.as_object_mut().unwrap().remove("federated_identity");
1156+
assert!(evaluate_discovery(&bare).is_err());
1157+
// Supported but not required, as a shadow-mode host says.
1158+
assert!(!evaluate_discovery(&with(serde_json::json!(false))).unwrap());
1159+
// Absent: the capability decides, as before the flag.
1160+
assert!(evaluate_discovery(&supported).unwrap());
1161+
for flag in [
1162+
serde_json::json!("true"),
1163+
serde_json::json!(1),
1164+
serde_json::Value::Null,
1165+
] {
1166+
assert!(evaluate_discovery(&with(flag)).is_err());
1167+
}
1168+
}
11361169
#[tokio::test]
11371170
async fn a_community_is_authorized_by_the_server_its_host_routes_to() {
11381171
use super::super::{config::Config, tests::Memory};

‎src-tauri/src/host_request.rs‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -911,15 +911,24 @@ mod tests {
911911
let manager =
912912
buzzodz_plugins::Manager::open(Some(temp.path().into()), "test", false).unwrap();
913913
let grants = manager.host_grants("block.builderlab", "bundled").unwrap();
914-
if option_env!("BUZZ_BUILD_FEDERATED_IDENTITY_CONFIG").is_some_and(|c| !c.is_empty()) {
915-
// FI builds reach Builderlab only through the native forwarder.
914+
// A server the build adds joins the built-in one at the list's end.
915+
let added = option_env!("BUZZ_BUILD_FEDERATED_IDENTITY_CONFIG")
916+
.and_then(|c| serde_json::from_str::<Vec<serde_json::Value>>(c).ok())
917+
.is_some_and(|servers| servers.len() > 1);
918+
if added {
919+
// Builds that add a server reach Builderlab only through the
920+
// native forwarder.
916921
assert!(grants
917922
.federated_identity
918923
.is_some_and(|grant| !grant.operations.is_empty()));
919924
assert!(!grants.files && grants.network_origins.is_empty());
920925
return;
921926
}
922-
assert!(grants.federated_identity.is_none());
927+
// The built-in server keeps the forwarder beside the browser origins.
928+
assert_eq!(
929+
grants.federated_identity.is_some(),
930+
option_env!("BUZZ_BUILD_FEDERATED_IDENTITY_CONFIG").is_some_and(|c| !c.is_empty())
931+
);
923932
assert_eq!(
924933
grants.files,
925934
buzzodz_plugins::apps_control_plane(buzzodz_plugins::BUILDERLAB_ORIGIN).is_some()

‎src-tauri/src/lib.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ use nsec_backup::{
5252
nsec_restore_wait, NsecBackupHost,
5353
};
5454
use nsec_backup_choice::{nsec_backup_choice, nsec_backup_set_choice};
55+
mod builderlab_session;
5556
mod clipboard;
5657
mod jev;
5758
mod keep_awake;
@@ -775,6 +776,9 @@ fn commands<R: tauri::Runtime>() -> impl Fn(tauri::ipc::Invoke<R>) -> bool + Sen
775776
jev::jev_classifier_status,
776777
jev::jev_classifier_set_key,
777778
jev::jev_classifier_clear_key,
779+
builderlab_session::builderlab_session_load,
780+
builderlab_session::builderlab_session_save,
781+
builderlab_session::builderlab_session_clear,
778782
agent_state::app_agent_state_load,
779783
agent_state::app_agent_state_set,
780784
decisions::decide,

0 commit comments

Comments
 (0)