~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

A group's address comes from its name as it is typed

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:web/new-group
crates/group-host/src/api.rs+28−0
@@ -69,6 +69,34 @@ fn view(did: &str, r: &Record) -> Value {
json!({"uri": format!("at://{did}/{}/{}", r.collection, r.rkey), "cid": r.cid.to_string(), "value": value})
}
/// Whether an address under this host's domain is free for a new group:
/// no account's handle here, nor kept by a group as its address. Anyone
/// may ask, as anyone may resolve a handle.
pub async fn check_address(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Answer {
let address = param(&p, "address")?.to_ascii_lowercase();
let label = address.strip_suffix(&host.config.handle_domain);
let ours = label.is_some_and(|l| !l.is_empty() && !l.contains('.'));
if !ours {
return Err(invalid(format!(
"an address is one label under {}",
host.config.handle_domain
)));
}
let available = !host.held_here(&address)?;
Ok(Json(json!({ "address": address, "available": available })))
}
/// The host as a PDS describes itself: its DID, and the domain whose names
/// it gives its groups. Nobody signs up here: a group is made for someone.
pub async fn describe_server(State(host): State<Arc<Host>>) -> Json<Value> {
Json(json!({
"did": host.config.service_did,
"availableUserDomains": [host.config.handle_domain],
"inviteCodeRequired": true,
"blobUploadLimit": host.config.blob_upload_limit,
}))
}
pub async fn describe_repo(State(host): State<Arc<Host>>, Query(p): Query<Params>) -> Answer {
let repo = param(&p, "repo")?;
let account = host.store.account(repo).map_err(XrpcError::internal)?;
crates/group-host/src/lib.rs+5−0
@@ -133,6 +133,11 @@ pub fn router(host: Arc<Host>) -> Router {
"/xrpc/com.atproto.repo.describeRepo",
get(api::describe_repo),
)
.route(
"/xrpc/com.atproto.server.describeServer",
get(api::describe_server),
)
.route("/xrpc/fyi.opensocial.checkAddress", get(api::check_address))
.route("/xrpc/com.atproto.repo.getRecord", get(api::get_record))
.route("/xrpc/com.atproto.repo.listRecords", get(api::list_records))
.route("/xrpc/com.atproto.sync.getRepo", get(api::get_repo))
crates/group-host/src/repo.rs+15−6
@@ -172,6 +172,17 @@ fn now() -> i64 {
}
impl Host {
/// Whether `name` is an account's here, as its handle or as its
/// address: a name under this host's domain no new account may take.
pub fn held_here(&self, name: &str) -> Result<bool, XrpcError> {
let by_handle = self.store.account(name).map_err(XrpcError::internal)?;
let by_address = self.store.addressed(name).map_err(XrpcError::internal)?;
Ok(
by_handle.is_some_and(|a| a.handle == name.to_ascii_lowercase())
|| by_address.is_some(),
)
}
/// Makes an account at `handle`, one label under the host's handle
/// domain: its keys, its `did:plc` published to the directory with
/// the host's rotation key, and an empty repo. Its DID.
@@ -195,12 +206,10 @@ impl Host {
format!("{handle} is taken"),
)
};
if self
.store
.account(handle)
.map_err(XrpcError::internal)?
.is_some()
{
// Taken as another's handle, or as another's address, kept by a
// group that has since taken a handle of its own: before anything
// is sent to the directory.
if self.held_here(handle)? {
return Err(taken());
}
let signing = Keypair::generate(Curve::K256);
crates/group-host/tests/groups.rs+41−0
@@ -519,3 +519,44 @@ async fn refuses_a_group_it_should_not_start() {
.await;
assert_eq!(status, 400);
}
#[tokio::test]
async fn keeps_a_groups_address_for_it_after_it_takes_a_handle_of_its_own() {
let h = start(&[("HANDLE_DOMAIN", ".groups.test")], false).await;
let [alice, bob, _] = people(&h).await;
let did = start_group(
&h,
&alice,
json!({"handle": RIDERS, "displayName": "Riders"}),
)
.await;
let free = async |address: &str| {
h.get("fyi.opensocial.checkAddress", &format!("address={address}"))
.await
};
assert_eq!(free("hikers.groups.test").await.1["available"], true);
assert_eq!(
free("Riders.groups.test").await.1,
json!({"address": RIDERS, "available": false})
);
// On a domain of its own, its address stays its own.
h.host
.store
.set_handle(&did, "riders.example.com", &[])
.unwrap();
assert_eq!(free(RIDERS).await.1["available"], false);
let lxm = format!("{NS}.createGroup");
let body = json!({"handle": RIDERS, "displayName": "Riders again"});
let (status, said) = post(&h, &lxm, &body, &[auth(&h, &bob, &lxm)]).await;
assert_eq!(
(status, said["error"].as_str()),
(400, Some("HandleTaken")),
"{said}"
);
// Only one label under this host's domain is an address here.
for not_ours in ["riders.example.com", ".groups.test", "a.b.groups.test"] {
assert_eq!(free(not_ours).await.0, 400, "{not_ours}");
}
}
crates/group-host/tests/repos.rs+18−0
@@ -528,3 +528,21 @@ async fn exports_a_tree_of_many_layers() {
assert_eq!(tree.leaves().len(), 200);
assert!(tree.nodes().len() > 2);
}
#[tokio::test]
async fn describes_itself_as_a_pds_that_names_groups_under_its_domain() {
let h = start(&[("HANDLE_DOMAIN", ".groups.test")], false).await;
let (status, described) = h.get("com.atproto.server.describeServer", "").await;
assert_eq!(status, 200, "{described}");
assert_eq!(described["did"], h.host.config.service_did.as_str());
assert_eq!(
described["availableUserDomains"],
serde_json::json!([".groups.test"])
);
// Nobody signs up here: a group is made for someone.
assert_eq!(described["inviteCodeRequired"], true);
assert_eq!(
described["blobUploadLimit"],
h.host.config.blob_upload_limit
);
}
docs/design/groups.md+12−0
@@ -35,6 +35,18 @@ from their own PDS (for this host's `SERVICE_DID`), makes:
`GROUP_FOUNDERS` names who the host starts groups for; anyone, unless it
names someone.
`com.atproto.server.describeServer` says, as any PDS does, the domain the
host names its groups under (`availableUserDomains`), its DID, and that
nobody signs up here (`inviteCodeRequired`): a group is made for someone.
The console's form for starting one reads the domain from it, and makes
the label under it from the group's name as it is typed, until the label
is changed by hand; once typing stops it asks whether the address is
free, and offers the next free one if not. `fyi.opensocial.checkAddress`
answers that, for anyone: whether the name is an account's handle here,
or kept as a group's address after it took a handle of its own. A group
is never started at either; resolving the name as a handle would miss
the second.
## Who may do what
A space's access record says who reads it (`readableBy`: roles, or
harness/e2e/flows.spec.mjs+15−6
@@ -43,20 +43,29 @@ test('coming back to her groups by a link, the page drawn in the browser', async
test('starting a group', async () => {
await page.getByRole('link', { name: 'Start a group' }).click()
await page.getByRole('textbox', { name: 'Handle' }).fill('hikers.groups.test')
await page.getByRole('textbox', { name: 'Name' }).fill('Hikers')
// Its address made from its name, under the host's domain.
await page.getByRole('textbox', { name: 'Name' }).pressSequentially('Hikers')
await expect(page.getByRole('textbox', { name: 'Its address' })).toHaveValue('hikers')
await expect(page.getByText('.groups.test', { exact: true })).toBeVisible()
await page.getByRole('textbox', { name: 'What it is for' }).fill('Walks on Sundays.')
await page.getByRole('button', { name: 'Start the group' }).click()
await page.waitForURL(url('/g/hikers.groups.test'))
await expect(page.getByRole('heading', { name: 'Hikers' })).toBeVisible()
await expect(page.getByText('Walks on Sundays.')).toBeVisible()
await expect(page.getByText('You are a member.')).toBeVisible()
// A handle taken already is the form's to say.
// An address taken already is said as it is typed, with the next free
// one to take; and the host's to refuse, sent all the same.
await page.goto(url('/new'))
await page.getByRole('textbox', { name: 'Handle' }).fill('hikers.groups.test')
await page.getByRole('textbox', { name: 'Name' }).fill('Hikers again')
await page.getByRole('textbox', { name: 'Name' }).pressSequentially('Hikers')
await expect(page.getByText('hikers.groups.test is taken.')).toBeVisible()
await expect(page.getByRole('button', { name: 'Use hikers-2.groups.test' })).toBeVisible()
await page.getByRole('button', { name: 'Start the group' }).click()
await expect(page.locator('.danger')).toBeVisible()
await expect(page.locator('p.danger')).toBeVisible()
// Its address changed by hand stays as it was put, whatever the name.
await page.goto(url('/new'))
await page.getByRole('textbox', { name: 'Its address' }).pressSequentially('Sunday Walks!')
await page.getByRole('textbox', { name: 'Name' }).pressSequentially('Hikers')
await expect(page.getByRole('textbox', { name: 'Its address' })).toHaveValue('sunday-walks-')
})
test('asking to join, and being admitted', async () => {
lexicons/fyi/opensocial/checkAddress.jsonnew+44−0
@@ -0,0 +1,44 @@
{
"lexicon": 1,
"id": "fyi.opensocial.checkAddress",
"defs": {
"main": {
"type": "query",
"description": "Whether an address under this host's domain is free for a new group: no account's handle here, nor kept by a group as its address after it took a handle of its own. Anyone may ask, as anyone may resolve a handle.",
"parameters": {
"type": "params",
"required": [
"address"
],
"properties": {
"address": {
"type": "string",
"maxLength": 253,
"description": "One label under this host's domain, as describeServer names it: riders.groups.test."
}
}
},
"output": {
"encoding": "application/json",
"schema": {
"type": "object",
"required": [
"address",
"available"
],
"properties": {
"address": {
"type": "string",
"maxLength": 253,
"description": "The address, lowercased."
},
"available": {
"type": "boolean",
"description": "Whether a new group may take it."
}
}
}
}
}
}
}
lexicons/upstream/com/atproto/server/describeServer.jsonnew+63−0
@@ -0,0 +1,63 @@
{
"lexicon": 1,
"id": "com.atproto.server.describeServer",
"defs": {
"main": {
"type": "query",
"description": "Describes the server's account creation requirements and capabilities. Implemented by PDS.",
"output": {
"encoding": "application/json",
"schema": {
"type": "object",
"required": ["did", "availableUserDomains"],
"properties": {
"inviteCodeRequired": {
"type": "boolean",
"description": "If true, an invite code must be supplied to create an account on this instance."
},
"phoneVerificationRequired": {
"type": "boolean",
"description": "If true, a phone verification token must be supplied to create an account on this instance."
},
"blobUploadLimit": {
"type": "integer",
"description": "Maximum size of a blob that can be uploaded via com.atproto.repo.uploadBlob, in bytes."
},
"availableUserDomains": {
"type": "array",
"description": "List of domain suffixes that can be used in account handles.",
"items": { "type": "string" }
},
"links": {
"type": "ref",
"description": "URLs of service policy documents.",
"ref": "#links"
},
"contact": {
"type": "ref",
"description": "Contact information",
"ref": "#contact"
},
"did": {
"type": "string",
"format": "did"
}
}
}
}
},
"links": {
"type": "object",
"properties": {
"privacyPolicy": { "type": "string", "format": "uri" },
"termsOfService": { "type": "string", "format": "uri" }
}
},
"contact": {
"type": "object",
"properties": {
"email": { "type": "string" }
}
}
}
}
web/src/lib/organisms/NewGroupForm.svelte+51−5
@@ -1,15 +1,61 @@
<script lang="ts">
import { finished, labelOf } from '#lib/handles.ts';
/**
* Starting a group: its handle, its name and words, and how people get
* in. `failed` is what the host said of the last try, if it refused it.
* Starting a group: its name, and its address under the host's
* `domain`, made from the name as it is typed until it is changed by
* hand; whether that address is free, asked once typing stops, with the
* next free one to take if not; its words; and how people get in.
* `failed` is what the host said of the last try, if it refused it.
*/
let { failed }: { failed?: string } = $props();
let { failed, domain }: { failed?: string; domain: string } = $props();
let name = $state('');
let label = $state('');
let edited = $state(false);
// Taken, and the next free one if there is one near: none while free or unasked.
let taken = $state<{ label: string; next?: string } | null>(null);
// Free unless the host says not: its handle, or kept as a group's
// address. A host that cannot say leaves it to the host to refuse.
const free = async (l: string) => {
const asked = await fetch(`/xrpc/fyi.opensocial.checkAddress?address=${encodeURIComponent(l + domain)}`).catch(() => null);
const said: { available?: boolean } | null = asked?.ok ? await asked.json() : null;
return said?.available !== false;
};
$effect(() => {
const l = finished(label);
taken = null;
if (!l) return;
const wait = setTimeout(async () => {
if (await free(l)) return;
let next: string | undefined;
for (let n = 2; n < 20 && !next; n++) if (await free(`${l}-${n}`)) next = `${l}-${n}`;
if (finished(label) === l) taken = { label: l, next };
}, 350);
return () => clearTimeout(wait);
});
</script>
<form class="stack" method="post">
{#if failed}<p class="danger">{failed}</p>{/if}
<label class="field">Handle <input name="handle" required placeholder="riders.example.com" /></label>
<label class="field">Name <input name="displayName" required maxlength="64" /></label>
<label class="field">
Name
<input name="displayName" required maxlength="64" bind:value={name} oninput={() => (label = edited ? label : labelOf(name))} />
</label>
<label class="field">
Its address
<span class="address">
<input name="label" required maxlength="63" pattern="[a-z0-9][a-z0-9\-]*" bind:value={label} oninput={() => ((edited = true), (label = labelOf(label)))} />
<span class="mute mono">{domain}</span>
</span>
</label>
{#if taken}
<p class="danger">
{taken.label}{domain} is taken.
{#if taken.next}<button class="quiet" type="button" onclick={() => ((edited = true), (label = taken?.next ?? label))}>Use {taken.next}{domain}</button>{/if}
</p>
{:else}
<p class="mute small">Made from its name; change it if you like. It is the group's handle, and where its pages are.</p>
{/if}
<label class="field">What it is for <textarea name="description" maxlength="300"></textarea></label>
<label class="field">
How people join
web/src/lib/handles.tsnew+19−0
web/src/routes/new/+page.server.ts+14−3
web/src/routes/new/+page.svelte+1−1
web/src/app.css+3−0