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

The opensocial command starts, inspects, runs, moves and seeds groups

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:cli/commands
crates/opensocial/src/bin/opensocial.rs+5−3
@@ -1,11 +1,13 @@
//! `opensocial`: see [`opensocial::USAGE`].
fn main() {
#[tokio::main]
async fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
match opensocial::run(&args) {
let env = opensocial::Env::from(|k| std::env::var(k).ok());
match opensocial::run(&args, &env).await {
Ok(out) => print!("{out}"),
Err(e) => {
eprintln!("{e}");
eprintln!("{e:#}");
std::process::exit(1);
}
}
crates/opensocial/src/lib.rs+438−10
448 lines changed: not loaded until asked for.
crates/opensocial/tests/cli.rs+16−0
@@ -24,3 +24,19 @@ fn refuses_an_unknown_command() {
assert!(!out.status.success());
assert!(String::from_utf8_lossy(&out.stderr).starts_with("no command frobnicate"));
}
#[test]
fn reads_who_it_is_from_the_environment() {
let out = Command::new(env!("CARGO_BIN_EXE_opensocial"))
.args(["inspect", "riders.groups.test"])
.env_remove("OPENSOCIAL_AS")
.env_remove("OPENSOCIAL_PASSWORD")
.output()
.unwrap();
assert!(!out.status.success());
let said = String::from_utf8_lossy(&out.stderr);
assert!(
said.contains("set OPENSOCIAL_AS and OPENSOCIAL_PASSWORD"),
"{said}"
);
}
crates/opensocial/tests/commands.rsnew+285−0
@@ -0,0 +1,285 @@
//! The commands, run as a person on the reference PDS against hosts of
//! this repo's own, in process.
#[path = "../../group-host/tests/common/net.rs"]
#[allow(dead_code)]
mod net;
use group_host::Host;
use group_host::config::Config;
use net::net;
use opensocial::{Env, did_web, run};
use std::collections::HashMap;
use std::sync::Arc;
use tempfile::TempDir;
/// A host at a free port, on the reference directory, resolving
/// handles at the reference PDS.
struct Running {
host: Arc<Host>,
url: String,
_data: TempDir,
}
async fn host() -> Running {
let n = net();
// By name, as the reference PDS takes a did:web of one, not of an
// address; on every address, IPv6 and IPv4, whichever localhost is.
let listener = tokio::net::TcpListener::bind("[::]:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let url = format!("http://localhost:{port}");
let data = tempfile::tempdir().unwrap();
let env: HashMap<&str, String> = HashMap::from([
("DATA_DIR", data.path().to_str().unwrap().to_string()),
("PLC_URL", n.plc.clone()),
("HANDLE_DOMAIN", ".groups.test".into()),
("HANDLE_RESOLVERS", n.pds.clone()),
("PUBLIC_URL", url.clone()),
]);
let host = Arc::new(Host::open(Config::from(|k| env.get(k).cloned()).unwrap()).unwrap());
let router = group_host::router(host.clone());
tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
Running {
host,
url,
_data: data,
}
}
/// The command's environment: `h`, signed in as the reference PDS's
/// `who`th account.
fn env(h: &Running, who: usize) -> Env {
let n = net();
let person = &n.accounts[who];
let vars: HashMap<&str, String> = HashMap::from([
("OPENSOCIAL_HOST", format!("{}/", h.url)),
("PDS_URL", n.pds.clone()),
("OPENSOCIAL_AS", person.handle.clone()),
("OPENSOCIAL_PASSWORD", person.password.clone()),
(
"OPENSOCIAL_SEED_INVITE",
format!(" {} ,", n.accounts[1].handle),
),
]);
Env::from(|k| vars.get(k).cloned())
}
async fn opensocial(env: &Env, args: &[&str]) -> anyhow::Result<String> {
let args: Vec<String> = args.iter().map(|a| a.to_string()).collect();
run(&args, env).await
}
async fn ok(env: &Env, args: &[&str]) -> String {
opensocial(env, args)
.await
.unwrap_or_else(|e| panic!("{args:?}: {e:#}"))
}
async fn fails(env: &Env, args: &[&str]) -> String {
format!("{:#}", opensocial(env, args).await.unwrap_err())
}
#[tokio::test]
async fn starts_inspects_and_runs_a_group() {
let h = host().await;
let alice = env(&h, 0);
let bob = &net().accounts[1].handle;
let made = ok(
&alice,
&[
"create-group",
"riders.groups.test",
"--name",
"Riders",
"--description",
"Saturdays.",
"--join",
"invite",
],
)
.await;
assert!(
made.starts_with("group riders.groups.test did:plc:"),
"{made}"
);
let did = made.split_whitespace().nth(2).unwrap().to_string();
let seen = ok(&alice, &["inspect", "riders.groups.test"]).await;
assert!(seen.contains("name Riders\n"), "{seen}");
assert!(seen.contains("joining invite\n"), "{seen}");
assert!(seen.contains("admin Admin\n"), "{seen}");
assert!(seen.contains(&net().accounts[0].handle), "{seen}");
assert!(seen.contains("fyi.opensocial.members/self"), "{seen}");
let said = ok(
&alice,
&[
"membership",
"invite",
&did,
bob,
"--message",
"Ride with us",
],
)
.await;
assert_eq!(said, format!("{bob}: invited\n"));
let me = net().accounts[0].did.clone();
let said = ok(
&alice,
&["membership", "assign", &did, &me, "admin,member,"],
)
.await;
assert_eq!(said, format!("{me}: admin, member\n"));
// Bob is no member yet: the host says why.
let said = fails(
&alice,
&["membership", "eject", &did, bob, "--reason", "spam"],
)
.await;
assert!(
said.starts_with("fyi.opensocial.ejectMember: 400"),
"{said}"
);
}
#[tokio::test]
async fn seeds_a_group_to_try_things_on() {
let h = host().await;
let said = ok(&env(&h, 0), &["seed", "trial.groups.test"]).await;
let bob = &net().accounts[1].handle;
assert!(said.contains("rule Be kind\n"), "{said}");
assert!(said.contains("role moderator\n"), "{said}");
assert!(said.ends_with(&format!("invited {bob}\n")), "{said}");
let h2 = host().await;
let alice = env(&h2, 0);
ok(&alice, &["create-group", "quiet.groups.test"]).await;
let group = h2
.host
.store
.account("quiet.groups.test")
.unwrap()
.unwrap()
.did;
let seen = ok(&alice, &["inspect", &group]).await;
assert!(seen.contains("name quiet\n"), "{seen}");
// Someone outside it sees no members, and is told so.
let seen = ok(&env(&h2, 1), &["inspect", &group]).await;
assert!(seen.contains("members\n none\n"), "{seen}");
}
#[tokio::test]
async fn moves_a_group_to_another_host() {
let (a, b) = (host().await, host().await);
let alice = env(&a, 0);
ok(&alice, &["create-group", "riders.groups.test"]).await;
let said = ok(
&alice,
&[
"migrate",
"riders.groups.test",
"--to",
&format!("{}/", b.url),
],
)
.await;
assert!(said.contains("handed over to "), "{said}");
assert!(said.ends_with("switched on\n"), "{said}");
let did = a
.host
.store
.account("riders.groups.test")
.unwrap()
.unwrap()
.did;
assert!(b.host.deactivation(&did).unwrap().is_none());
// Named by its DID, to a host that is not there.
let said = fails(
&alice,
&[
"migrate",
&did,
"--to",
"http://127.0.0.1:1",
"--to-did",
"did:web:nowhere",
],
)
.await;
assert!(said.contains("fyi.opensocial.migratePrepare"), "{said}");
}
#[tokio::test]
async fn says_what_is_wrong_with_what_it_is_asked() {
let h = host().await;
let alice = env(&h, 0);
for args in [
&["create-group"][..],
&["inspect", "a", "b"],
&["migrate", "riders.groups.test"],
&["membership"],
&["membership", "assign", "g"],
&["membership", "frob", "g", "m"],
&["membership", "eject", "g", "m", "extra"],
] {
assert!(fails(&alice, args).await.starts_with("usage:"), "{args:?}");
}
assert!(
fails(&alice, &["create-group", "x", "--colour", "red"])
.await
.starts_with("no option --colour")
);
assert_eq!(
fails(&alice, &["create-group", "x", "--name"]).await,
"--name wants a value"
);
assert!(
fails(&alice, &["frob"])
.await
.starts_with("no command frob")
);
for args in [&[][..], &["help"], &["--help"], &["-h"]] {
assert_eq!(ok(&alice, args).await, opensocial::USAGE);
}
let mut nobody = alice.clone();
nobody.password = None;
assert!(
fails(&nobody, &["inspect", "x"])
.await
.contains("set OPENSOCIAL_AS and OPENSOCIAL_PASSWORD")
);
let mut wrong = alice.clone();
wrong.password = Some("not it".into());
assert!(
fails(&wrong, &["inspect", "x"])
.await
.starts_with("signing in as ")
);
let mut unreachable = alice.clone();
unreachable.pds = "http://127.0.0.1:1".into();
assert!(
fails(&unreachable, &["inspect", "x"])
.await
.starts_with("reaching http://127.0.0.1:1")
);
let mut gone = alice.clone();
gone.host = "http://127.0.0.1:1".into();
for args in [
&["inspect", "x.test"][..],
&["create-group", "x.groups.test"],
] {
let said = fails(&gone, args).await;
assert!(said.starts_with("reaching http://127.0.0.1:1"), "{said}");
}
}
#[test]
fn reads_its_environment() {
let env = Env::from(|_| None);
assert_eq!(env.host, "http://localhost:2600");
assert_eq!(env.host_did, "did:web:localhost%3A2600");
assert_eq!(env.pds, "http://localhost:2583");
assert!(env.handle.is_none() && env.seed_invite.is_empty());
assert_eq!(did_web("https://groups.example/"), "did:web:groups.example");
}
crates/opensocial/Cargo.toml+9−0
@@ -8,6 +8,15 @@ rust-version.workspace = true
[dependencies]
anyhow.workspace = true
reqwest.workspace = true
serde_json.workspace = true
tokio.workspace = true
[dev-dependencies]
axum.workspace = true
group-host.workspace = true
serde.workspace = true
tempfile.workspace = true
[[bin]]
name = "opensocial"
docs/design/README.md+6−3
@@ -129,9 +129,12 @@ says otherwise.
[moving](moving.md#moving-the-host)):
`methods/{moderation,recovery,importAccount,migration}.ts`,
`hostLabels.ts`, `scripts/move-host.ts`.
9. **MCP and the command.** The MCP tools over what steps 4 to 8 brought,
and the `opensocial` command's `create-group`, `inspect`, `membership`,
`migrate`, `move-host` and seeds, as `packages/cli` has them.
9. **MCP and the command.** The `opensocial` command's `create-group`,
`inspect`, `membership`, `migrate` and `seed`, signed in as a person on
their own PDS (done, see [the commands](../reference/cli.md); moving
the host is `group-host move-host`, as it needs the host's own
database and keys); then the MCP tools over what steps 4 to 8 brought,
with the OAuth an assistant signs in by and `listConnectedApps`.
The MCP tools and the command's subcommands may come in with each step
instead, beside the methods they call, where that is the smaller pull.
docs/reference/cli.md+22−3
@@ -11,12 +11,31 @@ Anything else fails with its usage.
## `opensocial`
It acts as a person: it signs in to their own PDS and asks it for a
service token for each method it calls, as an app does, so an account on
any PDS may run it against any host.
| Command | What it does |
| --- | --- |
| `help`, `--help`, `-h`, or none | prints its usage |
Any other command fails with `no command <name>` and the usage. Commands
arrive with the methods they call (see [the order](../design/README.md#the-order)).
| `create-group <handle> [--name] [--description] [--join open\|approval\|invite]` | starts a group, run by you |
| `inspect <group>` | the group as you may see it: its roles, members and spaces |
| `membership assign <group> <member> <role,role…>` | gives a member these roles, in place of theirs (`member` among them) |
| `membership eject <group> <member> [--reason]` | puts a member out |
| `membership invite <group> <person> [--message]` | invites someone in |
| `migrate <group> --to <address> [--to-did <did>]` | moves a group, whole, from this host to another ([moving](../design/moving.md)) |
| `seed <handle>` | a group to try things on: two rules, a moderator role, and an invite for each of `OPENSOCIAL_SEED_INVITE` |
A group or person is a handle or a DID. Anything else fails with its
usage.
| Variable | What it is |
| --- | --- |
| `OPENSOCIAL_AS`, `OPENSOCIAL_PASSWORD` | the handle you sign in as, and its password (an app password is enough) |
| `PDS_URL` | where you sign in; `http://localhost:2583` |
| `OPENSOCIAL_HOST` | the host; `http://localhost:2600` |
| `OPENSOCIAL_HOST_DID` | its DID; the did:web of its address |
| `OPENSOCIAL_SEED_INVITE` | who `seed` invites, comma-separated |
## `just`
Cargo.lock+7−0
@@ -1065,6 +1065,13 @@ name = "opensocial"
version = "0.1.0"
dependencies = [
"anyhow",
"axum",
"group-host",
"reqwest",
"serde",
"serde_json",
"tempfile",
"tokio",
]
[[package]]