The only tool you need to know what is happening and how to fix it.
Go alertingexception-trackerissue-trackinglogsmetricsmonitoringobservability-platformopen-telemetryotelsession-replaytelemetrytraces
feat: better registration (#289)
narrow-adventure22e80286dbad
diff --git a/backend/app/controllers/auth.controller.go b/backend/app/controllers/auth.controller.goindex 11906d41..deb6bc5e 100644--- a/backend/app/controllers/auth.controller.go+++ b/backend/app/controllers/auth.controller.go@@ -163,16 +163,25 @@ func (a authController) Register(c *gin.Context) {}}- if !validFrameworks[request.Framework] {- traceway.CaptureMessage("Invalid framework received during registration: " + request.Framework)- c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, flutter, android, ios"})+ wantsProject := request.ProjectName != "" || request.Framework != ""+ if wantsProject && (request.ProjectName == "" || request.Framework == "") {+ c.JSON(http.StatusBadRequest, gin.H{"error": "projectName and framework must be provided together"})return}- project, err := transactional.ProjectRepository.CreateWithOrganization(tx, request.ProjectName, request.Framework, org.Id)- if err != nil {- c.AbortWithError(http.StatusInternalServerError, err)- return+ var project *models.Project+ if wantsProject {+ if !validFrameworks[request.Framework] {+ traceway.CaptureMessage("Invalid framework received during registration: " + request.Framework)+ c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, flutter, android, ios"})+ return+ }++ project, err = transactional.ProjectRepository.CreateWithOrganization(tx, request.ProjectName, request.Framework, org.Id)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, err)+ return+ }}token, err := services.GenerateToken(user.Id, user.Email)@@ -187,16 +196,17 @@ func (a authController) Register(c *gin.Context) {return}- // cache can get out of sync here- // the transaction for creating the project is not guaranteed to have- // finished when this is inserted into cache- cache.ProjectCache.AddProject(&models.Project{- Id: project.Id,- Name: project.Name,- Token: project.Token,- Framework: project.Framework,- OrganizationId: project.OrganizationId,- })+ var projectWithUrl *models.ProjectWithBackendUrl+ if project != nil {+ cache.ProjectCache.AddProject(&models.Project{+ Id: project.Id,+ Name: project.Name,+ Token: project.Token,+ Framework: project.Framework,+ OrganizationId: project.OrganizationId,+ })+ projectWithUrl = project.ToProjectWithBackendUrl()+ }organizations, err := transactional.OrganizationRepository.FindByUserIdWithRoles(tx, user.Id)if err != nil {@@ -207,7 +217,7 @@ func (a authController) Register(c *gin.Context) {c.JSON(http.StatusCreated, &models.RegisterResponse{Token: token,User: user.ToResponse(),- Project: *project.ToProjectWithBackendUrl(),+ Project: projectWithUrl,Projects: projects,Organizations: organizations,})diff --git a/backend/app/controllers/dashboard_template.controller.go b/backend/app/controllers/dashboard_template.controller.goindex e08b17c5..4115e2d6 100644--- a/backend/app/controllers/dashboard_template.controller.go+++ b/backend/app/controllers/dashboard_template.controller.go@@ -2,6 +2,7 @@ package controllersimport ("database/sql"+ "errors""fmt""net/http""strconv"@@ -86,11 +87,14 @@ func uniqueDashboardName(existing []*models.Dashboard, base string) string {}}-func installDashboardTemplate(ctx *gin.Context, tx *sql.Tx, template *models.DashboardTemplate, organizationId int) *models.Dashboard {+var errTemplateInvalid = errors.New("invalid dashboard template")++var errDashboardNameTaken = errors.New("dashboard name already exists")++func installDashboardTemplateTx(tx *sql.Tx, template *models.DashboardTemplate, organizationId int, createdBy *int) (*models.Dashboard, error) {def, err := dashboardsvc.ParseDefinition(template.Definition)if err != nil {- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to parse template %s definition: %w", template.Key, err))- return nil+ return nil, traceway.NewStackTraceErrorf("failed to parse template %s definition: %w (%w)", template.Key, err, errTemplateInvalid)}for i := range def.Widgets {def.Widgets[i].WidgetType = strings.TrimSpace(def.Widgets[i].WidgetType)@@ -98,30 +102,21 @@ func installDashboardTemplate(ctx *gin.Context, tx *sql.Tx, template *models.Dasdef.Widgets[i].WidgetType = "line_chart"}if !dashboardsvc.IsAllowedWidgetType(def.Widgets[i].WidgetType) {- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("template %s contains unsupported widget type %s", template.Key, def.Widgets[i].WidgetType))- return nil+ return nil, traceway.NewStackTraceErrorf("template %s contains unsupported widget type %s (%w)", template.Key, def.Widgets[i].WidgetType, errTemplateInvalid)}}dashboardsvc.EnsureWidgetIds(def)definition, err := dashboardsvc.MarshalDefinition(def)if err != nil {- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to marshal template %s definition: %w", template.Key, err))- return nil+ return nil, traceway.NewStackTraceErrorf("failed to marshal template %s definition: %w (%w)", template.Key, err, errTemplateInvalid)}existing, err := transactional.DashboardRepository.FindByOrganization(tx, organizationId)if err != nil {- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to list dashboards: %w", err))- return nil+ return nil, traceway.NewStackTraceErrorf("failed to list dashboards: %w", err)}name := uniqueDashboardName(existing, template.Name)- userId := middleware.GetUserId(ctx)- var createdBy *int- if userId > 0 {- createdBy = &userId- }-templateKey := template.Keynow := time.Now().UTC()dashboard := &models.Dashboard{@@ -137,16 +132,82 @@ func installDashboardTemplate(ctx *gin.Context, tx *sql.Tx, template *models.Dasid, err := transactional.DashboardRepository.Create(tx, dashboard)if err != nil {if db.IsUniqueViolation(err) {+ return nil, errDashboardNameTaken+ }+ return nil, traceway.NewStackTraceErrorf("failed to install template %s: %w", template.Key, err)+ }+ dashboard.Id = id+ return dashboard, nil+}++func installDashboardTemplate(ctx *gin.Context, tx *sql.Tx, template *models.DashboardTemplate, organizationId int) *models.Dashboard {+ userId := middleware.GetUserId(ctx)+ var createdBy *int+ if userId > 0 {+ createdBy = &userId+ }++ dashboard, err := installDashboardTemplateTx(tx, template, organizationId, createdBy)+ if err != nil {+ if errors.Is(err, errDashboardNameTaken) {ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "A dashboard with this name already exists."})return nil}- ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("failed to install template %s: %w", template.Key, err))+ ctx.AbortWithError(http.StatusInternalServerError, err)return nil}- dashboard.Id = idreturn dashboard}+func populateDefaultDashboards(tx *sql.Tx, project *models.Project, createdBy *int) error {+ if project.OrganizationId == nil {+ return nil+ }+ keys := defaultTemplateKeysForFramework(project.Framework)+ if len(keys) == 0 {+ return nil+ }++ existing, err := transactional.DashboardRepository.FindAssignmentsByProject(tx, project.Id)+ if err != nil {+ return err+ }+ if len(existing) > 0 {+ return nil+ }++ position := 0+ for _, key := range keys {+ template, err := transactional.DashboardTemplateRepository.FindByKey(tx, key)+ if err != nil {+ return err+ }+ if template == nil {+ traceway.CaptureException(fmt.Errorf("default dashboard template %s is not seeded", key))+ continue+ }++ dashboard, err := installDashboardTemplateTx(tx, template, *project.OrganizationId, createdBy)+ if err != nil {+ if errors.Is(err, errTemplateInvalid) {+ traceway.CaptureException(err)+ continue+ }+ return err+ }+ if err := transactional.DashboardRepository.CreateAssignment(tx, &models.ProjectDashboard{+ ProjectId: project.Id,+ DashboardId: dashboard.Id,+ Position: position,+ CreatedAt: time.Now().UTC(),+ }); err != nil {+ return err+ }+ position+++ }+ return nil+}+type InstallTemplateRequest struct {OrganizationId *int `json:"organizationId"`ProjectIds []uuid.UUID `json:"projectIds"`diff --git a/backend/app/controllers/oauth.controller.go b/backend/app/controllers/oauth.controller.goindex 1eebcfc2..86673664 100644--- a/backend/app/controllers/oauth.controller.go+++ b/backend/app/controllers/oauth.controller.go@@ -34,8 +34,8 @@ type oauthProvidersResponse struct {type finishOAuthSetupRequest struct {OrganizationName string `json:"organizationName" binding:"required"`Timezone string `json:"timezone" binding:"required"`- ProjectName string `json:"projectName" binding:"required"`- Framework string `json:"framework" binding:"required"`+ ProjectName string `json:"projectName"`+ Framework string `json:"framework"`}func (a oauthController) ListProviders(c *gin.Context) {@@ -217,7 +217,12 @@ func (a oauthController) FinishSetup(c *gin.Context) {return}- if !validFrameworks[request.Framework] {+ wantsProject := request.ProjectName != "" || request.Framework != ""+ if wantsProject && (request.ProjectName == "" || request.Framework == "") {+ c.JSON(http.StatusBadRequest, gin.H{"error": "projectName and framework must be provided together"})+ return+ }+ if wantsProject && !validFrameworks[request.Framework] {c.JSON(http.StatusBadRequest, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, flutter, android, ios"})return}@@ -280,19 +285,23 @@ func (a oauthController) FinishSetup(c *gin.Context) {}}- project, err := transactional.ProjectRepository.CreateWithOrganization(tx, request.ProjectName, request.Framework, org.Id)- if err != nil {- c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: create project: %w", err))- return- }+ var projectWithUrl *models.ProjectWithBackendUrl+ if wantsProject {+ project, err := transactional.ProjectRepository.CreateWithOrganization(tx, request.ProjectName, request.Framework, org.Id)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("FinishSetup: create project: %w", err))+ return+ }- cache.ProjectCache.AddProject(&models.Project{- Id: project.Id,- Name: project.Name,- Token: project.Token,- Framework: project.Framework,- OrganizationId: project.OrganizationId,- })+ cache.ProjectCache.AddProject(&models.Project{+ Id: project.Id,+ Name: project.Name,+ Token: project.Token,+ Framework: project.Framework,+ OrganizationId: project.OrganizationId,+ })+ projectWithUrl = project.ToProjectWithBackendUrl()+ }token, err := services.GenerateToken(user.Id, user.Email)if err != nil {@@ -315,7 +324,7 @@ func (a oauthController) FinishSetup(c *gin.Context) {c.JSON(http.StatusCreated, &models.RegisterResponse{Token: token,User: user.ToResponse(),- Project: *project.ToProjectWithBackendUrl(),+ Project: projectWithUrl,Projects: projects,Organizations: organizations,})diff --git a/backend/app/controllers/project.controller.go b/backend/app/controllers/project.controller.goindex f9ddedc8..5418273d 100644--- a/backend/app/controllers/project.controller.go+++ b/backend/app/controllers/project.controller.go@@ -155,20 +155,14 @@ func (p projectController) CreateProject(c *gin.Context) {return}- // Validate project name- nameLen := utf8.RuneCountInString(request.Name)- if nameLen < 1 || nameLen > 100 {- c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Project name must be between 1 and 100 characters"})- return- }- if !projectNameRegex.MatchString(request.Name) {- c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Project name can only contain letters, numbers, spaces, hyphens, and underscores"})+ if msg := validateProjectName(request.Name); msg != "" {+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": msg})return}if !validFrameworks[request.Framework] {traceway.CaptureMessage("Invalid framework received: " + request.Framework)- c.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, laravel, django, flutter, android, ios"})+ c.JSON(http.StatusUnprocessableEntity, gin.H{"error": invalidFrameworkMessage})return}diff --git a/backend/app/controllers/project_batch.go b/backend/app/controllers/project_batch.gonew file mode 100644index 00000000..0da450ef--- /dev/null+++ b/backend/app/controllers/project_batch.go@@ -0,0 +1,189 @@+package controllers++import (+ "database/sql"+ "errors"+ "net/http"+ "strings"+ "unicode/utf8"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ traceway "go.tracewayapp.com"++ "github.com/tracewayapp/traceway/backend/app/cache"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"+)++const maxBatchProjects = 20++type BatchProjectInput struct {+ Name string `json:"name"`+ Framework string `json:"framework"`+}++type BatchProjectResult struct {+ Project *models.Project+ Status string+}++type batchValidationError struct{ Message string }++func (e *batchValidationError) Error() string { return e.Message }++func validateProjectName(name string) string {+ nameLen := utf8.RuneCountInString(name)+ if nameLen < 1 || nameLen > 100 {+ return "Project name must be between 1 and 100 characters"+ }+ if !projectNameRegex.MatchString(name) {+ return "Project name can only contain letters, numbers, spaces, hyphens, and underscores"+ }+ return ""+}++const invalidFrameworkMessage = "Framework must be one of: gin, fiber, chi, fasthttp, stdlib, custom, react, svelte, vuejs, jquery, react-native, hono, cloudflare, opentelemetry, symfony, laravel, django, flutter, android, ios"++func batchCreateProjects(tx *sql.Tx, orgId int, createdBy int, inputs []BatchProjectInput) ([]BatchProjectResult, error) {+ if len(inputs) == 0 {+ return nil, &batchValidationError{"At least one project is required"}+ }+ if len(inputs) > maxBatchProjects {+ return nil, &batchValidationError{"At most 20 projects per request"}+ }++ for i := range inputs {+ inputs[i].Name = strings.TrimSpace(inputs[i].Name)+ if msg := validateProjectName(inputs[i].Name); msg != "" {+ return nil, &batchValidationError{msg}+ }+ if !validFrameworks[inputs[i].Framework] {+ traceway.CaptureMessage("Invalid framework received in batch create: " + inputs[i].Framework)+ return nil, &batchValidationError{invalidFrameworkMessage}+ }+ }++ existing, err := transactional.ProjectRepository.FindByOrganizationId(tx, orgId)+ if err != nil {+ return nil, err+ }+ byName := make(map[string]*models.Project, len(existing))+ for _, p := range existing {+ byName[p.Name] = p+ }++ results := make([]BatchProjectResult, 0, len(inputs))+ for _, input := range inputs {+ if project, ok := byName[input.Name]; ok {+ if project.Framework != input.Framework {+ return nil, &batchValidationError{Message: "Project " + input.Name + " already exists with framework " + project.Framework + "; requested " + input.Framework}+ }+ results = append(results, BatchProjectResult{Project: project, Status: "existing"})+ continue+ }++ if ProjectLimitHook != nil {+ if err := ProjectLimitHook(tx, orgId); err != nil {+ return nil, err+ }+ }++ project, err := transactional.ProjectRepository.CreateWithOrganization(tx, input.Name, input.Framework, orgId)+ if err != nil {+ return nil, err+ }+ if err := populateDefaultDashboards(tx, project, &createdBy); err != nil {+ return nil, err+ }+ byName[project.Name] = project+ results = append(results, BatchProjectResult{Project: project, Status: "created"})+ }+ return results, nil+}++type BatchProjectResponseItem struct {+ Id uuid.UUID `json:"id"`+ Name string `json:"name"`+ Framework string `json:"framework"`+ Token string `json:"token"`+ SourceMapToken *string `json:"sourceMapToken,omitempty"`+ BackendUrl string `json:"backendUrl"`+ Status string `json:"status"`+}++func toBatchProjectResponse(results []BatchProjectResult) []BatchProjectResponseItem {+ items := make([]BatchProjectResponseItem, 0, len(results))+ for _, r := range results {+ items = append(items, BatchProjectResponseItem{+ Id: r.Project.Id,+ Name: r.Project.Name,+ Framework: r.Project.Framework,+ Token: r.Project.Token,+ SourceMapToken: r.Project.SourceMapToken,+ BackendUrl: models.GetBackendUrl(),+ Status: r.Status,+ })+ }+ return items+}++func cacheCreatedProjectsOnCommit(ctx *gin.Context, results []BatchProjectResult) {+ created := []*models.Project{}+ for _, r := range results {+ if r.Status == "created" {+ created = append(created, r.Project)+ }+ }+ if len(created) == 0 {+ return+ }+ middleware.OnCommit(ctx, func() {+ for _, p := range created {+ cache.ProjectCache.AddProject(p)+ }+ })+}++func respondBatchCreateError(ctx *gin.Context, err error) {+ var validationErr *batchValidationError+ if errors.As(err, &validationErr) {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": validationErr.Message})+ return+ }+ var limitErr *LimitExceededError+ if errors.As(err, &limitErr) {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": limitErr.Message})+ return+ }+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("batch create projects: %w", err))+}++type BatchCreateProjectsRequest struct {+ OrganizationId int `json:"organizationId" binding:"required"`+ Projects []BatchProjectInput `json:"projects" binding:"required"`+}++func (p projectController) BatchCreateProjects(ctx *gin.Context) {+ var request BatchCreateProjectsRequest+ if err := ctx.ShouldBindJSON(&request); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})+ return+ }++ tx := db.GetTx(ctx)+ if !requireOrgWrite(ctx, tx, request.OrganizationId) {+ return+ }++ results, err := batchCreateProjects(tx, request.OrganizationId, middleware.GetUserId(ctx), request.Projects)+ if err != nil {+ respondBatchCreateError(ctx, err)+ return+ }++ cacheCreatedProjectsOnCommit(ctx, results)+ ctx.JSON(http.StatusCreated, gin.H{"projects": toBatchProjectResponse(results)})+}diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.goindex 77d594c5..27233d8b 100644--- a/backend/app/controllers/routes.go+++ b/backend/app/controllers/routes.go@@ -76,6 +76,7 @@ func RegisterControllers(router *gin.RouterGroup) {router.GET("/projects", middleware.UseAppAuth, ProjectController.ListProjects)router.POST("/projects", middleware.UseAppAuth, middleware.RequireProjectAccess, ProjectController.CreateProject)+ router.POST("/projects/batch", middleware.UseAppAuth, middleware.Transactional, ProjectController.BatchCreateProjects)router.PUT("/projects", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, ProjectController.UpdateProject)router.DELETE("/projects", middleware.UseAppAuth, middleware.RequireProjectAccess, middleware.RequireWriteAccess, ProjectController.DeleteProject)@@ -195,6 +196,14 @@ func RegisterControllers(router *gin.RouterGroup) {router.GET("/personal-access-tokens", middleware.UseAppAuth, PATController.List)router.DELETE("/personal-access-tokens/:id", middleware.UseAppAuth, middleware.Transactional, PATController.Revoke)+ router.POST("/setup-tokens", middleware.UseAppAuth, middleware.RateLimitPerUser(10, time.Hour), middleware.Transactional, SetupTokenController.Create)+ router.GET("/setup/session", middleware.RateLimitPerIP(60, time.Minute), middleware.UseSetupAuth, middleware.Transactional, SetupController.GetSession)+ router.PUT("/setup/plan", middleware.RateLimitPerIP(20, time.Minute), middleware.UseSetupAuth, middleware.Transactional, SetupController.SubmitPlan)+ router.GET("/setup/plan", middleware.RateLimitPerIP(60, time.Minute), middleware.UseSetupAuth, middleware.Transactional, SetupController.GetPlan)+ router.GET("/setup/drafts", middleware.UseAppAuth, middleware.RateLimitPerUser(60, time.Minute), middleware.Transactional, SetupController.ListDraft)+ router.POST("/setup/drafts/:id/approve", middleware.UseAppAuth, middleware.Transactional, SetupController.ApproveDraft)+ router.POST("/setup/drafts/:id/reject", middleware.UseAppAuth, middleware.Transactional, SetupController.RejectDraft)+// The OAuth discovery documents (/.well-known/oauth-*) are registered on the// root engine in cmd/run.go, not here: RFC 8414 / RFC 9728 clients fetch them// at the origin root, not under /api.diff --git a/backend/app/controllers/setup.controller.go b/backend/app/controllers/setup.controller.gonew file mode 100644index 00000000..515f565f--- /dev/null+++ b/backend/app/controllers/setup.controller.go@@ -0,0 +1,389 @@+package controllers++import (+ "encoding/json"+ "net/http"+ "regexp"+ "strconv"+ "strings"+ "time"+ "unicode/utf8"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ traceway "go.tracewayapp.com"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"+)++type setupController struct{}++var envVarNameRegex = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)++const (+ setupEnvFormatToken = "token"+ setupEnvFormatConnectionString = "connectionString"+)++type SetupSessionProject struct {+ Id uuid.UUID `json:"id"`+ Name string `json:"name"`+ Framework string `json:"framework"`+}++type SetupSessionResponse struct {+ OrganizationId int `json:"organizationId"`+ OrganizationName string `json:"organizationName"`+ Email string `json:"email"`+ BackendUrl string `json:"backendUrl"`+ Projects []SetupSessionProject `json:"projects"`+}++func (s setupController) GetSession(ctx *gin.Context) {+ tx := db.GetTx(ctx)+ orgId := middleware.GetSetupOrganizationId(ctx)++ org, err := transactional.OrganizationRepository.FindById(tx, orgId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("setup session: load organization: %w", err))+ return+ }+ if org == nil {+ ctx.AbortWithStatus(http.StatusUnauthorized)+ return+ }++ projects, err := transactional.ProjectRepository.FindByOrganizationId(tx, orgId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("setup session: load projects: %w", err))+ return+ }++ items := make([]SetupSessionProject, 0, len(projects))+ for _, p := range projects {+ items = append(items, SetupSessionProject{Id: p.Id, Name: p.Name, Framework: p.Framework})+ }++ ctx.JSON(http.StatusOK, SetupSessionResponse{+ OrganizationId: orgId,+ OrganizationName: org.Name,+ Email: middleware.GetUserEmail(ctx),+ BackendUrl: models.GetBackendUrl(),+ Projects: items,+ })+}++func validateSetupPlanPayload(payload *models.SetupPlanPayload) string {+ if len(payload.Projects) == 0 {+ return "At least one project is required"+ }+ if len(payload.Projects) > maxBatchProjects {+ return "At most 20 projects per plan"+ }++ seen := map[string]bool{}+ for i := range payload.Projects {+ p := &payload.Projects[i]+ p.Name = strings.TrimSpace(p.Name)+ if msg := validateProjectName(p.Name); msg != "" {+ return msg+ }+ if seen[p.Name] {+ return "Duplicate project name in plan: " + p.Name+ }+ seen[p.Name] = true+ if !validFrameworks[p.Framework] {+ return invalidFrameworkMessage+ }+ if utf8.RuneCountInString(p.EnvFile) > 300 {+ return "envFile must be 300 characters or fewer"+ }+ if p.EnvVar != "" && !envVarNameRegex.MatchString(p.EnvVar) {+ return "envVar must be a valid environment variable name"+ }+ if utf8.RuneCountInString(p.EnvVar) > 100 {+ return "envVar must be 100 characters or fewer"+ }+ switch p.EnvFormat {+ case "", setupEnvFormatToken, setupEnvFormatConnectionString:+ default:+ return "envFormat must be \"token\" or \"connectionString\""+ }+ if p.Deployment != nil {+ p.Deployment.Platform = strings.TrimSpace(p.Deployment.Platform)+ p.Deployment.Instructions = strings.TrimSpace(p.Deployment.Instructions)+ if utf8.RuneCountInString(p.Deployment.Platform) > 100 {+ return "deployment platform must be 100 characters or fewer"+ }+ if utf8.RuneCountInString(p.Deployment.Instructions) > 2000 {+ return "deployment instructions must be 2000 characters or fewer"+ }+ }+ }+ return ""+}++func (s setupController) SubmitPlan(ctx *gin.Context) {+ var payload models.SetupPlanPayload+ if err := ctx.ShouldBindJSON(&payload); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})+ return+ }+ if msg := validateSetupPlanPayload(&payload); msg != "" {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": msg})+ return+ }++ canonical, err := json.Marshal(payload)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("marshal setup plan: %w", err))+ return+ }++ tx := db.GetTx(ctx)+ if err := transactional.SetupPlanRepository.Upsert(tx, uuid.New().String(), middleware.GetUserId(ctx), middleware.GetSetupOrganizationId(ctx), string(canonical)); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("store setup plan: %w", err))+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"status": "pending"})+}++type setupPlanResultItem struct {+ Id uuid.UUID `json:"id"`+ Status string `json:"status"`+}++func resolvePlanResultProjects(ctx *gin.Context, plan *transactional.SetupPlanRow) ([]BatchProjectResponseItem, bool) {+ tx := db.GetTx(ctx)++ var resultItems []setupPlanResultItem+ if plan.Result != "" {+ if err := json.Unmarshal([]byte(plan.Result), &resultItems); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("parse setup plan result: %w", err))+ return nil, false+ }+ }++ items := make([]BatchProjectResponseItem, 0, len(resultItems))+ for _, r := range resultItems {+ project, err := transactional.ProjectRepository.FindById(tx, r.Id)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("load setup plan project: %w", err))+ return nil, false+ }+ if project == nil {+ continue+ }+ items = append(items, BatchProjectResponseItem{+ Id: project.Id,+ Name: project.Name,+ Framework: project.Framework,+ Token: project.Token,+ SourceMapToken: project.SourceMapToken,+ BackendUrl: models.GetBackendUrl(),+ Status: r.Status,+ })+ }+ return items, true+}++func (s setupController) GetPlan(ctx *gin.Context) {+ tx := db.GetTx(ctx)++ plan, err := transactional.SetupPlanRepository.FindLatestByUserAndOrganization(tx, middleware.GetUserId(ctx), middleware.GetSetupOrganizationId(ctx))+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("load setup plan: %w", err))+ return+ }+ if plan == nil {+ ctx.JSON(http.StatusOK, gin.H{"status": "none"})+ return+ }++ switch plan.Status {+ case "approved":+ projects, ok := resolvePlanResultProjects(ctx, plan)+ if !ok {+ return+ }+ ctx.JSON(http.StatusOK, gin.H{"status": "approved", "projects": projects})+ case "rejected":+ ctx.JSON(http.StatusOK, gin.H{"status": "rejected", "reason": plan.RejectReason})+ default:+ ctx.JSON(http.StatusOK, gin.H{"status": "pending"})+ }+}++type SetupDraftResponse struct {+ Id string `json:"id"`+ Status string `json:"status"`+ Payload models.SetupPlanPayload `json:"payload"`+ CreatedAt time.Time `json:"createdAt"`+ RequestedByEmail string `json:"requestedByEmail"`+ RejectReason string `json:"rejectReason,omitempty"`+ Projects []BatchProjectResponseItem `json:"projects,omitempty"`+}++func (s setupController) draftResponse(ctx *gin.Context, plan *transactional.SetupPlanRow) (*SetupDraftResponse, bool) {+ var payload models.SetupPlanPayload+ if err := json.Unmarshal([]byte(plan.Payload), &payload); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("parse setup plan payload: %w", err))+ return nil, false+ }++ response := &SetupDraftResponse{+ Id: plan.Id,+ Status: plan.Status,+ Payload: payload,+ CreatedAt: plan.CreatedAt,+ RequestedByEmail: plan.RequestedByEmail,+ RejectReason: plan.RejectReason,+ }+ if plan.Status == "approved" {+ projects, ok := resolvePlanResultProjects(ctx, plan)+ if !ok {+ return nil, false+ }+ response.Projects = projects+ }+ return response, true+}++func (s setupController) ListDraft(ctx *gin.Context) {+ orgId, err := strconv.Atoi(ctx.Query("organizationId"))+ if err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "organizationId is required"})+ return+ }++ tx := db.GetTx(ctx)+ if !requireOrgWrite(ctx, tx, orgId) {+ return+ }++ plan, err := transactional.SetupPlanRepository.FindReviewableByOrganization(tx, orgId)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("load setup plan: %w", err))+ return+ }+ if plan == nil {+ ctx.JSON(http.StatusOK, gin.H{"draft": nil})+ return+ }++ draft, ok := s.draftResponse(ctx, plan)+ if !ok {+ return+ }+ ctx.JSON(http.StatusOK, gin.H{"draft": draft})+}++func (s setupController) loadDecidablePlan(ctx *gin.Context) *transactional.SetupPlanRow {+ tx := db.GetTx(ctx)++ plan, err := transactional.SetupPlanRepository.FindById(tx, ctx.Param("id"))+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("load setup plan: %w", err))+ return nil+ }+ if plan == nil {+ ctx.JSON(http.StatusNotFound, gin.H{"error": "Proposal not found"})+ return nil+ }+ if !requireOrgWrite(ctx, tx, plan.OrganizationId) {+ return nil+ }+ if plan.Status != "pending" {+ ctx.JSON(http.StatusConflict, gin.H{"error": "This proposal was already decided"})+ return nil+ }+ return plan+}++func (s setupController) ApproveDraft(ctx *gin.Context) {+ plan := s.loadDecidablePlan(ctx)+ if plan == nil {+ return+ }++ var payload models.SetupPlanPayload+ if err := json.Unmarshal([]byte(plan.Payload), &payload); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("parse setup plan payload: %w", err))+ return+ }++ inputs := make([]BatchProjectInput, 0, len(payload.Projects))+ for _, p := range payload.Projects {+ inputs = append(inputs, BatchProjectInput{Name: p.Name, Framework: p.Framework})+ }++ tx := db.GetTx(ctx)+ userId := middleware.GetUserId(ctx)++ results, err := batchCreateProjects(tx, plan.OrganizationId, userId, inputs)+ if err != nil {+ respondBatchCreateError(ctx, err)+ return+ }++ resultItems := make([]setupPlanResultItem, 0, len(results))+ for _, r := range results {+ resultItems = append(resultItems, setupPlanResultItem{Id: r.Project.Id, Status: r.Status})+ }+ resultJSON, err := json.Marshal(resultItems)+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("marshal setup plan result: %w", err))+ return+ }++ rows, err := transactional.SetupPlanRepository.Decide(tx, plan.Id, "approved", "", string(resultJSON), userId, time.Now().UTC())+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("approve setup plan: %w", err))+ return+ }+ if rows == 0 {+ ctx.JSON(http.StatusConflict, gin.H{"error": "This proposal was already decided"})+ return+ }++ cacheCreatedProjectsOnCommit(ctx, results)+ ctx.JSON(http.StatusOK, gin.H{"projects": toBatchProjectResponse(results)})+}++type RejectDraftRequest struct {+ Reason string `json:"reason"`+}++func (s setupController) RejectDraft(ctx *gin.Context) {+ plan := s.loadDecidablePlan(ctx)+ if plan == nil {+ return+ }++ var request RejectDraftRequest+ _ = ctx.ShouldBindJSON(&request)+ reason := strings.TrimSpace(request.Reason)+ if utf8.RuneCountInString(reason) > 500 {+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Reason must be 500 characters or fewer"})+ return+ }++ tx := db.GetTx(ctx)+ rows, err := transactional.SetupPlanRepository.Decide(tx, plan.Id, "rejected", reason, "", middleware.GetUserId(ctx), time.Now().UTC())+ if err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("reject setup plan: %w", err))+ return+ }+ if rows == 0 {+ ctx.JSON(http.StatusConflict, gin.H{"error": "This proposal was already decided"})+ return+ }++ ctx.JSON(http.StatusOK, gin.H{"status": "rejected"})+}++var SetupController = setupController{}diff --git a/backend/app/controllers/setup_test.go b/backend/app/controllers/setup_test.gonew file mode 100644index 00000000..05ff040d--- /dev/null+++ b/backend/app/controllers/setup_test.go@@ -0,0 +1,448 @@+//go:build !telemetry_ch && !transactional_pg++package controllers++import (+ "database/sql"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "strconv"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/config"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/migrations"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"+ "github.com/tracewayapp/traceway/backend/app/services"+ _ "modernc.org/sqlite"+)++func setupSetupControllerDB(t *testing.T) {+ t.Helper()++ mainDB, err := sql.Open("sqlite", ":memory:")+ if err != nil {+ t.Fatalf("open main sqlite: %v", err)+ }+ mainDB.SetMaxOpenConns(1)++ telemetryDB, err := sql.Open("sqlite", ":memory:")+ if err != nil {+ t.Fatalf("open telemetry sqlite: %v", err)+ }+ telemetryDB.SetMaxOpenConns(1)++ prevDB, prevTelemetry, prevDriver := db.DB, db.TelemetryDB, db.Driver+ db.DB = mainDB+ db.TelemetryDB = telemetryDB+ db.Driver = lit.SQLite+ models.Init(db.Driver)++ prevConfig := config.Config+ if config.Config == nil {+ config.Init(&config.Cfg{})+ }++ t.Cleanup(func() {+ mainDB.Close()+ telemetryDB.Close()+ db.DB = prevDB+ db.TelemetryDB = prevTelemetry+ db.Driver = prevDriver+ config.Init(prevConfig)+ })++ if err := migrations.Run("sqlite"); err != nil {+ t.Fatalf("run migrations: %v", err)+ }+}++func createSetupTestAccount(t *testing.T, tx *sql.Tx, email, role string) (userId int, orgId int) {+ t.Helper()+ user, err := transactional.UserRepository.Create(tx, email, "Test User", "hashed-password")+ if err != nil {+ t.Fatalf("create user: %v", err)+ }+ org, err := transactional.OrganizationRepository.Create(tx, "Test Org "+email, "UTC")+ if err != nil {+ t.Fatalf("create org: %v", err)+ }+ if _, err := transactional.OrganizationRepository.AddUser(tx, org.Id, user.Id, role); err != nil {+ t.Fatalf("add user to org: %v", err)+ }+ return user.Id, org.Id+}++func newControllerTestContext(t *testing.T, tx *sql.Tx, userId int, method, path, body string) (*gin.Context, *httptest.ResponseRecorder) {+ t.Helper()+ gin.SetMode(gin.TestMode)+ recorder := httptest.NewRecorder()+ c, _ := gin.CreateTestContext(recorder)+ var reader *strings.Reader+ if body == "" {+ reader = strings.NewReader("")+ } else {+ reader = strings.NewReader(body)+ }+ c.Request = httptest.NewRequest(method, path, reader)+ c.Request.Header.Set("Content-Type", "application/json")+ if tx != nil {+ c.Set(db.TransactionContextKey, tx)+ }+ if userId != 0 {+ c.Set(middleware.UserIdContextKey, userId)+ }+ return c, recorder+}++func TestBatchCreateProjectsCreatesAndIsIdempotent(t *testing.T) {+ setupSetupControllerDB(t)++ tx, err := db.DB.Begin()+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ defer tx.Rollback()++ userId, orgId := createSetupTestAccount(t, tx, "[email protected]", "owner")++ inputs := []BatchProjectInput{+ {Name: "Product Backend", Framework: "opentelemetry"},+ {Name: "Product Web", Framework: "react"},+ }+ results, err := batchCreateProjects(tx, orgId, userId, inputs)+ if err != nil {+ t.Fatalf("batch create: %v", err)+ }+ if len(results) != 2 {+ t.Fatalf("results = %d, want 2", len(results))+ }+ for i, r := range results {+ if r.Status != "created" {+ t.Errorf("results[%d].Status = %q, want created", i, r.Status)+ }+ if r.Project.Token == "" {+ t.Errorf("results[%d] has no token", i)+ }+ if len(r.Project.AiFlaggedLanguages) == 0 {+ t.Errorf("results[%d] has empty AiFlaggedLanguages", i)+ }+ }++ assignments, err := transactional.DashboardRepository.FindAssignmentsByProject(tx, results[0].Project.Id)+ if err != nil {+ t.Fatalf("list assignments: %v", err)+ }+ if len(assignments) == 0 {+ t.Error("opentelemetry project should get default dashboards")+ }++ rerun, err := batchCreateProjects(tx, orgId, userId, inputs)+ if err != nil {+ t.Fatalf("rerun batch create: %v", err)+ }+ for i, r := range rerun {+ if r.Status != "existing" {+ t.Errorf("rerun[%d].Status = %q, want existing", i, r.Status)+ }+ if r.Project.Id != results[i].Project.Id {+ t.Errorf("rerun[%d] returned a different project id", i)+ }+ }++ folded, err := batchCreateProjects(tx, orgId, userId, []BatchProjectInput{+ {Name: "Workers", Framework: "opentelemetry"},+ {Name: "Workers", Framework: "opentelemetry"},+ })+ if err != nil {+ t.Fatalf("folded batch create: %v", err)+ }+ if folded[0].Status != "created" || folded[1].Status != "existing" || folded[0].Project.Id != folded[1].Project.Id {+ t.Errorf("duplicate names should fold onto one project: %+v", folded)+ }++ _, err = batchCreateProjects(tx, orgId, userId, []BatchProjectInput{+ {Name: "Product Web", Framework: "opentelemetry"},+ })+ var validationErr *batchValidationError+ if !errors.As(err, &validationErr) || !strings.Contains(validationErr.Message, "already exists with framework react") {+ t.Fatalf("framework mismatch = %v, want a validation error naming the existing framework", err)+ }+}++func TestBatchCreateProjectsValidation(t *testing.T) {+ setupSetupControllerDB(t)++ tx, err := db.DB.Begin()+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ defer tx.Rollback()++ userId, orgId := createSetupTestAccount(t, tx, "[email protected]", "owner")++ cases := map[string][]BatchProjectInput{+ "empty": {},+ "invalid framework": {{Name: "App", Framework: "nope"}},+ "bad name": {{Name: "Bad!Name", Framework: "opentelemetry"}},+ "empty name": {{Name: " ", Framework: "opentelemetry"}},+ }+ tooMany := make([]BatchProjectInput, maxBatchProjects+1)+ for i := range tooMany {+ tooMany[i] = BatchProjectInput{Name: "P" + strings.Repeat("x", i%5), Framework: "opentelemetry"}+ }+ cases["too many"] = tooMany++ for name, inputs := range cases {+ t.Run(name, func(t *testing.T) {+ _, err := batchCreateProjects(tx, orgId, userId, inputs)+ var validationErr *batchValidationError+ if !errors.As(err, &validationErr) {+ t.Errorf("expected batchValidationError, got %v", err)+ }+ })+ }+}++func TestBatchCreateProjectsLimitHookAbortsBatch(t *testing.T) {+ setupSetupControllerDB(t)++ tx, err := db.DB.Begin()+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ defer tx.Rollback()++ userId, orgId := createSetupTestAccount(t, tx, "[email protected]", "owner")++ calls := 0+ prevHook := ProjectLimitHook+ ProjectLimitHook = func(tx *sql.Tx, orgId int) error {+ calls+++ if calls > 1 {+ return &LimitExceededError{Message: "plan limit reached"}+ }+ return nil+ }+ defer func() { ProjectLimitHook = prevHook }()++ _, err = batchCreateProjects(tx, orgId, userId, []BatchProjectInput{+ {Name: "One", Framework: "opentelemetry"},+ {Name: "Two", Framework: "opentelemetry"},+ })+ var limitErr *LimitExceededError+ if !errors.As(err, &limitErr) {+ t.Fatalf("expected LimitExceededError, got %v", err)+ }+}++func TestRegisterWithoutProject(t *testing.T) {+ setupSetupControllerDB(t)++ prevSecret := config.Config.JWTSecret+ config.Config.JWTSecret = strings.Repeat("s", 32)+ if err := services.InitJWT(); err != nil {+ t.Fatalf("init jwt: %v", err)+ }+ services.InitTurnstile()+ t.Cleanup(func() {+ config.Config.JWTSecret = prevSecret+ _ = services.InitJWT()+ })++ register := func(t *testing.T, body string) (*httptest.ResponseRecorder, map[string]any) {+ t.Helper()+ tx, err := db.DB.Begin()+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ c, recorder := newControllerTestContext(t, tx, 0, http.MethodPost, "/api/register", body)+ AuthController.Register(c)+ if recorder.Code >= 200 && recorder.Code < 300 {+ if err := tx.Commit(); err != nil {+ t.Fatalf("commit: %v", err)+ }+ } else {+ tx.Rollback()+ }+ var payload map[string]any+ _ = json.Unmarshal(recorder.Body.Bytes(), &payload)+ return recorder, payload+ }++ recorder, _ := register(t, `{"email":"[email protected]","name":"A","password":"password1","organizationName":"HalfOrg","timezone":"UTC","projectName":"OnlyName"}`)+ if recorder.Code != http.StatusBadRequest {+ t.Fatalf("half project fields: status = %d, want 400", recorder.Code)+ }++ recorder, payload := register(t, `{"email":"[email protected]","name":"A","password":"password1","organizationName":"NopOrg","timezone":"UTC"}`)+ if recorder.Code != http.StatusCreated {+ t.Fatalf("no project: status = %d, body = %s", recorder.Code, recorder.Body.String())+ }+ if _, exists := payload["project"]; exists {+ t.Error("response must omit the project key when no project was created")+ }+ if projects, ok := payload["projects"].([]any); !ok || len(projects) != 0 {+ t.Errorf("projects = %v, want empty list", payload["projects"])+ }++ var count int+ if err := db.DB.QueryRow("SELECT COUNT(*) FROM projects").Scan(&count); err != nil {+ t.Fatalf("count projects: %v", err)+ }+ if count != 0 {+ t.Fatalf("projects in db = %d, want 0", count)+ }+}++func submitTestPlan(t *testing.T, tx *sql.Tx, userId, orgId int, payload string) {+ t.Helper()+ c, recorder := newControllerTestContext(t, tx, userId, http.MethodPut, "/api/setup/plan", payload)+ c.Set(middleware.SetupOrganizationIdContextKey, orgId)+ c.Set(middleware.SetupScopeContextKey, true)+ SetupController.SubmitPlan(c)+ if recorder.Code != http.StatusOK {+ t.Fatalf("submit plan: status = %d, body = %s", recorder.Code, recorder.Body.String())+ }+}++func latestDraftId(t *testing.T, tx *sql.Tx, userId, orgId int) string {+ t.Helper()+ plan, err := transactional.SetupPlanRepository.FindLatestByUserAndOrganization(tx, userId, orgId)+ if err != nil || plan == nil {+ t.Fatalf("load latest plan: (%v, %v)", plan, err)+ }+ return plan.Id+}++func TestSetupDraftLifecycle(t *testing.T) {+ setupSetupControllerDB(t)++ tx, err := db.DB.Begin()+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ defer tx.Rollback()++ userId, orgId := createSetupTestAccount(t, tx, "[email protected]", "owner")++ planBody := `{"projects":[+ {"name":"Product Backend","framework":"opentelemetry","envFile":"backend/.env","envVar":"TRACEWAY_BACKEND_TOKEN"},+ {"name":"Product Web","framework":"react","envFile":"web/.env","envVar":"VITE_TRACEWAY_CONNECTION_STRING","envFormat":"connectionString",+ "deployment":{"platform":"Vercel","instructions":"vercel env add VITE_TRACEWAY_CONNECTION_STRING <token>"}}+ ]}`+ submitTestPlan(t, tx, userId, orgId, planBody)++ c, recorder := newControllerTestContext(t, tx, userId, http.MethodGet, "/api/setup/plan", "")+ c.Set(middleware.SetupOrganizationIdContextKey, orgId)+ SetupController.GetPlan(c)+ if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), `"pending"`) {+ t.Fatalf("get plan: status = %d, body = %s", recorder.Code, recorder.Body.String())+ }++ c, recorder = newControllerTestContext(t, tx, userId, http.MethodGet, "/api/setup/drafts?organizationId="+strconv.Itoa(orgId), "")+ SetupController.ListDraft(c)+ if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), "Product Backend") {+ t.Fatalf("list draft: status = %d, body = %s", recorder.Code, recorder.Body.String())+ }++ draftId := latestDraftId(t, tx, userId, orgId)+ c, recorder = newControllerTestContext(t, tx, userId, http.MethodPost, "/api/setup/drafts/"+draftId+"/approve", "")+ c.Params = gin.Params{{Key: "id", Value: draftId}}+ SetupController.ApproveDraft(c)+ if recorder.Code != http.StatusOK {+ t.Fatalf("approve: status = %d, body = %s", recorder.Code, recorder.Body.String())+ }+ var approveResponse struct {+ Projects []BatchProjectResponseItem `json:"projects"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &approveResponse); err != nil {+ t.Fatalf("parse approve response: %v", err)+ }+ if len(approveResponse.Projects) != 2 || approveResponse.Projects[0].Token == "" {+ t.Fatalf("approve response = %+v", approveResponse)+ }++ readonly, err := transactional.UserRepository.Create(tx, "[email protected]", "Read Only", "hashed-password")+ if err != nil {+ t.Fatalf("create read-only user: %v", err)+ }+ if _, err := transactional.OrganizationRepository.AddUser(tx, orgId, readonly.Id, "readonly"); err != nil {+ t.Fatalf("add read-only user: %v", err)+ }+ c, recorder = newControllerTestContext(t, tx, readonly.Id, http.MethodGet, "/api/setup/drafts?organizationId="+strconv.Itoa(orgId), "")+ SetupController.ListDraft(c)+ if recorder.Code != http.StatusForbidden {+ t.Fatalf("read-only list draft: status = %d, body = %s", recorder.Code, recorder.Body.String())+ }+ if strings.Contains(recorder.Body.String(), approveResponse.Projects[0].Token) {+ t.Fatal("read-only draft response exposed a project token")+ }++ c, recorder = newControllerTestContext(t, tx, userId, http.MethodPost, "/api/setup/drafts/"+draftId+"/approve", "")+ c.Params = gin.Params{{Key: "id", Value: draftId}}+ SetupController.ApproveDraft(c)+ if recorder.Code != http.StatusConflict {+ t.Fatalf("second approve: status = %d, want 409", recorder.Code)+ }++ c, recorder = newControllerTestContext(t, tx, userId, http.MethodGet, "/api/setup/plan", "")+ c.Set(middleware.SetupOrganizationIdContextKey, orgId)+ SetupController.GetPlan(c)+ if !strings.Contains(recorder.Body.String(), `"approved"`) || !strings.Contains(recorder.Body.String(), `"token"`) {+ t.Fatalf("approved plan body = %s", recorder.Body.String())+ }++ submitTestPlan(t, tx, userId, orgId, `{"projects":[{"name":"Another","framework":"opentelemetry"}]}`)+ draftId = latestDraftId(t, tx, userId, orgId)+ c, recorder = newControllerTestContext(t, tx, userId, http.MethodPost, "/api/setup/drafts/"+draftId+"/reject", `{"reason":"wrong project split"}`)+ c.Params = gin.Params{{Key: "id", Value: draftId}}+ SetupController.RejectDraft(c)+ if recorder.Code != http.StatusOK {+ t.Fatalf("reject: status = %d, body = %s", recorder.Code, recorder.Body.String())+ }++ c, recorder = newControllerTestContext(t, tx, userId, http.MethodGet, "/api/setup/plan", "")+ c.Set(middleware.SetupOrganizationIdContextKey, orgId)+ SetupController.GetPlan(c)+ if !strings.Contains(recorder.Body.String(), `"rejected"`) || !strings.Contains(recorder.Body.String(), "wrong project split") {+ t.Fatalf("rejected plan body = %s", recorder.Body.String())+ }+}+func TestSubmitPlanValidation(t *testing.T) {+ setupSetupControllerDB(t)++ tx, err := db.DB.Begin()+ if err != nil {+ t.Fatalf("begin: %v", err)+ }+ defer tx.Rollback()++ userId, orgId := createSetupTestAccount(t, tx, "[email protected]", "owner")++ cases := map[string]string{+ "empty projects": `{"projects":[]}`,+ "bad framework": `{"projects":[{"name":"App","framework":"laravel-x"}]}`,+ "duplicate names": `{"projects":[{"name":"App","framework":"react"},{"name":"App","framework":"svelte"}]}`,+ "bad env var": `{"projects":[{"name":"App","framework":"react","envVar":"1BAD"}]}`,+ "bad env format": `{"projects":[{"name":"App","framework":"react","envFormat":"base64"}]}`,+ "long instructions": `{"projects":[{"name":"App","framework":"react","deployment":{"platform":"Fly","instructions":"` + strings.Repeat("x", 2100) + `"}}]}`,+ }+ for name, body := range cases {+ t.Run(name, func(t *testing.T) {+ c, recorder := newControllerTestContext(t, tx, userId, http.MethodPut, "/api/setup/plan", body)+ c.Set(middleware.SetupOrganizationIdContextKey, orgId)+ SetupController.SubmitPlan(c)+ if recorder.Code != http.StatusUnprocessableEntity {+ t.Errorf("status = %d, want 422 (body: %s)", recorder.Code, recorder.Body.String())+ }+ })+ }+}diff --git a/backend/app/controllers/setup_token.controller.go b/backend/app/controllers/setup_token.controller.gonew file mode 100644index 00000000..9aea01a4--- /dev/null+++ b/backend/app/controllers/setup_token.controller.go@@ -0,0 +1,58 @@+package controllers++import (+ "net/http"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/google/uuid"+ traceway "go.tracewayapp.com"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/middleware"+ "github.com/tracewayapp/traceway/backend/app/models"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"+ "github.com/tracewayapp/traceway/backend/app/services/authserver"+)++const setupTokenTTL = 6 * time.Hour++type setupTokenController struct{}++func (s setupTokenController) Create(ctx *gin.Context) {+ var req models.CreateSetupTokenRequest+ if err := ctx.ShouldBindJSON(&req); err != nil {+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})+ return+ }++ tx := db.GetTx(ctx)+ userId := middleware.GetUserId(ctx)++ if !requireOrgWrite(ctx, tx, req.OrganizationId) {+ return+ }++ if err := transactional.SetupTokenRepository.DeleteByUserAndOrganization(tx, userId, req.OrganizationId); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("replace setup token: %w", err))+ return+ }++ token := authserver.NewSetupToken()+ expiresAt := time.Now().Add(setupTokenTTL).UTC()++ if err := transactional.SetupTokenRepository.Create(tx, uuid.New().String(), token, patPrefix(token), userId, req.OrganizationId, expiresAt); err != nil {+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("create setup token: %w", err))+ return+ }++ ctx.JSON(http.StatusCreated, models.CreateSetupTokenResponse{+ Token: token,+ Prefix: patPrefix(token),+ ExpiresAt: expiresAt,+ OrganizationId: req.OrganizationId,+ BackendUrl: models.GetBackendUrl(),+ })+}++var SetupTokenController = setupTokenController{}diff --git a/backend/app/middleware/use_setup_auth.middleware.go b/backend/app/middleware/use_setup_auth.middleware.gonew file mode 100644index 00000000..e28a04f0--- /dev/null+++ b/backend/app/middleware/use_setup_auth.middleware.go@@ -0,0 +1,59 @@+package middleware++import (+ "net/http"+ "strings"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"+ traceway "go.tracewayapp.com"++ "github.com/gin-gonic/gin"+)++const SetupOrganizationIdContextKey = "setupOrganizationId"+const SetupScopeContextKey = "setupScope"++func UseSetupAuth(c *gin.Context) {+ authHeader := c.GetHeader("Authorization")+ if !strings.HasPrefix(authHeader, "Bearer ") {+ c.AbortWithStatus(http.StatusUnauthorized)+ return+ }+ token := strings.TrimPrefix(authHeader, "Bearer ")+ if !strings.HasPrefix(token, "tws_") {+ c.AbortWithStatus(http.StatusUnauthorized)+ return+ }++ st, err := transactional.SetupTokenRepository.FindActiveByToken(db.DB, token)+ if err != nil {+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("setup token auth failed: %w", err))+ return+ }+ if st == nil {+ c.AbortWithStatus(http.StatusUnauthorized)+ return+ }++ c.Set(UserIdContextKey, st.UserId)+ c.Set(UserEmailContextKey, st.Email)+ c.Set(SetupOrganizationIdContextKey, st.OrganizationId)+ c.Set(SetupScopeContextKey, true)++ c.Next()+}++func GetSetupOrganizationId(c *gin.Context) int {+ if id, exists := c.Get(SetupOrganizationIdContextKey); exists {+ return id.(int)+ }+ return 0+}++func IsSetupScope(c *gin.Context) bool {+ if v, exists := c.Get(SetupScopeContextKey); exists {+ return v.(bool)+ }+ return false+}diff --git a/backend/app/middleware/use_setup_auth_test.go b/backend/app/middleware/use_setup_auth_test.gonew file mode 100644index 00000000..4b8051f6--- /dev/null+++ b/backend/app/middleware/use_setup_auth_test.go@@ -0,0 +1,155 @@+//go:build !transactional_pg++package middleware++import (+ "database/sql"+ "errors"+ "net/http"+ "net/http/httptest"+ "testing"+ "time"++ "github.com/gin-gonic/gin"+ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional"+ _ "modernc.org/sqlite"+)++func setupSetupAuthDB(t *testing.T) {+ t.Helper()++ mainDB, err := sql.Open("sqlite", ":memory:")+ if err != nil {+ t.Fatalf("failed to open in-memory sqlite: %v", err)+ }+ mainDB.SetMaxOpenConns(1)++ prevDB, prevDriver := db.DB, db.Driver+ db.DB = mainDB+ db.Driver = lit.SQLite+ t.Cleanup(func() {+ mainDB.Close()+ db.DB = prevDB+ db.Driver = prevDriver+ })++ for _, ddl := range []string{+ `CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT NOT NULL)`,+ `CREATE TABLE organization_users (+ user_id INTEGER NOT NULL,+ organization_id INTEGER NOT NULL,+ role TEXT NOT NULL,+ UNIQUE(user_id, organization_id)+ )`,+ `CREATE TABLE setup_tokens (+ id TEXT PRIMARY KEY,+ token_hash TEXT NOT NULL UNIQUE,+ prefix TEXT NOT NULL,+ user_id INTEGER NOT NULL,+ organization_id INTEGER NOT NULL,+ created_at DATETIME NOT NULL,+ expires_at DATETIME NOT NULL+ )`,+ } {+ if _, err := mainDB.Exec(ddl); err != nil {+ t.Fatalf("ddl failed: %v", err)+ }+ }+}++func setupAuthContext(t *testing.T, authorization string) (*gin.Context, *httptest.ResponseRecorder) {+ t.Helper()+ gin.SetMode(gin.TestMode)+ recorder := httptest.NewRecorder()+ c, _ := gin.CreateTestContext(recorder)+ c.Request = httptest.NewRequest(http.MethodGet, "/api/setup/session", nil)+ if authorization != "" {+ c.Request.Header.Set("Authorization", authorization)+ }+ return c, recorder+}++func TestUseSetupAuthValidToken(t *testing.T) {+ setupSetupAuthDB(t)++ res, err := db.DB.Exec("INSERT INTO users (email) VALUES ('[email protected]')")+ if err != nil {+ t.Fatalf("insert user: %v", err)+ }+ userId64, _ := res.LastInsertId()+ userId := int(userId64)+ if _, err := db.DB.Exec("INSERT INTO organization_users (user_id, organization_id, role) VALUES (?, ?, 'user')", userId, 42); err != nil {+ t.Fatalf("grant organization role: %v", err)+ }++ token := "tws_valid-token"+ if err := transactional.SetupTokenRepository.Create(db.DB, "tok-1", token, token, userId, 42, time.Now().Add(time.Hour)); err != nil {+ t.Fatalf("create token: %v", err)+ }++ c, recorder := setupAuthContext(t, "Bearer "+token)+ UseSetupAuth(c)++ if c.IsAborted() {+ t.Fatalf("request aborted with status %d", recorder.Code)+ }+ if got := GetUserId(c); got != userId {+ t.Errorf("userId = %d, want %d", got, userId)+ }+ if got := GetUserEmail(c); got != "[email protected]" {+ t.Errorf("userEmail = %q", got)+ }+ if got := GetSetupOrganizationId(c); got != 42 {+ t.Errorf("setupOrganizationId = %d, want 42", got)+ }+ if !IsSetupScope(c) {+ t.Error("setup scope marker not set")+ }+}++func TestUseSetupAuthRejects(t *testing.T) {+ setupSetupAuthDB(t)++ res, _ := db.DB.Exec("INSERT INTO users (email) VALUES ('[email protected]')")+ userId64, _ := res.LastInsertId()+ if _, err := db.DB.Exec("INSERT INTO organization_users (user_id, organization_id, role) VALUES (?, ?, 'user')", userId64, 42); err != nil {+ t.Fatalf("grant organization role: %v", err)+ }++ expired := "tws_expired-token"+ if err := transactional.SetupTokenRepository.Create(db.DB, "tok-exp", expired, expired, int(userId64), 42, time.Now().Add(-time.Minute)); err != nil {+ t.Fatalf("create expired token: %v", err)+ }++ cases := map[string]string{+ "missing header": "",+ "non-bearer": "Basic abc",+ "unknown setup token": "Bearer tws_unknown-token",+ "expired setup token": "Bearer " + expired,+ "pat prefix": "Bearer twp_not-a-setup-token",+ "jwt-looking string": "Bearer eyJhbGciOiJIUzI1NiJ9.e30.x",+ }+ for name, header := range cases {+ t.Run(name, func(t *testing.T) {+ c, recorder := setupAuthContext(t, header)+ UseSetupAuth(c)+ if !c.IsAborted() || recorder.Code != http.StatusUnauthorized {+ t.Errorf("expected 401 abort, got aborted=%v status=%d", c.IsAborted(), recorder.Code)+ }+ if IsSetupScope(c) {+ t.Error("setup scope must not be set on rejection")+ }+ })+ }+}++func TestSetupTokenNeverPassesAppAuth(t *testing.T) {+ setupSetupAuthDB(t)++ identity, err := AuthenticateBearer("tws_" + "some-opaque-setup-token")+ if !errors.Is(err, ErrInvalidBearer) {+ t.Fatalf("AuthenticateBearer(tws_...) = (%v, %v), want ErrInvalidBearer", identity, err)+ }+}diff --git a/backend/app/migrations/pg/0119_create_setup_tokens.up.sql b/backend/app/migrations/pg/0119_create_setup_tokens.up.sqlnew file mode 100644index 00000000..bac63feb--- /dev/null+++ b/backend/app/migrations/pg/0119_create_setup_tokens.up.sql@@ -0,0 +1,9 @@+CREATE TABLE IF NOT EXISTS setup_tokens (+ id TEXT PRIMARY KEY,+ token_hash TEXT NOT NULL UNIQUE,+ prefix TEXT NOT NULL,+ user_id INTEGER NOT NULL REFERENCES users(id),+ organization_id INTEGER NOT NULL REFERENCES organizations(id),+ created_at TIMESTAMPTZ NOT NULL,+ expires_at TIMESTAMPTZ NOT NULL+)diff --git a/backend/app/migrations/pg/0120_create_setup_tokens_user_org_idx.up.sql b/backend/app/migrations/pg/0120_create_setup_tokens_user_org_idx.up.sqlnew file mode 100644index 00000000..53c2ddbd--- /dev/null+++ b/backend/app/migrations/pg/0120_create_setup_tokens_user_org_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX IF NOT EXISTS idx_setup_tokens_user_org ON setup_tokens(user_id, organization_id)diff --git a/backend/app/migrations/pg/0121_create_setup_plans.up.sql b/backend/app/migrations/pg/0121_create_setup_plans.up.sqlnew file mode 100644index 00000000..99a1f154--- /dev/null+++ b/backend/app/migrations/pg/0121_create_setup_plans.up.sql@@ -0,0 +1,12 @@+CREATE TABLE IF NOT EXISTS setup_plans (+ id TEXT PRIMARY KEY,+ user_id INTEGER NOT NULL REFERENCES users(id),+ organization_id INTEGER NOT NULL REFERENCES organizations(id),+ payload TEXT NOT NULL,+ status TEXT NOT NULL,+ reject_reason TEXT,+ result TEXT,+ created_at TIMESTAMPTZ NOT NULL,+ decided_at TIMESTAMPTZ,+ decided_by INTEGER+)diff --git a/backend/app/migrations/pg/0122_create_setup_plans_user_org_idx.up.sql b/backend/app/migrations/pg/0122_create_setup_plans_user_org_idx.up.sqlnew file mode 100644index 00000000..39b91010--- /dev/null+++ b/backend/app/migrations/pg/0122_create_setup_plans_user_org_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX IF NOT EXISTS idx_setup_plans_user_org ON setup_plans(user_id, organization_id)diff --git a/backend/app/migrations/pg/0123_create_setup_plans_org_idx.up.sql b/backend/app/migrations/pg/0123_create_setup_plans_org_idx.up.sqlnew file mode 100644index 00000000..00e96700--- /dev/null+++ b/backend/app/migrations/pg/0123_create_setup_plans_org_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX IF NOT EXISTS idx_setup_plans_org ON setup_plans(organization_id)diff --git a/backend/app/migrations/sqlite/0067_create_setup_tokens.up.sql b/backend/app/migrations/sqlite/0067_create_setup_tokens.up.sqlnew file mode 100644index 00000000..b7662a9f--- /dev/null+++ b/backend/app/migrations/sqlite/0067_create_setup_tokens.up.sql@@ -0,0 +1,11 @@+CREATE TABLE IF NOT EXISTS setup_tokens (+ id TEXT PRIMARY KEY,+ token_hash TEXT NOT NULL UNIQUE,+ prefix TEXT NOT NULL,+ user_id INTEGER NOT NULL,+ organization_id INTEGER NOT NULL,+ created_at DATETIME NOT NULL,+ expires_at DATETIME NOT NULL+);++CREATE INDEX IF NOT EXISTS idx_setup_tokens_user_org ON setup_tokens(user_id, organization_id);diff --git a/backend/app/migrations/sqlite/0068_create_setup_plans.up.sql b/backend/app/migrations/sqlite/0068_create_setup_plans.up.sqlnew file mode 100644index 00000000..d1e83549--- /dev/null+++ b/backend/app/migrations/sqlite/0068_create_setup_plans.up.sql@@ -0,0 +1,16 @@+CREATE TABLE IF NOT EXISTS setup_plans (+ id TEXT PRIMARY KEY,+ user_id INTEGER NOT NULL,+ organization_id INTEGER NOT NULL,+ payload TEXT NOT NULL,+ status TEXT NOT NULL,+ reject_reason TEXT,+ result TEXT,+ created_at DATETIME NOT NULL,+ decided_at DATETIME,+ decided_by INTEGER+);++CREATE INDEX IF NOT EXISTS idx_setup_plans_user_org ON setup_plans(user_id, organization_id);++CREATE INDEX IF NOT EXISTS idx_setup_plans_org ON setup_plans(organization_id);diff --git a/backend/app/models/auth.model.go b/backend/app/models/auth.model.goindex 329ddcb1..a7c68011 100644--- a/backend/app/models/auth.model.go+++ b/backend/app/models/auth.model.go@@ -25,15 +25,15 @@ type RegisterRequest struct {Password string `json:"password" binding:"required,min=8"`OrganizationName string `json:"organizationName" binding:"required"`Timezone string `json:"timezone" binding:"required"`- ProjectName string `json:"projectName" binding:"required"`- Framework string `json:"framework" binding:"required"`+ ProjectName string `json:"projectName"`+ Framework string `json:"framework"`CaptchaToken string `json:"captchaToken"`}type RegisterResponse struct {Token string `json:"token"`User UserResponse `json:"user"`- Project ProjectWithBackendUrl `json:"project"`+ Project *ProjectWithBackendUrl `json:"project,omitempty"`Projects []*ProjectWithBackendUrl `json:"projects"`Organizations []*UserOrganizationResponse `json:"organizations"`}diff --git a/backend/app/models/project.model.go b/backend/app/models/project.model.goindex 50091c3d..733103f3 100644--- a/backend/app/models/project.model.go+++ b/backend/app/models/project.model.go@@ -59,10 +59,10 @@ type Project struct {}func (p Project) ToProjectWithBackendUrl() *ProjectWithBackendUrl {- return &ProjectWithBackendUrl{Project: p, BackendUrl: getBackendUrl()}+ return &ProjectWithBackendUrl{Project: p, BackendUrl: GetBackendUrl()}}-func getBackendUrl() string {+func GetBackendUrl() string {if url := config.Config.AppBaseURL; url != "" {return url}diff --git a/backend/app/models/setup.model.go b/backend/app/models/setup.model.gonew file mode 100644index 00000000..ee2f52f8--- /dev/null+++ b/backend/app/models/setup.model.go@@ -0,0 +1,33 @@+package models++import "time"++type CreateSetupTokenRequest struct {+ OrganizationId int `json:"organizationId" binding:"required"`+}++type CreateSetupTokenResponse struct {+ Token string `json:"token"`+ Prefix string `json:"prefix"`+ ExpiresAt time.Time `json:"expiresAt"`+ OrganizationId int `json:"organizationId"`+ BackendUrl string `json:"backendUrl"`+}++type SetupPlanDeployment struct {+ Platform string `json:"platform"`+ Instructions string `json:"instructions"`+}++type SetupPlanProject struct {+ Name string `json:"name"`+ Framework string `json:"framework"`+ EnvFile string `json:"envFile,omitempty"`+ EnvVar string `json:"envVar,omitempty"`+ EnvFormat string `json:"envFormat,omitempty"`+ Deployment *SetupPlanDeployment `json:"deployment,omitempty"`+}++type SetupPlanPayload struct {+ Projects []SetupPlanProject `json:"projects"`+}diff --git a/backend/app/repositories/transactional/pg/setup_plan.repository.go b/backend/app/repositories/transactional/pg/setup_plan.repository.gonew file mode 100644index 00000000..327ba468--- /dev/null+++ b/backend/app/repositories/transactional/pg/setup_plan.repository.go@@ -0,0 +1,182 @@+//go:build transactional_pg++package pg++import (+ "database/sql"+ "errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+ "time"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+)++type setupPlanRepository struct{}++func (r *setupPlanRepository) Upsert(ex lit.Executor, id string, userId, organizationId int, payload string) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM setup_plans WHERE user_id = :user_id AND organization_id = :org_id",+ lit.P{"user_id": userId, "org_id": organizationId},+ )+ if err != nil {+ return err+ }+ if _, err = ex.Exec(query, args...); err != nil {+ return err+ }++ query, args, err = lit.ParseNamedQuery(+ db.Driver,+ `INSERT INTO setup_plans (id, user_id, organization_id, payload, status, created_at)+ VALUES (:id, :user_id, :org_id, :payload, :status, :created_at)`,+ lit.P{+ "id": id,+ "user_id": userId,+ "org_id": organizationId,+ "payload": payload,+ "status": "pending",+ "created_at": shared.FormatAuthTime(time.Now()),+ },+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++const setupPlanColumns = `p.id, p.user_id, p.organization_id, u.email, p.payload, p.status,+ p.reject_reason, p.result, p.created_at, p.decided_at, p.decided_by`++func (r *setupPlanRepository) scanRow(row *sql.Row) (*shared.SetupPlanRow, error) {+ var (+ plan shared.SetupPlanRow+ rejectReason sql.NullString+ result sql.NullString+ createdAt string+ decidedAt sql.NullString+ decidedBy sql.NullInt64+ )+ err := row.Scan(&plan.Id, &plan.UserId, &plan.OrganizationId, &plan.RequestedByEmail, &plan.Payload,+ &plan.Status, &rejectReason, &result, &createdAt, &decidedAt, &decidedBy)+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }+ plan.RejectReason = rejectReason.String+ plan.Result = result.String+ if plan.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {+ return nil, err+ }+ if plan.DecidedAt, err = shared.ParseNullableAuthTime(decidedAt); err != nil {+ return nil, err+ }+ if decidedBy.Valid {+ by := int(decidedBy.Int64)+ plan.DecidedBy = &by+ }+ return &plan, nil+}++func (r *setupPlanRepository) FindLatestByUserAndOrganization(ex lit.Executor, userId, organizationId int) (*shared.SetupPlanRow, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT `+setupPlanColumns+`+ FROM setup_plans p+ JOIN users u ON u.id = p.user_id+ WHERE p.user_id = :user_id AND p.organization_id = :org_id+ ORDER BY p.created_at DESC+ LIMIT 1`,+ lit.P{"user_id": userId, "org_id": organizationId},+ )+ if err != nil {+ return nil, err+ }+ return r.scanRow(ex.QueryRow(query, args...))+}++func (r *setupPlanRepository) FindReviewableByOrganization(ex lit.Executor, organizationId int) (*shared.SetupPlanRow, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT `+setupPlanColumns+`+ FROM setup_plans p+ JOIN users u ON u.id = p.user_id+ WHERE p.organization_id = :org_id+ ORDER BY CASE WHEN p.status = :pending THEN 0 ELSE 1 END, p.created_at DESC+ LIMIT 1`,+ lit.P{"org_id": organizationId, "pending": "pending"},+ )+ if err != nil {+ return nil, err+ }+ return r.scanRow(ex.QueryRow(query, args...))+}++func (r *setupPlanRepository) FindById(ex lit.Executor, id string) (*shared.SetupPlanRow, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT `+setupPlanColumns+`+ FROM setup_plans p+ JOIN users u ON u.id = p.user_id+ WHERE p.id = :id`,+ lit.P{"id": id},+ )+ if err != nil {+ return nil, err+ }+ return r.scanRow(ex.QueryRow(query, args...))+}++func (r *setupPlanRepository) Decide(ex lit.Executor, id, status, rejectReason, result string, decidedBy int, decidedAt time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `UPDATE setup_plans+ SET status = :status, reject_reason = :reason, result = :result, decided_at = :decided_at, decided_by = :decided_by+ WHERE id = :id AND status = :pending`,+ lit.P{+ "status": status,+ "reason": rejectReason,+ "result": result,+ "decided_at": shared.FormatAuthTime(decidedAt),+ "decided_by": decidedBy,+ "id": id,+ "pending": "pending",+ },+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++func (r *setupPlanRepository) PruneOld(ex lit.Executor, now time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `DELETE FROM setup_plans+ WHERE (status <> :pending AND decided_at < :decided_cutoff)+ OR (status = :pending AND created_at < :pending_cutoff)`,+ lit.P{+ "pending": "pending",+ "decided_cutoff": shared.FormatAuthTime(now.Add(-7 * 24 * time.Hour)),+ "pending_cutoff": shared.FormatAuthTime(now.Add(-24 * time.Hour)),+ },+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++var SetupPlanRepository = setupPlanRepository{}diff --git a/backend/app/repositories/transactional/pg/setup_token.repository.go b/backend/app/repositories/transactional/pg/setup_token.repository.gonew file mode 100644index 00000000..0409748f--- /dev/null+++ b/backend/app/repositories/transactional/pg/setup_token.repository.go@@ -0,0 +1,106 @@+//go:build transactional_pg++package pg++import (+ "database/sql"+ "errors"+ "time"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+)++type setupTokenRepository struct{}++func (r *setupTokenRepository) Create(ex lit.Executor, id, token, prefix string, userId, organizationId int, expiresAt time.Time) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `INSERT INTO setup_tokens (id, token_hash, prefix, user_id, organization_id, created_at, expires_at)+ VALUES (:id, :hash, :prefix, :user_id, :organization_id, :created_at, :expires_at)`,+ lit.P{+ "id": id,+ "hash": shared.HashAuthToken(token),+ "prefix": prefix,+ "user_id": userId,+ "organization_id": organizationId,+ "created_at": shared.FormatAuthTime(time.Now()),+ "expires_at": shared.FormatAuthTime(expiresAt),+ },+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++func (r *setupTokenRepository) DeleteByUserAndOrganization(ex lit.Executor, userId, organizationId int) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM setup_tokens WHERE user_id = :user_id AND organization_id = :org_id",+ lit.P{"user_id": userId, "org_id": organizationId},+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++func (r *setupTokenRepository) FindActiveByToken(ex lit.Executor, token string) (*shared.ActiveSetupToken, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT s.id, s.user_id, s.organization_id, s.expires_at, u.email+ FROM setup_tokens s+ JOIN users u ON u.id = s.user_id+ JOIN organization_users ou+ ON ou.user_id = s.user_id+ AND ou.organization_id = s.organization_id+ AND ou.role <> 'readonly'+ WHERE s.token_hash = :hash`,+ lit.P{"hash": shared.HashAuthToken(token)},+ )+ if err != nil {+ return nil, err+ }++ var (+ st shared.ActiveSetupToken+ expiresAt string+ )+ err = ex.QueryRow(query, args...).Scan(&st.Id, &st.UserId, &st.OrganizationId, &expiresAt, &st.Email)+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }++ if st.ExpiresAt, err = shared.ParseAuthTime(expiresAt); err != nil {+ return nil, err+ }+ if time.Now().After(st.ExpiresAt) {+ return nil, nil+ }+ return &st, nil+}++func (r *setupTokenRepository) PruneExpired(ex lit.Executor, now time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM setup_tokens WHERE expires_at < :cutoff",+ lit.P{"cutoff": shared.FormatAuthTime(now)},+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++var SetupTokenRepository = setupTokenRepository{}diff --git a/backend/app/repositories/transactional/setup_plan.repository_test.go b/backend/app/repositories/transactional/setup_plan.repository_test.gonew file mode 100644index 00000000..b331c481--- /dev/null+++ b/backend/app/repositories/transactional/setup_plan.repository_test.go@@ -0,0 +1,192 @@+//go:build !transactional_pg++package transactional++import (+ "testing"+ "time"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+)++func setupSetupPlanTables(t *testing.T) {+ t.Helper()+ setupSetupTokenTables(t)+ if _, err := db.DB.Exec(`CREATE TABLE IF NOT EXISTS setup_plans (+ id TEXT PRIMARY KEY,+ user_id INTEGER NOT NULL,+ organization_id INTEGER NOT NULL,+ payload TEXT NOT NULL,+ status TEXT NOT NULL,+ reject_reason TEXT,+ result TEXT,+ created_at DATETIME NOT NULL,+ decided_at DATETIME,+ decided_by INTEGER+ )`); err != nil {+ t.Fatalf("failed to create setup_plans table: %v", err)+ }+}++const testPlanPayload = `{"projects":[{"name":"Api","framework":"opentelemetry"}]}`++func TestSetupPlanUpsertReplacesPrevious(t *testing.T) {+ setupTestDB(t)+ setupSetupPlanTables(t)+ userId := insertSetupTestUser(t, "[email protected]")++ if err := SetupPlanRepository.Upsert(db.DB, "plan-1", userId, 1, testPlanPayload); err != nil {+ t.Fatalf("failed to upsert plan-1: %v", err)+ }+ if _, err := SetupPlanRepository.Decide(db.DB, "plan-1", "approved", "", "[]", userId, time.Now()); err != nil {+ t.Fatalf("failed to decide plan-1: %v", err)+ }+ if err := SetupPlanRepository.Upsert(db.DB, "plan-2", userId, 1, testPlanPayload); err != nil {+ t.Fatalf("failed to upsert plan-2: %v", err)+ }++ var count int+ if err := db.DB.QueryRow("SELECT COUNT(*) FROM setup_plans WHERE user_id = ? AND organization_id = 1", userId).Scan(&count); err != nil {+ t.Fatalf("count failed: %v", err)+ }+ if count != 1 {+ t.Fatalf("plans for (user, org) = %d, want 1 (upsert replaces)", count)+ }++ plan, err := SetupPlanRepository.FindLatestByUserAndOrganization(db.DB, userId, 1)+ if err != nil {+ t.Fatalf("find latest failed: %v", err)+ }+ if plan == nil || plan.Id != "plan-2" || plan.Status != "pending" {+ t.Fatalf("latest plan = %+v, want fresh pending plan-2", plan)+ }+ if plan.RequestedByEmail != "[email protected]" {+ t.Errorf("requestedByEmail = %q", plan.RequestedByEmail)+ }+}++func TestSetupPlanDecideGuard(t *testing.T) {+ setupTestDB(t)+ setupSetupPlanTables(t)+ userId := insertSetupTestUser(t, "[email protected]")++ if err := SetupPlanRepository.Upsert(db.DB, "plan-1", userId, 1, testPlanPayload); err != nil {+ t.Fatalf("failed to upsert: %v", err)+ }++ rows, err := SetupPlanRepository.Decide(db.DB, "plan-1", "rejected", "wrong split", "", userId, time.Now())+ if err != nil || rows != 1 {+ t.Fatalf("first decide: (%d, %v), want (1, nil)", rows, err)+ }++ rows, err = SetupPlanRepository.Decide(db.DB, "plan-1", "approved", "", "[]", userId, time.Now())+ if err != nil {+ t.Fatalf("second decide errored: %v", err)+ }+ if rows != 0 {+ t.Fatalf("second decide affected %d rows, want 0 (already decided)", rows)+ }++ plan, err := SetupPlanRepository.FindById(db.DB, "plan-1")+ if err != nil || plan == nil {+ t.Fatalf("find by id: (%v, %v)", plan, err)+ }+ if plan.Status != "rejected" || plan.RejectReason != "wrong split" {+ t.Errorf("plan = %+v, want rejected with reason preserved", plan)+ }+ if plan.DecidedAt == nil || plan.DecidedBy == nil || *plan.DecidedBy != userId {+ t.Errorf("decided metadata missing: %+v", plan)+ }+}++func TestSetupPlanFindReviewablePrefersPendingAcrossUsers(t *testing.T) {+ setupTestDB(t)+ setupSetupPlanTables(t)+ firstUserId := insertSetupTestUser(t, "[email protected]")+ secondUserId := insertSetupTestUser(t, "[email protected]")++ if err := SetupPlanRepository.Upsert(db.DB, "older-pending", firstUserId, 1, testPlanPayload); err != nil {+ t.Fatalf("failed to insert pending plan: %v", err)+ }+ if err := SetupPlanRepository.Upsert(db.DB, "newer-approved", secondUserId, 1, testPlanPayload); err != nil {+ t.Fatalf("failed to insert approved plan: %v", err)+ }+ if _, err := SetupPlanRepository.Decide(db.DB, "newer-approved", "approved", "", "[]", secondUserId, time.Now()); err != nil {+ t.Fatalf("failed to approve newer plan: %v", err)+ }++ older := shared.FormatAuthTime(time.Now().Add(-time.Minute))+ newer := shared.FormatAuthTime(time.Now())+ if _, err := db.DB.Exec("UPDATE setup_plans SET created_at = ? WHERE id = ?", older, "older-pending"); err != nil {+ t.Fatalf("failed to age pending plan: %v", err)+ }+ if _, err := db.DB.Exec("UPDATE setup_plans SET created_at = ? WHERE id = ?", newer, "newer-approved"); err != nil {+ t.Fatalf("failed to date approved plan: %v", err)+ }++ plan, err := SetupPlanRepository.FindReviewableByOrganization(db.DB, 1)+ if err != nil {+ t.Fatalf("find reviewable failed: %v", err)+ }+ if plan == nil || plan.Id != "older-pending" {+ t.Fatalf("reviewable plan = %+v, want older-pending", plan)+ }++ if _, err := SetupPlanRepository.Decide(db.DB, "older-pending", "rejected", "", "", firstUserId, time.Now()); err != nil {+ t.Fatalf("failed to reject pending plan: %v", err)+ }+ plan, err = SetupPlanRepository.FindReviewableByOrganization(db.DB, 1)+ if err != nil {+ t.Fatalf("find latest decided failed: %v", err)+ }+ if plan == nil || plan.Id != "newer-approved" {+ t.Fatalf("latest decided plan = %+v, want newer-approved", plan)+ }+}++func TestSetupPlanPruneOld(t *testing.T) {+ setupTestDB(t)+ setupSetupPlanTables(t)+ userId := insertSetupTestUser(t, "[email protected]")++ now := time.Now().UTC()+ insert := func(id, status string, createdAt time.Time, decidedAt *time.Time) {+ t.Helper()+ var decided any+ if decidedAt != nil {+ decided = shared.FormatAuthTime(*decidedAt)+ }+ if _, err := db.DB.Exec(+ "INSERT INTO setup_plans (id, user_id, organization_id, payload, status, created_at, decided_at) VALUES (?, ?, ?, ?, ?, ?, ?)",+ id, userId, 1, testPlanPayload, status, shared.FormatAuthTime(createdAt), decided,+ ); err != nil {+ t.Fatalf("insert %s: %v", id, err)+ }+ }++ oldDecision := now.Add(-8 * 24 * time.Hour)+ freshDecision := now.Add(-time.Hour)+ insert("stale-approved", "approved", oldDecision, &oldDecision)+ insert("fresh-approved", "approved", freshDecision, &freshDecision)+ insert("stale-pending", "pending", now.Add(-25*time.Hour), nil)+ insert("fresh-pending", "pending", now.Add(-time.Hour), nil)++ pruned, err := SetupPlanRepository.PruneOld(db.DB, now)+ if err != nil {+ t.Fatalf("prune failed: %v", err)+ }+ if pruned != 2 {+ t.Fatalf("pruned = %d, want 2", pruned)+ }+ for _, id := range []string{"fresh-approved", "fresh-pending"} {+ if plan, _ := SetupPlanRepository.FindById(db.DB, id); plan == nil {+ t.Errorf("%s must survive the prune", id)+ }+ }+ for _, id := range []string{"stale-approved", "stale-pending"} {+ if plan, _ := SetupPlanRepository.FindById(db.DB, id); plan != nil {+ t.Errorf("%s should be pruned", id)+ }+ }+}diff --git a/backend/app/repositories/transactional/setup_token.repository_test.go b/backend/app/repositories/transactional/setup_token.repository_test.gonew file mode 100644index 00000000..7e1d13c5--- /dev/null+++ b/backend/app/repositories/transactional/setup_token.repository_test.go@@ -0,0 +1,208 @@+//go:build !transactional_pg++package transactional++import (+ "testing"+ "time"++ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+)++func setupSetupTokenTables(t *testing.T) {+ t.Helper()+ if _, err := db.DB.Exec(`CREATE TABLE IF NOT EXISTS users (+ id INTEGER PRIMARY KEY AUTOINCREMENT,+ email TEXT NOT NULL,+ name TEXT NOT NULL DEFAULT '',+ password TEXT NOT NULL DEFAULT ''+ )`); err != nil {+ t.Fatalf("failed to create users table: %v", err)+ }+ if _, err := db.DB.Exec(`CREATE TABLE IF NOT EXISTS setup_tokens (+ id TEXT PRIMARY KEY,+ token_hash TEXT NOT NULL UNIQUE,+ prefix TEXT NOT NULL,+ user_id INTEGER NOT NULL,+ organization_id INTEGER NOT NULL,+ created_at DATETIME NOT NULL,+ expires_at DATETIME NOT NULL+ )`); err != nil {+ t.Fatalf("failed to create setup_tokens table: %v", err)+ }+ if _, err := db.DB.Exec(`CREATE TABLE IF NOT EXISTS organization_users (+ user_id INTEGER NOT NULL,+ organization_id INTEGER NOT NULL,+ role TEXT NOT NULL,+ UNIQUE(user_id, organization_id)+ )`); err != nil {+ t.Fatalf("failed to create organization_users table: %v", err)+ }+}++func insertSetupTestUser(t *testing.T, email string) int {+ t.Helper()+ res, err := db.DB.Exec("INSERT INTO users (email) VALUES (?)", email)+ if err != nil {+ t.Fatalf("failed to insert user: %v", err)+ }+ id, _ := res.LastInsertId()+ return int(id)+}++func grantSetupTestOrg(t *testing.T, userId, organizationId int, role string) {+ t.Helper()+ if _, err := db.DB.Exec(+ "INSERT INTO organization_users (user_id, organization_id, role) VALUES (?, ?, ?)",+ userId, organizationId, role,+ ); err != nil {+ t.Fatalf("failed to grant organization role: %v", err)+ }+}++func TestSetupTokenRoundTrip(t *testing.T) {+ setupTestDB(t)+ setupSetupTokenTables(t)+ userId := insertSetupTestUser(t, "[email protected]")+ grantSetupTestOrg(t, userId, 7, "user")++ token := "tws_test-token-value"+ expiresAt := time.Now().Add(time.Hour).UTC()+ if err := SetupTokenRepository.Create(db.DB, "tok-1", token, token[:12], userId, 7, expiresAt); err != nil {+ t.Fatalf("failed to create setup token: %v", err)+ }++ var storedHash string+ if err := db.DB.QueryRow("SELECT token_hash FROM setup_tokens WHERE id = 'tok-1'").Scan(&storedHash); err != nil {+ t.Fatalf("failed to read token_hash: %v", err)+ }+ if storedHash == token {+ t.Fatal("token must not be stored in plaintext")+ }+ if storedHash != shared.HashAuthToken(token) {+ t.Fatalf("token_hash = %q, want sha256 of the token", storedHash)+ }++ st, err := SetupTokenRepository.FindActiveByToken(db.DB, token)+ if err != nil {+ t.Fatalf("failed to find setup token: %v", err)+ }+ if st == nil {+ t.Fatal("expected an active setup token")+ }+ if st.UserId != userId || st.OrganizationId != 7 || st.Email != "[email protected]" {+ t.Errorf("unexpected token identity: %+v", st)+ }+ if st.ExpiresAt.Sub(expiresAt).Abs() > time.Second {+ t.Errorf("expiresAt = %v, want %v", st.ExpiresAt, expiresAt)+ }+}++func TestSetupTokenUnknownAndExpired(t *testing.T) {+ setupTestDB(t)+ setupSetupTokenTables(t)+ userId := insertSetupTestUser(t, "[email protected]")+ grantSetupTestOrg(t, userId, 7, "user")++ if st, err := SetupTokenRepository.FindActiveByToken(db.DB, "tws_unknown"); err != nil || st != nil {+ t.Fatalf("unknown token: got (%v, %v), want (nil, nil)", st, err)+ }++ expired := "tws_expired-token"+ if err := SetupTokenRepository.Create(db.DB, "tok-exp", expired, expired[:12], userId, 7, time.Now().Add(-time.Minute)); err != nil {+ t.Fatalf("failed to create expired token: %v", err)+ }+ if st, err := SetupTokenRepository.FindActiveByToken(db.DB, expired); err != nil || st != nil {+ t.Fatalf("expired token: got (%v, %v), want (nil, nil)", st, err)+ }+}++func TestSetupTokenDeleteByUserAndOrganizationScopes(t *testing.T) {+ setupTestDB(t)+ setupSetupTokenTables(t)+ userId := insertSetupTestUser(t, "[email protected]")+ otherUser := insertSetupTestUser(t, "[email protected]")+ grantSetupTestOrg(t, userId, 1, "user")+ grantSetupTestOrg(t, userId, 2, "user")+ grantSetupTestOrg(t, otherUser, 1, "user")++ expiresAt := time.Now().Add(time.Hour)+ mustCreate := func(id, token string, uid, orgId int) {+ t.Helper()+ if err := SetupTokenRepository.Create(db.DB, id, token, token, uid, orgId, expiresAt); err != nil {+ t.Fatalf("failed to create %s: %v", id, err)+ }+ }+ mustCreate("tok-a", "tws_token-a", userId, 1)+ mustCreate("tok-b", "tws_token-b", userId, 2)+ mustCreate("tok-c", "tws_token-c", otherUser, 1)++ if err := SetupTokenRepository.DeleteByUserAndOrganization(db.DB, userId, 1); err != nil {+ t.Fatalf("failed to delete: %v", err)+ }++ if st, _ := SetupTokenRepository.FindActiveByToken(db.DB, "tws_token-a"); st != nil {+ t.Error("token for (user, org 1) should be deleted")+ }+ if st, _ := SetupTokenRepository.FindActiveByToken(db.DB, "tws_token-b"); st == nil {+ t.Error("same user's token for another org must survive")+ }+ if st, _ := SetupTokenRepository.FindActiveByToken(db.DB, "tws_token-c"); st == nil {+ t.Error("another user's token for the same org must survive")+ }+}++func TestSetupTokenRequiresCurrentOrganizationWriteAccess(t *testing.T) {+ setupTestDB(t)+ setupSetupTokenTables(t)+ userId := insertSetupTestUser(t, "[email protected]")+ grantSetupTestOrg(t, userId, 7, "user")++ token := "tws_membership-token"+ if err := SetupTokenRepository.Create(db.DB, "tok-membership", token, token, userId, 7, time.Now().Add(time.Hour)); err != nil {+ t.Fatalf("failed to create setup token: %v", err)+ }+ if st, err := SetupTokenRepository.FindActiveByToken(db.DB, token); err != nil || st == nil {+ t.Fatalf("writable membership token = (%v, %v), want active", st, err)+ }++ if _, err := db.DB.Exec("UPDATE organization_users SET role = 'readonly' WHERE user_id = ? AND organization_id = ?", userId, 7); err != nil {+ t.Fatalf("downgrade membership: %v", err)+ }+ if st, err := SetupTokenRepository.FindActiveByToken(db.DB, token); err != nil || st != nil {+ t.Fatalf("read-only membership token = (%v, %v), want inactive", st, err)+ }++ if _, err := db.DB.Exec("DELETE FROM organization_users WHERE user_id = ? AND organization_id = ?", userId, 7); err != nil {+ t.Fatalf("remove membership: %v", err)+ }+ if st, err := SetupTokenRepository.FindActiveByToken(db.DB, token); err != nil || st != nil {+ t.Fatalf("removed membership token = (%v, %v), want inactive", st, err)+ }+}++func TestSetupTokenPruneExpired(t *testing.T) {+ setupTestDB(t)+ setupSetupTokenTables(t)+ userId := insertSetupTestUser(t, "[email protected]")+ grantSetupTestOrg(t, userId, 1, "user")++ if err := SetupTokenRepository.Create(db.DB, "tok-live", "tws_live", "tws_live", userId, 1, time.Now().Add(time.Hour)); err != nil {+ t.Fatalf("failed to create live token: %v", err)+ }+ if err := SetupTokenRepository.Create(db.DB, "tok-dead", "tws_dead", "tws_dead", userId, 1, time.Now().Add(-time.Hour)); err != nil {+ t.Fatalf("failed to create expired token: %v", err)+ }++ pruned, err := SetupTokenRepository.PruneExpired(db.DB, time.Now())+ if err != nil {+ t.Fatalf("prune failed: %v", err)+ }+ if pruned != 1 {+ t.Fatalf("pruned = %d, want 1", pruned)+ }+ if st, _ := SetupTokenRepository.FindActiveByToken(db.DB, "tws_live"); st == nil {+ t.Error("live token must survive the prune")+ }+}diff --git a/backend/app/repositories/transactional/shared/types.go b/backend/app/repositories/transactional/shared/types.goindex b0701993..3ff4ad13 100644--- a/backend/app/repositories/transactional/shared/types.go+++ b/backend/app/repositories/transactional/shared/types.go@@ -17,3 +17,25 @@ type ActivePAT struct {Email stringLastUsedAt *time.Time}++type ActiveSetupToken struct {+ Id string+ UserId int+ OrganizationId int+ Email string+ ExpiresAt time.Time+}++type SetupPlanRow struct {+ Id string+ UserId int+ OrganizationId int+ RequestedByEmail string+ Payload string+ Status string+ RejectReason string+ Result string+ CreatedAt time.Time+ DecidedAt *time.Time+ DecidedBy *int+}diff --git a/backend/app/repositories/transactional/sqlite/setup_plan.repository.go b/backend/app/repositories/transactional/sqlite/setup_plan.repository.gonew file mode 100644index 00000000..b86336f0--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/setup_plan.repository.go@@ -0,0 +1,182 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "errors"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+ "time"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+)++type setupPlanRepository struct{}++func (r *setupPlanRepository) Upsert(ex lit.Executor, id string, userId, organizationId int, payload string) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM setup_plans WHERE user_id = :user_id AND organization_id = :org_id",+ lit.P{"user_id": userId, "org_id": organizationId},+ )+ if err != nil {+ return err+ }+ if _, err = ex.Exec(query, args...); err != nil {+ return err+ }++ query, args, err = lit.ParseNamedQuery(+ db.Driver,+ `INSERT INTO setup_plans (id, user_id, organization_id, payload, status, created_at)+ VALUES (:id, :user_id, :org_id, :payload, :status, :created_at)`,+ lit.P{+ "id": id,+ "user_id": userId,+ "org_id": organizationId,+ "payload": payload,+ "status": "pending",+ "created_at": shared.FormatAuthTime(time.Now()),+ },+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++const setupPlanColumns = `p.id, p.user_id, p.organization_id, u.email, p.payload, p.status,+ p.reject_reason, p.result, p.created_at, p.decided_at, p.decided_by`++func (r *setupPlanRepository) scanRow(row *sql.Row) (*shared.SetupPlanRow, error) {+ var (+ plan shared.SetupPlanRow+ rejectReason sql.NullString+ result sql.NullString+ createdAt string+ decidedAt sql.NullString+ decidedBy sql.NullInt64+ )+ err := row.Scan(&plan.Id, &plan.UserId, &plan.OrganizationId, &plan.RequestedByEmail, &plan.Payload,+ &plan.Status, &rejectReason, &result, &createdAt, &decidedAt, &decidedBy)+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }+ plan.RejectReason = rejectReason.String+ plan.Result = result.String+ if plan.CreatedAt, err = shared.ParseAuthTime(createdAt); err != nil {+ return nil, err+ }+ if plan.DecidedAt, err = shared.ParseNullableAuthTime(decidedAt); err != nil {+ return nil, err+ }+ if decidedBy.Valid {+ by := int(decidedBy.Int64)+ plan.DecidedBy = &by+ }+ return &plan, nil+}++func (r *setupPlanRepository) FindLatestByUserAndOrganization(ex lit.Executor, userId, organizationId int) (*shared.SetupPlanRow, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT `+setupPlanColumns+`+ FROM setup_plans p+ JOIN users u ON u.id = p.user_id+ WHERE p.user_id = :user_id AND p.organization_id = :org_id+ ORDER BY p.created_at DESC+ LIMIT 1`,+ lit.P{"user_id": userId, "org_id": organizationId},+ )+ if err != nil {+ return nil, err+ }+ return r.scanRow(ex.QueryRow(query, args...))+}++func (r *setupPlanRepository) FindReviewableByOrganization(ex lit.Executor, organizationId int) (*shared.SetupPlanRow, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT `+setupPlanColumns+`+ FROM setup_plans p+ JOIN users u ON u.id = p.user_id+ WHERE p.organization_id = :org_id+ ORDER BY CASE WHEN p.status = :pending THEN 0 ELSE 1 END, p.created_at DESC+ LIMIT 1`,+ lit.P{"org_id": organizationId, "pending": "pending"},+ )+ if err != nil {+ return nil, err+ }+ return r.scanRow(ex.QueryRow(query, args...))+}++func (r *setupPlanRepository) FindById(ex lit.Executor, id string) (*shared.SetupPlanRow, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT `+setupPlanColumns+`+ FROM setup_plans p+ JOIN users u ON u.id = p.user_id+ WHERE p.id = :id`,+ lit.P{"id": id},+ )+ if err != nil {+ return nil, err+ }+ return r.scanRow(ex.QueryRow(query, args...))+}++func (r *setupPlanRepository) Decide(ex lit.Executor, id, status, rejectReason, result string, decidedBy int, decidedAt time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `UPDATE setup_plans+ SET status = :status, reject_reason = :reason, result = :result, decided_at = :decided_at, decided_by = :decided_by+ WHERE id = :id AND status = :pending`,+ lit.P{+ "status": status,+ "reason": rejectReason,+ "result": result,+ "decided_at": shared.FormatAuthTime(decidedAt),+ "decided_by": decidedBy,+ "id": id,+ "pending": "pending",+ },+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++func (r *setupPlanRepository) PruneOld(ex lit.Executor, now time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `DELETE FROM setup_plans+ WHERE (status <> :pending AND decided_at < :decided_cutoff)+ OR (status = :pending AND created_at < :pending_cutoff)`,+ lit.P{+ "pending": "pending",+ "decided_cutoff": shared.FormatAuthTime(now.Add(-7 * 24 * time.Hour)),+ "pending_cutoff": shared.FormatAuthTime(now.Add(-24 * time.Hour)),+ },+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++var SetupPlanRepository = setupPlanRepository{}diff --git a/backend/app/repositories/transactional/sqlite/setup_token.repository.go b/backend/app/repositories/transactional/sqlite/setup_token.repository.gonew file mode 100644index 00000000..a18bb082--- /dev/null+++ b/backend/app/repositories/transactional/sqlite/setup_token.repository.go@@ -0,0 +1,106 @@+//go:build !transactional_pg++package sqlite++import (+ "database/sql"+ "errors"+ "time"++ "github.com/tracewayapp/lit/v2"+ "github.com/tracewayapp/traceway/backend/app/db"+ "github.com/tracewayapp/traceway/backend/app/repositories/transactional/shared"+)++type setupTokenRepository struct{}++func (r *setupTokenRepository) Create(ex lit.Executor, id, token, prefix string, userId, organizationId int, expiresAt time.Time) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `INSERT INTO setup_tokens (id, token_hash, prefix, user_id, organization_id, created_at, expires_at)+ VALUES (:id, :hash, :prefix, :user_id, :organization_id, :created_at, :expires_at)`,+ lit.P{+ "id": id,+ "hash": shared.HashAuthToken(token),+ "prefix": prefix,+ "user_id": userId,+ "organization_id": organizationId,+ "created_at": shared.FormatAuthTime(time.Now()),+ "expires_at": shared.FormatAuthTime(expiresAt),+ },+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++func (r *setupTokenRepository) DeleteByUserAndOrganization(ex lit.Executor, userId, organizationId int) error {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM setup_tokens WHERE user_id = :user_id AND organization_id = :org_id",+ lit.P{"user_id": userId, "org_id": organizationId},+ )+ if err != nil {+ return err+ }+ _, err = ex.Exec(query, args...)+ return err+}++func (r *setupTokenRepository) FindActiveByToken(ex lit.Executor, token string) (*shared.ActiveSetupToken, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ `SELECT s.id, s.user_id, s.organization_id, s.expires_at, u.email+ FROM setup_tokens s+ JOIN users u ON u.id = s.user_id+ JOIN organization_users ou+ ON ou.user_id = s.user_id+ AND ou.organization_id = s.organization_id+ AND ou.role <> 'readonly'+ WHERE s.token_hash = :hash`,+ lit.P{"hash": shared.HashAuthToken(token)},+ )+ if err != nil {+ return nil, err+ }++ var (+ st shared.ActiveSetupToken+ expiresAt string+ )+ err = ex.QueryRow(query, args...).Scan(&st.Id, &st.UserId, &st.OrganizationId, &expiresAt, &st.Email)+ if errors.Is(err, sql.ErrNoRows) {+ return nil, nil+ }+ if err != nil {+ return nil, err+ }++ if st.ExpiresAt, err = shared.ParseAuthTime(expiresAt); err != nil {+ return nil, err+ }+ if time.Now().After(st.ExpiresAt) {+ return nil, nil+ }+ return &st, nil+}++func (r *setupTokenRepository) PruneExpired(ex lit.Executor, now time.Time) (int64, error) {+ query, args, err := lit.ParseNamedQuery(+ db.Driver,+ "DELETE FROM setup_tokens WHERE expires_at < :cutoff",+ lit.P{"cutoff": shared.FormatAuthTime(now)},+ )+ if err != nil {+ return 0, err+ }+ res, err := ex.Exec(query, args...)+ if err != nil {+ return 0, err+ }+ return res.RowsAffected()+}++var SetupTokenRepository = setupTokenRepository{}diff --git a/backend/app/repositories/transactional/transactional_pg.go b/backend/app/repositories/transactional/transactional_pg.goindex a60c90ea..bc5ad3a9 100644--- a/backend/app/repositories/transactional/transactional_pg.go+++ b/backend/app/repositories/transactional/transactional_pg.go@@ -30,6 +30,8 @@ var (ProjectRepository = pgrepo.ProjectRepositoryProjectUserRoleRepository = pgrepo.ProjectUserRoleRepositoryRefreshTokenRepository = pgrepo.RefreshTokenRepository+ SetupPlanRepository = pgrepo.SetupPlanRepository+ SetupTokenRepository = pgrepo.SetupTokenRepositoryStatusPageRepository = pgrepo.StatusPageRepositorySyntheticCheckRepository = pgrepo.SyntheticCheckRepositorySyntheticRunnerRepository = pgrepo.SyntheticRunnerRepositorydiff --git a/backend/app/repositories/transactional/transactional_shared.go b/backend/app/repositories/transactional/transactional_shared.goindex 1ff4a53c..741dddc1 100644--- a/backend/app/repositories/transactional/transactional_shared.go+++ b/backend/app/repositories/transactional/transactional_shared.go@@ -6,5 +6,7 @@ import "github.com/tracewayapp/traceway/backend/app/repositories/transactional/s// which relational backend is compiled in.type (ActivePAT = shared.ActivePAT+ ActiveSetupToken = shared.ActiveSetupTokenMetricRegistrationEntry = shared.MetricRegistrationEntry+ SetupPlanRow = shared.SetupPlanRow)diff --git a/backend/app/repositories/transactional/transactional_sqlite.go b/backend/app/repositories/transactional/transactional_sqlite.goindex 2effc2c5..6787fa7d 100644--- a/backend/app/repositories/transactional/transactional_sqlite.go+++ b/backend/app/repositories/transactional/transactional_sqlite.go@@ -30,6 +30,8 @@ var (ProjectRepository = sqliterepo.ProjectRepositoryProjectUserRoleRepository = sqliterepo.ProjectUserRoleRepositoryRefreshTokenRepository = sqliterepo.RefreshTokenRepository+ SetupPlanRepository = sqliterepo.SetupPlanRepository+ SetupTokenRepository = sqliterepo.SetupTokenRepositoryStatusPageRepository = sqliterepo.StatusPageRepositorySyntheticCheckRepository = sqliterepo.SyntheticCheckRepositorySyntheticRunnerRepository = sqliterepo.SyntheticRunnerRepositorydiff --git a/backend/app/retention/auth_tokens.go b/backend/app/retention/auth_tokens.goindex b05ed95e..19523492 100644--- a/backend/app/retention/auth_tokens.go+++ b/backend/app/retention/auth_tokens.go@@ -45,6 +45,18 @@ func startAuthTokensPrune(ctx context.Context) {}total += n+ n, err = transactional.SetupTokenRepository.PruneExpired(tx, now)+ if err != nil {+ return total, err+ }+ total += n++ n, err = transactional.SetupPlanRepository.PruneOld(tx, now)+ if err != nil {+ return total, err+ }+ total += n+return total, nil})}diff --git a/backend/app/services/authserver/tokens.go b/backend/app/services/authserver/tokens.goindex d93205b8..5fb3ed55 100644--- a/backend/app/services/authserver/tokens.go+++ b/backend/app/services/authserver/tokens.go@@ -43,6 +43,10 @@ func NewPATToken() string {return newOpaqueToken("twp_")}+func NewSetupToken() string {+ return newOpaqueToken("tws_")+}+func IssueTokenSet(tx *sql.Tx, userId int, email, clientId string) (*models.TokenSetResponse, error) {return issueTokenSetWithFamily(tx, userId, email, clientId, uuid.New().String())}diff --git a/cli/cmd/traceway/root.go b/cli/cmd/traceway/root.goindex 8882bac7..0e56c20d 100644--- a/cli/cmd/traceway/root.go+++ b/cli/cmd/traceway/root.go@@ -33,6 +33,7 @@ func newRootCmd() *cobra.Command {cmd.AddCommand(newLogoutCmd())cmd.AddCommand(newProfilesCmd())cmd.AddCommand(newProjectsCmd())+ cmd.AddCommand(newSetupCmd())cmd.AddCommand(newExceptionsCmd())cmd.AddCommand(newLogsCmd())cmd.AddCommand(newEndpointsCmd())diff --git a/cli/cmd/traceway/setup.go b/cli/cmd/traceway/setup.gonew file mode 100644index 00000000..de383644--- /dev/null+++ b/cli/cmd/traceway/setup.go@@ -0,0 +1,65 @@+package main++import (+ "time"++ "github.com/spf13/cobra"+)++var (+ setupApplyURL string+ setupApplyToken string+ setupApplyTokenStdin bool+ setupApplyPlanPath string+ setupApplyWaitTimeout time.Duration+)++func newSetupCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "setup",+ Short: "Provision Traceway projects from a setup plan",+ }+ cmd.AddCommand(newSetupApplyCmd())+ return cmd+}++func newSetupApplyCmd() *cobra.Command {+ cmd := &cobra.Command{+ Use: "apply",+ Short: "Submit a setup plan for approval and write the resulting tokens into env files",+ Long: "Submit a setup plan for approval and write the resulting tokens into env files.\n\n" ++ "The plan is proposed as a draft: nothing is created until a logged-in user\n" ++ "approves it in the Traceway dashboard (the /setup page, or step 2 of\n" ++ "registration). This command waits for that decision, then writes each\n" ++ "project's ingest token into the env file named by the plan. Token values are\n" ++ "never printed.\n\n" ++ "Plan file format (JSON):\n\n" ++ " {\n" ++ " \"url\": \"https://traceway.example.com\",\n" ++ " \"projects\": [\n" ++ " {\"name\": \"Product Backend\", \"framework\": \"opentelemetry\",\n" ++ " \"envFile\": \"backend/.env\", \"envVar\": \"TRACEWAY_BACKEND_TOKEN\"},\n" ++ " {\"name\": \"Product Web\", \"framework\": \"svelte\",\n" ++ " \"envFile\": \"web/.env\", \"envVar\": \"PUBLIC_TRACEWAY_CONNECTION_STRING\",\n" ++ " \"envFormat\": \"connectionString\",\n" ++ " \"deployment\": {\"platform\": \"Vercel\", \"instructions\": \"vercel env add ... <token>\"}}\n" ++ " ]\n" ++ " }\n\n" ++ "envFormat \"token\" (default) writes the raw project token; \"connectionString\"\n" ++ "writes <token>@<instance>/api/report for the browser and mobile SDKs. Relative\n" ++ "envFile paths resolve against the plan file's directory. A deployment block\n" ++ "marks a credential that must live in the hosting platform instead; its exact\n" ++ "command (with the secret value) is shown on the dashboard's /setup page after\n" ++ "approval. The setup token is short-lived; pass it via --token-stdin or the\n" ++ "TRACEWAY_SETUP_TOKEN env var rather than --token to keep it out of shell\n" ++ "history. Re-running is safe: a pending draft is replaced and approved projects\n" ++ "are matched by name instead of duplicated.",+ RunE: runSetupApply,+ }+ cmd.Flags().StringVar(&setupApplyURL, "url", "", "Traceway base URL (default: the plan file's \"url\")")+ cmd.Flags().StringVar(&setupApplyToken, "token", "", "Setup token (tws_...); prefer --token-stdin or TRACEWAY_SETUP_TOKEN")+ cmd.Flags().BoolVar(&setupApplyTokenStdin, "token-stdin", false, "Read the setup token from stdin")+ cmd.Flags().StringVar(&setupApplyPlanPath, "plan", "", "Path to the setup plan JSON file (required)")+ cmd.Flags().DurationVar(&setupApplyWaitTimeout, "wait-timeout", 30*time.Minute, "How long to wait for the user to approve the plan")+ return cmd+}diff --git a/cli/cmd/traceway/setup_apply.go b/cli/cmd/traceway/setup_apply.gonew file mode 100644index 00000000..d908fb0c--- /dev/null+++ b/cli/cmd/traceway/setup_apply.go@@ -0,0 +1,331 @@+package main++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "regexp"+ "strings"+ "time"++ "github.com/spf13/cobra"++ "github.com/tracewayapp/traceway/cli/internal/envfile"+ "github.com/tracewayapp/traceway/cli/internal/exitcode"+ "github.com/tracewayapp/traceway/cli/internal/output"+ "github.com/tracewayapp/traceway/cli/pkg/client"+)++var setupPollInterval = 3 * time.Second++const (+ envFormatToken = "token"+ envFormatConnectionString = "connectionString"+)++type setupPlan struct {+ URL string `json:"url"`+ Projects []client.SetupPlanProject `json:"projects"`+}++var setupEnvVarRegex = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)++func loadSetupPlan(path string) (*setupPlan, error) {+ data, err := os.ReadFile(path)+ if err != nil {+ return nil, fmt.Errorf("reading plan file: %w", err)+ }+ var plan setupPlan+ if err := json.Unmarshal(data, &plan); err != nil {+ return nil, fmt.Errorf("parsing plan file: %w", err)+ }+ return &plan, nil+}++func validateSetupPlan(plan *setupPlan) error {+ if len(plan.Projects) == 0 {+ return errors.New("the plan has no projects")+ }+ if len(plan.Projects) > 20 {+ return errors.New("the plan has more than 20 projects")+ }+ for i, p := range plan.Projects {+ if strings.TrimSpace(p.Name) == "" {+ return fmt.Errorf("projects[%d] has no name", i)+ }+ if strings.TrimSpace(p.Framework) == "" {+ return fmt.Errorf("project %q has no framework", p.Name)+ }+ if p.EnvFile != "" && p.EnvVar == "" {+ return fmt.Errorf("project %q sets envFile without envVar", p.Name)+ }+ if p.EnvVar != "" && !setupEnvVarRegex.MatchString(p.EnvVar) {+ return fmt.Errorf("project %q has an invalid envVar %q", p.Name, p.EnvVar)+ }+ switch p.EnvFormat {+ case "", envFormatToken, envFormatConnectionString:+ default:+ return fmt.Errorf("project %q has an invalid envFormat %q (use \"token\" or \"connectionString\")", p.Name, p.EnvFormat)+ }+ }+ return nil+}++func resolveSetupToken(cmd *cobra.Command) (string, error) {+ if setupApplyToken != "" && setupApplyTokenStdin {+ return "", errors.New("choose one of --token or --token-stdin, not both")+ }+ if setupApplyToken != "" {+ return strings.TrimSpace(setupApplyToken), nil+ }+ if setupApplyTokenStdin {+ return readTokenStdin(cmd.InOrStdin())+ }+ return strings.TrimSpace(os.Getenv("TRACEWAY_SETUP_TOKEN")), nil+}++func renderSetupTokenError(errOut io.Writer, mode output.Mode) error {+ env := output.ErrorEnvelope{+ Code: "invalid_setup_token",+ Message: "the setup token is invalid or expired",+ Hint: "generate a new setup token on the Traceway dashboard's /setup page and retry",+ ExitCode: exitcode.Auth,+ }+ _ = output.RenderError(errOut, mode, env)+ return newCLIError(env.ExitCode, env.Code)+}++func renderSetupAPIError(errOut io.Writer, mode output.Mode, err error) error {+ if errors.Is(err, client.ErrUnauthorized) {+ return renderSetupTokenError(errOut, mode)+ }+ return renderAPIError(errOut, mode, err, false)+}++func setupEnvValue(project client.SetupProject, format, fallbackURL string) string {+ if format == envFormatConnectionString {+ base := strings.TrimRight(project.BackendURL, "/")+ if base == "" {+ base = strings.TrimRight(fallbackURL, "/")+ }+ return project.Token + "@" + base + "/api/report"+ }+ return project.Token+}++type setupApplyProjectSummary struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Framework string `json:"framework"`+ Status string `json:"status"`+ EnvFile string `json:"envFile,omitempty"`+ EnvVar string `json:"envVar,omitempty"`+ EnvResult string `json:"envResult,omitempty"`+ DashboardURL string `json:"dashboardUrl"`+ DeploymentPlatform string `json:"deploymentPlatform,omitempty"`+}++func runSetupApply(cmd *cobra.Command, _ []string) error {+ ctx := cmd.Context()+ if ctx == nil {+ ctx = context.Background()+ }+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())++ if setupApplyPlanPath == "" {+ return renderUsageError(cmd.ErrOrStderr(), mode, "no plan file provided", "traceway setup apply --plan <file> --token-stdin")+ }+ plan, err := loadSetupPlan(setupApplyPlanPath)+ if err != nil {+ return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(), "traceway setup apply --help")+ }+ if err := validateSetupPlan(plan); err != nil {+ return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(), "traceway setup apply --help")+ }++ token, err := resolveSetupToken(cmd)+ if err != nil {+ return renderUsageError(cmd.ErrOrStderr(), mode, err.Error(), "traceway setup apply --help")+ }+ if token == "" {+ return renderUsageError(cmd.ErrOrStderr(), mode, "no setup token provided", "traceway setup apply --plan <file> --token-stdin (or set TRACEWAY_SETUP_TOKEN)")+ }++ url := strings.TrimSpace(setupApplyURL)+ if url == "" {+ url = strings.TrimSpace(plan.URL)+ }+ if url == "" {+ return renderUsageError(cmd.ErrOrStderr(), mode, "no Traceway URL provided", "pass --url or add \"url\" to the plan file")+ }+ url = strings.TrimRight(url, "/")++ c := client.New(url, client.WithJWT(token))++ session, err := c.GetSetupSession(ctx)+ if err != nil {+ return renderSetupAPIError(cmd.ErrOrStderr(), mode, err)+ }+ fmt.Fprintf(cmd.ErrOrStderr(), "Applying plan to organization %q on %s as %s\n", session.OrganizationName, url, session.Email)++ if err := c.SubmitSetupPlan(ctx, plan.Projects); err != nil {+ return renderSetupAPIError(cmd.ErrOrStderr(), mode, err)+ }+ fmt.Fprintf(cmd.ErrOrStderr(), "Plan submitted. Ask the user to review and approve it at %s/setup (it also appears on the registration page if they still have it open).\nWaiting for approval...\n", url)++ projects, err := waitForSetupDecision(ctx, cmd.ErrOrStderr(), mode, c)+ if err != nil {+ return err+ }++ byName := make(map[string]client.SetupProject, len(projects))+ for _, p := range projects {+ byName[p.Name] = p+ }++ planDir := filepath.Dir(setupApplyPlanPath)+ summaries := make([]setupApplyProjectSummary, 0, len(plan.Projects))+ envWriteFailed := false+ projectMissing := false+ for _, planned := range plan.Projects {+ project, ok := byName[strings.TrimSpace(planned.Name)]+ if !ok {+ summaries = append(summaries, setupApplyProjectSummary{Name: planned.Name, Framework: planned.Framework, Status: "missing"})+ projectMissing = true+ continue+ }++ summary := setupApplyProjectSummary{+ ID: project.ID,+ Name: project.Name,+ Framework: project.Framework,+ Status: project.Status,+ DashboardURL: url + "/?projectId=" + project.ID,+ }+ if planned.Deployment != nil {+ summary.DeploymentPlatform = planned.Deployment.Platform+ }+ if planned.EnvFile != "" {+ envPath := planned.EnvFile+ if !filepath.IsAbs(envPath) {+ envPath = filepath.Join(planDir, envPath)+ }+ summary.EnvFile = planned.EnvFile+ summary.EnvVar = planned.EnvVar+ result, err := envfile.Upsert(envPath, planned.EnvVar, setupEnvValue(project, planned.EnvFormat, url))+ if err != nil {+ summary.EnvResult = "error: " + err.Error()+ envWriteFailed = true+ } else {+ summary.EnvResult = string(result)+ }+ }+ summaries = append(summaries, summary)+ }++ if err := renderSetupApplySummary(cmd.OutOrStdout(), mode, summaries, plan.Projects, url); err != nil {+ return err+ }+ if envWriteFailed {+ return newCLIError(exitcode.Generic, "env_write_failed")+ }+ if projectMissing {+ env := output.ErrorEnvelope{+ Code: "setup_project_missing",+ Message: "one or more approved projects could not be loaded",+ Hint: "review the setup in Traceway and rerun the plan to restore the missing project",+ ExitCode: exitcode.Generic,+ }+ _ = output.RenderError(cmd.ErrOrStderr(), mode, env)+ return newCLIError(env.ExitCode, env.Code)+ }+ return nil+}++func waitForSetupDecision(ctx context.Context, errOut io.Writer, mode output.Mode, c *client.Client) ([]client.SetupProject, error) {+ deadline := time.Now().Add(setupApplyWaitTimeout)+ for {+ status, err := c.GetSetupPlan(ctx)+ if err != nil {+ return nil, renderSetupAPIError(errOut, mode, err)+ }+ switch status.Status {+ case "approved":+ return status.Projects, nil+ case "rejected":+ message := "the user rejected the setup plan"+ if status.Reason != "" {+ message += ": " + status.Reason+ }+ env := output.ErrorEnvelope{+ Code: "setup_plan_rejected",+ Message: message,+ Hint: "revise the plan with the user and run setup apply again",+ ExitCode: exitcode.Generic,+ }+ _ = output.RenderError(errOut, mode, env)+ return nil, newCLIError(env.ExitCode, env.Code)+ }++ if time.Now().After(deadline) {+ env := output.ErrorEnvelope{+ Code: "setup_approval_timeout",+ Message: "timed out waiting for the plan to be approved",+ Hint: "run setup apply again once the user is ready; re-submitting replaces the pending draft",+ ExitCode: exitcode.Generic,+ }+ _ = output.RenderError(errOut, mode, env)+ return nil, newCLIError(env.ExitCode, env.Code)+ }++ select {+ case <-ctx.Done():+ return nil, ctx.Err()+ case <-time.After(setupPollInterval):+ }+ }+}++func renderSetupApplySummary(out io.Writer, mode output.Mode, summaries []setupApplyProjectSummary, planned []client.SetupPlanProject, url string) error {+ switch mode {+ case output.ModeJSON:+ return output.RenderJSON(out, map[string]any{"projects": summaries}, output.ParseFieldsFlag(flagFields))+ case output.ModeYAML:+ return output.RenderYAML(out, map[string]any{"projects": summaries}, output.ParseFieldsFlag(flagFields))+ }++ tw := output.NewTabWriter(out)+ fmt.Fprintln(tw, "NAME\tFRAMEWORK\tSTATUS\tENV\tDASHBOARD")+ for _, s := range summaries {+ env := "-"+ if s.EnvFile != "" {+ env = fmt.Sprintf("%s (%s, %s)", s.EnvFile, s.EnvVar, s.EnvResult)+ }+ fmt.Fprintf(tw, "%s\t%s\t%s\t%s\t%s\n", s.Name, s.Framework, s.Status, env, s.DashboardURL)+ }+ if err := tw.Flush(); err != nil {+ return err+ }++ withDeployment := []client.SetupPlanProject{}+ for _, p := range planned {+ if p.Deployment != nil {+ withDeployment = append(withDeployment, p)+ }+ }+ if len(withDeployment) > 0 {+ fmt.Fprintln(out, "\nNext steps (deployment credentials):")+ for _, p := range withDeployment {+ credential := p.EnvVar+ if credential == "" {+ credential = "its Traceway credential"+ }+ fmt.Fprintf(out, " - %s: add %s to %s. The exact command with the secret value is on %s/setup.\n", p.Name, credential, p.Deployment.Platform, url)+ }+ }+ return nil+}diff --git a/cli/cmd/traceway/setup_apply_test.go b/cli/cmd/traceway/setup_apply_test.gonew file mode 100644index 00000000..2f314d8e--- /dev/null+++ b/cli/cmd/traceway/setup_apply_test.go@@ -0,0 +1,398 @@+package main++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++const testSetupToken = "tws_test-setup-token"++func newSetupTestServer(t *testing.T, approveAfterPolls int32) *httptest.Server {+ t.Helper()+ var polls int32+ var submitted atomic.Bool++ backendToken := "tok_backend-secret"+ webToken := "tok_web-secret"++ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if got := r.Header.Get("Authorization"); got != "Bearer "+testSetupToken {+ w.WriteHeader(http.StatusUnauthorized)+ return+ }+ switch r.Method + " " + r.URL.Path {+ case "GET /api/setup/session":+ _ = json.NewEncoder(w).Encode(map[string]any{+ "organizationId": 1, "organizationName": "Acme", "email": "[email protected]",+ "backendUrl": "https://traceway.example.com", "projects": []any{},+ })+ case "PUT /api/setup/plan":+ submitted.Store(true)+ _ = json.NewEncoder(w).Encode(map[string]any{"status": "pending"})+ case "GET /api/setup/plan":+ if !submitted.Load() {+ _ = json.NewEncoder(w).Encode(map[string]any{"status": "none"})+ return+ }+ if atomic.AddInt32(&polls, 1) <= approveAfterPolls {+ _ = json.NewEncoder(w).Encode(map[string]any{"status": "pending"})+ return+ }+ _ = json.NewEncoder(w).Encode(map[string]any{+ "status": "approved",+ "projects": []map[string]any{+ {"id": "p-backend", "name": "Product Backend", "framework": "opentelemetry",+ "token": backendToken, "backendUrl": "https://traceway.example.com", "status": "created"},+ {"id": "p-web", "name": "Product Web", "framework": "svelte",+ "token": webToken, "backendUrl": "https://traceway.example.com", "status": "created"},+ },+ })+ default:+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)+ w.WriteHeader(http.StatusNotFound)+ }+ }))+}++func writeSetupPlanFile(t *testing.T, dir, url string) string {+ t.Helper()+ plan := map[string]any{+ "url": url,+ "projects": []map[string]any{+ {"name": "Product Backend", "framework": "opentelemetry",+ "envFile": "backend/.env", "envVar": "TRACEWAY_BACKEND_TOKEN"},+ {"name": "Product Web", "framework": "svelte",+ "envFile": "web/.env", "envVar": "PUBLIC_TRACEWAY_CONNECTION_STRING", "envFormat": "connectionString",+ "deployment": map[string]any{"platform": "Vercel", "instructions": "vercel env add PUBLIC_TRACEWAY_CONNECTION_STRING <token>"}},+ },+ }+ data, err := json.Marshal(plan)+ if err != nil {+ t.Fatalf("marshal plan: %v", err)+ }+ path := filepath.Join(dir, "plan.json")+ if err := os.WriteFile(path, data, 0o644); err != nil {+ t.Fatalf("write plan: %v", err)+ }+ for _, sub := range []string{"backend", "web"} {+ if err := os.Mkdir(filepath.Join(dir, sub), 0o755); err != nil {+ t.Fatalf("mkdir %s: %v", sub, err)+ }+ }+ return path+}++func setupTestEnvIsolation(t *testing.T) {+ t.Helper()+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())+ t.Setenv("XDG_STATE_HOME", t.TempDir())+ t.Setenv("TRACEWAY_SETUP_TOKEN", "")++ prevInterval := setupPollInterval+ setupPollInterval = 5 * time.Millisecond+ t.Cleanup(func() { setupPollInterval = prevInterval })+}++func TestSetupApplyHappyPath(t *testing.T) {+ setupTestEnvIsolation(t)+ server := newSetupTestServer(t, 2)+ defer server.Close()++ dir := t.TempDir()+ planPath := writeSetupPlanFile(t, dir, server.URL)++ stdout, stderr, err := runCmd(t, testSetupToken+"\n", "setup", "apply", "--plan", planPath, "--token-stdin", "--output", "table")+ if err != nil {+ t.Fatalf("setup apply failed: %v\nstderr: %s", err, stderr.String())+ }++ combined := stdout.String() + stderr.String()+ if strings.Contains(combined, "tok_backend-secret") || strings.Contains(combined, "tok_web-secret") {+ t.Fatal("token values leaked into output")+ }+ if !strings.Contains(stdout.String(), "Product Backend") || !strings.Contains(stdout.String(), "created") {+ t.Errorf("summary missing rows: %s", stdout.String())+ }+ if !strings.Contains(stdout.String(), "Next steps") || !strings.Contains(stdout.String(), "Vercel") {+ t.Errorf("summary missing next steps: %s", stdout.String())+ }+ if !strings.Contains(stderr.String(), "review and approve") {+ t.Errorf("stderr missing approval prompt: %s", stderr.String())+ }++ backendEnv, err := os.ReadFile(filepath.Join(dir, "backend", ".env"))+ if err != nil {+ t.Fatalf("read backend env: %v", err)+ }+ if string(backendEnv) != "TRACEWAY_BACKEND_TOKEN=tok_backend-secret\n" {+ t.Errorf("backend env = %q", backendEnv)+ }+ info, err := os.Stat(filepath.Join(dir, "backend", ".env"))+ if err != nil {+ t.Fatalf("stat backend env: %v", err)+ }+ if info.Mode().Perm() != 0o600 {+ t.Errorf("backend env mode = %v, want 0600", info.Mode().Perm())+ }++ webEnv, err := os.ReadFile(filepath.Join(dir, "web", ".env"))+ if err != nil {+ t.Fatalf("read web env: %v", err)+ }+ want := "PUBLIC_TRACEWAY_CONNECTION_STRING=tok_web-secret@https://traceway.example.com/api/report\n"+ if string(webEnv) != want {+ t.Errorf("web env = %q, want %q", webEnv, want)+ }++ stateDir := os.Getenv("XDG_STATE_HOME")+ if entries, err := os.ReadDir(stateDir); err == nil && len(entries) != 0 {+ t.Errorf("state dir should stay empty, has %v", entries)+ }+}++func TestSetupApplyTokenFromEnv(t *testing.T) {+ setupTestEnvIsolation(t)+ server := newSetupTestServer(t, 0)+ defer server.Close()++ dir := t.TempDir()+ planPath := writeSetupPlanFile(t, dir, server.URL)+ t.Setenv("TRACEWAY_SETUP_TOKEN", testSetupToken)++ _, stderr, err := runCmd(t, "", "setup", "apply", "--plan", planPath)+ if err != nil {+ t.Fatalf("setup apply failed: %v\nstderr: %s", err, stderr.String())+ }+}++func TestSetupApplyURLFlagOverridesPlan(t *testing.T) {+ setupTestEnvIsolation(t)+ server := newSetupTestServer(t, 0)+ defer server.Close()++ dir := t.TempDir()+ planPath := writeSetupPlanFile(t, dir, "https://wrong.example.invalid")++ _, stderr, err := runCmd(t, testSetupToken+"\n", "setup", "apply", "--plan", planPath, "--token-stdin", "--url", server.URL)+ if err != nil {+ t.Fatalf("setup apply failed: %v\nstderr: %s", err, stderr.String())+ }+}++func TestSetupApplyRejection(t *testing.T) {+ setupTestEnvIsolation(t)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.Method + " " + r.URL.Path {+ case "GET /api/setup/session":+ _ = json.NewEncoder(w).Encode(map[string]any{"organizationId": 1, "organizationName": "Acme", "email": "[email protected]", "backendUrl": "x", "projects": []any{}})+ case "PUT /api/setup/plan":+ _ = json.NewEncoder(w).Encode(map[string]any{"status": "pending"})+ case "GET /api/setup/plan":+ _ = json.NewEncoder(w).Encode(map[string]any{"status": "rejected", "reason": "wrong project split"})+ }+ }))+ defer server.Close()++ dir := t.TempDir()+ planPath := writeSetupPlanFile(t, dir, server.URL)++ _, stderr, err := runCmd(t, testSetupToken+"\n", "setup", "apply", "--plan", planPath, "--token-stdin")+ if err == nil {+ t.Fatal("expected rejection error")+ }+ var cliErr *cliError+ if !asCLIError(err, &cliErr) || cliErr.code != 1 {+ t.Fatalf("error = %v, want cliError with exit 1", err)+ }+ if !strings.Contains(stderr.String(), "wrong project split") {+ t.Errorf("stderr should carry the rejection reason: %s", stderr.String())+ }+}++func TestSetupApplyInvalidToken(t *testing.T) {+ setupTestEnvIsolation(t)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusUnauthorized)+ }))+ defer server.Close()++ dir := t.TempDir()+ planPath := writeSetupPlanFile(t, dir, server.URL)++ _, stderr, err := runCmd(t, "tws_expired\n", "setup", "apply", "--plan", planPath, "--token-stdin")+ if err == nil {+ t.Fatal("expected auth error")+ }+ var cliErr *cliError+ if !asCLIError(err, &cliErr) || cliErr.code != 4 {+ t.Fatalf("error = %v, want cliError with exit 4", err)+ }+ if !strings.Contains(stderr.String(), "invalid_setup_token") && !strings.Contains(stderr.String(), "invalid or expired") {+ t.Errorf("stderr = %s", stderr.String())+ }+}++func TestSetupApplyApprovalTimeout(t *testing.T) {+ setupTestEnvIsolation(t)+ server := newSetupTestServer(t, 1<<30)+ defer server.Close()++ dir := t.TempDir()+ planPath := writeSetupPlanFile(t, dir, server.URL)++ _, stderr, err := runCmd(t, testSetupToken+"\n", "setup", "apply", "--plan", planPath, "--token-stdin", "--wait-timeout", "30ms")+ if err == nil {+ t.Fatal("expected timeout error")+ }+ if !strings.Contains(stderr.String(), "setup_approval_timeout") && !strings.Contains(stderr.String(), "timed out") {+ t.Errorf("stderr = %s", stderr.String())+ }+}++func TestSetupApplyFailsWhenApprovedProjectIsMissing(t *testing.T) {+ setupTestEnvIsolation(t)+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch r.Method + " " + r.URL.Path {+ case "GET /api/setup/session":+ _ = json.NewEncoder(w).Encode(map[string]any{"organizationId": 1, "organizationName": "Acme", "email": "[email protected]", "backendUrl": "x", "projects": []any{}})+ case "PUT /api/setup/plan":+ _ = json.NewEncoder(w).Encode(map[string]any{"status": "pending"})+ case "GET /api/setup/plan":+ _ = json.NewEncoder(w).Encode(map[string]any{+ "status": "approved",+ "projects": []map[string]any{{+ "id": "p-backend", "name": "Product Backend", "framework": "opentelemetry",+ "token": "tok_backend-secret", "backendUrl": "https://traceway.example.com", "status": "created",+ }},+ })+ }+ }))+ defer server.Close()++ dir := t.TempDir()+ planPath := writeSetupPlanFile(t, dir, server.URL)++ stdout, stderr, err := runCmd(t, testSetupToken+"\n", "setup", "apply", "--plan", planPath, "--token-stdin")+ if err == nil {+ t.Fatal("expected missing project error")+ }+ if !strings.Contains(stdout.String(), "missing") || !strings.Contains(stderr.String(), "setup_project_missing") {+ t.Fatalf("missing project result not reported: stdout=%s stderr=%s", stdout.String(), stderr.String())+ }+ if _, statErr := os.Stat(filepath.Join(dir, "web", ".env")); !os.IsNotExist(statErr) {+ t.Fatalf("missing project's env file should not be written, stat err = %v", statErr)+ }+}++func TestSetupApplyUsageErrors(t *testing.T) {+ setupTestEnvIsolation(t)+ dir := t.TempDir()+ planPath := writeSetupPlanFile(t, dir, "https://x.example")++ badPlanPath := filepath.Join(dir, "bad-plan.json")+ if err := os.WriteFile(badPlanPath, []byte(`{"projects":[{"name":"A","framework":"react","envFile":"x/.env"}]}`), 0o644); err != nil {+ t.Fatalf("write bad plan: %v", err)+ }++ cases := map[string][]string{+ "no plan": {"setup", "apply", "--token", testSetupToken},+ "no token": {"setup", "apply", "--plan", planPath},+ "both token flags": {"setup", "apply", "--plan", planPath, "--token", "x", "--token-stdin"},+ "envFile without envVar": {"setup", "apply", "--plan", badPlanPath, "--token", testSetupToken},+ "missing plan file": {"setup", "apply", "--plan", filepath.Join(dir, "nope.json"), "--token", testSetupToken},+ }+ for name, args := range cases {+ t.Run(name, func(t *testing.T) {+ _, _, err := runCmd(t, "", args...)+ var cliErr *cliError+ if !asCLIError(err, &cliErr) || cliErr.code != 2 {+ t.Errorf("error = %v, want usage error (exit 2)", err)+ }+ })+ }+}++func TestSetupApplyIdempotentRerun(t *testing.T) {+ setupTestEnvIsolation(t)+ server := newSetupTestServer(t, 0)+ defer server.Close()++ dir := t.TempDir()+ planPath := writeSetupPlanFile(t, dir, server.URL)++ if _, stderr, err := runCmd(t, testSetupToken+"\n", "setup", "apply", "--plan", planPath, "--token-stdin"); err != nil {+ t.Fatalf("first apply failed: %v\nstderr: %s", err, stderr.String())+ }+ before, err := os.Stat(filepath.Join(dir, "backend", ".env"))+ if err != nil {+ t.Fatalf("stat: %v", err)+ }++ stdout, stderr, err := runCmd(t, testSetupToken+"\n", "setup", "apply", "--plan", planPath, "--token-stdin")+ if err != nil {+ t.Fatalf("second apply failed: %v\nstderr: %s", err, stderr.String())+ }+ if !strings.Contains(stdout.String(), "unchanged") {+ t.Errorf("second apply should report unchanged env files: %s", stdout.String())+ }+ after, err := os.Stat(filepath.Join(dir, "backend", ".env"))+ if err != nil {+ t.Fatalf("stat: %v", err)+ }+ if !after.ModTime().Equal(before.ModTime()) {+ t.Error("unchanged env file must not be rewritten")+ }+}++func TestSetupApplyJSONOutputExcludesTokens(t *testing.T) {+ setupTestEnvIsolation(t)+ server := newSetupTestServer(t, 0)+ defer server.Close()++ dir := t.TempDir()+ planPath := writeSetupPlanFile(t, dir, server.URL)++ stdout, stderr, err := runCmd(t, testSetupToken+"\n", "setup", "apply", "--plan", planPath, "--token-stdin", "--output", "json")+ if err != nil {+ t.Fatalf("setup apply failed: %v\nstderr: %s", err, stderr.String())+ }+ if strings.Contains(stdout.String(), "tok_backend-secret") || strings.Contains(stdout.String(), "tok_web-secret") {+ t.Fatal("json output leaked token values")+ }+ var payload struct {+ Projects []map[string]any `json:"projects"`+ }+ if err := json.Unmarshal(stdout.Bytes(), &payload); err != nil {+ t.Fatalf("stdout is not valid json: %v\n%s", err, stdout.String())+ }+ if len(payload.Projects) != 2 {+ t.Fatalf("projects = %v", payload.Projects)+ }+ for _, p := range payload.Projects {+ if _, exists := p["token"]; exists {+ t.Error("json output must not have a token field")+ }+ }+}++func asCLIError(err error, target **cliError) bool {+ for err != nil {+ if ce, ok := err.(*cliError); ok {+ *target = ce+ return true+ }+ unwrapper, ok := err.(interface{ Unwrap() error })+ if !ok {+ return false+ }+ err = unwrapper.Unwrap()+ }+ return false+}diff --git a/cli/internal/envfile/envfile.go b/cli/internal/envfile/envfile.gonew file mode 100644index 00000000..48edc5da--- /dev/null+++ b/cli/internal/envfile/envfile.go@@ -0,0 +1,119 @@+package envfile++import (+ "errors"+ "fmt"+ "io/fs"+ "os"+ "path/filepath"+ "regexp"+ "strings"+)++type Result string++const (+ ResultCreated Result = "created"+ ResultAdded Result = "added"+ ResultUpdated Result = "updated"+ ResultUnchanged Result = "unchanged"+)++func Upsert(path, key, value string) (Result, error) {+ content, mode, existed, err := readEnvFile(path)+ if err != nil {+ return "", err+ }++ eol := "\n"+ if strings.Contains(content, "\r\n") {+ eol = "\r\n"+ }++ assignRe, err := regexp.Compile(`^(\s*(?:export\s+)?)` + regexp.QuoteMeta(key) + `\s*=`)+ if err != nil {+ return "", err+ }++ lines := strings.Split(content, "\n")+ replaced := false+ for i, line := range lines {+ trimmed := strings.TrimSuffix(line, "\r")+ match := assignRe.FindStringSubmatch(trimmed)+ if match == nil {+ continue+ }+ suffix := ""+ if strings.HasSuffix(line, "\r") {+ suffix = "\r"+ }+ lines[i] = match[1] + key + "=" + value + suffix+ replaced = true+ }++ var updated string+ result := ResultUpdated+ if replaced {+ updated = strings.Join(lines, "\n")+ } else {+ updated = content+ if updated != "" && !strings.HasSuffix(updated, "\n") {+ updated += eol+ }+ updated += key + "=" + value + eol+ result = ResultAdded+ if !existed {+ result = ResultCreated+ }+ }++ if existed && updated == content {+ return ResultUnchanged, nil+ }++ if err := writeAtomic(path, updated, mode); err != nil {+ return "", err+ }+ return result, nil+}++func readEnvFile(path string) (content string, mode fs.FileMode, existed bool, err error) {+ data, err := os.ReadFile(path)+ if errors.Is(err, fs.ErrNotExist) {+ return "", 0o600, false, nil+ }+ if err != nil {+ return "", 0, false, fmt.Errorf("reading %s: %w", path, err)+ }+ info, err := os.Stat(path)+ if err != nil {+ return "", 0, false, fmt.Errorf("reading %s: %w", path, err)+ }+ return string(data), info.Mode().Perm(), true, nil+}++func writeAtomic(path, content string, mode fs.FileMode) error {+ dir := filepath.Dir(path)+ tmp, err := os.CreateTemp(dir, ".tmp-env-*")+ if err != nil {+ return fmt.Errorf("writing %s: %w", path, err)+ }+ tmpName := tmp.Name()+ defer os.Remove(tmpName)++ if _, err := tmp.WriteString(content); err != nil {+ tmp.Close()+ return fmt.Errorf("writing %s: %w", path, err)+ }+ if err := tmp.Chmod(mode); err != nil {+ tmp.Close()+ return fmt.Errorf("writing %s: %w", path, err)+ }+ if err := tmp.Close(); err != nil {+ return fmt.Errorf("writing %s: %w", path, err)+ }+ if err := os.Rename(tmpName, path); err != nil {+ return fmt.Errorf("writing %s: %w", path, err)+ }+ return nil+}diff --git a/cli/internal/envfile/envfile_test.go b/cli/internal/envfile/envfile_test.gonew file mode 100644index 00000000..10bcf354--- /dev/null+++ b/cli/internal/envfile/envfile_test.go@@ -0,0 +1,164 @@+package envfile++import (+ "os"+ "path/filepath"+ "strings"+ "testing"+)++func write(t *testing.T, path, content string, mode os.FileMode) {+ t.Helper()+ if err := os.WriteFile(path, []byte(content), mode); err != nil {+ t.Fatalf("write %s: %v", path, err)+ }+}++func read(t *testing.T, path string) string {+ t.Helper()+ data, err := os.ReadFile(path)+ if err != nil {+ t.Fatalf("read %s: %v", path, err)+ }+ return string(data)+}++func TestUpsertCreatesFileWith0600(t *testing.T) {+ path := filepath.Join(t.TempDir(), ".env")++ result, err := Upsert(path, "TRACEWAY_TOKEN", "secret-value")+ if err != nil {+ t.Fatalf("upsert: %v", err)+ }+ if result != ResultCreated {+ t.Errorf("result = %s, want created", result)+ }+ if got := read(t, path); got != "TRACEWAY_TOKEN=secret-value\n" {+ t.Errorf("content = %q", got)+ }+ info, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat: %v", err)+ }+ if info.Mode().Perm() != 0o600 {+ t.Errorf("mode = %v, want 0600", info.Mode().Perm())+ }+}++func TestUpsertAppendsWithoutTrailingNewline(t *testing.T) {+ path := filepath.Join(t.TempDir(), ".env")+ write(t, path, "OTHER=1", 0o644)++ result, err := Upsert(path, "TRACEWAY_TOKEN", "v")+ if err != nil {+ t.Fatalf("upsert: %v", err)+ }+ if result != ResultAdded {+ t.Errorf("result = %s, want added", result)+ }+ if got := read(t, path); got != "OTHER=1\nTRACEWAY_TOKEN=v\n" {+ t.Errorf("content = %q", got)+ }+}++func TestUpsertReplacesAllUncommentedAssignments(t *testing.T) {+ path := filepath.Join(t.TempDir(), ".env")+ write(t, path, strings.Join([]string{+ "# TRACEWAY_TOKEN=commented-out",+ " # TRACEWAY_TOKEN=also-commented",+ "TRACEWAY_TOKEN=old-1",+ " export TRACEWAY_TOKEN=old-2",+ "TRACEWAY_TOKEN_SUFFIXED=untouched",+ "OTHER=1",+ }, "\n")+"\n", 0o644)++ result, err := Upsert(path, "TRACEWAY_TOKEN", "new")+ if err != nil {+ t.Fatalf("upsert: %v", err)+ }+ if result != ResultUpdated {+ t.Errorf("result = %s, want updated", result)+ }+ want := strings.Join([]string{+ "# TRACEWAY_TOKEN=commented-out",+ " # TRACEWAY_TOKEN=also-commented",+ "TRACEWAY_TOKEN=new",+ " export TRACEWAY_TOKEN=new",+ "TRACEWAY_TOKEN_SUFFIXED=untouched",+ "OTHER=1",+ }, "\n") + "\n"+ if got := read(t, path); got != want {+ t.Errorf("content = %q, want %q", got, want)+ }+}++func TestUpsertUnchangedDoesNotRewrite(t *testing.T) {+ path := filepath.Join(t.TempDir(), ".env")+ write(t, path, "TRACEWAY_TOKEN=same\n", 0o644)++ before, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat: %v", err)+ }++ result, err := Upsert(path, "TRACEWAY_TOKEN", "same")+ if err != nil {+ t.Fatalf("upsert: %v", err)+ }+ if result != ResultUnchanged {+ t.Errorf("result = %s, want unchanged", result)+ }+ after, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat: %v", err)+ }+ if !after.ModTime().Equal(before.ModTime()) {+ t.Error("unchanged upsert must not rewrite the file")+ }+}++func TestUpsertPreservesModeAndCRLF(t *testing.T) {+ path := filepath.Join(t.TempDir(), ".env")+ write(t, path, "A=1\r\nTRACEWAY_TOKEN=old\r\n", 0o640)++ if _, err := Upsert(path, "TRACEWAY_TOKEN", "new"); err != nil {+ t.Fatalf("upsert: %v", err)+ }+ if got := read(t, path); got != "A=1\r\nTRACEWAY_TOKEN=new\r\n" {+ t.Errorf("content = %q", got)+ }++ if _, err := Upsert(path, "B", "2"); err != nil {+ t.Fatalf("append upsert: %v", err)+ }+ if got := read(t, path); got != "A=1\r\nTRACEWAY_TOKEN=new\r\nB=2\r\n" {+ t.Errorf("content = %q", got)+ }++ info, err := os.Stat(path)+ if err != nil {+ t.Fatalf("stat: %v", err)+ }+ if info.Mode().Perm() != 0o640 {+ t.Errorf("mode = %v, want 0640 preserved", info.Mode().Perm())+ }+}++func TestUpsertConnectionStringValueRoundTrips(t *testing.T) {+ path := filepath.Join(t.TempDir(), ".env")+ value := "tok_abc@https://traceway.example.com/api/report"++ if _, err := Upsert(path, "PUBLIC_TRACEWAY", value); err != nil {+ t.Fatalf("upsert: %v", err)+ }+ if got := read(t, path); got != "PUBLIC_TRACEWAY="+value+"\n" {+ t.Errorf("content = %q", got)+ }+}++func TestUpsertMissingParentDirErrors(t *testing.T) {+ path := filepath.Join(t.TempDir(), "missing", ".env")+ if _, err := Upsert(path, "KEY", "v"); err == nil {+ t.Fatal("expected an error for a missing parent directory")+ }+}diff --git a/cli/pkg/client/setup.go b/cli/pkg/client/setup.gonew file mode 100644index 00000000..bfe31658--- /dev/null+++ b/cli/pkg/client/setup.go@@ -0,0 +1,71 @@+package client++import (+ "context"+ "net/http"+)++type SetupSessionProject struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Framework string `json:"framework"`+}++type SetupSession struct {+ OrganizationID int `json:"organizationId"`+ OrganizationName string `json:"organizationName"`+ Email string `json:"email"`+ BackendURL string `json:"backendUrl"`+ Projects []SetupSessionProject `json:"projects"`+}++func (c *Client) GetSetupSession(ctx context.Context) (*SetupSession, error) {+ var session SetupSession+ if err := c.do(ctx, http.MethodGet, "/api/setup/session", nil, &session); err != nil {+ return nil, err+ }+ return &session, nil+}++type SetupPlanDeployment struct {+ Platform string `json:"platform"`+ Instructions string `json:"instructions"`+}++type SetupPlanProject struct {+ Name string `json:"name"`+ Framework string `json:"framework"`+ EnvFile string `json:"envFile,omitempty"`+ EnvVar string `json:"envVar,omitempty"`+ EnvFormat string `json:"envFormat,omitempty"`+ Deployment *SetupPlanDeployment `json:"deployment,omitempty"`+}++func (c *Client) SubmitSetupPlan(ctx context.Context, projects []SetupPlanProject) error {+ body := map[string]any{"projects": projects}+ return c.do(ctx, http.MethodPut, "/api/setup/plan", body, nil)+}++type SetupProject struct {+ ID string `json:"id"`+ Name string `json:"name"`+ Framework string `json:"framework"`+ Token string `json:"token"`+ SourceMapToken string `json:"sourceMapToken"`+ BackendURL string `json:"backendUrl"`+ Status string `json:"status"`+}++type SetupPlanStatus struct {+ Status string `json:"status"`+ Reason string `json:"reason,omitempty"`+ Projects []SetupProject `json:"projects,omitempty"`+}++func (c *Client) GetSetupPlan(ctx context.Context) (*SetupPlanStatus, error) {+ var status SetupPlanStatus+ if err := c.do(ctx, http.MethodGet, "/api/setup/plan", nil, &status); err != nil {+ return nil, err+ }+ return &status, nil+}diff --git a/cli/pkg/client/setup_test.go b/cli/pkg/client/setup_test.gonew file mode 100644index 00000000..50b270be--- /dev/null+++ b/cli/pkg/client/setup_test.go@@ -0,0 +1,112 @@+package client++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "testing"+)++func TestGetSetupSession(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodGet || r.URL.Path != "/api/setup/session" {+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)+ }+ if got := r.Header.Get("Authorization"); got != "Bearer tws_test" {+ t.Errorf("Authorization = %q", got)+ }+ _ = json.NewEncoder(w).Encode(map[string]any{+ "organizationId": 3,+ "organizationName": "Acme",+ "email": "[email protected]",+ "backendUrl": "https://traceway.example.com",+ "projects": []map[string]any{{"id": "p1", "name": "Api", "framework": "opentelemetry"}},+ })+ }))+ defer server.Close()++ session, err := New(server.URL, WithJWT("tws_test")).GetSetupSession(context.Background())+ if err != nil {+ t.Fatalf("GetSetupSession: %v", err)+ }+ if session.OrganizationName != "Acme" || session.Email != "[email protected]" || len(session.Projects) != 1 {+ t.Errorf("session = %+v", session)+ }+}++func TestSubmitSetupPlan(t *testing.T) {+ var received map[string]any+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPut || r.URL.Path != "/api/setup/plan" {+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)+ }+ _ = json.NewDecoder(r.Body).Decode(&received)+ _ = json.NewEncoder(w).Encode(map[string]any{"status": "pending"})+ }))+ defer server.Close()++ err := New(server.URL, WithJWT("tws_test")).SubmitSetupPlan(context.Background(), []SetupPlanProject{+ {Name: "Api", Framework: "opentelemetry", EnvFile: "backend/.env", EnvVar: "TRACEWAY_TOKEN"},+ })+ if err != nil {+ t.Fatalf("SubmitSetupPlan: %v", err)+ }+ projects, ok := received["projects"].([]any)+ if !ok || len(projects) != 1 {+ t.Fatalf("request body = %v", received)+ }+ first := projects[0].(map[string]any)+ if first["name"] != "Api" || first["envVar"] != "TRACEWAY_TOKEN" {+ t.Errorf("projects[0] = %v", first)+ }+ if _, exists := first["deployment"]; exists {+ t.Error("empty deployment must be omitted from the wire body")+ }+}++func TestGetSetupPlanStatuses(t *testing.T) {+ responses := map[string]string{+ "pending": `{"status":"pending"}`,+ "rejected": `{"status":"rejected","reason":"nope"}`,+ "approved": `{"status":"approved","projects":[{"id":"p1","name":"Api","framework":"opentelemetry","token":"tok_secret","backendUrl":"https://x.example","status":"created"}]}`,+ }+ for name, body := range responses {+ t.Run(name, func(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ _, _ = w.Write([]byte(body))+ }))+ defer server.Close()++ status, err := New(server.URL, WithJWT("tws_test")).GetSetupPlan(context.Background())+ if err != nil {+ t.Fatalf("GetSetupPlan: %v", err)+ }+ if status.Status != name {+ t.Errorf("status = %q, want %q", status.Status, name)+ }+ if name == "rejected" && status.Reason != "nope" {+ t.Errorf("reason = %q", status.Reason)+ }+ if name == "approved" && (len(status.Projects) != 1 || status.Projects[0].Token != "tok_secret") {+ t.Errorf("projects = %+v", status.Projects)+ }+ })+ }+}++func TestSetupEndpointsMapUnauthorized(t *testing.T) {+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusUnauthorized)+ }))+ defer server.Close()++ c := New(server.URL, WithJWT("tws_expired"))+ if _, err := c.GetSetupSession(context.Background()); !errors.Is(err, ErrUnauthorized) {+ t.Errorf("GetSetupSession error = %v, want ErrUnauthorized", err)+ }+ if _, err := c.GetSetupPlan(context.Background()); !errors.Is(err, ErrUnauthorized) {+ t.Errorf("GetSetupPlan error = %v, want ErrUnauthorized", err)+ }+}diff --git a/docs/pages/client/otel/nextjs/index.mdx b/docs/pages/client/otel/nextjs/index.mdxindex 0419eff0..5c45d1d6 100644--- a/docs/pages/client/otel/nextjs/index.mdx+++ b/docs/pages/client/otel/nextjs/index.mdx@@ -5,7 +5,7 @@ Traceway instruments Next.js on two sides:- **Frontend (Browser)**: uncaught errors, render errors, and session recording via [`@tracewayapp/react`](https://www.npmjs.com/package/@tracewayapp/react).- **Backend (Server)**: request traces, database spans, and server-side exceptions via OpenTelemetry.-The two work side by side on the same project. Most apps will want both.+The two work side by side under separate Traceway projects. Use an **OpenTelemetry** project for the server and a **React** project for the browser; swapping those tokens causes backend endpoint, task, and span data to be discarded.---@@ -27,7 +27,7 @@ import { TracewayProvider } from "@tracewayapp/react";export function TracewayClientProvider({ children }: { children: React.ReactNode }) {return (- <TracewayProvider connectionString="your-token@https://traceway.example.com/api/report">+ <TracewayProvider connectionString={process.env.NEXT_PUBLIC_TRACEWAY_WEB_CONNECTION_STRING!}>{children}</TracewayProvider>);@@ -49,7 +49,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })}```-**Backend.** Install the OTel Node SDK and add a single `instrumentation.ts`. This installs all three signals at once: traces, metrics, and logs.+**Backend.** Install the OTel Node SDK and add `instrumentation.ts` plus a Node-only sibling. This installs all three signals at once: traces, metrics, and logs without pulling Node built-ins into Next.js's Edge compilation.```bashnpm install @opentelemetry/sdk-node \@@ -64,52 +64,60 @@ npm install @opentelemetry/sdk-node \@opentelemetry/api-logs```+Create `instrumentation.ts` at the project root:+```typescript-// instrumentation.ts (project root)export async function register() {- if (process.env.NEXT_RUNTIME !== "nodejs") return;-- const { NodeSDK } = await import("@opentelemetry/sdk-node");- const { OTLPTraceExporter } = await import("@opentelemetry/exporter-trace-otlp-http");- const { OTLPMetricExporter } = await import("@opentelemetry/exporter-metrics-otlp-http");- const { OTLPLogExporter } = await import("@opentelemetry/exporter-logs-otlp-http");- const { PeriodicExportingMetricReader } = await import("@opentelemetry/sdk-metrics");- const { BatchLogRecordProcessor } = await import("@opentelemetry/sdk-logs");- const { getNodeAutoInstrumentations } = await import("@opentelemetry/auto-instrumentations-node");- const { resourceFromAttributes } = await import("@opentelemetry/resources");-- const base = "https://your-traceway-instance.com/api/otel";- const headers = { Authorization: "Bearer your-project-token" };-- new NodeSDK({- resource: resourceFromAttributes({- "service.name": "my-nextjs-app",- "service.version": "1.0.0",- }),- traceExporter: new OTLPTraceExporter({ url: `${base}/v1/traces`, headers }),- metricReaders: [- new PeriodicExportingMetricReader({- exporter: new OTLPMetricExporter({ url: `${base}/v1/metrics`, headers }),- exportIntervalMillis: 30_000,- }),- ],- logRecordProcessors: [- new BatchLogRecordProcessor({- exporter: new OTLPLogExporter({ url: `${base}/v1/logs`, headers }),- }),- ],- instrumentations: [getNodeAutoInstrumentations()],- }).start();+ if (process.env.NEXT_RUNTIME === "nodejs") {+ await import("./instrumentation.node");+ }}```-Three details in that file are easy to get wrong:+Create `instrumentation.node.ts` alongside it:++```typescript+import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";+import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";+import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";+import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";+import { resourceFromAttributes } from "@opentelemetry/resources";+import { BatchLogRecordProcessor } from "@opentelemetry/sdk-logs";+import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";+import { NodeSDK } from "@opentelemetry/sdk-node";++const instance = process.env.TRACEWAY_URL!.replace(/\/+$/, "");+const base = `${instance}/api/otel`;+const headers = { Authorization: `Bearer ${process.env.TRACEWAY_BACKEND_TOKEN}` };++new NodeSDK({+ resource: resourceFromAttributes({+ "service.name": "my-nextjs-app",+ "service.version": "1.0.0",+ }),+ traceExporter: new OTLPTraceExporter({ url: `${base}/v1/traces`, headers }),+ metricReaders: [+ new PeriodicExportingMetricReader({+ exporter: new OTLPMetricExporter({ url: `${base}/v1/metrics`, headers }),+ exportIntervalMillis: 30_000,+ }),+ ],+ logRecordProcessors: [+ new BatchLogRecordProcessor({+ exporter: new OTLPLogExporter({ url: `${base}/v1/logs`, headers }),+ }),+ ],+ instrumentations: [getNodeAutoInstrumentations()],+}).start();+```++Three details in the Node-only file are easy to get wrong:- `resourceFromAttributes({ ... })` is the current API. `@opentelemetry/resources` 2.x removed the `Resource` class, so `new Resource({ ... })` throws `TypeError: Resource is not a constructor` and takes the Next.js dev server down with it.- `new BatchLogRecordProcessor({ exporter })` takes an options object. Passing the exporter directly (`new BatchLogRecordProcessor(exporter)`) fails to compile in TypeScript with `error TS2345`. In plain JavaScript it starts and then ships zero logs.- `metricReaders` and `logRecordProcessors` are arrays. The older singular `metricReader` and `logRecordProcessor` fields still work but are deprecated.-The `process.env.NEXT_RUNTIME !== "nodejs"` guard is required. Next.js runs `instrumentation.ts` in both the Node.js and Edge runtimes, and the OTel Node SDK only works in Node.js. The dynamic `import()` calls keep OTel out of the Edge bundle.+The separate `instrumentation.node.ts` boundary is required. Next.js compiles `instrumentation.ts` for both Node.js and Edge, and the OTel Node SDK only works in Node.js. Putting its imports directly in the hook—even dynamic imports after a runtime guard—can make development builds resolve modules such as `stream`, `fs`, and `worker_threads` for Edge and fail. The wrapper above conditionally imports one Node-only module, matching Next.js's recommended NodeSDK pattern.> Next.js < 15: also set `experimental.instrumentationHook: true` in `next.config.js`. Not needed for 15+.@@ -132,7 +140,7 @@ import { TracewayProvider } from "@tracewayapp/react";export default function App({ Component, pageProps }: AppProps) {return (- <TracewayProvider connectionString="your-token@https://traceway.example.com/api/report">+ <TracewayProvider connectionString={process.env.NEXT_PUBLIC_TRACEWAY_WEB_CONNECTION_STRING!}><Component {...pageProps} /></TracewayProvider>);@@ -151,7 +159,7 @@ Defaults match the rest of the JS SDK family (no flags needed):| `captureNetwork` | `true` | `fetch` and XHR calls recorded as network actions || `captureNavigation` | `true` | History API push/replace/pop recorded as navigation actions |-The `connectionString` uses the standard `{token}@{apiUrl}` format from your Traceway project page.+The `connectionString` uses the standard `{token}@{apiUrl}` value from the React browser project. Do not use the OpenTelemetry server project's token here.`TracewayProvider` also acts as a React error boundary. Render-time exceptions are captured and re-thrown so your app behaves exactly as without Traceway. No separate `<TracewayErrorBoundary>` is required.@@ -197,6 +205,42 @@ export function TestErrorButton() {The error should appear in your Traceway dashboard under **Issues** within a few seconds, with the session recording attached.+### Browser source maps and debug IDs++Install the debug-ID plugin and source-map uploader, then use Next's webpack build. The plugin currently supports webpack, not Turbopack; Next.js 16 defaults to Turbopack, so a normal `next build` would silently skip this integration.++```bash+npm install -D @tracewayapp/bundler-plugin @tracewayapp/sourcemap-upload+```++In `next.config.ts`:++```typescript+import type { NextConfig } from "next";+import { TracewayDebugIdsWebpackPlugin } from "@tracewayapp/bundler-plugin/webpack";++const nextConfig: NextConfig = {+ productionBrowserSourceMaps: true,+ webpack(config, { isServer, dev }) {+ if (!isServer && !dev) {+ config.devtool = "source-map";+ config.plugins.push(new TracewayDebugIdsWebpackPlugin());+ }+ return config;+ },+};++export default nextConfig;+```++The `!dev` guard keeps the production-only plugin from replacing Next.js's development source-map mode. Use `next build --webpack`, then verify the emitted client bundles contain `//# debugId=` and their `.js.map` files contain a `debugId` field. Upload the browser artifacts with the **React project's** upload token:++```bash+TRACEWAY_URL=https://traceway.example.com \+TRACEWAY_SOURCEMAP_TOKEN=... \+npx @tracewayapp/sourcemap-upload --directory .next/static/chunks+```+---## Backend (Server)@@ -295,7 +339,7 @@ export async function POST() {### Logs-Logs are a separate OTLP pipeline. The Quick Start `instrumentation.ts` already configures it. Create one shared module for the logger:+Logs are a separate OTLP pipeline. The Quick Start `instrumentation.node.ts` already configures it. Create one shared module for the logger:```typescript// lib/otel.ts@@ -368,7 +412,12 @@ OTel patches CommonJS packages at `require()` time. Next.js bundles server depenimport type { NextConfig } from "next";const nextConfig: NextConfig = {- serverExternalPackages: ["ioredis", "redis", "mysql2"],+ serverExternalPackages: [+ "@opentelemetry/auto-instrumentations-node",+ "ioredis",+ "redis",+ "mysql2",+ ],};export default nextConfig;@@ -389,7 +438,7 @@ NODE_OPTIONS='--require ./otel.js' next startOn Next.js that makes `@opentelemetry/instrumentation-http` create the request root span before Next.js's own tracer runs. That span only knows the literal URL (`url.path: /api/users/42`), never the route pattern, so it wins over Next.js's span and your endpoints fragment into one row per id. Wrapping handlers does not repair it, because a handler can only reach the innermost active span.-Use `instrumentation.ts` with the `register()` hook, as shown in the Quick Start.+Use `instrumentation.ts` with the `register()` hook and its Node-only sibling, as shown in the Quick Start.### What gets captured@@ -597,17 +646,12 @@ Error: Test error from Next.js server.next/server/chunks/[root-of-the-server]__0og452-._.js:1:983```-Next.js installs its own `Error.prepareStackTrace`, which bypasses Node's source map support, so the stack recorded by OTel keeps the bundled frames. Reset it at the top of `register()` to get Node's default formatter back:--```typescript-// instrumentation.ts (project root)-export async function register() {- if (process.env.NEXT_RUNTIME !== "nodejs") return;+Next.js installs its own `Error.prepareStackTrace`, which bypasses Node's source map support, so the stack recorded by OTel keeps the bundled frames. Reset it near the top of the Node-only module to get Node's default formatter back:- (Error as unknown as { prepareStackTrace?: unknown }).prepareStackTrace = undefined;+In `instrumentation.node.ts`:- // ...the rest of the SDK setup-}+```typescript+(Error as unknown as { prepareStackTrace?: unknown }).prepareStackTrace = undefined;```That is enough in development, where Next.js already runs the server with `--enable-source-maps`. Frames then read `app/api/orders/route.ts:12:9`.@@ -652,7 +696,7 @@ export OTEL_EXPORTER_OTLP_ENDPOINT="https://your-traceway-instance.com/api/otel"export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-project-token"```-With these set, your `instrumentation.ts` can omit the exporter URLs, the headers, and the `resource` block. The SDK picks all of them up automatically.+With these set, your `instrumentation.node.ts` can omit the exporter URLs, the headers, and the `resource` block. The SDK picks all of them up automatically.---diff --git a/frontend/src/app.d.ts b/frontend/src/app.d.tsindex 7be578df..ec484f2b 100644--- a/frontend/src/app.d.ts+++ b/frontend/src/app.d.ts@@ -28,6 +28,7 @@ declare global {}) => string;remove: (widgetId: string) => void;+ reset: (widgetId: string) => void;};onTurnstileLoad?: () => void;}diff --git a/frontend/src/lib/components/setup/manual-projects-editor.svelte b/frontend/src/lib/components/setup/manual-projects-editor.sveltenew file mode 100644index 00000000..d5fe37a1--- /dev/null+++ b/frontend/src/lib/components/setup/manual-projects-editor.svelte@@ -0,0 +1,125 @@+<script lang="ts">+ import { untrack } from 'svelte';+ import { Plus, X } from '@lucide/svelte';+ import { toast } from 'svelte-sonner';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { Label } from '$lib/components/ui/label';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import {+ projectsState,+ type Framework,+ type ProjectWithToken+ } from '$lib/state/projects.svelte';+ import FrameworkCombobox from '$lib/components/framework-combobox.svelte';++ let {+ organizationId,+ initialFramework = 'opentelemetry',+ onCreated+ }: {+ organizationId: number;+ initialFramework?: Framework;+ onCreated: (projects: ProjectWithToken[]) => void;+ } = $props();++ type Row = { key: number; name: string; framework: Framework };++ let nextKey = 1;+ let rows = $state<Row[]>([+ { key: 0, name: '', framework: untrack(() => initialFramework) }+ ]);+ let loading = $state(false);+ let error = $state('');++ function addRow() {+ rows = [...rows, { key: nextKey++, name: '', framework: 'opentelemetry' }];+ }++ function removeRow(key: number) {+ rows = rows.filter((r) => r.key !== key);+ }++ async function handleSubmit(e: Event) {+ e.preventDefault();+ loading = true;+ error = '';+ try {+ const created = await projectsState.createProjects(+ organizationId,+ rows.map((r) => ({ name: r.name.trim(), framework: r.framework }))+ );+ toast.success('Successfully created the Projects', { position: 'top-center' });+ if (created.length > 0) {+ projectsState.selectProject(created[0].id);+ }+ rows = [{ key: nextKey++, name: '', framework: 'opentelemetry' }];+ onCreated(created);+ } catch (err) {+ error = err instanceof Error ? err.message : 'Failed to create projects';+ } finally {+ loading = false;+ }+ }+</script>++<form onsubmit={handleSubmit} class="rounded-md border bg-card">+ <div class="border-b px-4 py-3">+ <h3 class="font-semibold">Create Projects</h3>+ <p class="mt-1 text-sm text-muted-foreground">+ One project per deployed application: a backend uses OpenTelemetry; each browser or mobile+ app gets its own project.+ </p>+ </div>+ <div class="space-y-4 p-4">+ {#if error}+ <ErrorAlert {error} />+ {/if}++ <div class="hidden gap-3 sm:grid sm:grid-cols-[1fr_1fr_2rem]">+ <Label>Project Name</Label>+ <Label>Framework</Label>+ <span></span>+ </div>+ {#each rows as row (row.key)}+ <div class="grid grid-cols-1 gap-3 sm:grid-cols-[1fr_1fr_2rem] sm:items-center">+ <Input+ type="text"+ placeholder="My Application"+ bind:value={row.name}+ disabled={loading}+ />+ <FrameworkCombobox bind:value={row.framework} disabled={loading} />+ <div class="flex justify-end">+ {#if rows.length > 1}+ <Button+ type="button"+ variant="ghost"+ size="icon"+ onclick={() => removeRow(row.key)}+ disabled={loading}+ title="Remove project"+ >+ <X class="h-4 w-4" />+ </Button>+ {/if}+ </div>+ </div>+ {/each}++ <div class="flex items-center justify-between pt-1">+ <Button type="button" variant="ghost" size="sm" onclick={addRow} disabled={loading}>+ <Plus class="mr-2 h-4 w-4" />+ Add another project+ </Button>+ <Button type="submit" variant="success" disabled={loading}>+ {#if loading}+ Creating...+ {:else}+ <Plus class="mr-2 h-4 w-4" />+ New Projects+ {/if}+ </Button>+ </div>+ </div>+</form>diff --git a/frontend/src/lib/components/setup/party-icon.svelte b/frontend/src/lib/components/setup/party-icon.sveltenew file mode 100644index 00000000..e30ab67f--- /dev/null+++ b/frontend/src/lib/components/setup/party-icon.svelte@@ -0,0 +1,12 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 268" width="100%" height="100%">+ <path fill="#ff37ad" d="M22.498 68.97a11.845 11.845 0 1 0 0-23.687c-6.471.098-11.666 5.372-11.666 11.844s5.195 11.746 11.666 11.844m181.393-10.04a11.845 11.845 0 1 0-.003-23.688c-6.471.098-11.665 5.373-11.665 11.845c.001 6.472 5.197 11.745 11.668 11.842" />+ <path fill="#fcc954" d="M213.503 211.097a11.845 11.845 0 1 0-.003-23.687c-6.471.098-11.665 5.373-11.664 11.845s5.196 11.745 11.667 11.842M70.872 23.689a11.845 11.845 0 1 0 0-23.688C64.4.1 59.206 5.373 59.206 11.845S64.4 23.591 70.872 23.689" />+ <path fill="#2890e9" d="M140.945 105.94a9.25 9.25 0 0 1-8.974-11.484c.37-1.482.672-2.97.899-4.455a25.4 25.4 0 0 1-8.732 1.904c-5.379.205-10.195-.702-14.3-2.69a22.23 22.23 0 0 1-9.614-8.877c-4.415-7.652-4.034-17.718.964-25.645c4.765-7.568 12.836-11.664 21.586-10.995c6.74.527 12.647 3.051 17.378 7.382q1.293-3.647 2.473-7.803c4.833-17.058 6.429-34.187 6.442-34.36a9.24 9.24 0 0 1 10.041-8.37a9.25 9.25 0 0 1 8.37 10.044c-.067.767-1.768 19.03-7.068 37.735c-2.676 9.445-5.838 17.426-9.42 23.798q.396 2.13.631 4.372c.746 7.211.152 14.974-1.714 22.445a9.256 9.256 0 0 1-8.962 6.998m-20.123-43.827c-.956 0-2.64.28-3.996 2.43c-1.298 2.06-1.552 4.873-.588 6.544c1.282 2.223 5.054 2.417 7.19 2.336c2.424-.092 4.908-1.612 7.338-4.382a16 16 0 0 0-1.43-2.422c-2.007-2.787-4.547-4.212-7.998-4.482c-.13-.008-.305-.024-.516-.024" />+ <path fill="#f0a420" d="M114.361 131.268c-38.343-30.224-78.42-43.319-89.514-29.246a12.8 12.8 0 0 0-2.257 4.509a4 4 0 0 0-.156.61v.024q-.223.947-.333 1.917L.393 236.18c-3.477 20.412 16.73 36.755 35.967 29.093l117.721-46.908c2.076-.826 7.185-3.982 8.583-5.724q.556-.544 1.037-1.153c11.092-14.075-11-49.988-49.34-80.223z" />+ <path fill="#fcc954" d="M163.688 211.494c11.1-14.08-10.984-50-49.327-80.226c-38.343-30.227-78.425-43.316-89.524-29.236s10.983 50 49.326 80.226c38.343 30.227 78.425 43.316 89.525 29.236" />+ <path fill="#f0a420" d="M156.994 203.294c9.108-11.556-10.956-42.563-44.817-69.256c-33.861-26.695-68.697-38.966-77.804-27.413c-9.11 11.556 10.954 42.563 44.815 69.256c33.86 26.695 68.697 38.969 77.806 27.413" />+ <path fill="#2e6ac9" d="M76.059 249.456c-14.327.07-26.004-7.101-40.158-18.257C19.431 218.21 8.493 202.665 7.63 193.81l-4.668 27.327c2.16 7.798 9.523 17.683 20.202 26.101c8.883 7.004 17.844 11.813 27.135 12.48l25.76-10.266zm-14.332-49.6c-27.443-21.637-45.271-46.467-44.77-60.669l-4.549 26.63c.351 12.685 15.175 33.184 36.262 49.808c18.894 14.896 38.583 25.38 53.66 23.363l25.593-10.2c-20.62 1.425-42.376-10.147-66.196-28.931" />+ <path fill="#2890e9" d="M118.535 145.052a11.845 11.845 0 1 0 0-23.688c-6.471.098-11.666 5.372-11.666 11.844s5.195 11.746 11.666 11.844" />+ <path fill="#ff37ad" d="m182.412 122.007l.087-.097c.108-.116.308-.33.596-.621a45 45 0 0 1 2.8-2.56c3.56-2.98 7.45-5.54 11.594-7.63c10.128-5.125 25.208-9.307 44.985-4.747c5.943 1.37 11.87-2.336 13.241-8.278c1.37-5.942-2.336-11.87-8.278-13.24c-25.602-5.903-45.957-.506-59.922 6.566a82.5 82.5 0 0 0-15.857 10.449a66 66 0 0 0-4.215 3.866a45 45 0 0 0-1.53 1.615l-.12.135l-.042.048l-.02.022l-.007.008c-.003.005-.009.01 8.361 7.21l-8.37-7.2c-3.877 4.622-3.328 11.5 1.233 15.448s11.446 3.506 15.464-.994M73.03 43.248a11.75 11.75 0 0 0-16.23-3.664a11.76 11.76 0 0 0-3.665 16.227c.427.683 9.178 14.86 10.976 34.276c1.83 19.727-3.966 37.86-17.253 54.12c4.474 5.686 9.858 11.596 16.008 17.507c8.51-9.834 14.913-20.402 19.12-31.583c5.175-13.756 7.006-28.342 5.445-43.348c-2.487-23.874-12.874-41.11-14.402-43.535" />+ <path fill="#2890e9" d="M220.242 156.578c6.002 1.553 10.244 3.246 12.077 4.034a11.86 11.86 0 0 0 13.94-1.12a11.87 11.87 0 0 0 4.107-8.765a11.85 11.85 0 0 0-8.06-11.426c-5.618-2.495-26.905-10.92-55.044-9.423c-18.941 1.007-37.155 6.253-54.133 15.608c-16.076 8.86-31.004 21.412-44.556 37.425a199 199 0 0 0 20.17 12.607c22.882-26.08 49.283-40.217 78.7-42.085a105.9 105.9 0 0 1 32.8 3.145" />+</svg>diff --git a/frontend/src/lib/components/setup/setup-draft-review.svelte b/frontend/src/lib/components/setup/setup-draft-review.sveltenew file mode 100644index 00000000..dfed8cb1--- /dev/null+++ b/frontend/src/lib/components/setup/setup-draft-review.svelte@@ -0,0 +1,140 @@+<script lang="ts">+ import { Check, Bot } from '@lucide/svelte';+ import { toast } from 'svelte-sonner';+ import { api } from '$lib/api';+ import { Button } from '$lib/components/ui/button';+ import { Input } from '$lib/components/ui/input';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import { getFrameworkLabel } from '$lib/state/projects.svelte';+ import type { SetupDraft } from '$lib/utils/setup-plan';+ import FrameworkIcon from '$lib/components/framework-icon.svelte';++ let { draft, onDecided }: { draft: SetupDraft; onDecided: () => void } = $props();++ let loading = $state(false);+ let error = $state('');+ let rejecting = $state(false);+ let rejectReason = $state('');++ async function approve() {+ loading = true;+ error = '';+ try {+ await api.post(`/setup/drafts/${draft.id}/approve`, {});+ toast.success('Successfully created the Projects', { position: 'top-center' });+ onDecided();+ } catch (e: unknown) {+ const err = e as Error & { status?: number };+ if (err.status === 409) {+ onDecided();+ } else {+ error = err.message || 'Failed to approve the proposal';+ }+ } finally {+ loading = false;+ }+ }++ async function reject() {+ loading = true;+ error = '';+ try {+ await api.post(`/setup/drafts/${draft.id}/reject`, { reason: rejectReason.trim() });+ onDecided();+ } catch (e: unknown) {+ const err = e as Error & { status?: number };+ if (err.status === 409) {+ onDecided();+ } else {+ error = err.message || 'Failed to reject the proposal';+ }+ } finally {+ loading = false;+ }+ }+</script>++<div class="rounded-md border-2 border-primary/40 bg-card">+ <div class="border-b px-4 py-3">+ <div class="flex items-center gap-3">+ <Bot class="h-5 w-5 text-primary" />+ <h3 class="font-semibold">Your AI assistant proposed this setup</h3>+ </div>+ <p class="mt-1 ml-8 text-sm text-muted-foreground">+ Requested by {draft.requestedByEmail}. Nothing is created until you approve it.+ </p>+ </div>+ <div class="space-y-3 p-4">+ {#if error}+ <ErrorAlert {error} />+ {/if}++ <ul class="space-y-2">+ {#each draft.payload.projects as project (project.name)}+ <li class="rounded-md border px-3 py-2.5">+ <div class="flex items-center gap-3">+ <FrameworkIcon framework={project.framework} class="size-5 shrink-0" />+ <div class="min-w-0 flex-1">+ <div class="truncate text-sm font-medium">{project.name}</div>+ <div class="text-xs text-muted-foreground">+ {getFrameworkLabel(project.framework as never) || project.framework}+ </div>+ </div>+ </div>+ {#if project.envFile || project.deployment}+ <div class="mt-2 ml-8 space-y-1 text-xs text-muted-foreground">+ {#if project.envFile}+ <div>+ Token written to <code class="rounded bg-muted px-1 py-0.5"+ >{project.envFile}</code+ >+ as+ <code class="rounded bg-muted px-1 py-0.5">{project.envVar}</code>+ </div>+ {/if}+ {#if project.deployment}+ <div>+ Deployment: {project.deployment.platform} (instructions shown here after+ approval)+ </div>+ {/if}+ </div>+ {/if}+ </li>+ {/each}+ </ul>++ {#if rejecting}+ <div class="space-y-2">+ <Input+ type="text"+ placeholder="Why? Your agent sees this and revises the plan (optional)"+ bind:value={rejectReason}+ disabled={loading}+ />+ <div class="flex justify-end gap-2">+ <Button variant="outline" onclick={() => (rejecting = false)} disabled={loading}>+ Back+ </Button>+ <Button variant="destructive" onclick={reject} disabled={loading}>+ Reject Proposal+ </Button>+ </div>+ </div>+ {:else}+ <div class="flex justify-end gap-2">+ <Button variant="outline" onclick={() => (rejecting = true)} disabled={loading}>+ Reject+ </Button>+ <Button onclick={approve} disabled={loading}>+ {#if loading}+ Approving...+ {:else}+ <Check class="mr-2 h-4 w-4" />+ Approve Setup+ {/if}+ </Button>+ </div>+ {/if}+ </div>+</div>diff --git a/frontend/src/lib/components/setup/setup-live-projects.svelte b/frontend/src/lib/components/setup/setup-live-projects.sveltenew file mode 100644index 00000000..c44420c2--- /dev/null+++ b/frontend/src/lib/components/setup/setup-live-projects.svelte@@ -0,0 +1,63 @@+<script lang="ts">+ import { Badge } from '$lib/components/ui/badge';+ import { getFrameworkLabel, type Project } from '$lib/state/projects.svelte';+ import FrameworkIcon from '$lib/components/framework-icon.svelte';++ let {+ projects,+ initialProjectIds,+ waitingText+ }: {+ projects: Project[];+ initialProjectIds: Set<string>;+ waitingText: string;+ } = $props();+</script>++<div class="rounded-md border bg-card">+ <div class="border-b px-4 py-3">+ <h3 class="font-semibold">Projects</h3>+ </div>+ <div class="p-4">+ {#if projects.length === 0}+ <div class="flex items-center gap-3 text-sm text-muted-foreground">+ <span class="relative flex h-2.5 w-2.5">+ <span+ class="absolute inline-flex h-full w-full animate-ping rounded-full bg-primary opacity-60"+ ></span>+ <span class="relative inline-flex h-2.5 w-2.5 rounded-full bg-primary"></span>+ </span>+ {waitingText}+ </div>+ {:else}+ <ul class="space-y-2">+ {#each projects as project (project.id)}+ {@const isNew = !initialProjectIds.has(project.id)}+ <li+ class="flex items-center gap-3 rounded-md border px-3 py-2 {isNew+ ? ''+ : 'opacity-60'}"+ >+ <FrameworkIcon framework={project.framework} class="size-5 shrink-0" />+ <div class="min-w-0 flex-1">+ <div class="truncate text-sm font-medium">{project.name}</div>+ <div class="text-xs text-muted-foreground">+ {getFrameworkLabel(project.framework)}+ </div>+ </div>+ {#if isNew}+ <Badge+ variant="outline"+ class="border-green-600/40 bg-green-500/10 text-green-600 dark:text-green-400"+ >+ Created+ </Badge>+ {:else}+ <Badge variant="outline" class="text-muted-foreground">Existing</Badge>+ {/if}+ </li>+ {/each}+ </ul>+ {/if}+ </div>+</div>diff --git a/frontend/src/lib/components/setup/setup-next-steps.svelte b/frontend/src/lib/components/setup/setup-next-steps.sveltenew file mode 100644index 00000000..5d6acbcf--- /dev/null+++ b/frontend/src/lib/components/setup/setup-next-steps.svelte@@ -0,0 +1,74 @@+<script lang="ts">+ import bash from 'svelte-highlight/languages/bash';+ import { Rocket } from '@lucide/svelte';+ import {+ credentialValue,+ substituteToken,+ type SetupDraft,+ type SetupDraftProject,+ type SetupPlanProject+ } from '$lib/utils/setup-plan';+ import CopyableCodeBlock from './copyable-code-block.svelte';+ import CopyableInline from './copyable-inline.svelte';++ let { draft }: { draft: SetupDraft } = $props();++ type NextStep = {+ planned: SetupPlanProject;+ project: SetupDraftProject;+ instructions: string;+ value: string;+ };++ const steps = $derived.by((): NextStep[] => {+ const byName = new Map((draft.projects ?? []).map((p) => [p.name, p]));+ const result: NextStep[] = [];+ for (const planned of draft.payload.projects) {+ if (!planned.deployment) continue;+ const project = byName.get(planned.name);+ if (!project) continue;+ const value = credentialValue(planned, project);+ result.push({+ planned,+ project,+ instructions: substituteToken(planned.deployment.instructions, value),+ value+ });+ }+ return result;+ });+</script>++{#if steps.length > 0}+ <div class="rounded-md border bg-card">+ <div class="border-b px-4 py-3">+ <div class="flex items-center gap-3">+ <Rocket class="h-5 w-5 text-primary" />+ <h3 class="font-semibold">Next Steps: Deployment Credentials</h3>+ </div>+ <p class="mt-1 ml-8 text-sm text-muted-foreground">+ These credentials can't be written into your code by the agent because of how the app is+ deployed. Add them to your hosting platform.+ </p>+ </div>+ <div class="space-y-4 p-4">+ {#each steps as step (step.project.id)}+ <div class="space-y-2">+ <div class="text-sm font-medium">+ {step.planned.name}+ <span class="text-muted-foreground">on {step.planned.deployment?.platform}</span>+ </div>+ <CopyableCodeBlock code={step.instructions} language={bash} />+ {#if !step.planned.deployment?.instructions.includes('<token>')}+ <div class="space-y-1">+ <div class="text-xs text-muted-foreground">+ Credential value{step.planned.envVar ? ` for ${step.planned.envVar}` : ''}:+ </div>+ <CopyableInline value={step.value} />+ </div>+ {/if}+ </div>+ {/each}+ </div>+ </div>+{/if}diff --git a/frontend/src/lib/components/setup/setup-projects-step.svelte b/frontend/src/lib/components/setup/setup-projects-step.sveltenew file mode 100644index 00000000..0125b032--- /dev/null+++ b/frontend/src/lib/components/setup/setup-projects-step.svelte@@ -0,0 +1,211 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import { ArrowRight } from '@lucide/svelte';+ import { Portal } from 'bits-ui';+ import { api } from '$lib/api';+ import { Button } from '$lib/components/ui/button';+ import { projectsState } from '$lib/state/projects.svelte';+ import { gotoHref } from '$lib/utils/navigation';+ import { getSetupMode, type SetupMode } from '$lib/utils/setup-storage';+ import type { SetupDraft } from '$lib/utils/setup-plan';+ import type { Framework } from '$lib/state/projects.svelte';+ import SetupModeTabs from './setup-mode-tabs.svelte';+ import SetupTokenPanel from './setup-token-panel.svelte';+ import SetupDraftReview from './setup-draft-review.svelte';+ import SetupNextSteps from './setup-next-steps.svelte';+ import SetupLiveProjects from './setup-live-projects.svelte';+ import ManualProjectsEditor from './manual-projects-editor.svelte';+ import PartyIcon from './party-icon.svelte';++ let {+ organizationId,+ redirectTo = null,+ initialFramework = 'opentelemetry'+ }: {+ organizationId: number;+ redirectTo?: string | null;+ initialFramework?: Framework;+ } = $props();++ let mode = $state<SetupMode>(getSetupMode());+ let draft = $state<SetupDraft | null>(null);+ let draftLoaded = $state(false);+ let initialProjectIds = $state<Set<string>>(new Set());+ let snapshotTaken = $state(false);+ let pollInFlight = false;+ let celebrating = $state(false);+ let celebrated = false;++ const orgProjects = $derived(+ projectsState.projects.filter((p) => p.organizationId === organizationId)+ );+ const newProjects = $derived(orgProjects.filter((p) => !initialProjectIds.has(p.id)));+ // Deployment credentials are only shown on this page, so the auto-redirect+ // must not run past them.+ const hasDeploymentSteps = $derived(+ draft?.status === 'approved' && draft.payload.projects.some((p) => p.deployment)+ );++ function destination(): string {+ if (redirectTo) return redirectTo;+ const first = newProjects[0] ?? orgProjects[0];+ return first ? `/?projectId=${first.id}` : '/';+ }++ function finish() {+ gotoHref(destination(), { replaceState: true });+ }++ // The first created projects trigger the celebration; it redirects to the+ // new project's dashboard unless deployment credentials still need showing.+ $effect(() => {+ if (celebrated || !snapshotTaken || newProjects.length === 0) return;+ celebrated = true;+ celebrating = true;+ const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ setTimeout(+ () => {+ celebrating = false;+ if (!hasDeploymentSteps) finish();+ },+ reduced ? 400 : 2000+ );+ });++ async function refresh() {+ if (pollInFlight) return;+ pollInFlight = true;+ try {+ const [draftResponse] = await Promise.all([+ api.get(`/setup/drafts?organizationId=${organizationId}`),+ projectsState.loadProjects()+ ]);+ draft = draftResponse?.draft ?? null;+ draftLoaded = true;+ } catch {+ } finally {+ pollInFlight = false;+ }+ }++ onMount(() => {+ initialProjectIds = new Set(+ projectsState.projects.filter((p) => p.organizationId === organizationId).map((p) => p.id)+ );+ snapshotTaken = true;+ refresh();++ const interval = setInterval(() => {+ if (document.hidden) return;+ refresh();+ }, 3000);+ return () => clearInterval(interval);+ });+</script>++<div class="space-y-4">+ <SetupModeTabs {mode} onModeChange={(m) => (mode = m)} />++ {#if mode === 'ai'}+ {#if !draftLoaded}+ <p class="text-sm text-muted-foreground">Loading the latest setup proposal...</p>+ {:else if draft?.status === 'pending'}+ <SetupDraftReview {draft} onDecided={refresh} />+ {:else}+ {#if draft?.status === 'approved'}+ <SetupNextSteps {draft} />+ {/if}+ {#if draft?.status === 'rejected'}+ <p class="text-sm text-muted-foreground">+ You rejected the last proposal{draft.rejectReason ? ` (“${draft.rejectReason}”)` : ''}.+ Your agent can revise it and submit a new one with the same setup token.+ </p>+ {/if}+ {#if newProjects.length === 0}+ <SetupTokenPanel {organizationId} autoMint={draft === null} />+ {/if}+ {/if}+ {#if snapshotTaken}+ <SetupLiveProjects+ projects={orgProjects}+ {initialProjectIds}+ waitingText="Your assistant's proposal will appear here for your approval, and created projects show up live."+ />+ {/if}+ {:else}+ <ManualProjectsEditor {organizationId} {initialFramework} onCreated={() => refresh()} />+ {#if snapshotTaken && orgProjects.length > 0}+ <SetupLiveProjects projects={orgProjects} {initialProjectIds} waitingText="" />+ {/if}+ {/if}++ {#if hasDeploymentSteps && newProjects.length > 0 && !celebrating}+ <div class="flex justify-end pt-2">+ <Button onclick={finish}>+ Continue to Dashboard+ <ArrowRight class="ml-2 h-4 w-4" />+ </Button>+ </div>+ {/if}+</div>++{#if celebrating}+ <Portal>+ <div class="celebration" aria-hidden="true">+ <span class="celebration-icon">+ <PartyIcon />+ </span>+ </div>+ </Portal>+{/if}++<style>+ .celebration {+ position: fixed;+ inset: 0;+ z-index: 60;+ display: grid;+ place-items: center;+ pointer-events: none;+ }++ .celebration-icon {+ width: 20rem;+ height: 20rem;+ max-width: 80%;+ max-height: 80vw;+ padding: 50px;+ background: #fff;+ border-radius: 100%;+ filter: drop-shadow(0 12px 32px rgb(0 0 0 / 0.18));+ animation: setup-pop 2s cubic-bezier(0.34, 1.4, 0.64, 1) forwards;+ }++ @keyframes setup-pop {+ 0% {+ opacity: 0;+ transform: scale(0.2);+ }+ 15% {+ opacity: 1;+ transform: scale(1.12);+ }+ 25% {+ transform: scale(1);+ }+ 80% {+ opacity: 1;+ transform: scale(1);+ }+ 100% {+ opacity: 0;+ transform: scale(1.3);+ }+ }++ @media (prefers-reduced-motion: reduce) {+ .celebration {+ display: none;+ }+ }+</style>diff --git a/frontend/src/lib/components/setup/setup-token-panel.svelte b/frontend/src/lib/components/setup/setup-token-panel.sveltenew file mode 100644index 00000000..9a99ef8c--- /dev/null+++ b/frontend/src/lib/components/setup/setup-token-panel.svelte@@ -0,0 +1,134 @@+<script lang="ts">+ import { onMount } from 'svelte';+ import bash from 'svelte-highlight/languages/bash';+ import { RefreshCw } from '@lucide/svelte';+ import { api } from '$lib/api';+ import { Button } from '$lib/components/ui/button';+ import { ErrorAlert } from '$lib/components/ui/error-alert';+ import { SKILL_INSTALL_COMMAND, getSetupTokenPromptParts } from '$lib/utils/ai-setup';+ import type { SetupTokenResponse } from '$lib/utils/setup-plan';+ import CopyableCodeBlock from './copyable-code-block.svelte';+ import CopyablePrompt from './copyable-prompt.svelte';++ let { organizationId, autoMint = true }: { organizationId: number; autoMint?: boolean } =+ $props();++ let minting = $state(false);+ let mintError = $state('');+ let setupToken = $state<SetupTokenResponse | null>(null);+ let now = $state(Date.now());++ const minutesLeft = $derived.by(() => {+ if (!setupToken) return 0;+ return Math.max(0, Math.ceil((new Date(setupToken.expiresAt).getTime() - now) / 60000));+ });+ const expired = $derived(setupToken !== null && minutesLeft <= 0);+ const timeLeftLabel = $derived(+ minutesLeft >= 90 ? `${Math.floor(minutesLeft / 60)} h ${minutesLeft % 60} min` : `${minutesLeft} min`+ );+ const promptParts = $derived(+ setupToken ? getSetupTokenPromptParts(setupToken.backendUrl, setupToken.token) : []+ );++ async function mint() {+ minting = true;+ mintError = '';+ try {+ setupToken = await api.post('/setup-tokens', { organizationId });+ } catch (e) {+ mintError = e instanceof Error ? e.message : 'Failed to generate a setup token';+ } finally {+ minting = false;+ }+ }++ onMount(() => {+ if (autoMint) mint();+ const tick = setInterval(() => (now = Date.now()), 30000);+ return () => clearInterval(tick);+ });++ let lastOrgId: number | undefined;+ $effect(() => {+ if (lastOrgId === undefined) {+ lastOrgId = organizationId;+ return;+ }+ if (organizationId !== lastOrgId) {+ lastOrgId = organizationId;+ if (autoMint) mint();+ }+ });+</script>++<div class="space-y-4">+ <div class="rounded-md border bg-card">+ <div class="border-b px-4 py-3">+ <div class="flex items-center gap-3">+ <div+ class="flex h-6 w-6 items-center justify-center rounded-full bg-primary text-sm font-medium text-primary-foreground"+ >+ 1+ </div>+ <h3 class="font-semibold">Install the Traceway Skill</h3>+ </div>+ <p class="mt-1 ml-9 text-sm text-muted-foreground">+ Add the Traceway setup skill to your coding agent. Works with Claude Code, Cursor, and any+ agent that supports agent skills.+ </p>+ </div>+ <div class="p-4">+ <CopyableCodeBlock code={SKILL_INSTALL_COMMAND} language={bash} />+ </div>+ </div>++ <div class="rounded-md border bg-card">+ <div class="border-b px-4 py-3">+ <div class="flex items-center gap-3">+ <div+ class="flex h-6 w-6 items-center justify-center rounded-full bg-primary text-sm font-medium text-primary-foreground"+ >+ 2+ </div>+ <h3 class="font-semibold">Run the Setup Prompt</h3>+ </div>+ <p class="mt-1 ml-9 text-sm text-muted-foreground">+ Paste this prompt into your agent. It analyzes your code and proposes the projects to+ create; the proposal appears here for your approval.+ </p>+ </div>+ <div class="space-y-3 p-4">+ {#if mintError}+ <ErrorAlert error={mintError} />+ <Button variant="outline" size="sm" onclick={mint} disabled={minting}>+ <RefreshCw class="mr-2 h-4 w-4" />+ Try Again+ </Button>+ {:else if minting}+ <p class="text-sm text-muted-foreground">Generating a setup token...</p>+ {:else if !setupToken}+ <p class="text-sm text-muted-foreground">+ Generate a replacement only after the current agent has received the proposal decision. A+ new token invalidates the previous one.+ </p>+ <Button variant="outline" size="sm" onclick={mint} disabled={minting}>+ <RefreshCw class="mr-2 h-4 w-4" />+ Generate New Token+ </Button>+ {:else if expired}+ <p class="text-sm text-muted-foreground">This setup token expired.</p>+ <Button variant="outline" size="sm" onclick={mint} disabled={minting}>+ <RefreshCw class="mr-2 h-4 w-4" />+ Generate New Token+ </Button>+ {:else}+ <CopyablePrompt parts={promptParts} />+ <p class="text-xs text-muted-foreground">+ The setup token lets your coding agent propose a setup plan for this organization for the+ next {timeLeftLabel}. It is not an ingest token, and nothing is created until you approve+ the proposal here.+ </p>+ {/if}+ </div>+ </div>+</div>diff --git a/frontend/src/lib/components/turnstile-widget.svelte b/frontend/src/lib/components/turnstile-widget.svelteindex d3541138..2d80c314 100644--- a/frontend/src/lib/components/turnstile-widget.svelte+++ b/frontend/src/lib/components/turnstile-widget.svelte@@ -59,6 +59,13 @@window.turnstile.remove(widgetId);}});++ export function reset() {+ if (widgetId && window.turnstile) {+ window.turnstile.reset(widgetId);+ onVerify('');+ }+ }</script><div bind:this={container} class="flex justify-center"></div>diff --git a/frontend/src/lib/state/projects.svelte.ts b/frontend/src/lib/state/projects.svelte.tsindex 15ff3ed9..4995e0b9 100644--- a/frontend/src/lib/state/projects.svelte.ts+++ b/frontend/src/lib/state/projects.svelte.ts@@ -177,9 +177,7 @@ class ProjectsState {// If no current project selected or current project not in list, select first oneif (!this.currentProjectId || !this.projects.find((p) => p.id === this.currentProjectId)) {- if (this.projects.length > 0) {- this.currentProjectId = this.projects[0].id;- }+ this.currentProjectId = this.projects.length > 0 ? this.projects[0].id : null;}// Cache in localStorage@@ -207,23 +205,26 @@ class ProjectsState {}}+ async createProjects(+ organizationId: number,+ projects: { name: string; framework: Framework }[]+ ): Promise<ProjectWithToken[]> {+ const response = await api.post('/projects/batch', { organizationId, projects });+ await this.loadProjects();+ return response.projects;+ }+async createProject(name: string,framework: Framework = 'gin',organizationId?: number): Promise<ProjectWithToken> {- const response = await api.post(- '/projects',- { name, framework, organizationId },- {- projectId: this.currentProjectId ?? undefined- }- );-- // Reload projects to refresh cache- await this.loadProjects();-- return response;+ const targetOrgId = organizationId ?? this.currentProject?.organizationId;+ if (!targetOrgId) {+ throw new Error('No organization selected');+ }+ const created = await this.createProjects(targetOrgId, [{ name, framework }]);+ return created[0];}async updateProject(@@ -276,6 +277,12 @@ class ProjectsState {this.currentProjectId = projectId;}+ clear() {+ this.projects = [];+ this.currentProjectId = null;+ localStorage.removeItem(PROJECTS_CACHE_KEY);+ }+initFromCache() {const cached = localStorage.getItem(PROJECTS_CACHE_KEY);if (cached) {diff --git a/frontend/src/lib/utils/ai-setup.ts b/frontend/src/lib/utils/ai-setup.tsindex c21700d7..22ad8138 100644--- a/frontend/src/lib/utils/ai-setup.ts+++ b/frontend/src/lib/utils/ai-setup.ts@@ -34,3 +34,18 @@ export function getSetupPrompt(.map((p) => p.text).join('');}++export function getSetupTokenPromptParts(backendUrl: string, setupToken: string): PromptPart[] {+ return [+ { text: '/traceway-setup with setup token ', bold: false },+ { text: setupToken, bold: true },+ { text: ' and url ', bold: false },+ { text: backendUrl, bold: true }+ ];+}++export function getSetupTokenPrompt(backendUrl: string, setupToken: string): string {+ return getSetupTokenPromptParts(backendUrl, setupToken)+ .map((p) => p.text)+ .join('');+}diff --git a/frontend/src/lib/utils/setup-plan.ts b/frontend/src/lib/utils/setup-plan.tsnew file mode 100644index 00000000..7dea4197--- /dev/null+++ b/frontend/src/lib/utils/setup-plan.ts@@ -0,0 +1,53 @@+export interface SetupPlanDeployment {+ platform: string;+ instructions: string;+}++export interface SetupPlanProject {+ name: string;+ framework: string;+ envFile?: string;+ envVar?: string;+ envFormat?: 'token' | 'connectionString';+ deployment?: SetupPlanDeployment;+}++export interface SetupDraftProject {+ id: string;+ name: string;+ framework: string;+ token: string;+ sourceMapToken?: string | null;+ backendUrl: string;+ status: 'created' | 'existing';+}++export interface SetupDraft {+ id: string;+ status: 'pending' | 'approved' | 'rejected';+ payload: { projects: SetupPlanProject[] };+ createdAt: string;+ requestedByEmail: string;+ rejectReason?: string;+ projects?: SetupDraftProject[];+}++export interface SetupTokenResponse {+ token: string;+ prefix: string;+ expiresAt: string;+ organizationId: number;+ backendUrl: string;+}++export function credentialValue(planned: SetupPlanProject, project: SetupDraftProject): string {+ if (planned.envFormat === 'connectionString') {+ const base = project.backendUrl.replace(/\/+$/, '');+ return `${project.token}@${base}/api/report`;+ }+ return project.token;+}++export function substituteToken(instructions: string, value: string): string {+ return instructions.replaceAll('<token>', value);+}diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelteindex 21ce1792..c41b2a75 100644--- a/frontend/src/routes/+layout.svelte+++ b/frontend/src/routes/+layout.svelte@@ -132,6 +132,16 @@}});+ // Zero-project accounts have no dashboard to show: they are locked to the+ // standalone /setup flow until their first project exists.+ const needsSetup = $derived(authState.isAuthenticated && projectsState.projects.length === 0);++ $effect(() => {+ if (needsSetup && !isPublicPath(page.url.pathname) && page.url.pathname !== '/setup') {+ goto(resolve('/setup'), { replaceState: true });+ }+ });+// Track navigation depth for smart back buttonslet lastPathname = '';afterNavigate((navigation) => {@@ -193,6 +203,7 @@function handleLogout() {authState.logout();+ projectsState.clear();goto(resolve('/login'));}@@ -258,7 +269,38 @@<Tooltip.Provider delayDuration={0}><!-- This is not ideal, but because our layout is a top level route it can end up showing sidebar on the login page (after the login before the transition). --><!-- We could consider moving this to a lower level layout for the actual app, for now it's just a path check -->- {#if authState.isAuthenticated && !isPublicPath(page.url.pathname)}+ {#if authState.isAuthenticated && !isPublicPath(page.url.pathname) && needsSetup}+ <div class="flex min-h-screen flex-col">+ <header class="flex h-14 shrink-0 items-center justify-between px-4">+ {#if themeState.isDark}+ <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-7 w-auto" />+ {:else}+ <img src="/traceway-logo.png" alt="Traceway Logo" class="h-7 w-auto" />+ {/if}+ <div class="flex items-center gap-2">+ <Button+ variant="ghost"+ size="icon"+ onclick={toggleTheme}+ title={themeState.isDark ? 'Switch to Light Mode' : 'Switch to Dark Mode'}+ >+ {#if themeState.isDark}+ <Sun class="h-5 w-5" />+ {:else}+ <Moon class="h-5 w-5" />+ {/if}+ </Button>+ <Button variant="ghost" size="icon" onclick={handleLogout} title="Logout">+ <LogOut class="h-5 w-5" />+ </Button>+ </div>+ </header>+ <main class="flex flex-1 justify-center px-4 py-10">+ {@render children()}+ </main>+ </div>+ <Toaster position="top-center" />+ {:else if authState.isAuthenticated && !isPublicPath(page.url.pathname)}<Sidebar.SidebarProviderbind:open={sidebarOpen}onOpenChange={(open) => localStorage.setItem(SIDEBAR_OPEN_KEY, String(open))}diff --git a/frontend/src/routes/+page.svelte b/frontend/src/routes/+page.svelteindex e984a30d..8e488308 100644--- a/frontend/src/routes/+page.svelte+++ b/frontend/src/routes/+page.svelte@@ -14,6 +14,7 @@Bug,CircleQuestionMark,CircleCheck,+ FolderPlus,RefreshCw,Star,Unplug@@ -234,6 +235,10 @@ service:}async function loadDashboard(showFullPageLoading = true) {+ if (projectsState.currentProjectId === null) {+ loading = false;+ return;+ }if (showFullPageLoading) {loading = true;}@@ -375,6 +380,22 @@ service:<div class="flex items-center justify-center py-20"><LoadingCircle size="xlg" /></div>+ {:else if projectsState.projects.length === 0}+ <div class="rounded-md border bg-card">+ <div class="flex flex-col items-center justify-center px-6 py-12 text-center">+ <div class="mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-muted">+ <FolderPlus class="h-6 w-6 text-muted-foreground" />+ </div>+ <h3 class="mb-2 text-lg font-semibold">Create Your First Project</h3>+ <p class="mb-4 max-w-md text-sm text-muted-foreground">+ Let your coding agent propose the setup for your approval, or create projects manually.+ </p>+ <Button onclick={() => goto('/setup')}>+ Set Up Projects+ <ArrowRight class="ml-2 h-4 w-4" />+ </Button>+ </div>+ </div>{:else if !error && data && !data.hasData}<!-- Integration Not Connected --><div class="space-y-6">diff --git a/frontend/src/routes/connection/+page.svelte b/frontend/src/routes/connection/+page.svelteindex 406b95dc..d6e1474e 100644--- a/frontend/src/routes/connection/+page.svelte+++ b/frontend/src/routes/connection/+page.svelte@@ -6,6 +6,8 @@CardHeader,CardTitle} from '$lib/components/ui/card';+ import { goto } from '$app/navigation';+ import { Button } from '$lib/components/ui/button';import {projectsState,isJsFramework,@@ -225,9 +227,11 @@ service:{:else}<Card><CardContent class="p-6 text-center">- <p class="text-muted-foreground">- No project selected. Please select or create a project from the dropdown above.+ <p class="mb-4 text-muted-foreground">+ No project selected yet. Let your coding agent propose the setup, or create a project from+ the dropdown above.</p>+ <Button onclick={() => goto('/setup')}>Set Up Projects</Button></CardContent></Card>{/if}diff --git a/frontend/src/routes/finish-setup/+page.svelte b/frontend/src/routes/finish-setup/+page.svelteindex 7ea0c9bf..d418b51f 100644--- a/frontend/src/routes/finish-setup/+page.svelte+++ b/frontend/src/routes/finish-setup/+page.svelte@@ -1,7 +1,6 @@<script lang="ts">import { resolve } from '$app/paths';import { goto } from '$app/navigation';- import { gotoHref } from '$lib/utils/navigation';import { onMount } from 'svelte';import { Button } from '$lib/components/ui/button';import { Input } from '$lib/components/ui/input';@@ -17,19 +16,18 @@import * as Select from '$lib/components/ui/select';import { Check } from '@lucide/svelte';import { authState } from '$lib/state/auth.svelte';- import { projectsState, type Framework } from '$lib/state/projects.svelte';+ import { projectsState } from '$lib/state/projects.svelte';import { themeState } from '$lib/state/theme.svelte';- import FrameworkCombobox from '$lib/components/framework-combobox.svelte';import { consumeSsoReturnTo, safeLocalPath } from '$lib/utils/navigation';+ import SetupProjectsStep from '$lib/components/setup/setup-projects-step.svelte';- const DEFAULT_FRAMEWORK: Framework = 'opentelemetry';-+ let phase = $state<'organization' | 'projects'>('organization');let organizationName = $state('');let timezone = $state(Intl.DateTimeFormat().resolvedOptions().timeZone);- let projectName = $state('');- let framework = $state<Framework>(DEFAULT_FRAMEWORK);let error = $state('');let loading = $state(false);+ let newOrgId = $state<number | null>(null);+ let returnTo = $state('/');const timezones = Intl.supportedValuesOf('timeZone');@@ -49,7 +47,7 @@'Content-Type': 'application/json',Authorization: `Bearer ${authState.token}`},- body: JSON.stringify({ organizationName, timezone, projectName, framework })+ body: JSON.stringify({ organizationName, timezone })});if (!response.ok) {@@ -60,8 +58,15 @@const data = await response.json();authState.setToken(data.token);authState.setOrganizations(data.organizations || []);- projectsState.setProjects(data.projects);- gotoHref(safeLocalPath(consumeSsoReturnTo()));+ projectsState.setProjects(data.projects ?? []);+ newOrgId = data.organizations?.[0]?.id ?? null;+ returnTo = safeLocalPath(consumeSsoReturnTo());++ if (newOrgId === null) {+ goto(returnTo);+ return;+ }+ phase = 'projects';} catch (e) {error = e instanceof Error ? e.message : 'Setup failed';} finally {@@ -71,7 +76,7 @@</script><div class="flex min-h-screen w-full items-center justify-center px-4 py-8">- <Card class="w-[400px]">+ <Card class={phase === 'projects' ? 'w-full max-w-2xl' : 'w-[400px]'}><CardHeader><CardTitle class="text-2xl"><div class="flex flex-row items-center justify-center gap-2">@@ -82,71 +87,70 @@{/if}</div></CardTitle>- <CardDescription class="text-center">Finish setting up your account</CardDescription>+ <CardDescription class="text-center">+ {#if phase === 'projects'}+ Set up your projects+ {:else}+ Finish setting up your account+ {/if}+ </CardDescription></CardHeader><CardContent>- {#if error}- <ErrorAlert {error} class="mb-4" />+ {#if phase === 'projects' && newOrgId !== null}+ <SetupProjectsStep+ organizationId={newOrgId}+ redirectTo={returnTo === '/' ? null : returnTo}+ />+ {:else}+ {#if error}+ <ErrorAlert {error} class="mb-4" />+ {/if}+ <form+ onsubmit={(e) => {+ e.preventDefault();+ handleSubmit();+ }}+ class="grid w-full items-center gap-4"+ >+ <div class="flex flex-col space-y-1.5">+ <Label for="organizationName">Organization Name</Label>+ <Input+ id="organizationName"+ type="text"+ bind:value={organizationName}+ placeholder="Your company or team"+ required+ />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="timezone">Timezone</Label>+ <Select.Root type="single" bind:value={timezone}>+ <Select.Trigger class="w-full">+ <span>{timezone}</span>+ </Select.Trigger>+ <Select.Content class="max-h-60">+ {#each timezones as tz, __index (__index)}+ <Select.Item value={tz}>+ {#snippet children({ selected })}+ <span>{tz}</span>+ {#if selected}+ <Check class="absolute end-2 size-4" />+ {/if}+ {/snippet}+ </Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ <Button type="submit" disabled={loading} class="mt-2 w-full">+ {#if loading}+ Finishing setup...+ {:else}+ Finish setup+ {/if}+ </Button>+ </form>{/if}- <form- onsubmit={(e) => {- e.preventDefault();- handleSubmit();- }}- class="grid w-full items-center gap-4"- >- <div class="flex flex-col space-y-1.5">- <Label for="organizationName">Organization Name</Label>- <Input- id="organizationName"- type="text"- bind:value={organizationName}- placeholder="Your company or team"- required- />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="timezone">Timezone</Label>- <Select.Root type="single" bind:value={timezone}>- <Select.Trigger class="w-full">- <span>{timezone}</span>- </Select.Trigger>- <Select.Content class="max-h-60">- {#each timezones as tz, __index (__index)}- <Select.Item value={tz}>- {#snippet children({ selected })}- <span>{tz}</span>- {#if selected}- <Check class="absolute end-2 size-4" />- {/if}- {/snippet}- </Select.Item>- {/each}- </Select.Content>- </Select.Root>- </div>- <div class="flex flex-col space-y-1.5">- <Label for="projectName">Project Name</Label>- <Input- id="projectName"- type="text"- bind:value={projectName}- placeholder="My App"- required- />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="framework">Framework</Label>- <FrameworkCombobox bind:value={framework} />- </div>- <Button type="submit" disabled={loading} class="mt-2 w-full">- {#if loading}- Finishing setup...- {:else}- Finish setup- {/if}- </Button>- </form></CardContent></Card></div>diff --git a/frontend/src/routes/finish-setup/+page.ts b/frontend/src/routes/finish-setup/+page.tsindex a3d15781..2b883818 100644--- a/frontend/src/routes/finish-setup/+page.ts+++ b/frontend/src/routes/finish-setup/+page.ts@@ -1 +1,23 @@+import { redirect } from '@sveltejs/kit';+import type { PageLoad } from './$types';+export const ssr = false;++function cachedArray(key: string): unknown[] {+ try {+ const value = JSON.parse(localStorage.getItem(key) || '[]');+ return Array.isArray(value) ? value : [];+ } catch {+ return [];+ }+}++export const load: PageLoad = () => {+ if (!localStorage.getItem('AUTH_TOKEN')) return {};++ const organizations = cachedArray('USER_ORGANIZATIONS');+ if (organizations.length === 0) return {};++ const projects = cachedArray('PROJECTS_CACHE_V2');+ throw redirect(302, projects.length === 0 ? '/setup' : '/');+};diff --git a/frontend/src/routes/register/+page.svelte b/frontend/src/routes/register/+page.svelteindex 97748e2e..638dc8c6 100644--- a/frontend/src/routes/register/+page.svelte+++ b/frontend/src/routes/register/+page.svelte@@ -20,9 +20,9 @@import { projectsState, FRAMEWORK_LABELS, type Framework } from '$lib/state/projects.svelte';import { themeState } from '$lib/state/theme.svelte';import { toast } from 'svelte-sonner';- import FrameworkCombobox from '$lib/components/framework-combobox.svelte';import TurnstileWidget from '$lib/components/turnstile-widget.svelte';import OauthButtons from '$lib/components/oauth-buttons.svelte';+ import SetupProjectsStep from '$lib/components/setup/setup-projects-step.svelte';const DEFAULT_FRAMEWORK: Framework = 'opentelemetry';@@ -31,19 +31,22 @@return (value in FRAMEWORK_LABELS ? value : DEFAULT_FRAMEWORK) as Framework;}+ let step = $state<'account' | 'projects'>('account');let email = $state(page.url.searchParams.get('email') ?? '');let name = $state('');let password = $state('');let confirmPassword = $state('');let organizationName = $state('');let timezone = $state(Intl.DateTimeFormat().resolvedOptions().timeZone);- let projectName = $state('');- let framework = $state<Framework>(parseFrameworkParam(page.url.searchParams.get('framework')));let error = $state('');let loading = $state(false);let captchaToken = $state('');let passwordLoginEnabled = $state(true);let providersLoaded = $state(false);+ let newOrgId = $state<number | null>(null);+ let turnstileWidget = $state<TurnstileWidget | null>(null);++ const initialFramework = parseFrameworkParam(page.url.searchParams.get('framework'));const turnstileSiteKey = __TURNSTILE_SITE_KEY__;const captchaEnabled = turnstileSiteKey !== '';@@ -52,7 +55,7 @@if (!__CLOUD_MODE__) {$effect(() => {- if (!providersLoaded) return;+ if (!providersLoaded || step !== 'account') return;// Password login is disabled - this page is inaccessible, send to login.if (!passwordLoginEnabled) {@@ -112,8 +115,6 @@password,organizationName,timezone,- projectName,- framework,captchaToken})});@@ -127,11 +128,17 @@authState.setToken(data.token);authState.setOrganizations(data.organizations || []);- projectsState.setProjects(data.projects);+ projectsState.setProjects(data.projects ?? []);+ newOrgId = data.organizations?.[0]?.id ?? null;- goto(resolve('/'));+ if (newOrgId === null) {+ goto(resolve('/'));+ return;+ }+ step = 'projects';} catch (e) {error = e instanceof Error ? e.message : 'Registration failed';+ turnstileWidget?.reset();} finally {loading = false;}@@ -139,7 +146,7 @@</script><div class="flex min-h-screen w-full items-center justify-center px-4 py-8">- <Card class="w-[400px]">+ <Card class={step === 'projects' ? 'w-full max-w-2xl' : 'w-[400px]'}><CardHeader><CardTitle class="text-2xl"><div class="flex flex-row items-center justify-center gap-2">@@ -150,133 +157,133 @@{/if}</div></CardTitle>- <CardDescription class="text-center">Create your account</CardDescription>+ <CardDescription class="text-center">+ {#if step === 'projects'}+ Set up your projects+ {:else}+ Create your account+ {/if}+ </CardDescription></CardHeader><CardContent>- {#if error}- <ErrorAlert {error} class="mb-4" />- {/if}- <OauthButtons bind:passwordLoginEnabled bind:loaded={providersLoaded} />- {#if providersLoaded && passwordLoginEnabled}- <form- onsubmit={(e) => {- e.preventDefault();- handleRegister();- }}- class="grid w-full items-center gap-4"- >- <div class="flex flex-col space-y-1.5">- <Label for="email">Email</Label>- <Input- id="email"- type="email"- bind:value={email}- placeholder="[email protected]"- required- />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="name">Name</Label>- <Input id="name" type="text" bind:value={name} placeholder="Your name" required />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="password">Password</Label>- <Input- id="password"- type="password"- bind:value={password}- placeholder="Password (min 8 characters)"- required- />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="confirmPassword">Confirm Password</Label>- <Input- id="confirmPassword"- type="password"- bind:value={confirmPassword}- placeholder="Confirm password"- required- />- </div>-- <div class="mt-2 flex items-center gap-3">- <div class="flex-1 border-t"></div>- <p class="text-sm text-muted-foreground">Organization & Project</p>- <div class="flex-1 border-t"></div>- </div>+ {#if step === 'projects' && newOrgId !== null}+ <SetupProjectsStep+ organizationId={newOrgId}+ {initialFramework}+ />+ {:else}+ {#if error}+ <ErrorAlert {error} class="mb-4" />+ {/if}+ <OauthButtons bind:passwordLoginEnabled bind:loaded={providersLoaded} />+ {#if providersLoaded && passwordLoginEnabled}+ <form+ onsubmit={(e) => {+ e.preventDefault();+ handleRegister();+ }}+ class="grid w-full items-center gap-4"+ >+ <div class="flex flex-col space-y-1.5">+ <Label for="email">Email</Label>+ <Input+ id="email"+ type="email"+ bind:value={email}+ placeholder="[email protected]"+ required+ />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="name">Name</Label>+ <Input id="name" type="text" bind:value={name} placeholder="Your name" required />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="password">Password</Label>+ <Input+ id="password"+ type="password"+ bind:value={password}+ placeholder="Password (min 8 characters)"+ required+ />+ </div>+ <div class="flex flex-col space-y-1.5">+ <Label for="confirmPassword">Confirm Password</Label>+ <Input+ id="confirmPassword"+ type="password"+ bind:value={confirmPassword}+ placeholder="Confirm password"+ required+ />+ </div>- <div class="flex flex-col space-y-1.5">- <Label for="organizationName">Organization Name</Label>- <Input- id="organizationName"- type="text"- bind:value={organizationName}- placeholder="Your company or team"- required- />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="timezone">Timezone</Label>- <Select.Root type="single" bind:value={timezone}>- <Select.Trigger class="w-full">- <span>{timezone}</span>- </Select.Trigger>- <Select.Content class="max-h-60">- {#each timezones as tz, __index (__index)}- <Select.Item value={tz}>- {#snippet children({ selected })}- <span>{tz}</span>- {#if selected}- <Check class="absolute end-2 size-4" />- {/if}- {/snippet}- </Select.Item>- {/each}- </Select.Content>- </Select.Root>- </div>- <div class="flex flex-col space-y-1.5">- <Label for="projectName">Project Name</Label>- <Input- id="projectName"- type="text"- bind:value={projectName}- placeholder="My App"- required- />- </div>- <div class="flex flex-col space-y-1.5">- <Label for="framework">Framework</Label>- <FrameworkCombobox bind:value={framework} />- </div>+ <div class="mt-2 flex items-center gap-3">+ <div class="flex-1 border-t"></div>+ <p class="text-sm text-muted-foreground">Organization</p>+ <div class="flex-1 border-t"></div>+ </div>- {#if captchaEnabled}- <div class="mt-2 flex flex-col space-y-1.5">- <TurnstileWidget- siteKey={turnstileSiteKey}- onVerify={(token) => (captchaToken = token)}- onError={() => (captchaToken = '')}+ <div class="flex flex-col space-y-1.5">+ <Label for="organizationName">Organization Name</Label>+ <Input+ id="organizationName"+ type="text"+ bind:value={organizationName}+ placeholder="Your company or team"+ required/></div>- {/if}+ <div class="flex flex-col space-y-1.5">+ <Label for="timezone">Timezone</Label>+ <Select.Root type="single" bind:value={timezone}>+ <Select.Trigger class="w-full">+ <span>{timezone}</span>+ </Select.Trigger>+ <Select.Content class="max-h-60">+ {#each timezones as tz, __index (__index)}+ <Select.Item value={tz}>+ {#snippet children({ selected })}+ <span>{tz}</span>+ {#if selected}+ <Check class="absolute end-2 size-4" />+ {/if}+ {/snippet}+ </Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>- <Button- type="submit"- disabled={loading || (captchaEnabled && !captchaToken)}- class="mt-2 w-full"- >- {#if loading}- Creating account...- {:else}- Create Account+ {#if captchaEnabled}+ <div class="mt-2 flex flex-col space-y-1.5">+ <TurnstileWidget+ bind:this={turnstileWidget}+ siteKey={turnstileSiteKey}+ onVerify={(token) => (captchaToken = token)}+ onError={() => (captchaToken = '')}+ />+ </div>{/if}- </Button>- </form>++ <Button+ type="submit"+ disabled={loading || (captchaEnabled && !captchaToken)}+ class="mt-2 w-full"+ >+ {#if loading}+ Creating account...+ {:else}+ Create Account+ {/if}+ </Button>+ </form>+ {/if}{/if}</CardContent>- {#if __CLOUD_MODE__}+ {#if __CLOUD_MODE__ && step === 'account'}<CardFooter class="flex flex-col justify-center"><p class="text-sm text-muted-foreground">Already have an account? <a href={resolve('/login')} class="text-primary hover:underline"diff --git a/frontend/src/routes/register/+page.ts b/frontend/src/routes/register/+page.tsindex 98a094a3..f01b1ac0 100644--- a/frontend/src/routes/register/+page.ts+++ b/frontend/src/routes/register/+page.ts@@ -2,10 +2,10 @@ import { redirect } from '@sveltejs/kit';import type { PageLoad } from './$types';export const load: PageLoad = () => {- // Check if user is already authenticatedconst token = localStorage.getItem('AUTH_TOKEN');if (token) {- throw redirect(302, '/');+ const cached = JSON.parse(localStorage.getItem('PROJECTS_CACHE_V2') || '[]');+ throw redirect(302, cached.length === 0 ? '/setup' : '/');}return {};};diff --git a/frontend/src/routes/setup/+page.svelte b/frontend/src/routes/setup/+page.sveltenew file mode 100644index 00000000..797ff99b--- /dev/null+++ b/frontend/src/routes/setup/+page.svelte@@ -0,0 +1,67 @@+<script lang="ts">+ import * as Select from '$lib/components/ui/select';+ import { Label } from '$lib/components/ui/label';+ import { authState } from '$lib/state/auth.svelte';+ import { projectsState } from '$lib/state/projects.svelte';+ import SetupProjectsStep from '$lib/components/setup/setup-projects-step.svelte';++ const writableOrgs = $derived(authState.organizations.filter((o) => o.role !== 'readonly'));++ let selectedOrgId = $state<number | null>(null);++ $effect(() => {+ if (selectedOrgId !== null && writableOrgs.some((o) => o.id === selectedOrgId)) return;+ const currentOrgId = projectsState.currentProject?.organizationId;+ selectedOrgId = writableOrgs.some((o) => o.id === currentOrgId)+ ? currentOrgId!+ : (writableOrgs[0]?.id ?? null);+ });++ const selectedOrgName = $derived(+ writableOrgs.find((o) => o.id === selectedOrgId)?.name ?? ''+ );+</script>++<div class="mx-auto w-full max-w-2xl space-y-6">+ <div>+ <h1 class="text-2xl font-bold">Set Up Projects</h1>+ <p class="mt-1 text-sm text-muted-foreground">+ Let your coding agent propose the project setup for your approval, or create projects+ manually.+ </p>+ </div>++ {#if writableOrgs.length === 0}+ <p class="text-sm text-muted-foreground">+ You need an owner, admin, or user role in an organization to create projects.+ </p>+ {:else}+ {#if writableOrgs.length > 1}+ <div class="flex max-w-xs flex-col space-y-1.5">+ <Label>Organization</Label>+ <Select.Root+ type="single"+ value={selectedOrgId !== null ? String(selectedOrgId) : undefined}+ onValueChange={(val) => {+ if (val) selectedOrgId = Number(val);+ }}+ >+ <Select.Trigger class="w-full">+ {selectedOrgName || 'Select organization'}+ </Select.Trigger>+ <Select.Content>+ {#each writableOrgs as org (org.id)}+ <Select.Item value={String(org.id)}>{org.name}</Select.Item>+ {/each}+ </Select.Content>+ </Select.Root>+ </div>+ {/if}++ {#if selectedOrgId !== null}+ {#key selectedOrgId}+ <SetupProjectsStep organizationId={selectedOrgId} />+ {/key}+ {/if}+ {/if}+</div>diff --git a/frontend/src/routes/setup/+page.ts b/frontend/src/routes/setup/+page.tsnew file mode 100644index 00000000..99cc6fb0--- /dev/null+++ b/frontend/src/routes/setup/+page.ts@@ -0,0 +1,20 @@+import { redirect } from '@sveltejs/kit';+import { authState } from '$lib/state/auth.svelte';+import type { PageLoad } from './$types';++export const load: PageLoad = () => {+ if (!authState.isAuthenticated) {+ throw redirect(302, '/login?returnTo=%2Fsetup');+ }+ // The setup flow only exists for zero-project accounts; once projects+ // exist, new ones are added from the project dropdown instead.+ let cached: unknown = [];+ try {+ cached = JSON.parse(localStorage.getItem('PROJECTS_CACHE_V2') || '[]');+ } catch {+ cached = [];+ }+ if (Array.isArray(cached) && cached.length > 0) {+ throw redirect(302, '/');+ }+};diff --git a/skills/traceway-setup/SKILL.md b/skills/traceway-setup/SKILL.mdindex 26314bf3..63679796 100644--- a/skills/traceway-setup/SKILL.md+++ b/skills/traceway-setup/SKILL.md@@ -1,6 +1,6 @@---name: traceway-setup-description: Analyze a repository's backend, browser, mobile, AI, background-work, existing-observability, build, and deployment architecture; propose and explain the correct Traceway project topology; guide the user through creating projects and credentials in the Traceway dashboard; then instrument and verify every selected component. Every backend uses OpenTelemetry over OTLP/HTTP regardless of language or framework, keeping endpoints, tasks, AI traces, logs, application metrics, and host metrics in one backend project. Browser frontends and independently released mobile apps use separate Traceway projects with the Traceway SDKs, plus source map or symbol uploads where applicable. Use when the user wants to plan, add, migrate, or complete Traceway or OpenTelemetry monitoring for a backend, frontend, full-stack, mobile, iOS/Swift, or AI agent/chatbot repository. Accepts a project token and instance URL in the invocation, e.g. "/traceway-setup with token abc123 and url https://traceway.example.com".+description: Analyze and instrument repositories for Traceway observability. Use when the user wants to plan, add, migrate, or verify Traceway or OpenTelemetry monitoring for backend, browser, full-stack, mobile or iOS, or AI-agent software, including project topology and user-approved setup-plan creation. Backends use OTLP/HTTP; browser frontends and independently released mobile clients use separate Traceway SDK projects. Accept either an existing project token and instance URL or an organization setup token (`tws_...`) and URL; with no token, analyze first and guide setup-token acquisition. Treat any `tws_` token as a setup token.---# Set Up Traceway@@ -12,10 +12,20 @@ Analyze the application first, agree on its Traceway project structure with the- Inspect before asking for credentials or changing code.- Explain what was detected, what is already tracked, and how each production component should report to Traceway.- Present a proposed project map and wait for the user to confirm it before implementation.+- There are two classes of credentials, treated differently:+ - **Setup tokens** (prefix `tws_`) are org-scoped, expire in 6 hours, and can only propose a setup plan; nothing is created until the user approves the plan on the Traceway website. They are designed to transit chat, and asking the user to paste one is expected.+ - **Project ingest tokens and upload tokens** are long-lived. Never print their values, never ask the user to paste them into chat, and never commit them. When Step 3's apply script (or the `traceway` CLI) writes an approved plan's ingest tokens into env files, read only the variable names and statuses from its output, never the values.- Never print token values found in files or the environment. Report only that a value exists and the variable name that carries it.-- Do not require the user to paste secrets into chat. Implement against environment variables and let the user set real values in their local, deployment, or CI secret store. Real values are required only for live verification.- Never commit tokens or filled connection strings.+## Invocation Forms++| Invocation carries | Path |+|---|---|+| A project ingest token + url | Fast Path for a single component, otherwise Steps 1-2, then integrate against the existing project |+| A setup token (`tws_`) + url | Steps 1-2, then Step 3 from "Write the plan file" (3b) |+| No token | Steps 1-2, then Step 3 from the top |+**Every backend integrates with OpenTelemetry.** There is one backend path, not one per language or web framework: Go, Node, Python, PHP, Java, .NET, Ruby, and everything else export OTLP/HTTP to `<instance>/api/otel/*`. The Traceway project is created with framework **OpenTelemetry**, which is the only backend option in the dashboard's framework picker. The native Traceway Go SDK is a deliberate exception used only when the user explicitly asks for it.## Fast Path@@ -23,10 +33,10 @@ Analyze the application first, agree on its Traceway project structure with theWhen all of the following hold, skip Steps 2 and 3 and go straight to the integration steps:- the repository has exactly one deployable component, and-- the user supplied (or the environment already carries) an instance URL and a project token, and+- the user supplied (or the environment already carries) an instance URL and a project ingest token (not a `tws_` setup token, which exists to create projects), and- the token's project already matches that component.-Still run Step 1, because it decides *how* to instrument. Collapse "Propose and Confirm the Project Map" to a single confirmation line ("This is a Go API; it reports to your existing `<name>` project over OpenTelemetry") and skip the dashboard walkthrough entirely. The full map-and-dashboard ceremony exists for repositories with more than one deployable component, or where no project exists yet. Do not make a user who handed you a token sit through a project-map review for a single service.+Still run Step 1, because it decides *how* to instrument. Collapse "Propose and Confirm the Project Map" to a single confirmation line ("This is a Go API; it reports to your existing `<name>` project over OpenTelemetry") and skip the project-creation step entirely. The full map-and-creation ceremony exists for repositories with more than one deployable component, or where no project exists yet. Do not make a user who handed you a token sit through a project-map review for a single service.## Step 1: Analyze the Architecture@@ -79,23 +89,159 @@ Ask the user to confirm only what the repository cannot establish safely:4. Does the backend run on a VM/host, Kubernetes, or serverless/PaaS, and should host metrics be collected?5. Do mobile directories represent one cross-platform product or separate released apps?+Each confirmed row must also settle what Step 3's plan file needs:++- The **framework value**, one of the nine: `opentelemetry`, `react`, `svelte`, `vuejs`, `jquery`, `flutter`, `react-native`, `android`, `ios`.+- The **env wiring**: which untracked env file holds the credential (`envFile`) and under which name (`envVar`), following the credential-naming rules above (public prefixes like `VITE_`/`PUBLIC_`/`NEXT_PUBLIC_` for browser values). `envFormat` is `token` when the code composes the connection string itself or the value feeds an OTLP Authorization header, and `connectionString` when the SDK init reads the full `<token>@<instance>/api/report` string straight from the variable.+- The **deployment placement**, from Step 1's deployment analysis: when the credential cannot be hardcoded into the repository because of how the component is deployed (Vercel/Fly/K8s/CI-injected env, secret managers), add a `deployment` block with the platform name and the exact command or UI path, using the literal placeholder `<token>` for the value. The website substitutes the real value after approval; never put real tokens in the plan. A mobile project whose credential lives in build config usually gets a `deployment` block and no `envFile`.+Do not modify code until the user confirms this map.-## Step 3: Guide Dashboard Project Creation+## Step 3: Create the Projects++The default path: submit the confirmed map as a setup plan, the user approves it visually on the Traceway website, and a short curl script writes the resulting ingest tokens into env files. Nothing needs to be installed beyond `curl` and `jq`. Existing correctly mapped Traceway projects may be reused (the plan matches projects by name, so listing an existing name reuses it instead of duplicating).++### 3a. Get a setup token (skip when the invocation carried one)++Branch on account state; ask only if the repository and conversation do not establish it:++- **Has a Traceway account**: "Open `<instance>/setup` (Traceway Cloud: https://cloud.tracewayapp.com/setup). Log in if prompted; the page shows a setup token starting with `tws_`. Paste it here and keep the page open." The token expires in 6 hours; the page has a Generate New Token button.+- **No account yet**: "Open `<instance>/register` (Traceway Cloud: https://cloud.tracewayapp.com/register). Step 1 creates your account and organization. On step 2, keep 'AI' selected; it shows a setup token starting with `tws_`. Paste it here and leave that page open: my proposal will appear there for your approval, and the projects show up live once you approve."-Read `dashboard-project-setup.md` and give the user a tailored, ordered checklist containing exactly the projects from the confirmed map. Explain why each project exists, which framework to select, which signals it will receive, and which credentials it needs. Include the relevant Traceway documentation links.+Do not have the user create projects in the web UI on this path, and do not proceed without the token.-For every credential, define an environment variable rather than asking the user to paste the value. Runtime credentials take component-specific names (`TRACEWAY_BACKEND_TOKEN`, `PUBLIC_TRACEWAY_WEB_CONNECTION_STRING`, `TRACEWAY_MOBILE_CONNECTION_STRING`), respecting the framework's public-environment prefix rules.+### 3b. Write the plan file-**Upload tokens are different: the uploaders read fixed variable names.** `traceway-sourcemaps` reads `TRACEWAY_SOURCEMAP_TOKEN`, and `dart run traceway:upload_symbols` and the iOS dSYM script read `TRACEWAY_UPLOAD_TOKEN` (all three also read `TRACEWAY_URL`). Either name the CI secret exactly that, or keep a component-specific secret and pass it explicitly:+Write `traceway-setup-plan.json` from the confirmed map, one entry per project:++```json+{+ "projects": [+ {"name": "Product Backend", "framework": "opentelemetry",+ "envFile": "backend/.env", "envVar": "TRACEWAY_BACKEND_TOKEN"},+ {"name": "Product Web", "framework": "svelte",+ "envFile": "frontend/.env", "envVar": "PUBLIC_TRACEWAY_WEB_CONNECTION_STRING",+ "envFormat": "connectionString",+ "deployment": {"platform": "Vercel",+ "instructions": "vercel env add PUBLIC_TRACEWAY_WEB_CONNECTION_STRING production\n# paste: <token>"}}+ ]+}+```++Rules: `framework` is one of the nine values from Step 2; every `envFile` must be untracked (create it and confirm it is gitignored first); `envVar` follows the credential-naming rules; `deployment.instructions` uses the literal `<token>` placeholder, never a real value.++### 3c. Submit the plan and wait for approval (curl)++Use `curl` and `jq` directly for this step. Do NOT install the `traceway` CLI for it; nothing gets installed on this path. (Only if a CLI new enough to have `setup apply` is already present is `printf '%s' "$TRACEWAY_SETUP_TOKEN" | traceway setup apply --url "$TRACEWAY_URL" --plan traceway-setup-plan.json --token-stdin` an equivalent one-step alternative.) If `jq` is unavailable and cannot be installed, use the manual fallback (3e).++Export the credentials first; setup tokens may transit chat, so this is fine:```bash-traceway-sourcemaps --url "$TRACEWAY_URL" --token "$TRACEWAY_WEB_UPLOAD_TOKEN" --directory ./dist+export TRACEWAY_URL="<instance>" # no trailing slash+export TRACEWAY_SETUP_TOKEN="tws_..."+```++Validate the token and show the organization (this response carries project names only, safe to display):++```bash+curl -s -w '\nHTTP %{http_code}\n' -H "Authorization: Bearer $TRACEWAY_SETUP_TOKEN" \+ "$TRACEWAY_URL/api/setup/session"+```++Submit the plan as a draft:++```bash+curl -s -w '\nHTTP %{http_code}\n' -X PUT \+ -H "Authorization: Bearer $TRACEWAY_SETUP_TOKEN" -H 'Content-Type: application/json' \+ --data-binary @traceway-setup-plan.json "$TRACEWAY_URL/api/setup/plan"+```++`200 {"status":"pending"}` means the draft is up; tell the user: "Review the proposal on the Traceway page you have open and press **Approve Setup**." A `422` is a validation message: fix the plan and resubmit. A `401` means the token is invalid or expired: ask the user for a fresh one from `<instance>/setup`.++Then wait for the decision with the script below. The script exists because the decision response carries the ingest tokens: values must flow API to env file without ever reaching stdout, your context, or the chat. Write it to `traceway-setup-wait.sh` exactly as given and run `sh traceway-setup-wait.sh`. Never fetch `GET /api/setup/plan` directly, and never read the env files it writes.++```sh+#!/bin/sh+# Waits for the setup decision, then writes each ingest token into the env+# file named by the plan. Prints statuses and variable names only.+set -eu+PLAN=${1:-traceway-setup-plan.json}+AUTH="Authorization: Bearer ${TRACEWAY_SETUP_TOKEN:?}"+URL=${TRACEWAY_URL:?}+deadline=$(($(date +%s) + 1800))+while :; do+ resp=$(curl -s -H "$AUTH" "$URL/api/setup/plan")+ status=$(printf '%s' "$resp" | jq -r '.status // "error"')+ case "$status" in+ approved) break ;;+ rejected)+ echo "rejected: $(printf '%s' "$resp" | jq -r '.reason // "(no reason given)"')"+ exit 2 ;;+ pending|none) ;;+ *) echo "unexpected response, the setup token may have expired"; exit 1 ;;+ esac+ if [ "$(date +%s)" -ge "$deadline" ]; then+ echo "timed out waiting for approval; rerun when the user is ready"+ exit 3+ fi+ sleep 3+done+i=0+n=$(jq '.projects | length' "$PLAN")+while [ "$i" -lt "$n" ]; do+ name=$(jq -r ".projects[$i].name" "$PLAN")+ envfile=$(jq -r ".projects[$i].envFile // empty" "$PLAN")+ envvar=$(jq -r ".projects[$i].envVar // empty" "$PLAN")+ format=$(jq -r ".projects[$i].envFormat // \"token\"" "$PLAN")+ pstatus=$(printf '%s' "$resp" | jq -r --arg n "$name" \+ '[.projects[] | select(.name == $n)][0].status // "missing"')+ if [ "$pstatus" = missing ]; then+ echo "$name: missing from the approved plan"+ i=$((i + 1)); continue+ fi+ if [ -n "$envfile" ] && [ -n "$envvar" ]; then+ value=$(printf '%s' "$resp" | jq -r --arg n "$name" --arg f "$format" \+ '[.projects[] | select(.name == $n)][0]+ | if $f == "connectionString"+ then .token + "@" + (.backendUrl | sub("/+$"; "")) + "/api/report"+ else .token end')+ dir=$(dirname "$envfile"); mkdir -p "$dir"+ tmp=$(mktemp "$dir/.tmp-env-XXXXXX")+ { [ -f "$envfile" ] && grep -v "^${envvar}=" "$envfile" > "$tmp"; } || true+ printf '%s=%s\n' "$envvar" "$value" >> "$tmp"+ mv "$tmp" "$envfile"+ echo "$name: $pstatus, wrote $envvar to $envfile"+ else+ echo "$name: $pstatus"+ fi+ i=$((i + 1))+done+echo "done: deployment credentials, if any, are shown on the Traceway page the user has open"```-Inventing a name like `TRACEWAY_WEB_UPLOAD_TOKEN` and then calling the uploader with no `--token` fails at release time, not at setup time, so make the choice explicit in the CI step.+Env files come out mode 0600 via mktemp. Failure handling:-Proceed when the user confirms the required projects exist and the variables will be available. Existing correctly mapped Traceway projects may be reused.+- **Rejected (exit 2)**: the script prints the user's rejection reason. Revise the map with the user, update the plan file, submit again (a new PUT replaces the pending draft), and rerun the wait script. Already-approved projects are matched by name, never duplicated.+- **Expired or invalid token (401 / exit 1)**: ask the user for a fresh token from `<instance>/setup`, re-export it, resubmit, rerun.+- **Timeout (exit 3)**: resubmit and rerun when the user is ready; it is safe.++Delete the plan file and `traceway-setup-wait.sh` after a successful apply; they hold no secrets but they are setup litter.++### 3d. Confirm and handle deployment credentials++On approval the Traceway page celebrates and lands the user on the new project's dashboard, which doubles as the confirmation that the projects exist. For every project with a `deployment` block, the page first shows a **Next Steps** panel with the exact command and the real credential value; walk the user through completing it there before they continue, because the setup page is not reachable again once the account has projects. Never relay those values through chat; if a value is needed later, each project's Connection page in the dashboard carries its token.++### 3e. Manual fallback++When the user prefers clicking, `curl` or `jq` is unavailable, or apply keeps failing, follow `dashboard-project-setup.md`: the user creates each project in the dashboard UI and puts the tokens straight into their env files or secret store. On this path the old rule applies in full: ingest tokens never transit chat.++**Upload tokens stay manual on every path: the uploaders read fixed variable names.** `traceway-sourcemaps` reads `TRACEWAY_SOURCEMAP_TOKEN`, and `dart run traceway:upload_symbols` and the iOS dSYM script read `TRACEWAY_UPLOAD_TOKEN` (all three also read `TRACEWAY_URL`). Either name the CI secret exactly that, or keep a component-specific secret and pass it explicitly:++```bash+traceway-sourcemaps --url "$TRACEWAY_URL" --token "$TRACEWAY_WEB_UPLOAD_TOKEN" --directory ./dist+```++Inventing a name like `TRACEWAY_WEB_UPLOAD_TOKEN` and then calling the uploader with no `--token` fails at release time, not at setup time, so make the choice explicit in the CI step. Upload tokens are generated per project from **Connection** -> **Source Maps** or **Symbol Upload** in the dashboard.## Integration Paths@@ -170,6 +316,8 @@ Two of those lines are load-bearing in a way that fails silently:SDKs append `/v1/traces`, `/v1/metrics`, `/v1/logs` to the endpoint automatically, so set the **base** URL only. A full signal path in `OTEL_EXPORTER_OTLP_ENDPOINT` produces `/v1/traces/v1/traces`, and the signal-specific variables (`OTEL_EXPORTER_OTLP_TRACES_ENDPOINT`) are used verbatim with nothing appended. When configuring in code instead, the full URLs are `https://<instance>/api/otel/v1/traces` (and `/v1/metrics`, `/v1/logs`) with header `Authorization: Bearer <project-token>`.+When Step 3's apply script wrote the env files, the plan's variables already hold real values locally, so wire the exporter to exactly those names (e.g. `Authorization=Bearer ${TRACEWAY_BACKEND_TOKEN}`) and run live verification immediately. The script writes only each project's one plan variable: companion variables the integration reads, like `TRACEWAY_URL` for the instance URL, are yours to add to the same env file now. On the manual fallback the user populates the variables first.+Constraints: OTLP/HTTP only (protobuf or JSON). OTLP/gRPC is not supported, there is no listener on port 4317. `Content-Encoding: gzip` is fine. The body is read up to 10 MB and the rest is truncated, so an oversized batch answers `400 failed to unmarshal` rather than `413`. A wrong or missing token answers `401`, and any other path answers `404`. All three are invisible from the application: most SDKs log exporter failures at debug level only, so when nothing arrives, turn the SDK's own diagnostic logging on first.### Node.js example@@ -220,6 +368,63 @@ Three parts of that snippet are load-bearing:Auto-instrumentation covers Express routes (sets `http.route`), status codes, errors, and database clients (`pg`, `mysql2`, `mongodb`, `ioredis`). SQLite and custom business logic need manual `tracer.startActiveSpan()` child spans.+#### Next.js server exception++Next.js must not use the generic `instrumentation.mjs` preload above, `node --import`, or `NODE_OPTIONS`. Next.js creates its own incoming request root span with the matched `http.route`; preloading the generic Node HTTP instrumentation creates a competing root named from the literal URL, so `/api/users/1` and `/api/users/2` become separate endpoints.++For a Next.js server, create a minimal `instrumentation.ts` hook and put the SDK in a separate `instrumentation.node.ts`. Next.js compiles the hook for both Node and Edge; importing OTel packages directly in the hook, even with dynamic `import()` calls after a runtime guard, can make the development Edge compilation resolve Node built-ins and fail. The wrapper must conditionally import only the Node module:++```typescript+export async function register() {+ if (process.env.NEXT_RUNTIME === "nodejs") {+ await import("./instrumentation.node");+ }+}+```++Keep every Node-only import and the SDK startup in the sibling module:++```typescript+import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";+import { OTLPLogExporter } from "@opentelemetry/exporter-logs-otlp-http";+import { OTLPMetricExporter } from "@opentelemetry/exporter-metrics-otlp-http";+import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";+import { resourceFromAttributes } from "@opentelemetry/resources";+import { BatchLogRecordProcessor } from "@opentelemetry/sdk-logs";+import { PeriodicExportingMetricReader } from "@opentelemetry/sdk-metrics";+import { NodeSDK } from "@opentelemetry/sdk-node";++(Error as unknown as { prepareStackTrace?: unknown }).prepareStackTrace = undefined;++const instance = process.env.TRACEWAY_URL!.replace(/\/+$/, "");+const base = `${instance}/api/otel`;+const headers = { Authorization: `Bearer ${process.env.TRACEWAY_BACKEND_TOKEN}` };++new NodeSDK({+ resource: resourceFromAttributes({+ "service.name": process.env.OTEL_SERVICE_NAME ?? "nextjs-server",+ "service.version": process.env.APP_VERSION ?? "development",+ }),+ traceExporter: new OTLPTraceExporter({ url: `${base}/v1/traces`, headers }),+ metricReaders: [+ new PeriodicExportingMetricReader({+ exporter: new OTLPMetricExporter({ url: `${base}/v1/metrics`, headers }),+ exportIntervalMillis: 30_000,+ }),+ ],+ logRecordProcessors: [+ new BatchLogRecordProcessor({+ exporter: new OTLPLogExporter({ url: `${base}/v1/logs`, headers }),+ }),+ ],+ instrumentations: [getNodeAutoInstrumentations()],+}).start();+```++Install the log exporter and SDK packages in addition to the generic Node dependencies: `@opentelemetry/exporter-logs-otlp-http`, `@opentelemetry/sdk-logs`, `@opentelemetry/api-logs`, and `@opentelemetry/resources`. Next.js versions before 15 also need `experimental.instrumentationHook: true`. Full setup and verification: https://docs.tracewayapp.com/client/otel/nextjs++Resetting `Error.prepareStackTrace` in `instrumentation.node.ts` lets Node apply source maps instead of leaving server Issues pointed at minified Next chunks. Production must also start with `NODE_OPTIONS=--enable-source-maps`, and the build must emit `.next/server/**/*.js.map`; verify both rather than assuming readable server stacks. If the webpack build omits them, add `experimental: { serverSourceMaps: true }` to `next.config`. Also list `@opentelemetry/auto-instrumentations-node` in `serverExternalPackages` so Next does not bundle the instrumentation registry or warn about its optional transports.+### Per-language notes- **Go**: use the framework's OTel middleware. `go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin`, `github.com/riandyrn/otelchi` (a community package, and pass `otelchi.WithChiRoutes(r)` or it reports raw URLs), `github.com/gofiber/contrib/otelfiber/v2`. All three set `http.route` from the matched route pattern. Exporter: `otlptracehttp.WithEndpointURL(...)` + `WithHeaders`. Two Go-only traps:@@ -434,7 +639,9 @@ Frontend and mobile projects do NOT use OTel; they use the Traceway SDKs reportiFor the per-framework init code (plain JS, React, Vue, Svelte/SvelteKit, jQuery), the shared SDK options, error filtering, custom attributes, distributed tracing, and the full debug-ID + source map pipeline, read `frontend-js.md` in this skill directory. Online docs: https://docs.tracewayapp.com/client/react (or `vue`, `svelte`, `jquery`, `js-sdk`).-**Full-stack JS** (Next.js, SvelteKit, Remix): only when "Analyze the Architecture" confirmed the framework's server actually serves the app in production. A frontend-only deployment gets just the browser pieces above; a separate backend follows "Backend OTel Setup". When it is genuinely full-stack, integrate both sides under the two confirmed projects: server side follows "Backend OTel Setup" with the backend project's token, and browser side follows the three pieces above with the frontend project's token.+**Full-stack JS** (Next.js, SvelteKit, Remix): only when "Analyze the Architecture" confirmed the framework's server actually serves the app in production. A frontend-only deployment gets just the browser pieces above; a separate backend follows "Backend OTel Setup". When it is genuinely full-stack, integrate both sides under the two confirmed projects: server side follows "Backend OTel Setup" with the backend project's token, and browser side follows the three pieces above with the frontend project's token. For Next.js specifically, use the `instrumentation.ts` framework hook in the "Next.js server exception" above; never apply the generic Node preload to it.++For the Next.js **browser** build, `@tracewayapp/bundler-plugin` currently has a webpack entry point, not a Turbopack one. Set `productionBrowserSourceMaps: true`, add `TracewayDebugIdsWebpackPlugin` only when `!isServer && !dev` (the plugin is production-only and must not replace Next's development source-map mode), and make the production build run `next build --webpack` (Next.js 16 defaults to Turbopack, which otherwise ignores this plugin). After building, confirm client `.js` files contain `//# debugId=` and their `.js.map` siblings contain `debugId`, then upload `.next/static/chunks` with the React project's source-map upload token.**Mobile**, always the platform SDK, never OTel:@@ -478,6 +685,8 @@ Metrics arrive within ~60s under their hostmetrics names (`system.cpu.utilizatioEvery dashboard page named below is at `<instance>/<page>`: `/endpoints`, `/issues`, `/tasks`, `/ai-traces`, `/logs`, `/dashboards`. Set the time picker to the last 15 minutes before reading any of them. Verify each project independently and finish with a project-to-component summary.+When the CLI applied the plan, the local env files hold real values, so run local verification now rather than deferring it. Deployment environments are verified only after the user completes the website's Next Steps panel; re-state which variables must exist there before that verification can pass.+1. **Backend project**- Run `curl <app>/api/users/1`, then `/2`, then `/3`, and open `/endpoints`. Exactly one row, `GET /api/users/:id`, with non-zero status codes. Three rows means `http.route` is not being set. Fix that before checking anything else.- Two results that look broken but are not: a request to a URL matching no route arrives as `UNMATCHED`, not as the URL you typed; and if the project has "drop healthy healthchecks" enabled, successful `/health` requests are discarded on ingest, so never use a healthcheck route as the smoke test.@@ -506,3 +715,4 @@ Every dashboard page named below is at `<instance>/<page>`: `/endpoints`, `/issutraceway metrics query --name system.cpu.utilization --since 15m```Tasks and AI traces have no `list` subcommand, only `show <id>`, so check those two on `/tasks` and `/ai-traces` in the dashboard.+6. **Hand the user a test drive.** After your own verification, finish by telling the user exactly how to see the connection working themselves: two or three copy-paste actions against THEIR app, each paired with the Traceway page it lands on. For example: hit one real parametrized endpoint a few times (`curl <their-app>/api/users/1`, `/2`, `/3` becomes a single row on `/endpoints` within seconds), trigger their app's error path or a deliberate test exception (appears on `/issues` linked to the failing request), and run or wait for one background job (`/tasks`). Use their actual routes and commands, remind them to set the dashboard time picker to the last 15 minutes, and note that approval already dropped them on the right project's dashboard.diff --git a/skills/traceway-setup/dashboard-project-setup.md b/skills/traceway-setup/dashboard-project-setup.mdindex f5685693..146eafb7 100644--- a/skills/traceway-setup/dashboard-project-setup.md+++ b/skills/traceway-setup/dashboard-project-setup.md@@ -1,6 +1,6 @@-# Create the Traceway Project Structure+# Manual Fallback: Create the Project Structure in the Dashboard UI-Use this guide only after "Analyze the Architecture" produced a repository inventory and "Propose and Confirm the Project Map" was confirmed by the user. Tailor every instruction to the detected components; do not hand the user a generic list of every supported platform.+Use this guide only when the setup-token + CLI path in SKILL.md Step 3 is unavailable or the user prefers clicking through the UI, and only after "Analyze the Architecture" produced a repository inventory and "Propose and Confirm the Project Map" was confirmed by the user. Tailor every instruction to the detected components; do not hand the user a generic list of every supported platform. On this path ingest tokens never transit chat: the user saves each token straight into their env file or secret store.## 1. Establish the Dashboard@@ -10,7 +10,7 @@ Ask whether the user uses Traceway Cloud or a self-hosted instance only if the r- Traceway Cloud registration: https://cloud.tracewayapp.com/register- Self-hosted dashboard: `https://<their-instance>`-If the user does not have an account, direct them to registration and wait for them to finish account and organization setup. Do not ask for dashboard credentials.+If the user does not have an account, direct them to registration and wait. Registration has two steps: step 1 creates the account and organization; step 2 offers "AI" and "Manual" project setup. For this manual path, tell the user to pick **Manual** on step 2 and enter the confirmed project rows right there (name plus framework per row, "Add another project" for more); each created project's token is shown for saving under the planned variable name. A user who already registered and skipped step 2 gets the same editor on `<their-instance>/setup` under the Manual tab. Do not ask for dashboard credentials.## 2. Present the Creation Checklist@@ -30,7 +30,11 @@ Explain the boundary in one paragraph: the backend project intentionally combine## 3. Create Each Project-For each checklist row, walk the user through the current dashboard UI:+Two equivalent UI paths; pick whichever matches where the user is:++**During onboarding** (registration step 2, or `<instance>/setup`): select the **Manual** tab, enter one row per checklist entry (project name plus framework), use "Add another project" for more rows, then select **New Projects**. Save each project's token under the planned environment-variable name.++**From the running dashboard**, for each checklist row:1. Open the Traceway dashboard.2. Open the project selector in the header.