Skip to content

armgit / posta

Public Imported from GitHub
0

Self-hosted email delivery platform that enables applications to send emails via HTTP APIs while handling SMTP delivery, templates, storage, security, and analytics. Fully self-hostable alternative to services like SendGrid or Mailgun.

feat(auth): self-service password reset (off by default) (#130)

Jonas Kanindab4efe3644b02
diff --git a/internal/handlers/user_handler.go b/internal/handlers/user_handler.go
index e2821e5..6dd1d1c 100644
--- a/internal/handlers/user_handler.go
+++ b/internal/handlers/user_handler.go
@@ -31,6 +31,7 @@ import (
"github.com/goposta/posta/internal/services/emailverify"
"github.com/goposta/posta/internal/services/eventbus"
"github.com/goposta/posta/internal/services/notification"
+ "github.com/goposta/posta/internal/services/passwordreset"
"github.com/goposta/posta/internal/services/seeder"
"github.com/goposta/posta/internal/services/settings"
"github.com/goposta/posta/internal/services/twofactor"
@@ -51,6 +52,7 @@ type UserHandler struct {
settings *settings.Provider
notifier *notification.Service
emailVerifier *emailverify.Service
+ passwordReset *passwordreset.Service
db *gorm.DB
migrator *workspacemigrate.Service
}
@@ -98,6 +100,18 @@ func (h *UserHandler) SetEmailVerifier(s *emailverify.Service) {
h.emailVerifier = s
}
+// SetPasswordReset wires the self-service password reset service.
+func (h *UserHandler) SetPasswordReset(s *passwordreset.Service) {
+ h.passwordReset = s
+}
+
+// passwordResetEnabled reports whether the forgot-password flow is both turned
+// on in platform settings and actually deliverable (notifier configured).
+func (h *UserHandler) passwordResetEnabled() bool {
+ return h.settings != nil && h.settings.PasswordResetEnabled() &&
+ h.passwordReset != nil && h.passwordReset.Deliverable()
+}
+
type LoginRequest struct {
Body struct {
Email string `json:"email" required:"true" format:"email"`
@@ -256,10 +270,78 @@ func (h *UserHandler) Register(c *okapi.Context, req *RegisterRequest) error {
})
}
-// RegistrationStatus returns whether registration is enabled (public endpoint).
func (h *UserHandler) RegistrationStatus(c *okapi.Context) error {
enabled := h.settings != nil && h.settings.RegistrationEnabled()
- return ok(c, okapi.M{"registration_enabled": enabled})
+ return ok(c, okapi.M{
+ "registration_enabled": enabled,
+ "password_reset_enabled": h.passwordResetEnabled(),
+ })
+}
+
+type ForgotPasswordRequest struct {
+ Body struct {
+ Email string `json:"email" required:"true" format:"email"`
+ } `json:"body"`
+}
+
+type ResetPasswordRequest struct {
+ Body struct {
+ Token string `json:"token" required:"true"`
+ NewPassword string `json:"new_password" required:"true" minLength:"8"`
+ } `json:"body"`
+}
+
+func (h *UserHandler) ForgotPassword(c *okapi.Context, req *ForgotPasswordRequest) error {
+ if !h.passwordResetEnabled() {
+ return c.AbortBadRequest("password reset is not enabled")
+ }
+
+ const genericMsg = "If an account exists for that email, a password reset link is on its way."
+ email := strings.ToLower(strings.TrimSpace(req.Body.Email))
+
+ user, err := h.repo.FindByEmail(email)
+ if err != nil || user == nil {
+ return ok(c, okapi.M{"message": genericMsg})
+ }
+ // Rate-limit per account to curb token flooding; stay generic on the wire.
+ if err := h.passwordReset.CanIssue(user.ID); err != nil {
+ return ok(c, okapi.M{"message": genericMsg})
+ }
+ if err := h.passwordReset.IssueAndSend(user); err != nil {
+ logger.Error("failed to send password reset email", "user_id", user.ID, "err", err)
+ return ok(c, okapi.M{"message": genericMsg})
+ }
+ if h.bus != nil {
+ h.bus.PublishSimple(models.EventCategoryUser, "user.password_reset_requested", &user.ID, user.Email, c.RealIP(),
+ fmt.Sprintf("Password reset requested for %q", user.Email), nil)
+ }
+ return ok(c, okapi.M{"message": genericMsg})
+}
+
+// ResetPassword redeems a reset token and sets the new password.
+func (h *UserHandler) ResetPassword(c *okapi.Context, req *ResetPasswordRequest) error {
+ if !h.passwordResetEnabled() {
+ return c.AbortBadRequest("password reset is not enabled")
+ }
+
+ user, err := h.passwordReset.Redeem(req.Body.Token, req.Body.NewPassword)
+ if err != nil {
+ return c.AbortBadRequest(err.Error())
+ }
+
+ if h.bus != nil {
+ h.bus.PublishSimple(models.EventCategoryUser, "user.password_reset", &user.ID, user.Email, c.RealIP(),
+ fmt.Sprintf("Password reset completed for %q", user.Email), nil)
+ }
+ // Notify the account owner that their password changed (best-effort).
+ if h.notifier != nil {
+ go func(uid uint) {
+ _ = h.notifier.SendSecurityToUser(uid, "Your password has been changed", notification.TemplatePasswordChanged, map[string]any{
+ "ChangedAt": time.Now().UTC().Format("January 2, 2006 at 15:04 UTC"),
+ })
+ }(user.ID)
+ }
+ return ok(c, okapi.M{"message": "password updated successfully"})
}
type VerifyEmailRequest struct {
diff --git a/internal/models/password_reset.go b/internal/models/password_reset.go
new file mode 100644
index 0000000..a01d8da
--- /dev/null
+++ b/internal/models/password_reset.go
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package models
+
+import "time"
+
+// PasswordResetToken backs the "forgot password" flow: a single-use, hashed,
+// expiring token tied to a user. Only the SHA-256 hash is stored.
+type PasswordResetToken struct {
+ ID uint `gorm:"primaryKey"`
+ UserID uint `gorm:"index;not null"`
+ TokenHash string `gorm:"uniqueIndex;size:64;not null"`
+ ExpiresAt time.Time `gorm:"not null"`
+ UsedAt *time.Time `gorm:""`
+ CreatedAt time.Time `gorm:"not null"`
+}
diff --git a/internal/routes/auth_routes.go b/internal/routes/auth_routes.go
index c841b10..6af1c05 100644
--- a/internal/routes/auth_routes.go
+++ b/internal/routes/auth_routes.go
@@ -121,6 +121,33 @@ func (r *Router) authRoutes() []okapi.RouteDefinition {
okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
},
},
+ {
+ Method: http.MethodPost,
+ Path: "/forgot-password",
+ Handler: okapi.H(r.h.user.ForgotPassword),
+ Group: authGroup,
+ Summary: "Request password reset",
+ Description: "Email a password reset link (when the feature is enabled). Always responds generically to avoid revealing whether an account exists.",
+ Request: &handlers.ForgotPasswordRequest{},
+ Response: &dto.Response[any]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
+ okapi.DocErrorResponse(429, &dto.ErrorResponseBody{}),
+ },
+ },
+ {
+ Method: http.MethodPost,
+ Path: "/reset-password",
+ Handler: okapi.H(r.h.user.ResetPassword),
+ Group: authGroup,
+ Summary: "Reset password",
+ Description: "Redeem a password reset token and set a new password",
+ Request: &handlers.ResetPasswordRequest{},
+ Response: &dto.Response[any]{},
+ Options: []okapi.RouteOption{
+ okapi.DocErrorResponse(400, &dto.ErrorResponseBody{}),
+ },
+ },
}
}
diff --git a/internal/routes/routes.go b/internal/routes/routes.go
index d6331c8..4fae614 100644
--- a/internal/routes/routes.go
+++ b/internal/routes/routes.go
@@ -35,6 +35,7 @@ import (
"github.com/goposta/posta/internal/services/eventbus"
"github.com/goposta/posta/internal/services/inbound"
"github.com/goposta/posta/internal/services/notification"
+ "github.com/goposta/posta/internal/services/passwordreset"
planpkg "github.com/goposta/posta/internal/services/plan"
"github.com/goposta/posta/internal/services/ratelimit"
"github.com/goposta/posta/internal/services/seeder"
@@ -293,6 +294,10 @@ func InitRoutes(app *okapi.Okapi, db *gorm.DB, redisClient *redis.Client, cfg *c
r.h.user.SetEmailVerifier(emailVerifySvc)
r.mw.verifiedEmail = middlewares.RequireVerifiedEmail(emailVerifySvc, userRepo)
+ // Self-service password reset (gated by the password_reset_enabled setting)
+ passwordResetSvc := passwordreset.NewService(userRepo, repositories.NewPasswordResetRepository(db), notif, cfg.AppWebURL)
+ r.h.user.SetPasswordReset(passwordResetSvc)
+
// Email content privacy
r.h.email.SetSettings(settingsProvider)
r.h.admin.SetEmailSettings(settingsProvider)
diff --git a/internal/services/notification/service.go b/internal/services/notification/service.go
index d8e387e..c7561d8 100644
--- a/internal/services/notification/service.go
+++ b/internal/services/notification/service.go
@@ -39,6 +39,7 @@ const (
TemplateInvitation = "workspace_invitation"
TemplateWelcome = "welcome"
TemplatePasswordChanged = "password_changed"
+ TemplatePasswordReset = "password_reset"
TemplateAPIKeyCreated = "api_key_created"
TemplateAPIKeyExpiry = "api_key_expiry"
TemplateBounceAlert = "bounce_alert"
@@ -103,6 +104,7 @@ func (s *Service) loadTemplates() {
TemplateInvitation,
TemplateWelcome,
TemplatePasswordChanged,
+ TemplatePasswordReset,
TemplateAPIKeyCreated,
TemplateAPIKeyExpiry,
TemplateBounceAlert,
diff --git a/internal/services/notification/templates/password_reset.tmpl b/internal/services/notification/templates/password_reset.tmpl
new file mode 100644
index 0000000..f075a5d
--- /dev/null
+++ b/internal/services/notification/templates/password_reset.tmpl
@@ -0,0 +1,19 @@
+{{ define "content" }}
+<h2 style="color: #111827; font-size: 20px; line-height: 1.3; margin: 0 0 18px; font-weight: 700; letter-spacing: -0.01em;">Reset your password</h2>
+<p style="margin: 0 0 16px;">Hi {{ .UserName }},</p>
+<p class="lead" style="margin: 0 0 16px; font-size: 15px; color: #4b5563;">We received a request to reset the password for your {{ .AppName }} account. Click the button below to choose a new one.</p>
+
+{{ if .ResetURL }}
+<table role="presentation" cellpadding="0" cellspacing="0" border="0" align="center" style="margin: 28px auto;">
+ <tr><td align="center" bgcolor="#7c3aed" style="border-radius: 8px;">
+ <a href="{{ .ResetURL }}" class="btn" style="display: inline-block; padding: 13px 30px; background-color: #7c3aed; color: #ffffff !important; text-decoration: none; border-radius: 8px; font-weight: 600; font-size: 15px; line-height: 1;">Reset password</a>
+ </td></tr>
+</table>
+
+<p class="muted" style="margin: 0 0 16px; color: #6b7280; font-size: 13px;">Or paste this link into your browser:</p>
+<p class="link-fallback" style="margin: 0 0 16px; word-break: break-all; font-size: 13px;"><a href="{{ .ResetURL }}" style="color: #7c3aed;">{{ .ResetURL }}</a></p>
+{{ end }}
+
+<div class="divider" style="height: 1px; line-height: 1px; font-size: 1px; background-color: #eceef2; margin: 28px 0;"></div>
+<p class="muted" style="margin: 0 0 16px; color: #6b7280; font-size: 13px;">This link expires in {{ .ExpiryHours }} hour(s). If you didn't request a password reset, you can safely ignore this email — your password won't change.</p>
+{{ end }}
diff --git a/internal/services/passwordreset/service.go b/internal/services/passwordreset/service.go
new file mode 100644
index 0000000..3547c93
--- /dev/null
+++ b/internal/services/passwordreset/service.go
@@ -0,0 +1,173 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// Package passwordreset handles the self-service "forgot password" flow: token
+// issuance, delivery via a notification template, and redemption (which sets a
+// new password). The feature is gated by a platform setting checked at the
+// handler layer; this service is concerned only with token mechanics.
+package passwordreset
+
+import (
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/hex"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/services/notification"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "golang.org/x/crypto/bcrypt"
+)
+
+const (
+ tokenTTL = 1 * time.Hour
+ resendWindow = 1 * time.Hour
+ resendMaxInWindow = 5
+)
+
+// Service coordinates password-reset token issuance and redemption.
+type Service struct {
+ userRepo *repositories.UserRepository
+ tokenRepo *repositories.PasswordResetRepository
+ notifier *notification.Service
+ appURL string
+}
+
+func NewService(
+ userRepo *repositories.UserRepository,
+ tokenRepo *repositories.PasswordResetRepository,
+ notifier *notification.Service,
+ appURL string,
+) *Service {
+ return &Service{
+ userRepo: userRepo,
+ tokenRepo: tokenRepo,
+ notifier: notifier,
+ appURL: strings.TrimRight(appURL, "/"),
+ }
+}
+
+func (s *Service) Deliverable() bool {
+ return s != nil && s.notifier != nil && s.notifier.IsConfigured()
+}
+
+func (s *Service) IssueAndSend(user *models.User) error {
+ if !s.Deliverable() {
+ return nil
+ }
+ if user == nil {
+ return errors.New("passwordreset: nil user")
+ }
+
+ if err := s.tokenRepo.InvalidatePending(user.ID); err != nil {
+ return fmt.Errorf("passwordreset: invalidate pending: %w", err)
+ }
+
+ rawToken, hash, err := newToken()
+ if err != nil {
+ return err
+ }
+ t := &models.PasswordResetToken{
+ UserID: user.ID,
+ TokenHash: hash,
+ ExpiresAt: time.Now().Add(tokenTTL),
+ CreatedAt: time.Now(),
+ }
+ if err := s.tokenRepo.Create(t); err != nil {
+ return fmt.Errorf("passwordreset: create token: %w", err)
+ }
+
+ resetURL := fmt.Sprintf("%s/auth/reset-password?token=%s", s.appURL, rawToken)
+ return s.notifier.Send(user.Email, "Reset your password", notification.TemplatePasswordReset, map[string]any{
+ "UserName": displayName(user),
+ "ResetURL": resetURL,
+ "ExpiryHours": int(tokenTTL.Hours()),
+ })
+}
+
+func (s *Service) Redeem(rawToken, newPassword string) (*models.User, error) {
+ if rawToken == "" {
+ return nil, errors.New("token is required")
+ }
+ t, err := s.tokenRepo.FindByTokenHash(hashToken(rawToken))
+ if err != nil {
+ return nil, errors.New("invalid or expired token")
+ }
+ if t.UsedAt != nil {
+ return nil, errors.New("this reset link has already been used")
+ }
+ if time.Now().After(t.ExpiresAt) {
+ return nil, errors.New("this reset link has expired")
+ }
+
+ user, err := s.userRepo.FindByID(t.UserID)
+ if err != nil {
+ return nil, errors.New("user not found")
+ }
+
+ hash, err := bcrypt.GenerateFromPassword([]byte(newPassword), bcrypt.DefaultCost)
+ if err != nil {
+ return nil, fmt.Errorf("passwordreset: hash password: %w", err)
+ }
+ user.PasswordHash = string(hash)
+ if err := s.userRepo.Update(user); err != nil {
+ return nil, fmt.Errorf("passwordreset: update password: %w", err)
+ }
+
+ if err := s.tokenRepo.MarkUsed(t.ID); err != nil {
+ return nil, fmt.Errorf("passwordreset: mark used: %w", err)
+ }
+ // Burn any other outstanding tokens so a second link can't reset again.
+ _ = s.tokenRepo.InvalidatePending(user.ID)
+ return user, nil
+}
+
+// CanIssue returns an error when the user has hit the request rate limit.
+func (s *Service) CanIssue(userID uint) error {
+ count, err := s.tokenRepo.CountRecentByUser(userID, time.Now().Add(-resendWindow))
+ if err != nil {
+ return nil
+ }
+ if count >= resendMaxInWindow {
+ return fmt.Errorf("too many password reset requests recently, try again later")
+ }
+ return nil
+}
+
+func newToken() (raw, hashHex string, err error) {
+ buf := make([]byte, 32)
+ if _, err := rand.Read(buf); err != nil {
+ return "", "", err
+ }
+ raw = hex.EncodeToString(buf)
+ return raw, hashToken(raw), nil
+}
+
+func hashToken(raw string) string {
+ sum := sha256.Sum256([]byte(raw))
+ return hex.EncodeToString(sum[:])
+}
+
+func displayName(u *models.User) string {
+ if u.Name != "" {
+ return u.Name
+ }
+ return u.Email
+}
diff --git a/internal/services/passwordreset/service_test.go b/internal/services/passwordreset/service_test.go
new file mode 100644
index 0000000..bb42def
--- /dev/null
+++ b/internal/services/passwordreset/service_test.go
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package passwordreset
+
+import (
+ "os"
+ "testing"
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "github.com/goposta/posta/internal/storage/repositories"
+ "golang.org/x/crypto/bcrypt"
+ "gorm.io/driver/postgres"
+ "gorm.io/gorm"
+ "gorm.io/gorm/logger"
+)
+
+func setup(t *testing.T) (*Service, *repositories.UserRepository, *repositories.PasswordResetRepository) {
+ t.Helper()
+ dsn := os.Getenv("TEST_DATABASE_DSN")
+ if dsn == "" {
+ dsn = "host=localhost user=posta password=posta dbname=posta port=5432 sslmode=disable"
+ }
+ db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
+ if err != nil {
+ t.Skipf("skipping: no test database available: %v", err)
+ }
+ if err := db.AutoMigrate(&models.User{}, &models.PasswordResetToken{}); err != nil {
+ t.Skipf("skipping: cannot migrate schema: %v", err)
+ }
+ tx := db.Begin()
+ t.Cleanup(func() { tx.Rollback() })
+ userRepo := repositories.NewUserRepository(tx)
+ tokenRepo := repositories.NewPasswordResetRepository(tx)
+ return NewService(userRepo, tokenRepo, nil, "https://app.test"), userRepo, tokenRepo
+}
+
+func mkUser(t *testing.T, r *repositories.UserRepository, email string) *models.User {
+ t.Helper()
+ hash, _ := bcrypt.GenerateFromPassword([]byte("oldpassword"), bcrypt.DefaultCost)
+ u := &models.User{Name: "T", Email: email, PasswordHash: string(hash)}
+ if err := r.Create(u); err != nil {
+ t.Fatalf("create user: %v", err)
+ }
+ return u
+}
+
+// issue mints a token row directly and returns the raw token.
+func issue(t *testing.T, r *repositories.PasswordResetRepository, userID uint, expires time.Time) string {
+ t.Helper()
+ raw, hash, err := newToken()
+ if err != nil {
+ t.Fatalf("newToken: %v", err)
+ }
+ if err := r.Create(&models.PasswordResetToken{UserID: userID, TokenHash: hash, ExpiresAt: expires, CreatedAt: time.Now()}); err != nil {
+ t.Fatalf("create token: %v", err)
+ }
+ return raw
+}
+
+func TestRedeemSetsNewPasswordAndBurnsToken(t *testing.T) {
+ svc, userRepo, tokenRepo := setup(t)
+ user := mkUser(t, userRepo, "[email protected]")
+ raw := issue(t, tokenRepo, user.ID, time.Now().Add(time.Hour))
+
+ got, err := svc.Redeem(raw, "brand-new-password")
+ if err != nil {
+ t.Fatalf("Redeem: %v", err)
+ }
+ if got.ID != user.ID {
+ t.Fatalf("Redeem returned user %d, want %d", got.ID, user.ID)
+ }
+
+ reloaded, _ := userRepo.FindByID(user.ID)
+ if bcrypt.CompareHashAndPassword([]byte(reloaded.PasswordHash), []byte("brand-new-password")) != nil {
+ t.Error("password was not updated to the new value")
+ }
+
+ // Single-use: the same token can't be redeemed again.
+ if _, err := svc.Redeem(raw, "another-password"); err == nil {
+ t.Error("expected reused token to be rejected")
+ }
+}
+
+func TestRedeemRejectsExpiredAndInvalidTokens(t *testing.T) {
+ svc, userRepo, tokenRepo := setup(t)
+ user := mkUser(t, userRepo, "[email protected]")
+
+ expired := issue(t, tokenRepo, user.ID, time.Now().Add(-time.Minute))
+ if _, err := svc.Redeem(expired, "whatever12"); err == nil {
+ t.Error("expected expired token to be rejected")
+ }
+ if _, err := svc.Redeem("not-a-real-token", "whatever12"); err == nil {
+ t.Error("expected unknown token to be rejected")
+ }
+ if _, err := svc.Redeem("", "whatever12"); err == nil {
+ t.Error("expected empty token to be rejected")
+ }
+}
diff --git a/internal/services/seeder/settings.go b/internal/services/seeder/settings.go
index 02a5a59..9900e97 100644
--- a/internal/services/seeder/settings.go
+++ b/internal/services/seeder/settings.go
@@ -45,6 +45,7 @@ func SeedDefaultSettings(repo *repositories.SettingRepository) {
{Key: "webhook_delivery_retention_days", Value: "30", Type: "int"},
{Key: "email_content_visibility", Value: "false", Type: "bool"},
{Key: "custom_headers_enabled", Value: "false", Type: "bool"},
+ {Key: "password_reset_enabled", Value: "false", Type: "bool"},
}
for i := range defaults {
diff --git a/internal/services/settings/provider.go b/internal/services/settings/provider.go
index 1c940bd..33232d9 100644
--- a/internal/services/settings/provider.go
+++ b/internal/services/settings/provider.go
@@ -146,3 +146,7 @@ func (p *Provider) EmailContentVisibility() bool {
func (p *Provider) CustomHeadersEnabled() bool {
return p.GetBool("custom_headers_enabled", false)
}
+
+func (p *Provider) PasswordResetEnabled() bool {
+ return p.GetBool("password_reset_enabled", false)
+}
diff --git a/internal/storage/migration/migration.go b/internal/storage/migration/migration.go
index 0fb00e0..7429d19 100644
--- a/internal/storage/migration/migration.go
+++ b/internal/storage/migration/migration.go
@@ -61,6 +61,7 @@ func Run(db *gorm.DB) error {
&models.WebhookDelivery{},
&models.Session{},
&models.UserEmailVerification{},
+ &models.PasswordResetToken{},
&models.Subscriber{},
&models.SubscriberList{},
&models.SubscriberListMember{},
diff --git a/internal/storage/repositories/password_reset_repo.go b/internal/storage/repositories/password_reset_repo.go
new file mode 100644
index 0000000..d23f22b
--- /dev/null
+++ b/internal/storage/repositories/password_reset_repo.go
@@ -0,0 +1,70 @@
+/*
+ * Copyright 2026 Jonas Kaninda
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+package repositories
+
+import (
+ "time"
+
+ "github.com/goposta/posta/internal/models"
+ "gorm.io/gorm"
+)
+
+type PasswordResetRepository struct {
+ db *gorm.DB
+}
+
+func NewPasswordResetRepository(db *gorm.DB) *PasswordResetRepository {
+ return &PasswordResetRepository{db: db}
+}
+
+func (r *PasswordResetRepository) Create(t *models.PasswordResetToken) error {
+ return r.db.Create(t).Error
+}
+
+func (r *PasswordResetRepository) FindByTokenHash(hash string) (*models.PasswordResetToken, error) {
+ var t models.PasswordResetToken
+ if err := r.db.Where("token_hash = ?", hash).First(&t).Error; err != nil {
+ return nil, err
+ }
+ return &t, nil
+}
+
+func (r *PasswordResetRepository) MarkUsed(id uint) error {
+ now := time.Now()
+ return r.db.Model(&models.PasswordResetToken{}).
+ Where("id = ?", id).
+ Update("used_at", now).Error
+}
+
+// InvalidatePending marks all pending (unused) tokens for a user as used.
+// Called when a new token is issued or when a reset completes.
+func (r *PasswordResetRepository) InvalidatePending(userID uint) error {
+ now := time.Now()
+ return r.db.Model(&models.PasswordResetToken{}).
+ Where("user_id = ? AND used_at IS NULL", userID).
+ Update("used_at", now).Error
+}
+
+// CountRecentByUser counts tokens created for a user since a given time (for rate limiting).
+func (r *PasswordResetRepository) CountRecentByUser(userID uint, since time.Time) (int64, error) {
+ var count int64
+ err := r.db.Model(&models.PasswordResetToken{}).
+ Where("user_id = ? AND created_at > ?", userID, since).
+ Count(&count).Error
+ return count, err
+}
diff --git a/web/src/api/auth.ts b/web/src/api/auth.ts
index babdfc5..a86e6a9 100644
--- a/web/src/api/auth.ts
+++ b/web/src/api/auth.ts
@@ -38,7 +38,13 @@ export const authApi = {
return api.post<ApiResponse<AuthResponse>>('/auth/register', { name, email, password })
},
registrationStatus() {
- return api.get<ApiResponse<{ registration_enabled: boolean }>>('/auth/registration-status')
+ return api.get<ApiResponse<{ registration_enabled: boolean; password_reset_enabled: boolean }>>('/auth/registration-status')
+ },
+ forgotPassword(email: string) {
+ return api.post<ApiResponse<{ message: string }>>('/auth/forgot-password', { email })
+ },
+ resetPassword(token: string, newPassword: string) {
+ return api.post<ApiResponse<{ message: string }>>('/auth/reset-password', { token, new_password: newPassword })
},
verifyEmail(token: string) {
return api.get<ApiResponse<{ message: string }>>(`/auth/verify-email?token=${encodeURIComponent(token)}`)
diff --git a/web/src/router/index.ts b/web/src/router/index.ts
index 2290893..7c30f04 100644
--- a/web/src/router/index.ts
+++ b/web/src/router/index.ts
@@ -36,6 +36,18 @@ const routes = [
component: () => import('../views/auth/VerifyEmail.vue'),
meta: { title: 'Verify email' },
},
+ {
+ path: '/auth/forgot-password',
+ name: 'forgot-password',
+ component: () => import('../views/auth/ForgotPassword.vue'),
+ meta: { guest: true, title: 'Forgot password' },
+ },
+ {
+ path: '/auth/reset-password',
+ name: 'reset-password',
+ component: () => import('../views/auth/ResetPassword.vue'),
+ meta: { guest: true, title: 'Reset password' },
+ },
{
path: '/',
component: () => import('../layouts/DashboardLayout.vue'),
diff --git a/web/src/views/admin/Settings.vue b/web/src/views/admin/Settings.vue
index 6bc3f58..ef413ab 100644
--- a/web/src/views/admin/Settings.vue
+++ b/web/src/views/admin/Settings.vue
@@ -18,6 +18,7 @@ const settingMeta: Record<string, { label: string; description: string; category
require_email_verification: { label: 'Require Email Verification', description: 'New users must verify their email before sending.', category: 'Security' },
require_domain_verification: { label: 'Require Domain Verification', description: 'Users must verify domain ownership before sending.', category: 'Security' },
two_factor_required: { label: 'Require Two-Factor Auth', description: 'Force all users to enable 2FA.', category: 'Security' },
+ password_reset_enabled: { label: 'Self-Service Password Reset', description: 'Allow users to reset a forgotten password via an emailed link. Requires a configured system SMTP sender.', category: 'Security' },
default_rate_limit_hourly: { label: 'Hourly Rate Limit', description: 'Default hourly send limit for users.', category: 'Limits' },
default_rate_limit_daily: { label: 'Daily Rate Limit', description: 'Default daily send limit for users.', category: 'Limits' },
max_batch_size: { label: 'Max Batch Size', description: 'Maximum recipients in a single batch send.', category: 'Limits' },
diff --git a/web/src/views/auth/ForgotPassword.vue b/web/src/views/auth/ForgotPassword.vue
new file mode 100644
index 0000000..cfd2b86
--- /dev/null
+++ b/web/src/views/auth/ForgotPassword.vue
@@ -0,0 +1,165 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { authApi } from '../../api/auth'
+import { useThemeStore } from '../../stores/theme'
+
+const theme = useThemeStore()
+
+const email = ref('')
+const emailError = ref('')
+const loading = ref(false)
+const sent = ref(false)
+const message = ref('')
+const emailInput = ref<HTMLInputElement | null>(null)
+
+onMounted(() => emailInput.value?.focus())
+
+async function submit() {
+ emailError.value = ''
+ if (!email.value) {
+ emailError.value = 'Enter your email address.'
+ return
+ }
+ loading.value = true
+ try {
+ const res = await authApi.forgotPassword(email.value)
+ message.value = res.data.data?.message || 'If an account exists for that email, a reset link is on its way.'
+ sent.value = true
+ } catch (err: any) {
+ emailError.value = err?.response?.data?.error?.message || 'Could not send the reset email. Please try again.'
+ } finally {
+ loading.value = false
+ }
+}
+</script>
+
+<template>
+ <div class="auth-page">
+ <div class="auth-card">
+ <div class="auth-header">
+ <div class="auth-wordmark" aria-label="Posta">Posta<span class="auth-wordmark-dot">.</span></div>
+ <h1 class="auth-title">{{ sent ? 'Check your email' : 'Forgot your password?' }}</h1>
+ <p class="auth-subtitle">
+ {{ sent ? message : "Enter your account email and we'll send you a link to reset your password." }}
+ </p>
+ </div>
+
+ <form v-if="!sent" class="auth-form" @submit.prevent="submit">
+ <div class="form-group">
+ <label class="form-label" for="email">Email</label>
+ <input
+ id="email"
+ ref="emailInput"
+ v-model="email"
+ type="email"
+ class="form-input"
+ :class="{ 'form-input-error': emailError }"
+ placeholder="[email protected]"
+ autocomplete="email"
+ :disabled="loading"
+ :aria-invalid="!!emailError"
+ :aria-describedby="emailError ? 'email-error' : undefined"
+ @input="emailError = ''"
+ />
+ <small v-if="emailError" id="email-error" class="form-error">{{ emailError }}</small>
+ </div>
+ <button type="submit" class="btn btn-primary auth-btn" :disabled="loading">
+ <span v-if="loading" class="spinner"></span>
+ {{ loading ? 'Sending...' : 'Send reset link' }}
+ </button>
+ </form>
+
+ <div v-else class="auth-form">
+ <div class="auth-success" role="status">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>
+ <span>Reset link sent. The link expires in 1 hour.</span>
+ </div>
+ </div>
+
+ <div class="auth-footer">
+ <router-link :to="{ name: 'login' }">Back to sign in</router-link>
+ </div>
+ </div>
+
+ <button class="theme-btn" @click="theme.toggle()" :title="theme.isDark ? 'Light mode' : 'Dark mode'">
+ <svg v-if="theme.isDark" width="18" height="18" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="3" stroke="currentColor" stroke-width="1.5"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.05 3.05l1.41 1.41M11.54 11.54l1.41 1.41M3.05 12.95l1.41-1.41M11.54 4.46l1.41-1.41" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
+ <svg v-else width="18" height="18" viewBox="0 0 16 16" fill="none"><path d="M14 9.5A6.5 6.5 0 016.5 2 6.5 6.5 0 1014 9.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ </button>
+ </div>
+</template>
+
+<style scoped>
+.auth-page {
+ min-height: 100vh;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--bg-secondary);
+ padding: 20px;
+ position: relative;
+}
+.auth-card {
+ width: 100%;
+ max-width: 400px;
+ background: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius-xl);
+ box-shadow: var(--shadow-lg);
+}
+.auth-header { text-align: center; padding: 36px 32px 0; }
+.auth-wordmark {
+ font-size: 32px;
+ font-weight: 800;
+ letter-spacing: -1px;
+ color: var(--text-primary);
+ margin-bottom: 24px;
+ line-height: 1;
+}
+.auth-wordmark-dot { color: var(--primary-500); margin-left: 1px; }
+.auth-title {
+ font-size: 22px;
+ font-weight: 600;
+ color: var(--text-primary);
+ letter-spacing: -0.2px;
+ margin: 0 0 8px;
+}
+.auth-subtitle { font-size: 14px; color: var(--text-muted); margin: 0; line-height: 1.5; }
+.auth-form { padding: 28px 32px 20px; }
+.auth-btn { width: 100%; padding: 11px 18px; font-size: 15px; margin-top: 4px; }
+.form-input-error { border-color: var(--danger-500, #ef4444); }
+.form-error { display: block; font-size: 12px; color: var(--danger-600, #dc2626); margin-top: 6px; }
+.auth-success {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 12px 14px;
+ font-size: 14px;
+ color: var(--success-700, #15803d);
+ background: var(--success-50, #f0fdf4);
+ border: 1px solid var(--success-200, #bbf7d0);
+ border-radius: var(--radius);
+}
+.auth-success svg { flex-shrink: 0; }
+.auth-footer {
+ text-align: center;
+ padding: 0 32px 28px;
+ font-size: 14px;
+ color: var(--text-muted);
+}
+.auth-footer a { color: var(--primary-500); font-weight: 500; }
+.theme-btn {
+ position: fixed;
+ top: 20px;
+ right: 20px;
+ background: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ padding: 10px;
+ cursor: pointer;
+ color: var(--text-tertiary);
+ display: flex;
+ align-items: center;
+ box-shadow: var(--shadow-sm);
+}
+.theme-btn:hover { color: var(--text-primary); border-color: var(--border-input); }
+</style>
diff --git a/web/src/views/auth/Login.vue b/web/src/views/auth/Login.vue
index 7e594d6..a82dc84 100644
--- a/web/src/views/auth/Login.vue
+++ b/web/src/views/auth/Login.vue
@@ -1,5 +1,5 @@
<script setup lang="ts">
-import { ref, onMounted } from 'vue'
+import { ref, onMounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { authApi } from '../../api/auth'
import { oauthApi } from '../../api/oauth'
@@ -20,6 +20,7 @@ const twoFactorCode = ref('')
const loading = ref(false)
const requires2FA = ref(false)
const registrationEnabled = ref(false)
+const passwordResetEnabled = ref(false)
const oauthProviders = ref<OAuthProviderInfo[]>([])
const ssoAvailable = ref(false)
const ssoMode = ref(false)
@@ -29,18 +30,38 @@ const passwordError = ref('')
const codeError = ref('')
const showPassword = ref(false)
+const emailInput = ref<HTMLInputElement | null>(null)
+const codeInput = ref<HTMLInputElement | null>(null)
+
onMounted(async () => {
+ emailInput.value?.focus()
try {
const [regRes, oauthRes] = await Promise.all([
authApi.registrationStatus(),
oauthApi.providers(),
])
registrationEnabled.value = regRes.data.data.registration_enabled
+ passwordResetEnabled.value = regRes.data.data.password_reset_enabled
oauthProviders.value = oauthRes.data.data.providers || []
ssoAvailable.value = !!oauthRes.data.data.sso_available
} catch { /* ignore */ }
})
+
+watch(requires2FA, (on) => {
+ if (on) nextTick(() => codeInput.value?.focus())
+})
+
+watch(twoFactorCode, (val) => {
+ const digits = val.replace(/\D/g, '').slice(0, 6)
+ if (digits !== val) {
+ twoFactorCode.value = digits
+ return
+ }
+ codeError.value = ''
+ if (digits.length === 6 && !loading.value) handleLogin()
+})
+
function oauthLogin(slug: string) {
// Full page navigation to the backend OAuth authorize endpoint
window.location.href = `/api/v1/auth/oauth/${slug}/authorize`
@@ -141,24 +162,39 @@ function resetLogin() {
<p v-else-if="ssoMode" class="auth-subtitle">We'll redirect you to your identity provider.</p>
</div>
+ <!-- Error surfaced via redirect (OAuth failure, session revoked, etc.) -->
+ <div v-if="loginError" class="auth-alert" role="alert">
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
+ <span>{{ loginError.replace(/_/g, ' ') }}</span>
+ </div>
+
<form class="auth-form" @submit.prevent="ssoMode ? submitSSO() : handleLogin()">
<template v-if="!requires2FA">
<div class="form-group">
<label class="form-label" for="email">Email</label>
<input
id="email"
+ ref="emailInput"
v-model="email"
type="email"
class="form-input"
:class="{ 'form-input-error': emailError }"
placeholder="[email protected]"
autocomplete="email"
+ :disabled="loading || ssoChecking"
+ :aria-invalid="!!emailError"
+ :aria-describedby="emailError ? 'email-error' : undefined"
@input="emailError = ''"
/>
- <small v-if="emailError" class="form-error">{{ emailError }}</small>
+ <small v-if="emailError" id="email-error" class="form-error">{{ emailError }}</small>
</div>
<div v-if="!ssoMode" class="form-group">
- <label class="form-label" for="password">Password</label>
+ <div class="form-label-row">
+ <label class="form-label" for="password">Password</label>
+ <router-link v-if="passwordResetEnabled" class="forgot-link" :to="{ name: 'forgot-password' }">
+ Forgot password?
+ </router-link>
+ </div>
<div class="password-wrap">
<input
id="password"
@@ -168,6 +204,9 @@ function resetLogin() {
:class="{ 'form-input-error': passwordError }"
placeholder="Enter your password"
autocomplete="current-password"
+ :disabled="loading"
+ :aria-invalid="!!passwordError"
+ :aria-describedby="passwordError ? 'password-error' : undefined"
@input="passwordError = ''"
/>
<button
@@ -181,7 +220,7 @@ function resetLogin() {
<svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
</button>
</div>
- <small v-if="passwordError" class="form-error">{{ passwordError }}</small>
+ <small v-if="passwordError" id="password-error" class="form-error">{{ passwordError }}</small>
</div>
</template>
<template v-else>
@@ -189,6 +228,7 @@ function resetLogin() {
<label class="form-label" for="2fa-code">Authentication code</label>
<input
id="2fa-code"
+ ref="codeInput"
v-model="twoFactorCode"
type="text"
class="form-input totp-input"
@@ -197,10 +237,11 @@ function resetLogin() {
maxlength="6"
inputmode="numeric"
autocomplete="one-time-code"
- autofocus
- @input="codeError = ''"
+ :disabled="loading"
+ :aria-invalid="!!codeError"
+ :aria-describedby="codeError ? 'code-error' : undefined"
/>
- <small v-if="codeError" class="form-error">{{ codeError }}</small>
+ <small v-if="codeError" id="code-error" class="form-error">{{ codeError }}</small>
</div>
</template>
<button v-if="!ssoMode" type="submit" class="btn btn-primary auth-btn" :disabled="loading">
@@ -241,11 +282,6 @@ function resetLogin() {
</div>
</div>
- <!-- Login error from redirect (OAuth failure, session revoked, etc.) -->
- <div v-if="loginError" class="oauth-error-msg">
- {{ loginError.replace(/_/g, ' ') }}
- </div>
-
<div class="auth-footer">
<template v-if="registrationEnabled">
<span>Don't have an account?</span>
@@ -307,6 +343,17 @@ function resetLogin() {
.auth-subtitle { font-size: 14px; color: var(--text-muted); margin: 0; }
+.form-label-row {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+}
+.forgot-link {
+ font-size: 12px;
+ font-weight: 500;
+ color: var(--primary-500);
+}
+
.password-wrap { position: relative; }
.password-wrap .form-input { padding-right: 40px; }
.password-toggle {
@@ -410,10 +457,18 @@ function resetLogin() {
font-weight: 500;
}
-.oauth-error-msg {
- padding: 10px 32px 16px;
+.auth-alert {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 24px 32px 0;
+ padding: 10px 12px;
font-size: 13px;
- color: var(--danger-600);
- text-align: center;
+ color: var(--danger-700, #b91c1c);
+ background: var(--danger-50, #fef2f2);
+ border: 1px solid var(--danger-200, #fecaca);
+ border-radius: var(--radius);
+ text-transform: capitalize;
}
+.auth-alert svg { flex-shrink: 0; }
</style>
diff --git a/web/src/views/auth/ResetPassword.vue b/web/src/views/auth/ResetPassword.vue
new file mode 100644
index 0000000..1d71c4b
--- /dev/null
+++ b/web/src/views/auth/ResetPassword.vue
@@ -0,0 +1,220 @@
+<script setup lang="ts">
+import { ref, onMounted } from 'vue'
+import { useRoute, useRouter } from 'vue-router'
+import { authApi } from '../../api/auth'
+import { useNotificationStore } from '../../stores/notification'
+import { useThemeStore } from '../../stores/theme'
+
+const route = useRoute()
+const router = useRouter()
+const notify = useNotificationStore()
+const theme = useThemeStore()
+
+const token = ref((route.query.token as string) || '')
+const password = ref('')
+const confirm = ref('')
+const showPassword = ref(false)
+const loading = ref(false)
+const passwordError = ref('')
+const confirmError = ref('')
+const passwordInput = ref<HTMLInputElement | null>(null)
+
+onMounted(() => passwordInput.value?.focus())
+
+async function submit() {
+ passwordError.value = ''
+ confirmError.value = ''
+ if (password.value.length < 8) {
+ passwordError.value = 'Password must be at least 8 characters.'
+ return
+ }
+ if (confirm.value !== password.value) {
+ confirmError.value = 'Passwords do not match.'
+ return
+ }
+ loading.value = true
+ try {
+ await authApi.resetPassword(token.value, password.value)
+ notify.success('Your password has been reset. Please sign in.')
+ router.push({ name: 'login' })
+ } catch (err: any) {
+ passwordError.value = err?.response?.data?.error?.message || 'Could not reset your password. The link may have expired.'
+ } finally {
+ loading.value = false
+ }
+}
+</script>
+
+<template>
+ <div class="auth-page">
+ <div class="auth-card">
+ <div class="auth-header">
+ <div class="auth-wordmark" aria-label="Posta">Posta<span class="auth-wordmark-dot">.</span></div>
+ <h1 class="auth-title">Set a new password</h1>
+ <p class="auth-subtitle">Choose a strong password you don't use elsewhere.</p>
+ </div>
+
+ <div v-if="!token" class="auth-form">
+ <div class="auth-alert" role="alert">
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
+ <span>This reset link is missing its token. Request a new one.</span>
+ </div>
+ </div>
+
+ <form v-else class="auth-form" @submit.prevent="submit">
+ <div class="form-group">
+ <label class="form-label" for="password">New password</label>
+ <div class="password-wrap">
+ <input
+ id="password"
+ ref="passwordInput"
+ v-model="password"
+ :type="showPassword ? 'text' : 'password'"
+ class="form-input"
+ :class="{ 'form-input-error': passwordError }"
+ placeholder="At least 8 characters"
+ autocomplete="new-password"
+ :disabled="loading"
+ :aria-invalid="!!passwordError"
+ :aria-describedby="passwordError ? 'password-error' : undefined"
+ @input="passwordError = ''"
+ />
+ <button
+ type="button"
+ class="password-toggle"
+ :aria-label="showPassword ? 'Hide password' : 'Show password'"
+ @click="showPassword = !showPassword"
+ >
+ <svg v-if="showPassword" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M17.94 17.94A10.07 10.07 0 0112 20c-7 0-11-8-11-8a18.45 18.45 0 015.06-5.94M9.9 4.24A9.12 9.12 0 0112 4c7 0 11 8 11 8a18.5 18.5 0 01-2.16 3.19m-6.72-1.07a3 3 0 11-4.24-4.24"/><line x1="1" y1="1" x2="23" y2="23"/></svg>
+ <svg v-else width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"/><circle cx="12" cy="12" r="3"/></svg>
+ </button>
+ </div>
+ <small v-if="passwordError" id="password-error" class="form-error">{{ passwordError }}</small>
+ </div>
+ <div class="form-group">
+ <label class="form-label" for="confirm">Confirm password</label>
+ <input
+ id="confirm"
+ v-model="confirm"
+ :type="showPassword ? 'text' : 'password'"
+ class="form-input"
+ :class="{ 'form-input-error': confirmError }"
+ placeholder="Re-enter your password"
+ autocomplete="new-password"
+ :disabled="loading"
+ :aria-invalid="!!confirmError"
+ :aria-describedby="confirmError ? 'confirm-error' : undefined"
+ @input="confirmError = ''"
+ />
+ <small v-if="confirmError" id="confirm-error" class="form-error">{{ confirmError }}</small>
+ </div>
+ <button type="submit" class="btn btn-primary auth-btn" :disabled="loading">
+ <span v-if="loading" class="spinner"></span>
+ {{ loading ? 'Resetting...' : 'Reset password' }}
+ </button>
+ </form>
+
+ <div class="auth-footer">
+ <router-link :to="{ name: 'login' }">Back to sign in</router-link>
+ </div>
+ </div>
+
+ <button class="theme-btn" @click="theme.toggle()" :title="theme.isDark ? 'Light mode' : 'Dark mode'">
+ <svg v-if="theme.isDark" width="18" height="18" viewBox="0 0 16 16" fill="none"><circle cx="8" cy="8" r="3" stroke="currentColor" stroke-width="1.5"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M3.05 3.05l1.41 1.41M11.54 11.54l1.41 1.41M3.05 12.95l1.41-1.41M11.54 4.46l1.41-1.41" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/></svg>
+ <svg v-else width="18" height="18" viewBox="0 0 16 16" fill="none"><path d="M14 9.5A6.5 6.5 0 016.5 2 6.5 6.5 0 1014 9.5z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ </button>
+ </div>
+</template>
+
+<style scoped>
+.auth-page {
+ min-height: 100vh;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: var(--bg-secondary);
+ padding: 20px;
+ position: relative;
+}
+.auth-card {
+ width: 100%;
+ max-width: 400px;
+ background: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius-xl);
+ box-shadow: var(--shadow-lg);
+}
+.auth-header { text-align: center; padding: 36px 32px 0; }
+.auth-wordmark {
+ font-size: 32px;
+ font-weight: 800;
+ letter-spacing: -1px;
+ color: var(--text-primary);
+ margin-bottom: 24px;
+ line-height: 1;
+}
+.auth-wordmark-dot { color: var(--primary-500); margin-left: 1px; }
+.auth-title {
+ font-size: 22px;
+ font-weight: 600;
+ color: var(--text-primary);
+ letter-spacing: -0.2px;
+ margin: 0 0 8px;
+}
+.auth-subtitle { font-size: 14px; color: var(--text-muted); margin: 0; line-height: 1.5; }
+.auth-form { padding: 28px 32px 20px; }
+.auth-btn { width: 100%; padding: 11px 18px; font-size: 15px; margin-top: 4px; }
+.password-wrap { position: relative; }
+.password-wrap .form-input { padding-right: 40px; }
+.password-toggle {
+ position: absolute;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ width: 36px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ border: none;
+ color: var(--text-muted);
+ cursor: pointer;
+}
+.password-toggle:hover { color: var(--text-primary); }
+.form-input-error { border-color: var(--danger-500, #ef4444); }
+.form-error { display: block; font-size: 12px; color: var(--danger-600, #dc2626); margin-top: 6px; }
+.auth-alert {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 10px 12px;
+ font-size: 13px;
+ color: var(--danger-700, #b91c1c);
+ background: var(--danger-50, #fef2f2);
+ border: 1px solid var(--danger-200, #fecaca);
+ border-radius: var(--radius);
+}
+.auth-alert svg { flex-shrink: 0; }
+.auth-footer {
+ text-align: center;
+ padding: 0 32px 28px;
+ font-size: 14px;
+ color: var(--text-muted);
+}
+.auth-footer a { color: var(--primary-500); font-weight: 500; }
+.theme-btn {
+ position: fixed;
+ top: 20px;
+ right: 20px;
+ background: var(--bg-primary);
+ border: 1px solid var(--border-primary);
+ border-radius: var(--radius);
+ padding: 10px;
+ cursor: pointer;
+ color: var(--text-tertiary);
+ display: flex;
+ align-items: center;
+ box-shadow: var(--shadow-sm);
+}
+.theme-btn:hover { color: var(--text-primary); border-color: var(--border-input); }
+</style>