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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,9 @@ records its **source**:
gives, and owners are admins of every repository, so membership of the GitHub organization that installed the App
carries over without a separate rule. Losing every such permission removes the membership.
- `invite`: an admin invited them by email or forge login (for people the forge doesn't cover, or organizations with
no linked repository). A pending invitation is accepted when someone signs in with that verified email or login.
no linked repository). An invitation waits for its invitee to accept or decline it in the app, whether or not they
have an account (`invitations.for_user_id` records the account once known); they're emailed either way. Members'
email addresses are shown to admins only.
- `staff`: DocSpring support ran `org:add-member`.
- `created`: they made the organization.

Expand Down
4 changes: 2 additions & 2 deletions server/frontend/content/docs/reference/access.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ Access that comes from GitHub shows as **GitHub** in the organization's member l

## Invitations

To add someone GitHub doesn't cover (a designer, a contractor, or anyone in an organization with no linked repository), an admin invites them by email address or GitHub login in the organization's **Members** section, choosing their role. They join when they next sign in with that verified email address or GitHub account. Someone who already has an account joins at once.
To add someone GitHub doesn't cover (a designer, a contractor, or anyone in an organization with no linked repository), an admin invites them by email address or GitHub login in the organization's **Members** section, choosing their role. They get an email, and the invitation waits in VisualCI until they accept or decline it (signed in with that verified email address or GitHub account): nobody joins an organization without saying so.

An organization can send 50 invitations a day, and one address can get 3 a day. An agent can do the same with the MCP tool `invite_member`. `get_organization` lists the members, each with their role and where their access came from.
An organization can send 50 invitations a day, and one address can get 3 a day. An agent can do the same with the MCP tool `invite_member`. `get_organization` lists the members, each with their role and where their access came from. Members' email addresses are shown to admins only; everyone else sees names and logins.

## Several GitHub accounts

Expand Down
10 changes: 10 additions & 0 deletions server/frontend/src/api/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,16 @@ export function useLogout() {
})
}

/** Accept or decline an invitation for the signed-in person; either way it leaves their list. */
export function useInvitationAnswer() {
const qc = useQueryClient()
return useMutation({
mutationFn: (v: { id: string; answer: 'accept' | 'decline' }) =>
post<{ slug?: string }>(`/api/ui/invitations/${enc(v.id)}/${v.answer}`, {}),
onSuccess: () => qc.invalidateQueries({ queryKey: keys.me }),
})
}

