Skip to content

Commit 2cfe7e6

Browse files
wpfleger96Hayt
andcommitted
Scope, order and surface the saved Builderlab sign-in; NIP-FI ownership wins
Key the keychain item by profile and compiled Builderlab deployment and check the caller's target; grant its commands to the main window. Order and await saves and deletes, with retryable errors. Let Cancel end the v1/session check. Choose NIP-FI by session ownership and retire the browser sign-in on takeover. Turn Apps tools off on NIP-FI. Tell a failed restore from a failed sign-out in Settings. Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
1 parent 2847bf6 commit 2cfe7e6

22 files changed

Lines changed: 500 additions & 89 deletions

‎docs/configuration.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -97,8 +97,9 @@ 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
9898
unconfigured). A server the build adds signs in with its native session. The
9999
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
100+
`v1/session` answers with a status other than 404, and on a 404 with the browser
101+
sign-in (`/v1/auth/login`); a network error or 5xx is a retryable error, never
102+
the browser sign-in. Both are kept in the system keyring and survive a restart
102103
(see [identity](identity.md)). Unset or set to
103104
`https://app.builderlab.xyz`, `BUZZ_BUILDERLAB_URL` keeps the built-in server.
104105
Another origin, or an empty value, turns it off when nothing is added, and the

‎docs/identity.md‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,8 +22,14 @@ Builderlab sign-in first sends an uncredentialed `GET {adapterBase}/v1/session`.
2222
A 404 means the server has no NIP-FI sign-in, so **Sign in with Builderlab** is
2323
the browser sign-in above. First run saves its credential in the same system
2424
keychain item the plugin restores, so the plugin is signed in at once and after
25-
a restart (deleted on sign-out or when Builderlab rejects it at launch).
26-
Builderlab Decisions is offered only while that browser sign-in is in use;
25+
a restart (deleted on sign-out or when Builderlab rejects it at launch). The
26+
item is the profile's for this build's Builderlab deployment, its origin and
27+
API base, so a build for another Builderlab never reads, sends or deletes it.
28+
A save that fails is a retryable sign-in error, and a sign-out stays unfinished
29+
until the item is deleted. Once a NIP-FI session exists it is the sign-in in
30+
use, even while its account is loading or failing, and the browser sign-in is
31+
signed out, revoked and deleted. Builderlab Decisions and the Apps agent tools
32+
are offered only while that browser sign-in is in use;
2733
native sends no NIP-FI session to it, as in builds that add a server. Any other answer means NIP-FI sign-in, as below; a network error or
2834
5xx shows the retryable sign-in error and never falls back to the browser. The
2935
plugin uses the server's native session whenever one exists, such as after a

‎src-tauri/capabilities/default.json‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,9 @@
156156
"allow-jev-classifier-status",
157157
"allow-jev-classifier-set-key",
158158
"allow-jev-classifier-clear-key",
159+
"allow-builderlab-session-load",
160+
"allow-builderlab-session-save",
161+
"allow-builderlab-session-clear",
159162
"allow-app-agent-state-load",
160163
"allow-app-agent-state-set",
161164
"allow-decide",

‎src-tauri/src/builderlab_session.rs‎

Lines changed: 73 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
//! The saved Builderlab browser sign-in credential of a build whose
22
//! 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.
3+
//! It is one OS secure item of its own per profile and compiled Builderlab
4+
//! deployment, never another item, and only that deployment's caller uses it.
45
use zeroize::Zeroizing;
56

67
#[cfg_attr(test, allow(dead_code))]
@@ -11,9 +12,36 @@ const SERVICE: &str = if cfg!(debug_assertions) {
1112
};
1213
const LIMIT: usize = 4096;
1314

