Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(spaces): teams: cua team, share with team:<id>, team machines (CUA-1354) (#5004)

Francesco Bonacci10f08baf0618
diff --git a/docs/content/docs/cua-cli/reference/cli/index.mdx b/docs/content/docs/cua-cli/reference/cli/index.mdx
index 37801ebc92..2c7a940309 100644
--- a/docs/content/docs/cua-cli/reference/cli/index.mdx
+++ b/docs/content/docs/cua-cli/reference/cli/index.mdx
@@ -166,6 +166,14 @@ Enroll this device on the relay, approve, rename and revoke devices, and read th
| --- | --- | --- |
| <span id="cua-devices-status"></span><span id="cua-devices-enroll"></span><span id="cua-devices-approve"></span><span id="cua-devices-ls"></span><span id="cua-devices-rename"></span><span id="cua-devices-revoke"></span><span id="cua-devices-audit"></span>[`cua devices`](/cua-cli/reference/cli/devices#cua-devices) | This device as a client of your cua.ai account on the relay: enroll (second factor), approve other devices, list, rename, revoke, and the audit log of who accessed what. | [`status`](/cua-cli/reference/cli/devices#cua-devices-status), [`enroll`](/cua-cli/reference/cli/devices#cua-devices-enroll), [`approve`](/cua-cli/reference/cli/devices#cua-devices-approve), [`ls`](/cua-cli/reference/cli/devices#cua-devices-ls), [`rename`](/cua-cli/reference/cli/devices#cua-devices-rename), [`revoke`](/cua-cli/reference/cli/devices#cua-devices-revoke), [`audit`](/cua-cli/reference/cli/devices#cua-devices-audit) |
+### `cua team`
+
+Create a team, invite members, share machines with them, approve their devices and read the team audit log. [Reference](/cua-cli/reference/cli/team).
+
+| Command | Description | Subcommands |
+| --- | --- | --- |
+| <span id="cua-team-create"></span><span id="cua-team-ls"></span><span id="cua-team-show"></span><span id="cua-team-invite"></span><span id="cua-team-join"></span><span id="cua-team-leave"></span><span id="cua-team-remove-member"></span><span id="cua-team-set-role"></span><span id="cua-team-devices"></span><span id="cua-team-approve"></span><span id="cua-team-deny"></span><span id="cua-team-request"></span><span id="cua-team-add-machine"></span><span id="cua-team-remove-machine"></span><span id="cua-team-audit"></span><span id="cua-team-delete"></span>[`cua team`](/cua-cli/reference/cli/team#cua-team) | Teams: share machines with every member and their agents. | [`create`](/cua-cli/reference/cli/team#cua-team-create), [`ls`](/cua-cli/reference/cli/team#cua-team-ls), [`show`](/cua-cli/reference/cli/team#cua-team-show), [`invite`](/cua-cli/reference/cli/team#cua-team-invite), [`join`](/cua-cli/reference/cli/team#cua-team-join), [`leave`](/cua-cli/reference/cli/team#cua-team-leave), [`remove-member`](/cua-cli/reference/cli/team#cua-team-remove-member), [`set-role`](/cua-cli/reference/cli/team#cua-team-set-role), [`devices`](/cua-cli/reference/cli/team#cua-team-devices), [`approve`](/cua-cli/reference/cli/team#cua-team-approve), [`deny`](/cua-cli/reference/cli/team#cua-team-deny), [`request`](/cua-cli/reference/cli/team#cua-team-request), [`add-machine`](/cua-cli/reference/cli/team#cua-team-add-machine), [`remove-machine`](/cua-cli/reference/cli/team#cua-team-remove-machine), [`audit`](/cua-cli/reference/cli/team#cua-team-audit), [`delete`](/cua-cli/reference/cli/team#cua-team-delete) |
+
### `cua teleport`
Move a desktop app session into a sandbox. [Reference](/cua-cli/reference/cli/teleport).
diff --git a/docs/content/docs/cua-cli/reference/cli/meta.json b/docs/content/docs/cua-cli/reference/cli/meta.json
index aba6f49322..7c356af392 100644
--- a/docs/content/docs/cua-cli/reference/cli/meta.json
+++ b/docs/content/docs/cua-cli/reference/cli/meta.json
@@ -19,6 +19,7 @@
"cloud",
"host",
"devices",
+ "team",
"teleport",
"volume",
"keyvault",
diff --git a/docs/content/docs/cua-cli/reference/cli/team.mdx b/docs/content/docs/cua-cli/reference/cli/team.mdx
new file mode 100644
index 0000000000..43dfe8847c
--- /dev/null
+++ b/docs/content/docs/cua-cli/reference/cli/team.mdx
@@ -0,0 +1,384 @@
+---
+title: "cua team"
+description: "Create a team, invite members, share machines with them, approve their devices and read the team audit log."
+---
+
+{/*
+ AUTO-GENERATED FILE - DO NOT EDIT DIRECTLY
+ Generated by: pnpm --dir docs docs:generate:cua-cli
+ Source: cua dump-docs --type cli
+ Version: 0.4.1
+*/}
+
+| Command | Description |
+| --- | --- |
+| [`cua team create`](#cua-team-create) | Create a team; you are its owner. |
+| [`cua team ls`](#cua-team-ls) | Your teams, and email invites waiting for you. |
+| [`cua team show`](#cua-team-show) | A team: members, machines, open invites and devices. |
+| [`cua team invite`](#cua-team-invite) | Invite someone by email, or make a link anyone can join with. |
+| [`cua team join`](#cua-team-join) | Join a team with an invite link or code, or (with --team) the email invite for your account's email. |
+| [`cua team leave`](#cua-team-leave) | Leave a team. |
+| [`cua team remove-member`](#cua-team-remove-member) | Remove a member (owner or admin; admins cannot remove admins). |
+| [`cua team set-role`](#cua-team-set-role) | Make a member an admin, or an admin a member (owner). |
+| [`cua team devices`](#cua-team-devices) | Member devices and whether they may open team machines. |
+| [`cua team approve`](#cua-team-approve) | Approve a member device so it can open team machines. |
+| [`cua team deny`](#cua-team-deny) | Decline a member device (it can no longer open team machines). |
+| [`cua team request`](#cua-team-request) | Ask the team's admins to approve this device. |
+| [`cua team add-machine`](#cua-team-add-machine) | Make a Space (or a machine you host) a team machine: every member and their agents see it and can open it. |
+| [`cua team remove-machine`](#cua-team-remove-machine) | Take a machine off the team. |
+| [`cua team audit`](#cua-team-audit) | The team's audit log: joins, approvals, machines opened, changes. |
+| [`cua team delete`](#cua-team-delete) | Delete a team (owner). |
+
+Every command also accepts the [global options](/cua-cli/reference/cli#global-options).
+
+<span id="cua-team"></span>
+
+Teams: share machines with every member and their agents. Owners and admins invite (email or link), approve member devices, add machines and read the audit log.
+
+```text output
+cua team [OPTIONS] <COMMAND>
+```
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team"
+cua team create AIGIS
+cua team invite AIGIS [email protected]
+cua team add-machine AIGIS local:build-box
+cua team approve AIGIS dev_0123456789abcdef01234567
+cua team audit AIGIS
+```
+
+## `cua team create`
+
+Create a team; you are its owner.
+
+```text output
+cua team create [OPTIONS] <NAME>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<NAME>` | string | required | Team name. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-create"
+cua team create "AIGIS"
+```
+
+## `cua team ls`
+
+Your teams, and email invites waiting for you.
+
+```text output
+cua team ls [OPTIONS]
+```
+
+Alias: `cua team list`.
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-ls"
+cua team ls
+cua team ls --json
+```
+
+## `cua team show`
+
+A team: members, machines, open invites and devices.
+
+```text output
+cua team show [OPTIONS] <TEAM>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id (`team-…`) or name. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-show"
+cua team show AIGIS
+```
+
+## `cua team invite`
+
+Invite someone by email, or make a link anyone can join with.
+
+```text output
+cua team invite [OPTIONS] <TEAM> [EMAIL]
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id or name. |
+| `<EMAIL>` | string | optional | Their email (they join by signing in with it). |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-team-invite--role"></span>`--role` | `member` \| `admin` | `member` | `member` or `admin` (only the owner invites admins). |
+| <span id="cua-team-invite--link"></span>`--link` | boolean | `false` | Make a link instead (up to 25 joins, 7 days). |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-invite"
+cua team invite AIGIS [email protected]
+cua team invite AIGIS --link
+cua team invite AIGIS [email protected] --role admin
+```
+
+## `cua team join`
+
+Join a team with an invite link or code, or (with --team) the email invite for your account's email.
+
+```text output
+cua team join [OPTIONS] [CODE]
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<CODE>` | string | optional | The invite link or code. |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-team-join--team"></span>`--team` | string | | The team of an email invite. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-join"
+cua team join https://relay.cua.ai/join/team/team-0a1b….xyz
+cua team join --team team-0a1b2c3d4e5f6a7b
+```
+
+## `cua team leave`
+
+Leave a team.
+
+```text output
+cua team leave [OPTIONS] <TEAM>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id or name. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-leave"
+cua team leave AIGIS
+```
+
+## `cua team remove-member`
+
+Remove a member (owner or admin; admins cannot remove admins).
+
+```text output
+cua team remove-member [OPTIONS] <TEAM> <WHO>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id or name. |
+| `<WHO>` | string | required | Their email or account id. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-remove-member"
+cua team remove-member AIGIS [email protected]
+```
+
+## `cua team set-role`
+
+Make a member an admin, or an admin a member (owner).
+
+```text output
+cua team set-role [OPTIONS] <TEAM> <WHO> <ROLE>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id or name. |
+| `<WHO>` | string | required | Their email or account id. |
+| `<ROLE>` | `member` \| `admin` | required | `member` or `admin`. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-set-role"
+cua team set-role AIGIS [email protected] admin
+```
+
+## `cua team devices`
+
+Member devices and whether they may open team machines.
+
+```text output
+cua team devices [OPTIONS] <TEAM>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id or name. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-devices"
+cua team devices AIGIS
+```
+
+## `cua team approve`
+
+Approve a member device so it can open team machines.
+
+```text output
+cua team approve [OPTIONS] <TEAM> <DEVICE>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id or name. |
+| `<DEVICE>` | string | required | Device id (`cua team devices`). |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-approve"
+cua team approve AIGIS dev_0123456789abcdef01234567
+```
+
+## `cua team deny`
+
+Decline a member device (it can no longer open team machines).
+
+```text output
+cua team deny [OPTIONS] <TEAM> <DEVICE>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id or name. |
+| `<DEVICE>` | string | required | Device id. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-deny"
+cua team deny AIGIS dev_0123456789abcdef01234567
+```
+
+## `cua team request`
+
+Ask the team's admins to approve this device.
+
+```text output
+cua team request [OPTIONS] <TEAM>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id or name. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-request"
+cua team request AIGIS
+```
+
+## `cua team add-machine`
+
+Make a Space (or a machine you host) a team machine: every member and their agents see it and can open it. macOS Spaces cannot.
+
+```text output
+cua team add-machine [OPTIONS] <TEAM> <SPACE>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id or name. |
+| `<SPACE>` | string | required | Space id or name. |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-team-add-machine--yes"></span>`--yes` | boolean | `false` | Confirm without a prompt. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-add-machine"
+cua team add-machine AIGIS local:build-box
+cua team add-machine AIGIS relay:0123abcd4567ef89 --yes
+```
+
+## `cua team remove-machine`
+
+Take a machine off the team.
+
+```text output
+cua team remove-machine [OPTIONS] <TEAM> <MACHINE>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id or name. |
+| `<MACHINE>` | string | required | The machine (`relay:<id>` or its id, as `cua team show` lists it). |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-remove-machine"
+cua team remove-machine AIGIS relay:0123abcd4567ef89
+```
+
+## `cua team audit`
+
+The team's audit log: joins, approvals, machines opened, changes.
+
+```text output
+cua team audit [OPTIONS] <TEAM>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id or name. |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-team-audit--limit"></span>`--limit` | integer | `50` | Newest events to show. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-audit"
+cua team audit AIGIS --limit 50
+```
+
+## `cua team delete`
+
+Delete a team (owner). Its machines stay yours.
+
+```text output
+cua team delete [OPTIONS] <TEAM>
+```
+
+| Argument | Type | Default | Description |
+| --- | --- | --- | --- |
+| `<TEAM>` | string | required | Team id or name. |
+
+| Flag | Type | Default | Description |
+| --- | --- | --- | --- |
+| <span id="cua-team-delete--yes"></span>`--yes` | boolean | `false` | Do not ask for confirmation. |
+
+**Examples**
+
+```bash test="cli-shape" id="ref-cua-team-delete"
+cua team delete AIGIS --yes
+```
+
+## Exit codes
+
+| Code | Meaning |
+| --- | --- |
+| `0` | Success. |
+| `1` | Failure, or `cua do` reported an error. |
+| `2` | Invalid argument, or an ambiguous sandbox name (qualify it: `local:NAME`, `cloud:NAME`). |
+| `3` | Not found: sandbox, window, skill or image (or an image not published yet). |
+| `4` | Not supported, or not configured (for example no Fleet credentials). |
+| `5` | No cua-spacesd answered, or a transport failure. |
+| `6` | Unauthenticated or permission denied (by Cua, Fleet or your cloud account). |
+| `7` | Not enough free disk space (see `cua cache`). |
+| `130` | Cancelled (Ctrl-C during a create): what it made was removed. |
diff --git a/docs/content/docs/cua-cli/reference/index.mdx b/docs/content/docs/cua-cli/reference/index.mdx
index 082aeb0a52..8d6126a963 100644
--- a/docs/content/docs/cua-cli/reference/index.mdx
+++ b/docs/content/docs/cua-cli/reference/index.mdx
@@ -32,6 +32,7 @@ description: "Every cua command and every cua MCP tool, generated from the CLI d
| [`cua cloud`](/cua-cli/reference/cli/cloud) | Your own AWS, Google Cloud or Modal account as a place for sandboxes and Spaces: connect, test, status, sweep. |
| [`cua host`](/cua-cli/reference/cli/host) | Set this machine up for unattended access. |
| [`cua devices`](/cua-cli/reference/cli/devices) | Enroll this device on the relay, approve, rename and revoke devices, and read the access log. |
+| [`cua team`](/cua-cli/reference/cli/team) | Create a team, invite members, share machines with them, approve their devices and read the team audit log. |
| [`cua teleport`](/cua-cli/reference/cli/teleport) | Move a desktop app session into a sandbox. |
| [`cua volume`](/cua-cli/reference/cli/volume) | Cua Volume: files, versions, grants, access requests and audit of the volume every Space and agent shares. |
| [`cua keyvault`](/cua-cli/reference/cli/keyvault) | Set up, unlock and lock the Cua Keyvault, with the OS key store or a passphrase. |
diff --git a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
index b1275fef0a..6a28937652 100644
--- a/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
+++ b/docs/content/docs/cua-sdk/reference/rust/cua-spaces.mdx
@@ -1679,6 +1679,8 @@ impl Spaces {
fn share_audit(&self, space: Option<&str>, limit: usize) -> Result<Vec<ShareAudit>>;
async fn share_space(&self, space: &str, who: &str, role: ShareRole) -> Result<SpaceShares>;
async fn unshare_space(&self, space: &str, who: Option<&str>) -> Result<SpaceShares>;
+ async fn share_with_team(&self, space: &str, team: &str) -> Result<SpaceShares>;
+ async fn unshare_from_team(&self, space: &str, team: &str) -> Result<SpaceShares>;
async fn relay_register(&self, space: &str) -> Result<RelayRegistration>;
async fn relay_unregister(&self, space: &str) -> Result<bool>;
async fn space_shares(&self, space: &str) -> Result<SpaceShares>;
@@ -2256,6 +2258,8 @@ pub fn tool_result(resp: CallToolResponse) -> ToolResult
pub fn apply_share(allow: &mut Vec<String>, viewers: &mut Vec<String>, who: &str, role: Option<ShareRole>)
/// Normalizes an invitee: an email ...
pub fn normalize_who(who: &str) -> Result<String>
+/// The team a `team:<id>` invitee names ...
+pub fn team_of(who: &str) -> Option<Result<String>>
// mod site_login
/// The `request_site_login` tool: files a ...
@@ -2384,6 +2388,10 @@ pub const DRIVER_ALIASES: [&str; 5] = _;
pub const DRIVER_SERVICE: &str = "driver";
// mod share
+/// Why a macOS Space cannot be a team ...
+pub const MACOS_TEAM_REFUSED: &str = /* ... */;
+/// Relay machine meta: the OS of the Space ...
+pub const META_SPACE_OS: &str = "cua.space.os";
/// The spacesd feature a Space needs to be ...
pub const RELAY_ATTACH_FEATURE: &str = "relay_attach";
diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rs
index 36a332b4b9..3d932f8a6a 100644
--- a/libs/cua/crates/cua-cli/src/lib.rs
+++ b/libs/cua/crates/cua-cli/src/lib.rs
@@ -52,6 +52,7 @@ mod shell;
mod skills;
#[doc(hidden)]
pub mod stream_probe;
+mod team_cmd;
mod telemetry_cmd;
pub mod teleport;
pub mod teleport_session;
@@ -230,6 +231,19 @@ enum Command {
cua devices audit"
)]
Devices(devices_cmd::DevicesCmd),
+ /// Teams: share machines with every member and their agents. Owners
+ /// and admins invite (email or link), approve member devices, add
+ /// machines and read the audit log.
+ #[command(
+ subcommand,
+ after_help = "Examples:
+ cua team create AIGIS
+ cua team invite AIGIS [email protected]
+ cua team add-machine AIGIS local:build-box
+ cua team approve AIGIS dev_0123456789abcdef01234567
+ cua team audit AIGIS"
+ )]
+ Team(team_cmd::TeamCmd),
/// Move a desktop app session (tabs, profile, sign-in) into a sandbox.
#[command(subcommand)]
Teleport(teleport::TeleportCmd),
@@ -1665,6 +1679,25 @@ async fn run(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
Command::Devices(cmd) => {
return devices_cmd::run(cmd, &util::cua_home(), json, out).await;
}
+ // Adding a machine is sharing the Space with the team: the same
+ // path as `cua spaces share <space> team:<id>` (attach, confirm).
+ Command::Team(team_cmd::TeamCmd::AddMachine { team, space, yes }) => {
+ let auth = devices_cmd::device_auth(&host::relay_url(None, &util::cua_home()))?;
+ let id = team_cmd::resolve_team(&auth, &team).await?;
+ let share = Cli {
+ command: Command::Spaces(host::SpacesCmd::Share {
+ space,
+ who: format!("team:{id}"),
+ role: "editor".into(),
+ yes,
+ }),
+ ..cli
+ };
+ return Box::pin(run(share, out)).await;
+ }
+ Command::Team(cmd) => {
+ return team_cmd::run(cmd, &util::cua_home(), json, out).await;
+ }
// A machine that provides Spaces over its direct address: kept in
// this cua home's registry, which the daemon reads too.
Command::Spaces(cmd @ host::SpacesCmd::Add { host: true, .. }) => {
@@ -2052,6 +2085,7 @@ async fn run_sdk(cli: Cli, out: &mut dyn Write) -> Result<i32, CuaError> {
| Command::Spaces(_)
| Command::Cloud(_)
| Command::Devices(_)
+ | Command::Team(_)
| Command::Fleet(_)
| Command::Teleport(_)
| Command::Cache(_)
diff --git a/libs/cua/crates/cua-cli/src/team_cmd.rs b/libs/cua/crates/cua-cli/src/team_cmd.rs
new file mode 100644
index 0000000000..fa19728ac7
--- /dev/null
+++ b/libs/cua/crates/cua-cli/src/team_cmd.rs
@@ -0,0 +1,738 @@
+//! `cua team …`: teams on the relay. A team shares machines with every
+//! member (and their agents); owners and admins invite by email or link,
+//! remove members, add machines they own, approve each member device
+//! before it opens team machines, and read the team's audit log. macOS
+//! Spaces cannot be team machines (one user per macOS copy).
+//!
+//! Adding a Space is `cua team add-machine <team> <space>`, the same as
+//! `cua spaces share <space> team:<id>` (it attaches the Space to the relay
+//! first, and asks you to confirm); see `lib.rs`.
+
+use crate::util::{self, line};
+use clap::Subcommand;
+use cua_host::{DeviceAuth, Team, TeamRole};
+use cua_sdk::CuaError;
+use std::io::Write;
+use std::path::Path;
+
+#[derive(Subcommand, Debug, Clone)]
+pub enum TeamCmd {
+ /// Create a team; you are its owner.
+ #[command(after_help = "Examples:
+ cua team create \"AIGIS\"")]
+ Create {
+ /// Team name.
+ name: String,
+ },
+ /// Your teams, and email invites waiting for you.
+ #[command(
+ visible_alias = "list",
+ after_help = "Examples:
+ cua team ls
+ cua team ls --json"
+ )]
+ Ls,
+ /// A team: members, machines, open invites and devices.
+ #[command(after_help = "Examples:
+ cua team show AIGIS")]
+ Show {
+ /// Team id (`team-…`) or name.
+ team: String,
+ },
+ /// Invite someone by email, or make a link anyone can join with.
+ #[command(after_help = "Examples:
+ cua team invite AIGIS [email protected]
+ cua team invite AIGIS --link
+ cua team invite AIGIS [email protected] --role admin")]
+ Invite {
+ /// Team id or name.
+ team: String,
+ /// Their email (they join by signing in with it).
+ #[arg(required_unless_present = "link", conflicts_with = "link")]
+ email: Option<String>,
+ /// Make a link instead (up to 25 joins, 7 days).
+ #[arg(long)]
+ link: bool,
+ /// `member` or `admin` (only the owner invites admins).
+ #[arg(long, default_value = "member", value_parser = ["member", "admin"])]
+ role: String,
+ },
+ /// Join a team with an invite link or code, or (with --team) the email
+ /// invite for your account's email.
+ #[command(after_help = "Examples:
+ cua team join https://relay.cua.ai/join/team/team-0a1b….xyz
+ cua team join --team team-0a1b2c3d4e5f6a7b")]
+ Join {
+ /// The invite link or code.
+ #[arg(required_unless_present = "team")]
+ code: Option<String>,
+ /// The team of an email invite.
+ #[arg(long, conflicts_with = "code")]
+ team: Option<String>,
+ },
+ /// Leave a team.
+ #[command(after_help = "Examples:
+ cua team leave AIGIS")]
+ Leave {
+ /// Team id or name.
+ team: String,
+ },
+ /// Remove a member (owner or admin; admins cannot remove admins).
+ #[command(after_help = "Examples:
+ cua team remove-member AIGIS [email protected]")]
+ RemoveMember {
+ /// Team id or name.
+ team: String,
+ /// Their email or account id.
+ who: String,
+ },
+ /// Make a member an admin, or an admin a member (owner).
+ #[command(after_help = "Examples:
+ cua team set-role AIGIS [email protected] admin")]
+ SetRole {
+ /// Team id or name.
+ team: String,
+ /// Their email or account id.
+ who: String,
+ /// `member` or `admin`.
+ #[arg(value_parser = ["member", "admin"])]
+ role: String,
+ },
+ /// Member devices and whether they may open team machines.
+ #[command(after_help = "Examples:
+ cua team devices AIGIS")]
+ Devices {
+ /// Team id or name.
+ team: String,
+ },
+ /// Approve a member device so it can open team machines.
+ #[command(after_help = "Examples:
+ cua team approve AIGIS dev_0123456789abcdef01234567")]
+ Approve {
+ /// Team id or name.
+ team: String,
+ /// Device id (`cua team devices`).
+ device: String,
+ },
+ /// Decline a member device (it can no longer open team machines).
+ #[command(after_help = "Examples:
+ cua team deny AIGIS dev_0123456789abcdef01234567")]
+ Deny {
+ /// Team id or name.
+ team: String,
+ /// Device id.
+ device: String,
+ },
+ /// Ask the team's admins to approve this device.
+ #[command(after_help = "Examples:
+ cua team request AIGIS")]
+ Request {
+ /// Team id or name.
+ team: String,
+ },
+ /// Make a Space (or a machine you host) a team machine: every member
+ /// and their agents see it and can open it. macOS Spaces cannot.
+ #[command(after_help = "Examples:
+ cua team add-machine AIGIS local:build-box
+ cua team add-machine AIGIS relay:0123abcd4567ef89 --yes")]
+ AddMachine {
+ /// Team id or name.
+ team: String,
+ /// Space id or name.
+ space: String,
+ /// Confirm without a prompt.
+ #[arg(long)]
+ yes: bool,
+ },
+ /// Take a machine off the team.
+ #[command(after_help = "Examples:
+ cua team remove-machine AIGIS relay:0123abcd4567ef89")]
+ RemoveMachine {
+ /// Team id or name.
+ team: String,
+ /// The machine (`relay:<id>` or its id, as `cua team show` lists it).
+ machine: String,
+ },
+ /// The team's audit log: joins, approvals, machines opened, changes.
+ #[command(after_help = "Examples:
+ cua team audit AIGIS --limit 50")]
+ Audit {
+ /// Team id or name.
+ team: String,
+ /// Newest events to show.
+ #[arg(long, default_value_t = 50)]
+ limit: usize,
+ },
+ /// Delete a team (owner). Its machines stay yours.
+ #[command(after_help = "Examples:
+ cua team delete AIGIS --yes")]
+ Delete {
+ /// Team id or name.
+ team: String,
+ /// Do not ask for confirmation.
+ #[arg(long)]
+ yes: bool,
+ },
+}
+
+impl TeamCmd {
+ /// The team argument, if the command has one.
+ pub fn team_arg(&self) -> Option<&str> {
+ match self {
+ TeamCmd::Show { team }
+ | TeamCmd::Invite { team, .. }
+ | TeamCmd::Leave { team }
+ | TeamCmd::RemoveMember { team, .. }
+ | TeamCmd::SetRole { team, .. }
+ | TeamCmd::Devices { team }
+ | TeamCmd::Approve { team, .. }
+ | TeamCmd::Deny { team, .. }
+ | TeamCmd::Request { team }
+ | TeamCmd::AddMachine { team, .. }
+ | TeamCmd::RemoveMachine { team, .. }
+ | TeamCmd::Audit { team, .. }
+ | TeamCmd::Delete { team, .. } => Some(team),
+ TeamCmd::Create { .. } | TeamCmd::Ls | TeamCmd::Join { .. } => None,
+ }
+ }
+}
+
+fn err(e: cua_host::Error) -> CuaError {
+ crate::host::host_err(e)
+}
+
+/// The team id `query` names: an id as is, else the one team of yours
+/// with that name (case-insensitive).
+pub async fn resolve_team(auth: &DeviceAuth, query: &str) -> Result<String, CuaError> {
+ let q = query.trim();
+ let q = q.strip_prefix("team:").unwrap_or(q);
+ if q.starts_with("team-") {
+ return Ok(q.to_string());
+ }
+ let list = auth.teams().await.map_err(err)?;
+ let matches: Vec<_> = list
+ .teams
+ .iter()
+ .filter(|t| t.name.eq_ignore_ascii_case(q))
+ .collect();
+ match matches.as_slice() {
+ [t] => Ok(t.id.clone()),
+ [] => Err(CuaError::NotFound(format!(
+ "no team of yours is called {q:?} (`cua team ls`)"
+ ))),
+ _ => Err(CuaError::InvalidArgument(format!(
+ "several of your teams are called {q:?}: use the team id (`cua team ls`)"
+ ))),
+ }
+}
+
+fn when(ts: u64) -> String {
+ chrono::DateTime::<chrono::Utc>::from_timestamp(ts as i64, 0)
+ .map(|d| d.format("%Y-%m-%d %H:%M UTC").to_string())
+ .unwrap_or_else(|| "-".into())
+}
+
+fn emit_json(out: &mut dyn Write, v: &impl serde::Serialize) {
+ line(out, serde_json::to_string(v).unwrap_or_default());
+}
+
+fn print_team(t: &Team, out: &mut dyn Write) {
+ line(
+ out,
+ format!("{} ({}), you are {}", t.name, t.id, t.role.as_str()),
+ );
+ line(out, format!("Members ({}):", t.members.len()));
+ for m in &t.members {
+ line(out, format!(" {} {}", m.label(), m.role.as_str()));
+ }
+ line(out, format!("Machines ({}):", t.machines.len()));
+ if t.machines.is_empty() {
+ line(
+ out,
+ " none yet: `cua team add-machine <team> <space>` (owner or admin)",
+ );
+ }
+ for m in &t.machines {
+ line(
+ out,
+ format!(
+ " relay:{} {} (owner {}{})",
+ m.id,
+ if m.name.is_empty() { "-" } else { &m.name },
+ m.owner,
+ if m.online { ", online" } else { ", offline" }
+ ),
+ );
+ }
+ if !t.invites.is_empty() {
+ line(out, "Open invites:");
+ for i in &t.invites {
+ line(
+ out,
+ format!(
+ " {} {} as {}, expires {}",
+ i.id,
+ i.email.as_deref().unwrap_or("link"),
+ i.role.as_str(),
+ when(i.expires_at)
+ ),
+ );
+ }
+ }
+ print_devices(t, out);
+ if let Some(state) = &t.this_device {
+ line(out, format!("This device: {state}"));
+ }
+}
+
+fn print_devices(t: &Team, out: &mut dyn Write) {
+ if t.devices.is_empty() {
+ return;
+ }
+ line(out, "Devices:");
+ for d in &t.devices {
+ line(
+ out,
+ format!(
+ " {} {} {}{}",
+ d.device,
+ d.email.as_deref().unwrap_or(&d.account),
+ d.state,
+ if d.name.is_empty() {
+ String::new()
+ } else {
+ format!(" ({})", d.name)
+ }
+ ),
+ );
+ }
+ if t.role.manages() && t.devices.iter().any(|d| d.state == "pending") {
+ line(
+ out,
+ format!("Approve one with `cua team approve {} <device>`.", t.id),
+ );
+ }
+}
+
+/// Runs `cmd` (all but `add-machine`, which goes through Spaces) for this
+/// device. `confirm` answers the delete prompt.
+pub async fn run_with(
+ cmd: TeamCmd,
+ auth: &DeviceAuth,
+ confirm: &dyn Fn(&str) -> bool,
+ json: bool,
+ out: &mut dyn Write,
+) -> Result<i32, CuaError> {
+ let team = match cmd.team_arg() {
+ Some(q) if !matches!(cmd, TeamCmd::AddMachine { .. }) => Some(resolve_team(auth, q).await?),
+ _ => None,
+ };
+ let id = || team.clone().unwrap_or_default();
+ match cmd {
+ TeamCmd::Create { name } => {
+ let t = auth.create_team(&name).await.map_err(err)?;
+ if json {
+ emit_json(out, &t);
+ } else {
+ line(out, format!("Created team {} ({}).", t.name, t.id));
+ line(out, "Next:");
+ line(
+ out,
+ format!(" cua team invite {} <email> (or --link)", t.id),
+ );
+ line(out, format!(" cua team add-machine {} <space>", t.id));
+ }
+ }
+ TeamCmd::Ls => {
+ let l = auth.teams().await.map_err(err)?;
+ if json {
+ emit_json(out, &l);
+ return Ok(0);
+ }
+ if l.teams.is_empty() {
+ line(
+ out,
+ "You are in no team. Create one with `cua team create <name>`.",
+ );
+ }
+ for t in &l.teams {
+ line(
+ out,
+ format!(
+ "{} {} {} {} members, {} machines{}",
+ t.id,
+ t.name,
+ t.role.as_str(),
+ t.members.len(),
+ t.machines.len(),
+ match t.this_device.as_deref() {
+ Some("approved") | None => String::new(),
+ Some(s) => format!(", this device {s}"),
+ }
+ ),
+ );
+ }
+ for i in &l.invites {
+ line(
+ out,
+ format!(
+ "Invited to {} ({}) as {}: `cua team join --team {}`",
+ i.team_name,
+ i.team,
+ i.invite.role.as_str(),
+ i.team
+ ),
+ );
+ }
+ }
+ TeamCmd::Show { .. } => {
+ let t = auth.team(&id()).await.map_err(err)?;
+ if json {
+ emit_json(out, &t);
+ } else {
+ print_team(&t, out);
+ }
+ }
+ TeamCmd::Invite {
+ email, link, role, ..
+ } => {
+ let role = TeamRole::parse(&role).map_err(err)?;
+ let email = if link { None } else { email };
+ let n = auth
+ .invite_to_team(&id(), email.as_deref(), role)
+ .await
+ .map_err(err)?;
+ if json {
+ emit_json(out, &n);
+ } else {
+ match &n.invite.email {
+ Some(e) => {
+ line(
+ out,
+ format!(
+ "Invited {e} as {}. Send them this link (it works only when they sign in as {e}), expires {}:",
+ role.as_str(),
+ when(n.invite.expires_at)
+ ),
+ );
+ }
+ None => line(
+ out,
+ format!(
+ "Invite link ({} joins, as {}, expires {}). Anyone with it can join; admins then approve their device:",
+ n.invite.uses_left,
+ role.as_str(),
+ when(n.invite.expires_at)
+ ),
+ ),
+ }
+ line(out, format!(" {}", n.link));
+ line(out, format!("They run: cua team join {}", n.link));
+ }
+ }
+ TeamCmd::Join { code, team } => {
+ let t = auth
+ .join_team(code.as_deref(), team.as_deref())
+ .await
+ .map_err(err)?;
+ if json {
+ emit_json(out, &t);
+ } else {
+ line(
+ out,
+ format!("You joined {} ({}) as {}.", t.name, t.id, t.role.as_str()),
+ );
+ match t.this_device.as_deref() {
+ Some("approved") => line(out, "This device can open the team's machines."),
+ Some(_) => line(
+ out,
+ "This device waits for a team admin's approval before it can open the team's machines.",
+ ),
+ None => line(
+ out,
+ format!(
+ "Enroll this device (`cua devices enroll`), then ask for approval: `cua team request {}`.",
+ t.id
+ ),
+ ),
+ }
+ }
+ }
+ TeamCmd::Leave { .. } => {
+ auth.leave_team(&id()).await.map_err(err)?;
+ if !json {
+ line(out, format!("You left {}.", id()));
+ }
+ }
+ TeamCmd::RemoveMember { who, .. } => {
+ auth.remove_team_member(&id(), &who).await.map_err(err)?;
+ if !json {
+ line(
+ out,
+ format!("Removed {who}: their open sessions on team machines ended."),
+ );
+ }
+ }
+ TeamCmd::SetRole { who, role, .. } => {
+ let role = TeamRole::parse(&role).map_err(err)?;
+ let m = auth.set_team_role(&id(), &who, role).await.map_err(err)?;
+ if json {
+ emit_json(out, &m);
+ } else {
+ line(out, format!("{} is now {}.", m.label(), m.role.as_str()));
+ }
+ }
+ TeamCmd::Devices { .. } => {
+ let t = auth.team(&id()).await.map_err(err)?;
+ if json {
+ emit_json(out, &t.devices);
+ } else if t.devices.is_empty() {
+ line(out, "No member device has asked yet.");
+ } else {
+ print_devices(&t, out);
+ }
+ }
+ TeamCmd::Approve { device, .. } => decide(auth, &id(), &device, true, json, out).await?,
+ TeamCmd::Deny { device, .. } => decide(auth, &id(), &device, false, json, out).await?,
+ TeamCmd::Request { .. } => {
+ let d = auth.request_team_device(&id()).await.map_err(err)?;
+ if json {
+ emit_json(out, &d);
+ } else {
+ line(out, format!("This device ({}): {}.", d.device, d.state));
+ }
+ }
+ TeamCmd::AddMachine { .. } => {
+ return Err(CuaError::Internal("add-machine runs through Spaces".into()));
+ }
+ TeamCmd::RemoveMachine { machine, .. } => {
+ let m = machine.trim();
+ let m = m.strip_prefix("relay:").unwrap_or(m);
+ let t = auth.remove_team_machine(&id(), m).await.map_err(err)?;
+ if json {
+ emit_json(out, &t);
+ } else {
+ line(
+ out,
+ format!("relay:{m} is no longer a machine of {}.", t.name),
+ );
+ }
+ }
+ TeamCmd::Audit { limit, .. } => {
+ let events = auth.team_audit(&id(), limit).await.map_err(err)?;
+ if json {
+ emit_json(out, &events);
+ return Ok(0);
+ }
+ for e in &events {
+ let mut parts = vec![when(e.ts), e.kind.clone(), e.actor.clone()];
+ parts.extend(e.subject.clone());
+ parts.extend(e.machine.as_ref().map(|m| format!("relay:{m}")));
+ parts.extend(e.detail.clone());
+ parts.extend(e.device.as_ref().map(|d| format!("from {d}")));
+ line(out, parts.join(" "));
+ }
+ }
+ TeamCmd::Delete { yes, .. } => {
+ if !yes && !confirm(&format!("Delete team {}? Members lose its machines.", id())) {
+ return Err(CuaError::InvalidArgument(
+ "not deleted (pass --yes when not in a terminal)".into(),
+ ));
+ }
+ auth.delete_team(&id()).await.map_err(err)?;
+ if !json {
+ line(out, format!("Deleted {}.", id()));
+ }
+ }
+ }
+ Ok(0)
+}
+
+async fn decide(
+ auth: &DeviceAuth,
+ team: &str,
+ device: &str,
+ approve: bool,
+ json: bool,
+ out: &mut dyn Write,
+) -> Result<(), CuaError> {
+ let d = auth
+ .decide_team_device(team, device.trim(), approve)
+ .await
+ .map_err(err)?;
+ if json {
+ emit_json(out, &d);
+ } else if approve {
+ line(
+ out,
+ format!(
+ "Approved {} ({}): it can open the team's machines.",
+ d.device,
+ d.email.as_deref().unwrap_or(&d.account)
+ ),
+ );
+ } else {
+ line(out, format!("Declined {}.", d.device));
+ }
+ Ok(())
+}
+
+/// `cua team …` (all but `add-machine`).
+pub async fn run(
+ cmd: TeamCmd,
+ home: &Path,
+ json: bool,
+ out: &mut dyn Write,
+) -> Result<i32, CuaError> {
+ let auth = crate::devices_cmd::device_auth(&crate::host::relay_url(None, home))?;
+ run_with(
+ cmd,
+ &auth,
+ &|q| util::interactive() && util::confirm(q, false),
+ json,
+ out,
+ )
+ .await
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cua_host::testing::FakeRelay;
+ use cua_host::{MemoryKeySlot, StaticToken};
+ use std::sync::Arc;
+
+ async fn enrolled(relay: &FakeRelay, token: &str, account: &str) -> DeviceAuth {
+ relay.fresh_sign_in(account);
+ let auth = DeviceAuth::new(
+ &relay.url,
+ Arc::new(StaticToken(token.into())),
+ Arc::new(MemoryKeySlot::default()),
+ format!("{account} laptop"),
+ )
+ .unwrap()
+ .with_machine_id(Some(format!("machine-of-{account}")));
+ auth.enroll().await.unwrap();
+ auth
+ }
+
+ async fn text(cmd: TeamCmd, auth: &DeviceAuth) -> Result<String, CuaError> {
+ let mut out = Vec::new();
+ run_with(cmd, auth, &|_| true, false, &mut out).await?;
+ Ok(String::from_utf8(out).unwrap())
+ }
+
+ #[tokio::test]
+ async fn create_invite_join_approve_and_audit() {
+ let relay = FakeRelay::start().await;
+ relay.add_account("t-ada", "ada", Some("[email protected]"));
+ relay.add_account("t-bob", "bob", Some("[email protected]"));
+ relay.require_devices(true);
+ let ada = enrolled(&relay, "t-ada", "ada").await;
+ let bob = enrolled(&relay, "t-bob", "bob").await;
+
+ let t = text(
+ TeamCmd::Create {
+ name: "AIGIS".into(),
+ },
+ &ada,
+ )
+ .await
+ .unwrap();
+ assert!(t.contains("Created team AIGIS (team-"), "{t}");
+ // Teams resolve by name.
+ let t = text(
+ TeamCmd::Invite {
+ team: "aigis".into(),
+ email: None,
+ link: true,
+ role: "member".into(),
+ },
+ &ada,
+ )
+ .await
+ .unwrap();
+ let link = t
+ .lines()
+ .find_map(|l| l.trim().strip_prefix("They run: cua team join "))
+ .expect("a join line")
+ .to_string();
+ assert!(link.contains("/join/team/"), "{link}");
+
+ let t = text(
+ TeamCmd::Join {
+ code: Some(link),
+ team: None,
+ },
+ &bob,
+ )
+ .await
+ .unwrap();
+ assert!(t.contains("You joined AIGIS"), "{t}");
+ assert!(t.contains("waits for a team admin's approval"), "{t}");
+
+ // A member cannot approve; the owner sees the device and approves.
+ let bob_device = bob.device_id().unwrap().unwrap();
+ let refused = text(
+ TeamCmd::Approve {
+ team: "AIGIS".into(),
+ device: bob_device.clone(),
+ },
+ &bob,
+ )
+ .await
+ .unwrap_err();
+ assert!(
+ matches!(refused, CuaError::PermissionDenied(_)),
+ "{refused:?}"
+ );
+ let t = text(
+ TeamCmd::Devices {
+ team: "AIGIS".into(),
+ },
+ &ada,
+ )
+ .await
+ .unwrap();
+ assert!(t.contains(&bob_device) && t.contains("pending"), "{t}");
+ let t = text(
+ TeamCmd::Approve {
+ team: "AIGIS".into(),
+ device: bob_device.clone(),
+ },
+ &ada,
+ )
+ .await
+ .unwrap();
+ assert!(t.contains("Approved"), "{t}");
+
+ let t = text(TeamCmd::Ls, &bob).await.unwrap();
+ assert!(t.contains("AIGIS member"), "{t}");
+ let t = text(
+ TeamCmd::Audit {
+ team: "AIGIS".into(),
+ limit: 50,
+ },
+ &ada,
+ )
+ .await
+ .unwrap();
+ for k in [
+ "team_created",
+ "invite_created",
+ "member_joined",
+ "device_approved",
+ ] {
+ assert!(t.contains(k), "{k} in {t}");
+ }
+ let e = text(
+ TeamCmd::Show {
+ team: "nope".into(),
+ },
+ &ada,
+ )
+ .await
+ .unwrap_err();
+ assert!(matches!(e, CuaError::NotFound(_)), "{e:?}");
+ }
+}
diff --git a/libs/cua/crates/cua-host/src/device.rs b/libs/cua/crates/cua-host/src/device.rs
index ee1fc3e11d..4ff5b47141 100644
--- a/libs/cua/crates/cua-host/src/device.rs
+++ b/libs/cua/crates/cua-host/src/device.rs
@@ -596,7 +596,7 @@ impl DeviceAuth {
/// identically on the retry (its session fails for the same reason
/// again), so this never masks a real enrollment problem: it only
/// costs one extra round trip, and only right after a restart.
- async fn with_session_retry<T, Fut>(
+ pub(crate) async fn with_session_retry<T, Fut>(
&self,
call: impl Fn(RelayClient, String) -> Fut,
) -> Result<T>
diff --git a/libs/cua/crates/cua-host/src/lib.rs b/libs/cua/crates/cua-host/src/lib.rs
index 0ca0f7a844..05cc747274 100644
--- a/libs/cua/crates/cua-host/src/lib.rs
+++ b/libs/cua/crates/cua-host/src/lib.rs
@@ -43,6 +43,7 @@ pub mod relay;
pub mod service;
#[cfg(test)]
mod setup_tests;
+pub mod team;
#[cfg(any(test, feature = "testing"))]
pub mod testing;
#[cfg(test)]
@@ -65,6 +66,10 @@ pub use relay::{
relay_url_from_env,
};
pub use service::{RunnerKind, ServiceManager, ServiceSpec, ServiceState};
+pub use team::{
+ NewTeamInvite, Team, TeamAuditEvent, TeamDevice, TeamInvite, TeamList, TeamMachine, TeamMember,
+ TeamRole, team_code_from_link,
+};
/// The default display name of this device: the macOS Computer Name, else
/// the host name without a `.local` / `.localdomain` suffix.
diff --git a/libs/cua/crates/cua-host/src/relay.rs b/libs/cua/crates/cua-host/src/relay.rs
index 28b73d0f64..6fe0b0b9e4 100644
--- a/libs/cua/crates/cua-host/src/relay.rs
+++ b/libs/cua/crates/cua-host/src/relay.rs
@@ -181,6 +181,10 @@ pub struct Machine {
/// never retroactively flagged "new".
#[serde(default = "confirmed_default")]
pub confirmed: bool,
+ /// The team the caller reaches this machine through (`team-…`), when
+ /// it is a team machine and not shared with the caller directly.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub team: Option<String>,
}
fn confirmed_default() -> bool {
@@ -409,7 +413,7 @@ const REGISTER_RETRY_BASE: Duration = Duration::from_millis(5);
#[derive(Clone, Debug)]
pub struct RelayClient {
base: String,
- http: reqwest::Client,
+ pub(crate) http: reqwest::Client,
device_session: Option<String>,
}
@@ -446,11 +450,11 @@ impl RelayClient {
format!("{}/m/{id}", self.base)
}
- fn url(&self, path: &str) -> String {
+ pub(crate) fn url(&self, path: &str) -> String {
format!("{}{path}", self.base)
}
- async fn send<T: serde::de::DeserializeOwned>(
+ pub(crate) async fn send<T: serde::de::DeserializeOwned>(
&self,
req: reqwest::RequestBuilder,
bearer: &str,
diff --git a/libs/cua/crates/cua-host/src/team.rs b/libs/cua/crates/cua-host/src/team.rs
new file mode 100644
index 0000000000..79d5415aec
--- /dev/null
+++ b/libs/cua/crates/cua-host/src/team.rs
@@ -0,0 +1,567 @@
+//! Teams on the relay: a named group of cua.ai accounts with roles
+//! (`owner`, `admin`, `member`) that shares machines with every member.
+//! Owners and admins invite (by email or link), remove members, add
+//! machines they own, approve member devices (a member device opens team
+//! machines only once approved) and read the team's audit log. macOS
+//! Spaces cannot be team machines (one user per macOS copy).
+//!
+//! [`RelayClient`] has the raw calls (account token, from an enrolled
+//! device's session); [`DeviceAuth`] wraps them with this device's session.
+
+use crate::Result;
+use crate::device::DeviceAuth;
+use crate::relay::RelayClient;
+use serde::{Deserialize, Serialize};
+use serde_json::json;
+
+/// A member's role.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum TeamRole {
+ #[default]
+ Member,
+ Admin,
+ Owner,
+}
+
+impl TeamRole {
+ /// `owner` / `admin` / `member`.
+ pub fn as_str(self) -> &'static str {
+ match self {
+ TeamRole::Owner => "owner",
+ TeamRole::Admin => "admin",
+ TeamRole::Member => "member",
+ }
+ }
+
+ /// Parses `member` / `admin`.
+ pub fn parse(s: &str) -> Result<TeamRole> {
+ match s.trim().to_ascii_lowercase().as_str() {
+ "member" => Ok(TeamRole::Member),
+ "admin" => Ok(TeamRole::Admin),
+ other => Err(crate::Error::InvalidArgument(format!(
+ "team role {other:?}: use member or admin"
+ ))),
+ }
+ }
+
+ /// Owners and admins manage the team.
+ pub fn manages(self) -> bool {
+ matches!(self, TeamRole::Owner | TeamRole::Admin)
+ }
+}
+
+/// One member.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamMember {
+ pub account: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub email: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub name: Option<String>,
+ pub role: TeamRole,
+ #[serde(default)]
+ pub joined_at: u64,
+}
+
+impl TeamMember {
+ /// Email when known, else the account id.
+ pub fn label(&self) -> &str {
+ self.email.as_deref().unwrap_or(&self.account)
+ }
+}
+
+/// A team machine.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamMachine {
+ pub id: String,
+ #[serde(default)]
+ pub name: String,
+ /// The owner's email (or account id).
+ #[serde(default)]
+ pub owner: String,
+ #[serde(default)]
+ pub online: bool,
+}
+
+/// An open invite (never its code).
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamInvite {
+ pub id: String,
+ /// Only this email may use it; a link invite otherwise.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub email: Option<String>,
+ pub role: TeamRole,
+ #[serde(default)]
+ pub expires_at: u64,
+ #[serde(default)]
+ pub uses_left: u32,
+}
+
+/// A member device and its approval: `pending`, `approved`, `denied`.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamDevice {
+ pub account: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub email: Option<String>,
+ pub device: String,
+ #[serde(default)]
+ pub name: String,
+ pub state: String,
+ #[serde(default)]
+ pub requested_at: u64,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub decided_by: Option<String>,
+}
+
+/// A team as one of its members sees it.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Team {
+ pub id: String,
+ pub name: String,
+ /// The caller's role.
+ pub role: TeamRole,
+ #[serde(default)]
+ pub created_at: u64,
+ #[serde(default)]
+ pub members: Vec<TeamMember>,
+ #[serde(default)]
+ pub machines: Vec<TeamMachine>,
+ /// Open invites (owner/admin view).
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub invites: Vec<TeamInvite>,
+ /// Member devices (owner/admin: all; member: their own).
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub devices: Vec<TeamDevice>,
+ /// This device's approval (`pending`, `approved`, `denied`), if known.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub this_device: Option<String>,
+}
+
+/// An email invite waiting for the caller.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct PendingTeamInvite {
+ pub team: String,
+ #[serde(default)]
+ pub team_name: String,
+ pub invite: TeamInvite,
+}
+
+/// `GET /v1/teams`.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamList {
+ #[serde(default)]
+ pub teams: Vec<Team>,
+ /// Email invites for the caller's verified email.
+ #[serde(default)]
+ pub invites: Vec<PendingTeamInvite>,
+}
+
+/// A new invite: its code and link are shown once.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct NewTeamInvite {
+ pub invite: TeamInvite,
+ pub code: String,
+ pub link: String,
+}
+
+/// One team audit line.
+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
+pub struct TeamAuditEvent {
+ pub ts: u64,
+ pub kind: String,
+ #[serde(default)]
+ pub actor: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub device: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub subject: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub machine: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub detail: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct AuditList {
+ #[serde(default)]
+ events: Vec<TeamAuditEvent>,
+}
+
+/// The invite code in a pasted link (`…/join/team/<code>`) or the code
+/// itself.
+pub fn team_code_from_link(s: &str) -> String {
+ let s = s.trim();
+ s.rsplit_once("/join/team/")
+ .map(|(_, c)| c)
+ .unwrap_or(s)
+ .trim_end_matches('/')
+ .to_string()
+}
+
+fn seg(s: &str) -> String {
+ url::form_urlencoded::byte_serialize(s.as_bytes())
+ .collect::<String>()
+ .replace('+', "%20")
+}
+
+impl RelayClient {
+ /// Your teams and the email invites waiting for you.
+ pub async fn teams(&self, token: &str) -> Result<TeamList> {
+ self.send(self.http.get(self.url("/v1/teams")), token).await
+ }
+
+ /// One team you are in.
+ pub async fn team(&self, token: &str, id: &str) -> Result<Team> {
+ self.send(
+ self.http.get(self.url(&format!("/v1/teams/{}", seg(id)))),
+ token,
+ )
+ .await
+ }
+
+ /// Creates a team; you are its owner.
+ pub async fn create_team(&self, token: &str, name: &str) -> Result<Team> {
+ self.send(
+ self.http
+ .post(self.url("/v1/teams"))
+ .json(&json!({ "name": name })),
+ token,
+ )
+ .await
+ }
+
+ /// Deletes a team (owner).
+ pub async fn delete_team(&self, token: &str, id: &str) -> Result<()> {
+ let _: serde_json::Value = self
+ .send(
+ self.http
+ .delete(self.url(&format!("/v1/teams/{}", seg(id)))),
+ token,
+ )
+ .await?;
+ Ok(())
+ }
+
+ /// Joins with an invite `code` (or link), or, with `team` and no code,
+ /// the email invite for your verified email.
+ pub async fn join_team(
+ &self,
+ token: &str,
+ code: Option<&str>,
+ team: Option<&str>,
+ ) -> Result<Team> {
+ self.send(
+ self.http.post(self.url("/v1/teams/join")).json(&json!({
+ "code": code.map(team_code_from_link),
+ "team": team,
+ })),
+ token,
+ )
+ .await
+ }
+
+ /// Leaves a team.
+ pub async fn leave_team(&self, token: &str, id: &str) -> Result<()> {
+ let _: serde_json::Value = self
+ .send(
+ self.http
+ .post(self.url(&format!("/v1/teams/{}/leave", seg(id))))
+ .json(&json!({})),
+ token,
+ )
+ .await?;
+ Ok(())
+ }
+
+ /// Invites `email` (or, without one, makes a link) as `role`.
+ pub async fn invite_to_team(
+ &self,
+ token: &str,
+ id: &str,
+ email: Option<&str>,
+ role: TeamRole,
+ ) -> Result<NewTeamInvite> {
+ self.send(
+ self.http
+ .post(self.url(&format!("/v1/teams/{}/invites", seg(id))))
+ .json(&json!({ "email": email, "role": role })),
+ token,
+ )
+ .await
+ }
+
+ /// Revokes an open invite.
+ pub async fn revoke_team_invite(&self, token: &str, id: &str, invite: &str) -> Result<()> {
+ let _: serde_json::Value = self
+ .send(
+ self.http.delete(self.url(&format!(
+ "/v1/teams/{}/invites/{}",
+ seg(id),
+ seg(invite)
+ ))),
+ token,
+ )
+ .await?;
+ Ok(())
+ }
+
+ /// Makes a member an admin or a member (owner).
+ pub async fn set_team_role(
+ &self,
+ token: &str,
+ id: &str,
+ who: &str,
+ role: TeamRole,
+ ) -> Result<TeamMember> {
+ self.send(
+ self.http
+ .patch(self.url(&format!("/v1/teams/{}/members/{}", seg(id), seg(who))))
+ .json(&json!({ "role": role })),
+ token,
+ )
+ .await
+ }
+
+ /// Removes a member (email or account id).
+ pub async fn remove_team_member(&self, token: &str, id: &str, who: &str) -> Result<()> {
+ let _: serde_json::Value = self
+ .send(
+ self.http
+ .delete(self.url(&format!("/v1/teams/{}/members/{}", seg(id), seg(who)))),
+ token,
+ )
+ .await?;
+ Ok(())
+ }
+
+ /// Asks the team's admins to approve this device.
+ pub async fn request_team_device(&self, token: &str, id: &str) -> Result<TeamDevice> {
+ self.send(
+ self.http
+ .post(self.url(&format!("/v1/teams/{}/devices/request", seg(id))))
+ .json(&json!({})),
+ token,
+ )
+ .await
+ }
+
+ /// Approves (or denies) a member device (owner/admin).
+ pub async fn decide_team_device(
+ &self,
+ token: &str,
+ id: &str,
+ device: &str,
+ approve: bool,
+ ) -> Result<TeamDevice> {
+ self.send(
+ self.http
+ .post(self.url(&format!(
+ "/v1/teams/{}/devices/{}/{}",
+ seg(id),
+ seg(device),
+ if approve { "approve" } else { "deny" }
+ )))
+ .json(&json!({})),
+ token,
+ )
+ .await
+ }
+
+ /// Adds a relay machine you own to the team (owner/admin). `os` is
+ /// what the Space runs, when known (`linux`, `macos`, `windows`).
+ pub async fn add_team_machine(
+ &self,
+ token: &str,
+ id: &str,
+ machine: &str,
+ os: Option<&str>,
+ ) -> Result<Team> {
+ self.send(
+ self.http
+ .post(self.url(&format!("/v1/teams/{}/machines", seg(id))))
+ .json(&json!({ "machine": machine, "os": os })),
+ token,
+ )
+ .await
+ }
+
+ /// Takes a machine off the team.
+ pub async fn remove_team_machine(&self, token: &str, id: &str, machine: &str) -> Result<Team> {
+ self.send(
+ self.http
+ .delete(self.url(&format!("/v1/teams/{}/machines/{}", seg(id), seg(machine)))),
+ token,
+ )
+ .await
+ }
+
+ /// The team's audit log, newest last (owner/admin).
+ pub async fn team_audit(
+ &self,
+ token: &str,
+ id: &str,
+ limit: usize,
+ ) -> Result<Vec<TeamAuditEvent>> {
+ let l: AuditList = self
+ .send(
+ self.http
+ .get(self.url(&format!("/v1/teams/{}/audit?limit={limit}", seg(id)))),
+ token,
+ )
+ .await?;
+ Ok(l.events)
+ }
+}
+
+/// Every team call from this enrolled device (its session, renewed once if
+/// the relay forgot it).
+macro_rules! with_device {
+ ($self:ident, [$($v:ident),*], |$relay:ident, $token:ident| $call:expr) => {
+ $self
+ .with_session_retry(move |$relay: RelayClient, $token: String| {
+ $(let $v = $v.clone();)*
+ async move { $call }
+ })
+ .await
+ };
+}
+
+impl DeviceAuth {
+ /// Your teams and the email invites waiting for you.
+ pub async fn teams(&self) -> Result<TeamList> {
+ with_device!(self, [], |r, t| r.teams(&t).await)
+ }
+
+ /// One team.
+ pub async fn team(&self, id: &str) -> Result<Team> {
+ let id = id.to_owned();
+ with_device!(self, [id], |r, t| r.team(&t, &id).await)
+ }
+
+ /// Creates a team.
+ pub async fn create_team(&self, name: &str) -> Result<Team> {
+ let name = name.to_owned();
+ with_device!(self, [name], |r, t| r.create_team(&t, &name).await)
+ }
+
+ /// Deletes a team (owner).
+ pub async fn delete_team(&self, id: &str) -> Result<()> {
+ let id = id.to_owned();
+ with_device!(self, [id], |r, t| r.delete_team(&t, &id).await)
+ }
+
+ /// Joins with a code or link, or the email invite of `team`.
+ pub async fn join_team(&self, code: Option<&str>, team: Option<&str>) -> Result<Team> {
+ let (code, team) = (code.map(str::to_owned), team.map(str::to_owned));
+ with_device!(self, [code, team], |r, t| r
+ .join_team(&t, code.as_deref(), team.as_deref())
+ .await)
+ }
+
+ /// Leaves a team.
+ pub async fn leave_team(&self, id: &str) -> Result<()> {
+ let id = id.to_owned();
+ with_device!(self, [id], |r, t| r.leave_team(&t, &id).await)
+ }
+
+ /// Invites by email, or makes a link without one.
+ pub async fn invite_to_team(
+ &self,
+ id: &str,
+ email: Option<&str>,
+ role: TeamRole,
+ ) -> Result<NewTeamInvite> {
+ let (id, email) = (id.to_owned(), email.map(str::to_owned));
+ with_device!(self, [id, email], |r, t| r
+ .invite_to_team(&t, &id, email.as_deref(), role)
+ .await)
+ }
+
+ /// Revokes an invite.
+ pub async fn revoke_team_invite(&self, id: &str, invite: &str) -> Result<()> {
+ let (id, invite) = (id.to_owned(), invite.to_owned());
+ with_device!(self, [id, invite], |r, t| r
+ .revoke_team_invite(&t, &id, &invite)
+ .await)
+ }
+
+ /// Changes a member's role (owner).
+ pub async fn set_team_role(&self, id: &str, who: &str, role: TeamRole) -> Result<TeamMember> {
+ let (id, who) = (id.to_owned(), who.to_owned());
+ with_device!(self, [id, who], |r, t| r
+ .set_team_role(&t, &id, &who, role)
+ .await)
+ }
+
+ /// Removes a member.
+ pub async fn remove_team_member(&self, id: &str, who: &str) -> Result<()> {
+ let (id, who) = (id.to_owned(), who.to_owned());
+ with_device!(self, [id, who], |r, t| r
+ .remove_team_member(&t, &id, &who)
+ .await)
+ }
+
+ /// Asks for this device's approval.
+ pub async fn request_team_device(&self, id: &str) -> Result<TeamDevice> {
+ let id = id.to_owned();
+ with_device!(self, [id], |r, t| r.request_team_device(&t, &id).await)
+ }
+
+ /// Approves or denies a member device.
+ pub async fn decide_team_device(
+ &self,
+ id: &str,
+ device: &str,
+ approve: bool,
+ ) -> Result<TeamDevice> {
+ let (id, device) = (id.to_owned(), device.to_owned());
+ with_device!(self, [id, device], |r, t| r
+ .decide_team_device(&t, &id, &device, approve)
+ .await)
+ }
+
+ /// Adds a relay machine you own (see [`RelayClient::add_team_machine`]).
+ pub async fn add_team_machine(
+ &self,
+ id: &str,
+ machine: &str,
+ os: Option<&str>,
+ ) -> Result<Team> {
+ let (id, machine, os) = (id.to_owned(), machine.to_owned(), os.map(str::to_owned));
+ with_device!(self, [id, machine, os], |r, t| r
+ .add_team_machine(&t, &id, &machine, os.as_deref())
+ .await)
+ }
+
+ /// Takes a machine off the team.
+ pub async fn remove_team_machine(&self, id: &str, machine: &str) -> Result<Team> {
+ let (id, machine) = (id.to_owned(), machine.to_owned());
+ with_device!(self, [id, machine], |r, t| r
+ .remove_team_machine(&t, &id, &machine)
+ .await)
+ }
+
+ /// The team's audit log.
+ pub async fn team_audit(&self, id: &str, limit: usize) -> Result<Vec<TeamAuditEvent>> {
+ let id = id.to_owned();
+ with_device!(self, [id], |r, t| r.team_audit(&t, &id, limit).await)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn links_and_roles() {
+ assert_eq!(
+ team_code_from_link(" https://relay.cua.ai/join/team/team-ab.cd_EF/ "),
+ "team-ab.cd_EF"
+ );
+ assert_eq!(team_code_from_link("team-ab.cd"), "team-ab.cd");
+ assert_eq!(TeamRole::parse("Admin").unwrap(), TeamRole::Admin);
+ assert!(TeamRole::parse("owner").is_err());
+ assert_eq!(seg("[email protected]"), "bob%2Bx%40ex.com");
+ }
+}
diff --git a/libs/cua/crates/cua-host/src/testing.rs b/libs/cua/crates/cua-host/src/testing.rs
index 09eb3a232c..f6c747d38d 100644
--- a/libs/cua/crates/cua-host/src/testing.rs
+++ b/libs/cua/crates/cua-host/src/testing.rs
@@ -78,6 +78,11 @@ struct State_ {
/// machine id → `(path prefix, base URL)` its `/m/<id>/…` gRPC-Web
/// requests go to (the longest matching prefix wins).
tunnels: BTreeMap<String, Vec<(String, String)>>,
+ /// Teams (a simplified model of the relay's: membership, machines,
+ /// invite codes, device approvals and an audit of kinds).
+ teams: BTreeMap<String, crate::team::Team>,
+ /// invite code → (team, role, email)
+ team_codes: BTreeMap<String, (String, crate::team::TeamRole, Option<String>)>,
}
impl State_ {
@@ -302,6 +307,7 @@ async fn register(
// registration here has nothing to vouch for either way; default to
// confirmed, matching behavior before S5 added the field.
confirmed: true,
+ team: None,
meta: body["meta"]
.as_object()
.map(|o| {
@@ -939,6 +945,20 @@ impl FakeRelay {
axum::routing::patch(device_rename).delete(device_revoke),
)
.route("/v1/audit", get(audit))
+ .route("/v1/teams", get(team_list).post(team_create))
+ .route("/v1/teams/join", post(team_join))
+ .route("/v1/teams/{id}", get(team_get))
+ .route("/v1/teams/{id}/invites", post(team_invite))
+ .route("/v1/teams/{id}/machines", post(team_add_machine))
+ .route(
+ "/v1/teams/{id}/machines/{machine}",
+ axum::routing::delete(team_remove_machine),
+ )
+ .route(
+ "/v1/teams/{id}/devices/{device}/approve",
+ post(team_approve),
+ )
+ .route("/v1/teams/{id}/audit", get(team_audit))
.fallback(proxied)
.with_state(state.clone());
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port))
@@ -1106,3 +1126,337 @@ impl FakeRelay {
.map(|r| r.token.clone())
}
}
+
+// ---- teams (simplified) ----
+
+type TeamResult = Result<(Identity, Option<String>), Response>;
+
+#[allow(clippy::result_large_err)]
+fn team_caller(st: &State_, headers: &HeaderMap) -> TeamResult {
+ let who = account_of(st, headers)?;
+ st.gate(headers)?;
+ let device = st.device_of(headers, &who);
+ Ok((who, device))
+}
+
+fn team_for(team: &crate::team::Team, who: &Identity) -> crate::team::Team {
+ let mut t = team.clone();
+ if let Some(m) = t.members.iter().find(|m| m.account == who.id) {
+ t.role = m.role;
+ }
+ if !t.role.manages() {
+ t.invites.clear();
+ t.devices.retain(|d| d.account == who.id);
+ }
+ t
+}
+
+async fn team_list(State(s): State<S>, headers: HeaderMap) -> Response {
+ let st = s.lock().unwrap();
+ let (who, _) = match team_caller(&st, &headers) {
+ Ok(v) => v,
+ Err(r) => return r,
+ };
+ let teams: Vec<_> = st
+ .teams
+ .values()
+ .filter(|t| t.members.iter().any(|m| m.account == who.id))
+ .map(|t| team_for(t, &who))
+ .collect();
+ Json(serde_json::json!({ "teams": teams, "invites": [] })).into_response()
+}
+
+async fn team_create(
+ State(s): State<S>,
+ headers: HeaderMap,
+ Json(body): Json<serde_json::Value>,
+) -> Response {
+ let mut st = s.lock().unwrap();
+ let (who, device) = match team_caller(&st, &headers) {
+ Ok(v) => v,
+ Err(r) => return r,
+ };
+ let id = format!("team-{:016x}", rand::random::<u64>());
+ let mut t = crate::team::Team {
+ id: id.clone(),
+ name: body["name"].as_str().unwrap_or_default().to_string(),
+ role: crate::team::TeamRole::Owner,
+ members: vec![crate::team::TeamMember {
+ account: who.id.clone(),
+ email: who.email.clone(),
+ role: crate::team::TeamRole::Owner,
+ ..Default::default()
+ }],
+ ..Default::default()
+ };
+ if let Some(d) = device {
+ t.devices.push(crate::team::TeamDevice {
+ account: who.id.clone(),
+ device: d,
+ state: "approved".into(),
+ decided_by: Some("auto".into()),
+ ..Default::default()
+ });
+ }
+ st.audit.push((
+ id.clone(),
+ serde_json::json!({"kind": "team_created", "actor": who.id}),
+ ));
+ st.teams.insert(id, t.clone());
+ (StatusCode::CREATED, Json(t)).into_response()
+}
+
+async fn team_get(State(s): State<S>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+ let st = s.lock().unwrap();
+ let (who, _) = match team_caller(&st, &headers) {
+ Ok(v) => v,
+ Err(r) => return r,
+ };
+ match st
+ .teams
+ .get(&id)
+ .filter(|t| t.members.iter().any(|m| m.account == who.id))
+ {
+ Some(t) => Json(team_for(t, &who)).into_response(),
+ None => err(StatusCode::NOT_FOUND, "no such team"),
+ }
+}
+
+#[allow(clippy::result_large_err)]
+fn require_team_manager<'a>(
+ st: &'a mut State_,
+ id: &str,
+ who: &Identity,
+) -> Result<&'a mut crate::team::Team, Response> {
+ let t = st
+ .teams
+ .get_mut(id)
+ .filter(|t| t.members.iter().any(|m| m.account == who.id))
+ .ok_or_else(|| err(StatusCode::NOT_FOUND, "no such team"))?;
+ let role = t
+ .members
+ .iter()
+ .find(|m| m.account == who.id)
+ .map(|m| m.role)
+ .unwrap_or_default();
+ if !role.manages() {
+ return Err(err(
+ StatusCode::FORBIDDEN,
+ "only the team's owner or an admin can do this",
+ ));
+ }
+ Ok(t)
+}
+
+async fn team_invite(
+ State(s): State<S>,
+ headers: HeaderMap,
+ Path(id): Path<String>,
+ Json(body): Json<serde_json::Value>,
+) -> Response {
+ let mut st = s.lock().unwrap();
+ let (who, _) = match team_caller(&st, &headers) {
+ Ok(v) => v,
+ Err(r) => return r,
+ };
+ let url = st.public_url.clone();
+ let t = match require_team_manager(&mut st, &id, &who) {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ let role: crate::team::TeamRole =
+ serde_json::from_value(body["role"].clone()).unwrap_or_default();
+ let email = body["email"].as_str().map(str::to_lowercase);
+ let invite = crate::team::TeamInvite {
+ id: format!("inv_{:08x}", rand::random::<u32>()),
+ email: email.clone(),
+ role,
+ expires_at: now_secs() + 86_400,
+ uses_left: if email.is_some() { 1 } else { 25 },
+ };
+ t.invites.push(invite.clone());
+ let code = format!("{id}.{:016x}", rand::random::<u64>());
+ st.team_codes
+ .insert(code.clone(), (id.clone(), role, email));
+ st.audit.push((
+ id,
+ serde_json::json!({"kind": "invite_created", "actor": who.id}),
+ ));
+ (
+ StatusCode::CREATED,
+ Json(crate::team::NewTeamInvite {
+ invite,
+ link: format!("{url}/join/team/{code}"),
+ code,
+ }),
+ )
+ .into_response()
+}
+
+async fn team_join(
+ State(s): State<S>,
+ headers: HeaderMap,
+ Json(body): Json<serde_json::Value>,
+) -> Response {
+ let mut st = s.lock().unwrap();
+ let (who, device) = match team_caller(&st, &headers) {
+ Ok(v) => v,
+ Err(r) => return r,
+ };
+ let code = body["code"].as_str().unwrap_or_default().to_string();
+ let Some((id, role, email)) = st.team_codes.get(&code).cloned() else {
+ return err(StatusCode::FORBIDDEN, "this invite is not valid");
+ };
+ if email.is_some() && email != who.email.as_ref().map(|e| e.to_lowercase()) {
+ return err(StatusCode::FORBIDDEN, "this invite is for another email");
+ }
+ let Some(t) = st.teams.get_mut(&id) else {
+ return err(StatusCode::NOT_FOUND, "no such team");
+ };
+ if !t.members.iter().any(|m| m.account == who.id) {
+ t.members.push(crate::team::TeamMember {
+ account: who.id.clone(),
+ email: who.email.clone(),
+ role,
+ ..Default::default()
+ });
+ if let Some(d) = &device {
+ t.devices.push(crate::team::TeamDevice {
+ account: who.id.clone(),
+ email: who.email.clone(),
+ device: d.clone(),
+ state: "pending".into(),
+ ..Default::default()
+ });
+ }
+ }
+ let mut view = team_for(t, &who);
+ view.this_device = device.map(|_| "pending".to_string());
+ st.audit.push((
+ id,
+ serde_json::json!({"kind": "member_joined", "actor": who.id}),
+ ));
+ Json(view).into_response()
+}
+
+async fn team_add_machine(
+ State(s): State<S>,
+ headers: HeaderMap,
+ Path(id): Path<String>,
+ Json(body): Json<serde_json::Value>,
+) -> Response {
+ let mut st = s.lock().unwrap();
+ let (who, _) = match team_caller(&st, &headers) {
+ Ok(v) => v,
+ Err(r) => return r,
+ };
+ let machine = body["machine"].as_str().unwrap_or_default().to_string();
+ let Some(record) = st.machines.get(&machine).map(|r| r.machine.clone()) else {
+ return err(StatusCode::NOT_FOUND, "no such machine");
+ };
+ if record.owner.id != who.id {
+ return err(StatusCode::FORBIDDEN, "add a machine you own");
+ }
+ let macos = body["os"].as_str() == Some("macos")
+ || record.meta.get("cua.space.os").map(String::as_str) == Some("macos");
+ if macos {
+ return err(
+ StatusCode::FORBIDDEN,
+ "macOS Spaces (uVisor-backed or any other virtual macOS) cannot be shared with a team: macOS licensing allows one user per macOS copy",
+ );
+ }
+ let t = match require_team_manager(&mut st, &id, &who) {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ if !t.machines.iter().any(|m| m.id == machine) {
+ t.machines.push(crate::team::TeamMachine {
+ id: machine.clone(),
+ name: record.name.clone(),
+ owner: who.email.clone().unwrap_or(who.id.clone()),
+ online: false,
+ });
+ }
+ let view = team_for(t, &who);
+ st.audit.push((
+ id,
+ serde_json::json!({"kind": "machine_added", "machine": machine}),
+ ));
+ Json(view).into_response()
+}
+
+async fn team_remove_machine(
+ State(s): State<S>,
+ headers: HeaderMap,
+ Path((id, machine)): Path<(String, String)>,
+) -> Response {
+ let mut st = s.lock().unwrap();
+ let (who, _) = match team_caller(&st, &headers) {
+ Ok(v) => v,
+ Err(r) => return r,
+ };
+ let t = match require_team_manager(&mut st, &id, &who) {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ let before = t.machines.len();
+ t.machines.retain(|m| m.id != machine);
+ if t.machines.len() == before {
+ return err(StatusCode::NOT_FOUND, "that machine is not in the team");
+ }
+ let view = team_for(t, &who);
+ st.audit.push((
+ id,
+ serde_json::json!({"kind": "machine_removed", "machine": machine}),
+ ));
+ Json(view).into_response()
+}
+
+async fn team_approve(
+ State(s): State<S>,
+ headers: HeaderMap,
+ Path((id, device)): Path<(String, String)>,
+) -> Response {
+ let mut st = s.lock().unwrap();
+ let (who, _) = match team_caller(&st, &headers) {
+ Ok(v) => v,
+ Err(r) => return r,
+ };
+ let t = match require_team_manager(&mut st, &id, &who) {
+ Ok(t) => t,
+ Err(r) => return r,
+ };
+ let Some(d) = t.devices.iter_mut().find(|d| d.device == device) else {
+ return err(StatusCode::NOT_FOUND, "no request from that device");
+ };
+ d.state = "approved".into();
+ d.decided_by = who.email.clone();
+ let d = d.clone();
+ st.audit.push((
+ id,
+ serde_json::json!({"kind": "device_approved", "subject": device}),
+ ));
+ Json(d).into_response()
+}
+
+async fn team_audit(State(s): State<S>, headers: HeaderMap, Path(id): Path<String>) -> Response {
+ let mut st = s.lock().unwrap();
+ let (who, _) = match team_caller(&st, &headers) {
+ Ok(v) => v,
+ Err(r) => return r,
+ };
+ if let Err(r) = require_team_manager(&mut st, &id, &who) {
+ return r;
+ }
+ let events: Vec<_> = st
+ .audit
+ .iter()
+ .filter(|(k, _)| k == &id)
+ .map(|(_, e)| {
+ let mut e = e.clone();
+ e["ts"] = now_secs().into();
+ e
+ })
+ .collect();
+ Json(serde_json::json!({ "events": events })).into_response()
+}
diff --git a/libs/cua/crates/cua-spaces-app-core/parity/golden/share-sheet.json b/libs/cua/crates/cua-spaces-app-core/parity/golden/share-sheet.json
index 04d5da25a7..8e9416873d 100644
--- a/libs/cua/crates/cua-spaces-app-core/parity/golden/share-sheet.json
+++ b/libs/cua/crates/cua-spaces-app-core/parity/golden/share-sheet.json
@@ -213,7 +213,7 @@
"disabled": null,
"empty": "Only you",
"error": null,
- "field": "Email or account ID [team:design] Share with people, one at a time. as editor",
+ "field": "Email or account ID [team:design] Enter a team as team:<id>, as `cua team ls` shows it. as editor",
"request": null,
"roles": "viewer=Can view, editor=Can edit",
"rows": [],
diff --git a/libs/cua/crates/cua-spaces-app-core/src/share.rs b/libs/cua/crates/cua-spaces-app-core/src/share.rs
index 3df7368949..d6325b0e45 100644
--- a/libs/cua/crates/cua-spaces-app-core/src/share.rs
+++ b/libs/cua/crates/cua-spaces-app-core/src/share.rs
@@ -190,8 +190,22 @@ pub fn validate_who(who: &str) -> Result<String, String> {
if w.is_empty() {
return Err("Enter an email or account ID.".into());
}
- if ["team:", "org:", "group:"].iter().any(|p| w.starts_with(p)) {
- return Err("Share with people, one at a time.".into());
+ if let Some(team) = w.strip_prefix("team:") {
+ // A team (`team:<id>` as `cua team ls` or the Teams page shows it):
+ // every member gets the Space, from a device an admin approved.
+ let ok = team.starts_with("team-")
+ && team.len() <= 64
+ && team
+ .chars()
+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
+ return if ok {
+ Ok(format!("team:{team}"))
+ } else {
+ Err("Enter a team as team:<id>, as `cua team ls` shows it.".into())
+ };
+ }
+ if ["org:", "group:"].iter().any(|p| w.starts_with(p)) {
+ return Err("Share with people, or with a team as team:<id>.".into());
}
if w.len() > 254 || w.chars().any(|c| c.is_control() || c.is_whitespace()) {
return Err("Enter an email or account ID.".into());
@@ -215,6 +229,15 @@ fn role_of(role: &str) -> &'static str {
if role == "editor" { "editor" } else { "viewer" }
}
+/// A team always gets full use (teams have no view-only members).
+fn role_for(who: &str, role: &str) -> &'static str {
+ if who.starts_with("team:") {
+ "editor"
+ } else {
+ role_of(role)
+ }
+}
+
/// The roles, in menu order.
pub fn roles() -> Vec<RoleOption> {
vec![
@@ -259,11 +282,8 @@ pub fn share_reduce(
if let Ok(who) = validate_who(&s.who) {
s.busy = true;
s.error = None;
- s.request = Some(ShareRequest::Share {
- space,
- who,
- role: role_of(&s.role).into(),
- });
+ let role = role_for(&who, &s.role).into();
+ s.request = Some(ShareRequest::Share { space, who, role });
}
}
ShareSheetAction::ChangeRole { who, role } if !s.busy && can_act(input) => {
@@ -318,7 +338,7 @@ pub fn share_view(input: &ShareInput, state: &ShareSheetState) -> ShareSheetView
.iter()
.map(|e| ShareRowView {
who: e.who.clone(),
- role: role_of(&e.role).into(),
+ role: role_for(&e.who, &e.role).into(),
connected: e.connected,
})
.collect(),
@@ -416,7 +436,24 @@ mod tests {
assert!(!s.busy);
assert_eq!(
validate_who("team:design").unwrap_err(),
- "Share with people, one at a time."
+ "Enter a team as team:<id>, as `cua team ls` shows it."
+ );
+ assert_eq!(validate_who(" team:team-0a1b ").unwrap(), "team:team-0a1b");
+ // A team is always shared for full use.
+ let s = share_reduce(
+ &i,
+ &share_initial(),
+ &ShareSheetAction::SetWho {
+ who: "team:team-0a1b".into(),
+ },
+ );
+ assert_eq!(
+ share_reduce(&i, &s, &ShareSheetAction::Submit).request,
+ Some(ShareRequest::Share {
+ space: "local:studio".into(),
+ who: "team:team-0a1b".into(),
+ role: "editor".into()
+ })
);
}
diff --git a/libs/cua/crates/cua-spaces/src/share.rs b/libs/cua/crates/cua-spaces/src/share.rs
index f5ebdc6fc1..9fba12276d 100644
--- a/libs/cua/crates/cua-spaces/src/share.rs
+++ b/libs/cua/crates/cua-spaces/src/share.rs
@@ -42,6 +42,10 @@ pub trait ShareConsent: Send + Sync {
/// (hosts from `cua host setup` are already joined).
pub const RELAY_ATTACH_FEATURE: &str = "relay_attach";
+/// Relay machine meta: the OS of the Space a machine is (`linux`, `macos`,
+/// `windows`).
+pub const META_SPACE_OS: &str = "cua.space.os";
+
/// What a person may do in a shared Space.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -144,7 +148,7 @@ pub fn normalize_who(who: &str) -> Result<String> {
}
if w.starts_with("team:") || w.starts_with("org:") || w.starts_with("group:") {
return Err(Error::invalid(
- "the relay shares with accounts (email or account id), not teams; share with each member",
+ "share with an account (email or account id), or with a team as team:<id> (`cua team ls`)",
));
}
if w.contains('@') {
@@ -169,6 +173,29 @@ pub fn normalize_who(who: &str) -> Result<String> {
Ok(w.to_string())
}
+/// The team a `team:<id>` invitee names (`None` for anything else).
+/// Sharing with a team makes the Space a team machine: every member (and
+/// their agents) sees it and opens it as an editor from a device a team
+/// admin approved.
+pub fn team_of(who: &str) -> Option<Result<String>> {
+ let id = who.trim().strip_prefix("team:")?;
+ let ok = id.starts_with("team-")
+ && id.len() <= 64
+ && id
+ .chars()
+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
+ Some(if ok {
+ Ok(id.to_string())
+ } else {
+ Err(Error::invalid(format!(
+ "{who:?} is not a team: use team:<id> as `cua team ls` shows it"
+ )))
+ })
+}
+
+/// Why a macOS Space cannot be a team machine.
+pub const MACOS_TEAM_REFUSED: &str = "macOS Spaces (uVisor-backed or any other virtual macOS) cannot be shared with a team: macOS licensing allows one user per macOS copy. Share a Linux or Windows Space, or a whole Mac set up with `cua host setup`";
+
/// Moves `who` onto the list for `role` (or off both with `None`).
pub fn apply_share(
allow: &mut Vec<String>,
@@ -300,13 +327,19 @@ impl Spaces {
{
return Ok(machine);
}
- let name = self
- .list()?
- .into_iter()
- .find(|i| i.id == canonical)
+ let listed = self.list()?.into_iter().find(|i| i.id == canonical);
+ let os = listed.as_ref().map(|i| i.os.clone()).unwrap_or_default();
+ let name = listed
.map(|i| i.name)
.filter(|n| !n.is_empty())
.unwrap_or_else(|| canonical.clone());
+ // What the Space runs, so the relay can keep macOS Spaces out of
+ // teams on its own.
+ let meta = if os.is_empty() {
+ Default::default()
+ } else {
+ std::collections::BTreeMap::from([(META_SPACE_OS.to_string(), os)])
+ };
// Registering again keeps the lists and rotates the machine token.
let reg = client
.register(
@@ -316,7 +349,7 @@ impl Spaces {
name,
allow: vec![],
host: None,
- meta: Default::default(),
+ meta,
},
)
.await
@@ -362,14 +395,30 @@ impl Spaces {
async fn shares_of(&self, space: &str, machine: &str) -> Result<SpaceShares> {
let relay = self.relay()?;
let token = relay.tokens.access_token().await?;
- let m = relay.client().await?.machine(&token, machine).await?;
+ let client = relay.client().await?;
+ let m = client.machine(&token, machine).await?;
+ let mut shares = entries(&m);
+ // Teams it is a machine of (best effort: a relay without teams, or
+ // a device not enrolled, lists none).
+ if let Ok(list) = client.teams(&token).await {
+ shares.extend(
+ list.teams
+ .iter()
+ .filter(|t| t.machines.iter().any(|tm| tm.id == machine))
+ .map(|t| ShareEntry {
+ who: format!("team:{}", t.id),
+ role: ShareRole::Editor,
+ connected: false,
+ }),
+ );
+ }
Ok(SpaceShares {
space: space.to_string(),
machine: machine.to_string(),
invitee_space: format!("relay:{machine}"),
url: m.url.clone(),
online: m.online,
- shares: entries(&m),
+ shares,
})
}
@@ -382,6 +431,9 @@ impl Spaces {
who: &str,
role: ShareRole,
) -> Result<SpaceShares> {
+ if let Some(team) = team_of(who) {
+ return self.share_with_team(space, &team?).await;
+ }
let who = normalize_who(who)?;
let canonical = self.resolve(space)?.to_string();
let consent = self
@@ -434,6 +486,9 @@ impl Spaces {
/// cut). With `who = None` the Space stops being shared with anyone,
/// and a Space that is not a host leaves the relay.
pub async fn unshare_space(&self, space: &str, who: Option<&str>) -> Result<SpaceShares> {
+ if let Some(team) = who.and_then(team_of) {
+ return self.unshare_from_team(space, &team?).await;
+ }
let id = self.resolve(space)?;
let canonical = id.to_string();
let Some(machine) = self.share_machine(&canonical, &id) else {
@@ -477,6 +532,94 @@ impl Spaces {
self.shares_of(&canonical, &machine).await
}
+ /// The consent prompt, run off the async runtime.
+ async fn confirm_share(&self, reason: String) -> Result<()> {
+ let consent = self
+ .inner
+ .share_consent
+ .read()
+ .expect("share consent")
+ .clone()
+ .ok_or_else(|| {
+ Error::host(
+ "share consent",
+ "nothing here can ask you to confirm; share from the Cua app or run `cua spaces share` in a terminal",
+ )
+ })?;
+ tokio::task::spawn_blocking(move || consent.confirm(&reason))
+ .await
+ .map_err(|e| Error::invalid(format!("consent prompt: {e}")))?
+ .map_err(|why| {
+ Error::Relay(cua_host::Error::PermissionDenied(format!(
+ "not shared: {why}"
+ )))
+ })
+ }
+
+ /// Makes `space` a machine of `team`: every member (and their agents)
+ /// lists it and opens it as an editor, from a device a team admin
+ /// approved. Only a team owner or admin who owns the Space can; a macOS
+ /// Space never can (one user per macOS copy).
+ pub async fn share_with_team(&self, space: &str, team: &str) -> Result<SpaceShares> {
+ let id = self.resolve(space)?;
+ let canonical = id.to_string();
+ // What the Space runs, as this device knows it (a relay machine's
+ // own record speaks for itself on the relay).
+ let os = self
+ .list()?
+ .into_iter()
+ .find(|i| i.id == canonical)
+ .map(|i| i.os)
+ .filter(|o| !o.is_empty());
+ if !matches!(id, SpaceId::Relay { .. })
+ && os
+ .as_deref()
+ .is_some_and(|o| o.eq_ignore_ascii_case("macos"))
+ {
+ return Err(Error::Relay(cua_host::Error::PermissionDenied(
+ MACOS_TEAM_REFUSED.into(),
+ )));
+ }
+ self.confirm_share(format!(
+ "Let every member of team {team} use {canonical} (see and control it)"
+ ))
+ .await?;
+ let machine = self.ensure_shared_machine(&canonical).await?;
+ let relay = self.relay()?;
+ let token = relay.tokens.access_token().await?;
+ relay
+ .client()
+ .await?
+ .add_team_machine(&token, team, &machine, os.as_deref())
+ .await
+ .map_err(|e| match e {
+ cua_host::Error::NotFound(m) if m.contains("no such team") => Error::NotFound(
+ format!("team {team} (you are not in it, or it does not exist)"),
+ ),
+ other => Error::Relay(other),
+ })?;
+ self.audit_share("share", &canonical, &format!("team:{team} editor"));
+ self.shares_of(&canonical, &machine).await
+ }
+
+ /// Takes `space` off `team`.
+ pub async fn unshare_from_team(&self, space: &str, team: &str) -> Result<SpaceShares> {
+ let id = self.resolve(space)?;
+ let canonical = id.to_string();
+ let Some(machine) = self.share_machine(&canonical, &id) else {
+ return Err(Error::NotFound(format!("{canonical} is not shared")));
+ };
+ let relay = self.relay()?;
+ let token = relay.tokens.access_token().await?;
+ relay
+ .client()
+ .await?
+ .remove_team_machine(&token, team, &machine)
+ .await?;
+ self.audit_share("unshare", &canonical, &format!("team:{team}"));
+ self.shares_of(&canonical, &machine).await
+ }
+
/// Detaches `space`'s driver from the relay and removes its machine.
async fn detach(&self, canonical: &str, machine: &str) -> Result<()> {
if let Ok(s) = self.space(canonical).await
@@ -668,7 +811,10 @@ mod tests {
);
}
let e = normalize_who("team:design").unwrap_err().to_string();
- assert!(e.contains("not teams"), "{e}");
+ assert!(e.contains("team:<id>"), "{e}");
+ assert_eq!(team_of("team:team-0a1b").unwrap().unwrap(), "team-0a1b");
+ assert!(team_of("team:design").unwrap().is_err());
+ assert!(team_of("[email protected]").is_none());
}
#[test]
diff --git a/libs/cua/crates/cua-spaces/tests/share.rs b/libs/cua/crates/cua-spaces/tests/share.rs
index f728c6a8d1..43d2de73ab 100644
--- a/libs/cua/crates/cua-spaces/tests/share.rs
+++ b/libs/cua/crates/cua-spaces/tests/share.rs
@@ -685,3 +685,126 @@ async fn only_the_owner_removes_a_relay_record() {
);
assert!(relay.machine(gone).is_none());
}
+
+/// `team:<id>` makes a Space a team machine (attaching it first, with the
+/// user's confirmation and the Space's OS on its relay record); a macOS
+/// Space never becomes one (one user per macOS copy); `unshare team:<id>`
+/// takes it off.
+#[tokio::test]
+async fn sharing_with_a_team_adds_a_team_machine_and_refuses_macos() {
+ let relay = FakeRelay::start().await;
+ relay.add_account("ada-token", "ada", Some("[email protected]"));
+ let home = tempfile::tempdir().unwrap();
+ let consent = yes();
+ let spaces = Spaces::builder()
+ .home(home.path())
+ .relay(RelayAccount::new(
+ &relay.url,
+ Arc::new(StaticToken("ada-token".into())),
+ ))
+ .share_consent(consent.clone())
+ .build();
+ let client = cua_host::RelayClient::new(&relay.url).unwrap();
+ let team = client.create_team("ada-token", "AIGIS").await.unwrap();
+
+ let linux = MockServer::start(MockAuth::default()).await;
+ linux.state.advertise(&["relay_attach"]);
+ *linux.state.os.lock().unwrap() = Some(Some(cua_proto::env::v1::OperatingSystem {
+ family: 1,
+ name: "Ubuntu".into(),
+ ..Default::default()
+ }));
+ let info = spaces
+ .add(&linux.url(), None, Some("build-box".into()))
+ .await
+ .unwrap();
+ let state = linux.state.clone();
+ let online = tokio::spawn({
+ let relay = relay.clone();
+ async move {
+ for _ in 0..400 {
+ if let Some(a) = state.relay_attached.lock().unwrap().clone() {
+ relay.set_online(&a.machine_id, true, "0.1.0");
+ return a;
+ }
+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;
+ }
+ panic!("never attached");
+ }
+ });
+ let shares = spaces
+ .share_space(&info.id, &format!("team:{}", team.id), ShareRole::Viewer)
+ .await
+ .unwrap();
+ let attached = online.await.unwrap();
+ assert!(
+ consent
+ .asked
+ .lock()
+ .unwrap()
+ .iter()
+ .any(|r| r.contains(&format!("every member of team {}", team.id))),
+ "the user confirmed"
+ );
+ // A team gets full use, whatever role was asked for.
+ assert_eq!(
+ shares.shares,
+ vec![cua_spaces::share::ShareEntry {
+ who: format!("team:{}", team.id),
+ role: ShareRole::Editor,
+ connected: false,
+ }]
+ );
+ let m = relay.machine(&attached.machine_id).unwrap();
+ assert_eq!(
+ m.meta.get("cua.space.os").map(String::as_str),
+ Some("linux")
+ );
+ let t = client.team("ada-token", &team.id).await.unwrap();
+ assert_eq!(t.machines[0].id, attached.machine_id);
+
+ // Off the team again.
+ let shares = spaces
+ .unshare_space(&info.id, Some(&format!("team:{}", team.id)))
+ .await
+ .unwrap();
+ assert!(shares.shares.is_empty(), "{shares:?}");
+ assert!(
+ client
+ .team("ada-token", &team.id)
+ .await
+ .unwrap()
+ .machines
+ .is_empty()
+ );
+
+ // A macOS Space is refused before anything reaches the relay.
+ let mac = MockServer::start(MockAuth::default()).await;
+ mac.state.advertise(&["relay_attach"]);
+ *mac.state.os.lock().unwrap() = Some(Some(cua_proto::env::v1::OperatingSystem {
+ family: 2,
+ name: "macOS".into(),
+ ..Default::default()
+ }));
+ let mac_info = spaces
+ .add(&mac.url(), None, Some("mac".into()))
+ .await
+ .unwrap();
+ let e = spaces
+ .share_space(
+ &mac_info.id,
+ &format!("team:{}", team.id),
+ ShareRole::Editor,
+ )
+ .await
+ .unwrap_err();
+ assert!(e.to_string().contains("one user per macOS copy"), "{e}");
+ assert!(mac.state.relay_attached.lock().unwrap().is_none());
+
+ // Not a team id.
+ let e = spaces
+ .share_space(&info.id, "team:design", ShareRole::Editor)
+ .await
+ .unwrap_err();
+ assert_eq!(e.tag(), "invalid_argument", "{e}");
+}
diff --git a/libs/cua/crates/cua-telemetry/src/cli_commands.in b/libs/cua/crates/cua-telemetry/src/cli_commands.in
index 4a2caf75d2..d74ffd2128 100644
--- a/libs/cua/crates/cua-telemetry/src/cli_commands.in
+++ b/libs/cua/crates/cua-telemetry/src/cli_commands.in
@@ -171,6 +171,22 @@
"spacesd.exec",
"spacesd.shell",
"spacesd.targets",
+ "team.add-machine",
+ "team.approve",
+ "team.audit",
+ "team.create",
+ "team.delete",
+ "team.deny",
+ "team.devices",
+ "team.invite",
+ "team.join",
+ "team.leave",
+ "team.ls",
+ "team.remove-machine",
+ "team.remove-member",
+ "team.request",
+ "team.set-role",
+ "team.show",
"telemetry.off",
"telemetry.on",
"telemetry.reset-id",
diff --git a/scripts/docs-generators/cli-specs/cua.json b/scripts/docs-generators/cli-specs/cua.json
index c9ee510c72..b2e7aa1af3 100644
--- a/scripts/docs-generators/cli-specs/cua.json
+++ b/scripts/docs-generators/cli-specs/cua.json
@@ -11135,6 +11135,585 @@
],
"usage": "cua devices [OPTIONS] <COMMAND>"
},
+ {
+ "abstract": "Teams: share machines with every member and their agents. Owners and admins invite (email or link), approve member devices, add machines and read the audit log",
+ "after_help": "Examples:\n cua team create AIGIS\n cua team invite AIGIS [email protected]\n cua team add-machine AIGIS local:build-box\n cua team approve AIGIS dev_0123456789abcdef01234567\n cua team audit AIGIS",
+ "aliases": [],
+ "arguments": [],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "team",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [
+ {
+ "abstract": "Create a team; you are its owner",
+ "after_help": "Examples:\n cua team create \"AIGIS\"",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "NAME",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "create",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team create [OPTIONS] <NAME>"
+ },
+ {
+ "abstract": "Your teams, and email invites waiting for you",
+ "after_help": "Examples:\n cua team ls\n cua team ls --json",
+ "aliases": [
+ "list"
+ ],
+ "arguments": [],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "ls",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team ls [OPTIONS]"
+ },
+ {
+ "abstract": "A team: members, machines, open invites and devices",
+ "after_help": "Examples:\n cua team show AIGIS",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team id (`team-…`) or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "TEAM",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "show",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team show [OPTIONS] <TEAM>"
+ },
+ {
+ "abstract": "Invite someone by email, or make a link anyone can join with",
+ "after_help": "Examples:\n cua team invite AIGIS [email protected]\n cua team invite AIGIS --link\n cua team invite AIGIS [email protected] --role admin",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "TEAM",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "Their email (they join by signing in with it)",
+ "hidden": false,
+ "is_optional": true,
+ "name": "EMAIL",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "Make a link instead (up to 25 joins, 7 days)",
+ "hidden": false,
+ "name": "link",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ }
+ ],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "invite",
+ "options": [
+ {
+ "aliases": [],
+ "default_value": "member",
+ "env": null,
+ "help": "`member` or `admin` (only the owner invites admins)",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "role",
+ "possible_values": [
+ "member",
+ "admin"
+ ],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "member | admin",
+ "value_name": "ROLE"
+ }
+ ],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team invite [OPTIONS] <TEAM> [EMAIL]"
+ },
+ {
+ "abstract": "Join a team with an invite link or code, or (with --team) the email invite for your account's email",
+ "after_help": "Examples:\n cua team join https://relay.cua.ai/join/team/team-0a1b….xyz\n cua team join --team team-0a1b2c3d4e5f6a7b",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "The invite link or code",
+ "hidden": false,
+ "is_optional": true,
+ "name": "CODE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "join",
+ "options": [
+ {
+ "aliases": [],
+ "default_value": null,
+ "env": null,
+ "help": "The team of an email invite",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "team",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "string",
+ "value_name": "TEAM"
+ }
+ ],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team join [OPTIONS] [CODE]"
+ },
+ {
+ "abstract": "Leave a team",
+ "after_help": "Examples:\n cua team leave AIGIS",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "TEAM",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "leave",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team leave [OPTIONS] <TEAM>"
+ },
+ {
+ "abstract": "Remove a member (owner or admin; admins cannot remove admins)",
+ "after_help": "Examples:\n cua team remove-member AIGIS [email protected]",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "TEAM",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "Their email or account id",
+ "hidden": false,
+ "is_optional": false,
+ "name": "WHO",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "remove-member",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team remove-member [OPTIONS] <TEAM> <WHO>"
+ },
+ {
+ "abstract": "Make a member an admin, or an admin a member (owner)",
+ "after_help": "Examples:\n cua team set-role AIGIS [email protected] admin",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "TEAM",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "Their email or account id",
+ "hidden": false,
+ "is_optional": false,
+ "name": "WHO",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "`member` or `admin`",
+ "hidden": false,
+ "is_optional": false,
+ "name": "ROLE",
+ "possible_values": [
+ "member",
+ "admin"
+ ],
+ "repeatable": false,
+ "type": "member | admin"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "set-role",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team set-role [OPTIONS] <TEAM> <WHO> <ROLE>"
+ },
+ {
+ "abstract": "Member devices and whether they may open team machines",
+ "after_help": "Examples:\n cua team devices AIGIS",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "TEAM",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "devices",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team devices [OPTIONS] <TEAM>"
+ },
+ {
+ "abstract": "Approve a member device so it can open team machines",
+ "after_help": "Examples:\n cua team approve AIGIS dev_0123456789abcdef01234567",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "TEAM",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "Device id (`cua team devices`)",
+ "hidden": false,
+ "is_optional": false,
+ "name": "DEVICE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "approve",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team approve [OPTIONS] <TEAM> <DEVICE>"
+ },
+ {
+ "abstract": "Decline a member device (it can no longer open team machines)",
+ "after_help": "Examples:\n cua team deny AIGIS dev_0123456789abcdef01234567",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "TEAM",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "Device id",
+ "hidden": false,
+ "is_optional": false,
+ "name": "DEVICE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "deny",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team deny [OPTIONS] <TEAM> <DEVICE>"
+ },
+ {
+ "abstract": "Ask the team's admins to approve this device",
+ "after_help": "Examples:\n cua team request AIGIS",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "TEAM",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "request",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team request [OPTIONS] <TEAM>"
+ },
+ {
+ "abstract": "Make a Space (or a machine you host) a team machine: every member and their agents see it and can open it. macOS Spaces cannot",
+ "after_help": "Examples:\n cua team add-machine AIGIS local:build-box\n cua team add-machine AIGIS relay:0123abcd4567ef89 --yes",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "TEAM",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "Space id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "SPACE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "Confirm without a prompt",
+ "hidden": false,
+ "name": "yes",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ }
+ ],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "add-machine",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team add-machine [OPTIONS] <TEAM> <SPACE>"
+ },
+ {
+ "abstract": "Take a machine off the team",
+ "after_help": "Examples:\n cua team remove-machine AIGIS relay:0123abcd4567ef89",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "TEAM",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ },
+ {
+ "default_value": null,
+ "help": "The machine (`relay:<id>` or its id, as `cua team show` lists it)",
+ "hidden": false,
+ "is_optional": false,
+ "name": "MACHINE",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "remove-machine",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team remove-machine [OPTIONS] <TEAM> <MACHINE>"
+ },
+ {
+ "abstract": "The team's audit log: joins, approvals, machines opened, changes",
+ "after_help": "Examples:\n cua team audit AIGIS --limit 50",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "TEAM",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "audit",
+ "options": [
+ {
+ "aliases": [],
+ "default_value": "50",
+ "env": null,
+ "help": "Newest events to show",
+ "hidden": false,
+ "is_optional": true,
+ "multiple_values": false,
+ "name": "limit",
+ "possible_values": [],
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": true,
+ "type": "integer",
+ "value_name": "LIMIT"
+ }
+ ],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team audit [OPTIONS] <TEAM>"
+ },
+ {
+ "abstract": "Delete a team (owner). Its machines stay yours",
+ "after_help": "Examples:\n cua team delete AIGIS --yes",
+ "aliases": [],
+ "arguments": [
+ {
+ "default_value": null,
+ "help": "Team id or name",
+ "hidden": false,
+ "is_optional": false,
+ "name": "TEAM",
+ "possible_values": [],
+ "repeatable": false,
+ "type": "string"
+ }
+ ],
+ "flags": [
+ {
+ "aliases": [],
+ "default_value": false,
+ "env": null,
+ "help": "Do not ask for confirmation",
+ "hidden": false,
+ "name": "yes",
+ "repeatable": false,
+ "short_name": null,
+ "takes_value": false
+ }
+ ],
+ "hidden": false,
+ "hidden_aliases": [],
+ "name": "delete",
+ "options": [],
+ "subcommand_optional": false,
+ "subcommands": [],
+ "usage": "cua team delete [OPTIONS] <TEAM>"
+ }
+ ],
+ "usage": "cua team [OPTIONS] <COMMAND>"
+ },
{
"abstract": "Move a desktop app session (tabs, profile, sign-in) into a sandbox",
"aliases": [],
diff --git a/scripts/docs-generators/cua-cli.ts b/scripts/docs-generators/cua-cli.ts
index 5ffe8d7c8b..1662456757 100644
--- a/scripts/docs-generators/cua-cli.ts
+++ b/scripts/docs-generators/cua-cli.ts
@@ -121,6 +121,7 @@ export const CLI_GROUPS: CliGroup[] = [
{ slug: 'cloud', title: 'cua cloud', summary: 'Your own AWS, Google Cloud or Modal account as a place for sandboxes and Spaces: connect, test, status, sweep', commands: ['cloud'] },
{ slug: 'host', title: 'cua host', summary: 'Set this machine up for unattended access', commands: ['host'] },
{ slug: 'devices', title: 'cua devices', summary: 'Enroll this device on the relay, approve, rename and revoke devices, and read the access log', commands: ['devices'] },
+ { slug: 'team', title: 'cua team', summary: 'Create a team, invite members, share machines with them, approve their devices and read the team audit log', commands: ['team'] },
{ slug: 'teleport', title: 'cua teleport', summary: 'Move a desktop app session into a sandbox', commands: ['teleport'] },
{ slug: 'volume', title: 'cua volume', summary: 'Cua Volume: files, versions, grants, access requests and audit of the volume every Space and agent shares', commands: ['volume'] },
{ slug: 'keyvault', title: 'cua keyvault', summary: 'Set up, unlock and lock the Cua Keyvault, with the OS key store or a passphrase', commands: ['keyvault'] },