Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions browser-host/relay-broker-api.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ async function harness(
}
const call = {
url: upstreamUrl,
method: init?.method ?? "GET",
body: init?.body ? JSON.parse(init.body) : undefined,
signal: init?.signal,
headers: init?.headers,
Expand Down Expand Up @@ -3132,6 +3133,75 @@ test("invite mint forwards only bounded ttl/max_uses and returns the relay invit
}
});

test("invite list and revoke sign their exact relay routes and never echo a code", async () => {
const cursor = "1795049564000000_0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f";
const page = { invites: [], next_before: null };
const { h, post } = await communityAdmin((call) =>
call.url.endsWith("/api/invites/revoke")
? call.body.code === "v2.leak"
? Response.json({ error: "v2.leak not found" }, { status: 404 })
: Response.json({ id: "x", revoked_at: 1 })
: Response.json(page),
);
try {
for (const [body, url] of [
[{}, `${fixtureRelayUrl}/api/invites`],
[{ before: cursor }, `${fixtureRelayUrl}/api/invites?before=${cursor}`],
]) {
const response = await post("invites", body);
expect(response.status).toBe(200);
expect(await response.json()).toEqual(page);
const sent = h.calls.at(-1);
expect(sent.url).toBe(url);
expect(sent.method).toBe("GET");
expect(sent.body).toBeUndefined();
expect(sent.auth.tags).toContainEqual(["u", url]);
expect(sent.auth.tags).toContainEqual(["method", "GET"]);
expect(sent.auth.tags.some(([name]) => name === "payload")).toBe(false);
}
const revoked = await post("invite-revoke", { code: "v2.abc" });
expect(revoked.status).toBe(200);
const sent = h.calls.at(-1);
expect(sent.url).toBe(`${fixtureRelayUrl}/api/invites/revoke`);
expect(sent.method).toBe("POST");
expect(sent.body).toEqual({ code: "v2.abc" });
expect(sent.auth.tags).toContainEqual([
"u",
`${fixtureRelayUrl}/api/invites/revoke`,
]);
expect(sent.auth.tags).toContainEqual(["method", "POST"]);
expect(sent.auth.tags).toContainEqual([
"payload",
createHash("sha256")
.update(JSON.stringify({ code: "v2.abc" }))
.digest("hex"),
]);

const calls = h.calls.length;
for (const body of [
{ before: "1&limit=200" },
{ before: `${cursor}&limit=1` },
{ before: "1795049564000000_0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2fx" },
{ limit: 200 },
])
expect((await post("invites", body)).status).toBe(400);
for (const body of [
{},
{ id: "x" },
{ id: "a", code: "v2.a" },
{ code: "a b" },
])
expect((await post("invite-revoke", body)).status).toBe(400);
expect(h.calls).toHaveLength(calls);

const refused = await post("invite-revoke", { code: "v2.leak" });
expect(refused.status).toBe(404);
expect(await refused.text()).not.toContain("v2.leak");
} finally {
await h.close();
}
});