export function useCreateOrg() {
const qc = useQueryClient()
return useMutation({
Expand Down
11 changes: 11 additions & 0 deletions server/frontend/src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ export type Me = {
/** Forges this server can sign in with (`github`). */
forges: string[]
organizations: OrgSummary[]
/** Invitations waiting for this person to accept or decline. */
invitations?: PendingInvitation[]
/** Staff (users.staff): can read customers' feedback. */
staff?: boolean
/** Ask "How did you hear about VisualCI?" (once, after sign-up). */
Expand All @@ -80,6 +82,15 @@ export type Me = {
notifications: Notifications
}

/** An invitation to an organization, waiting for the signed-in person's answer. */
export type PendingInvitation = {
id: string
organization: { slug: string; name: string }
role: 'admin' | 'member' | 'read'
invited_by: string | null
created_at: string
}

/** Emails people can turn off; security emails, billing problems and running out of credits always go. */
export type Notifications = { low_credits: boolean; receipts: boolean }

Expand Down
59 changes: 56 additions & 3 deletions server/frontend/src/components/AppShell.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { useEffect, useRef, type MouseEvent, type ReactNode } from 'react'
import { Link, Outlet, useParams } from '@tanstack/react-router'
import { Link, Outlet, useNavigate, useParams } from '@tanstack/react-router'
import { ChatTextIcon, CreditCardIcon, KeyIcon, MonitorIcon, MoonIcon, PaperPlaneTiltIcon, SignOutIcon, SunIcon, UsersIcon } from '@phosphor-icons/react'
import { useLogout, useMe, useProject, useSnapshot } from '../api/hooks'
import { useInvitationAnswer, useLogout, useMe, useProject, useSnapshot } from '../api/hooks'
import { errorMessage } from '../api/client'
import { useTheme, type ThemePref } from '../lib/theme'
import { Avatar, ErrorBox, Spinner } from './ui'
import { Avatar, Button, ErrorBox, Spinner } from './ui'
import { Logo } from './Logo'
import { appUrl } from '../lib/hosts'
import { isDemoPath } from '../lib/demo'
Expand Down Expand Up @@ -175,11 +176,63 @@ export function AppShell({ children }: { children: ReactNode }) {
</div>
</header>
{isDemoPath(window.location.pathname) && <DemoBanner />}
<InvitationsBanner />
<main className="app-main">{children}</main>
</div>
)
}

const roleWords: Record<string, string> = { admin: 'an admin', member: 'a member', read: 'a read-only member' }

/** Invitations waiting for the signed-in person: nobody joins an organization without saying so. */
function InvitationsBanner() {
const me = useMe().data
const answer = useInvitationAnswer()
const navigate = useNavigate()
const invitations = me?.invitations ?? []
if (!invitations.length) return null
return (
<div className="invitations-banner" role="region" aria-label="Invitations">
{invitations.map((i) => {
const busy = answer.isPending && answer.variables?.id === i.id
return (
<div key={i.id} className="invitation">
<span>
{i.invited_by ? <strong>{i.invited_by}</strong> : 'Someone'} invited you to join{' '}
<strong>{i.organization.name}</strong> as {roleWords[i.role] ?? i.role}.
</span>
<span className="invitation-actions">
<Button
size="sm"
variant="secondary"
disabled={busy}
onClick={() => answer.mutate({ id: i.id, answer: 'decline' })}
>
Decline
</Button>
<Button
size="sm"
variant="primary"
loading={busy && answer.variables?.answer === 'accept'}
disabled={busy}
onClick={() =>
answer.mutate(
{ id: i.id, answer: 'accept' },
{ onSuccess: () => navigate({ to: '/$org', params: { org: i.organization.slug } }) },
)
}
>
Accept
</Button>
</span>
</div>
)
})}
{answer.isError && <span className="field-error">{errorMessage(answer.error)}</span>}
</div>
)
}

/** On the public demo: what it is, and the way to try it on your own tests. */
function DemoBanner() {
const me = useMe().data
Expand Down
23 changes: 23 additions & 0 deletions server/frontend/src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -4413,6 +4413,29 @@ html.vci-signed-in .site-auth-out {
}

/* The public demo's banner, under the top bar. */
/* Invitations waiting for the signed-in person: one line each, with Accept and Decline. */
.invitations-banner {
display: grid;
gap: var(--space-2);
padding: var(--space-2) var(--space-6);
background: var(--color-accent-soft);
border-bottom: 1px solid var(--color-rule);
font-size: var(--text-sm);
}

.invitation {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: space-between;
gap: var(--space-3);
}

.invitation-actions {
display: inline-flex;
gap: var(--space-2);
}

.demo-banner {
display: flex;
flex-wrap: wrap;
Expand Down
2 changes: 2 additions & 0 deletions server/migration/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ mod m20261202_000029_build_error_code;
mod m20261202_000030_stripe_order;
mod m20261202_000033_linked_by;
mod m20261202_000034_render_job_token;
mod m20261202_000035_invitation_for_user;

pub struct Migrator;

Expand Down Expand Up @@ -82,6 +83,7 @@ impl MigratorTrait for Migrator {
Box::new(m20261202_000030_stripe_order::Migration),
Box::new(m20261202_000033_linked_by::Migration),
Box::new(m20261202_000034_render_job_token::Migration),
Box::new(m20261202_000035_invitation_for_user::Migration),
// inject-above (do not remove this comment)
]
}
Expand Down
30 changes: 30 additions & 0 deletions server/migration/src/m20261202_000035_invitation_for_user.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//! An invitation waits for its invitee to accept it, even when they already have an account. `for_user_id` is that
//! account once VisualCI knows it (an account with that email or login when they're invited, or the person who signs in
//! with that verified email), so the invitation shows on their side.
use sea_orm_migration::prelude::*;

pub struct Migration;

impl MigrationName for Migration {
fn name(&self) -> &str {
"m20261202_000035_invitation_for_user"
}
}

#[async_trait::async_trait]
impl MigrationTrait for Migration {
async fn up(&self, m: &SchemaManager) -> Result<(), DbErr> {
m.get_connection()
.execute_unprepared(
"ALTER TABLE invitations ADD COLUMN for_user_id BIGINT REFERENCES users(id) ON DELETE CASCADE;
CREATE INDEX invitations_for_user ON invitations (for_user_id) WHERE accepted_at IS NULL;",
)
.await?;
Ok(())
}

async fn down(&self, m: &SchemaManager) -> Result<(), DbErr> {
m.get_connection().execute_unprepared("ALTER TABLE invitations DROP COLUMN for_user_id;").await?;
Ok(())
}
}
141 changes: 87 additions & 54 deletions server/src/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,70 +234,107 @@ pub async fn after_sign_in(
let grants = grants_from(&projects, &permissions);
let scope = site_scope(db, settings, user.id, forge, site).await?;
let changed = memberships::Model::apply_forge(db, user.id, forge, &grants, scope.as_deref()).await?;
let accepted = accept_invitations(db, user, sign_in.identity.trusted_emails()).await?;
Ok(changed + accepted)
note_invitations(db, user, sign_in.identity.trusted_emails()).await?;
Ok(changed)
}

/// Accept the pending invitations for any of the user's verified addresses (their own, when verified, and
/// `verified_emails` from a forge) or forge logins. Returns how many.
/// Record that the pending invitations to these verified addresses (a forge's trusted emails at sign-in) are for this
/// person, so they show on their side even when it isn't their account's address. Nothing is accepted.
///
/// # Errors
/// On a database error.
pub async fn accept_invitations(
db: &DatabaseConnection,
user: &users::Model,
verified_emails: &[String],
) -> Result<usize> {
let logins = identities::Entity::find().filter(identities::Column::UserId.eq(user.id)).all(db).await?;
let pending = invitations::Entity::find().filter(invitations::Column::AcceptedAt.is_null()).all(db).await?;
let mut emails: Vec<String> = verified_emails.iter().map(|e| e.to_lowercase()).collect();
if user.email_verified_at.is_some() {
emails.push(user.email.to_lowercase());
pub async fn note_invitations(db: &DatabaseConnection, user: &users::Model, verified_emails: &[String]) -> Result<()> {
let emails: Vec<String> = verified_emails.iter().map(|e| e.to_lowercase()).collect();
if emails.is_empty() {
return Ok(());
}
let mut accepted = 0;
let pending = invitations::Entity::find()
.filter(invitations::Column::AcceptedAt.is_null())
.filter(invitations::Column::ForUserId.is_null())
.all(db)
.await?;
for invitation in pending {
let by_email = invitation.email.as_deref().is_some_and(|e| emails.contains(&e.to_lowercase()));
let by_login = invitation.login.as_deref().is_some_and(|l| {
logins
.iter()
// An invitation by login is for github.com or gitlab.com: a self-managed instance's logins are its own.
.any(|i| {
i.site.is_empty()
&& Some(i.forge.as_str()) == invitation.forge.as_deref()
&& i.login.eq_ignore_ascii_case(l)
})
});
if !(by_email || by_login) {
continue;
}
let role = Role::parse(&invitation.role).unwrap_or(Role::Read);
// An invitation adds someone or raises their role, never lowers it: otherwise an admin could demote the last
// admin (themselves included) or take a forge-derived row out of the forge's hands by inviting downwards.
let current = memberships::Entity::find()
.filter(memberships::memberships::Column::OrganizationId.eq(invitation.organization_id))
.filter(memberships::memberships::Column::UserId.eq(user.id))
.one(db)
.await?
.map(|m| m.role());
if current.is_none_or(|r| r < role) {
memberships::Model::grant(db, invitation.organization_id, user.id, role, memberships::INVITE).await?;
if invitation.email.as_deref().is_some_and(|e| emails.contains(&e.to_lowercase())) {
let mut a = invitation.into_active_model();
a.for_user_id = Set(Some(user.id));
a.update(db).await?;
}
let mut a = invitation.into_active_model();
a.accepted_by = Set(Some(user.id));
a.accepted_at = Set(Some(chrono::Utc::now().into()));
a.update(db).await?;
accepted += 1;
}
Ok(accepted)
Ok(())
}

/// The person's pending invitation `pid`, if it's theirs.
async fn their_invitation(db: &DatabaseConnection, user: &users::Model, pid: Uuid) -> Result<invitations::Model> {
let logins = identities::Entity::find().filter(identities::Column::UserId.eq(user.id)).all(db).await?;
crate::models::invitations::Model::pending_for(db, user, &logins)
.await?
.into_iter()
.find(|i| i.pid == pid)
.ok_or(Error::NotFound)
}

/// Accept an invitation that's for this person: they join with its role, or keep a higher one they have (an
/// invitation never lowers a role: otherwise an admin could demote the last admin, themselves included, or take a
/// forge-derived row out of the forge's hands by inviting downwards). Returns the organization's id.
///
/// # Errors
/// `NotFound` when it isn't a pending invitation for them; database errors.
pub async fn accept_invitation(db: &DatabaseConnection, user: &users::Model, pid: Uuid) -> Result<i64> {
let invitation = their_invitation(db, user, pid).await?;
let org = invitation.organization_id;
let role = Role::parse(&invitation.role).unwrap_or(Role::Read);
let current = memberships::Entity::find()
.filter(memberships::memberships::Column::OrganizationId.eq(org))
.filter(memberships::memberships::Column::UserId.eq(user.id))
.one(db)
.await?
.map(|m| m.role());
if current.is_none_or(|r| r < role) {
memberships::Model::grant(db, org, user.id, role, memberships::INVITE).await?;
}
let mut a = invitation.into_active_model();
a.accepted_by = Set(Some(user.id));
a.accepted_at = Set(Some(chrono::Utc::now().into()));
a.update(db).await?;
Ok(org)
}

/// Decline an invitation that's for this person: it's withdrawn, as if its admin had.
///
/// # Errors
/// `NotFound` when it isn't a pending invitation for them; database errors.
pub async fn decline_invitation(db: &DatabaseConnection, user: &users::Model, pid: Uuid) -> Result<()> {
let invitation = their_invitation(db, user, pid).await?;
invitations::Entity::delete_by_id(invitation.id).exec(db).await?;
Ok(())
}

/// The invitation, recorded for its invitee's account when they have one already.
///
/// # Errors
/// On a database error.
pub async fn for_invitee(
db: &DatabaseConnection,
invitation: invitations::Model,
invitee: &crate::models::invitations::Invitee,
) -> Result<invitations::Model> {
let Some(account) = invitee_user(db, invitee).await? else { return Ok(invitation) };
let mut a = invitation.into_active_model();
a.for_user_id = Set(Some(account.id));
Ok(a.update(db).await?)
}

/// An invitation for someone who already has an account (a verified email, or a forge login) takes effect at once.
/// The account an invitation is for, when one exists already: a verified email, or a login on github.com or
/// gitlab.com.
///
/// # Errors
/// On a database error.
pub async fn accept_existing(db: &DatabaseConnection, invitee: &crate::models::invitations::Invitee) -> Result<()> {
pub async fn invitee_user(
db: &DatabaseConnection,
invitee: &crate::models::invitations::Invitee,
) -> Result<Option<users::Model>> {
use crate::models::invitations::Invitee;
let user = match invitee {
Ok(match invitee {
Invitee::Email(e) => {
users::Entity::find()
.filter(sea_orm::sea_query::Expr::cust_with_values("lower(email) = $1", [e.clone()]))
Expand All @@ -315,11 +352,7 @@ pub async fn accept_existing(db: &DatabaseConnection, invitee: &crate::models::i
Some(i) => users::Entity::find_by_id(i.user_id).one(db).await?,
None => None,
},
};
if let Some(user) = user {
accept_invitations(db, &user, &[]).await?;
}
Ok(())
})
}

/// Recompute one person's memberships from one forge through the projects' installations (`installation` limits it
Expand Down
1 change: 0 additions & 1 deletion server/src/controllers/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,6 @@ async fn dev_login(
(user, true)
}
};
access::accept_invitations(&ctx.db, &user, &[]).await?;
let return_to = params.return_to.as_deref().and_then(safe_return);
let jar = signed_in(&ctx, jar, &user, created, return_to.as_deref(), "dev").await?;
Ok((jar, Json(serde_json::json!({ "ok": true }))).into_response())
Expand Down
Loading
Loading