15+
/// The item's account: the profile and the deployment's API base, so a build
16+
/// for another Builderlab never reads, sends or deletes this one's credential.
17+
fn account_for(profile: &str, origin: &str, api_base_path: &str) -> String {
18+
format!("{profile} {origin}{api_base_path}")
19+
}
20+
1421
#[cfg_attr(test, allow(dead_code))]
1522
fn account() -> String {
16-
std::env::var("BUZZODZ_PROFILE").unwrap_or_else(|_| "default".into())
23+
let profile = std::env::var("BUZZODZ_PROFILE").unwrap_or_else(|_| "default".into());
24+
account_for(
25+
&profile,
26+
buzzodz_plugins::BUILDERLAB_ORIGIN,
27+
buzzodz_plugins::BUILDERLAB_API_BASE_PATH,
28+
)
29+
}
30+
31+
/// The caller's sign-in target (`oauthTarget`) must be this build's.
32+
fn bound(target: &str, origin: &str, api_base_path: &str) -> Result<(), String> {
33+
if origin.is_empty() || target != format!("{origin}{}", api_base_path.trim_end_matches('/')) {
34+
return Err("This saved sign-in belongs to another Builderlab".into());
35+
}
36+
Ok(())
37+
}
38+
39+
fn this_build(target: &str) -> Result<(), String> {
40+
bound(
41+
target,
42+
buzzodz_plugins::BUILDERLAB_ORIGIN,
43+
buzzodz_plugins::BUILDERLAB_API_BASE_PATH,
44+
)
1745
}
1846

1947
#[cfg(all(
@@ -83,7 +111,8 @@ async fn blocking<T: Send + 'static>(
83111