test("member changes sign exact NIP-43 admin kinds and reject malformed changes locally", async () => {
const { h, post } = await communityAdmin((call) =>
Response.json({ accepted: true, event_id: call.body.id, message: "" }),
Expand Down
36 changes: 27 additions & 9 deletions browser-host/relay-broker.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,10 @@ import { validChannelCommand } from "./channel-commands.mjs";
import {
adminReason,
claimReason,
inviteListPath,
inviteRequest,
memberCommand,
revokeRequest,
} from "../src/features/communities/admin-protocol.ts";
import {
leaveRefusal,
Expand Down Expand Up @@ -2523,6 +2525,8 @@ export function relayBrokerPlugin({
"/api/relay/claim",
"/api/relay/accept-policy",
"/api/relay/invite",
"/api/relay/invites",
"/api/relay/invite-revoke",
"/api/relay/member",
"/api/relay/leave",
"/api/relay/gifs",
Expand Down Expand Up @@ -2837,13 +2841,15 @@ export function relayBrokerPlugin({
const claim = route === "/api/relay/claim";
const policy = route === "/api/relay/accept-policy";
const invite = route === "/api/relay/invite";
const inviteList = route === "/api/relay/invites";
const revoke = route === "/api/relay/invite-revoke";
const member = route === "/api/relay/member";
const leave = route === "/api/relay/leave";
const gifs = route === "/api/relay/gifs";
const profileSearch = route === "/api/relay/profile-search";
// Only these routes may surface an exact, allowed relay refusal.
const refusal =
invite || member
invite || inviteList || revoke || member
? adminReason
: claim
? claimReason
Expand All @@ -2856,18 +2862,24 @@ export function relayBrokerPlugin({
body?.error,
)
: undefined;
if (invite || member || leave) {
let invitePath;
if (invite || inviteList || revoke || member || leave) {
// Community-bound only; the relay remains the authority for roles.
if (!scoped)
return json(res, 400, { error: "Select a community first" });
try {
// The viewer's own leave request has one shape; the body carries nothing.
if (inviteList) invitePath = inviteListPath(filters);
filters = invite
? inviteRequest(filters)
: finalizeEvent(
leave ? leaveRequestTemplate() : memberCommand(filters),
key,
);
: revoke
? revokeRequest(filters)
: inviteList
? undefined
: finalizeEvent(
leave ? leaveRequestTemplate() : memberCommand(filters),
key,
);
} catch (error) {
return json(res, 400, { error: error.message, sent: false });
}
Expand Down Expand Up @@ -3225,6 +3237,8 @@ export function relayBrokerPlugin({
!claim &&
!policy &&
!invite &&
!inviteList &&
!revoke &&
!member &&
!leave &&
!gifs &&
Expand Down Expand Up @@ -3308,6 +3322,7 @@ export function relayBrokerPlugin({
return json(res, 404, { error: "GIF search is unavailable" });
const upstreamPath =
workflowPath ??
invitePath ??
(gifs
? gifSearchPath
: profileSearch
Expand All @@ -3320,8 +3335,10 @@ export function relayBrokerPlugin({
? "/api/invites/accept-policy"
: invite
? "/api/invites"
: "/query");
const method = workflowPath ? "GET" : "POST";
: revoke
? "/api/invites/revoke"
: "/query");
const method = workflowPath || invitePath ? "GET" : "POST";
const lane = admissions(relay, viewer).api;
let releasePresence;
if (presence) {
Expand All @@ -3339,7 +3356,8 @@ export function relayBrokerPlugin({
});
if (!presence) inflight.set(relay, (inflight.get(relay) ?? 0) + 1);
try {
const body = workflowPath ? undefined : JSON.stringify(filters);
const body =
workflowPath || invitePath ? undefined : JSON.stringify(filters);
const admissionStart = performance.now();
let connectsBefore, upstreamStart;
let response;
Expand Down
3 changes: 3 additions & 0 deletions docs/buzz-help.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,9 @@ In a Codex agent’s settings, open **Huddle voice** in the **Settings** tab to
**Copy link**, and shared expiry and use limits. On macOS, hover over the QR
or focus its action with the keyboard to reveal **Share**, which opens the
system share menu with a QR image and the invite link.
**Links** lists the community's invite links with their status, uses and
expiry; **Revoke** on a row, or paste a link into **Revoke a link**, stops
anyone new from joining with it. People who already joined stay in.
- To use Buzz on your phone, open Settings → **Mobile app** (**Pair mobile**
in builds without Builderlab). When you're signed in with Builderlab and your
account holds this identity's backup, it says to install the app (with store
Expand Down
26 changes: 24 additions & 2 deletions src-tauri/src/relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,13 @@ pub(crate) fn origin(value: &str) -> Result<Url> {

fn request_url(community: &str, path: &str, method: &str) -> Result<Url> {
let allowed = match method {
"GET" => matches!(path, "/" | "/api/join-policy"),
"GET" => matches!(path, "/" | "/api/join-policy") || invite_list(path),
"POST" => matches!(
path,
"/query"
| "/events"
| "/api/invites"
| "/api/invites/revoke"
| "/api/invites/claim"
| "/api/invites/accept-policy"
| "/gifs/search"
Expand All @@ -102,6 +103,27 @@ fn request_url(community: &str, path: &str, method: &str) -> Result<Url> {
.map_err(|_| "Invalid relay path".into())
}

/// `GET /api/invites`, optionally with the relay's `<micros>_<uuid>` cursor.
fn invite_list(path: &str) -> bool {
let Some(rest) = path.strip_prefix("/api/invites") else {
return false;
};
let Some(cursor) = rest.strip_prefix("?before=") else {
return rest.is_empty();
};
cursor.split_once('_').is_some_and(|(micros, id)| {
(1..=20).contains(&micros.len())
&& micros.bytes().all(|b| b.is_ascii_digit())
&& workflow_uuid(id)
})
}

/// Whether `relay_http` signs a request: every write, and the invite list,
/// which is an owner/admin-only read.
fn signed_http(method: &str, path: &str) -> bool {
method == "POST" || invite_list(path)
}

fn workflow_uuid(value: &str) -> bool {
uuid::Uuid::parse_str(value).is_ok()
&& value.len() == 36
Expand Down Expand Up @@ -1021,7 +1043,7 @@ pub(crate) async fn relay_http(
url,
&method,
body,
method == "POST",
signed_http(&method, &path),
MAX_RESPONSE,
);
cancellable(id.as_deref(), &method, &path, request).await
Expand Down
94 changes: 93 additions & 1 deletion src-tauri/src/relay/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,23 @@ fn routes_cannot_retarget_credentials_or_expand_http_access() {
] {
assert!(request_url("https://relay.test", path, "POST").is_err());
}
for path in ["/api/invites", "/gifs/search", "/profiles/search"] {
for path in ["/gifs/search", "/profiles/search", "/api/invites/revoke"] {
assert!(request_url("https://relay.test", path, "POST").is_ok());
assert!(request_url("https://relay.test", path, "GET").is_err());
}
let cursor = "/api/invites?before=1795049564000000_0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f";
for path in ["/api/invites", cursor] {
assert!(request_url("https://relay.test", path, "GET").is_ok());
}
assert!(request_url("https://relay.test", "/api/invites", "POST").is_ok());
for path in [
"/api/invites?limit=200",
"/api/invites?before=1_x",
"/api/invites?before=1795049564000000_0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f&limit=1",
"/api/invites/claim",
] {
assert!(request_url("https://relay.test", path, "GET").is_err());
}
assert!(request_url("https://relay.test", "/gifs/other", "POST").is_err());
assert!(request_url("https://relay.test", "/profiles/other", "POST").is_err());
assert!(request_url("https://relay.test", "/events", "GET").is_err());
Expand Down Expand Up @@ -4660,6 +4673,85 @@ mod federated_header {
);
community.assert_carried(head);
}
/// The invite list and revoke go through `relay_http` itself: both list
/// forms are signed GETs over their full URL, revoke binds its body.
#[tokio::test]
async fn relay_http_signs_invite_list_and_revoke() {
use tauri::Manager;
let community = community(false).await;
let app = tauri::test::mock_builder()
.manage(community.host.clone())
.manage(community.fi.clone())
.build(crate::app_context())
.unwrap();
let cursor = "?before=1795049564000000_0b9c8f7e-1d2a-4b3c-9e8f-7a6b5c4d3e2f";
let revoke = r#"{"code":"v2.abc"}"#;
let routes = [
("GET", "/api/invites".to_owned(), None),
("GET", format!("/api/invites{cursor}"), None),
("POST", "/api/invites/revoke".to_owned(), Some(revoke)),
];
let server = community.serve(routes.iter().map(|_| reply("200 OK", "{}")).collect());
for (method, path, body) in &routes {
let response = relay_http(
app.state(),
app.state(),
community.origin.to_string(),
path.clone(),
(*method).into(),
body.map(str::to_owned),
None,
)
.await
.unwrap();
assert_eq!(response.status, 200);
}
let heads = server.heads().await;
for ((method, path, body), head) in routes.iter().zip(&heads) {
assert!(head.starts_with(&format!("{method} {path} ")), "{head}");
let encoded = head
.lines()
.find_map(|line| line.strip_prefix("authorization: Nostr "))
.unwrap_or_else(|| panic!("unsigned: {head}"));
let event: serde_json::Value =
serde_json::from_slice(&STANDARD.decode(encoded).unwrap()).unwrap();
verify(&event);
let url = community.origin.join(path).unwrap();
assert_eq!(event["tags"][0], serde_json::json!(["u", url.as_str()]));
assert_eq!(event["tags"][1], serde_json::json!(["method", method]));
let payload = event["tags"]
.as_array()
.unwrap()
.iter()
.find(|tag| tag[0] == "payload");
match body {
Some(body) => assert_eq!(
payload.unwrap()[1],
format!("{:x}", Sha256::digest(body.as_bytes()))
),
None => assert!(payload.is_none()),
}
}
// No other invite path or query is reachable through the command.
for path in [
"/api/invites?limit=200",
"/api/invites?before=1_x",
&format!("/api/invites{cursor}&limit=1"),
"/api/invites/revoke",
] {
assert!(relay_http(
app.state(),
app.state(),
community.origin.to_string(),
path.into(),
"GET".into(),
None,
None,
)
.await
.is_err());
}
}
#[tokio::test]
async fn http_attaches_for_required_discovery() {
http(true).await;
Expand Down
Loading
Loading