Skip to content

The only tool you need to know what is happening and how to fix it.

Auth (getting ready for an mcp) (#255)

narrow-adventure3fb3e0dfa1eb
diff --git a/CLAUDE.md b/CLAUDE.md
index 53e1ea0e..c3209066 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -239,6 +239,7 @@ if err != nil {
### Environment Variables (Backend)
```
JWT_SECRET=<min 32 char secret for JWT signing>
+APP_BASE_URL= # public origin of this server (e.g. https://traceway.example.com). Used as the OAuth issuer / device verification URL and SSO redirect base. If unset, the device-auth + well-known endpoints derive it per-request from the Host / X-Forwarded-* headers; set it explicitly behind a proxy that doesn't forward Host.
CLICKHOUSE_SERVER=localhost:9000
CLICKHOUSE_DATABASE=traceway
CLICKHOUSE_USERNAME=default
@@ -287,6 +288,13 @@ Two-tier system:
1. **Client Auth**: Project bearer tokens (SDK telemetry via `Authorization: Bearer <project_token>`)
2. **App Auth**: JWT-based user authentication (dashboard via `Authorization: Bearer <jwt_token>`)
+**App Auth credentials.** `UseAppAuth` accepts three credential shapes on the `Authorization: Bearer` header:
+- **Dashboard JWT** — issued by `/api/login` / SSO (7-day expiry).
+- **Personal access token (PAT)** — opaque `twp_`-prefixed token; looked up by SHA-256 hash in `personal_access_tokens`, resolves to its user. Created/listed/revoked from the account page (`/api/personal-access-tokens*`). Non-expiring or with an optional TTL; `last_used_at` is touched (throttled to 1/min, off the request path).
+- **Device-flow access token** — a short-lived (15-min) JWT minted by the CLI's OAuth device flow.
+
+**CLI / OAuth device flow** (`backend/app/services/authserver/`, controllers `device_auth.controller.go` / `wellknown.controller.go` / `pat.controller.go`): RFC 8628 device authorization grant plus rotating refresh tokens. `traceway login` (default) → `POST /api/auth/device/authorize` (client_id allowlisted, per-IP rate-limited, opportunistically prunes expired rows) → user approves at `/device` → the CLI polls `POST /api/auth/device/token` (grant `device_code`; `/api/auth/token` is an equivalent alias) which issues a 15-min access token + 90-day rotating refresh token (family-tracked in `refresh_tokens`). Refresh (`grant_type=refresh_token`) rotates the token atomically and revokes the whole family on genuine reuse; within a 30s grace window a benign concurrent retry is answered with the same rotated token set (from an in-memory rotation cache) instead of `invalid_grant`. `POST /api/auth/logout` revokes a family server-side. Tokens are stored SHA-256-hashed. The grant endpoints **self-manage their transactions** via `db.ExecuteTransaction` (not `middleware.Transactional`) because OAuth returns 400 for normal flow control (`authorization_pending`, reuse-revoke) and those side effects must still commit. `/.well-known/oauth-authorization-server` and `/.well-known/oauth-protected-resource` are served at the **origin root** (registered in `cmd/run.go`, not the `/api` group) per RFC 8414 / 9728. The metadata currently advertises only the `device_code` + `refresh_token` grants; authorization-code + PKCE is a future addition for the MCP server.
+
---
## Frontend (`/frontend`)
@@ -553,6 +561,26 @@ backend/
| GET | `/api/password-reset/:token` | None | Validate reset token |
| POST | `/api/password-reset/:token` | None | Reset password with token |
+**CLI Device Auth & OAuth** (see the Authentication section above)
+| Method | Endpoint | Auth | Purpose |
+|--------|----------|------|---------|
+| POST | `/api/auth/device/authorize` | None | Start device flow; returns device/user code + verification URL |
+| POST | `/api/auth/device/token` | None | Poll for the token (grant `device_code`); also accepts `refresh_token` |
+| POST | `/api/auth/token` | None | Token endpoint: `device_code` or `refresh_token` grant (JSON or form-encoded) |
+| POST | `/api/auth/logout` | None | Revoke the presented refresh token's family (idempotent) |
+| GET | `/api/device` | App | Look up a user code for the approval screen |
+| POST | `/api/device/approve` | App | Approve a pending device authorization (tokens carry only the approving user's own role, so no write guard) |
+| POST | `/api/device/deny` | App | Deny a pending device authorization |
+| GET | `/.well-known/oauth-authorization-server` | None | RFC 8414 metadata (served at origin root, not `/api`) |
+| GET | `/.well-known/oauth-protected-resource` | None | RFC 9728 metadata (served at origin root, not `/api`) |
+
+**Personal Access Tokens**
+| Method | Endpoint | Auth | Purpose |
+|--------|----------|------|---------|
+| POST | `/api/personal-access-tokens` | App | Create a PAT (returns the `twp_` token once) |
+| GET | `/api/personal-access-tokens` | App | List the current user's active PATs |
+| DELETE | `/api/personal-access-tokens/:id` | App | Revoke a PAT |
+
**Projects**
| Method | Endpoint | Auth | Purpose |
|--------|----------|------|---------|
@@ -746,7 +774,9 @@ for _, item := range items {
#### Data Retention
-Retention is handled in three different ways depending on the deployment.
+Retention is handled in several different ways depending on the deployment.
+
+**0. Main-DB auth prune — `retention.Start` worker** (`backend/app/retention/auth_tokens.go` + `oauth_sessions.go`, sharing `startDBPruneWorker` in `prune_worker.go`). Runs in **all modes** (Postgres and SQLite) against `db.DB`: once at startup, then every 24h, deleting expired/consumed auth rows. `auth_tokens` prunes expired `device_authorizations` (also pruned opportunistically on every `/api/auth/device/authorize` call, so the daily worker is a backstop there), `refresh_tokens` that are expired, revoked, or used more than 30 days ago (used rows are kept a month for replay detection, then dropped to bound per-user growth), plus revoked-or-expired `personal_access_tokens` (PAT expiry was otherwise only enforced lazily at read time). `oauth_sessions` prunes expired SSO login sessions. No env var — always on. (Refresh-token families and PATs also have explicit revoke paths: `POST /api/auth/logout` and the account PAT UI.)
**1. ClickHouse — `TTL` clauses on the table itself.** Only a few tables have a TTL; everything else is kept indefinitely (operators can drop monthly partitions manually if needed).
diff --git a/backend/app/controllers/device_auth.controller.go b/backend/app/controllers/device_auth.controller.go
new file mode 100644
index 00000000..1277a434
--- /dev/null
+++ b/backend/app/controllers/device_auth.controller.go
@@ -0,0 +1,201 @@
+package controllers
+
+import (
+ "errors"
+ "net/http"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ 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"
+ "github.com/tracewayapp/traceway/backend/app/services/authserver"
+)
+
+type deviceAuthController struct{}
+
+func (c *deviceAuthController) Authorize(ctx *gin.Context) {
+ setTokenResponseHeaders(ctx)
+
+ var req models.DeviceAuthorizeRequest
+ // ShouldBind honors both JSON (the CLI) and form encoding (RFC 8628 §3.4).
+ // client_id is optional, so a malformed/absent body just falls through to the
+ // default client — CreateDeviceAuth substitutes it — rather than 400ing.
+ _ = ctx.ShouldBind(&req)
+
+ resp, err := authserver.CreateDeviceAuth(req.ClientId, authserver.IssuerBaseURLFromRequest(ctx))
+ if err != nil {
+ if errors.Is(err, authserver.ErrUnknownClient) {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid_client"})
+ return
+ }
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("device authorize: %w", err))
+ return
+ }
+ ctx.JSON(http.StatusOK, resp)
+}
+
+func (c *deviceAuthController) Token(ctx *gin.Context) {
+ setTokenResponseHeaders(ctx)
+
+ var req models.TokenRequest
+ // ShouldBind honors both JSON (the CLI) and application/x-www-form-urlencoded
+ // (RFC 6749 §3.2 / RFC 8628 §3.4, which standard OAuth clients send).
+ if err := ctx.ShouldBind(&req); err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid_request"})
+ return
+ }
+
+ switch req.GrantType {
+ case "device_code", "urn:ietf:params:oauth:grant-type:device_code":
+ ts, err := authserver.PollDeviceToken(req.DeviceCode)
+ if err != nil {
+ writeOAuthGrantError(ctx, err)
+ return
+ }
+ ctx.JSON(http.StatusOK, ts)
+ case "refresh_token":
+ ts, err := authserver.RotateRefresh(req.RefreshToken)
+ if err != nil {
+ writeOAuthGrantError(ctx, err)
+ return
+ }
+ ctx.JSON(http.StatusOK, ts)
+ default:
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "unsupported_grant_type"})
+ }
+}
+
+// Logout revokes the entire refresh-token family the presented token belongs
+// to, so `traceway logout` actually invalidates the session server-side. It is
+// intentionally unauthenticated (the refresh token is the credential) and
+// always returns 200 — it never reveals whether the token existed.
+func (c *deviceAuthController) Logout(ctx *gin.Context) {
+ var req models.TokenRequest
+ _ = ctx.ShouldBind(&req)
+
+ if req.RefreshToken != "" {
+ if err := authserver.RevokeByToken(req.RefreshToken); err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("logout revoke: %w", err))
+ return
+ }
+ }
+ ctx.JSON(http.StatusOK, gin.H{"status": "ok"})
+}
+
+func (c *deviceAuthController) Lookup(ctx *gin.Context) {
+ userCode := ctx.Query("user_code")
+ if userCode == "" {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "user_code is required"})
+ return
+ }
+
+ da, err := repositories.DeviceAuthorizationRepository.FindByUserCode(db.DB, userCode)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("device lookup: %w", err))
+ return
+ }
+ if da == nil {
+ ctx.JSON(http.StatusNotFound, gin.H{"error": "not_found"})
+ return
+ }
+ if time.Now().After(da.ExpiresAt) {
+ ctx.JSON(http.StatusGone, gin.H{"error": "expired"})
+ return
+ }
+
+ ctx.JSON(http.StatusOK, models.DeviceLookupResponse{
+ UserCode: da.UserCode,
+ Status: da.Status,
+ ClientName: clientDisplayName(da.ClientId),
+ RequestedAt: da.CreatedAt,
+ ExpiresAt: da.ExpiresAt,
+ })
+}
+
+func (c *deviceAuthController) Approve(ctx *gin.Context) {
+ c.resolve(ctx, true)
+}
+
+func (c *deviceAuthController) Deny(ctx *gin.Context) {
+ c.resolve(ctx, false)
+}
+
+func (c *deviceAuthController) resolve(ctx *gin.Context, approve bool) {
+ tx := db.GetTx(ctx)
+ userId := middleware.GetUserId(ctx)
+
+ var req models.DeviceApproveRequest
+ if err := ctx.ShouldBindJSON(&req); err != nil || req.UserCode == "" {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "user_code is required"})
+ return
+ }
+
+ var err error
+ if approve {
+ err = authserver.Approve(tx, req.UserCode, userId)
+ } else {
+ err = authserver.Deny(tx, req.UserCode)
+ }
+ if err != nil {
+ if errors.Is(err, authserver.ErrDeviceNotFound) {
+ ctx.JSON(http.StatusNotFound, gin.H{"error": "not_found"})
+ return
+ }
+ if errors.Is(err, authserver.ErrDeviceExpired) {
+ ctx.JSON(http.StatusGone, gin.H{"error": "expired"})
+ return
+ }
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("device resolve: %w", err))
+ return
+ }
+
+ status := "approved"
+ if !approve {
+ status = "denied"
+ }
+ ctx.JSON(http.StatusOK, gin.H{"status": status})
+}
+
+func writeOAuthGrantError(ctx *gin.Context, err error) {
+ switch {
+ case errors.Is(err, authserver.ErrAuthorizationPending):
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "authorization_pending"})
+ case errors.Is(err, authserver.ErrSlowDown):
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "slow_down"})
+ case errors.Is(err, authserver.ErrAccessDenied):
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "access_denied"})
+ case errors.Is(err, authserver.ErrExpiredToken):
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "expired_token"})
+ case errors.Is(err, authserver.ErrInvalidGrant):
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "invalid_grant"})
+ default:
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("token grant: %w", err))
+ }
+}
+
+// setTokenResponseHeaders marks OAuth responses uncacheable, as RFC 6749 §5.1
+// and RFC 8628 §3.2 require for responses that carry tokens or device codes.
+// It applies to error responses from the same endpoints too.
+func setTokenResponseHeaders(ctx *gin.Context) {
+ ctx.Header("Cache-Control", "no-store")
+ ctx.Header("Pragma", "no-cache")
+}
+
+// clientDisplayName never echoes an unrecognized client_id: the approval page
+// renders this as the trusted requester name.
+func clientDisplayName(clientId string) string {
+ switch clientId {
+ case "traceway-cli", "":
+ return "Traceway CLI"
+ case "traceway-mcp":
+ return "Traceway MCP"
+ default:
+ return "An unrecognized application"
+ }
+}
+
+var DeviceAuthController = deviceAuthController{}
diff --git a/backend/app/controllers/pat.controller.go b/backend/app/controllers/pat.controller.go
new file mode 100644
index 00000000..b2b74161
--- /dev/null
+++ b/backend/app/controllers/pat.controller.go
@@ -0,0 +1,101 @@
+package controllers
+
+import (
+ "net/http"
+ "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"
+ "github.com/tracewayapp/traceway/backend/app/services/authserver"
+)
+
+type patController struct{}
+
+func (c *patController) Create(ctx *gin.Context) {
+ tx := db.GetTx(ctx)
+ userId := middleware.GetUserId(ctx)
+
+ var req models.CreatePATRequest
+ if err := ctx.ShouldBindJSON(&req); err != nil {
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
+ return
+ }
+ name := strings.TrimSpace(req.Name)
+ if name == "" {
+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Name is required"})
+ return
+ }
+ if utf8.RuneCountInString(name) > 100 {
+ ctx.JSON(http.StatusUnprocessableEntity, gin.H{"error": "Name must be 100 characters or fewer"})
+ return
+ }
+
+ token := authserver.NewPATToken()
+ id := uuid.New().String()
+ prefix := patPrefix(token)
+
+ var expiresAt *time.Time
+ if req.ExpiresInDays != nil && *req.ExpiresInDays > 0 {
+ t := time.Now().Add(time.Duration(*req.ExpiresInDays) * 24 * time.Hour).UTC()
+ expiresAt = &t
+ }
+
+ if err := repositories.PersonalAccessTokenRepository.Create(tx, id, token, prefix, userId, name, expiresAt); err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("create pat: %w", err))
+ return
+ }
+
+ ctx.JSON(http.StatusCreated, models.CreatePATResponse{
+ Id: id,
+ Name: name,
+ Prefix: prefix,
+ Token: token,
+ CreatedAt: time.Now().UTC(),
+ ExpiresAt: expiresAt,
+ })
+}
+
+func (c *patController) List(ctx *gin.Context) {
+ userId := middleware.GetUserId(ctx)
+
+ tokens, err := repositories.PersonalAccessTokenRepository.ListByUser(db.DB, userId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("list pats: %w", err))
+ return
+ }
+ ctx.JSON(http.StatusOK, tokens)
+}
+
+func (c *patController) Revoke(ctx *gin.Context) {
+ tx := db.GetTx(ctx)
+ userId := middleware.GetUserId(ctx)
+ id := ctx.Param("id")
+
+ rows, err := repositories.PersonalAccessTokenRepository.Revoke(tx, id, userId)
+ if err != nil {
+ ctx.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("revoke pat: %w", err))
+ return
+ }
+ if rows == 0 {
+ ctx.JSON(http.StatusNotFound, gin.H{"error": "not_found"})
+ return
+ }
+ ctx.JSON(http.StatusOK, gin.H{"status": "revoked"})
+}
+
+func patPrefix(token string) string {
+ if len(token) <= 12 {
+ return token
+ }
+ return token[:12]
+}
+
+var PATController = patController{}
diff --git a/backend/app/controllers/routes.go b/backend/app/controllers/routes.go
index 0da38e6b..c19b4098 100644
--- a/backend/app/controllers/routes.go
+++ b/backend/app/controllers/routes.go
@@ -1,6 +1,8 @@
package controllers
import (
+ "time"
+
"github.com/tracewayapp/traceway/backend/app/config"
"github.com/tracewayapp/traceway/backend/app/controllers/clientcontrollers"
"github.com/tracewayapp/traceway/backend/app/controllers/otelcontrollers"
@@ -129,6 +131,22 @@ func RegisterControllers(router *gin.RouterGroup) {
router.GET("/auth/callback/:provider", middleware.Transactional, OAuthController.Callback)
router.POST("/auth/finish-setup", middleware.UseAppAuth, middleware.Transactional, OAuthController.FinishSetup)
+ router.POST("/auth/device/authorize", middleware.RateLimitPerIP(10, time.Minute), DeviceAuthController.Authorize)
+ router.POST("/auth/device/token", DeviceAuthController.Token)
+ router.POST("/auth/token", DeviceAuthController.Token)
+ router.POST("/auth/logout", DeviceAuthController.Logout)
+ router.GET("/device", middleware.UseAppAuth, DeviceAuthController.Lookup)
+ router.POST("/device/approve", middleware.UseAppAuth, middleware.Transactional, DeviceAuthController.Approve)
+ router.POST("/device/deny", middleware.UseAppAuth, middleware.Transactional, DeviceAuthController.Deny)
+
+ router.POST("/personal-access-tokens", middleware.UseAppAuth, middleware.Transactional, PATController.Create)
+ router.GET("/personal-access-tokens", middleware.UseAppAuth, PATController.List)
+ router.DELETE("/personal-access-tokens/:id", middleware.UseAppAuth, middleware.Transactional, PATController.Revoke)
+
+ // 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.
+
if config.Config.CloudMode != "true" {
router.GET("/has-organizations", middleware.Transactional, AuthController.HasOrganizations)
}
diff --git a/backend/app/controllers/wellknown.controller.go b/backend/app/controllers/wellknown.controller.go
new file mode 100644
index 00000000..a9870354
--- /dev/null
+++ b/backend/app/controllers/wellknown.controller.go
@@ -0,0 +1,36 @@
+package controllers
+
+import (
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/tracewayapp/traceway/backend/app/services/authserver"
+)
+
+type wellKnownController struct{}
+
+func (c *wellKnownController) AuthorizationServer(ctx *gin.Context) {
+ issuer := authserver.IssuerBaseURLFromRequest(ctx)
+ // response_types_supported is REQUIRED by RFC 8414 even though neither
+ // supported grant uses the authorization endpoint; "none" keeps spec-strict
+ // clients (e.g. the MCP SDK's metadata schema) from rejecting the document.
+ ctx.JSON(http.StatusOK, gin.H{
+ "issuer": issuer,
+ "token_endpoint": issuer + "/api/auth/token",
+ "device_authorization_endpoint": issuer + "/api/auth/device/authorize",
+ "grant_types_supported": []string{"urn:ietf:params:oauth:grant-type:device_code", "refresh_token"},
+ "response_types_supported": []string{"none"},
+ "token_endpoint_auth_methods_supported": []string{"none"},
+ })
+}
+
+func (c *wellKnownController) ProtectedResource(ctx *gin.Context) {
+ issuer := authserver.IssuerBaseURLFromRequest(ctx)
+ ctx.JSON(http.StatusOK, gin.H{
+ "resource": issuer,
+ "authorization_servers": []string{issuer},
+ })
+}
+
+var WellKnownController = wellKnownController{}
diff --git a/backend/app/middleware/rate_limit.middleware.go b/backend/app/middleware/rate_limit.middleware.go
new file mode 100644
index 00000000..4307d03c
--- /dev/null
+++ b/backend/app/middleware/rate_limit.middleware.go
@@ -0,0 +1,49 @@
+package middleware
+
+import (
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/gin-gonic/gin"
+)
+
+// RateLimitPerIP returns a fixed-window per-IP rate limiter for unauthenticated
+// endpoints that persist state per request (e.g. the device-authorize endpoint,
+// which inserts a main-DB row per call). Buckets live in memory; stale ones are
+// swept on each request, so the map stays bounded by the number of distinct IPs
+// seen within one window.
+func RateLimitPerIP(maxRequests int, window time.Duration) gin.HandlerFunc {
+ type bucket struct {
+ windowStart time.Time
+ count int
+ }
+ var mu sync.Mutex
+ buckets := map[string]*bucket{}
+
+ return func(c *gin.Context) {
+ now := time.Now()
+
+ mu.Lock()
+ for ip, b := range buckets {
+ if now.Sub(b.windowStart) > window {
+ delete(buckets, ip)
+ }
+ }
+ ip := c.ClientIP()
+ b, ok := buckets[ip]
+ if !ok {
+ b = &bucket{windowStart: now}
+ buckets[ip] = b
+ }
+ b.count++
+ count := b.count
+ mu.Unlock()
+
+ if count > maxRequests {
+ c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"error": "slow_down"})
+ return
+ }
+ c.Next()
+ }
+}
diff --git a/backend/app/middleware/use_app_auth.middleware.go b/backend/app/middleware/use_app_auth.middleware.go
index 59b8a069..baa7f66c 100644
--- a/backend/app/middleware/use_app_auth.middleware.go
+++ b/backend/app/middleware/use_app_auth.middleware.go
@@ -1,9 +1,15 @@
package middleware
import (
- "github.com/tracewayapp/traceway/backend/app/services"
+ "database/sql"
"net/http"
"strings"
+ "time"
+
+ "github.com/tracewayapp/traceway/backend/app/db"
+ "github.com/tracewayapp/traceway/backend/app/repositories"
+ "github.com/tracewayapp/traceway/backend/app/services"
+ traceway "go.tracewayapp.com"
"github.com/gin-gonic/gin"
)
@@ -11,7 +17,7 @@ import (
const UserIdContextKey = "userId"
const UserEmailContextKey = "userEmail"
-var UseAppAuth func(c *gin.Context)
+const patTouchInterval = time.Minute
func InitUseAppAuth() {
UseAppAuth = func(c *gin.Context) {
@@ -24,6 +30,23 @@ func InitUseAppAuth() {
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
+ if strings.HasPrefix(tokenString, "twp_") {
+ pat, err := repositories.PersonalAccessTokenRepository.FindActiveByToken(db.DB, tokenString)
+ if err != nil {
+ c.AbortWithError(http.StatusInternalServerError, traceway.NewStackTraceErrorf("pat lookup failed: %w", err))
+ return
+ }
+ if pat == nil {
+ c.AbortWithStatus(http.StatusUnauthorized)
+ return
+ }
+ c.Set(UserIdContextKey, pat.UserId)
+ c.Set(UserEmailContextKey, pat.Email)
+ touchPersonalAccessToken(pat)
+ c.Next()
+ return
+ }
+
claims, err := services.ValidateToken(tokenString)
if err != nil {
c.AbortWithStatus(http.StatusUnauthorized)
@@ -37,6 +60,22 @@ func InitUseAppAuth() {
}
}
+func touchPersonalAccessToken(pat *repositories.ActivePAT) {
+ now := time.Now()
+ if pat.LastUsedAt != nil && now.Sub(*pat.LastUsedAt) < patTouchInterval {
+ return
+ }
+
+ go func() {
+ defer traceway.Recover()
+ _, _ = db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {
+ return struct{}{}, repositories.PersonalAccessTokenRepository.TouchLastUsed(tx, pat.Id, now)
+ })
+ }()
+}
+
+var UseAppAuth func(c *gin.Context)
+
func GetUserId(c *gin.Context) int {
if id, exists := c.Get(UserIdContextKey); exists {
return id.(int)
diff --git a/backend/app/migrations/pg/0042_create_device_authorizations.up.sql b/backend/app/migrations/pg/0042_create_device_authorizations.up.sql
new file mode 100644
index 00000000..e04712c3
--- /dev/null
+++ b/backend/app/migrations/pg/0042_create_device_authorizations.up.sql
@@ -0,0 +1,11 @@
+CREATE TABLE IF NOT EXISTS device_authorizations (
+ device_code_hash TEXT PRIMARY KEY,
+ user_code TEXT NOT NULL UNIQUE,
+ client_id TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'pending',
+ user_id INTEGER REFERENCES users(id),
+ interval_seconds INTEGER NOT NULL DEFAULT 5,
+ last_polled_at TIMESTAMPTZ,
+ expires_at TIMESTAMPTZ NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL
+)
diff --git a/backend/app/migrations/pg/0043_create_refresh_tokens.up.sql b/backend/app/migrations/pg/0043_create_refresh_tokens.up.sql
new file mode 100644
index 00000000..d24a2fc2
--- /dev/null
+++ b/backend/app/migrations/pg/0043_create_refresh_tokens.up.sql
@@ -0,0 +1,10 @@
+CREATE TABLE IF NOT EXISTS refresh_tokens (
+ token_hash TEXT PRIMARY KEY,
+ family_id TEXT NOT NULL,
+ user_id INTEGER NOT NULL REFERENCES users(id),
+ client_id TEXT NOT NULL,
+ revoked BOOLEAN NOT NULL DEFAULT FALSE,
+ used BOOLEAN NOT NULL DEFAULT FALSE,
+ expires_at TIMESTAMPTZ NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL
+)
diff --git a/backend/app/migrations/pg/0044_create_refresh_tokens_family_idx.up.sql b/backend/app/migrations/pg/0044_create_refresh_tokens_family_idx.up.sql
new file mode 100644
index 00000000..2c8a5ec4
--- /dev/null
+++ b/backend/app/migrations/pg/0044_create_refresh_tokens_family_idx.up.sql
@@ -0,0 +1 @@
+CREATE INDEX IF NOT EXISTS idx_refresh_tokens_family_id ON refresh_tokens(family_id)
diff --git a/backend/app/migrations/pg/0045_create_personal_access_tokens.up.sql b/backend/app/migrations/pg/0045_create_personal_access_tokens.up.sql
new file mode 100644
index 00000000..3279666d
--- /dev/null
+++ b/backend/app/migrations/pg/0045_create_personal_access_tokens.up.sql
@@ -0,0 +1,11 @@
+CREATE TABLE IF NOT EXISTS personal_access_tokens (
+ id TEXT PRIMARY KEY,
+ token_hash TEXT NOT NULL UNIQUE,
+ prefix TEXT NOT NULL,
+ user_id INTEGER NOT NULL REFERENCES users(id),
+ name TEXT NOT NULL,
+ last_used_at TIMESTAMPTZ,
+ expires_at TIMESTAMPTZ,
+ revoked BOOLEAN NOT NULL DEFAULT FALSE,
+ created_at TIMESTAMPTZ NOT NULL
+)
diff --git a/backend/app/migrations/pg/0046_create_personal_access_tokens_user_idx.up.sql b/backend/app/migrations/pg/0046_create_personal_access_tokens_user_idx.up.sql
new file mode 100644
index 00000000..9ea693a6
--- /dev/null
+++ b/backend/app/migrations/pg/0046_create_personal_access_tokens_user_idx.up.sql
@@ -0,0 +1 @@
+CREATE INDEX IF NOT EXISTS idx_personal_access_tokens_user_id ON personal_access_tokens(user_id)
diff --git a/backend/app/migrations/pg/0047_add_used_at_to_refresh_tokens.up.sql b/backend/app/migrations/pg/0047_add_used_at_to_refresh_tokens.up.sql
new file mode 100644
index 00000000..b835ef2b
--- /dev/null
+++ b/backend/app/migrations/pg/0047_add_used_at_to_refresh_tokens.up.sql
@@ -0,0 +1 @@
+ALTER TABLE refresh_tokens ADD COLUMN used_at TIMESTAMPTZ
diff --git a/backend/app/migrations/sqlite/0016_create_device_authorizations.up.sql b/backend/app/migrations/sqlite/0016_create_device_authorizations.up.sql
new file mode 100644
index 00000000..160cd645
--- /dev/null
+++ b/backend/app/migrations/sqlite/0016_create_device_authorizations.up.sql
@@ -0,0 +1,11 @@
+CREATE TABLE IF NOT EXISTS device_authorizations (
+ device_code_hash TEXT PRIMARY KEY,
+ user_code TEXT NOT NULL UNIQUE,
+ client_id TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'pending',
+ user_id INTEGER,
+ interval_seconds INTEGER NOT NULL DEFAULT 5,
+ last_polled_at DATETIME,
+ expires_at DATETIME NOT NULL,
+ created_at DATETIME NOT NULL
+);
diff --git a/backend/app/migrations/sqlite/0017_create_refresh_tokens.up.sql b/backend/app/migrations/sqlite/0017_create_refresh_tokens.up.sql
new file mode 100644
index 00000000..7c5b5832
--- /dev/null
+++ b/backend/app/migrations/sqlite/0017_create_refresh_tokens.up.sql
@@ -0,0 +1,12 @@
+CREATE TABLE IF NOT EXISTS refresh_tokens (
+ token_hash TEXT PRIMARY KEY,
+ family_id TEXT NOT NULL,
+ user_id INTEGER NOT NULL,
+ client_id TEXT NOT NULL,
+ revoked INTEGER NOT NULL DEFAULT 0,
+ used INTEGER NOT NULL DEFAULT 0,
+ expires_at DATETIME NOT NULL,
+ created_at DATETIME NOT NULL
+);
+
+CREATE INDEX IF NOT EXISTS idx_refresh_tokens_family_id ON refresh_tokens(family_id);
diff --git a/backend/app/migrations/sqlite/0018_create_personal_access_tokens.up.sql b/backend/app/migrations/sqlite/0018_create_personal_access_tokens.up.sql
new file mode 100644
index 00000000..cbf92597
--- /dev/null
+++ b/backend/app/migrations/sqlite/0018_create_personal_access_tokens.up.sql
@@ -0,0 +1,13 @@
+CREATE TABLE IF NOT EXISTS personal_access_tokens (
+ id TEXT PRIMARY KEY,
+ token_hash TEXT NOT NULL UNIQUE,
+ prefix TEXT NOT NULL,
+ user_id INTEGER NOT NULL,
+ name TEXT NOT NULL,
+ last_used_at DATETIME,
+ expires_at DATETIME,
+ revoked INTEGER NOT NULL DEFAULT 0,
+ created_at DATETIME NOT NULL
+);
+
+CREATE INDEX IF NOT EXISTS idx_personal_access_tokens_user_id ON personal_access_tokens(user_id);
diff --git a/backend/app/migrations/sqlite/0019_add_used_at_to_refresh_tokens.up.sql b/backend/app/migrations/sqlite/0019_add_used_at_to_refresh_tokens.up.sql
new file mode 100644
index 00000000..f93c1acc
--- /dev/null
+++ b/backend/app/migrations/sqlite/0019_add_used_at_to_refresh_tokens.up.sql
@@ -0,0 +1 @@
+ALTER TABLE refresh_tokens ADD COLUMN used_at DATETIME
diff --git a/backend/app/models/auth_token.model.go b/backend/app/models/auth_token.model.go
new file mode 100644
index 00000000..0c94a119
--- /dev/null
+++ b/backend/app/models/auth_token.model.go
@@ -0,0 +1,90 @@
+package models
+
+import "time"
+
+type DeviceAuthorization struct {
+ DeviceCodeHash string
+ UserCode string
+ ClientId string
+ Status string
+ UserId *int
+ IntervalSeconds int
+ LastPolledAt *time.Time
+ ExpiresAt time.Time
+ CreatedAt time.Time
+}
+
+type RefreshToken struct {
+ TokenHash string
+ FamilyId string
+ UserId int
+ ClientId string
+ Revoked bool
+ Used bool
+ UsedAt *time.Time
+ ExpiresAt time.Time
+ CreatedAt time.Time
+}
+
+type PersonalAccessToken struct {
+ Id string `json:"id"`
+ Prefix string `json:"prefix"`
+ Name string `json:"name"`
+ LastUsedAt *time.Time `json:"lastUsedAt"`
+ ExpiresAt *time.Time `json:"expiresAt"`
+ CreatedAt time.Time `json:"createdAt"`
+}
+
+type DeviceAuthorizeRequest struct {
+ ClientId string `json:"client_id" form:"client_id"`
+}
+
+type DeviceAuthorizeResponse struct {
+ DeviceCode string `json:"device_code"`
+ UserCode string `json:"user_code"`
+ VerificationURI string `json:"verification_uri"`
+ VerificationURIComplete string `json:"verification_uri_complete"`
+ ExpiresIn int `json:"expires_in"`
+ Interval int `json:"interval"`
+}
+
+type TokenRequest struct {
+ GrantType string `json:"grant_type" form:"grant_type"`
+ DeviceCode string `json:"device_code" form:"device_code"`
+ RefreshToken string `json:"refresh_token" form:"refresh_token"`
+ ClientId string `json:"client_id" form:"client_id"`
+}
+
+type TokenSetResponse struct {
+ AccessToken string `json:"access_token"`
+ RefreshToken string `json:"refresh_token"`
+ TokenType string `json:"token_type"`
+ ExpiresIn int `json:"expires_in"`
+ Email string `json:"email,omitempty"`
+}
+
+type DeviceApproveRequest struct {
+ UserCode string `json:"user_code"`
+}
+
+type DeviceLookupResponse struct {
+ UserCode string `json:"user_code"`
+ Status string `json:"status"`
+ ClientName string `json:"clientName"`
+ RequestedAt time.Time `json:"requestedAt"`
+ ExpiresAt time.Time `json:"expiresAt"`
+}
+
+type CreatePATRequest struct {
+ Name string `json:"name"`
+ ExpiresInDays *int `json:"expiresInDays"`
+}
+
+type CreatePATResponse struct {
+ Id string `json:"id"`
+ Name string `json:"name"`
+ Prefix string `json:"prefix"`
+ Token string `json:"token"`
+ CreatedAt time.Time `json:"createdAt"`
+ ExpiresAt *time.Time `json:"expiresAt"`
+}
diff --git a/backend/app/repositories/auth_tokens_common.go b/backend/app/repositories/auth_tokens_common.go
new file mode 100644
index 00000000..d91cc8cc
--- /dev/null
+++ b/backend/app/repositories/auth_tokens_common.go
@@ -0,0 +1,41 @@
+package repositories
+
+import (
+ "crypto/sha256"
+ "database/sql"
+ "encoding/hex"
+ "fmt"
+ "time"
+)
+
+const authTimeLayout = "2006-01-02T15:04:05.000000000Z07:00"
+
+func hashAuthToken(plaintext string) string {
+ sum := sha256.Sum256([]byte(plaintext))
+ return hex.EncodeToString(sum[:])
+}
+
+func formatAuthTime(t time.Time) string {
+ return t.UTC().Format(authTimeLayout)
+}
+
+func parseAuthTime(s string) (time.Time, error) {
+ layouts := []string{authTimeLayout, time.RFC3339Nano, time.RFC3339, "2006-01-02 15:04:05.999999999-07:00", "2006-01-02 15:04:05"}
+ for _, layout := range layouts {
+ if parsed, err := time.Parse(layout, s); err == nil {
+ return parsed.UTC(), nil
+ }
+ }
+ return time.Time{}, fmt.Errorf("auth: cannot parse time %q", s)
+}
+
+func parseNullableAuthTime(ns sql.NullString) (*time.Time, error) {
+ if !ns.Valid || ns.String == "" {
+ return nil, nil
+ }
+ t, err := parseAuthTime(ns.String)
+ if err != nil {
+ return nil, err
+ }
+ return &t, nil
+}
diff --git a/backend/app/repositories/device_authorization.repository.go b/backend/app/repositories/device_authorization.repository.go
new file mode 100644
index 00000000..be22c54e
--- /dev/null
+++ b/backend/app/repositories/device_authorization.repository.go
@@ -0,0 +1,161 @@
+package repositories
+
+import (
+ "database/sql"
+ "errors"
+ "strings"
+ "time"
+
+ "github.com/tracewayapp/lit/v2"
+ "github.com/tracewayapp/traceway/backend/app/db"
+ "github.com/tracewayapp/traceway/backend/app/models"
+)
+
+type deviceAuthorizationRepository struct{}
+
+func (r *deviceAuthorizationRepository) Create(ex lit.Executor, deviceCode, userCode, clientId string, intervalSeconds int, expiresAt time.Time) error {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ `INSERT INTO device_authorizations (device_code_hash, user_code, client_id, status, interval_seconds, expires_at, created_at)
+ VALUES (:hash, :user_code, :client_id, 'pending', :interval, :expires_at, :created_at)`,
+ lit.P{
+ "hash": hashAuthToken(deviceCode),
+ "user_code": userCode,
+ "client_id": clientId,
+ "interval": intervalSeconds,
+ "expires_at": formatAuthTime(expiresAt),
+ "created_at": formatAuthTime(time.Now()),
+ },
+ )
+ if err != nil {
+ return err
+ }
+ _, err = ex.Exec(query, args...)
+ return err
+}
+
+func (r *deviceAuthorizationRepository) FindByDeviceCode(ex lit.Executor, deviceCode string) (*models.DeviceAuthorization, error) {
+ return r.findOne(ex, "device_code_hash = :v", hashAuthToken(deviceCode))
+}
+
+func (r *deviceAuthorizationRepository) FindByUserCode(ex lit.Executor, userCode string) (*models.DeviceAuthorization, error) {
+ // Codes are stored uppercase (generated from an uppercase alphabet); uppercase
+ // the lookup so a lowercase-but-correct entry still matches.
+ return r.findOne(ex, "user_code = :v", strings.ToUpper(userCode))
+}
+
+func (r *deviceAuthorizationRepository) findOne(ex lit.Executor, where, value string) (*models.DeviceAuthorization, error) {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ "SELECT device_code_hash, user_code, client_id, status, user_id, interval_seconds, last_polled_at, expires_at, created_at FROM device_authorizations WHERE "+where,
+ lit.P{"v": value},
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ var (
+ d models.DeviceAuthorization
+ userId sql.NullInt64
+ lastPolled sql.NullString
+ expiresAt string
+ createdAt string
+ )
+ err = ex.QueryRow(query, args...).Scan(&d.DeviceCodeHash, &d.UserCode, &d.ClientId, &d.Status, &userId, &d.IntervalSeconds, &lastPolled, &expiresAt, &createdAt)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ if userId.Valid {
+ uid := int(userId.Int64)
+ d.UserId = &uid
+ }
+ if d.LastPolledAt, err = parseNullableAuthTime(lastPolled); err != nil {
+ return nil, err
+ }
+ if d.ExpiresAt, err = parseAuthTime(expiresAt); err != nil {
+ return nil, err
+ }
+ if d.CreatedAt, err = parseAuthTime(createdAt); err != nil {
+ return nil, err
+ }
+ return &d, nil
+}
+
+func (r *deviceAuthorizationRepository) Approve(ex lit.Executor, userCode string, userId int) (int64, error) {
+ return r.updateStatus(ex, userCode, "approved", &userId)
+}
+
+func (r *deviceAuthorizationRepository) Deny(ex lit.Executor, userCode string) (int64, error) {
+ return r.updateStatus(ex, userCode, "denied", nil)
+}
+
+func (r *deviceAuthorizationRepository) updateStatus(ex lit.Executor, userCode, status string, userId *int) (int64, error) {
+ var uid any
+ if userId != nil {
+ uid = *userId
+ }
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ "UPDATE device_authorizations SET status = :status, user_id = :user_id WHERE user_code = :user_code AND status = 'pending'",
+ lit.P{"status": status, "user_id": uid, "user_code": strings.ToUpper(userCode)},
+ )
+ if err != nil {
+ return 0, err
+ }
+ res, err := ex.Exec(query, args...)
+ if err != nil {
+ return 0, err
+ }
+ return res.RowsAffected()
+}
+
+func (r *deviceAuthorizationRepository) MarkPolled(ex lit.Executor, deviceCode string, polledAt time.Time, intervalSeconds int) error {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ "UPDATE device_authorizations SET last_polled_at = :polled, interval_seconds = :interval WHERE device_code_hash = :hash",
+ lit.P{"polled": formatAuthTime(polledAt), "interval": intervalSeconds, "hash": hashAuthToken(deviceCode)},
+ )
+ if err != nil {
+ return err
+ }
+ _, err = ex.Exec(query, args...)
+ return err
+}
+
+func (r *deviceAuthorizationRepository) Delete(ex lit.Executor, deviceCode string) (int64, error) {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ "DELETE FROM device_authorizations WHERE device_code_hash = :hash",
+ lit.P{"hash": hashAuthToken(deviceCode)},
+ )
+ if err != nil {
+ return 0, err
+ }
+ res, err := ex.Exec(query, args...)
+ if err != nil {
+ return 0, err
+ }
+ return res.RowsAffected()
+}
+
+func (r *deviceAuthorizationRepository) PruneExpired(ex lit.Executor, now time.Time) (int64, error) {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ "DELETE FROM device_authorizations WHERE expires_at < :cutoff",
+ lit.P{"cutoff": formatAuthTime(now)},
+ )
+ if err != nil {
+ return 0, err
+ }
+ res, err := ex.Exec(query, args...)
+ if err != nil {
+ return 0, err
+ }
+ return res.RowsAffected()
+}
+
+var DeviceAuthorizationRepository = deviceAuthorizationRepository{}
diff --git a/backend/app/repositories/personal_access_token.repository.go b/backend/app/repositories/personal_access_token.repository.go
new file mode 100644
index 00000000..c4ba37e3
--- /dev/null
+++ b/backend/app/repositories/personal_access_token.repository.go
@@ -0,0 +1,185 @@
+package repositories
+
+import (
+ "database/sql"
+ "errors"
+ "time"
+
+ "github.com/tracewayapp/lit/v2"
+ "github.com/tracewayapp/traceway/backend/app/db"
+ "github.com/tracewayapp/traceway/backend/app/models"
+)
+
+type ActivePAT struct {
+ Id string
+ UserId int
+ Email string
+ LastUsedAt *time.Time
+}
+
+type personalAccessTokenRepository struct{}
+
+func (r *personalAccessTokenRepository) Create(ex lit.Executor, id, token, prefix string, userId int, name string, expiresAt *time.Time) error {
+ var expires any
+ if expiresAt != nil {
+ expires = formatAuthTime(*expiresAt)
+ }
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ `INSERT INTO personal_access_tokens (id, token_hash, prefix, user_id, name, revoked, expires_at, created_at)
+ VALUES (:id, :hash, :prefix, :user_id, :name, :revoked, :expires_at, :created_at)`,
+ lit.P{
+ "id": id,
+ "hash": hashAuthToken(token),
+ "prefix": prefix,
+ "user_id": userId,
+ "name": name,
+ "revoked": false,
+ "expires_at": expires,
+ "created_at": formatAuthTime(time.Now()),
+ },
+ )
+ if err != nil {
+ return err
+ }
+ _, err = ex.Exec(query, args...)
+ return err
+}
+
+func (r *personalAccessTokenRepository) FindActiveByToken(ex lit.Executor, token string) (*ActivePAT, error) {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ `SELECT p.id, p.user_id, p.revoked, p.expires_at, p.last_used_at, u.email
+ FROM personal_access_tokens p
+ JOIN users u ON u.id = p.user_id
+ WHERE p.token_hash = :hash`,
+ lit.P{"hash": hashAuthToken(token)},
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ var (
+ pat ActivePAT
+ revoked bool
+ expiresAt sql.NullString
+ lastUsed sql.NullString
+ )
+ err = ex.QueryRow(query, args...).Scan(&pat.Id, &pat.UserId, &revoked, &expiresAt, &lastUsed, &pat.Email)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ if revoked {
+ return nil, nil
+ }
+ expiry, err := parseNullableAuthTime(expiresAt)
+ if err != nil {
+ return nil, err
+ }
+ if expiry != nil && time.Now().After(*expiry) {
+ return nil, nil
+ }
+ if pat.LastUsedAt, err = parseNullableAuthTime(lastUsed); err != nil {
+ return nil, err
+ }
+ return &pat, nil
+}
+
+func (r *personalAccessTokenRepository) ListByUser(ex lit.Executor, userId int) ([]*models.PersonalAccessToken, error) {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ `SELECT id, prefix, name, last_used_at, expires_at, created_at
+ FROM personal_access_tokens
+ WHERE user_id = :user_id AND revoked = :revoked
+ ORDER BY created_at DESC`,
+ lit.P{"user_id": userId, "revoked": false},
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ rows, err := ex.Query(query, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+
+ tokens := []*models.PersonalAccessToken{}
+ for rows.Next() {
+ var (
+ pat models.PersonalAccessToken
+ lastUsed sql.NullString
+ expiresAt sql.NullString
+ createdAt string
+ )
+ if err := rows.Scan(&pat.Id, &pat.Prefix, &pat.Name, &lastUsed, &expiresAt, &createdAt); err != nil {
+ return nil, err
+ }
+ if pat.LastUsedAt, err = parseNullableAuthTime(lastUsed); err != nil {
+ return nil, err
+ }
+ if pat.ExpiresAt, err = parseNullableAuthTime(expiresAt); err != nil {
+ return nil, err
+ }
+ if pat.CreatedAt, err = parseAuthTime(createdAt); err != nil {
+ return nil, err
+ }
+ tokens = append(tokens, &pat)
+ }
+ return tokens, rows.Err()
+}
+
+func (r *personalAccessTokenRepository) Revoke(ex lit.Executor, id string, userId int) (int64, error) {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ "UPDATE personal_access_tokens SET revoked = :revoked WHERE id = :id AND user_id = :user_id AND revoked = :active",
+ lit.P{"revoked": true, "id": id, "user_id": userId, "active": false},
+ )
+ if err != nil {
+ return 0, err
+ }
+ res, err := ex.Exec(query, args...)
+ if err != nil {
+ return 0, err
+ }
+ return res.RowsAffected()
+}
+
+// PruneExpired deletes rows that are no longer usable: revoked tokens, and
+// tokens past their (optional) expiry. Unlike device codes and refresh tokens,
+// PAT expiry was previously only enforced lazily at read time, so expired and
+// revoked rows accumulated indefinitely.
+func (r *personalAccessTokenRepository) PruneExpired(ex lit.Executor, now time.Time) (int64, error) {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ "DELETE FROM personal_access_tokens WHERE revoked = :revoked OR (expires_at IS NOT NULL AND expires_at < :cutoff)",
+ lit.P{"revoked": true, "cutoff": formatAuthTime(now)},
+ )
+ if err != nil {
+ return 0, err
+ }
+ res, err := ex.Exec(query, args...)
+ if err != nil {
+ return 0, err
+ }
+ return res.RowsAffected()
+}
+
+func (r *personalAccessTokenRepository) TouchLastUsed(ex lit.Executor, id string, usedAt time.Time) error {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ "UPDATE personal_access_tokens SET last_used_at = :used WHERE id = :id",
+ lit.P{"used": formatAuthTime(usedAt), "id": id},
+ )
+ if err != nil {
+ return err
+ }
+ _, err = ex.Exec(query, args...)
+ return err
+}
+
+var PersonalAccessTokenRepository = personalAccessTokenRepository{}
diff --git a/backend/app/repositories/refresh_token.repository.go b/backend/app/repositories/refresh_token.repository.go
new file mode 100644
index 00000000..ef733ea5
--- /dev/null
+++ b/backend/app/repositories/refresh_token.repository.go
@@ -0,0 +1,138 @@
+package repositories
+
+import (
+ "database/sql"
+ "errors"
+ "time"
+
+ "github.com/tracewayapp/lit/v2"
+ "github.com/tracewayapp/traceway/backend/app/db"
+ "github.com/tracewayapp/traceway/backend/app/models"
+)
+
+type refreshTokenRepository struct{}
+
+func (r *refreshTokenRepository) Insert(ex lit.Executor, token, familyId string, userId int, clientId string, expiresAt time.Time) error {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ `INSERT INTO refresh_tokens (token_hash, family_id, user_id, client_id, revoked, used, expires_at, created_at)
+ VALUES (:hash, :family, :user_id, :client_id, :revoked, :used, :expires_at, :created_at)`,
+ lit.P{
+ "hash": hashAuthToken(token),
+ "family": familyId,
+ "user_id": userId,
+ "client_id": clientId,
+ "revoked": false,
+ "used": false,
+ "expires_at": formatAuthTime(expiresAt),
+ "created_at": formatAuthTime(time.Now()),
+ },
+ )
+ if err != nil {
+ return err
+ }
+ _, err = ex.Exec(query, args...)
+ return err
+}
+
+func (r *refreshTokenRepository) FindByToken(ex lit.Executor, token string) (*models.RefreshToken, error) {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ "SELECT token_hash, family_id, user_id, client_id, revoked, used, used_at, expires_at, created_at FROM refresh_tokens WHERE token_hash = :hash",
+ lit.P{"hash": hashAuthToken(token)},
+ )
+ if err != nil {
+ return nil, err
+ }
+
+ var (
+ t models.RefreshToken
+ usedAt sql.NullString
+ expiresAt string
+ createdAt string
+ )
+ err = ex.QueryRow(query, args...).Scan(&t.TokenHash, &t.FamilyId, &t.UserId, &t.ClientId, &t.Revoked, &t.Used, &usedAt, &expiresAt, &createdAt)
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, err
+ }
+
+ if t.UsedAt, err = parseNullableAuthTime(usedAt); err != nil {
+ return nil, err
+ }
+ if t.ExpiresAt, err = parseAuthTime(expiresAt); err != nil {
+ return nil, err
+ }
+ if t.CreatedAt, err = parseAuthTime(createdAt); err != nil {
+ return nil, err
+ }
+ return &t, nil
+}
+
+// MarkUsedIfUnused atomically flips the token to used, but only if it is still
+// unused and not revoked. The rows-affected result is the concurrency guard: a
+// return of 0 means another request already consumed (or revoked) this token,
+// which is how RotateRefresh distinguishes a benign concurrent retry from a
+// genuine replay of an already-rotated token.
+func (r *refreshTokenRepository) MarkUsedIfUnused(ex lit.Executor, token string, usedAt time.Time) (int64, error) {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ "UPDATE refresh_tokens SET used = :used, used_at = :used_at WHERE token_hash = :hash AND used = :active AND revoked = :active",
+ lit.P{"used": true, "used_at": formatAuthTime(usedAt), "hash": hashAuthToken(token), "active": false},
+ )
+ if err != nil {
+ return 0, err
+ }
+ res, err := ex.Exec(query, args...)
+ if err != nil {
+ return 0, err
+ }
+ return res.RowsAffected()
+}
+
+func (r *refreshTokenRepository) RevokeFamily(ex lit.Executor, familyId string) error {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ "UPDATE refresh_tokens SET revoked = :revoked WHERE family_id = :family",
+ lit.P{"revoked": true, "family": familyId},
+ )
+ if err != nil {
+ return err
+ }
+ _, err = ex.Exec(query, args...)
+ return err
+}
+
+// usedRefreshTokenRetention is how long a consumed (rotated) token row is kept
+// so a genuine replay can still be detected and revoke its family. Without a
+// cap, every rotation would leave a row behind for the full 90-day expiry;
+// after a month the row's only value is replay detection for a token an
+// attacker can no longer redeem, so it is safe to drop. Revoked rows carry no
+// signal at all (the family is already dead) and are dropped immediately,
+// matching the PAT prune.
+const usedRefreshTokenRetention = 30 * 24 * time.Hour
+
+func (r *refreshTokenRepository) PruneExpired(ex lit.Executor, now time.Time) (int64, error) {
+ query, args, err := lit.ParseNamedQuery(
+ db.Driver,
+ "DELETE FROM refresh_tokens WHERE expires_at < :cutoff OR revoked = :revoked OR (used = :used AND used_at < :used_cutoff)",
+ lit.P{
+ "cutoff": formatAuthTime(now),
+ "revoked": true,
+ "used": true,
+ "used_cutoff": formatAuthTime(now.Add(-usedRefreshTokenRetention)),
+ },
+ )
+ if err != nil {
+ return 0, err
+ }
+ res, err := ex.Exec(query, args...)
+ if err != nil {
+ return 0, err
+ }
+ return res.RowsAffected()
+}
+
+var RefreshTokenRepository = refreshTokenRepository{}
diff --git a/backend/app/retention/auth_tokens.go b/backend/app/retention/auth_tokens.go
new file mode 100644
index 00000000..016dff6c
--- /dev/null
+++ b/backend/app/retention/auth_tokens.go
@@ -0,0 +1,38 @@
+package retention
+
+import (
+ "context"
+ "database/sql"
+ "time"
+
+ "github.com/tracewayapp/traceway/backend/app/repositories"
+)
+
+const authTokensPruneInterval = 24 * time.Hour
+
+func startAuthTokensPrune(ctx context.Context) {
+ startDBPruneWorker(ctx, "auth_tokens", authTokensPruneInterval, func(tx *sql.Tx) (int64, error) {
+ now := time.Now().UTC()
+ var total int64
+
+ n, err := repositories.DeviceAuthorizationRepository.PruneExpired(tx, now)
+ if err != nil {
+ return total, err
+ }
+ total += n
+
+ n, err = repositories.RefreshTokenRepository.PruneExpired(tx, now)
+ if err != nil {
+ return total, err
+ }
+ total += n
+
+ n, err = repositories.PersonalAccessTokenRepository.PruneExpired(tx, now)
+ if err != nil {
+ return total, err
+ }
+ total += n
+
+ return total, nil
+ })
+}
diff --git a/backend/app/retention/oauth_sessions.go b/backend/app/retention/oauth_sessions.go
index 3b061c7e..37dabd60 100644
--- a/backend/app/retention/oauth_sessions.go
+++ b/backend/app/retention/oauth_sessions.go
@@ -3,47 +3,15 @@ package retention
import (
"context"
"database/sql"
- "fmt"
"time"
- "github.com/tracewayapp/traceway/backend/app/config"
- "github.com/tracewayapp/traceway/backend/app/db"
"github.com/tracewayapp/traceway/backend/app/repositories"
- traceway "go.tracewayapp.com"
)
const oauthSessionsPruneInterval = 24 * time.Hour
func startOAuthSessionsPrune(ctx context.Context) {
- config.Logf("Starting oauth_sessions prune worker (interval: %s)", oauthSessionsPruneInterval)
-
- go func() {
- defer traceway.Recover()
-
- runOAuthSessionsPrune(ctx)
-
- ticker := time.NewTicker(oauthSessionsPruneInterval)
- defer ticker.Stop()
- for {
- select {
- case <-ctx.Done():
- return
- case <-ticker.C:
- runOAuthSessionsPrune(ctx)
- }
- }
- }()
-}
-
-func runOAuthSessionsPrune(ctx context.Context) {
- if ctx.Err() != nil || db.DB == nil {
- return
- }
-
- _, err := db.ExecuteTransaction(func(tx *sql.Tx) (int64, error) {
+ startDBPruneWorker(ctx, "oauth_sessions", oauthSessionsPruneInterval, func(tx *sql.Tx) (int64, error) {
return repositories.OAuthSessionRepository.PruneExpired(tx, time.Now().UTC())
})
- if err != nil {
- traceway.CaptureException(fmt.Errorf("retention: prune oauth_sessions failed: %w", err))
- }
}
diff --git a/backend/app/retention/prune_worker.go b/backend/app/retention/prune_worker.go
new file mode 100644
index 00000000..d64e4022
--- /dev/null
+++ b/backend/app/retention/prune_worker.go
@@ -0,0 +1,47 @@
+package retention
+
+import (
+ "context"
+ "database/sql"
+ "fmt"
+ "time"
+
+ "github.com/tracewayapp/traceway/backend/app/config"
+ "github.com/tracewayapp/traceway/backend/app/db"
+ traceway "go.tracewayapp.com"
+)
+
+// startDBPruneWorker runs prune once at startup and then every interval until
+// ctx is cancelled, inside a panic-guarded goroutine. It is the shared
+// scaffolding behind the main-DB retention workers (oauth_sessions, auth_tokens).
+func startDBPruneWorker(ctx context.Context, name string, interval time.Duration, prune func(tx *sql.Tx) (int64, error)) {
+ config.Logf("Starting %s prune worker (interval: %s)", name, interval)
+
+ go func() {
+ defer traceway.Recover()
+
+ runDBPrune(ctx, name, prune)
+
+ ticker := time.NewTicker(interval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ runDBPrune(ctx, name, prune)
+ }
+ }
+ }()
+}
+
+// runDBPrune wraps a prune closure with the shared guard, transaction, and
+// non-fatal error reporting.
+func runDBPrune(ctx context.Context, name string, prune func(tx *sql.Tx) (int64, error)) {
+ if ctx.Err() != nil || db.DB == nil {
+ return
+ }
+ if _, err := db.ExecuteTransaction(prune); err != nil {
+ traceway.CaptureException(fmt.Errorf("retention: prune %s failed: %w", name, err))
+ }
+}
diff --git a/backend/app/retention/retention.go b/backend/app/retention/retention.go
index 0d0b47a8..c714cf61 100644
--- a/backend/app/retention/retention.go
+++ b/backend/app/retention/retention.go
@@ -21,6 +21,7 @@ func Start(ctx context.Context) {
startRecordingDiskCleanup(ctx, parseRetentionDays(cfg.SessionRecordingRetentionDays))
startProfileArchiveDiskCleanup(ctx, parseRetentionDays(cfg.ProfileRetentionDays))
startOAuthSessionsPrune(ctx)
+ startAuthTokensPrune(ctx)
}
func parseRetentionDays(value string) int {
diff --git a/backend/app/services/authserver/authserver_test.go b/backend/app/services/authserver/authserver_test.go
new file mode 100644
index 00000000..2fc2d684
--- /dev/null
+++ b/backend/app/services/authserver/authserver_test.go
@@ -0,0 +1,337 @@
+//go:build !pgch
+
+package authserver
+
+import (
+ "database/sql"
+ "errors"
+ "testing"
+ "time"
+
+ "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/migrations"
+ "github.com/tracewayapp/traceway/backend/app/models"
+ "github.com/tracewayapp/traceway/backend/app/repositories"
+ "github.com/tracewayapp/traceway/backend/app/services"
+
+ _ "modernc.org/sqlite"
+)
+
+func setupAuthDB(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)
+
+ db.DB = mainDB
+ db.TelemetryDB = telemetryDB
+ db.Driver = lit.SQLite
+ models.Init(db.Driver)
+
+ if err := migrations.Run("sqlite"); err != nil {
+ t.Fatalf("run migrations: %v", err)
+ }
+
+ config.Init(&config.Cfg{JWTSecret: "test-secret-that-is-at-least-32-chars-long"})
+ if err := services.InitJWT(); err != nil {
+ t.Fatalf("init jwt: %v", err)
+ }
+
+ if _, err := mainDB.Exec("INSERT INTO users (id, email, name, password) VALUES (1, '[email protected]', 'Dev', 'x')"); err != nil {
+ t.Fatalf("seed user: %v", err)
+ }
+
+ t.Cleanup(func() {
+ mainDB.Close()
+ telemetryDB.Close()
+ })
+}
+
+func insertRefresh(t *testing.T, token, family string) {
+ t.Helper()
+ if err := repositories.RefreshTokenRepository.Insert(db.DB, token, family, 1, cliClientID, time.Now().Add(time.Hour)); err != nil {
+ t.Fatalf("insert refresh token: %v", err)
+ }
+}
+
+func TestRotateRefresh_sequentialRotation(t *testing.T) {
+ setupAuthDB(t)
+ insertRefresh(t, "twr_seq", "fam-seq")
+
+ ts, err := RotateRefresh("twr_seq")
+ if err != nil {
+ t.Fatalf("RotateRefresh: %v", err)
+ }
+ if ts.RefreshToken == "" || ts.RefreshToken == "twr_seq" {
+ t.Fatalf("expected a rotated refresh token, got %q", ts.RefreshToken)
+ }
+ if ts.AccessToken == "" {
+ t.Fatal("expected an access token")
+ }
+
+ old, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, "twr_seq")
+ if old == nil || !old.Used {
+ t.Fatalf("presented token should be marked used, got %+v", old)
+ }
+ fresh, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, ts.RefreshToken)
+ if fresh == nil || fresh.Used || fresh.Revoked || fresh.FamilyId != "fam-seq" {
+ t.Fatalf("rotated token should be live in the same family, got %+v", fresh)
+ }
+}
+
+func TestRotateRefresh_replayOutsideGraceRevokesFamily(t *testing.T) {
+ setupAuthDB(t)
+ insertRefresh(t, "twr_old", "fam-old")
+ insertRefresh(t, "twr_sibling", "fam-old")
+
+ // Simulate a token consumed well outside the reuse-grace window.
+ if _, err := repositories.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_old", time.Now().Add(-time.Hour)); err != nil {
+ t.Fatalf("mark used: %v", err)
+ }
+
+ if _, err := RotateRefresh("twr_old"); !errors.Is(err, ErrInvalidGrant) {
+ t.Fatalf("expected ErrInvalidGrant, got %v", err)
+ }
+
+ sib, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, "twr_sibling")
+ if sib == nil || !sib.Revoked {
+ t.Fatalf("genuine replay must revoke the whole family, sibling = %+v", sib)
+ }
+}
+
+func TestRotateRefresh_concurrentWithinGraceKeepsFamily(t *testing.T) {
+ setupAuthDB(t)
+ insertRefresh(t, "twr_race", "fam-race")
+ insertRefresh(t, "twr_winner", "fam-race")
+
+ // The racing request already consumed the token just now (within grace).
+ if _, err := repositories.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_race", time.Now()); err != nil {
+ t.Fatalf("mark used: %v", err)
+ }
+
+ if _, err := RotateRefresh("twr_race"); !errors.Is(err, ErrInvalidGrant) {
+ t.Fatalf("expected ErrInvalidGrant, got %v", err)
+ }
+
+ winner, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, "twr_winner")
+ if winner == nil || winner.Revoked {
+ t.Fatalf("benign concurrent retry must NOT revoke the family, winner = %+v", winner)
+ }
+}
+
+func TestRotateRefresh_lostResponseReplaysTokenSetWithinGrace(t *testing.T) {
+ setupAuthDB(t)
+ insertRefresh(t, "twr_lost", "fam-lost")
+
+ first, err := RotateRefresh("twr_lost")
+ if err != nil {
+ t.Fatalf("first rotation: %v", err)
+ }
+
+ // The client lost the response (or failed to persist it) and re-presents
+ // the consumed token within the grace window: it must receive the same
+ // rotated token set, not invalid_grant, and the family must stay intact.
+ second, err := RotateRefresh("twr_lost")
+ if err != nil {
+ t.Fatalf("grace-window retry: %v", err)
+ }
+ if second.RefreshToken != first.RefreshToken || second.AccessToken != first.AccessToken {
+ t.Fatalf("grace-window retry must replay the rotated token set, got %+v want %+v", second, first)
+ }
+
+ winner, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, first.RefreshToken)
+ if winner == nil || winner.Revoked {
+ t.Fatalf("grace-window retry must not revoke the family, winner = %+v", winner)
+ }
+}
+
+func TestCreateDeviceAuth_unknownClientRejected(t *testing.T) {
+ setupAuthDB(t)
+
+ if _, err := CreateDeviceAuth("Traceway Security Check", "http://localhost"); !errors.Is(err, ErrUnknownClient) {
+ t.Fatalf("expected ErrUnknownClient, got %v", err)
+ }
+ if _, err := CreateDeviceAuth(mcpClientID, "http://localhost"); err != nil {
+ t.Fatalf("known client must be accepted, got %v", err)
+ }
+}
+
+func TestApprove_expiredCodeRejected(t *testing.T) {
+ setupAuthDB(t)
+
+ if err := repositories.DeviceAuthorizationRepository.Create(db.DB, "dev-exp", "CCCC-DDDD", cliClientID, 5, time.Now().Add(-time.Minute)); err != nil {
+ t.Fatalf("create device auth: %v", err)
+ }
+
+ tx, err := db.DB.Begin()
+ if err != nil {
+ t.Fatalf("begin: %v", err)
+ }
+ defer tx.Rollback()
+
+ if err := Approve(tx, "CCCC-DDDD", 1); !errors.Is(err, ErrDeviceExpired) {
+ t.Fatalf("expected ErrDeviceExpired, got %v", err)
+ }
+}
+
+func TestApprove_lowercaseUserCode(t *testing.T) {
+ setupAuthDB(t)
+
+ if err := repositories.DeviceAuthorizationRepository.Create(db.DB, "dev-lc", "EEEE-FFFF", cliClientID, 5, time.Now().Add(deviceCodeTTL)); err != nil {
+ t.Fatalf("create device auth: %v", err)
+ }
+
+ tx, err := db.DB.Begin()
+ if err != nil {
+ t.Fatalf("begin: %v", err)
+ }
+ if err := Approve(tx, "eeee-ffff", 1); err != nil {
+ tx.Rollback()
+ t.Fatalf("approve with lowercase code: %v", err)
+ }
+ if err := tx.Commit(); err != nil {
+ t.Fatalf("commit: %v", err)
+ }
+
+ da, _ := repositories.DeviceAuthorizationRepository.FindByUserCode(db.DB, "EEEE-FFFF")
+ if da == nil || da.Status != "approved" {
+ t.Fatalf("code should be approved, got %+v", da)
+ }
+}
+
+func TestRefreshTokenRepository_PruneExpired(t *testing.T) {
+ setupAuthDB(t)
+
+ insertRefresh(t, "twr_live", "fam-prune")
+ insertRefresh(t, "twr_recent_used", "fam-prune")
+ insertRefresh(t, "twr_old_used", "fam-prune")
+ insertRefresh(t, "twr_revoked", "fam-dead")
+ if err := repositories.RefreshTokenRepository.Insert(db.DB, "twr_expired", "fam-prune", 1, cliClientID, time.Now().Add(-time.Hour)); err != nil {
+ t.Fatalf("insert expired: %v", err)
+ }
+
+ if _, err := repositories.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_recent_used", time.Now()); err != nil {
+ t.Fatalf("mark used: %v", err)
+ }
+ if _, err := repositories.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_old_used", time.Now().Add(-31*24*time.Hour)); err != nil {
+ t.Fatalf("mark used: %v", err)
+ }
+ if err := repositories.RefreshTokenRepository.RevokeFamily(db.DB, "fam-dead"); err != nil {
+ t.Fatalf("revoke family: %v", err)
+ }
+
+ n, err := repositories.RefreshTokenRepository.PruneExpired(db.DB, time.Now())
+ if err != nil {
+ t.Fatalf("prune: %v", err)
+ }
+ if n != 3 {
+ t.Fatalf("prune removed %d rows, want 3 (expired + revoked + anciently used)", n)
+ }
+ for _, tok := range []string{"twr_live", "twr_recent_used"} {
+ if rt, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, tok); rt == nil {
+ t.Fatalf("%s should survive pruning", tok)
+ }
+ }
+}
+
+func TestRevokeByToken_revokesFamily(t *testing.T) {
+ setupAuthDB(t)
+ insertRefresh(t, "twr_a", "fam-logout")
+ insertRefresh(t, "twr_b", "fam-logout")
+
+ if err := RevokeByToken("twr_a"); err != nil {
+ t.Fatalf("RevokeByToken: %v", err)
+ }
+
+ for _, tok := range []string{"twr_a", "twr_b"} {
+ rt, _ := repositories.RefreshTokenRepository.FindByToken(db.DB, tok)
+ if rt == nil || !rt.Revoked {
+ t.Fatalf("logout must revoke the whole family, %s = %+v", tok, rt)
+ }
+ }
+ // Unknown token is a no-op, not an error.
+ if err := RevokeByToken("twr_missing"); err != nil {
+ t.Fatalf("RevokeByToken(unknown) should be a no-op, got %v", err)
+ }
+}
+
+func TestPollDeviceToken_singleUse(t *testing.T) {
+ setupAuthDB(t)
+
+ const deviceCode = "dev-code"
+ const userCode = "AAAA-BBBB"
+ if err := repositories.DeviceAuthorizationRepository.Create(db.DB, deviceCode, userCode, cliClientID, 5, time.Now().Add(deviceCodeTTL)); err != nil {
+ t.Fatalf("create device auth: %v", err)
+ }
+ if _, err := repositories.DeviceAuthorizationRepository.Approve(db.DB, userCode, 1); err != nil {
+ t.Fatalf("approve: %v", err)
+ }
+
+ ts, err := PollDeviceToken(deviceCode)
+ if err != nil {
+ t.Fatalf("first poll: %v", err)
+ }
+ if ts.AccessToken == "" || ts.RefreshToken == "" {
+ t.Fatalf("first poll should issue a token set, got %+v", ts)
+ }
+
+ if _, err := PollDeviceToken(deviceCode); !errors.Is(err, ErrExpiredToken) {
+ t.Fatalf("a device code must be single-use; second poll = %v", err)
+ }
+}
+
+func TestMarkUsedIfUnused_isConditional(t *testing.T) {
+ setupAuthDB(t)
+ insertRefresh(t, "twr_once", "fam-once")
+
+ n, err := repositories.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_once", time.Now())
+ if err != nil || n != 1 {
+ t.Fatalf("first mark = (%d, %v), want (1, nil)", n, err)
+ }
+ n, err = repositories.RefreshTokenRepository.MarkUsedIfUnused(db.DB, "twr_once", time.Now())
+ if err != nil || n != 0 {
+ t.Fatalf("second mark = (%d, %v), want (0, nil)", n, err)
+ }
+}
+
+func TestPersonalAccessTokenRepository_PruneExpired(t *testing.T) {
+ setupAuthDB(t)
+
+ expired := time.Now().Add(-time.Hour)
+ must := func(err error) {
+ t.Helper()
+ if err != nil {
+ t.Fatalf("pat create: %v", err)
+ }
+ }
+ must(repositories.PersonalAccessTokenRepository.Create(db.DB, "id-active", "twp_active", "twp_active12", 1, "active", nil))
+ must(repositories.PersonalAccessTokenRepository.Create(db.DB, "id-expired", "twp_expired", "twp_expired1", 1, "expired", &expired))
+ must(repositories.PersonalAccessTokenRepository.Create(db.DB, "id-revoked", "twp_revoked", "twp_revoked1", 1, "revoked", nil))
+ if _, err := repositories.PersonalAccessTokenRepository.Revoke(db.DB, "id-revoked", 1); err != nil {
+ t.Fatalf("revoke: %v", err)
+ }
+
+ n, err := repositories.PersonalAccessTokenRepository.PruneExpired(db.DB, time.Now())
+ if err != nil {
+ t.Fatalf("prune: %v", err)
+ }
+ if n != 2 {
+ t.Fatalf("prune removed %d rows, want 2 (expired + revoked)", n)
+ }
+
+ active, _ := repositories.PersonalAccessTokenRepository.FindActiveByToken(db.DB, "twp_active")
+ if active == nil {
+ t.Fatal("active PAT should survive pruning")
+ }
+}
diff --git a/backend/app/services/authserver/config.go b/backend/app/services/authserver/config.go
new file mode 100644
index 00000000..a8178a2e
--- /dev/null
+++ b/backend/app/services/authserver/config.go
@@ -0,0 +1,73 @@
+package authserver
+
+import (
+ "strings"
+ "time"
+
+ "github.com/gin-gonic/gin"
+
+ "github.com/tracewayapp/traceway/backend/app/config"
+)
+
+const (
+ accessTokenTTL = 15 * time.Minute
+ refreshTokenTTL = 90 * 24 * time.Hour
+ deviceCodeTTL = 10 * time.Minute
+ devicePollInterval = 5 * time.Second
+ cliClientID = "traceway-cli"
+ mcpClientID = "traceway-mcp"
+
+ // reuseGrace is the window during which re-presenting a just-used refresh
+ // token is treated as a benign concurrent retry (two CLI processes racing,
+ // or a client that lost the rotated response) rather than a stolen-token
+ // replay: within it the family is NOT revoked. Genuine replays surface long
+ // after this window, once the legitimate client has moved on.
+ reuseGrace = 30 * time.Second
+)
+
+// IssuerBaseURL is the OAuth issuer and verification-URL base. It is always the
+// server we are running on. Prefer IssuerBaseURLFromRequest in request handlers
+// so the issuer resolves even when APP_BASE_URL is unset.
+func IssuerBaseURL() string {
+ return strings.TrimRight(config.Config.AppBaseURL, "/")
+}
+
+// IssuerBaseURLFromRequest returns the configured issuer base URL, or derives it
+// from the incoming request when APP_BASE_URL is unset — the common case on
+// self-hosted deployments that never set it. It honors X-Forwarded-Proto /
+// X-Forwarded-Host from a fronting reverse proxy, falling back to the request's
+// own scheme and Host. The returned value has no trailing slash.
+func IssuerBaseURLFromRequest(c *gin.Context) string {
+ if base := IssuerBaseURL(); base != "" {
+ return base
+ }
+
+ scheme := "http"
+ if proto := firstForwardedValue(c.GetHeader("X-Forwarded-Proto")); proto != "" {
+ scheme = proto
+ } else if c.Request != nil && c.Request.TLS != nil {
+ scheme = "https"
+ }
+
+ host := firstForwardedValue(c.GetHeader("X-Forwarded-Host"))
+ if host == "" && c.Request != nil {
+ host = c.Request.Host
+ }
+ if host == "" {
+ return ""
+ }
+ return scheme + "://" + host
+}
+
+// firstForwardedValue returns the first entry of a possibly comma-separated
+// X-Forwarded-* header value (proxies append, so the client-facing value is
+// first), trimmed of whitespace.
+func firstForwardedValue(header string) string {
+ if header == "" {
+ return ""
+ }
+ if i := strings.IndexByte(header, ','); i >= 0 {
+ header = header[:i]
+ }
+ return strings.TrimSpace(header)
+}
diff --git a/backend/app/services/authserver/device.go b/backend/app/services/authserver/device.go
new file mode 100644
index 00000000..f8a1cbe6
--- /dev/null
+++ b/backend/app/services/authserver/device.go
@@ -0,0 +1,160 @@
+package authserver
+
+import (
+ "database/sql"
+ "errors"
+ "strings"
+ "time"
+
+ "github.com/tracewayapp/traceway/backend/app/db"
+ "github.com/tracewayapp/traceway/backend/app/models"
+ "github.com/tracewayapp/traceway/backend/app/repositories"
+)
+
+var (
+ ErrAuthorizationPending = errors.New("authorization_pending")
+ ErrSlowDown = errors.New("slow_down")
+ ErrAccessDenied = errors.New("access_denied")
+ ErrExpiredToken = errors.New("expired_token")
+ ErrDeviceNotFound = errors.New("device_not_found")
+ ErrDeviceExpired = errors.New("device_code_expired")
+ ErrUnknownClient = errors.New("invalid_client")
+)
+
+// Only first-party clients may start the device flow: the approval screen
+// renders the client's display name as a trusted party, so an arbitrary
+// attacker-chosen client_id would make phishing prompts look first-party.
+var knownDeviceClients = map[string]bool{
+ cliClientID: true,
+ mcpClientID: true,
+}
+
+func CreateDeviceAuth(clientId, baseURL string) (*models.DeviceAuthorizeResponse, error) {
+ if clientId == "" {
+ clientId = cliClientID
+ }
+ if !knownDeviceClients[clientId] {
+ return nil, ErrUnknownClient
+ }
+
+ deviceCode := newOpaqueToken("")
+ userCode := newUserCode()
+ interval := int(devicePollInterval.Seconds())
+ ttl := deviceCodeTTL
+
+ // Opportunistically drop expired rows so this unauthenticated endpoint can
+ // never accumulate more than one device-code TTL's worth of rows between
+ // the daily prune-worker runs.
+ _, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {
+ if _, err := repositories.DeviceAuthorizationRepository.PruneExpired(tx, time.Now()); err != nil {
+ return struct{}{}, err
+ }
+ return struct{}{}, repositories.DeviceAuthorizationRepository.Create(tx, deviceCode, userCode, clientId, interval, time.Now().Add(ttl))
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ verificationURI := strings.TrimRight(baseURL, "/") + "/device"
+ return &models.DeviceAuthorizeResponse{
+ DeviceCode: deviceCode,
+ UserCode: userCode,
+ VerificationURI: verificationURI,
+ VerificationURIComplete: verificationURI + "?user_code=" + userCode,
+ ExpiresIn: int(ttl.Seconds()),
+ Interval: interval,
+ }, nil
+}
+
+// PollDeviceToken owns its own transactions: the OAuth token endpoint returns
+// 400 for normal flow control (pending/slow_down), so it cannot rely on the
+// request-scoped Transactional middleware (which only commits on 2xx).
+func PollDeviceToken(deviceCode string) (*models.TokenSetResponse, error) {
+ da, err := repositories.DeviceAuthorizationRepository.FindByDeviceCode(db.DB, deviceCode)
+ if err != nil {
+ return nil, err
+ }
+ if da == nil || time.Now().After(da.ExpiresAt) {
+ return nil, ErrExpiredToken
+ }
+
+ switch da.Status {
+ case "denied":
+ return nil, ErrAccessDenied
+ case "approved":
+ if da.UserId == nil {
+ return nil, ErrAccessDenied
+ }
+ return db.ExecuteTransaction(func(tx *sql.Tx) (*models.TokenSetResponse, error) {
+ // Consume the device code first: a device code is single-use, so if
+ // the row is already gone another concurrent poll redeemed it and we
+ // must not mint a second token set for the same code.
+ deleted, err := repositories.DeviceAuthorizationRepository.Delete(tx, deviceCode)
+ if err != nil {
+ return nil, err
+ }
+ if deleted == 0 {
+ return nil, ErrExpiredToken
+ }
+ user, err := repositories.UserRepository.FindById(tx, *da.UserId)
+ if err != nil {
+ return nil, err
+ }
+ if user == nil {
+ return nil, ErrAccessDenied
+ }
+ return IssueTokenSet(tx, *da.UserId, user.Email, da.ClientId)
+ })
+ default:
+ now := time.Now()
+ interval := da.IntervalSeconds
+ slow := da.LastPolledAt != nil && now.Before(da.LastPolledAt.Add(time.Duration(da.IntervalSeconds)*time.Second))
+ if slow {
+ interval = da.IntervalSeconds + 5
+ }
+ _, _ = db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {
+ return struct{}{}, repositories.DeviceAuthorizationRepository.MarkPolled(tx, deviceCode, now, interval)
+ })
+ if slow {
+ return nil, ErrSlowDown
+ }
+ return nil, ErrAuthorizationPending
+ }
+}
+
+func Approve(tx *sql.Tx, userCode string, userId int) error {
+ return resolveDevice(tx, userCode, func(canonicalCode string) (int64, error) {
+ return repositories.DeviceAuthorizationRepository.Approve(tx, canonicalCode, userId)
+ })
+}
+
+func Deny(tx *sql.Tx, userCode string) error {
+ return resolveDevice(tx, userCode, func(canonicalCode string) (int64, error) {
+ return repositories.DeviceAuthorizationRepository.Deny(tx, canonicalCode)
+ })
+}
+
+// resolveDevice loads the authorization first so an expired-but-still-pending
+// code is rejected here (the poll endpoint would refuse it anyway, so letting
+// the approval "succeed" would only mislead the user), and so the status
+// update runs against the stored canonical user code.
+func resolveDevice(tx *sql.Tx, userCode string, update func(canonicalCode string) (int64, error)) error {
+ da, err := repositories.DeviceAuthorizationRepository.FindByUserCode(tx, userCode)
+ if err != nil {
+ return err
+ }
+ if da == nil {
+ return ErrDeviceNotFound
+ }
+ if time.Now().After(da.ExpiresAt) {
+ return ErrDeviceExpired
+ }
+ rows, err := update(da.UserCode)
+ if err != nil {
+ return err
+ }
+ if rows == 0 {
+ return ErrDeviceNotFound
+ }
+ return nil
+}
diff --git a/backend/app/services/authserver/refresh.go b/backend/app/services/authserver/refresh.go
new file mode 100644
index 00000000..3d8d4080
--- /dev/null
+++ b/backend/app/services/authserver/refresh.go
@@ -0,0 +1,185 @@
+package authserver
+
+import (
+ "crypto/sha256"
+ "database/sql"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "sync"
+ "time"
+
+ traceway "go.tracewayapp.com"
+
+ "github.com/tracewayapp/traceway/backend/app/db"
+ "github.com/tracewayapp/traceway/backend/app/models"
+ "github.com/tracewayapp/traceway/backend/app/repositories"
+)
+
+var ErrInvalidGrant = errors.New("invalid_grant")
+
+// rotationCache remembers, for reuseGrace, the token set a rotation produced,
+// keyed by the hash of the refresh token that was consumed. It is what makes
+// the grace window actually work: a client that lost the rotation response (or
+// failed to persist it) re-presents the consumed token and gets the same
+// rotated set back instead of an invalid_grant it can never recover from. Only
+// hashes are used as keys; the raw presented token is never stored. Being
+// in-memory, a restart or another instance falls back to invalid_grant, which
+// is the pre-cache behavior.
+var (
+ rotationCacheMu sync.Mutex
+ rotationCache = map[string]rotationCacheEntry{}
+)
+
+type rotationCacheEntry struct {
+ ts *models.TokenSetResponse
+ expiresAt time.Time
+}
+
+func rotationCacheKey(presented string) string {
+ sum := sha256.Sum256([]byte(presented))
+ return hex.EncodeToString(sum[:])
+}
+
+func storeRotation(presented string, ts *models.TokenSetResponse) {
+ now := time.Now()
+ rotationCacheMu.Lock()
+ defer rotationCacheMu.Unlock()
+ for k, e := range rotationCache {
+ if now.After(e.expiresAt) {
+ delete(rotationCache, k)
+ }
+ }
+ rotationCache[rotationCacheKey(presented)] = rotationCacheEntry{ts: ts, expiresAt: now.Add(reuseGrace)}
+}
+
+func cachedRotation(presented string) *models.TokenSetResponse {
+ rotationCacheMu.Lock()
+ defer rotationCacheMu.Unlock()
+ e, ok := rotationCache[rotationCacheKey(presented)]
+ if !ok || time.Now().After(e.expiresAt) {
+ return nil
+ }
+ return e.ts
+}
+
+// errReplay and errBenignReuse classify a rows-affected==0 outcome from the
+// atomic mark-used inside the rotation transaction. They never leave this file:
+// errBenignReuse replays the cached rotated token set (falling back to
+// ErrInvalidGrant when the cache has no entry), while errReplay maps to
+// ErrInvalidGrant and additionally triggers a family revoke, committed in its
+// own transaction because the rotation transaction rolls back when the
+// closure returns an error.
+var (
+ errReplay = errors.New("refresh token replayed")
+ errBenignReuse = errors.New("refresh token concurrently reused within grace")
+)
+
+// RotateRefresh owns its own transactions. Reuse detection must revoke the
+// token family even though the endpoint returns 400, so the family revoke runs
+// in its own committed transaction rather than the request-scoped one (which
+// the Transactional middleware would roll back on a non-2xx response).
+//
+// Rotation is atomic: the presented token is flipped to used inside the same
+// transaction that mints its replacement, via a conditional UPDATE whose
+// rows-affected result is the concurrency guard. If the token was already
+// consumed, we distinguish a benign concurrent retry (within reuseGrace, the
+// winner's rotated token set is replayed from the rotation cache so the loser
+// recovers) from a genuine replay of a long-since-rotated token (family
+// revoked).
+func RotateRefresh(presented string) (*models.TokenSetResponse, error) {
+ rt, err := repositories.RefreshTokenRepository.FindByToken(db.DB, presented)
+ if err != nil {
+ return nil, err
+ }
+ if rt == nil {
+ return nil, ErrInvalidGrant
+ }
+
+ if rt.Revoked {
+ revokeFamily(rt.FamilyId)
+ return nil, ErrInvalidGrant
+ }
+
+ if time.Now().After(rt.ExpiresAt) {
+ return nil, ErrInvalidGrant
+ }
+
+ ts, err := db.ExecuteTransaction(func(tx *sql.Tx) (*models.TokenSetResponse, error) {
+ affected, err := repositories.RefreshTokenRepository.MarkUsedIfUnused(tx, presented, time.Now())
+ if err != nil {
+ return nil, err
+ }
+ if affected == 0 {
+ // Someone else consumed or revoked this token between our read and
+ // this write. Re-read inside the transaction to classify it, then
+ // signal via a sentinel so the family revoke happens in a committed
+ // transaction rather than this one (which rolls back on error).
+ current, err := repositories.RefreshTokenRepository.FindByToken(tx, presented)
+ if err != nil {
+ return nil, err
+ }
+ if current != nil && !current.Revoked && current.UsedAt != nil && time.Since(*current.UsedAt) <= reuseGrace {
+ return nil, errBenignReuse
+ }
+ return nil, errReplay
+ }
+
+ user, err := repositories.UserRepository.FindById(tx, rt.UserId)
+ if err != nil {
+ return nil, err
+ }
+ if user == nil {
+ return nil, ErrInvalidGrant
+ }
+ return issueTokenSetWithFamily(tx, rt.UserId, user.Email, rt.ClientId, rt.FamilyId)
+ })
+ if err != nil {
+ if errors.Is(err, errReplay) {
+ revokeFamily(rt.FamilyId)
+ return nil, ErrInvalidGrant
+ }
+ if errors.Is(err, errBenignReuse) {
+ if cached := cachedRotation(presented); cached != nil {
+ return cached, nil
+ }
+ return nil, ErrInvalidGrant
+ }
+ return nil, err
+ }
+ storeRotation(presented, ts)
+ return ts, nil
+}
+
+// RevokeByToken revokes the entire family the presented refresh token belongs
+// to. It is idempotent and never reveals whether the token existed, so it is
+// safe to expose on an unauthenticated logout endpoint. Like RotateRefresh it
+// self-manages its transaction because the endpoint may return a non-2xx that
+// the Transactional middleware would otherwise roll back.
+func RevokeByToken(presented string) error {
+ rt, err := repositories.RefreshTokenRepository.FindByToken(db.DB, presented)
+ if err != nil {
+ return err
+ }
+ if rt == nil {
+ return nil
+ }
+ _, err = db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {
+ return struct{}{}, repositories.RefreshTokenRepository.RevokeFamily(tx, rt.FamilyId)
+ })
+ return err
+}
+
+// revokeFamily revokes a token family in its own committed transaction. It is
+// used on the error paths of RotateRefresh, where the rotation transaction has
+// rolled back but the revoke must persist. A failed revoke must not change the
+// caller's invalid_grant response, but it is a security-relevant write, so it
+// is reported instead of discarded.
+func revokeFamily(familyId string) {
+ _, err := db.ExecuteTransaction(func(tx *sql.Tx) (struct{}, error) {
+ return struct{}{}, repositories.RefreshTokenRepository.RevokeFamily(tx, familyId)
+ })
+ if err != nil {
+ traceway.CaptureException(fmt.Errorf("revoking refresh-token family %s after reuse detection: %w", familyId, err))
+ }
+}
diff --git a/backend/app/services/authserver/tokens.go b/backend/app/services/authserver/tokens.go
new file mode 100644
index 00000000..c82fdd7b
--- /dev/null
+++ b/backend/app/services/authserver/tokens.go
@@ -0,0 +1,69 @@
+package authserver
+
+import (
+ "crypto/rand"
+ "database/sql"
+ "encoding/base64"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/tracewayapp/traceway/backend/app/models"
+ "github.com/tracewayapp/traceway/backend/app/repositories"
+ "github.com/tracewayapp/traceway/backend/app/services"
+)
+
+const userCodeAlphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"
+
+func randomBytes(n int) []byte {
+ b := make([]byte, n)
+ if _, err := rand.Read(b); err != nil {
+ panic(err)
+ }
+ return b
+}
+
+func newOpaqueToken(prefix string) string {
+ return prefix + base64.RawURLEncoding.EncodeToString(randomBytes(32))
+}
+
+func newUserCode() string {
+ b := randomBytes(8)
+ var sb strings.Builder
+ for i, x := range b {
+ if i == 4 {
+ sb.WriteByte('-')
+ }
+ sb.WriteByte(userCodeAlphabet[int(x)%len(userCodeAlphabet)])
+ }
+ return sb.String()
+}
+
+func NewPATToken() string {
+ return newOpaqueToken("twp_")
+}
+
+func IssueTokenSet(tx *sql.Tx, userId int, email, clientId string) (*models.TokenSetResponse, error) {
+ return issueTokenSetWithFamily(tx, userId, email, clientId, uuid.New().String())
+}
+
+func issueTokenSetWithFamily(tx *sql.Tx, userId int, email, clientId, familyId string) (*models.TokenSetResponse, error) {
+ ttl := accessTokenTTL
+ access, err := services.GenerateAccessToken(userId, email, ttl)
+ if err != nil {
+ return nil, err
+ }
+
+ refresh := newOpaqueToken("twr_")
+ if err := repositories.RefreshTokenRepository.Insert(tx, refresh, familyId, userId, clientId, time.Now().Add(refreshTokenTTL)); err != nil {
+ return nil, err
+ }
+
+ return &models.TokenSetResponse{
+ AccessToken: access,
+ RefreshToken: refresh,
+ TokenType: "Bearer",
+ ExpiresIn: int(ttl.Seconds()),
+ Email: email,
+ }, nil
+}
diff --git a/backend/app/services/jwt.service.go b/backend/app/services/jwt.service.go
index a17bd954..77c97560 100644
--- a/backend/app/services/jwt.service.go
+++ b/backend/app/services/jwt.service.go
@@ -30,11 +30,19 @@ func InitJWT() error {
}
func GenerateToken(userId int, email string) (string, error) {
+ return generateToken(userId, email, 7*24*time.Hour)
+}
+
+func GenerateAccessToken(userId int, email string, ttl time.Duration) (string, error) {
+ return generateToken(userId, email, ttl)
+}
+
+func generateToken(userId int, email string, ttl time.Duration) (string, error) {
claims := JWTClaims{
UserId: userId,
Email: email,
RegisteredClaims: jwt.RegisteredClaims{
- ExpiresAt: jwt.NewNumericDate(time.Now().Add(7 * 24 * time.Hour)),
+ ExpiresAt: jwt.NewNumericDate(time.Now().Add(ttl)),
IssuedAt: jwt.NewNumericDate(time.Now()),
NotBefore: jwt.NewNumericDate(time.Now()),
},
diff --git a/backend/cmd/run.go b/backend/cmd/run.go
index 5ab87a9a..84026b10 100644
--- a/backend/cmd/run.go
+++ b/backend/cmd/run.go
@@ -198,6 +198,13 @@ func Run(opts ...Option) {
ctx.JSON(200, gin.H{"version": "0.0.1"})
})
+ // OAuth discovery documents must live at the origin root (RFC 8414 / RFC
+ // 9728), not under /api, so metadata-driven clients (and the future MCP
+ // integration) can find them. Registered before the SPA NoRoute fallback so
+ // they aren't shadowed by index.html.
+ router.GET("/.well-known/oauth-authorization-server", controllers.WellKnownController.AuthorizationServer)
+ router.GET("/.well-known/oauth-protected-resource", controllers.WellKnownController.ProtectedResource)
+
apiOnly := cfg.APIOnly == "true"
if apiOnly {
diff --git a/cli/README.md b/cli/README.md
index f226ea40..6638a400 100644
--- a/cli/README.md
+++ b/cli/README.md
@@ -29,6 +29,8 @@ Check an installed binary with `traceway version` (or `traceway --version`). Sou
```bash
# 1. log in (creates ~/.config/traceway/config.json + ~/.local/state/traceway/state.json)
+# Default: browser device login — prints a URL + short code, you approve in the
+# browser, and the CLI receives a token that auto-refreshes.
traceway login --url https://cloud.traceway.com
# 2. pick a project (one-time; future calls use it implicitly)
@@ -46,8 +48,8 @@ traceway metrics query --name http.server.duration --aggregation avg --since 1h
| Command | Purpose |
|---|---|
-| `traceway login` | Authenticate and store the JWT |
-| `traceway logout` | Forget the stored JWT for a profile |
+| `traceway login` | Authenticate and store a token. Three modes: default browser **device flow** (auto-refreshing); `--password` (email + password, or `--password-stdin`; passing `--username` implies this mode); `--token` / `--token-stdin` (store a personal access token). The device flow needs an interactive terminal — in CI use `--token` or `--password`, or pass `--no-browser` to drive it manually. |
+| `traceway logout` | Revoke the session server-side (device logins) and forget the stored credentials for a profile |
| `traceway profiles {list,use}` | Manage multiple Traceway accounts/instances |
| `traceway projects {list,use}` | List or select the active project |
| `traceway exceptions list` | Recent grouped exceptions |
diff --git a/cli/cmd/traceway/aitraces.go b/cli/cmd/traceway/aitraces.go
index f8f4e7ed..d542728d 100644
--- a/cli/cmd/traceway/aitraces.go
+++ b/cli/cmd/traceway/aitraces.go
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra"
"github.com/tracewayapp/traceway/cli/internal/output"
- "github.com/tracewayapp/traceway/cli/pkg/client"
)
func newAiTracesCmd() *cobra.Command {
@@ -53,7 +52,7 @@ func runAiTracesShow(cmd *cobra.Command, args []string) error {
return renderTimestampError(cmd.ErrOrStderr(), mode, "recorded-at", err)
}
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
resp, err := c.GetAiTrace(ctx, sess.ProjectID, args[0], recordedAt)
if err != nil {
return renderAPIError(cmd.ErrOrStderr(), mode, err, false)
diff --git a/cli/cmd/traceway/credentials.go b/cli/cmd/traceway/credentials.go
new file mode 100644
index 00000000..cfba711c
--- /dev/null
+++ b/cli/cmd/traceway/credentials.go
@@ -0,0 +1,91 @@
+package main
+
+import (
+ "time"
+
+ "github.com/tracewayapp/traceway/cli/internal/config"
+ "github.com/tracewayapp/traceway/cli/internal/state"
+ "github.com/tracewayapp/traceway/cli/pkg/client"
+)
+
+// credential is the result of any login path: the access token plus, for the
+// device flow, a refresh token and access-token expiry.
+type credential struct {
+ Kind string
+ AccessToken string
+ RefreshToken string
+ ExpiresAt int64
+}
+
+// saveProfileCredentials persists profile config (url/username) and runtime
+// state (tokens/kind), preserving the current project and setting the
+// CurrentProfile pointer on first login. Shared by all login paths.
+func saveProfileCredentials(cfg *config.Config, st *state.State, profileName, url, username string, cred credential) error {
+ if cfg.Profiles == nil {
+ cfg.Profiles = map[string]config.Profile{}
+ }
+ cfg.Profiles[profileName] = config.Profile{URL: url, Username: username}
+
+ if st.Profiles == nil {
+ st.Profiles = map[string]state.ProfileState{}
+ }
+ currentProject := st.Profiles[profileName].CurrentProjectID
+ st.Profiles[profileName] = state.ProfileState{
+ JWT: cred.AccessToken,
+ RefreshToken: cred.RefreshToken,
+ TokenExpiresAt: cred.ExpiresAt,
+ CredentialKind: cred.Kind,
+ CurrentProjectID: currentProject,
+ }
+ if st.CurrentProfile == "" {
+ st.CurrentProfile = profileName
+ }
+
+ if err := cfg.Save(); err != nil {
+ return err
+ }
+ return st.Save()
+}
+
+// updateProfileTokens reloads state and updates only the token fields for the
+// profile (preserving project + config), then atomically saves. Used by the
+// refresher so a silent refresh doesn't clobber a concurrent project change.
+func updateProfileTokens(profileName string, ts *client.TokenSet) error {
+ st, err := state.Load()
+ if err != nil {
+ return err
+ }
+ sp := st.Profiles[profileName]
+ sp.JWT = ts.AccessToken
+ if ts.RefreshToken != "" {
+ sp.RefreshToken = ts.RefreshToken
+ }
+ sp.TokenExpiresAt = expiresAtUnix(ts.ExpiresIn)
+ if sp.CredentialKind == "" {
+ sp.CredentialKind = state.KindDevice
+ }
+ if st.Profiles == nil {
+ st.Profiles = map[string]state.ProfileState{}
+ }
+ st.Profiles[profileName] = sp
+ return st.Save()
+}
+
+// loadProfileJWT reads just the stored access token for a profile from disk,
+// returning "" if state can't be read. The refresher uses it to adopt a token
+// another concurrent process may have already rotated, avoiding a redundant
+// refresh that would trip server-side reuse detection.
+func loadProfileJWT(profileName string) string {
+ st, err := state.Load()
+ if err != nil {
+ return ""
+ }
+ return st.Profiles[profileName].JWT
+}
+
+func expiresAtUnix(expiresInSeconds int) int64 {
+ if expiresInSeconds <= 0 {
+ return 0
+ }
+ return time.Now().Add(time.Duration(expiresInSeconds) * time.Second).Unix()
+}
diff --git a/cli/cmd/traceway/endpoints.go b/cli/cmd/traceway/endpoints.go
index e29bf100..30ed8727 100644
--- a/cli/cmd/traceway/endpoints.go
+++ b/cli/cmd/traceway/endpoints.go
@@ -70,7 +70,7 @@ func runEndpointsList(cmd *cobra.Command, _ []string) error {
enumFlagHint("traceway endpoints list", "--sort-direction", sortDirections))
}
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
resp, err := c.ListEndpoints(ctx, sess.ProjectID, client.ListEndpointsRequest{
TimeRange: tr,
Pagination: page,
@@ -145,7 +145,7 @@ func runEndpointsChart(cmd *cobra.Command, _ []string) error {
}
intervalMin, _ := cmd.Flags().GetInt("interval-minutes")
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
resp, err := c.GetEndpointChart(ctx, sess.ProjectID, client.EndpointChartRequest{
TimeRange: tr,
MetricType: metricType,
@@ -239,7 +239,7 @@ func runEndpointsSlow(cmd *cobra.Command, args []string) error {
return renderSessionError(cmd.ErrOrStderr(), mode, err)
}
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
resp, err := c.GetSlowEndpoint(ctx, sess.ProjectID, args[0])
if err != nil {
return renderAPIError(cmd.ErrOrStderr(), mode, err, false)
@@ -300,7 +300,7 @@ func runEndpointsShow(cmd *cobra.Command, args []string) error {
return renderTimestampError(cmd.ErrOrStderr(), mode, "recorded-at", err)
}
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
resp, err := c.GetEndpoint(ctx, sess.ProjectID, args[0], recordedAt)
if err != nil {
return renderAPIError(cmd.ErrOrStderr(), mode, err, false)
diff --git a/cli/cmd/traceway/exceptions.go b/cli/cmd/traceway/exceptions.go
index 90b7f4ef..5486e172 100644
--- a/cli/cmd/traceway/exceptions.go
+++ b/cli/cmd/traceway/exceptions.go
@@ -74,7 +74,7 @@ func runExceptionsList(cmd *cobra.Command, _ []string) error {
enumFlagHint("traceway exceptions list", "--order-by", exceptionsOrderBy))
}
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
resp, err := c.ListExceptions(ctx, sess.ProjectID, client.ListExceptionsRequest{
TimeRange: tr,
Pagination: page,
@@ -137,7 +137,7 @@ func runExceptionsShow(cmd *cobra.Command, args []string) error {
page := resolvePagination(cmd)
page.PageSize = pickDefault(page.PageSize, 20) // detail uses 20 by default
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
resp, err := c.GetException(ctx, sess.ProjectID, args[0], page)
if err != nil {
return renderAPIError(cmd.ErrOrStderr(), mode, err, false)
@@ -217,7 +217,7 @@ func runExceptionsOccurrence(cmd *cobra.Command, args []string) error {
return renderTimestampError(cmd.ErrOrStderr(), mode, "recorded-at", err)
}
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
resp, err := c.GetExceptionById(ctx, sess.ProjectID, args[0], recordedAt)
if err != nil {
return renderAPIError(cmd.ErrOrStderr(), mode, err, false)
@@ -313,7 +313,7 @@ func runExceptionsMutation(
return err
}
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
if err := doIt(c, ctx, sess.ProjectID, hashes); err != nil {
return renderAPIError(cmd.ErrOrStderr(), mode, err, false)
}
diff --git a/cli/cmd/traceway/login.go b/cli/cmd/traceway/login.go
index 251b119b..1fae8bd3 100644
--- a/cli/cmd/traceway/login.go
+++ b/cli/cmd/traceway/login.go
@@ -25,53 +25,74 @@ var (
loginURL string
loginUsername string
loginPasswordFile bool
+ loginPassword bool
+ loginToken string
+ loginTokenStdin bool
+ loginNoBrowser bool
)
func newLoginCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "login",
- Short: "Authenticate against a Traceway instance and store the JWT",
- RunE: runLogin,
+ Short: "Authenticate against a Traceway instance and store the token",
+ Long: "Authenticate against a Traceway instance and store the token.\n\n" +
+ "By default this starts a browser device-login flow: the CLI prints a URL\n" +
+ "and a short code, you approve in your browser, and the CLI receives a token.\n" +
+ "Use --password for email/password login, or --token to store a personal\n" +
+ "access token.",
+ RunE: runLogin,
}
cmd.Flags().StringVar(&loginURL, "url", "", "Traceway base URL (default: existing or "+defaultURL+")")
- cmd.Flags().StringVar(&loginUsername, "username", "", "Email address (default: existing or interactive prompt)")
- cmd.Flags().BoolVar(&loginPasswordFile, "password-stdin", false, "Read password from stdin instead of prompting")
+ cmd.Flags().StringVar(&loginUsername, "username", "", "Email address for password login, implies --password (default: existing or interactive prompt)")
+ cmd.Flags().BoolVar(&loginPasswordFile, "password-stdin", false, "Read password from stdin (implies --password)")
+ cmd.Flags().BoolVar(&loginPassword, "password", false, "Authenticate with email + password instead of the browser device flow")
+ cmd.Flags().StringVar(&loginToken, "token", "", "Authenticate with a personal access token")
+ cmd.Flags().BoolVar(&loginTokenStdin, "token-stdin", false, "Read a personal access token from stdin")
+ cmd.Flags().BoolVar(&loginNoBrowser, "no-browser", false, "Do not attempt to open a browser during the device flow")
return cmd
}
func runLogin(cmd *cobra.Command, _ []string) error {
+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())
+
+ tokenMode := loginToken != "" || loginTokenStdin
+ // --username selected the password flow before the device flow became the
+ // default; keep it doing so instead of silently ignoring it for auth.
+ passwordMode := loginPassword || loginPasswordFile || loginUsername != ""
+
+ if tokenMode && passwordMode {
+ return renderUsageError(cmd.ErrOrStderr(), mode, "choose one of --token or --password/--username, not both", "traceway login --help")
+ }
+ if loginToken != "" && loginTokenStdin {
+ return renderUsageError(cmd.ErrOrStderr(), mode, "choose one of --token or --token-stdin, not both", "traceway login --help")
+ }
+
+ switch {
+ case tokenMode:
+ return runLoginToken(cmd)
+ case passwordMode:
+ return runLoginPassword(cmd)
+ default:
+ return runLoginWeb(cmd)
+ }
+}
+
+func runLoginPassword(cmd *cobra.Command) error {
ctx := cmd.Context()
if ctx == nil {
ctx = context.Background()
}
+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())
- cfg, err := config.Load()
- if err != nil {
- return err
- }
- st, err := state.Load()
+ cfg, st, profileName, url, err := loadLoginContext()
if err != nil {
return err
}
- profileName := resolveProfileName(st)
-
- existingCfg, hasCfg := cfg.Profiles[profileName]
- existingState, hasState := st.Profiles[profileName]
-
- url := loginURL
- if url == "" {
- if hasCfg {
- url = existingCfg.URL
- } else {
- url = defaultURL
- }
- }
-
username := loginUsername
if username == "" {
- if hasCfg {
- username = existingCfg.Username
+ if existing, ok := cfg.Profiles[profileName]; ok {
+ username = existing.Username
}
if username == "" {
username, err = promptUsername(cmd.InOrStdin(), cmd.OutOrStdout())
@@ -86,46 +107,42 @@ func runLogin(cmd *cobra.Command, _ []string) error {
return err
}
- mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())
- c := client.New(url)
- jwt, err := c.Login(ctx, username, password)
+ jwt, err := client.New(url).Login(ctx, username, password)
if err != nil {
return renderAPIError(cmd.ErrOrStderr(), mode, err, true)
}
- if cfg.Profiles == nil {
- cfg.Profiles = map[string]config.Profile{}
- }
- cfg.Profiles[profileName] = config.Profile{
- URL: url,
- Username: username,
+ if err := saveProfileCredentials(cfg, st, profileName, url, username, credential{Kind: state.KindPassword, AccessToken: jwt}); err != nil {
+ return err
}
- if st.Profiles == nil {
- st.Profiles = map[string]state.ProfileState{}
- }
- currentProject := ""
- if hasState {
- currentProject = existingState.CurrentProjectID
- }
- st.Profiles[profileName] = state.ProfileState{
- JWT: jwt,
- CurrentProjectID: currentProject,
- }
- // First profile ever → set CurrentProfile pointer. Don't override on subsequent logins.
- if st.CurrentProfile == "" {
- st.CurrentProfile = profileName
- }
+ _, err = fmt.Fprintf(cmd.OutOrStdout(), "Logged in as %s on %s (profile: %s)\n", username, url, profileName)
+ return err
+}
- if err := cfg.Save(); err != nil {
- return err
+// loadLoginContext loads config + state and resolves the active profile name
+// and base URL, shared by all login paths.
+func loadLoginContext() (*config.Config, *state.State, string, string, error) {
+ cfg, err := config.Load()
+ if err != nil {
+ return nil, nil, "", "", err
}
- if err := st.Save(); err != nil {
- return err
+ st, err := state.Load()
+ if err != nil {
+ return nil, nil, "", "", err
}
- _, err = fmt.Fprintf(cmd.OutOrStdout(), "Logged in as %s on %s (profile: %s)\n", username, url, profileName)
- return err
+ profileName := resolveProfileName(st)
+
+ url := loginURL
+ if url == "" {
+ if existing, ok := cfg.Profiles[profileName]; ok && existing.URL != "" {
+ url = existing.URL
+ } else {
+ url = defaultURL
+ }
+ }
+ return cfg, st, profileName, url, nil
}
func promptUsername(in io.Reader, out io.Writer) (string, error) {
diff --git a/cli/cmd/traceway/login_token.go b/cli/cmd/traceway/login_token.go
new file mode 100644
index 00000000..901ae35f
--- /dev/null
+++ b/cli/cmd/traceway/login_token.go
@@ -0,0 +1,67 @@
+package main
+
+import (
+ "bufio"
+ "context"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+
+ "github.com/spf13/cobra"
+
+ "github.com/tracewayapp/traceway/cli/internal/output"
+ "github.com/tracewayapp/traceway/cli/internal/state"
+ "github.com/tracewayapp/traceway/cli/pkg/client"
+)
+
+func runLoginToken(cmd *cobra.Command) error {
+ ctx := cmd.Context()
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())
+
+ cfg, st, profileName, url, err := loadLoginContext()
+ if err != nil {
+ return err
+ }
+
+ token := strings.TrimSpace(loginToken)
+ if loginTokenStdin {
+ token, err = readTokenStdin(cmd.InOrStdin())
+ if err != nil {
+ return err
+ }
+ }
+ if token == "" {
+ return renderUsageError(cmd.ErrOrStderr(), mode, "no token provided", "traceway login --token <token>")
+ }
+
+ username := loginUsername
+ if username == "" {
+ if existing, ok := cfg.Profiles[profileName]; ok {
+ username = existing.Username
+ }
+ }
+
+ if _, err := client.New(url, client.WithJWT(token)).ListProjects(ctx); err != nil {
+ return renderAPIError(cmd.ErrOrStderr(), mode, err, false)
+ }
+
+ if err := saveProfileCredentials(cfg, st, profileName, url, username, credential{Kind: state.KindPAT, AccessToken: token}); err != nil {
+ return err
+ }
+
+ _, err = fmt.Fprintf(cmd.OutOrStdout(), "Stored personal access token for %s (profile: %s)\n", url, profileName)
+ return err
+}
+
+func readTokenStdin(in io.Reader) (string, error) {
+ r := bufio.NewReader(in)
+ line, err := r.ReadString('\n')
+ if err != nil && !errors.Is(err, io.EOF) {
+ return "", err
+ }
+ return strings.TrimSpace(line), nil
+}
diff --git a/cli/cmd/traceway/login_token_test.go b/cli/cmd/traceway/login_token_test.go
new file mode 100644
index 00000000..6c28d5b9
--- /dev/null
+++ b/cli/cmd/traceway/login_token_test.go
@@ -0,0 +1,79 @@
+package main
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/tracewayapp/traceway/cli/internal/state"
+)
+
+func TestLoginToken_success(t *testing.T) {
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ t.Setenv("XDG_STATE_HOME", t.TempDir())
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Authorization") != "Bearer twp_secret" {
+ t.Errorf("auth = %q", r.Header.Get("Authorization"))
+ }
+ _, _ = w.Write([]byte(`[]`))
+ }))
+ defer srv.Close()
+
+ if _, _, err := runCmd(t, "", "login", "--url", srv.URL, "--token", "twp_secret"); err != nil {
+ t.Fatalf("login token: %v", err)
+ }
+
+ st, _ := state.Load()
+ sp := st.Profiles["default"]
+ if sp.CredentialKind != state.KindPAT {
+ t.Errorf("kind = %q, want pat", sp.CredentialKind)
+ }
+ if sp.JWT != "twp_secret" {
+ t.Errorf("jwt = %q", sp.JWT)
+ }
+ if sp.RefreshToken != "" {
+ t.Errorf("unexpected refresh token %q", sp.RefreshToken)
+ }
+}
+
+func TestLoginToken_stdin_success(t *testing.T) {
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ t.Setenv("XDG_STATE_HOME", t.TempDir())
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("Authorization") != "Bearer twp_fromstdin" {
+ t.Errorf("auth = %q", r.Header.Get("Authorization"))
+ }
+ _, _ = w.Write([]byte(`[]`))
+ }))
+ defer srv.Close()
+
+ if _, _, err := runCmd(t, "twp_fromstdin\n", "login", "--url", srv.URL, "--token-stdin"); err != nil {
+ t.Fatalf("login token-stdin: %v", err)
+ }
+
+ st, _ := state.Load()
+ if st.Profiles["default"].JWT != "twp_fromstdin" {
+ t.Errorf("jwt = %q", st.Profiles["default"].JWT)
+ }
+}
+
+func TestLoginToken_rejected_doesNotSave(t *testing.T) {
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ t.Setenv("XDG_STATE_HOME", t.TempDir())
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusUnauthorized)
+ }))
+ defer srv.Close()
+
+ _, _, err := runCmd(t, "", "login", "--url", srv.URL, "--token", "twp_bad")
+ if err == nil {
+ t.Fatal("expected error for rejected token")
+ }
+ st, _ := state.Load()
+ if _, ok := st.Profiles["default"]; ok {
+ t.Error("profile should not be saved when token is rejected")
+ }
+}
diff --git a/cli/cmd/traceway/login_web.go b/cli/cmd/traceway/login_web.go
new file mode 100644
index 00000000..684f0769
--- /dev/null
+++ b/cli/cmd/traceway/login_web.go
@@ -0,0 +1,160 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os/exec"
+ "runtime"
+ "time"
+
+ "github.com/spf13/cobra"
+
+ "github.com/tracewayapp/traceway/cli/internal/exitcode"
+ "github.com/tracewayapp/traceway/cli/internal/output"
+ "github.com/tracewayapp/traceway/cli/internal/state"
+ "github.com/tracewayapp/traceway/cli/pkg/client"
+)
+
+func runLoginWeb(cmd *cobra.Command) error {
+ ctx := cmd.Context()
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())
+ out := cmd.OutOrStdout()
+
+ // The device flow needs a human to approve the code in a browser. In a
+ // non-interactive context (CI, scripts) nobody will, so it would otherwise
+ // poll uselessly until the ~10-minute deadline — fail fast and point at the
+ // non-interactive login modes instead. --no-browser is the explicit opt-in
+ // for driving the flow manually (e.g. a headless box where the code is
+ // approved from another device), so it suppresses the guard.
+ if !loginNoBrowser && !output.StdoutIsTerminal() {
+ return renderUsageError(cmd.ErrOrStderr(), mode,
+ "the browser device-login flow requires an interactive terminal",
+ "use 'traceway login --token <token>' or 'traceway login --password' for non-interactive login")
+ }
+
+ cfg, st, profileName, url, err := loadLoginContext()
+ if err != nil {
+ return err
+ }
+
+ c := client.New(url)
+ da, err := c.DeviceAuthorize(ctx, "")
+ if err != nil {
+ // A backend that predates the device flow 404s the authorize endpoint,
+ // or serves the SPA's index.html (a JSON syntax error). Point at the
+ // password flow instead of surfacing an opaque error.
+ var syntaxErr *json.SyntaxError
+ if errors.Is(err, client.ErrNotFound) || errors.As(err, &syntaxErr) {
+ _ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{
+ Code: "device_login_unsupported",
+ Message: "this server does not support the browser device-login flow (it may be running an older Traceway version)",
+ Hint: "traceway login --password",
+ ExitCode: exitcode.Auth,
+ })
+ return newCLIError(exitcode.Auth, "device_login_unsupported")
+ }
+ return renderAPIError(cmd.ErrOrStderr(), mode, err, true)
+ }
+
+ openURL := da.VerificationURIComplete
+ if openURL == "" {
+ openURL = da.VerificationURI
+ }
+
+ _, _ = fmt.Fprintf(out, "\nTo sign in, open this URL in your browser:\n\n %s\n\n", da.VerificationURI)
+ _, _ = fmt.Fprintf(out, "And enter the code: %s\n\n", da.UserCode)
+
+ if !loginNoBrowser && output.StdoutIsTerminal() {
+ _ = openBrowser(openURL)
+ }
+ _, _ = fmt.Fprintln(out, "Waiting for authorization...")
+
+ interval := da.Interval
+ if interval < 1 {
+ interval = 5
+ }
+ deadline := time.Now().Add(10 * time.Minute)
+ if da.ExpiresIn > 0 {
+ deadline = time.Now().Add(time.Duration(da.ExpiresIn) * time.Second)
+ }
+
+ for {
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-time.After(time.Duration(interval) * time.Second):
+ }
+
+ if time.Now().After(deadline) {
+ return renderDeviceError(cmd.ErrOrStderr(), mode, "device_code_expired", "the login request expired before it was approved")
+ }
+
+ ts, err := c.PollDeviceToken(ctx, da.DeviceCode)
+ if err != nil {
+ switch {
+ case errors.Is(err, client.ErrAuthorizationPending):
+ continue
+ case errors.Is(err, client.ErrSlowDown):
+ interval += 5
+ continue
+ case errors.Is(err, client.ErrAccessDenied):
+ return renderDeviceError(cmd.ErrOrStderr(), mode, "access_denied", "the login request was denied")
+ case errors.Is(err, client.ErrExpiredToken):
+ return renderDeviceError(cmd.ErrOrStderr(), mode, "device_code_expired", "the login request expired before it was approved")
+ default:
+ return renderAPIError(cmd.ErrOrStderr(), mode, err, true)
+ }
+ }
+
+ username := ts.Email
+ if username == "" {
+ username = loginUsername
+ }
+ cred := credential{
+ Kind: state.KindDevice,
+ AccessToken: ts.AccessToken,
+ RefreshToken: ts.RefreshToken,
+ ExpiresAt: expiresAtUnix(ts.ExpiresIn),
+ }
+ if err := saveProfileCredentials(cfg, st, profileName, url, username, cred); err != nil {
+ return err
+ }
+
+ who := username
+ if who == "" {
+ who = "you"
+ }
+ _, err = fmt.Fprintf(out, "\nLogged in as %s on %s (profile: %s)\n", who, url, profileName)
+ return err
+ }
+}
+
+func renderDeviceError(errOut io.Writer, mode output.Mode, code, msg string) error {
+ _ = output.RenderError(errOut, mode, output.ErrorEnvelope{
+ Code: code,
+ Message: msg,
+ Hint: "traceway login",
+ ExitCode: exitcode.Auth,
+ })
+ return newCLIError(exitcode.Auth, code)
+}
+
+func openBrowser(url string) error {
+ var name string
+ var args []string
+ switch runtime.GOOS {
+ case "darwin":
+ name, args = "open", []string{url}
+ case "windows":
+ name, args = "rundll32", []string{"url.dll,FileProtocolHandler", url}
+ default:
+ name, args = "xdg-open", []string{url}
+ }
+ return exec.Command(name, args...).Start()
+}
diff --git a/cli/cmd/traceway/login_web_test.go b/cli/cmd/traceway/login_web_test.go
new file mode 100644
index 00000000..a65360d9
--- /dev/null
+++ b/cli/cmd/traceway/login_web_test.go
@@ -0,0 +1,56 @@
+package main
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/tracewayapp/traceway/cli/internal/state"
+)
+
+func TestLoginWeb_deviceFlow_success(t *testing.T) {
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ t.Setenv("XDG_STATE_HOME", t.TempDir())
+
+ polls := 0
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/auth/device/authorize":
+ _, _ = w.Write([]byte(`{"device_code":"dev","user_code":"AAAA-BBBB","verification_uri":"http://x/device","verification_uri_complete":"http://x/device?user_code=AAAA-BBBB","expires_in":600,"interval":1}`))
+ case "/api/auth/device/token":
+ polls++
+ if polls == 1 {
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = w.Write([]byte(`{"error":"authorization_pending"}`))
+ return
+ }
+ _, _ = w.Write([]byte(`{"access_token":"at","refresh_token":"rt","token_type":"Bearer","expires_in":900,"email":"[email protected]"}`))
+ default:
+ t.Errorf("unexpected path %q", r.URL.Path)
+ }
+ }))
+ defer srv.Close()
+
+ _, _, err := runCmd(t, "", "login", "--url", srv.URL, "--no-browser")
+ if err != nil {
+ t.Fatalf("login web: %v", err)
+ }
+
+ st, _ := state.Load()
+ sp, ok := st.Profiles["default"]
+ if !ok {
+ t.Fatal("default profile not saved")
+ }
+ if sp.CredentialKind != state.KindDevice {
+ t.Errorf("kind = %q, want device", sp.CredentialKind)
+ }
+ if sp.JWT != "at" {
+ t.Errorf("jwt = %q", sp.JWT)
+ }
+ if sp.RefreshToken != "rt" {
+ t.Errorf("refresh token = %q", sp.RefreshToken)
+ }
+ if sp.TokenExpiresAt == 0 {
+ t.Error("token expiry not recorded")
+ }
+}
diff --git a/cli/cmd/traceway/logout.go b/cli/cmd/traceway/logout.go
index 36a02abf..ed6d0bbb 100644
--- a/cli/cmd/traceway/logout.go
+++ b/cli/cmd/traceway/logout.go
@@ -1,6 +1,7 @@
package main
import (
+ "context"
"fmt"
"github.com/spf13/cobra"
@@ -9,6 +10,7 @@ import (
"github.com/tracewayapp/traceway/cli/internal/exitcode"
"github.com/tracewayapp/traceway/cli/internal/output"
"github.com/tracewayapp/traceway/cli/internal/state"
+ "github.com/tracewayapp/traceway/cli/pkg/client"
)
func newLogoutCmd() *cobra.Command {
@@ -31,8 +33,8 @@ func runLogout(cmd *cobra.Command, _ []string) error {
name := resolveProfileName(st)
- _, inCfg := cfg.Profiles[name]
- _, inState := st.Profiles[name]
+ cp, inCfg := cfg.Profiles[name]
+ sp, inState := st.Profiles[name]
if !inCfg && !inState {
mode := output.ResolveMode(flagOutput, output.StdoutIsTerminal())
_ = output.RenderError(cmd.ErrOrStderr(), mode, output.ErrorEnvelope{
@@ -43,6 +45,17 @@ func runLogout(cmd *cobra.Command, _ []string) error {
return newCLIError(exitcode.Auth, "no_profile")
}
+ // Best-effort server-side revoke of the device session before we drop the
+ // local credentials. Errors are ignored: local logout must always succeed,
+ // even offline.
+ if sp.CredentialKind == state.KindDevice && sp.RefreshToken != "" && cp.URL != "" {
+ ctx := cmd.Context()
+ if ctx == nil {
+ ctx = context.Background()
+ }
+ _ = client.New(cp.URL).Logout(ctx, sp.RefreshToken)
+ }
+
delete(cfg.Profiles, name)
delete(st.Profiles, name)
diff --git a/cli/cmd/traceway/logs.go b/cli/cmd/traceway/logs.go
index a2a7226a..4d8c0650 100644
--- a/cli/cmd/traceway/logs.go
+++ b/cli/cmd/traceway/logs.go
@@ -74,7 +74,7 @@ func runLogsQuery(cmd *cobra.Command, _ []string) error {
enumFlagHint("traceway logs query", "--sort-direction", sortDirections))
}
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
resp, err := c.QueryLogs(ctx, sess.ProjectID, client.QueryLogsRequest{
TimeRange: tr,
Pagination: page,
diff --git a/cli/cmd/traceway/metrics.go b/cli/cmd/traceway/metrics.go
index 6f064911..325f853d 100644
--- a/cli/cmd/traceway/metrics.go
+++ b/cli/cmd/traceway/metrics.go
@@ -71,7 +71,7 @@ func runMetricsQuery(cmd *cobra.Command, _ []string) error {
"use --tag key=value (repeatable)")
}
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
resp, err := c.QueryMetrics(ctx, sess.ProjectID, client.QueryMetricsRequest{
TimeRange: tr,
IntervalMinutes: intervalMin,
diff --git a/cli/cmd/traceway/projects.go b/cli/cmd/traceway/projects.go
index 2c64678d..52f607f8 100644
--- a/cli/cmd/traceway/projects.go
+++ b/cli/cmd/traceway/projects.go
@@ -9,7 +9,6 @@ import (
"github.com/tracewayapp/traceway/cli/internal/exitcode"
"github.com/tracewayapp/traceway/cli/internal/output"
"github.com/tracewayapp/traceway/cli/internal/state"
- "github.com/tracewayapp/traceway/cli/pkg/client"
)
func newProjectsCmd() *cobra.Command {
@@ -67,7 +66,7 @@ func runProjectsList(cmd *cobra.Command, _ []string) error {
return newCLIError(exitcode.Auth, "not_authenticated")
}
- c := client.New(cfgProfile.URL, client.WithJWT(stateProfile.JWT))
+ c := newRefreshingClient(cfgProfile.URL, profileName, stateProfile.JWT, stateProfile.RefreshToken, stateProfile.CredentialKind)
projects, err := c.ListProjects(ctx)
if err != nil {
return renderAPIError(cmd.ErrOrStderr(), mode, err, false)
diff --git a/cli/cmd/traceway/session.go b/cli/cmd/traceway/session.go
index 42ad9e23..459c989b 100644
--- a/cli/cmd/traceway/session.go
+++ b/cli/cmd/traceway/session.go
@@ -1,24 +1,29 @@
package main
import (
+ "context"
"errors"
"fmt"
"io"
+ "os"
"github.com/tracewayapp/traceway/cli/internal/config"
"github.com/tracewayapp/traceway/cli/internal/exitcode"
"github.com/tracewayapp/traceway/cli/internal/output"
"github.com/tracewayapp/traceway/cli/internal/state"
+ "github.com/tracewayapp/traceway/cli/pkg/client"
)
// session bundles everything a query command needs after resolving config,
// state, the active profile, and the project ID. Built by loadSession.
type session struct {
- ProfileName string
- URL string
- Username string
- JWT string
- ProjectID string
+ ProfileName string
+ URL string
+ Username string
+ JWT string
+ RefreshToken string
+ Kind string
+ ProjectID string
}
// Sentinel errors so the caller can map them to the right error envelope.
@@ -62,14 +67,80 @@ func loadSession() (*session, error) {
}
return &session{
- ProfileName: name,
- URL: cp.URL,
- Username: cp.Username,
- JWT: sp.JWT,
- ProjectID: projectID,
+ ProfileName: name,
+ URL: cp.URL,
+ Username: cp.Username,
+ JWT: sp.JWT,
+ RefreshToken: sp.RefreshToken,
+ Kind: sp.CredentialKind,
+ ProjectID: projectID,
}, nil
}
+// errNoRefresh wraps client.ErrUnauthorized so the transport maps it back to
+// the token_expired envelope: for password/PAT credentials a 401 genuinely
+// means "log in again", unlike a failed device-flow refresh.
+var errNoRefresh = fmt.Errorf("session: no refresh token for profile: %w", client.ErrUnauthorized)
+
+// Client builds an API client for this session that transparently refreshes
+// the access token on a 401 (device logins) and persists the rotated tokens.
+func (s *session) Client(opts ...client.Option) *client.Client {
+ return newRefreshingClient(s.URL, s.ProfileName, s.JWT, s.RefreshToken, s.Kind, opts...)
+}
+
+// newRefreshingClient returns a client whose refresher exchanges the stored
+// refresh token for a new access token and persists the rotation. Non-device
+// credentials (password, PAT) have no refresh token, so the refresher reports
+// errNoRefresh and the original 401 surfaces as token_expired.
+//
+// The refresher is lock-free but concurrency-safe: because refresh tokens are
+// single-use and the server revokes a family on genuine replay, two CLI
+// processes racing to refresh the same token must not both call the server. So
+// before (and after a lost race) it re-reads the on-disk token; if another
+// process already rotated it, we adopt that token instead of minting a new one.
+// A failed persist is non-fatal for the current command, and a retry within the
+// server's reuse-grace window is answered with the same rotated token set; a
+// later command re-presenting the stale token is treated as a replay, revoking
+// the family, so the warning below tells the user a re-login may be needed.
+func newRefreshingClient(url, profileName, jwt, refreshToken, kind string, opts ...client.Option) *client.Client {
+ rt := refreshToken
+ current := jwt
+ refresher := func(ctx context.Context) (string, error) {
+ if kind != state.KindDevice || rt == "" {
+ return "", errNoRefresh
+ }
+
+ // Another process may have already refreshed; prefer its token.
+ if disk := loadProfileJWT(profileName); disk != "" && disk != current {
+ current = disk
+ return disk, nil
+ }
+
+ ts, err := client.New(url).Refresh(ctx, rt)
+ if err != nil {
+ // Lost a refresh race: the winner may have just persisted a token.
+ if errors.Is(err, client.ErrInvalidGrant) {
+ if disk := loadProfileJWT(profileName); disk != "" && disk != current {
+ current = disk
+ return disk, nil
+ }
+ }
+ return "", err
+ }
+
+ if perr := updateProfileTokens(profileName, ts); perr != nil {
+ fmt.Fprintf(os.Stderr, "warning: refreshed access token but could not save it: %v (later commands may require 'traceway login' again)\n", perr)
+ }
+ if ts.RefreshToken != "" {
+ rt = ts.RefreshToken
+ }
+ current = ts.AccessToken
+ return ts.AccessToken, nil
+ }
+ base := []client.Option{client.WithJWT(jwt), client.WithRefresher(refresher)}
+ return client.New(url, append(base, opts...)...)
+}
+
// renderSessionError maps loadSession sentinel errors to envelopes.
func renderSessionError(errOut io.Writer, mode output.Mode, err error) error {
switch {
diff --git a/cli/cmd/traceway/session_refresh_test.go b/cli/cmd/traceway/session_refresh_test.go
new file mode 100644
index 00000000..701010b3
--- /dev/null
+++ b/cli/cmd/traceway/session_refresh_test.go
@@ -0,0 +1,60 @@
+package main
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/tracewayapp/traceway/cli/internal/config"
+ "github.com/tracewayapp/traceway/cli/internal/state"
+)
+
+func TestSession_refreshesExpiredDeviceToken(t *testing.T) {
+ t.Setenv("XDG_CONFIG_HOME", t.TempDir())
+ t.Setenv("XDG_STATE_HOME", t.TempDir())
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ switch r.URL.Path {
+ case "/api/auth/token":
+ _, _ = w.Write([]byte(`{"access_token":"fresh","refresh_token":"rt2","expires_in":900,"email":"[email protected]"}`))
+ case "/api/projects":
+ if r.Header.Get("Authorization") == "Bearer stale" {
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ if r.Header.Get("Authorization") != "Bearer fresh" {
+ t.Errorf("retry auth = %q", r.Header.Get("Authorization"))
+ }
+ _, _ = w.Write([]byte(`[]`))
+ default:
+ t.Errorf("unexpected path %q", r.URL.Path)
+ }
+ }))
+ defer srv.Close()
+
+ cfg := &config.Config{Profiles: map[string]config.Profile{
+ "default": {URL: srv.URL, Username: "[email protected]"},
+ }}
+ if err := cfg.Save(); err != nil {
+ t.Fatal(err)
+ }
+ st := &state.State{CurrentProfile: "default", Profiles: map[string]state.ProfileState{
+ "default": {JWT: "stale", RefreshToken: "rt", CredentialKind: state.KindDevice, CurrentProjectID: "proj-1"},
+ }}
+ if err := st.Save(); err != nil {
+ t.Fatal(err)
+ }
+
+ if _, _, err := runCmd(t, "", "projects", "list"); err != nil {
+ t.Fatalf("projects list: %v", err)
+ }
+
+ got, _ := state.Load()
+ sp := got.Profiles["default"]
+ if sp.JWT != "fresh" {
+ t.Errorf("access token not refreshed in state: %q", sp.JWT)
+ }
+ if sp.RefreshToken != "rt2" {
+ t.Errorf("refresh token not rotated in state: %q", sp.RefreshToken)
+ }
+}
diff --git a/cli/cmd/traceway/sessions.go b/cli/cmd/traceway/sessions.go
index 713de7db..86564c9f 100644
--- a/cli/cmd/traceway/sessions.go
+++ b/cli/cmd/traceway/sessions.go
@@ -7,7 +7,6 @@ import (
"github.com/spf13/cobra"
"github.com/tracewayapp/traceway/cli/internal/output"
- "github.com/tracewayapp/traceway/cli/pkg/client"
)
func newSessionsCmd() *cobra.Command {
@@ -54,7 +53,7 @@ func runSessionsShow(cmd *cobra.Command, args []string) error {
return renderTimestampError(cmd.ErrOrStderr(), mode, "started-at", err)
}
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
resp, err := c.GetSession(ctx, sess.ProjectID, args[0], startedAt)
if err != nil {
return renderAPIError(cmd.ErrOrStderr(), mode, err, false)
diff --git a/cli/cmd/traceway/tasks.go b/cli/cmd/traceway/tasks.go
index 11d56a9b..ec3dd777 100644
--- a/cli/cmd/traceway/tasks.go
+++ b/cli/cmd/traceway/tasks.go
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra"
"github.com/tracewayapp/traceway/cli/internal/output"
- "github.com/tracewayapp/traceway/cli/pkg/client"
)
func newTasksCmd() *cobra.Command {
@@ -52,7 +51,7 @@ func runTasksShow(cmd *cobra.Command, args []string) error {
return renderTimestampError(cmd.ErrOrStderr(), mode, "recorded-at", err)
}
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
resp, err := c.GetTask(ctx, sess.ProjectID, args[0], recordedAt)
if err != nil {
return renderAPIError(cmd.ErrOrStderr(), mode, err, false)
diff --git a/cli/cmd/traceway/traces.go b/cli/cmd/traceway/traces.go
index 0b157914..754371d9 100644
--- a/cli/cmd/traceway/traces.go
+++ b/cli/cmd/traceway/traces.go
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra"
"github.com/tracewayapp/traceway/cli/internal/output"
- "github.com/tracewayapp/traceway/cli/pkg/client"
)
func newTracesCmd() *cobra.Command {
@@ -57,7 +56,7 @@ func runTracesShow(cmd *cobra.Command, args []string) error {
return renderTimestampError(cmd.ErrOrStderr(), mode, "recorded-at", err)
}
- c := client.New(sess.URL, client.WithJWT(sess.JWT))
+ c := sess.Client()
resp, err := c.GetDistributedTrace(ctx, args[0], recordedAt)
if err != nil {
return renderAPIError(cmd.ErrOrStderr(), mode, err, false)
diff --git a/cli/internal/state/state.go b/cli/internal/state/state.go
index feb8871d..9108e66d 100644
--- a/cli/internal/state/state.go
+++ b/cli/internal/state/state.go
@@ -18,9 +18,20 @@ type State struct {
Profiles map[string]ProfileState `json:"profiles"`
}
+// Credential kinds stored on ProfileState.CredentialKind. An empty value is
+// treated as a legacy password login (non-refreshable).
+const (
+ KindPassword = "password"
+ KindDevice = "device"
+ KindPAT = "pat"
+)
+
// ProfileState holds runtime state for a single Traceway profile.
type ProfileState struct {
JWT string `json:"jwt"`
+ RefreshToken string `json:"refresh_token,omitempty"`
+ TokenExpiresAt int64 `json:"token_expires_at,omitempty"`
+ CredentialKind string `json:"credential_kind,omitempty"`
CurrentProjectID string `json:"current_project_id,omitempty"`
}
diff --git a/cli/pkg/client/auth.go b/cli/pkg/client/auth.go
index 590c2ccb..3decce2b 100644
--- a/cli/pkg/client/auth.go
+++ b/cli/pkg/client/auth.go
@@ -2,6 +2,7 @@ package client
import (
"context"
+ "encoding/json"
"errors"
"net/http"
)
@@ -28,3 +29,107 @@ func (c *Client) Login(ctx context.Context, email, password string) (string, err
}
return resp.Token, nil
}
+
+// DeviceAuth is the response from starting the device authorization flow.
+type DeviceAuth struct {
+ DeviceCode string `json:"device_code"`
+ UserCode string `json:"user_code"`
+ VerificationURI string `json:"verification_uri"`
+ VerificationURIComplete string `json:"verification_uri_complete"`
+ ExpiresIn int `json:"expires_in"`
+ Interval int `json:"interval"`
+}
+
+// TokenSet is the access + refresh token pair issued by the device-code and
+// refresh grants.
+type TokenSet struct {
+ AccessToken string `json:"access_token"`
+ RefreshToken string `json:"refresh_token"`
+ TokenType string `json:"token_type"`
+ ExpiresIn int `json:"expires_in"`
+ Email string `json:"email"`
+}
+
+type deviceAuthorizeRequest struct {
+ ClientID string `json:"client_id,omitempty"`
+}
+
+// DeviceAuthorize starts the device authorization flow and returns the user
+// code, verification URL, and polling parameters.
+func (c *Client) DeviceAuthorize(ctx context.Context, clientID string) (*DeviceAuth, error) {
+ var resp DeviceAuth
+ if err := c.do(ctx, http.MethodPost, "/api/auth/device/authorize", deviceAuthorizeRequest{ClientID: clientID}, &resp); err != nil {
+ return nil, err
+ }
+ return &resp, nil
+}
+
+type deviceTokenRequest struct {
+ GrantType string `json:"grant_type"`
+ DeviceCode string `json:"device_code"`
+}
+
+// PollDeviceToken polls the token endpoint once. It returns ErrAuthorizationPending,
+// ErrSlowDown, ErrAccessDenied, or ErrExpiredToken to drive the polling loop.
+func (c *Client) PollDeviceToken(ctx context.Context, deviceCode string) (*TokenSet, error) {
+ var resp TokenSet
+ if err := c.do(ctx, http.MethodPost, "/api/auth/device/token", deviceTokenRequest{GrantType: "device_code", DeviceCode: deviceCode}, &resp); err != nil {
+ return nil, mapOAuthError(err)
+ }
+ return &resp, nil
+}
+
+type refreshRequest struct {
+ GrantType string `json:"grant_type"`
+ RefreshToken string `json:"refresh_token"`
+}
+
+// Refresh exchanges a refresh token for a new token set (with a rotated refresh
+// token). It returns ErrInvalidGrant when the refresh token is expired, revoked,
+// or reused.
+func (c *Client) Refresh(ctx context.Context, refreshToken string) (*TokenSet, error) {
+ var resp TokenSet
+ if err := c.do(ctx, http.MethodPost, "/api/auth/token", refreshRequest{GrantType: "refresh_token", RefreshToken: refreshToken}, &resp); err != nil {
+ return nil, mapOAuthError(err)
+ }
+ return &resp, nil
+}
+
+type logoutRequest struct {
+ RefreshToken string `json:"refresh_token"`
+}
+
+// Logout revokes the refresh token's family server-side so the session cannot
+// be refreshed after the local credentials are removed. It is idempotent; the
+// caller should treat any error as non-fatal (local logout must still succeed).
+func (c *Client) Logout(ctx context.Context, refreshToken string) error {
+ return c.do(ctx, http.MethodPost, "/api/auth/logout", logoutRequest{RefreshToken: refreshToken}, nil)
+}
+
+// mapOAuthError translates an OAuth-style {"error":"..."} 400 body into the
+// matching sentinel error.
+func mapOAuthError(err error) error {
+ var apiErr *APIError
+ if !errors.As(err, &apiErr) {
+ return err
+ }
+ var body struct {
+ Error string `json:"error"`
+ }
+ if jsonErr := json.Unmarshal([]byte(apiErr.Body), &body); jsonErr != nil {
+ return err
+ }
+ switch body.Error {
+ case "authorization_pending":
+ return ErrAuthorizationPending
+ case "slow_down":
+ return ErrSlowDown
+ case "access_denied":
+ return ErrAccessDenied
+ case "expired_token":
+ return ErrExpiredToken
+ case "invalid_grant":
+ return ErrInvalidGrant
+ }
+ return err
+}
diff --git a/cli/pkg/client/client.go b/cli/pkg/client/client.go
index c65cacc0..bdf6ace7 100644
--- a/cli/pkg/client/client.go
+++ b/cli/pkg/client/client.go
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"fmt"
"io"
"net/http"
@@ -17,8 +18,13 @@ type Client struct {
HTTPClient *http.Client
JWT string
UserAgent string
+ refresher Refresher
}
+// Refresher returns a fresh access token (JWT) when the current one is
+// rejected. do() invokes it at most once per request, on a 401, then retries.
+type Refresher func(ctx context.Context) (string, error)
+
// Option mutates a Client during construction.
type Option func(*Client)
@@ -46,34 +52,69 @@ func WithJWT(jwt string) Option {
return func(c *Client) { c.JWT = jwt }
}
+// WithRefresher enables transparent access-token refresh: on a 401, do()
+// calls the refresher for a new token and retries the request once.
+func WithRefresher(r Refresher) Option {
+ return func(c *Client) { c.refresher = r }
+}
+
// do is the internal HTTP transport. It JSON-encodes body (if non-nil),
// JSON-decodes the response into out (if non-nil), and maps non-2xx status
// codes to typed errors.
func (c *Client) do(ctx context.Context, method, path string, body, out any) error {
- var reqBody io.Reader
+ var buf []byte
if body != nil {
- buf, err := json.Marshal(body)
+ b, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("encoding request body: %w", err)
}
- reqBody = bytes.NewReader(buf)
+ buf = b
}
- req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, reqBody)
- if err != nil {
- return fmt.Errorf("building request: %w", err)
- }
- req.Header.Set("Content-Type", "application/json")
- req.Header.Set("Accept", "application/json")
- req.Header.Set("User-Agent", c.UserAgent)
- if c.JWT != "" {
- req.Header.Set("Authorization", "Bearer "+c.JWT)
+ attempt := func() (*http.Response, error) {
+ var reqBody io.Reader
+ if buf != nil {
+ reqBody = bytes.NewReader(buf)
+ }
+ req, err := http.NewRequestWithContext(ctx, method, c.BaseURL+path, reqBody)
+ if err != nil {
+ return nil, fmt.Errorf("building request: %w", err)
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Accept", "application/json")
+ req.Header.Set("User-Agent", c.UserAgent)
+ if c.JWT != "" {
+ req.Header.Set("Authorization", "Bearer "+c.JWT)
+ }
+ return c.HTTPClient.Do(req)
}
- resp, err := c.HTTPClient.Do(req)
+ resp, err := attempt()
if err != nil {
return err
}
+
+ if resp.StatusCode == http.StatusUnauthorized && c.refresher != nil {
+ resp.Body.Close()
+ newJWT, refreshErr := c.refresher(ctx)
+ if refreshErr != nil {
+ // Only a dead session maps to ErrUnauthorized ("log in again").
+ // Anything else (server error, network failure) must surface as
+ // itself, or a transient outage reads as an expired login.
+ if errors.Is(refreshErr, ErrUnauthorized) || errors.Is(refreshErr, ErrInvalidGrant) {
+ return ErrUnauthorized
+ }
+ return fmt.Errorf("refreshing the session after a 401: %w", refreshErr)
+ }
+ if newJWT == "" {
+ return ErrUnauthorized
+ }
+ c.JWT = newJWT
+ resp, err = attempt()
+ if err != nil {
+ return err
+ }
+ }
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
diff --git a/cli/pkg/client/device_test.go b/cli/pkg/client/device_test.go
new file mode 100644
index 00000000..21d15af9
--- /dev/null
+++ b/cli/pkg/client/device_test.go
@@ -0,0 +1,177 @@
+package client
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "sync/atomic"
+ "testing"
+)
+
+func TestDeviceAuthorize_success(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/auth/device/authorize" {
+ t.Errorf("path = %q", r.URL.Path)
+ }
+ _, _ = w.Write([]byte(`{"device_code":"dev","user_code":"WXYZ-1234","verification_uri":"https://x/device","verification_uri_complete":"https://x/device?user_code=WXYZ-1234","expires_in":600,"interval":5}`))
+ }))
+ defer srv.Close()
+
+ c := New(srv.URL)
+ da, err := c.DeviceAuthorize(context.Background(), "")
+ if err != nil {
+ t.Fatalf("DeviceAuthorize: %v", err)
+ }
+ if da.DeviceCode != "dev" || da.UserCode != "WXYZ-1234" || da.Interval != 5 || da.ExpiresIn != 600 {
+ t.Errorf("got %+v", da)
+ }
+}
+
+func TestPollDeviceToken_states(t *testing.T) {
+ cases := []struct {
+ body string
+ want error
+ }{
+ {`{"error":"authorization_pending"}`, ErrAuthorizationPending},
+ {`{"error":"slow_down"}`, ErrSlowDown},
+ {`{"error":"access_denied"}`, ErrAccessDenied},
+ {`{"error":"expired_token"}`, ErrExpiredToken},
+ }
+ for _, tc := range cases {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = w.Write([]byte(tc.body))
+ }))
+ c := New(srv.URL)
+ _, err := c.PollDeviceToken(context.Background(), "dev")
+ if !errors.Is(err, tc.want) {
+ t.Errorf("body %s: got %v, want %v", tc.body, err, tc.want)
+ }
+ srv.Close()
+ }
+}
+
+func TestPollDeviceToken_success(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ _, _ = w.Write([]byte(`{"access_token":"at","refresh_token":"rt","token_type":"Bearer","expires_in":900,"email":"[email protected]"}`))
+ }))
+ defer srv.Close()
+
+ c := New(srv.URL)
+ ts, err := c.PollDeviceToken(context.Background(), "dev")
+ if err != nil {
+ t.Fatalf("poll: %v", err)
+ }
+ if ts.AccessToken != "at" || ts.RefreshToken != "rt" || ts.Email != "[email protected]" || ts.ExpiresIn != 900 {
+ t.Errorf("got %+v", ts)
+ }
+}
+
+func TestRefresh_success(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/api/auth/token" {
+ t.Errorf("path = %q", r.URL.Path)
+ }
+ var req map[string]string
+ _ = json.NewDecoder(r.Body).Decode(&req)
+ if req["grant_type"] != "refresh_token" || req["refresh_token"] != "old" {
+ t.Errorf("req = %v", req)
+ }
+ _, _ = w.Write([]byte(`{"access_token":"new-at","refresh_token":"new-rt","expires_in":900}`))
+ }))
+ defer srv.Close()
+
+ c := New(srv.URL)
+ ts, err := c.Refresh(context.Background(), "old")
+ if err != nil {
+ t.Fatalf("refresh: %v", err)
+ }
+ if ts.AccessToken != "new-at" || ts.RefreshToken != "new-rt" {
+ t.Errorf("got %+v", ts)
+ }
+}
+
+func TestRefresh_invalidGrant(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = w.Write([]byte(`{"error":"invalid_grant"}`))
+ }))
+ defer srv.Close()
+
+ c := New(srv.URL)
+ _, err := c.Refresh(context.Background(), "x")
+ if !errors.Is(err, ErrInvalidGrant) {
+ t.Errorf("got %v, want ErrInvalidGrant", err)
+ }
+}
+
+func TestDo_refreshOn401_retriesOnce(t *testing.T) {
+ var calls int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ n := atomic.AddInt32(&calls, 1)
+ auth := r.Header.Get("Authorization")
+ if n == 1 {
+ if auth != "Bearer old" {
+ t.Errorf("first auth = %q", auth)
+ }
+ w.WriteHeader(http.StatusUnauthorized)
+ return
+ }
+ if auth != "Bearer new" {
+ t.Errorf("retry auth = %q", auth)
+ }
+ _, _ = w.Write([]byte(`[]`))
+ }))
+ defer srv.Close()
+
+ refreshed := false
+ c := New(srv.URL, WithJWT("old"), WithRefresher(func(_ context.Context) (string, error) {
+ refreshed = true
+ return "new", nil
+ }))
+ if _, err := c.ListProjects(context.Background()); err != nil {
+ t.Fatalf("ListProjects: %v", err)
+ }
+ if !refreshed {
+ t.Error("refresher was not called")
+ }
+ if atomic.LoadInt32(&calls) != 2 {
+ t.Errorf("server calls = %d, want 2", calls)
+ }
+}
+
+func TestDo_refreshInvalidGrant_returnsUnauthorized(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusUnauthorized)
+ }))
+ defer srv.Close()
+
+ c := New(srv.URL, WithJWT("old"), WithRefresher(func(_ context.Context) (string, error) {
+ return "", ErrInvalidGrant
+ }))
+ _, err := c.ListProjects(context.Background())
+ if !errors.Is(err, ErrUnauthorized) {
+ t.Errorf("got %v, want ErrUnauthorized", err)
+ }
+}
+
+func TestDo_refreshFails_surfacesRefreshError(t *testing.T) {
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
+ w.WriteHeader(http.StatusUnauthorized)
+ }))
+ defer srv.Close()
+
+ refreshErr := errors.New("refresh failed")
+ c := New(srv.URL, WithJWT("old"), WithRefresher(func(_ context.Context) (string, error) {
+ return "", refreshErr
+ }))
+ _, err := c.ListProjects(context.Background())
+ if errors.Is(err, ErrUnauthorized) {
+ t.Errorf("got ErrUnauthorized, want the refresh error surfaced")
+ }
+ if !errors.Is(err, refreshErr) {
+ t.Errorf("got %v, want wrapped %v", err, refreshErr)
+ }
+}
diff --git a/cli/pkg/client/errors.go b/cli/pkg/client/errors.go
index 02ff2463..5497c08c 100644
--- a/cli/pkg/client/errors.go
+++ b/cli/pkg/client/errors.go
@@ -15,6 +15,12 @@ var (
ErrForbidden = errors.New("forbidden (403)")
ErrNotFound = errors.New("not found (404)")
ErrRateLimited = errors.New("rate limited (429)")
+
+ ErrAuthorizationPending = errors.New("authorization_pending")
+ ErrSlowDown = errors.New("slow_down")
+ ErrAccessDenied = errors.New("access_denied")
+ ErrExpiredToken = errors.New("expired_token")
+ ErrInvalidGrant = errors.New("invalid_grant")
)
// APIError is returned for any non-2xx response that isn't covered by a sentinel.
diff --git a/docs/pages/client/android/index.mdx b/docs/pages/client/android/index.mdx
index 0e2078cb..2dfae1a8 100644
--- a/docs/pages/client/android/index.mdx
+++ b/docs/pages/client/android/index.mdx
@@ -117,12 +117,19 @@ Every `println` and any other write to `System.out` / `System.err` is mirrored i
Calls that go straight to `android.util.Log` bypass `System.out` and are **not** captured automatically. To pick up Logcat lines, install a Timber tree (or any other logger) that calls `TracewayClient.instance?.recordLog(message, level)`:
```kotlin
+import android.util.Log
import com.tracewayapp.traceway.TracewayClient
import timber.log.Timber
Timber.plant(object : Timber.Tree() {
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
- TracewayClient.instance?.recordLog(message, level = priority.toLogLevel())
+ val level = when (priority) {
+ Log.VERBOSE, Log.DEBUG -> "debug"
+ Log.WARN -> "warn"
+ Log.ERROR, Log.ASSERT -> "error"
+ else -> "info"
+ }
+ TracewayClient.instance?.recordLog(message, level = level)
}
})
```
diff --git a/docs/pages/learn/_meta.json b/docs/pages/learn/_meta.json
index 6192d7ce..db1be2e1 100644
--- a/docs/pages/learn/_meta.json
+++ b/docs/pages/learn/_meta.json
@@ -15,6 +15,7 @@
"logs": "Logs",
"alerts": "Alerts",
"sso": "SSO",
+ "cli-auth": "CLI Authentication",
"embedded-mode": "Embedded Mode",
"otel-agent": "OTel Agent",
"build-tags": "Build Tags",
diff --git a/docs/pages/learn/cli-auth.mdx b/docs/pages/learn/cli-auth.mdx
new file mode 100644
index 00000000..312ebc50
--- /dev/null
+++ b/docs/pages/learn/cli-auth.mdx
@@ -0,0 +1,87 @@
+# CLI Authentication
+
+import { Callout } from "nextra/components";
+
+The `traceway` CLI and the dashboard share the same accounts, but the CLI signs in with its own OAuth-style flows rather than storing your dashboard password. There are three ways to log in, plus long-lived **personal access tokens** for automation.
+
+## Browser device login (default)
+
+Running `traceway login` with no flags starts a [device authorization](https://datatracker.ietf.org/doc/html/rfc8628) flow:
+
+```
+traceway login ──► POST /api/auth/device/authorize
+ └─► CLI prints a URL + short code (XXXX-XXXX)
+ └─► you open the URL, sign in, approve the code at /device
+ └─► CLI polls POST /api/auth/device/token (grant device_code)
+ └─► receives a 15-min access token + a rotating
+ 90-day refresh token, stored locally (0600)
+```
+
+The CLI refreshes the access token automatically when it expires, rotating the refresh token each time. You stay logged in for up to 90 days of inactivity without re-entering anything.
+
+The device flow needs an interactive terminal (someone has to approve the code). In CI or scripts, use a personal access token or password login instead; on a headless box you can pass `--no-browser` and approve the code from another device.
+
+## Password login
+
+```bash
+traceway login --password # prompts for email + password
+traceway login --username [email protected] # implies --password
+traceway login --password-stdin # reads the password from stdin
+```
+
+Password logins are not refreshable: when the token expires you log in again.
+
+## Personal access tokens
+
+Create a token from the dashboard (**Account → Personal access tokens**), then:
+
+```bash
+traceway login --token twp_xxxxxxxxxxxx
+# or
+echo "twp_xxxxxxxxxxxx" | traceway login --token-stdin
+```
+
+PATs are the right choice for CI and long-running automation. They're shown once at creation, carry an optional expiry, and can be revoked at any time from the same dashboard page. The backend accepts a `twp_`-prefixed token anywhere it accepts a dashboard token.
+
+## Logging out
+
+```bash
+traceway logout
+```
+
+For device logins this revokes the refresh-token family server-side (so it can't be refreshed again) and then removes the local credentials. Revoking a PAT is done from the dashboard.
+
+## Self-hosting: configuring authentication
+
+The CLI and MCP device flow work against any Traceway instance with no extra setup; the endpoints are always registered. Two server settings shape whether it is safe and where the login URLs point.
+
+### Set a strong `JWT_SECRET`
+
+<Callout type="warning">
+ `JWT_SECRET` is what makes authentication safe. It signs **every** token the server issues: dashboard sessions and the short-lived access tokens the CLI and MCP server receive from the device flow. Anyone who knows it can forge a valid token for any user and take over any account. Set it to a strong, unique value you keep out of source control, and **never expose an instance that is still using a default**.
+</Callout>
+
+Generate one and pass it as an environment variable:
+
+```bash
+openssl rand -hex 32 # use the output as JWT_SECRET
+```
+
+- Minimum length is 32 characters; the server refuses to start with a shorter secret.
+- The **All-in-One image ships a built-in default** so it can boot with zero config. That default is public, so override `JWT_SECRET` before you put the instance on a network anyone else can reach. Every other deployment guide already requires you to set it.
+- Keep it **stable**. Rotating it logs out active dashboard sessions (users sign in again). CLI logins and personal access tokens are opaque, database-backed credentials, so those keep working: a CLI simply refreshes into a token signed with the new secret on its next call.
+
+`OAUTH_SESSION_SECRET` falls back to `JWT_SECRET` when unset; set it separately only if you want to rotate the OAuth cookie secret independently.
+
+### Set `APP_BASE_URL` to your public origin
+
+`APP_BASE_URL` becomes the OAuth **issuer**, the base of the device-login verification URL the CLI prints, and the origin advertised in the discovery documents below. If it is unset the server derives the origin per-request from the `Host` / `X-Forwarded-*` headers, which is fine for direct access. Set it explicitly when the server sits behind a proxy that rewrites the `Host` header, so the printed URL points where users can actually reach it.
+
+### Discovery endpoints
+
+Spec-compliant clients, including the MCP server, self-configure from two documents served at the origin root, so you never hard-code endpoints:
+
+- `GET /.well-known/oauth-authorization-server`: [RFC 8414](https://datatracker.ietf.org/doc/html/rfc8414) authorization-server metadata (issuer, token and device-authorization endpoints, supported grants).
+- `GET /.well-known/oauth-protected-resource`: [RFC 9728](https://datatracker.ietf.org/doc/html/rfc9728) protected-resource metadata.
+
+Both derive their URLs from `APP_BASE_URL` (or the request headers when it is unset). No additional configuration is required.
diff --git a/docs/pages/server/all-in-one.mdx b/docs/pages/server/all-in-one.mdx
index c1a64ed0..d792ebb7 100644
--- a/docs/pages/server/all-in-one.mdx
+++ b/docs/pages/server/all-in-one.mdx
@@ -1,5 +1,7 @@
# All-in-One Container
+import { Callout } from "nextra/components";
+
Single Docker container with ClickHouse, PostgreSQL, and the Go backend managed by supervisord. Best for simple setups where you want everything in one place.
## Quick Start
@@ -40,6 +42,10 @@ docker run -d --name traceway \
All environment variables have working defaults, no configuration required. Override as needed:
+<Callout type="warning">
+ **Set `JWT_SECRET` before exposing this image to anyone else.** It signs every authentication token (dashboard sessions and CLI/MCP device logins), so the built-in default, which is public, lets anyone forge a token for any account. Generate a strong secret with `openssl rand -hex 32`. See [CLI Authentication](/learn/cli-auth#set-a-strong-jwt_secret).
+</Callout>
+
| Variable | Default | Description |
|----------|---------|-------------|
| `CLICKHOUSE_SERVER` | `localhost:9000` | ClickHouse host:port |
@@ -53,9 +59,9 @@ All environment variables have working defaults, no configuration required. Over
| `POSTGRES_USERNAME` | `traceway` | PostgreSQL username |
| `POSTGRES_PASSWORD` | *(empty)* | PostgreSQL password |
| `POSTGRES_SSLMODE` | `disable` | PostgreSQL SSL mode |
-| `JWT_SECRET` | *(built-in default)* | JWT signing secret (min 32 chars) |
+| `JWT_SECRET` | *(built-in default, **override in production**)* | Signs all authentication tokens: dashboard sessions and CLI/MCP device logins. The built-in default is public; set a strong unique secret (min 32 chars, `openssl rand -hex 32`) and keep it stable. See [CLI Authentication](/learn/cli-auth#set-a-strong-jwt_secret). |
| `GIN_MODE` | `release` | Gin framework mode |
-| `APP_BASE_URL` | *(none)* | Public URL of your Traceway instance (e.g. `https://traceway.example.com`). Used for SDK setup instructions, email links, and OAuth callback URLs. |
+| `APP_BASE_URL` | *(none)* | Public URL of your Traceway instance (e.g. `https://traceway.example.com`). Used for SDK setup instructions, email links, OAuth callback URLs, and the CLI/MCP OAuth issuer plus device-login verification URL. If unset, the device-auth and `/.well-known` endpoints derive it per-request from the `Host` / `X-Forwarded-*` headers; set it explicitly behind a proxy that rewrites `Host`. See [CLI Authentication](/learn/cli-auth). |
| `STORAGE_TYPE` | `local` | Blob storage backend for source maps, session recordings, and AI traces: `local` or `s3`. See [Blob Storage](/server/storage) for the S3 variables. |
| `STORAGE_PATH` | `./storage` | Folder for local blob storage, `/app/storage` in this image. Mount a volume there. Ignored when `STORAGE_TYPE=s3`. |
| `SESSION_RECORDING_RETENTION_DAYS` | `30` | Days to keep session recording files on disk under `STORAGE_PATH/recordings/`. Files older than the TTL are deleted hourly and on startup. No effect when `STORAGE_TYPE=s3`. Set to `0` to disable. |
diff --git a/docs/pages/server/docker-compose.mdx b/docs/pages/server/docker-compose.mdx
index 9cd5f3ac..17018932 100644
--- a/docs/pages/server/docker-compose.mdx
+++ b/docs/pages/server/docker-compose.mdx
@@ -98,8 +98,8 @@ Edit the environment variables in your compose file as needed:
| `POSTGRES_USERNAME` | `traceway` | PostgreSQL username |
| `POSTGRES_PASSWORD` | `traceway` | PostgreSQL password |
| `POSTGRES_SSLMODE` | `disable` | PostgreSQL SSL mode |
-| `JWT_SECRET` | `change-this-to-a-secure-secret-at-least-32-chars` | JWT signing secret (min 32 chars) |
-| `APP_BASE_URL` | *(none)* | Public URL of your Traceway instance (e.g. `https://traceway.example.com`). Used for SDK setup instructions, email links, and OAuth callback URLs. |
+| `JWT_SECRET` | `change-this-to-a-secure-secret-at-least-32-chars` | Signs all authentication tokens (dashboard sessions and CLI/MCP device logins). Replace the placeholder with a strong, unique secret of at least 32 chars (`openssl rand -hex 32`) and keep it stable. See [CLI Authentication](/learn/cli-auth#set-a-strong-jwt_secret). |
+| `APP_BASE_URL` | *(none)* | Public URL of your Traceway instance (e.g. `https://traceway.example.com`). Used for SDK setup instructions, email links, OAuth callback URLs, and the CLI/MCP OAuth issuer plus device-login verification URL. If unset, the device-auth and `/.well-known` endpoints derive it per-request from the `Host` / `X-Forwarded-*` headers; set it explicitly behind a proxy that rewrites `Host`. See [CLI Authentication](/learn/cli-auth). |
| `STORAGE_TYPE` | `local` | Blob storage backend for source maps, session recordings, and AI traces: `local` or `s3`. See [Blob Storage](/server/storage) for the S3 variables. |
| `STORAGE_PATH` | `./storage` | Folder for local blob storage, `/app/storage` in the minimal image. Mount a volume there. Ignored when `STORAGE_TYPE=s3`. |
| `SESSION_RECORDING_RETENTION_DAYS` | `30` | Days to keep session recording files on disk under `STORAGE_PATH/recordings/`. A worker deletes older files hourly and on startup. No effect when `STORAGE_TYPE=s3`. Set to `0` to disable. |
diff --git a/docs/pages/server/haloy.mdx b/docs/pages/server/haloy.mdx
index 89d040eb..4352d5e4 100644
--- a/docs/pages/server/haloy.mdx
+++ b/docs/pages/server/haloy.mdx
@@ -163,7 +163,7 @@ Point your SDK's connection string at your Traceway domain:
| Variable | Default | Description |
|----------|---------|-------------|
-| `APP_BASE_URL` | `https://traceway.yourdomain.com` | Public URL of the Traceway instance |
+| `APP_BASE_URL` | `https://traceway.yourdomain.com` | Public URL of the Traceway instance. Also the CLI/MCP OAuth issuer and device-login verification URL. See [CLI Authentication](/learn/cli-auth). |
| `CLICKHOUSE_SERVER` | `clickhouse:9000` | ClickHouse host:port |
| `CLICKHOUSE_DATABASE` | `traceway` | ClickHouse database name |
| `CLICKHOUSE_USERNAME` | `default` | ClickHouse username |
@@ -175,7 +175,7 @@ Point your SDK's connection string at your Traceway domain:
| `POSTGRES_USERNAME` | `traceway` | PostgreSQL username |
| `POSTGRES_PASSWORD` | *(from env)* | PostgreSQL password |
| `POSTGRES_SSLMODE` | `disable` | PostgreSQL SSL mode |
-| `JWT_SECRET` | *(from env)* | JWT signing secret (min 32 chars) |
+| `JWT_SECRET` | *(from env)* | Signs all authentication tokens (dashboard sessions and CLI/MCP device logins). Use a strong, unique secret of at least 32 chars; keep it stable. See [CLI Authentication](/learn/cli-auth#set-a-strong-jwt_secret). |
| `GOOGLE_CLIENT_ID` | *(unset)* | Optional. Google OAuth client ID. Setting both Google variables enables the **Continue with Google** button. See the [SSO guide](/learn/sso). |
| `GOOGLE_CLIENT_SECRET` | *(unset)* | Optional. Google OAuth client secret. |
| `GITHUB_CLIENT_ID` | *(unset)* | Optional. GitHub OAuth App client ID. Setting both GitHub variables enables the **Continue with GitHub** button. |
diff --git a/docs/pages/server/local-setup.mdx b/docs/pages/server/local-setup.mdx
index b7d503e3..59b6b36b 100644
--- a/docs/pages/server/local-setup.mdx
+++ b/docs/pages/server/local-setup.mdx
@@ -61,7 +61,7 @@ POSTGRES_SSLMODE=disable
| Variable | Description |
|----------|-------------|
-| `JWT_SECRET` | Secret key for signing JWT tokens. Must be at least 32 characters. |
+| `JWT_SECRET` | Signs all authentication tokens (dashboard sessions and CLI/MCP device logins). Must be at least 32 characters; use a strong, unique secret and keep it stable. See [CLI Authentication](/learn/cli-auth#set-a-strong-jwt_secret). |
| `CLICKHOUSE_SERVER` | ClickHouse server address (host:port) |
| `CLICKHOUSE_DATABASE` | ClickHouse database name |
| `CLICKHOUSE_USERNAME` | ClickHouse username |
@@ -73,7 +73,7 @@ POSTGRES_SSLMODE=disable
| `POSTGRES_USERNAME` | PostgreSQL username |
| `POSTGRES_PASSWORD` | PostgreSQL password |
| `POSTGRES_SSLMODE` | PostgreSQL SSL mode (`disable`, `require`, etc.) |
-| `APP_BASE_URL` | Public URL of your Traceway instance. Used for SDK connection instructions, email links, and OAuth callback URLs. For local dev set this to `http://localhost:5173` so OAuth callbacks land on the Vite dev server (which proxies `/api` back to the Go backend). |
+| `APP_BASE_URL` | Public URL of your Traceway instance. Used for SDK connection instructions, email links, OAuth callback URLs, and the CLI/MCP OAuth issuer plus device-login verification URL. For local dev set this to `http://localhost:5173` so OAuth callbacks land on the Vite dev server (which proxies `/api` back to the Go backend). |
| `GOOGLE_CLIENT_ID` | Optional. Google OAuth client ID. Setting both Google variables enables the **Continue with Google** button. See the [SSO guide](/learn/sso). |
| `GOOGLE_CLIENT_SECRET` | Optional. Google OAuth client secret. |
| `GITHUB_CLIENT_ID` | Optional. GitHub OAuth App client ID. Setting both GitHub variables enables the **Continue with GitHub** button. See the [SSO guide](/learn/sso). |
diff --git a/docs/pages/server/minimal.mdx b/docs/pages/server/minimal.mdx
index 558c69e3..fd8cc485 100644
--- a/docs/pages/server/minimal.mdx
+++ b/docs/pages/server/minimal.mdx
@@ -56,8 +56,8 @@ Then use `traceway:minimal` instead of `ghcr.io/tracewayapp/traceway:minimal` in
| `POSTGRES_USERNAME` | PostgreSQL username | `traceway` |
| `POSTGRES_PASSWORD` | PostgreSQL password | `password` |
| `POSTGRES_SSLMODE` | PostgreSQL SSL mode | `disable` |
-| `JWT_SECRET` | JWT signing secret (min 32 chars) | `your-secret-here` |
-| `APP_BASE_URL` | Public URL of your instance. Used for SDK setup instructions, email links, and OAuth callback URLs. | `https://traceway.example.com` |
+| `JWT_SECRET` | Signs all authentication tokens (dashboard sessions and CLI/MCP device logins). Use a strong, unique secret of at least 32 chars; keep it stable. See [CLI Authentication](/learn/cli-auth#set-a-strong-jwt_secret). | `your-secret-here` |
+| `APP_BASE_URL` | Public URL of your instance. Used for SDK setup instructions, email links, OAuth callback URLs, and the CLI/MCP OAuth issuer plus device-login verification URL. If unset, derived per-request from `Host` / `X-Forwarded-*`. | `https://traceway.example.com` |
| `STORAGE_TYPE` | Blob storage backend for source maps, session recordings, and AI traces: `local` (default) or `s3`. See [Blob Storage](/server/storage) for the S3 variables. | `local` |
| `STORAGE_PATH` | Folder for local blob storage. Defaults to `./storage`, which is `/app/storage` in this image. Mount a volume there. Ignored when `STORAGE_TYPE=s3`. | `/app/storage` |
| `SESSION_RECORDING_RETENTION_DAYS` | Days to keep on-disk session recordings under `STORAGE_PATH/recordings/`. Defaults to `30`. Worker runs hourly and on startup. `0` disables; no effect when `STORAGE_TYPE=s3`. | `30` |
diff --git a/docs/pages/server/sqlite.mdx b/docs/pages/server/sqlite.mdx
index 31a62702..dab84c69 100644
--- a/docs/pages/server/sqlite.mdx
+++ b/docs/pages/server/sqlite.mdx
@@ -58,8 +58,8 @@ If `STORAGE_TYPE` is unset (or set to `local`), blobs are written to `/data/stor
| Variable | Default | Description |
|----------|---------|-------------|
-| `JWT_SECRET` | *(required)* | JWT signing secret, minimum 32 characters |
-| `APP_BASE_URL` | *(unset)* | Public URL of your instance. Used for SDK setup snippets, password-reset emails, and OAuth callback URLs |
+| `JWT_SECRET` | *(required)* | Signs all authentication tokens (dashboard sessions and CLI/MCP device logins). Use a strong, unique secret of at least 32 characters (`openssl rand -hex 32`) and keep it stable. See [CLI Authentication](/learn/cli-auth#set-a-strong-jwt_secret). |
+| `APP_BASE_URL` | *(unset)* | Public URL of your instance. Used for SDK setup snippets, password-reset emails, OAuth callback URLs, and the CLI/MCP OAuth issuer plus device-login verification URL. If unset, the device-auth and `/.well-known` endpoints derive it per-request from the `Host` / `X-Forwarded-*` headers. See [CLI Authentication](/learn/cli-auth) |
| `SQLITE_PATH` | `/data/traceway.db` | Main SQLite file. Telemetry DB is derived as `<path>_telemetry.db` |
| `STORAGE_TYPE` | `local` | Blob storage backend. `local` or `s3` |
| `STORAGE_PATH` | `/data/storage` | Folder for local blob storage. Ignored when `STORAGE_TYPE=s3` |
diff --git a/docs/pages/symbolicator/android.mdx b/docs/pages/symbolicator/android.mdx
index 6345e08e..db86aa69 100644
--- a/docs/pages/symbolicator/android.mdx
+++ b/docs/pages/symbolicator/android.mdx
@@ -139,4 +139,3 @@ Symbolication then happens in Traceway, in the collector processor or in the bac
- [Architecture](/symbolicator): when symbolication runs, the cache tiers, and the `.tw` format
- [iOS](/symbolicator/ios) and [Dart](/symbolicator/dart): the flat-DWARF approach for native symbols
- [Performance](/symbolicator/performance): the Android benchmark, cache sizing, and failure handling
-```
diff --git a/docs/pages/symbolicator/ios.mdx b/docs/pages/symbolicator/ios.mdx
index a57e0d69..1d1f4251 100644
--- a/docs/pages/symbolicator/ios.mdx
+++ b/docs/pages/symbolicator/ios.mdx
@@ -3,12 +3,14 @@
For iOS, the debug info is the build's `.dSYM` (a Mach-O wrapper around DWARF). A stripped Swift or Objective-C release build keeps no function names or line tables in the shipped binary, so a crash reports against raw machine code. Each frame carries the image's Mach-O UUID, an offset into that image, and the image name:
```
-Fatal error: Unexpectedly found nil while unwrapping an Optional value
+Fatal Signal SIGTRAP (5)
+*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
+os: ios arch: arm64
#00 8a5f0c2e1b7d4f93a6e0c8b1d2f3a4b5 0x00000000000a1340 MyApp
#01 8a5f0c2e1b7d4f93a6e0c8b1d2f3a4b5 0x00000000000a2d10 MyApp
```
-The offset is image-relative (the frame address minus the image's load address), so it is independent of where the dynamic linker slid the image at runtime. With the build's `.dSYM` uploaded, that resolves into named source frames, inline calls expanded:
+Everything above the `*** …` separator is the error preamble, preserved verbatim in the symbolicated output. The `os: … arch: …` line picks the dSYM architecture slice to resolve against (`arm64` when absent). The offset is image-relative (the frame address minus the image's load address), so it is independent of where the dynamic linker slid the image at runtime. With the build's `.dSYM` uploaded, that resolves into named source frames, inline calls expanded:
```
#0 ProfileViewModel.load() (ProfileViewModel.swift:88:14)
@@ -70,7 +72,7 @@ Unlike the Dart upload, iOS needs no `arch` or `debug_id` form fields. The backe
iossymbols/{projectId}/{uuid}.dsym
```
-Because the key is content-addressed, releases never collide and re-uploading the same build is idempotent. The response reports how many entries were stored:
+Because the key is content-addressed, releases never collide and re-uploading the same build is idempotent. The response reports how many uploaded files were accepted — a fat dSYM counts once, even though it stores one entry per slice:
```json
{ "uploaded": 2 }
@@ -96,6 +98,8 @@ The parser pulls three things from each frame:
A trace that is already symbolic, or carries no recognizable iOS frames, passes through untouched.
+When crafting traces by hand (a custom sender, CI tooling), include the `*** …` separator line between the error message and the frames, as the Traceway iOS SDK does. The symbolicated output preserves everything above the first `***` line as the error preamble — without a separator, the entire raw trace (frame lines included) is treated as preamble and carried into the resolved output verbatim, duplicating the frames.
+
## How an offset resolves
The matching key is the Mach-O UUID (the debug ID). Because the frame offset is image-relative rather than the absolute runtime address, no runtime slide needs to be sent: the original VM address is reconstructed from the dSYM itself.
diff --git a/frontend/src/lib/components/app-sidebar.svelte b/frontend/src/lib/components/app-sidebar.svelte
index d60015a1..d6a7742b 100644
--- a/frontend/src/lib/components/app-sidebar.svelte
+++ b/frontend/src/lib/components/app-sidebar.svelte
@@ -14,7 +14,8 @@
Gauge,
ListEnd,
Settings,
- BookOpen
+ BookOpen,
+ KeyRound
} from '@lucide/svelte';
import { themeState } from '$lib/state/theme.svelte';
import { projectsState, isFrontendFramework, isCloudflareFramework } from '$lib/state/projects.svelte';
@@ -66,6 +67,7 @@
);
const allSidebarItemsBottom: SidebarItem[] = [
+ { Icon: KeyRound, href: '/account', title: 'Account', stickyParams: [] },
{
Icon: BookOpen,
href: 'https://docs.tracewayapp.com',
diff --git a/frontend/src/lib/components/oauth-buttons.svelte b/frontend/src/lib/components/oauth-buttons.svelte
index a128054e..6e1de813 100644
--- a/frontend/src/lib/components/oauth-buttons.svelte
+++ b/frontend/src/lib/components/oauth-buttons.svelte
@@ -1,6 +1,7 @@
<script lang="ts">
import { Button } from "$lib/components/ui/button";
import { onMount } from 'svelte';
+ import { stashSsoReturnTo } from '$lib/utils/navigation';
let { passwordLoginEnabled = $bindable(true), loaded = $bindable(false) } = $props();
@@ -24,6 +25,7 @@
});
function start(provider: string) {
+ stashSsoReturnTo(new URLSearchParams(window.location.search).get('returnTo'));
window.location.href = `/api/auth/start/${provider}`;
}
diff --git a/frontend/src/lib/state/personal-access-tokens.svelte.ts b/frontend/src/lib/state/personal-access-tokens.svelte.ts
new file mode 100644
index 00000000..e5f32521
--- /dev/null
+++ b/frontend/src/lib/state/personal-access-tokens.svelte.ts
@@ -0,0 +1,50 @@
+import { api } from '$lib/api';
+
+export interface PersonalAccessToken {
+ id: string;
+ prefix: string;
+ name: string;
+ lastUsedAt: string | null;
+ expiresAt: string | null;
+ createdAt: string;
+}
+
+export interface CreatedToken {
+ id: string;
+ name: string;
+ prefix: string;
+ token: string;
+ createdAt: string;
+ expiresAt: string | null;
+}
+
+class PersonalAccessTokensState {
+ tokens = $state<PersonalAccessToken[]>([]);
+ loading = $state(false);
+ error = $state('');
+
+ async load() {
+ this.loading = true;
+ this.error = '';
+ try {
+ this.tokens = (await api.get('/personal-access-tokens')) as PersonalAccessToken[];
+ } catch (e: unknown) {
+ this.error = e instanceof Error ? e.message : 'Failed to load tokens';
+ } finally {
+ this.loading = false;
+ }
+ }
+
+ async create(name: string, expiresInDays: number | null): Promise<CreatedToken> {
+ const res = (await api.post('/personal-access-tokens', { name, expiresInDays })) as CreatedToken;
+ await this.load();
+ return res;
+ }
+
+ async revoke(id: string) {
+ await api.delete(`/personal-access-tokens/${id}`);
+ await this.load();
+ }
+}
+
+export const personalAccessTokensState = new PersonalAccessTokensState();
diff --git a/frontend/src/lib/utils/framework-code.ts b/frontend/src/lib/utils/framework-code.ts
index fe61b930..8d80099e 100644
--- a/frontend/src/lib/utils/framework-code.ts
+++ b/frontend/src/lib/utils/framework-code.ts
@@ -47,7 +47,7 @@ export function getInstallCommand(framework: Framework): string {
case 'flutter':
return 'flutter pub add traceway';
case 'android':
- return 'implementation("com.tracewayapp:traceway:1.0.0")';
+ return 'implementation("com.tracewayapp:traceway:1.0.1")';
case 'ios':
return '.package(url: "https://github.com/tracewayapp/traceway-ios.git", from: "0.1.0")';
case 'custom':
diff --git a/frontend/src/lib/utils/navigation.ts b/frontend/src/lib/utils/navigation.ts
index 29a944e8..f187fe35 100644
--- a/frontend/src/lib/utils/navigation.ts
+++ b/frontend/src/lib/utils/navigation.ts
@@ -1,5 +1,41 @@
import { goto } from '$app/navigation';
+// Only allow same-origin, absolute-path redirects. Reject absolute URLs
+// (https://evil.com), protocol-relative (//evil.com), and backslash tricks
+// (/\evil.com) so returnTo can't be used as an open redirect.
+export function safeLocalPath(raw: string | null): string {
+ if (!raw) return '/';
+ let decoded: string;
+ try {
+ decoded = decodeURIComponent(raw);
+ } catch {
+ return '/';
+ }
+ if (!decoded.startsWith('/') || decoded.startsWith('//') || decoded.startsWith('/\\')) {
+ return '/';
+ }
+ return decoded;
+}
+
+// SSO logins bounce through the provider and land on /auth/callback, losing
+// any ?returnTo= the login page had. Stash it in sessionStorage before leaving
+// and consume it when the callback (or finish-setup) decides where to land.
+const SSO_RETURN_TO_KEY = 'traceway_sso_return_to';
+
+export function stashSsoReturnTo(path: string | null) {
+ if (path) {
+ sessionStorage.setItem(SSO_RETURN_TO_KEY, path);
+ } else {
+ sessionStorage.removeItem(SSO_RETURN_TO_KEY);
+ }
+}
+
+export function consumeSsoReturnTo(): string | null {
+ const path = sessionStorage.getItem(SSO_RETURN_TO_KEY);
+ sessionStorage.removeItem(SSO_RETURN_TO_KEY);
+ return path;
+}
+
export function addStickyParamsToHref(href: string, ...stickyParams: string[]) {
const currentParams = new URLSearchParams(window.location.search);
const url = new URL(href, window.location.origin);
diff --git a/frontend/src/routes/+layout.svelte b/frontend/src/routes/+layout.svelte
index e93e9f5b..d8061f5c 100644
--- a/frontend/src/routes/+layout.svelte
+++ b/frontend/src/routes/+layout.svelte
@@ -41,7 +41,8 @@
'/auth/callback',
'/finish-setup',
'/forgot-password',
- '/reset-password'
+ '/reset-password',
+ '/device'
]);
function isProjectScopedPath(pathname: string): boolean {
@@ -138,7 +139,7 @@
<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 && page.url.pathname !== '/login' && page.url.pathname !== '/register' && page.url.pathname !== '/auth/callback' && page.url.pathname !== '/finish-setup' && page.url.pathname !== '/forgot-password' && page.url.pathname !== '/reset-password' && !page.url.pathname.startsWith('/accept-invitation')}
+{#if authState.isAuthenticated && page.url.pathname !== '/login' && page.url.pathname !== '/register' && page.url.pathname !== '/auth/callback' && page.url.pathname !== '/finish-setup' && page.url.pathname !== '/forgot-password' && page.url.pathname !== '/reset-password' && page.url.pathname !== '/device' && !page.url.pathname.startsWith('/accept-invitation')}
<Sidebar.SidebarProvider>
<AppSidebar />
<Sidebar.SidebarInset>
@@ -235,7 +236,7 @@
<Toaster position="bottom-right" />
{:else}
- {#if page.url.pathname === '/login' || page.url.pathname === '/register' || page.url.pathname === '/auth/callback' || page.url.pathname === '/finish-setup' || page.url.pathname === '/forgot-password' || page.url.pathname === '/reset-password' || page.url.pathname.startsWith('/accept-invitation')}
+ {#if page.url.pathname === '/login' || page.url.pathname === '/register' || page.url.pathname === '/auth/callback' || page.url.pathname === '/finish-setup' || page.url.pathname === '/forgot-password' || page.url.pathname === '/reset-password' || page.url.pathname === '/device' || page.url.pathname.startsWith('/accept-invitation')}
<main class="h-screen w-screen">
{@render children()}
</main>
diff --git a/frontend/src/routes/account/+page.svelte b/frontend/src/routes/account/+page.svelte
new file mode 100644
index 00000000..bcdb662e
--- /dev/null
+++ b/frontend/src/routes/account/+page.svelte
@@ -0,0 +1,10 @@
+<script lang="ts">
+ import PersonalAccessTokens from './personal-access-tokens.svelte';
+</script>
+
+<div class="space-y-6">
+ <div>
+ <h1 class="text-2xl font-semibold tracking-tight">Account</h1>
+ </div>
+ <PersonalAccessTokens />
+</div>
diff --git a/frontend/src/routes/account/create-token-dialog.svelte b/frontend/src/routes/account/create-token-dialog.svelte
new file mode 100644
index 00000000..10b62ade
--- /dev/null
+++ b/frontend/src/routes/account/create-token-dialog.svelte
@@ -0,0 +1,110 @@
+<script lang="ts">
+ import * as AlertDialog from '$lib/components/ui/alert-dialog';
+ import { Button } from '$lib/components/ui/button';
+ import { Input } from '$lib/components/ui/input';
+ import { Label } from '$lib/components/ui/label';
+ import * as Select from '$lib/components/ui/select';
+ import { Plus, TriangleAlert } from '@lucide/svelte';
+ import { toast } from 'svelte-sonner';
+ import CopyableInline from '$lib/components/setup/copyable-inline.svelte';
+ import { personalAccessTokensState } from '$lib/state/personal-access-tokens.svelte';
+
+ let { open = $bindable() }: { open: boolean } = $props();
+
+ let name = $state('');
+ let expiry = $state('30');
+ let loading = $state(false);
+ let error = $state('');
+ let createdToken = $state<string | null>(null);
+
+ const expiryOptions = [
+ { value: '30', label: '30 days' },
+ { value: '60', label: '60 days' },
+ { value: '90', label: '90 days' },
+ { value: '0', label: 'No expiration' }
+ ];
+
+ async function handleCreate() {
+ loading = true;
+ error = '';
+ try {
+ const days = parseInt(expiry, 10);
+ const res = await personalAccessTokensState.create(name.trim(), days > 0 ? days : null);
+ createdToken = res.token;
+ toast.success('Successfully created the token', { position: 'top-center' });
+ } catch (e: unknown) {
+ error = e instanceof Error ? e.message : 'Failed to create token';
+ } finally {
+ loading = false;
+ }
+ }
+
+ function handleOpenChange(isOpen: boolean) {
+ if (!isOpen) {
+ name = '';
+ expiry = '30';
+ error = '';
+ createdToken = null;
+ }
+ open = isOpen;
+ }
+</script>
+
+<AlertDialog.Root {open} onOpenChange={handleOpenChange}>
+ <AlertDialog.Content class="max-w-md">
+ {#if createdToken}
+ <AlertDialog.Header>
+ <AlertDialog.Title>Token created</AlertDialog.Title>
+ <AlertDialog.Description>
+ Copy your token now. For security, you won't be able to see it again.
+ </AlertDialog.Description>
+ </AlertDialog.Header>
+ <div class="space-y-3">
+ <CopyableInline value={createdToken} />
+ <p class="flex items-center gap-2 text-sm text-amber-600">
+ <TriangleAlert class="h-4 w-4 shrink-0" />
+ Store it somewhere safe — this is the only time it will be shown.
+ </p>
+ </div>
+ <AlertDialog.Footer>
+ <Button onclick={() => handleOpenChange(false)}>Done</Button>
+ </AlertDialog.Footer>
+ {:else}
+ <AlertDialog.Header>
+ <AlertDialog.Title>Create personal access token</AlertDialog.Title>
+ <AlertDialog.Description>
+ Use this token to authenticate the Traceway CLI or scripts.
+ </AlertDialog.Description>
+ </AlertDialog.Header>
+ <form onsubmit={(e) => { e.preventDefault(); handleCreate(); }} class="space-y-4">
+ <div class="space-y-2">
+ <Label for="token-name">Name</Label>
+ <Input id="token-name" bind:value={name} placeholder="e.g. laptop CLI" required />
+ </div>
+ <div class="space-y-2">
+ <Label for="token-expiry">Expiration</Label>
+ <Select.Root type="single" bind:value={expiry}>
+ <Select.Trigger class="w-full">
+ {expiryOptions.find((o) => o.value === expiry)?.label || 'Select'}
+ </Select.Trigger>
+ <Select.Content>
+ {#each expiryOptions as option}
+ <Select.Item value={option.value}>{option.label}</Select.Item>
+ {/each}
+ </Select.Content>
+ </Select.Root>
+ </div>
+ {#if error}
+ <p class="text-sm text-destructive">{error}</p>
+ {/if}
+ </form>
+ <AlertDialog.Footer>
+ <AlertDialog.Cancel disabled={loading}>Cancel</AlertDialog.Cancel>
+ <Button onclick={handleCreate} disabled={loading}>
+ <Plus class="mr-2 h-4 w-4" />
+ {loading ? 'Creating…' : 'Create token'}
+ </Button>
+ </AlertDialog.Footer>
+ {/if}
+ </AlertDialog.Content>
+</AlertDialog.Root>
diff --git a/frontend/src/routes/account/personal-access-tokens.svelte b/frontend/src/routes/account/personal-access-tokens.svelte
new file mode 100644
index 00000000..7c84468c
--- /dev/null
+++ b/frontend/src/routes/account/personal-access-tokens.svelte
@@ -0,0 +1,141 @@
+<script lang="ts">
+ import { onMount } from 'svelte';
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '$lib/components/ui/card';
+ import { Button } from '$lib/components/ui/button';
+ import * as Table from '$lib/components/ui/table';
+ import * as AlertDialog from '$lib/components/ui/alert-dialog';
+ import { Badge } from '$lib/components/ui/badge';
+ import TableEmptyState from '$lib/components/ui/table-empty-state/table-empty-state.svelte';
+ import { LoadingCircle } from '$lib/components/ui/loading-circle';
+ import { Plus, Trash2 } from '@lucide/svelte';
+ import { toast } from 'svelte-sonner';
+ import {
+ personalAccessTokensState,
+ type PersonalAccessToken
+ } from '$lib/state/personal-access-tokens.svelte';
+ import CreateTokenDialog from './create-token-dialog.svelte';
+
+ let showCreate = $state(false);
+ let tokenToRevoke = $state<PersonalAccessToken | null>(null);
+ let revoking = $state(false);
+
+ onMount(() => personalAccessTokensState.load());
+
+ function formatDate(value: string | null): string {
+ if (!value) return '';
+ return new Date(value).toLocaleDateString(undefined, {
+ year: 'numeric',
+ month: 'short',
+ day: 'numeric'
+ });
+ }
+
+ function isExpired(value: string | null): boolean {
+ return !!value && new Date(value).getTime() < Date.now();
+ }
+
+ async function confirmRevoke() {
+ if (!tokenToRevoke) return;
+ revoking = true;
+ try {
+ await personalAccessTokensState.revoke(tokenToRevoke.id);
+ toast.success('Successfully revoked the token', { position: 'top-center' });
+ tokenToRevoke = null;
+ } catch (e: unknown) {
+ toast.error(e instanceof Error ? e.message : 'Failed to revoke token');
+ } finally {
+ revoking = false;
+ }
+ }
+</script>
+
+<Card class="pb-0">
+ <CardHeader class="flex flex-row items-center justify-between space-y-0 pb-4">
+ <div>
+ <CardTitle>Personal Access Tokens</CardTitle>
+ <CardDescription>
+ Authenticate the Traceway CLI or scripts without a browser. Treat tokens like passwords.
+ </CardDescription>
+ </div>
+ <Button variant="outline" onclick={() => (showCreate = true)}>
+ <Plus class="mr-2 h-4 w-4" />
+ Create token
+ </Button>
+ </CardHeader>
+ <CardContent class="p-0">
+ {#if personalAccessTokensState.loading}
+ <div class="flex items-center justify-center py-12">
+ <LoadingCircle size="lg" />
+ </div>
+ {:else}
+ <Table.Root>
+ <Table.Header>
+ <Table.Row class="hover:bg-transparent">
+ <Table.Head>Name</Table.Head>
+ <Table.Head>Prefix</Table.Head>
+ <Table.Head>Created</Table.Head>
+ <Table.Head>Last used</Table.Head>
+ <Table.Head>Expires</Table.Head>
+ <Table.Head class="w-[80px]"></Table.Head>
+ </Table.Row>
+ </Table.Header>
+ <Table.Body>
+ {#if personalAccessTokensState.tokens.length === 0}
+ <TableEmptyState colspan={6} message="No tokens yet." />
+ {:else}
+ {#each personalAccessTokensState.tokens as token (token.id)}
+ <Table.Row>
+ <Table.Cell class="font-medium">{token.name}</Table.Cell>
+ <Table.Cell>
+ <code class="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">{token.prefix}…</code>
+ </Table.Cell>
+ <Table.Cell>{formatDate(token.createdAt)}</Table.Cell>
+ <Table.Cell>
+ {#if token.lastUsedAt}
+ {formatDate(token.lastUsedAt)}
+ {:else}
+ <Badge variant="outline">Never</Badge>
+ {/if}
+ </Table.Cell>
+ <Table.Cell>
+ {#if !token.expiresAt}
+ <span class="text-muted-foreground">Never</span>
+ {:else if isExpired(token.expiresAt)}
+ <Badge variant="outline" class="border-amber-200 bg-amber-50 text-amber-700">Expired</Badge>
+ {:else}
+ {formatDate(token.expiresAt)}
+ {/if}
+ </Table.Cell>
+ <Table.Cell>
+ <Button variant="ghost" size="icon" onclick={() => (tokenToRevoke = token)}>
+ <Trash2 class="h-4 w-4 text-destructive" />
+ </Button>
+ </Table.Cell>
+ </Table.Row>
+ {/each}
+ {/if}
+ </Table.Body>
+ </Table.Root>
+ {/if}
+ </CardContent>
+</Card>
+
+<CreateTokenDialog bind:open={showCreate} />
+
+<AlertDialog.Root open={tokenToRevoke !== null} onOpenChange={(open) => { if (!open) tokenToRevoke = null; }}>
+ <AlertDialog.Content>
+ <AlertDialog.Header>
+ <AlertDialog.Title>Revoke token</AlertDialog.Title>
+ <AlertDialog.Description>
+ This permanently revokes {tokenToRevoke?.name ? `"${tokenToRevoke.name}"` : 'this token'}. Any
+ CLI or script using it will stop working immediately.
+ </AlertDialog.Description>
+ </AlertDialog.Header>
+ <AlertDialog.Footer>
+ <AlertDialog.Cancel disabled={revoking}>Cancel</AlertDialog.Cancel>
+ <Button variant="destructive" onclick={confirmRevoke} disabled={revoking}>
+ {revoking ? 'Revoking…' : 'Revoke token'}
+ </Button>
+ </AlertDialog.Footer>
+ </AlertDialog.Content>
+</AlertDialog.Root>
diff --git a/frontend/src/routes/auth/callback/+page.svelte b/frontend/src/routes/auth/callback/+page.svelte
index ad35770b..dd575e76 100644
--- a/frontend/src/routes/auth/callback/+page.svelte
+++ b/frontend/src/routes/auth/callback/+page.svelte
@@ -3,6 +3,7 @@
import { onMount } from 'svelte';
import { authState } from '$lib/state/auth.svelte';
import { projectsState } from '$lib/state/projects.svelte';
+ import { consumeSsoReturnTo, safeLocalPath } from '$lib/utils/navigation';
import { Alert, AlertDescription, AlertTitle } from "$lib/components/ui/alert";
import { CircleAlert } from "@lucide/svelte";
import { LoadingCircle } from '$lib/components/ui/loading-circle';
@@ -26,6 +27,7 @@
authState.setToken(token);
if (needsSetup) {
+ // Leave the stashed returnTo in place: finish-setup consumes it.
goto('/finish-setup');
return;
}
@@ -40,7 +42,7 @@
const data = await response.json();
authState.setOrganizations(data.organizations || []);
projectsState.setProjects(data.projects || []);
- goto('/');
+ goto(safeLocalPath(consumeSsoReturnTo()));
} catch {
authState.logout();
error = 'Failed to load your account. Please try logging in again.';
diff --git a/frontend/src/routes/device/+page.svelte b/frontend/src/routes/device/+page.svelte
new file mode 100644
index 00000000..1f496012
--- /dev/null
+++ b/frontend/src/routes/device/+page.svelte
@@ -0,0 +1,246 @@
+<script lang="ts">
+ import { goto } from '$app/navigation';
+ import { page } from '$app/state';
+ import { onMount } from 'svelte';
+ import { Button } from '$lib/components/ui/button';
+ import { Input } from '$lib/components/ui/input';
+ import { Label } from '$lib/components/ui/label';
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '$lib/components/ui/card';
+ import { Alert, AlertDescription, AlertTitle } from '$lib/components/ui/alert';
+ import { CircleAlert, Check, ShieldCheck } from '@lucide/svelte';
+ import { authState } from '$lib/state/auth.svelte';
+ import { themeState } from '$lib/state/theme.svelte';
+
+ type Status =
+ | 'loading'
+ | 'needLogin'
+ | 'needCode'
+ | 'confirm'
+ | 'approving'
+ | 'approved'
+ | 'denied'
+ | 'notFound'
+ | 'expired'
+ | 'alreadyHandled'
+ | 'error';
+
+ let status = $state<Status>('loading');
+ let error = $state('');
+ let info = $state<{ userCode: string; clientName: string } | null>(null);
+ let manualCode = $state('');
+
+ const userCode = $derived(page.url.searchParams.get('user_code'));
+
+ // Codes are generated uppercase in the XXXX-XXXX shape; users may paste them
+ // lowercase, with spaces, or without the hyphen. Normalize to match the
+ // server's exact lookup.
+ function normalizeUserCode(raw: string): string {
+ const cleaned = raw.toUpperCase().replace(/[^0-9A-Z]/g, '');
+ return cleaned.length === 8 ? `${cleaned.slice(0, 4)}-${cleaned.slice(4)}` : cleaned;
+ }
+
+ function loginRedirect() {
+ const target = `/device${userCode ? `?user_code=${encodeURIComponent(userCode)}` : ''}`;
+ goto(`/login?returnTo=${encodeURIComponent(target)}`);
+ }
+
+ async function lookup(code: string) {
+ status = 'loading';
+ error = '';
+ try {
+ const res = await fetch(`/api/device?user_code=${encodeURIComponent(code)}`, {
+ headers: { Authorization: `Bearer ${authState.token}` }
+ });
+ if (res.status === 401) {
+ // The stored session is dead; clear it or the login page's
+ // authenticated-redirect bounces us to / and loses the code.
+ authState.logout();
+ loginRedirect();
+ return;
+ }
+ if (res.status === 404) {
+ status = 'notFound';
+ return;
+ }
+ if (res.status === 410) {
+ status = 'expired';
+ return;
+ }
+ if (!res.ok) {
+ status = 'error';
+ error = 'We could not look up that code.';
+ return;
+ }
+ const data = await res.json();
+ if (data.status === 'approved' || data.status === 'denied') {
+ status = 'alreadyHandled';
+ return;
+ }
+ if (data.status === 'expired') {
+ status = 'expired';
+ return;
+ }
+ info = { userCode: data.user_code, clientName: data.clientName || 'a device' };
+ status = 'confirm';
+ } catch {
+ status = 'error';
+ error = 'We could not reach the server. Please try again.';
+ }
+ }
+
+ async function resolve(approve: boolean) {
+ if (!info) return;
+ status = 'approving';
+ error = '';
+ try {
+ const res = await fetch(`/api/device/${approve ? 'approve' : 'deny'}`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ Authorization: `Bearer ${authState.token}`
+ },
+ body: JSON.stringify({ user_code: info.userCode })
+ });
+ if (!res.ok) {
+ if (res.status === 401) {
+ authState.logout();
+ loginRedirect();
+ return;
+ }
+ if (res.status === 404) {
+ status = 'notFound';
+ return;
+ }
+ if (res.status === 410) {
+ status = 'expired';
+ return;
+ }
+ status = 'error';
+ error = 'We could not complete the request.';
+ return;
+ }
+ status = approve ? 'approved' : 'denied';
+ } catch {
+ status = 'error';
+ error = 'We could not reach the server. Please try again.';
+ }
+ }
+
+ function submitManual(e: SubmitEvent) {
+ e.preventDefault();
+ const code = normalizeUserCode(manualCode);
+ if (code) lookup(code);
+ }
+
+ onMount(() => {
+ if (!authState.isAuthenticated) {
+ status = 'needLogin';
+ return;
+ }
+ if (userCode) {
+ lookup(normalizeUserCode(userCode));
+ } else {
+ status = 'needCode';
+ }
+ });
+</script>
+
+<div class="flex min-h-screen w-full items-center justify-center px-4 py-8">
+ <Card class="w-[420px]">
+ <CardHeader>
+ <CardTitle class="text-2xl">
+ <div class="flex flex-row items-center justify-center gap-2">
+ {#if themeState.isDark}
+ <img src="/traceway-logo-white.svg" alt="Traceway Logo" class="h-8 w-auto" />
+ {:else}
+ <img src="/traceway-logo.png" alt="Traceway Logo" class="h-8 w-auto" />
+ {/if}
+ </div>
+ </CardTitle>
+ <CardDescription class="text-center">Device login</CardDescription>
+ </CardHeader>
+ <CardContent>
+ {#if status === 'loading' || status === 'approving'}
+ <div class="flex items-center justify-center py-8">
+ <div class="h-8 w-8 animate-spin rounded-full border-b-2 border-primary"></div>
+ </div>
+ {:else if status === 'needLogin'}
+ <div class="space-y-4">
+ <p class="text-center text-muted-foreground">
+ Log in to confirm a device login on your account.
+ </p>
+ <Button class="w-full" onclick={loginRedirect}>Log in to continue</Button>
+ </div>
+ {:else if status === 'needCode'}
+ <form onsubmit={submitManual} class="space-y-4">
+ <div class="space-y-2">
+ <Label for="code">Enter the code shown in your terminal</Label>
+ <Input id="code" bind:value={manualCode} placeholder="XXXX-XXXX" autocomplete="off" />
+ </div>
+ <Button type="submit" class="w-full" disabled={!manualCode.trim()}>Continue</Button>
+ </form>
+ {:else if status === 'confirm' && info}
+ <div class="space-y-4">
+ <p class="text-center text-muted-foreground">
+ <strong>{info.clientName}</strong> is requesting access to your Traceway account.
+ </p>
+ <div class="font-mono text-4xl font-semibold tracking-[0.3em] text-center py-4">
+ {info.userCode}
+ </div>
+ <p class="text-center text-sm text-muted-foreground">
+ Only approve if this matches the code shown in your terminal.
+ </p>
+ <div class="flex gap-2">
+ <Button class="flex-1" onclick={() => resolve(true)}>
+ <ShieldCheck class="mr-2 h-4 w-4" />
+ Approve
+ </Button>
+ <Button variant="outline" class="flex-1" onclick={() => resolve(false)}>Deny</Button>
+ </div>
+ </div>
+ {:else if status === 'approved'}
+ <div class="flex flex-col items-center justify-center gap-4 py-8">
+ <div class="rounded-full bg-green-100 p-3">
+ <Check class="h-8 w-8 text-green-600" />
+ </div>
+ <p class="text-center text-lg font-medium">Device approved</p>
+ <p class="text-center text-muted-foreground">You can return to your terminal.</p>
+ </div>
+ {:else if status === 'denied'}
+ <Alert>
+ <CircleAlert class="h-4 w-4" />
+ <AlertTitle>Request denied</AlertTitle>
+ <AlertDescription>The device login was denied. You can close this page.</AlertDescription>
+ </Alert>
+ {:else if status === 'notFound'}
+ <Alert variant="destructive" class="border-red-200 bg-red-50">
+ <CircleAlert class="h-4 w-4 text-red-700" />
+ <AlertTitle class="text-red-800">Code not found</AlertTitle>
+ <AlertDescription class="text-red-700">
+ We couldn't find that code. Start a new login from your terminal.
+ </AlertDescription>
+ </Alert>
+ {:else if status === 'expired'}
+ <Alert variant="destructive" class="border-red-200 bg-red-50">
+ <CircleAlert class="h-4 w-4 text-red-700" />
+ <AlertTitle class="text-red-800">Code expired</AlertTitle>
+ <AlertDescription class="text-red-700">
+ This login request has expired. Start a new login from your terminal.
+ </AlertDescription>
+ </Alert>
+ {:else if status === 'alreadyHandled'}
+ <Alert>
+ <CircleAlert class="h-4 w-4" />
+ <AlertTitle>Already handled</AlertTitle>
+ <AlertDescription>This login request was already approved or denied.</AlertDescription>
+ </Alert>
+ {:else}
+ <Alert variant="destructive" class="border-red-200 bg-red-50">
+ <CircleAlert class="h-4 w-4 text-red-700" />
+ <AlertTitle class="text-red-800">Something went wrong</AlertTitle>
+ <AlertDescription class="text-red-700">{error || 'Please try again.'}</AlertDescription>
+ </Alert>
+ {/if}
+ </CardContent>
+ </Card>
+</div>
diff --git a/frontend/src/routes/finish-setup/+page.svelte b/frontend/src/routes/finish-setup/+page.svelte
index f19751ec..506b0f9e 100644
--- a/frontend/src/routes/finish-setup/+page.svelte
+++ b/frontend/src/routes/finish-setup/+page.svelte
@@ -12,6 +12,7 @@
import { projectsState, type Framework } 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';
const DEFAULT_FRAMEWORK: Framework = 'gin';
@@ -52,7 +53,7 @@
authState.setToken(data.token);
authState.setOrganizations(data.organizations || []);
projectsState.setProjects(data.projects);
- goto('/');
+ goto(safeLocalPath(consumeSsoReturnTo()));
} catch (e) {
error = e instanceof Error ? e.message : 'Setup failed';
} finally {
diff --git a/frontend/src/routes/login/+page.svelte b/frontend/src/routes/login/+page.svelte
index f48f89b0..dfbef8d8 100644
--- a/frontend/src/routes/login/+page.svelte
+++ b/frontend/src/routes/login/+page.svelte
@@ -12,6 +12,7 @@
import { themeState } from '$lib/state/theme.svelte';
import { toast } from 'svelte-sonner';
import OauthButtons from '$lib/components/oauth-buttons.svelte';
+ import { safeLocalPath } from '$lib/utils/navigation';
const ERROR_MESSAGES: Record<string, string> = {
oauth_failed: 'Sign-in failed. Please try again.',
@@ -86,9 +87,8 @@
authState.setOrganizations(data.organizations || []);
projectsState.setProjects(data.projects);
- // Redirect to returnTo if provided, otherwise go to dashboard
- const redirectTo = returnTo ? decodeURIComponent(returnTo) : '/';
- goto(redirectTo);
+ // Redirect to returnTo if provided (validated same-origin), otherwise dashboard
+ goto(safeLocalPath(returnTo));
} catch (e) {
error = e instanceof Error ? e.message : 'Invalid email or password';
} finally {
diff --git a/skills/traceway-setup/android.md b/skills/traceway-setup/android.md
index 92108b8f..b28df7f4 100644
--- a/skills/traceway-setup/android.md
+++ b/skills/traceway-setup/android.md
@@ -105,7 +105,8 @@ android {
}
traceway {
- uploadToken = "<upload-token>" // prefer a Gradle property / env var in CI
+ // The plugin reads no environment variables itself — wire the secret in here.
+ uploadToken = System.getenv("TRACEWAY_UPLOAD_TOKEN") ?: ""
url = "https://<instance>" // instance base URL
autoUpload = false // true runs upload after assembleRelease
// proguardUuid = "..." // optional: pin the build UUID yourself
@@ -131,7 +132,7 @@ Traceway.init(
./gradlew assembleRelease uploadReleaseTracewaySymbols
```
-With `autoUpload = true` the upload runs automatically after `assembleRelease`. Keep the upload token in a secret and feed it through the environment or a Gradle property rather than the literal above:
+With `autoUpload = true` the upload runs automatically after `assembleRelease`. Keep the upload token in a CI secret — the `System.getenv` wiring in the `traceway { ... }` block above is what feeds it to the plugin (there is no built-in environment lookup):
```bash
TRACEWAY_UPLOAD_TOKEN=<upload-token> ./gradlew assembleRelease uploadReleaseTracewaySymbols