84112
/// The saved credential record, or `None` when there is none.
85113
#[tauri::command]
86-
pub(crate) async fn builderlab_session_load() -> Result<Option<String>, String> {
114+
pub(crate) async fn builderlab_session_load(target: String) -> Result<Option<String>, String> {
115+
this_build(&target)?;
87116
let value = blocking(platform::read).await?;
88117
value
89118
.map(|bytes| {
@@ -93,7 +122,8 @@ pub(crate) async fn builderlab_session_load() -> Result<Option<String>, String>
93122
}
94123

95124
#[tauri::command]
96-
pub(crate) async fn builderlab_session_save(value: String) -> Result<(), String> {
125+
pub(crate) async fn builderlab_session_save(target: String, value: String) -> Result<(), String> {
126+
this_build(&target)?;
97127
let value = Zeroizing::new(value);
98128
if value.is_empty() || value.len() > LIMIT {
99129
return Err("Invalid Builderlab sign-in".into());
@@ -102,6 +132,44 @@ pub(crate) async fn builderlab_session_save(value: String) -> Result<(), String>
102132
}
103133

104134
#[tauri::command]
105-
pub(crate) async fn builderlab_session_clear() -> Result<(), String> {
135+
pub(crate) async fn builderlab_session_clear(target: String) -> Result<(), String> {
136+
this_build(&target)?;
106137
blocking(platform::delete).await
107138
}
139+
140+
#[cfg(test)]
141+
mod tests {
142+
use super::*;
143+
144+
#[test]
145+
fn each_builderlab_deployment_has_its_own_item_and_callers() {
146+
let public = account_for("default", "https://app.builderlab.xyz", "/api/goose/");
147+
assert_ne!(
148+
public,
149+
account_for("default", "https://builderlab.example", "/api/goose/")
150+
);
151+
assert_ne!(
152+
public,
153+
account_for("default", "https://app.builderlab.xyz", "/team/api/goose/")
154+
);
155+
assert_ne!(
156+
public,
157+
account_for("work", "https://app.builderlab.xyz", "/api/goose/")
158+
);
159+
let origin = "https://app.builderlab.xyz";
160+
assert!(bound(
161+
"https://app.builderlab.xyz/api/goose",
162+
origin,
163+
"/api/goose/"
164+
)
165+
.is_ok());
166+
for other in [
167+
"https://builderlab.example/api/goose",
168+
"https://app.builderlab.xyz/team/api/goose",
169+
"",
170+
] {
171+
assert!(bound(other, origin, "/api/goose/").is_err(), "{other}");
172+
}
173+
assert!(bound("/api/goose", "", "").is_err());
174+
}
175+
}

‎src/app/IdentitySettings.test.tsx‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -517,3 +517,41 @@ it("restores an unfinished per-server sign-out's Try again when Settings opens a
517517
expect(pub.service.signOut).toHaveBeenCalledTimes(2);
518518
expect(screen.queryByRole("alert")).toBeNull();
519519
});
520+
521+
it("shows a failed cold-start restore as a restore whose Try again restores, never signing out", async () => {
522+
const { block, pub, root, servers } = twoServers();
523+
block.publish({ status: "signed-in", email: "[email protected]" });
524+
// Offline at launch: the restore read failed, and nothing signed out.
525+
pub.publish({ status: "unavailable", failure: "network-unavailable" });
526+
render(
527+
<IdentitySettings
528+
viewer={viewer}
529+
federatedIdentity={root}
530+
memberships={memberships}
531+
servers={servers}
532+
/>,
533+
{ wrapper: ToastProvider },
534+
);
535+
const alert = await screen.findByRole("alert");
536+
expect(alert).toHaveTextContent(
537+
"Couldn’t restore your sign-in to app.builderlab.xyz.",
538+
);
539+
expect(alert).not.toHaveTextContent("sign out");
540+
vi.mocked(
541+
pub.service.restore as NonNullable<typeof pub.service.restore>,
542+
).mockImplementation(async () => {
543+
pub.publish({ status: "signed-in", email: "[email protected]" });
544+
return pub.service.snapshot();
545+
});
546+
await userEvent
547+
.setup()
548+
.click(screen.getByRole("button", { name: "Try again" }));
549+
expect(pub.service.restore).toHaveBeenCalledTimes(1);
550+
expect(pub.service.signOut).not.toHaveBeenCalled();
551+
expect(screen.queryByRole("alert")).toBeNull();
552+
expect(
553+
await screen.findByRole("button", {
554+
name: "Sign out of app.builderlab.xyz",
555+
}),
556+
).toBeVisible();
557+
});

‎src/app/IdentitySettings.tsx‎

Lines changed: 45 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,12 @@ const WAITING = {
4040
not_linked: BACKUP_FAILURES.not_linked.message,
4141
} as const;
4242

43-
/** Unavailable for want of native, not because a sign-out didn't finish. */
43+
/** Unavailable for want of native, not because an operation failed. */
4444
const NOT_SIGN_OUT = new Set(["native-unavailable", "desktop-required"]);
45+
/** Servers whose sign-out this app started and native has not finished.
46+
* Any other unavailable server failed to restore, such as offline at launch;
47+
* native finishes an earlier run's sign-out as it restores. */
48+
const signingOut = new Set<string>();
4549

4650
/** One sentence per uploader status; failures read as first run's copy. */
4751
function backupSentence(status: BackupStatus) {
@@ -292,45 +296,69 @@ function OrganizationSignIns({
292296
const authority = session.snapshot().authority;
293297
if (!authority) return;
294298
report(session);
295-
void session.signOut().catch((error: unknown) =>
296-
report(session, {
297-
authority,
298-
failure: error instanceof Error ? error.message : "",
299-
}),
300-
);
299+
signingOut.add(authority.id);
300+
void session
301+
.signOut()
302+
.then(() => {
303+
if (session.snapshot().status !== "unavailable")
304+
signingOut.delete(authority.id);
305+
})
306+
.catch((error: unknown) =>
307+
report(session, {
308+
authority,
309+
failure: error instanceof Error ? error.message : "",
310+
}),
311+
);
301312
};
302313
const signedIn = sessions.filter(
303314
(_, index) =>
304315
states[index]?.status === "signed-in" && states[index]?.authority,
305316
);
306317
// Native reports a sign-out it couldn't finish, such as a storage failure,
307318
// as that server's unavailable snapshot rather than an error. Read from the
308-
// session, it survives Settings closing and a reload until cleanup ends.
319+
// session, it survives Settings closing until cleanup ends.
309320
const unfinished = new Map(failures);
321+
const unrestored = new Map<FederatedIdentity, SignOutFailure>();
310322
sessions.forEach((session, index) => {
311323
const state = states[index];
312324
if (
313325
state?.status === "unavailable" &&
314326
state.authority &&
315327
!NOT_SIGN_OUT.has(state.failure ?? "")
316328
)
317-
unfinished.set(session, {
318-
authority: state.authority,
319-
failure: state.failure ?? "",
320-
});
329+
(signingOut.has(state.authority.id) ? unfinished : unrestored).set(
330+
session,
331+
{ authority: state.authority, failure: state.failure ?? "" },
332+
);
321333
});
322-
const problems = [...unfinished].map(([session, { authority, failure }]) => (
334+
const problem = (
335+
{ authority, failure }: SignOutFailure,
336+
failed: string,
337+
retry: () => void,
338+
) => (
323339
<div key={authority.id}>
324340
<p role="alert" className="text-body-sm text-danger">
325-
{`Couldn’t sign out of ${serverName(authority)}. ${recoveryMessage(failure)}`}
341+
{`Couldn’t ${failed} ${serverName(authority)}. ${recoveryMessage(failure)}`}
326342
</p>
327-
<Button type="button" onClick={() => signOut(session)}>
343+
<Button type="button" onClick={retry}>
328344
Try again
329345
</Button>
330346
</div>
331-
));
347+
);
348+
const problems = [
349+
...[...unfinished].map(([session, failure]) =>
350+
problem(failure, "sign out of", () => signOut(session)),
351+
),
352+
...[...unrestored].map(([session, failure]) =>
353+
problem(
354+
failure,
355+
"restore your sign-in to",
356+
() => void session.restore?.().catch(() => {}),
357+
),
358+
),
359+
];
332360
// The first server's own row would repeat its failure without naming it.
333-
const firstFailed = [...unfinished.values()].some(
361+
const firstFailed = [...unfinished.values(), ...unrestored.values()].some(
334362
({ authority }) => authority.id === identity.snapshot().authority?.id,
335363
);
336364
if (signedIn.length === 0)

‎src/bundled/bestie/testing.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,7 @@ export async function bestieFixture(
102102
return { parameters: [["code", "one-time"]] };
103103
}
104104
if (command === "oauth_callback_cancel") return;
105+
if (command.startsWith("builderlab_session_")) return null;
105106
if (command === "identity_restore") return identity.pubkey;
106107
if (command === "identity_prepare_remote_agent_authorization")
107108
return ["auth", identity.pubkey, "", "ef".repeat(64)];

‎src/bundled/builderlab/README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -208,8 +208,9 @@ The plugin's server is the build's Builderlab: its first
208208
[sign-in server](../../../docs/configuration.md#federated-identity-build-input),
209209
the built-in `https://app.builderlab.xyz` unless the build adds another. An
210210
added server's native session is its only sign-in. The built-in server's is used
211-
when it exists or `v1/session` offers it (not 404); otherwise the plugin uses the
212-
browser sign-in below and keeps its credential in the system keychain. Both
211+
when it exists or `v1/session` offers it (any status but 404). On a 404 the
212+
plugin uses the browser sign-in below and keeps its credential in the system
213+
keychain; a network error or 5xx is a retryable error, never that fallback. Both
213214
survive a restart. A build without a sign-in server uses
214215
the `BUZZ_BUILDERLAB_URL` [build input](../../../docs/configuration.md#builderlab-url-build-input)
215216
as its server address, appends `/api/goose`, and keeps its sign-in in memory.

‎src/bundled/builderlab/apps/index.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,26 @@ it("adds the app tools only for a tenant with an Apps control plane", async () =
125125
);
126126
});
127127

128+
it("turns the tools off while the NIP-FI session is in use, never calling as the browser sign-in", async () => {
129+
const { ctx, respond, session: browser } = await setup();
130+
const tools = new Map<string, AddedTool>();
131+
ctx.agents.addTool = (tool: AddedTool) => tools.set(tool.name, tool);
132+
const federated = {
133+
...browser,
134+
snapshot: () => ({ ...browser.snapshot(), federated: true }),
135+
};
136+
applyApps(ctx as never, federated, true, browser);
137+
for (const name of ["apps_list", "apps_create"])
138+
await expect(
139+
(tools.get(name) as AddedTool).call(
140+
{} as BuzzClient,
141+
{},
142+
{ name: "demo" },
143+
),
144+
).rejects.toThrow("not available with your organization sign-in");
145+
expect(respond).not.toHaveBeenCalled();
146+
});
147+
128148
it("returns once the deployed version serves", async () => {
129149
vi.useFakeTimers();
130150
const { call, responses, respond } = await setup();

‎src/bundled/builderlab/apps/index.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,15 @@ export function applyApps(
9797
});
9898
const base = controlPlane();
9999
if (!base || (!legacy && !dev)) return;
100-
const apps = () => createAppsClient(ctx.host, legacy ?? session, base, dev);
100+
// Off while the NIP-FI session is in use, as in an FI build: the tools
101+
// never call as a browser sign-in hidden behind it.
102+
const apps = () => {
103+
if (session.snapshot().federated)
104+
throw new Error(
105+
"Builderlab Apps tools are not available with your organization sign-in.",
106+
);
107+
return createAppsClient(ctx.host, legacy ?? session, base, dev);
108+
};
101109
const reply = (value: unknown) => JSON.stringify(value, null, 2);
102110
ctx.agents.addTool({
103111
name: "apps_contract",

0 commit comments

Comments
 (0)