Skip to content

Commit f869df8

Browse files
TheSentinel454codexElrond
authored
Add recoverable hosted community deletion (#403)
Signed-off-by: OpenAI Codex <[email protected]> Signed-off-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Signed-off-by: Codex <[email protected]> Co-authored-by: OpenAI Codex <[email protected]> Co-authored-by: Elrond <28d6302a099e5225b02c4155ac4236e4912603df2ab08dbfc2f4fef08ce598c8@buzz.block.builderlab.xyz> Co-authored-by: Codex <[email protected]>
1 parent f264c62 commit f869df8

10 files changed

Lines changed: 3099 additions & 126 deletions

File tree

‎dev/builderlab.mjs‎

Lines changed: 41 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ const API = "https://app.builderlab.xyz/api/goose";
1010
// Builderlab checks Origin on identity binding; it also seeds the challenge origin.
1111
export const BUILDERLAB_ORIGIN = "https://app.builderlab.xyz";
1212
const LOGIN_TIMEOUT_MS = 10 * 60 * 1000;
13+
const MAX_RESPONSE_BYTES = 64 * 1024;
14+
const RESPONSE_STATUS = Symbol("builderlabResponseStatus");
1315
const COMPLETE_HTML =
1416
"<!doctype html><meta charset=utf-8><title>Buzz authentication complete</title><p>You're signed in. You can close this window and return to Buzz.";
1517

@@ -22,13 +24,21 @@ const ROUTES = {
2224
create: ["/v1/buzz/communities", ["name"]],
2325
archive: ["/v1/buzz/communities/archive", ["community_id"]],
2426
unarchive: ["/v1/buzz/communities/unarchive", ["community_id"]],
27+
delete: [
28+
"/v1/buzz/communities/delete",
29+
["community_id", "host", "request_id", "acknowledgement_version"],
30+
],
2531
// Builderlab's transfer endpoint takes camelCase keys.
2632
transfer: [
2733
"/v1/buzz/communities/transfer",
2834
["communityId", "transfereeNpub"],
2935
],
3036
};
3137

38+
/** Upstream status is metadata, not part of the public JSON body. */
39+
export const builderlabResponseStatus = (value) =>
40+
value?.[RESPONSE_STATUS] ?? 200;
41+
3242
/** Signs the kind 24243 challenge exactly as block/buzz desktop does, after the same checks. */
3343
export function bindingEvent(key, challenge, now = Date.now()) {
3444
const { challenge_id, nonce, verification_code, origin, expires_at } =
@@ -161,10 +171,23 @@ export function createBuilderlab({
161171
redirect: "error",
162172
signal: AbortSignal.timeout(60000),
163173
});
164-
const value = await response.json().catch(() => undefined);
174+
const text = await response.text();
175+
if (Buffer.byteLength(text) > MAX_RESPONSE_BYTES)
176+
throw new Error("Builderlab response was too large");
177+
let value;
178+
try {
179+
value = JSON.parse(text);
180+
} catch {
181+
throw new Error("Builderlab returned an invalid response");
182+
}
165183
// Structured `{ error: { code, ... } }` bodies pass through for friendly UI messages.
166-
if (value && typeof value === "object" && (response.ok || value.error))
184+
if (value && typeof value === "object" && (response.ok || value.error)) {
185+
Object.defineProperty(value, RESPONSE_STATUS, {
186+
value: response.status,
187+
enumerable: false,
188+
});
167189
return value;
190+
}
168191
throw new Error(`Builderlab request failed (HTTP ${response.status}).`);
169192
};
170193
const me = async (session, signal) => {
@@ -177,8 +200,16 @@ export function createBuilderlab({
177200
throw new Error(
178201
`Builderlab session check failed with HTTP ${response.status}`,
179202
);
180-
const { email, name, expires_at } = await response.json();
181-
return { email, name, expiresAt: expires_at };
203+
const { email, name, expires_at, capabilities } = await response.json();
204+
return {
205+
email,
206+
name,
207+
expiresAt: expires_at,
208+
capabilities: {
209+
can_delete_buzz_communities:
210+
capabilities?.can_delete_buzz_communities === true,
211+
},
212+
};
182213
};
183214
// Sign-in and sign-out bump the generation; late results from an older one never
184215
// write, clear or describe the current session.
@@ -271,7 +302,12 @@ export function createBuilderlab({
271302
const body = {};
272303
for (const field of fields) {
273304
const value = input?.[field];
274-
if (typeof value !== "string" || !value || value.length > 200)
305+
if (field === "acknowledgement_version") {
306+
if (!Number.isInteger(value)) throw new Error(`Missing ${field}`);
307+
body[field] = value;
308+
continue;
309+
}
310+
if (typeof value !== "string" || !value || value.length > 253)
275311
throw new Error(`Missing ${field}`);
276312
body[field] = value;
277313
}

‎dev/builderlab.test.mjs‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { generateSecretKey, getPublicKey, verifyEvent } from "nostr-tools";
33
import {
44
BUILDERLAB_ORIGIN,
55
bindingEvent,
6+
builderlabResponseStatus,
67
createBuilderlab,
78
} from "./builderlab.mjs";
89

@@ -107,6 +108,7 @@ it("completes browser sign-in through a loopback callback without exposing the c
107108
108109
name: "A",
109110
expiresAt: "2030",
111+
capabilities: { can_delete_buzz_communities: false },
110112
});
111113
expect(JSON.stringify(auth)).not.toContain("secret");
112114
expect(h.opened().pathname).toBe("/api/goose/v1/auth/login");
@@ -153,6 +155,90 @@ it("forwards only allowlisted fields and ignores unknown actions", async () => {
153155
expect(await h.builderlab.call("../auth/me", {})).toBeUndefined();
154156
});
155157

158+
it("forwards the exact deletion tuple for both admission and same-UUID replay", async () => {
159+
const h = account({
160+
"/v1/buzz/communities/delete": () =>
161+
Response.json({ status: "submitted" }, { status: 202 }),
162+
});
163+
await signIn(h);
164+
const request = {
165+
community_id: "community",
166+
host: "North.communities.buzz.xyz",
167+
request_id: "11111111-1111-4111-8111-111111111111",
168+
acknowledgement_version: 1,
169+
owner_pubkey: "must-not-pass",
170+
extra: "dropped",
171+
};
172+
const admitted = await h.builderlab.call("delete", request);
173+
expect(builderlabResponseStatus(admitted)).toBe(202);
174+
expect(h.requests.at(-1).path).toBe("/v1/buzz/communities/delete");
175+
expect(JSON.parse(h.requests.at(-1).init.body)).toEqual({
176+
community_id: request.community_id,
177+
host: request.host,
178+
request_id: request.request_id,
179+
acknowledgement_version: 1,
180+
});
181+
const replay = await h.builderlab.call("delete", request);
182+
expect(builderlabResponseStatus(replay)).toBe(202);
183+
expect(h.requests.at(-1).path).toBe("/v1/buzz/communities/delete");
184+
expect(JSON.parse(h.requests.at(-1).init.body)).toEqual({
185+
community_id: request.community_id,
186+
host: request.host,
187+
request_id: request.request_id,
188+
acknowledgement_version: 1,
189+
});
190+
expect(
191+
h.requests.filter((item) => item.path === "/v1/buzz/communities/delete"),
192+
).toHaveLength(2);
193+
});
194+
195+
it("does not expose a removed deletion receipt action", async () => {
196+
const h = account({});
197+
expect(await h.builderlab.call("delete-receipt", {})).toBeUndefined();
198+
expect(h.requests).toHaveLength(0);
199+
});
200+
201+
it.each([
202+
[true, true],
203+
["true", false],
204+
[1, false],
205+
[undefined, false],
206+
])("maps delete capability %j to literal true=%s", async (value, expected) => {
207+
const h = account({
208+
"/v1/auth/me": () =>
209+
Response.json({
210+
211+
expires_at: "2030",
212+
capabilities: { can_delete_buzz_communities: value },
213+
}),
214+
});
215+
expect((await signIn(h)).capabilities).toEqual({
216+
can_delete_buzz_communities: expected,
217+
});
218+
});
219+
220+
it.each([
221+
["malformed", "{"],
222+
["oversize", JSON.stringify({ value: "x".repeat(70_000) })],
223+
])("rejects a %s downstream response after dispatch", async (_label, body) => {
224+
const h = account({
225+
"/v1/buzz/communities/delete": () =>
226+
new Response(body, {
227+
status: 202,
228+
headers: { "Content-Type": "application/json" },
229+
}),
230+
});
231+
await signIn(h);
232+
await expect(
233+
h.builderlab.call("delete", {
234+
community_id: "community",
235+
host: "north.communities.buzz.xyz",
236+
request_id: "11111111-1111-4111-8111-111111111111",
237+
acknowledgement_version: 1,
238+
}),
239+
).rejects.toThrow(/invalid response|too large/);
240+
});
241+
156242
it("binds the local key by verifying a signed challenge and passes structured errors through", async () => {
157243
const h = account({
158244
"/v1/buzz/nostr-identities/challenge": () =>

‎dev/relay-broker-api.test.mjs‎

Lines changed: 71 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,12 @@ beforeEach(() => {
3333
afterEach(() => vi.restoreAllMocks());
3434

3535
// Real browser HTTP -> production broker. Ephemeral key; upstream I/O is entirely local.
36-
async function harness(respond, capabilities = {}, relayUrl = fixtureRelayUrl) {
36+
async function harness(
37+
respond,
38+
capabilities = {},
39+
relayUrl = fixtureRelayUrl,
40+
builderlab = {},
41+
) {
3742
const key = new Uint8Array(32);
3843
key[31] = 7;
3944
const viewer = getPublicKey(key);
@@ -51,6 +56,7 @@ async function harness(respond, capabilities = {}, relayUrl = fixtureRelayUrl) {
5156
});
5257
const plugin = relayBrokerPlugin({
5358
relayUrl,
59+
builderlab,
5460
communityAliases: fixtureAliases,
5561
identity: () => key,
5662
socketFactory: socket.factory,
@@ -125,6 +131,70 @@ async function harness(respond, capabilities = {}, relayUrl = fixtureRelayUrl) {
125131
};
126132
}
127133
const filters = [{ kinds: [0], limit: 1 }];
134+
135+
test.each([
136+
[202, { status: "aborted" }],
137+
[409, { error: { code: "must_archive" } }],
138+
])(
139+
"Builderlab HTTP forwards structured deletion status %s",
140+
async (status, result) => {
141+
let openLogin;
142+
const loginOpened = new Promise((resolve) => {
143+
openLogin = resolve;
144+
});
145+
const request = {
146+
community_id: "11111111-1111-4111-8111-111111111111",
147+
host: "north.communities.buzz.xyz",
148+
request_id: "22222222-2222-4222-8222-222222222222",
149+
acknowledgement_version: 1,
150+
};
151+
const upstream = [];
152+
const h = await harness(() => Response.json([]), {}, fixtureRelayUrl, {
153+
open: async (url) => openLogin(url),
154+
fetch: async (url, init) => {
155+
const path = new URL(url).pathname;
156+
if (path.endsWith("/v1/auth/login/exchange"))
157+
return Response.json({
158+
session_credential: "fixture-only",
159+
expires_at: "2030",
160+
});
161+
if (path.endsWith("/v1/auth/me"))
162+
return Response.json({
163+
164+
expires_at: "2030",
165+
});
166+
if (path.endsWith("/v1/buzz/communities/delete")) {
167+
upstream.push(JSON.parse(init.body));
168+
return Response.json({ ...request, ...result }, { status });
169+
}
170+
throw new Error(`Unexpected fixture request: ${path}`);
171+
},
172+
});
173+
try {
174+
const login = fetch(`${h.base}/api/builderlab/login`, {
175+
method: "POST",
176+
headers: { "Content-Type": "application/json" },
177+
body: "{}",
178+
});
179+
const opened = new URL(await loginOpened);
180+
const callback = opened.searchParams.get("returnTo");
181+
expect(callback).toBeTruthy();
182+
expect((await fetch(`${callback}?code=fixture`)).status).toBe(200);
183+
expect((await login).status).toBe(200);
184+
const response = await fetch(`${h.base}/api/builderlab/delete`, {
185+
method: "POST",
186+
headers: { "Content-Type": "application/json" },
187+
body: JSON.stringify(request),
188+
});
189+
expect(response.status).toBe(status);
190+
expect(await response.json()).toEqual({ ...request, ...result });
191+
expect(upstream).toEqual([request]);
192+
} finally {
193+
await h.close();
194+
}
195+
},
196+
);
197+
128198
const success = (call) =>
129199
Response.json(
130200
call.url.endsWith("/events")

‎dev/relay-broker.mjs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ import {
6969
import { readRelayLibrary } from "../src/features/agents/relay-library.ts";
7070
import { eventDto } from "../src/features/relay/events.ts";
7171
import { readAgentLibrary } from "./agent-library.mjs";
72-
import { createBuilderlab } from "./builderlab.mjs";
72+
import { builderlabResponseStatus, createBuilderlab } from "./builderlab.mjs";
7373
import {
7474
decodeSidebarPreferences,
7575
assertSidebarAssignmentIntent,
@@ -827,7 +827,7 @@ export function relayBrokerPlugin({
827827
raw ? JSON.parse(raw) : {},
828828
);
829829
return result
830-
? json(res, 200, result)
830+
? json(res, builderlabResponseStatus(result), result)
831831
: json(res, 404, { error: "Unknown Builderlab route" });
832832
} catch (error) {
833833
return json(res, 502, {

‎docs/plugin-architecture.md‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -131,8 +131,20 @@ personal groups and the existing + creation buttons, independently of this plugi
131131
Hosted communities (`block.hosted-communities`) is a Block-specific bundled plugin
132132
under Settings → Communities. It manages Block-hosted relays through a Builderlab
133133
account: browser sign-in, binding the local Buzz identity (a locally signed kind
134-
24243 challenge), and create/archive/unarchive/transfer. Joining stays in the
135-
existing Add a community dialog; the card only copies the new relay address. Its
134+
24243 challenge), and create/archive/unarchive/transfer. A server-declared,
135+
default-off capability also exposes owner deletion for archived communities. The
136+
card persists the bound four-field request before admission. A fresh request can
137+
terminate on a known structured pre-admission code and HTTP status pair;
138+
ambiguous first responses stay pending until an explicit same-UUID delete replay.
139+
Only a tuple-bound non-aborted 202 confirms progress; an aborted 202 ends recovery
140+
without claiming deletion. The card displays valid server quota when available;
141+
without it, Create remains available and the server enforces its owner limit.
142+
`can_create: false` alone disables Create; usage is informational and is never
143+
estimated from visible rows. One origin-wide pending slot is
144+
re-read and verified before dispatch; browser local storage has no atomic compare-and-set,
145+
so exactly simultaneous contexts remain a documented client-side race;
146+
it never signs deletion or infers acceptance from a missing list row. Joining
147+
stays in the existing Add a community dialog; the card only copies the new relay address. Its
136148
`/api/builderlab/*` routes live in the development broker (`dev/builderlab.mjs`),
137149
which keeps the session credential and signing key in Node. Packaged builds ship no
138150
broker, so this plugin cannot sign in or manage communities there until a native

0 commit comments

Comments
 (0)