An open-source, faster Devin alternative
TypeScript
implementaiton of org members and implementations based on workos (#85)
Mohamed Habib53b0cb3280ba
diff --git a/internal/api/dashboard.go b/internal/api/dashboard.goindex 50d62fee..82747ea9 100644--- a/internal/api/dashboard.go+++ b/internal/api/dashboard.go@@ -29,11 +29,44 @@ func (s *Server) dashboardMe(c echo.Context) error {email := c.Get("user_email")orgID, _ := auth.GetOrgID(c)- return c.JSON(http.StatusOK, map[string]interface{}{+ resp := map[string]interface{}{"id": userID,"email": email,"orgId": orgID,- })+ }++ // Include the user's org list if WorkOS is configured+ if s.store != nil && s.workos != nil && s.workos.OrgMgr() != nil {+ if emailStr, ok := email.(string); ok {+ user, err := s.store.GetUserByEmail(c.Request().Context(), emailStr)+ if err == nil && user.WorkOSUserID != nil {+ memberships, err := s.workos.OrgMgr().ListUserMemberships(c.Request().Context(), *user.WorkOSUserID)+ if err == nil {+ type orgInfo struct {+ ID uuid.UUID `json:"id"`+ Name string `json:"name"`+ IsPersonal bool `json:"isPersonal"`+ IsActive bool `json:"isActive"`+ }+ var orgs []orgInfo+ for _, m := range memberships {+ localOrg, err := s.store.GetOrgByWorkOSID(c.Request().Context(), m.OrganizationID)+ if err == nil {+ orgs = append(orgs, orgInfo{+ ID: localOrg.ID,+ Name: localOrg.Name,+ IsPersonal: localOrg.IsPersonal,+ IsActive: localOrg.ID == user.OrgID,+ })+ }+ }+ resp["orgs"] = orgs+ }+ }+ }+ }++ return c.JSON(http.StatusOK, resp)}// dashboardSessions returns session history for the authenticated org.@@ -218,6 +251,18 @@ func (s *Server) dashboardUpdateOrg(c echo.Context) error {})}+ // Only the org owner can rename+ userID, _ := c.Get("user_id").(uuid.UUID)+ currentOrg, err := s.store.GetOrg(c.Request().Context(), orgID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "org not found"})+ }+ if currentOrg.OwnerUserID == nil || *currentOrg.OwnerUserID != userID {+ return c.JSON(http.StatusForbidden, map[string]string{+ "error": "only the org owner can rename this organization",+ })+ }+var req struct {Name string `json:"name"`}@@ -234,6 +279,13 @@ func (s *Server) dashboardUpdateOrg(c echo.Context) error {})}+ // Sync name to WorkOS if linked+ if org.WorkOSOrgID != nil && s.workos != nil && s.workos.OrgMgr() != nil {+ if err := s.workos.OrgMgr().UpdateOrganization(c.Request().Context(), *org.WorkOSOrgID, req.Name); err != nil {+ log.Printf("workos: failed to sync org name: %v", err)+ }+ }+return c.JSON(http.StatusOK, org)}diff --git a/internal/api/dashboard_org.go b/internal/api/dashboard_org.gonew file mode 100644index 00000000..e6a7eefd--- /dev/null+++ b/internal/api/dashboard_org.go@@ -0,0 +1,439 @@+package api++import (+ "log"+ "net/http"++ "github.com/google/uuid"+ "github.com/labstack/echo/v4"+ "github.com/opensandbox/opensandbox/internal/auth"+)++// dashboardListOrgMembers returns the members of the current org via WorkOS.+func (s *Server) dashboardListOrgMembers(c echo.Context) error {+ if s.store == nil || s.workos == nil || s.workos.OrgMgr() == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{+ "error": "not configured",+ })+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ org, err := s.store.GetOrg(c.Request().Context(), orgID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "org not found"})+ }++ if org.WorkOSOrgID == nil {+ // Org not linked to WorkOS yet — return local users only+ users, err := s.store.ListUsersByOrgID(c.Request().Context(), orgID)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ type memberResp struct {+ ID uuid.UUID `json:"id"`+ Email string `json:"email"`+ Name string `json:"name"`+ Role string `json:"role"`+ }+ var members []memberResp+ for _, u := range users {+ members = append(members, memberResp{+ ID: u.ID,+ Email: u.Email,+ Name: u.Name,+ Role: u.Role,+ })+ }+ return c.JSON(http.StatusOK, members)+ }++ // Fetch from WorkOS+ memberships, err := s.workos.OrgMgr().ListMemberships(c.Request().Context(), *org.WorkOSOrgID)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ type memberResp struct {+ MembershipID string `json:"membershipId"`+ UserID string `json:"workosUserId"`+ Email string `json:"email"`+ Name string `json:"name"`+ Role string `json:"role"`+ Status string `json:"status"`+ }++ var members []memberResp+ for _, m := range memberships {+ // Enrich with user details from WorkOS+ email := ""+ name := ""+ workosUser, err := s.workos.OrgMgr().GetUser(c.Request().Context(), m.UserID)+ if err == nil {+ email = workosUser.Email+ name = workosUser.FirstName+ if workosUser.LastName != "" {+ name += " " + workosUser.LastName+ }+ }+ members = append(members, memberResp{+ MembershipID: m.ID,+ UserID: m.UserID,+ Email: email,+ Name: name,+ Role: m.Role.Slug,+ Status: string(m.Status),+ })+ }++ return c.JSON(http.StatusOK, members)+}++// dashboardRemoveMember removes a member from the org via WorkOS.+func (s *Server) dashboardRemoveMember(c echo.Context) error {+ if s.store == nil || s.workos == nil || s.workos.OrgMgr() == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})+ }++ membershipID := c.Param("membershipId")+ if membershipID == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "membershipId required"})+ }++ err := s.workos.OrgMgr().DeleteMembership(c.Request().Context(), membershipID)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ return c.JSON(http.StatusOK, map[string]string{"status": "removed"})+}++// dashboardSendInvitation sends an invitation to join the current org.+func (s *Server) dashboardSendInvitation(c echo.Context) error {+ if s.store == nil || s.workos == nil || s.workos.OrgMgr() == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ var req struct {+ Email string `json:"email"`+ Role string `json:"role"`+ }+ if err := c.Bind(&req); err != nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invalid request body"})+ }+ if req.Email == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "email is required"})+ }+ if req.Role == "" {+ req.Role = "member"+ }++ org, err := s.store.GetOrg(c.Request().Context(), orgID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "org not found"})+ }+ if org.WorkOSOrgID == nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "org not linked to WorkOS — run backfill first"})+ }++ // Get inviter's WorkOS user ID+ inviterWorkOSUserID := ""+ if uid, ok := c.Get("user_id").(uuid.UUID); ok {+ user, err := s.store.GetUserByEmail(c.Request().Context(), c.Get("user_email").(string))+ if err == nil && user.WorkOSUserID != nil {+ inviterWorkOSUserID = *user.WorkOSUserID+ }+ _ = uid+ }++ inv, err := s.workos.OrgMgr().SendInvitation(c.Request().Context(), req.Email, *org.WorkOSOrgID, inviterWorkOSUserID, req.Role, 7)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ return c.JSON(http.StatusOK, map[string]interface{}{+ "id": inv.ID,+ "email": inv.Email,+ "state": inv.State,+ "expiresAt": inv.ExpiresAt,+ "createdAt": inv.CreatedAt,+ })+}++// dashboardListInvitations returns pending invitations for the current org.+func (s *Server) dashboardListInvitations(c echo.Context) error {+ if s.store == nil || s.workos == nil || s.workos.OrgMgr() == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ org, err := s.store.GetOrg(c.Request().Context(), orgID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "org not found"})+ }+ if org.WorkOSOrgID == nil {+ return c.JSON(http.StatusOK, []interface{}{})+ }++ invitations, err := s.workos.OrgMgr().ListInvitations(c.Request().Context(), *org.WorkOSOrgID)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ type invResp struct {+ ID string `json:"id"`+ Email string `json:"email"`+ State string `json:"state"`+ Role string `json:"role"`+ ExpiresAt string `json:"expiresAt"`+ CreatedAt string `json:"createdAt"`+ }++ var resp []invResp+ for _, inv := range invitations {+ resp = append(resp, invResp{+ ID: inv.ID,+ Email: inv.Email,+ State: string(inv.State),+ ExpiresAt: inv.ExpiresAt,+ CreatedAt: inv.CreatedAt,+ })+ }++ return c.JSON(http.StatusOK, resp)+}++// dashboardRevokeInvitation revokes a pending invitation.+func (s *Server) dashboardRevokeInvitation(c echo.Context) error {+ if s.store == nil || s.workos == nil || s.workos.OrgMgr() == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})+ }++ invID := c.Param("id")+ if invID == "" {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "invitation id required"})+ }++ err := s.workos.OrgMgr().RevokeInvitation(c.Request().Context(), invID)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ return c.JSON(http.StatusOK, map[string]string{"status": "revoked"})+}++// dashboardListOrgs returns all orgs the user belongs to (via WorkOS memberships).+func (s *Server) dashboardListOrgs(c echo.Context) error {+ if s.store == nil || s.workos == nil || s.workos.OrgMgr() == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})+ }++ email, ok := c.Get("user_email").(string)+ if !ok || email == "" {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})+ }++ user, err := s.store.GetUserByEmail(c.Request().Context(), email)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "user not found"})+ }++ if user.WorkOSUserID == nil {+ // No WorkOS link — return only the current org+ org, err := s.store.GetOrg(c.Request().Context(), user.OrgID)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ type orgResp struct {+ ID uuid.UUID `json:"id"`+ Name string `json:"name"`+ IsPersonal bool `json:"isPersonal"`+ IsActive bool `json:"isActive"`+ }+ return c.JSON(http.StatusOK, []orgResp{{+ ID: org.ID,+ Name: org.Name,+ IsPersonal: org.IsPersonal,+ IsActive: true,+ }})+ }++ memberships, err := s.workos.OrgMgr().ListUserMemberships(c.Request().Context(), *user.WorkOSUserID)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ type orgResp struct {+ ID uuid.UUID `json:"id"`+ Name string `json:"name"`+ IsPersonal bool `json:"isPersonal"`+ IsActive bool `json:"isActive"`+ }++ var orgs []orgResp+ for _, m := range memberships {+ localOrg, err := s.store.GetOrgByWorkOSID(c.Request().Context(), m.OrganizationID)+ if err != nil {+ continue+ }+ orgs = append(orgs, orgResp{+ ID: localOrg.ID,+ Name: localOrg.Name,+ IsPersonal: localOrg.IsPersonal,+ IsActive: localOrg.ID == user.OrgID,+ })+ }++ return c.JSON(http.StatusOK, orgs)+}++// dashboardSwitchOrg switches the user's active org.+func (s *Server) dashboardSwitchOrg(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})+ }++ var req struct {+ OrgID uuid.UUID `json:"orgId"`+ }+ if err := c.Bind(&req); err != nil || req.OrgID == uuid.Nil {+ return c.JSON(http.StatusBadRequest, map[string]string{"error": "orgId is required"})+ }++ email, ok := c.Get("user_email").(string)+ if !ok || email == "" {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "auth required"})+ }++ user, err := s.store.GetUserByEmail(c.Request().Context(), email)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "user not found"})+ }++ // Validate the user has access to the target org via WorkOS+ if s.workos != nil && s.workos.OrgMgr() != nil && user.WorkOSUserID != nil {+ targetOrg, err := s.store.GetOrg(c.Request().Context(), req.OrgID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "target org not found"})+ }+ if targetOrg.WorkOSOrgID != nil {+ memberships, err := s.workos.OrgMgr().ListUserMemberships(c.Request().Context(), *user.WorkOSUserID)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }+ found := false+ for _, m := range memberships {+ if m.OrganizationID == *targetOrg.WorkOSOrgID {+ found = true+ break+ }+ }+ if !found {+ return c.JSON(http.StatusForbidden, map[string]string{"error": "not a member of this org"})+ }+ }+ }++ if err := s.store.SetActiveOrg(c.Request().Context(), user.ID, req.OrgID); err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ org, err := s.store.GetOrg(c.Request().Context(), req.OrgID)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ return c.JSON(http.StatusOK, org)+}++// dashboardGetCredits returns the credit balance for the current org.+func (s *Server) dashboardGetCredits(c echo.Context) error {+ if s.store == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})+ }++ orgID, ok := auth.GetOrgID(c)+ if !ok {+ return c.JSON(http.StatusUnauthorized, map[string]string{"error": "org context required"})+ }++ org, err := s.store.GetOrg(c.Request().Context(), orgID)+ if err != nil {+ return c.JSON(http.StatusNotFound, map[string]string{"error": "org not found"})+ }++ return c.JSON(http.StatusOK, map[string]interface{}{+ "balanceCents": org.CreditBalanceCents,+ "isPersonal": org.IsPersonal,+ })+}++// dashboardBackfillWorkOSOrgs is a one-time admin endpoint to create WorkOS orgs+// for existing orgs that predate the WorkOS integration.+func (s *Server) dashboardBackfillWorkOSOrgs(c echo.Context) error {+ if s.store == nil || s.workos == nil || s.workos.OrgMgr() == nil {+ return c.JSON(http.StatusServiceUnavailable, map[string]string{"error": "not configured"})+ }++ ctx := c.Request().Context()+ orgs, err := s.store.ListOrgsWithoutWorkOS(ctx)+ if err != nil {+ return c.JSON(http.StatusInternalServerError, map[string]string{"error": err.Error()})+ }++ type result struct {+ OrgID uuid.UUID `json:"orgId"`+ OrgName string `json:"orgName"`+ WorkOSOrgID string `json:"workosOrgId,omitempty"`+ Error string `json:"error,omitempty"`+ }++ var results []result+ for _, org := range orgs {+ workosOrgID, err := s.workos.OrgMgr().CreateOrganization(ctx, org.Name)+ if err != nil {+ log.Printf("backfill: failed to create WorkOS org for %s: %v", org.Name, err)+ results = append(results, result{OrgID: org.ID, OrgName: org.Name, Error: err.Error()})+ continue+ }++ if err := s.store.UpdateOrgWorkOSID(ctx, org.ID, workosOrgID); err != nil {+ log.Printf("backfill: failed to update org %s with WorkOS ID: %v", org.Name, err)+ results = append(results, result{OrgID: org.ID, OrgName: org.Name, Error: err.Error()})+ continue+ }++ // Create WorkOS memberships for all users in this org+ users, err := s.store.ListUsersByOrgID(ctx, org.ID)+ if err == nil {+ for _, user := range users {+ if user.WorkOSUserID != nil {+ _, err := s.workos.OrgMgr().CreateMembership(ctx, workosOrgID, *user.WorkOSUserID, "admin")+ if err != nil {+ log.Printf("backfill: failed to create membership for user %s in org %s: %v", user.Email, org.Name, err)+ }+ }+ }+ }++ log.Printf("backfill: created WorkOS org %s for %s", workosOrgID, org.Name)+ results = append(results, result{OrgID: org.ID, OrgName: org.Name, WorkOSOrgID: workosOrgID})+ }++ return c.JSON(http.StatusOK, map[string]interface{}{+ "processed": len(results),+ "results": results,+ })+}diff --git a/internal/api/router.go b/internal/api/router.goindex 124b38b3..e0b98b5b 100644--- a/internal/api/router.go+++ b/internal/api/router.go@@ -308,6 +308,19 @@ func NewServer(mgr sandbox.Manager, ptyMgr *sandbox.PTYManager, apiKey string, odash.GET("/images", s.dashboardListImages)dash.DELETE("/images/:id", s.dashboardDeleteImage)+ // Organization members and invitations+ dash.GET("/org/members", s.dashboardListOrgMembers)+ dash.DELETE("/org/members/:membershipId", s.dashboardRemoveMember)+ dash.POST("/org/invitations", s.dashboardSendInvitation)+ dash.GET("/org/invitations", s.dashboardListInvitations)+ dash.DELETE("/org/invitations/:id", s.dashboardRevokeInvitation)+ dash.GET("/orgs", s.dashboardListOrgs)+ dash.POST("/org/switch", s.dashboardSwitchOrg)+ dash.GET("/org/credits", s.dashboardGetCredits)++ // Admin endpoints+ dash.POST("/admin/backfill-workos-orgs", s.dashboardBackfillWorkOSOrgs)+// Session detail + statsdash.GET("/sessions/:sandboxId", s.dashboardGetSession)dash.GET("/sessions/:sandboxId/stats", s.dashboardGetSessionStats)diff --git a/internal/auth/oauth_handlers.go b/internal/auth/oauth_handlers.goindex ee7e0863..e906ea2c 100644--- a/internal/auth/oauth_handlers.go+++ b/internal/auth/oauth_handlers.go@@ -7,6 +7,7 @@ import ("net/http""time"+ "github.com/google/uuid""github.com/labstack/echo/v4""github.com/workos/workos-go/v4/pkg/usermanagement")@@ -68,21 +69,25 @@ func (h *OAuthHandlers) HandleCallback(c echo.Context) error {})}- // Verify CSRF state+ // Verify CSRF state — only when the user started from /auth/login (which sets the cookie).+ // Invitation flows bypass login, so the user arrives with a code but no state/cookie.stateCookie, err := c.Cookie("oauth_state")- if err != nil || stateCookie.Value != state {- return c.JSON(http.StatusBadRequest, map[string]string{- "error": "invalid state parameter",+ if err == nil {+ // Cookie exists — verify it matches (normal login flow)+ if stateCookie.Value != state {+ return c.JSON(http.StatusBadRequest, map[string]string{+ "error": "invalid state parameter",+ })+ }+ // Clear state cookie+ c.SetCookie(&http.Cookie{+ Name: "oauth_state",+ Value: "",+ Path: "/",+ MaxAge: -1,})}-- // Clear state cookie- c.SetCookie(&http.Cookie{- Name: "oauth_state",- Value: "",- Path: "/",- MaxAge: -1,- })+ // No cookie = invitation flow — skip CSRF check (code is single-use and client-bound)cfg := h.workos.Config()ctx := c.Request().Context()@@ -108,14 +113,10 @@ func (h *OAuthHandlers) HandleCallback(c echo.Context) error {name = authResult.User.Email}- // Determine org name — use organization ID, or create a personal org per user- orgName := authResult.User.Email // personal org keyed by email- if authResult.OrganizationID != "" {- orgName = authResult.OrganizationID- }-// Provision org and user in local database- localUser, err := h.workos.ProvisionOrgAndUser(ctx, authResult.User.Email, name, orgName)+ // orgName is used for slug generation; workosOrgID is set if user was invited to an org+ orgName := authResult.User.Email+ localUser, err := h.workos.ProvisionOrgAndUser(ctx, authResult.User.Email, name, orgName, authResult.User.ID, authResult.OrganizationID)if err != nil {log.Printf("workos: provisioning failed: %v", err)return c.JSON(http.StatusInternalServerError, map[string]string{@@ -173,11 +174,47 @@ func (h *OAuthHandlers) HandleMe(c echo.Context) error {email := c.Get("user_email")orgID, _ := GetOrgID(c)- return c.JSON(http.StatusOK, map[string]interface{}{+ resp := map[string]interface{}{"id": userID,"email": email,"orgId": orgID,- })+ }++ // If we have a store and WorkOS org manager, include the user's org list+ store := h.workos.Store()+ orgMgr := h.workos.OrgMgr()+ if store != nil && orgMgr != nil {+ if uid, ok := userID.(uuid.UUID); ok {+ user, err := store.GetUserByEmail(c.Request().Context(), email.(string))+ if err == nil && user.WorkOSUserID != nil {+ memberships, err := orgMgr.ListUserMemberships(c.Request().Context(), *user.WorkOSUserID)+ if err == nil {+ type orgInfo struct {+ ID uuid.UUID `json:"id"`+ Name string `json:"name"`+ IsPersonal bool `json:"isPersonal"`+ IsActive bool `json:"isActive"`+ }+ var orgs []orgInfo+ for _, m := range memberships {+ localOrg, err := store.GetOrgByWorkOSID(c.Request().Context(), m.OrganizationID)+ if err == nil {+ orgs = append(orgs, orgInfo{+ ID: localOrg.ID,+ Name: localOrg.Name,+ IsPersonal: localOrg.IsPersonal,+ IsActive: localOrg.ID == user.OrgID,+ })+ }+ }+ resp["orgs"] = orgs+ }+ }+ _ = uid // suppress unused+ }+ }++ return c.JSON(http.StatusOK, resp)}// isSecureRequest returns true if the request is over HTTPS,diff --git a/internal/auth/workos.go b/internal/auth/workos.goindex 6e206e48..914d03df 100644--- a/internal/auth/workos.go+++ b/internal/auth/workos.go@@ -28,18 +28,21 @@ type WorkOSConfig struct {// It checks for a session cookie or Authorization header, validates with WorkOS,// and provisions orgs/users in the local database on first login.type WorkOSMiddleware struct {- config WorkOSConfig- store *db.Store- userMgr *usermanagement.Client+ config WorkOSConfig+ store *db.Store+ userMgr *usermanagement.Client+ orgManager *OrgManager}// NewWorkOSMiddleware creates WorkOS session middleware.func NewWorkOSMiddleware(config WorkOSConfig, store *db.Store) *WorkOSMiddleware {var userMgr *usermanagement.Client+ var orgMgr *OrgManagerif config.APIKey != "" {userMgr = usermanagement.NewClient(config.APIKey)+ orgMgr = NewOrgManager(config.APIKey)}- return &WorkOSMiddleware{config: config, store: store, userMgr: userMgr}+ return &WorkOSMiddleware{config: config, store: store, userMgr: userMgr, orgManager: orgMgr}}// Middleware returns the Echo middleware function.@@ -110,6 +113,11 @@ func (w *WorkOSMiddleware) Store() *db.Store {return w.store}+// OrgMgr returns the WorkOS organization manager.+func (w *WorkOSMiddleware) OrgMgr() *OrgManager {+ return w.orgManager+}+// validateSession validates a WorkOS access token by looking up the user// in the local database. The access token is the one returned by// AuthenticateWithCode during the OAuth callback, and the user was@@ -146,7 +154,9 @@ func (w *WorkOSMiddleware) validateSession(ctx context.Context, accessToken stri// ProvisionOrgAndUser creates or fetches an org and user based on WorkOS data.// Called on first login to auto-provision local records.-func (w *WorkOSMiddleware) ProvisionOrgAndUser(ctx context.Context, email, name, orgName string) (*WorkOSUser, error) {+// workosUserID is the WorkOS user ID from the auth result.+// workosOrgID is the WorkOS organization ID if the user was invited to an org.+func (w *WorkOSMiddleware) ProvisionOrgAndUser(ctx context.Context, email, name, orgName, workosUserID, workosOrgID string) (*WorkOSUser, error) {if w.store == nil {return nil, fmt.Errorf("database not configured")}@@ -154,6 +164,15 @@ func (w *WorkOSMiddleware) ProvisionOrgAndUser(ctx context.Context, email, name,// Check if user existsexistingUser, err := w.store.GetUserByEmail(ctx, email)if err == nil {+ // User exists — if they came through an invitation to a new org, switch them to it+ if workosOrgID != "" {+ if invitedOrg, err := w.store.GetOrgByWorkOSID(ctx, workosOrgID); err == nil {+ if invitedOrg.ID != existingUser.OrgID {+ _ = w.store.SetActiveOrg(ctx, existingUser.ID, invitedOrg.ID)+ existingUser.OrgID = invitedOrg.ID+ }+ }+ }return &WorkOSUser{ID: existingUser.ID,OrgID: existingUser.OrgID,@@ -162,39 +181,91 @@ func (w *WorkOSMiddleware) ProvisionOrgAndUser(ctx context.Context, email, name,}, nil}- // Create org (slug from org name — sanitize for emails and special chars)+ // --- New user: create personal org ---++ // Create a WorkOS organization for the user's personal workspace+ personalOrgName := email + "'s Workspace"+ var workosPersonalOrgID string+ if w.orgManager != nil {+ wid, err := w.orgManager.CreateOrganization(ctx, personalOrgName)+ if err != nil {+ log.Printf("workos: failed to create WorkOS org for %s: %v", email, err)+ // Continue without WorkOS org — can be backfilled later+ } else {+ workosPersonalOrgID = wid+ }+ }++ // Create local orgslug := strings.ToLower(orgName)slug = strings.ReplaceAll(slug, "@", "-at-")slug = strings.ReplaceAll(slug, ".", "-")slug = strings.ReplaceAll(slug, " ", "-")- org, err := w.store.GetOrgBySlug(ctx, slug)++ var org *db.Org+ if workosPersonalOrgID != "" {+ org, err = w.store.CreateOrgWithWorkOS(ctx, personalOrgName, slug, workosPersonalOrgID, true, nil)+ } else {+ org, err = w.store.CreateOrg(ctx, personalOrgName, slug)+ }if err != nil {- org, err = w.store.CreateOrg(ctx, orgName, slug)+ // Slug collision — try to get existing org+ org, err = w.store.GetOrgBySlug(ctx, slug)if err != nil {return nil, fmt.Errorf("failed to create org: %w", err)}+ } else {log.Printf("workos: provisioned new org: %s (%s)", org.Name, org.ID)+ }- // Generate a default API key for the new org- apiKey, err := GenerateAPIKey()- if err == nil {- hash := db.HashAPIKey(apiKey)- prefix := apiKey[:8]- _, _ = w.store.CreateAPIKey(ctx, org.ID, nil, hash, prefix, "Default", []string{"sandbox:*"})- log.Printf("workos: created default API key for org %s: %s...", org.Slug, prefix)- }+ // Generate a default API key for the new org+ apiKey, err := GenerateAPIKey()+ if err == nil {+ hash := db.HashAPIKey(apiKey)+ prefix := apiKey[:8]+ _, _ = w.store.CreateAPIKey(ctx, org.ID, nil, hash, prefix, "Default", []string{"sandbox:*"})+ log.Printf("workos: created default API key for org %s: %s...", org.Slug, prefix)}- // Create user- user, err := w.store.CreateUser(ctx, org.ID, email, name, "admin")+ // Determine which org the user should be active in+ activeOrgID := org.ID++ // Create user with WorkOS user ID+ var user *db.User+ if workosUserID != "" {+ user, err = w.store.CreateUserWithWorkOS(ctx, activeOrgID, email, name, "admin", workosUserID)+ } else {+ user, err = w.store.CreateUser(ctx, activeOrgID, email, name, "admin")+ }if err != nil {return nil, fmt.Errorf("failed to create user: %w", err)}log.Printf("workos: provisioned new user: %s (%s)", user.Email, user.ID)+ // Set the owner_user_id on the org now that we have the user ID+ if org.OwnerUserID == nil {+ _ = w.store.SetOrgOwner(ctx, org.ID, user.ID)+ }++ // Create WorkOS membership linking user to their personal org+ if w.orgManager != nil && workosPersonalOrgID != "" && workosUserID != "" {+ _, err := w.orgManager.CreateMembership(ctx, workosPersonalOrgID, workosUserID, "admin")+ if err != nil {+ log.Printf("workos: failed to create membership for %s: %v", email, err)+ }+ }++ // If user was invited to another org, switch their active org to it+ if workosOrgID != "" && workosOrgID != workosPersonalOrgID {+ if invitedOrg, err := w.store.GetOrgByWorkOSID(ctx, workosOrgID); err == nil {+ _ = w.store.SetActiveOrg(ctx, user.ID, invitedOrg.ID)+ activeOrgID = invitedOrg.ID+ }+ }+return &WorkOSUser{ID: user.ID,- OrgID: user.OrgID,+ OrgID: activeOrgID,Email: user.Email,Name: user.Name,}, nildiff --git a/internal/auth/workos_orgs.go b/internal/auth/workos_orgs.gonew file mode 100644index 00000000..05df3a94--- /dev/null+++ b/internal/auth/workos_orgs.go@@ -0,0 +1,184 @@+package auth++import (+ "context"+ "fmt"++ "github.com/workos/workos-go/v4/pkg/organizations"+ "github.com/workos/workos-go/v4/pkg/usermanagement"+)++// OrgManager wraps WorkOS organization and membership SDK calls.+type OrgManager struct {+ orgClient *organizations.Client+ userMgr *usermanagement.Client+}++// NewOrgManager creates a new OrgManager with the given WorkOS API key.+func NewOrgManager(apiKey string) *OrgManager {+ return &OrgManager{+ orgClient: &organizations.Client{APIKey: apiKey},+ userMgr: usermanagement.NewClient(apiKey),+ }+}++// CreateOrganization creates a new WorkOS organization and returns its ID.+func (m *OrgManager) CreateOrganization(ctx context.Context, name string) (string, error) {+ org, err := m.orgClient.CreateOrganization(ctx, organizations.CreateOrganizationOpts{+ Name: name,+ })+ if err != nil {+ return "", fmt.Errorf("workos: failed to create organization: %w", err)+ }+ return org.ID, nil+}++// UpdateOrganization renames a WorkOS organization.+func (m *OrgManager) UpdateOrganization(ctx context.Context, orgID, name string) error {+ _, err := m.orgClient.UpdateOrganization(ctx, organizations.UpdateOrganizationOpts{+ Organization: orgID,+ Name: name,+ })+ if err != nil {+ return fmt.Errorf("workos: failed to update organization: %w", err)+ }+ return nil+}++// GetOrganization returns a WorkOS organization by ID.+func (m *OrgManager) GetOrganization(ctx context.Context, orgID string) (*organizations.Organization, error) {+ org, err := m.orgClient.GetOrganization(ctx, organizations.GetOrganizationOpts{+ Organization: orgID,+ })+ if err != nil {+ return nil, fmt.Errorf("workos: failed to get organization: %w", err)+ }+ return &org, nil+}++// CreateMembership adds a user to a WorkOS organization.+func (m *OrgManager) CreateMembership(ctx context.Context, workosOrgID, workosUserID string, roleSlug string) (string, error) {+ membership, err := m.userMgr.CreateOrganizationMembership(ctx, usermanagement.CreateOrganizationMembershipOpts{+ UserID: workosUserID,+ OrganizationID: workosOrgID,+ RoleSlug: roleSlug,+ })+ if err != nil {+ return "", fmt.Errorf("workos: failed to create membership: %w", err)+ }+ return membership.ID, nil+}++// ListMemberships returns all memberships for a WorkOS organization.+func (m *OrgManager) ListMemberships(ctx context.Context, workosOrgID string) ([]usermanagement.OrganizationMembership, error) {+ var all []usermanagement.OrganizationMembership+ var after string+ for {+ resp, err := m.userMgr.ListOrganizationMemberships(ctx, usermanagement.ListOrganizationMembershipsOpts{+ OrganizationID: workosOrgID,+ Limit: 100,+ After: after,+ })+ if err != nil {+ return nil, fmt.Errorf("workos: failed to list memberships: %w", err)+ }+ all = append(all, resp.Data...)+ if resp.ListMetadata.After == "" {+ break+ }+ after = resp.ListMetadata.After+ }+ return all, nil+}++// ListUserMemberships returns all org memberships for a specific WorkOS user.+func (m *OrgManager) ListUserMemberships(ctx context.Context, workosUserID string) ([]usermanagement.OrganizationMembership, error) {+ var all []usermanagement.OrganizationMembership+ var after string+ for {+ resp, err := m.userMgr.ListOrganizationMemberships(ctx, usermanagement.ListOrganizationMembershipsOpts{+ UserID: workosUserID,+ Limit: 100,+ After: after,+ })+ if err != nil {+ return nil, fmt.Errorf("workos: failed to list user memberships: %w", err)+ }+ all = append(all, resp.Data...)+ if resp.ListMetadata.After == "" {+ break+ }+ after = resp.ListMetadata.After+ }+ return all, nil+}++// DeleteMembership removes a user from a WorkOS organization.+func (m *OrgManager) DeleteMembership(ctx context.Context, membershipID string) error {+ err := m.userMgr.DeleteOrganizationMembership(ctx, usermanagement.DeleteOrganizationMembershipOpts{+ OrganizationMembership: membershipID,+ })+ if err != nil {+ return fmt.Errorf("workos: failed to delete membership: %w", err)+ }+ return nil+}++// SendInvitation sends an invitation to join a WorkOS organization.+func (m *OrgManager) SendInvitation(ctx context.Context, email, workosOrgID, inviterUserID, roleSlug string, expiresInDays int) (*usermanagement.Invitation, error) {+ inv, err := m.userMgr.SendInvitation(ctx, usermanagement.SendInvitationOpts{+ Email: email,+ OrganizationID: workosOrgID,+ InviterUserID: inviterUserID,+ RoleSlug: roleSlug,+ ExpiresInDays: expiresInDays,+ })+ if err != nil {+ return nil, fmt.Errorf("workos: failed to send invitation: %w", err)+ }+ return &inv, nil+}++// ListInvitations returns pending invitations for a WorkOS organization.+func (m *OrgManager) ListInvitations(ctx context.Context, workosOrgID string) ([]usermanagement.Invitation, error) {+ var all []usermanagement.Invitation+ var after string+ for {+ resp, err := m.userMgr.ListInvitations(ctx, usermanagement.ListInvitationsOpts{+ OrganizationID: workosOrgID,+ Limit: 100,+ After: after,+ })+ if err != nil {+ return nil, fmt.Errorf("workos: failed to list invitations: %w", err)+ }+ all = append(all, resp.Data...)+ if resp.ListMetadata.After == "" {+ break+ }+ after = resp.ListMetadata.After+ }+ return all, nil+}++// RevokeInvitation revokes a pending WorkOS invitation.+func (m *OrgManager) RevokeInvitation(ctx context.Context, invitationID string) error {+ _, err := m.userMgr.RevokeInvitation(ctx, usermanagement.RevokeInvitationOpts{+ Invitation: invitationID,+ })+ if err != nil {+ return fmt.Errorf("workos: failed to revoke invitation: %w", err)+ }+ return nil+}++// GetUser returns a WorkOS user by ID.+func (m *OrgManager) GetUser(ctx context.Context, userID string) (*usermanagement.User, error) {+ user, err := m.userMgr.GetUser(ctx, usermanagement.GetUserOpts{+ User: userID,+ })+ if err != nil {+ return nil, fmt.Errorf("workos: failed to get user: %w", err)+ }+ return &user, nil+}diff --git a/internal/db/migrations/016_orgs_workos.down.sql b/internal/db/migrations/016_orgs_workos.down.sqlnew file mode 100644index 00000000..5dd0c428--- /dev/null+++ b/internal/db/migrations/016_orgs_workos.down.sql@@ -0,0 +1,5 @@+ALTER TABLE users DROP COLUMN IF EXISTS workos_user_id;+ALTER TABLE orgs DROP COLUMN IF EXISTS credit_balance_cents;+ALTER TABLE orgs DROP COLUMN IF EXISTS owner_user_id;+ALTER TABLE orgs DROP COLUMN IF EXISTS is_personal;+ALTER TABLE orgs DROP COLUMN IF EXISTS workos_org_id;diff --git a/internal/db/migrations/016_orgs_workos.up.sql b/internal/db/migrations/016_orgs_workos.up.sqlnew file mode 100644index 00000000..ef4000eb--- /dev/null+++ b/internal/db/migrations/016_orgs_workos.up.sql@@ -0,0 +1,12 @@+-- Link orgs to WorkOS organizations+ALTER TABLE orgs ADD COLUMN workos_org_id TEXT UNIQUE;+ALTER TABLE orgs ADD COLUMN is_personal BOOLEAN NOT NULL DEFAULT false;+ALTER TABLE orgs ADD COLUMN owner_user_id UUID REFERENCES users(id);+ALTER TABLE orgs ADD COLUMN credit_balance_cents INT NOT NULL DEFAULT 3000;++-- Link users to WorkOS users+ALTER TABLE users ADD COLUMN workos_user_id TEXT UNIQUE;++-- Mark existing orgs as personal (backfill for pre-existing data)+UPDATE orgs SET is_personal = true, owner_user_id = u.id+FROM users u WHERE u.org_id = orgs.id;diff --git a/internal/db/store.go b/internal/db/store.goindex 2c0d1ef9..933c8abd 100644--- a/internal/db/store.go+++ b/internal/db/store.go@@ -87,6 +87,7 @@ func (s *Store) Migrate(ctx context.Context) error {{13, "migrations/013_checkpoint_patches.up.sql"},{14, "migrations/014_image_cache.up.sql"},{15, "migrations/015_projects.up.sql"},+ {16, "migrations/016_orgs_workos.up.sql"},}for _, m := range migrations {@@ -138,12 +139,19 @@ type Org struct {VerificationTxtValue *string `json:"verificationTxtValue,omitempty"`SSLTxtName *string `json:"sslTxtName,omitempty"`SSLTxtValue *string `json:"sslTxtValue,omitempty"`++ // WorkOS organization fields+ WorkOSOrgID *string `json:"workosOrgId,omitempty"`+ IsPersonal bool `json:"isPersonal"`+ OwnerUserID *uuid.UUID `json:"ownerUserId,omitempty"`+ CreditBalanceCents int `json:"creditBalanceCents"`}// orgColumns is the list of columns returned by all Org queries.const orgColumns = `id, name, slug, plan, max_concurrent_sandboxes, max_sandbox_timeout_sec, created_at, updated_at,custom_domain, cf_hostname_id, domain_verification_status, domain_ssl_status,- verification_txt_name, verification_txt_value, ssl_txt_name, ssl_txt_value`+ verification_txt_name, verification_txt_value, ssl_txt_name, ssl_txt_value,+ workos_org_id, is_personal, owner_user_id, credit_balance_cents`// scanOrg scans a row into an Org struct.func scanOrg(row pgx.Row) (*Org, error) {@@ -153,6 +161,7 @@ func scanOrg(row pgx.Row) (*Org, error) {&org.MaxSandboxTimeoutSec, &org.CreatedAt, &org.UpdatedAt,&org.CustomDomain, &org.CFHostnameID, &org.DomainVerificationStatus, &org.DomainSSLStatus,&org.VerificationTxtName, &org.VerificationTxtValue, &org.SSLTxtName, &org.SSLTxtValue,+ &org.WorkOSOrgID, &org.IsPersonal, &org.OwnerUserID, &org.CreditBalanceCents,)return org, err}@@ -264,21 +273,41 @@ func (s *Store) UpdateOrgDomainStatus(ctx context.Context, orgID uuid.UUID, veri// --- User operations ---type User struct {- ID uuid.UUID `json:"id"`- OrgID uuid.UUID `json:"orgId"`- Email string `json:"email"`- Name string `json:"name"`- Role string `json:"role"`- CreatedAt time.Time `json:"createdAt"`+ ID uuid.UUID `json:"id"`+ OrgID uuid.UUID `json:"orgId"`+ Email string `json:"email"`+ Name string `json:"name"`+ Role string `json:"role"`+ CreatedAt time.Time `json:"createdAt"`+ WorkOSUserID *string `json:"workosUserId,omitempty"`}-func (s *Store) CreateUser(ctx context.Context, orgID uuid.UUID, email, name, role string) (*User, error) {+const userColumns = `id, org_id, email, name, role, created_at, workos_user_id`++func scanUser(row pgx.Row) (*User, error) {user := &User{}- err := s.pool.QueryRow(ctx,+ err := row.Scan(&user.ID, &user.OrgID, &user.Email, &user.Name, &user.Role, &user.CreatedAt, &user.WorkOSUserID)+ return user, err+}++func (s *Store) CreateUser(ctx context.Context, orgID uuid.UUID, email, name, role string) (*User, error) {+ user, err := scanUser(s.pool.QueryRow(ctx,`INSERT INTO users (org_id, email, name, role) VALUES ($1, $2, $3, $4)- RETURNING id, org_id, email, name, role, created_at`,+ RETURNING `+userColumns,orgID, email, name, role,- ).Scan(&user.ID, &user.OrgID, &user.Email, &user.Name, &user.Role, &user.CreatedAt)+ ))+ if err != nil {+ return nil, fmt.Errorf("failed to create user: %w", err)+ }+ return user, nil+}++func (s *Store) CreateUserWithWorkOS(ctx context.Context, orgID uuid.UUID, email, name, role, workosUserID string) (*User, error) {+ user, err := scanUser(s.pool.QueryRow(ctx,+ `INSERT INTO users (org_id, email, name, role, workos_user_id) VALUES ($1, $2, $3, $4, $5)+ RETURNING `+userColumns,+ orgID, email, name, role, workosUserID,+ ))if err != nil {return nil, fmt.Errorf("failed to create user: %w", err)}@@ -286,10 +315,9 @@ func (s *Store) CreateUser(ctx context.Context, orgID uuid.UUID, email, name, ro}func (s *Store) GetUserByEmail(ctx context.Context, email string) (*User, error) {- user := &User{}- err := s.pool.QueryRow(ctx,- `SELECT id, org_id, email, name, role, created_at FROM users WHERE email = $1`, email,- ).Scan(&user.ID, &user.OrgID, &user.Email, &user.Name, &user.Role, &user.CreatedAt)+ user, err := scanUser(s.pool.QueryRow(ctx,+ `SELECT `+userColumns+` FROM users WHERE email = $1`, email,+ ))if err != nil {return nil, fmt.Errorf("user not found: %w", err)}@@ -607,12 +635,12 @@ func (s *Store) StoreAccessToken(ctx context.Context, userID uuid.UUID, accessTofunc (s *Store) GetUserByAccessToken(ctx context.Context, accessToken string) (*User, error) {user := &User{}err := s.pool.QueryRow(ctx,- `SELECT u.id, u.org_id, u.email, u.name, u.role, u.created_at+ `SELECT u.id, u.org_id, u.email, u.name, u.role, u.created_at, u.workos_user_idFROM users uINNER JOIN user_sessions s ON s.user_id = u.idWHERE s.access_token = $1 AND s.expires_at > now()`,accessToken,- ).Scan(&user.ID, &user.OrgID, &user.Email, &user.Name, &user.Role, &user.CreatedAt)+ ).Scan(&user.ID, &user.OrgID, &user.Email, &user.Name, &user.Role, &user.CreatedAt, &user.WorkOSUserID)if err != nil {return nil, fmt.Errorf("session not found or expired: %w", err)}@@ -625,6 +653,129 @@ func (s *Store) DeleteAccessTokensForUser(ctx context.Context, userID uuid.UUID)return err}+// --- WorkOS Org integration operations ---++// CreateOrgWithWorkOS creates an org with WorkOS organization fields.+func (s *Store) CreateOrgWithWorkOS(ctx context.Context, name, slug, workosOrgID string, isPersonal bool, ownerUserID *uuid.UUID) (*Org, error) {+ org, err := scanOrg(s.pool.QueryRow(ctx,+ `INSERT INTO orgs (name, slug, workos_org_id, is_personal, owner_user_id)+ VALUES ($1, $2, $3, $4, $5)+ RETURNING `+orgColumns,+ name, slug, workosOrgID, isPersonal, ownerUserID,+ ))+ if err != nil {+ return nil, fmt.Errorf("failed to create org: %w", err)+ }+ return org, nil+}++// GetOrgByWorkOSID looks up a local org by its WorkOS organization ID.+func (s *Store) GetOrgByWorkOSID(ctx context.Context, workosOrgID string) (*Org, error) {+ org, err := scanOrg(s.pool.QueryRow(ctx,+ `SELECT `+orgColumns+` FROM orgs WHERE workos_org_id = $1`, workosOrgID,+ ))+ if err != nil {+ return nil, fmt.Errorf("org not found by workos_org_id: %w", err)+ }+ return org, nil+}++// SetActiveOrg updates the user's active org (users.org_id).+func (s *Store) SetActiveOrg(ctx context.Context, userID, orgID uuid.UUID) error {+ tag, err := s.pool.Exec(ctx,+ `UPDATE users SET org_id = $1 WHERE id = $2`, orgID, userID)+ if err != nil {+ return fmt.Errorf("failed to set active org: %w", err)+ }+ if tag.RowsAffected() == 0 {+ return fmt.Errorf("user not found")+ }+ return nil+}++// SetOrgOwner sets the owner_user_id on an org.+func (s *Store) SetOrgOwner(ctx context.Context, orgID, userID uuid.UUID) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE orgs SET owner_user_id = $1, updated_at = now() WHERE id = $2`,+ userID, orgID)+ return err+}++// UpdateOrgWorkOSID sets the WorkOS org ID on an existing org (used for backfill).+func (s *Store) UpdateOrgWorkOSID(ctx context.Context, orgID uuid.UUID, workosOrgID string) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE orgs SET workos_org_id = $1, updated_at = now() WHERE id = $2`,+ workosOrgID, orgID)+ return err+}++// UpdateUserWorkOSID sets the WorkOS user ID on an existing user (used for backfill).+func (s *Store) UpdateUserWorkOSID(ctx context.Context, userID uuid.UUID, workosUserID string) error {+ _, err := s.pool.Exec(ctx,+ `UPDATE users SET workos_user_id = $1 WHERE id = $2`,+ workosUserID, userID)+ return err+}++// ListOrgsWithoutWorkOS returns orgs that have no WorkOS org ID (for backfill).+func (s *Store) ListOrgsWithoutWorkOS(ctx context.Context) ([]*Org, error) {+ rows, err := s.pool.Query(ctx,+ `SELECT `+orgColumns+` FROM orgs WHERE workos_org_id IS NULL ORDER BY created_at`)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var orgs []*Org+ for rows.Next() {+ org := &Org{}+ err := rows.Scan(+ &org.ID, &org.Name, &org.Slug, &org.Plan, &org.MaxConcurrentSandboxes,+ &org.MaxSandboxTimeoutSec, &org.CreatedAt, &org.UpdatedAt,+ &org.CustomDomain, &org.CFHostnameID, &org.DomainVerificationStatus, &org.DomainSSLStatus,+ &org.VerificationTxtName, &org.VerificationTxtValue, &org.SSLTxtName, &org.SSLTxtValue,+ &org.WorkOSOrgID, &org.IsPersonal, &org.OwnerUserID, &org.CreditBalanceCents,+ )+ if err != nil {+ return nil, err+ }+ orgs = append(orgs, org)+ }+ return orgs, nil+}++// GetUserByWorkOSID looks up a user by their WorkOS user ID.+func (s *Store) GetUserByWorkOSID(ctx context.Context, workosUserID string) (*User, error) {+ user, err := scanUser(s.pool.QueryRow(ctx,+ `SELECT `+userColumns+` FROM users WHERE workos_user_id = $1`, workosUserID,+ ))+ if err != nil {+ return nil, fmt.Errorf("user not found by workos_user_id: %w", err)+ }+ return user, nil+}++// ListUsersByOrgID returns all users in an org.+func (s *Store) ListUsersByOrgID(ctx context.Context, orgID uuid.UUID) ([]*User, error) {+ rows, err := s.pool.Query(ctx,+ `SELECT `+userColumns+` FROM users WHERE org_id = $1 ORDER BY created_at`, orgID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()++ var users []*User+ for rows.Next() {+ user := &User{}+ err := rows.Scan(&user.ID, &user.OrgID, &user.Email, &user.Name, &user.Role, &user.CreatedAt, &user.WorkOSUserID)+ if err != nil {+ return nil, err+ }+ users = append(users, user)+ }+ return users, nil+}+// Pool returns the underlying pgx pool for advanced use cases.func (s *Store) Pool() *pgxpool.Pool {return s.pooldiff --git a/web/src/api/client.ts b/web/src/api/client.tsindex 8eb7772a..a8bf72f5 100644--- a/web/src/api/client.ts+++ b/web/src/api/client.ts@@ -36,7 +36,7 @@ export async function logout(): Promise<void> {}// API functions-export const getMe = () => apiFetch<{ id: string; email: string; orgId: string }>('/me')+export const getMe = () => apiFetch<MeResponse>('/me')export const getSessions = (status?: string) =>apiFetch<Session[]>(`/sessions${status ? `?status=${status}` : ''}`)@@ -202,4 +202,72 @@ export interface Org {verificationTxtValue?: stringsslTxtName?: stringsslTxtValue?: string+ workosOrgId?: string+ isPersonal: boolean+ creditBalanceCents: number}++export interface MeResponse {+ id: string+ email: string+ orgId: string+ orgs?: OrgInfo[]+}++export interface OrgInfo {+ id: string+ name: string+ isPersonal: boolean+ isActive: boolean+}++export interface OrgMember {+ membershipId?: string+ workosUserId?: string+ id?: string+ email: string+ name: string+ role: string+ status?: string+}++export interface OrgInvitation {+ id: string+ email: string+ state: string+ role?: string+ expiresAt: string+ createdAt: string+}++export interface Credits {+ balanceCents: number+ isPersonal: boolean+}++// Organization members+export const getOrgMembers = () => apiFetch<OrgMember[]>('/org/members')++export const removeMember = (membershipId: string) =>+ apiFetch<void>(`/org/members/${membershipId}`, { method: 'DELETE' })++// Invitations+export const sendInvitation = (email: string, role = 'member') =>+ apiFetch<OrgInvitation>('/org/invitations', {+ method: 'POST',+ body: JSON.stringify({ email, role }),+ })++export const getInvitations = () => apiFetch<OrgInvitation[]>('/org/invitations')++export const revokeInvitation = (id: string) =>+ apiFetch<void>(`/org/invitations/${id}`, { method: 'DELETE' })++// Org switching+export const listOrgs = () => apiFetch<OrgInfo[]>('/orgs')++export const switchOrg = (orgId: string) =>+ apiFetch<Org>('/org/switch', { method: 'POST', body: JSON.stringify({ orgId }) })++// Credits+export const getCredits = () => apiFetch<Credits>('/org/credits')diff --git a/web/src/components/Layout.tsx b/web/src/components/Layout.tsxindex e39c9522..d0cf41e3 100644--- a/web/src/components/Layout.tsx+++ b/web/src/components/Layout.tsx@@ -1,3 +1,4 @@+import { useState } from 'react'import { NavLink, Outlet } from 'react-router-dom'import { useAuth } from '../hooks/useAuth'import { logout } from '../api/client'@@ -62,7 +63,10 @@ const navItems = []export default function Layout() {- const { user } = useAuth()+ const { user, switchOrg } = useAuth()+ const [orgSwitcherOpen, setOrgSwitcherOpen] = useState(false)+ const hasMultipleOrgs = (user?.orgs?.length ?? 0) > 1+ const activeOrg = user?.orgs?.find(o => o.isActive)return (<div style={{ display: 'flex', minHeight: '100vh' }}>@@ -107,6 +111,60 @@ export default function Layout() {</div></div>+ {/* Org Switcher (only visible with multiple orgs) */}+ {hasMultipleOrgs && (+ <div style={{ padding: '10px 12px', borderBottom: '1px solid var(--border-subtle)', position: 'relative' }}>+ <button+ onClick={() => setOrgSwitcherOpen(!orgSwitcherOpen)}+ style={{+ width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ padding: '8px 10px', background: 'rgba(255,255,255,0.03)',+ border: '1px solid var(--border-subtle)', borderRadius: 6,+ cursor: 'pointer', color: 'var(--text-primary)', fontSize: 12,+ fontFamily: 'var(--font-body)',+ }}+ >+ <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>+ {activeOrg?.name || 'Select org'}+ </span>+ <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">+ <polyline points="6 9 12 15 18 9" />+ </svg>+ </button>+ {orgSwitcherOpen && (+ <div style={{+ position: 'absolute', top: '100%', left: 12, right: 12,+ background: 'var(--bg-deep)', border: '1px solid var(--border-subtle)',+ borderRadius: 6, marginTop: 4, zIndex: 100,+ boxShadow: '0 4px 16px rgba(0,0,0,0.3)',+ }}>+ {user?.orgs?.map(org => (+ <button+ key={org.id}+ onClick={() => {+ switchOrg(org.id)+ setOrgSwitcherOpen(false)+ }}+ style={{+ display: 'block', width: '100%', textAlign: 'left',+ padding: '8px 12px', background: org.isActive ? 'rgba(99,102,241,0.1)' : 'none',+ border: 'none', cursor: 'pointer',+ color: org.isActive ? 'var(--text-primary)' : 'var(--text-secondary)',+ fontSize: 12, fontFamily: 'var(--font-body)',+ borderBottom: '1px solid var(--border-subtle)',+ }}+ onMouseOver={e => { if (!org.isActive) e.currentTarget.style.background = 'rgba(255,255,255,0.03)' }}+ onMouseOut={e => { if (!org.isActive) e.currentTarget.style.background = 'none' }}+ >+ {org.name}+ {org.isPersonal && <span style={{ fontSize: 10, color: 'var(--text-tertiary)', marginLeft: 6 }}>(personal)</span>}+ </button>+ ))}+ </div>+ )}+ </div>+ )}+{/* Nav Links */}<div style={{ flex: 1, padding: '10px 8px' }}>{navItems.map(item => (diff --git a/web/src/hooks/useAuth.tsx b/web/src/hooks/useAuth.tsxindex c0fc090f..75fe6145 100644--- a/web/src/hooks/useAuth.tsx+++ b/web/src/hooks/useAuth.tsx@@ -1,22 +1,27 @@-import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'-import { getMe } from '../api/client'+import { createContext, useContext, useEffect, useState, useCallback, type ReactNode } from 'react'+import { getMe, switchOrg as switchOrgApi, type OrgInfo } from '../api/client'interface AuthUser {id: stringemail: stringorgId: string+ orgs?: OrgInfo[]}interface AuthContextValue {user: AuthUser | nullloading: booleanerror: string | null+ switchOrg: (orgId: string) => Promise<void>+ refreshUser: () => Promise<void>}const AuthContext = createContext<AuthContextValue>({user: null,loading: true,error: null,+ switchOrg: async () => {},+ refreshUser: async () => {},})export function AuthProvider({ children }: { children: ReactNode }) {@@ -24,19 +29,28 @@ export function AuthProvider({ children }: { children: ReactNode }) {const [loading, setLoading] = useState(true)const [error, setError] = useState<string | null>(null)- useEffect(() => {- getMe()- .then(setUser)- .catch((err: Error) => {- if (!err.message.includes('Unauthorized')) {- setError(err.message)- }- })- .finally(() => setLoading(false))+ const refreshUser = useCallback(async () => {+ try {+ const me = await getMe()+ setUser(me)+ } catch (err: unknown) {+ if (err instanceof Error && !err.message.includes('Unauthorized')) {+ setError(err.message)+ }+ }}, [])+ useEffect(() => {+ refreshUser().finally(() => setLoading(false))+ }, [refreshUser])++ const switchOrg = useCallback(async (orgId: string) => {+ await switchOrgApi(orgId)+ await refreshUser()+ }, [refreshUser])+return (- <AuthContext.Provider value={{ user, loading, error }}>+ <AuthContext.Provider value={{ user, loading, error, switchOrg, refreshUser }}>{children}</AuthContext.Provider>)diff --git a/web/src/pages/Settings.tsx b/web/src/pages/Settings.tsxindex ca3d3510..2536b082 100644--- a/web/src/pages/Settings.tsx+++ b/web/src/pages/Settings.tsx@@ -1,6 +1,10 @@import { useState, useEffect } from 'react'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'-import { getOrg, updateOrg, setCustomDomain, deleteCustomDomain, refreshCustomDomain } from '../api/client'+import {+ getOrg, updateOrg, setCustomDomain, deleteCustomDomain, refreshCustomDomain,+ getOrgMembers, getInvitations, sendInvitation, revokeInvitation, removeMember,+ type OrgMember, type OrgInvitation,+} from '../api/client'function StatusBadge({ status }: { status: string }) {let color = 'var(--text-tertiary)'@@ -328,6 +332,220 @@ export default function Settings() {</>)}</div>++ {/* Team Members */}+ <TeamMembers />++ {/* Pending Invitations */}+ <PendingInvitations />+ </div>+ )+}++function TeamMembers() {+ const queryClient = useQueryClient()+ const { data: members, isLoading } = useQuery({+ queryKey: ['org-members'],+ queryFn: getOrgMembers,+ })++ const [inviteEmail, setInviteEmail] = useState('')+ const [showInvite, setShowInvite] = useState(false)++ const inviteMutation = useMutation({+ mutationFn: (email: string) => sendInvitation(email),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['org-members'] })+ queryClient.invalidateQueries({ queryKey: ['org-invitations'] })+ setInviteEmail('')+ setShowInvite(false)+ },+ })++ const removeMutation = useMutation({+ mutationFn: (membershipId: string) => removeMember(membershipId),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['org-members'] })+ },+ })++ return (+ <div className="glass-card animate-in stagger-3" style={{ padding: 28, maxWidth: 520, marginTop: 20 }}>+ <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>+ <div>+ <h2 style={{ fontSize: 16, fontWeight: 600, color: 'var(--text-primary)', margin: 0 }}>Team Members</h2>+ <p style={{ fontSize: 13, color: 'var(--text-tertiary)', margin: '4px 0 0' }}>+ People with access to this organization+ </p>+ </div>+ <button+ className="btn-primary"+ onClick={() => setShowInvite(!showInvite)}+ style={{ fontSize: 12, padding: '6px 14px' }}+ >+ Invite+ </button>+ </div>++ {showInvite && (+ <div style={{ marginBottom: 16, display: 'flex', gap: 8 }}>+ <input+ type="email"+ value={inviteEmail}+ onChange={e => setInviteEmail(e.target.value)}+ placeholder="[email protected]"+ className="input"+ style={{ flex: 1 }}+ />+ <button+ className="btn-primary"+ onClick={() => inviteMutation.mutate(inviteEmail)}+ disabled={inviteMutation.isPending || !inviteEmail.trim()}+ style={{ fontSize: 12, padding: '6px 14px', whiteSpace: 'nowrap' }}+ >+ {inviteMutation.isPending ? 'Sending...' : 'Send'}+ </button>+ </div>+ )}+ {inviteMutation.isError && (+ <div style={{ marginBottom: 10, fontSize: 12, color: 'var(--accent-red, #ef4444)' }}>+ {inviteMutation.error?.message}+ </div>+ )}++ {isLoading ? (+ <div style={{ padding: 20, textAlign: 'center' }}>+ <div className="loading-spinner" />+ </div>+ ) : (+ <div>+ {(members ?? []).map((member: OrgMember, i: number) => (+ <div key={member.membershipId || member.id || i} style={{+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ padding: '10px 0',+ borderBottom: i < (members?.length ?? 0) - 1 ? '1px solid var(--border-subtle)' : 'none',+ }}>+ <div>+ <div style={{ fontSize: 13, color: 'var(--text-primary)', fontWeight: 500 }}>+ {member.name || member.email}+ </div>+ <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>+ {member.email}+ </div>+ </div>+ <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>+ <span style={{+ fontSize: 11, fontWeight: 600,+ color: 'var(--text-tertiary)',+ textTransform: 'uppercase',+ letterSpacing: '0.5px',+ }}>+ {member.role}+ </span>+ {member.membershipId && (+ <button+ onClick={() => {+ if (confirm(`Remove ${member.email} from this organization?`)) {+ removeMutation.mutate(member.membershipId!)+ }+ }}+ disabled={removeMutation.isPending}+ style={{+ background: 'none', border: 'none', cursor: 'pointer',+ color: 'var(--text-tertiary)', fontSize: 11,+ padding: '2px 6px',+ }}+ onMouseOver={e => (e.currentTarget.style.color = 'var(--accent-red, #ef4444)')}+ onMouseOut={e => (e.currentTarget.style.color = 'var(--text-tertiary)')}+ >+ Remove+ </button>+ )}+ </div>+ </div>+ ))}+ {(!members || members.length === 0) && (+ <div style={{ fontSize: 13, color: 'var(--text-tertiary)', padding: '10px 0' }}>+ No members yet.+ </div>+ )}+ </div>+ )}+ </div>+ )+}++function PendingInvitations() {+ const queryClient = useQueryClient()+ const { data: invitations, isLoading } = useQuery({+ queryKey: ['org-invitations'],+ queryFn: getInvitations,+ })++ const revokeMutation = useMutation({+ mutationFn: (id: string) => revokeInvitation(id),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['org-invitations'] })+ },+ })++ const pending = (invitations ?? []).filter((inv: OrgInvitation) => inv.state === 'pending')++ // Don't show the section if there are no pending invitations+ if (!isLoading && pending.length === 0) {+ return null+ }++ return (+ <div className="glass-card animate-in stagger-4" style={{ padding: 28, maxWidth: 520, marginTop: 20 }}>+ <div style={{ marginBottom: 18 }}>+ <h2 style={{ fontSize: 16, fontWeight: 600, color: 'var(--text-primary)', margin: 0 }}>Pending Invitations</h2>+ <p style={{ fontSize: 13, color: 'var(--text-tertiary)', margin: '4px 0 0' }}>+ Invitations waiting to be accepted+ </p>+ </div>++ {isLoading ? (+ <div style={{ padding: 20, textAlign: 'center' }}>+ <div className="loading-spinner" />+ </div>+ ) : (+ <div>+ {pending.map((inv: OrgInvitation, i: number) => (+ <div key={inv.id} style={{+ display: 'flex', alignItems: 'center', justifyContent: 'space-between',+ padding: '10px 0',+ borderBottom: i < pending.length - 1 ? '1px solid var(--border-subtle)' : 'none',+ }}>+ <div>+ <div style={{ fontSize: 13, color: 'var(--text-primary)', fontWeight: 500 }}>+ {inv.email}+ </div>+ <div style={{ fontSize: 11, color: 'var(--text-tertiary)' }}>+ {inv.state} · expires {new Date(inv.expiresAt).toLocaleDateString()}+ </div>+ </div>+ <button+ onClick={() => {+ if (confirm(`Revoke invitation for ${inv.email}?`)) {+ revokeMutation.mutate(inv.id)+ }+ }}+ disabled={revokeMutation.isPending}+ style={{+ background: 'none', border: 'none', cursor: 'pointer',+ color: 'var(--text-tertiary)', fontSize: 11,+ padding: '2px 6px',+ }}+ onMouseOver={e => (e.currentTarget.style.color = 'var(--accent-red, #ef4444)')}+ onMouseOut={e => (e.currentTarget.style.color = 'var(--text-tertiary)')}+ >+ Revoke+ </button>+ </div>+ ))}+ </div>+ )}</div>)}