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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/web/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ node_modules
dist
dist-ssr
*.local
package-lock.json

# Editor directories and files
.vscode/*
Expand Down
14 changes: 9 additions & 5 deletions apps/web/src/hooks/use-login-form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,14 @@ import { useForm } from "@tanstack/react-form";
import { useQueryClient } from "@tanstack/react-query";
import { useNavigate } from "@tanstack/react-router";
import { useState } from "react";

import { ApiErrorCode, getApiErrorCode } from "@/lib/api-error";
import { currentUserQueryOptions, login } from "@/lib/auth-api";

const loginErrorMessages: Partial<Record<ApiErrorCode, string>> = {
[ApiErrorCode.InvalidCredentials]: "Invalid username or password.",
[ApiErrorCode.Unauthenticated]: "Session expired. Please log in again.",
};

export function useLoginForm() {
const navigate = useNavigate();
const queryClient = useQueryClient();
Expand All @@ -25,11 +30,10 @@ export function useLoginForm() {
});
await navigate({ to: "/dashboard" });
} catch (err: unknown) {
const apiErr = err as {
response?: { data?: { error?: string } };
};
const code = getApiErrorCode(err);
setServerError(
apiErr?.response?.data?.error ?? "Invalid username or password.",
(code && loginErrorMessages[code]) ??
"Something went wrong. Please try again.",
);
}
},
Expand Down
55 changes: 55 additions & 0 deletions apps/web/src/lib/api-error.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/**
* Machine-readable error codes returned by the API in error envelopes.
* Switch on these values instead of HTTP status codes or message strings,
* as messages are subject to change.
*/
export const ApiErrorCode = {
// Authentication / token errors.
InvalidCredentials: "AUTH_INVALID_CREDENTIALS",
MissingToken: "AUTH_MISSING_TOKEN",
TokenInvalid: "AUTH_TOKEN_INVALID",
Unauthenticated: "AUTH_UNAUTHENTICATED",

// User domain errors.
UserNotFound: "USER_NOT_FOUND",
UsernameTaken: "USER_USERNAME_TAKEN",
Forbidden: "FORBIDDEN",

// Generic / request errors.
BadRequest: "BAD_REQUEST",
InternalError: "INTERNAL_ERROR",
} as const;

export type ApiErrorCode = (typeof ApiErrorCode)[keyof typeof ApiErrorCode];

/** Shape of the success envelope returned by the API on success. */
export interface SuccessEnvelope<T> {
success: true;
data: T;
request_id?: string;
}

/** Shape of the error envelope returned by the API on failure. */
export interface ApiErrorEnvelope {
success: false;
error_code: ApiErrorCode;
error: string;
request_id?: string;
}

/** Discriminated union of all possible API response envelopes. */
export type ApiEnvelope<T> = SuccessEnvelope<T> | ApiErrorEnvelope;

/**
* Extracts the `error_code` from an Axios error response.
* Returns `null` when the error is not an API error envelope.
*/
export function getApiErrorCode(error: unknown): ApiErrorCode | null {
const err = error as {
response?: { data?: { error_code?: string } };
};
const code = err?.response?.data?.error_code;
if (!code) return null;
const known = Object.values(ApiErrorCode) as string[];
return known.includes(code) ? (code as ApiErrorCode) : null;
}
11 changes: 3 additions & 8 deletions apps/web/src/lib/auth-api.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { queryOptions } from "@tanstack/react-query";

import { apiClient } from "./api-client";
import type { SuccessEnvelope } from "./api-error";

/** Shape of the authenticated user returned by GET /users/me. */
export interface User {
Expand All @@ -11,13 +12,6 @@ export interface User {
created_at: string;
}

/** API envelope wrapper used by the backend presenter. */
interface Envelope<T> {
success: boolean;
data: T;
request_id?: string;
}

export async function login(username: string, password: string): Promise<void> {
await apiClient.instance.post("/auth/login", { username, password });
}
Expand All @@ -27,7 +21,8 @@ export async function logout(): Promise<void> {
}

export async function getMe(): Promise<User> {
const { data } = await apiClient.instance.get<Envelope<User>>("/users/me");
const { data } =
await apiClient.instance.get<SuccessEnvelope<User>>("/users/me");
return data.data;
}

Expand Down
46 changes: 46 additions & 0 deletions services/api/internal/apierr/codes.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Package apierr defines machine-readable error codes used in API error
// responses. Clients should switch on Code values rather than HTTP status
// codes or human-readable messages, because messages are subject to change.
package apierr

// Code is a stable, machine-readable string that identifies a specific error
// condition. Codes are grouped by domain prefix (e.g. AUTH_, USER_).
type Code string

const (
// CodeInvalidCredentials represents invalid authentication credentials.
CodeInvalidCredentials Code = "AUTH_INVALID_CREDENTIALS"
// CodeMissingToken represents a missing authentication token.
CodeMissingToken Code = "AUTH_MISSING_TOKEN"
// CodeTokenInvalid represents an invalid authentication token.
CodeTokenInvalid Code = "AUTH_TOKEN_INVALID"
// CodeUnauthenticated represents an unauthenticated request.
CodeUnauthenticated Code = "AUTH_UNAUTHENTICATED"

// CodeUserNotFound represents a user that was not found.
CodeUserNotFound Code = "USER_NOT_FOUND"
// CodeUsernameTaken represents a username that is already taken.
CodeUsernameTaken Code = "USER_USERNAME_TAKEN"
// CodeForbidden represents a forbidden action.
CodeForbidden Code = "FORBIDDEN"

// CodeBadRequest represents a bad request.
CodeBadRequest Code = "BAD_REQUEST"
// CodeInternalError represents an internal server error.
CodeInternalError Code = "INTERNAL_ERROR"
)

// Error carries a machine-readable Code alongside a human-readable Message.
// It implements the error interface so it can propagate through service layers
// and be detected by the transport presenter.
type Error struct {
Code Code
Message string
}

func (e *Error) Error() string { return e.Message }

// New returns a new *Error with the given code and message.
func New(code Code, message string) *Error {
return &Error{Code: code, Message: message}
}
19 changes: 19 additions & 0 deletions services/api/internal/domain/auth/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package auth

import "errors"

// Auth domain sentinel errors.
var (
// ErrInvalidCredentials is returned when a login attempt fails due to an
// unknown username or incorrect password. The message is intentionally
// vague to prevent username enumeration.
ErrInvalidCredentials = errors.New("invalid username or password")

// ErrTokenInvalid is returned when a token cannot be verified — it may be
// malformed, have an invalid signature, or be expired.
ErrTokenInvalid = errors.New("invalid or expired token")

// ErrSessionInvalidated is returned when the token's session family has
// been explicitly revoked (e.g. due to detected token reuse or logout).
ErrSessionInvalidated = errors.New("session has been invalidated")
)
16 changes: 8 additions & 8 deletions services/api/internal/service/auth/auth_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ func (s *Service) Login(ctx context.Context, username, password string) (*domain
u, err := s.users.FindByUsername(ctx, username)
if err != nil {
if errors.Is(err, userdom.ErrNotFound) {
return nil, fmt.Errorf("auth: invalid credentials")
return nil, domainauth.ErrInvalidCredentials
}
return nil, err
}

if err := bcrypt.CompareHashAndPassword([]byte(u.PasswordHash), []byte(password)); err != nil {
return nil, fmt.Errorf("auth: invalid credentials")
return nil, domainauth.ErrInvalidCredentials
}

familyID := uuid.NewString()
Expand All @@ -83,11 +83,11 @@ func (s *Service) Login(ctx context.Context, username, password string) (*domain
func (s *Service) Refresh(ctx context.Context, refreshToken string) (*domainauth.TokenPair, error) {
claims, err := s.tokens.Verify(refreshToken)
if err != nil {
return nil, fmt.Errorf("auth: invalid refresh token: %w", err)
return nil, domainauth.ErrTokenInvalid
}

if claims.Kind != "refresh" {
return nil, fmt.Errorf("auth: expected refresh token")
return nil, domainauth.ErrTokenInvalid
}

// Fast path: reject immediately if the family was already invalidated.
Expand All @@ -96,7 +96,7 @@ func (s *Service) Refresh(ctx context.Context, refreshToken string) (*domainauth
return nil, err
}
if revoked {
return nil, fmt.Errorf("auth: session has been invalidated")
return nil, domainauth.ErrSessionInvalidated
}

// Record use — detect reuse.
Expand All @@ -110,13 +110,13 @@ func (s *Service) Refresh(ctx context.Context, refreshToken string) (*domainauth
if time.Since(*firstUsedAt) <= gracePeriod {
// Within the grace period: likely a network retry — reject without
// breaking the session so the original response can be retried.
return nil, fmt.Errorf("auth: token recently used, please retry with the latest token")
return nil, domainauth.ErrTokenInvalid
}
// Outside the grace period: potential token theft — revoke the family.
if err := s.refreshStore.RevokeFamily(ctx, claims.FamilyID, s.refreshTTL); err != nil {
return nil, fmt.Errorf("auth: token reuse detected, failed to revoke session family: %w", err)
return nil, fmt.Errorf("auth: revoke session family: %w", err)
}
return nil, fmt.Errorf("auth: token reuse detected, session invalidated")
return nil, domainauth.ErrSessionInvalidated
}

// Issue a rotated token pair preserving the same session family.
Expand Down
24 changes: 12 additions & 12 deletions services/api/internal/service/auth/auth_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,8 +108,8 @@ func TestLogin_Success(t *testing.T) {
func TestLogin_UserNotFound(t *testing.T) {
svc := newAuthSvc(&stubUserRepo{}, &stubRefreshStore{})
_, err := svc.Login(context.Background(), "ghost", "pass1234")
if err == nil {
t.Fatal("expected error, got nil")
if !errors.Is(err, domainauth.ErrInvalidCredentials) {
t.Fatalf("expected ErrInvalidCredentials, got %v", err)
}
}

Expand All @@ -125,8 +125,8 @@ func TestLogin_WrongPassword(t *testing.T) {
}, &stubRefreshStore{})

_, err := svc.Login(context.Background(), "alice", "wrongpass")
if err == nil {
t.Fatal("expected error for wrong password, got nil")
if !errors.Is(err, domainauth.ErrInvalidCredentials) {
t.Fatalf("expected ErrInvalidCredentials, got %v", err)
}
}

Expand Down Expand Up @@ -171,8 +171,8 @@ func TestRefresh_WrongKind(t *testing.T) {
// Pass an access token where a refresh token is expected.
access, _ := tm.IssueAccess("sub", "alice", userdom.RoleUser, "fam1")
_, err := svc.Refresh(context.Background(), access)
if err == nil {
t.Fatal("expected error for access token used as refresh, got nil")
if !errors.Is(err, domainauth.ErrTokenInvalid) {
t.Fatalf("expected ErrTokenInvalid, got %v", err)
}
}

Expand All @@ -185,8 +185,8 @@ func TestRefresh_FamilyRevoked(t *testing.T) {

refresh, _ := tm.IssueRefresh("sub", "alice", userdom.RoleUser, "fam1")
_, err := svc.Refresh(context.Background(), refresh)
if err == nil {
t.Fatal("expected error for revoked family, got nil")
if !errors.Is(err, domainauth.ErrSessionInvalidated) {
t.Fatalf("expected ErrSessionInvalidated, got %v", err)
}
}

Expand All @@ -209,8 +209,8 @@ func TestRefresh_ReuseWithinGrace_RejectsWithoutRevokingFamily(t *testing.T) {

refresh, _ := tm.IssueRefresh("sub", "alice", userdom.RoleUser, "fam1")
_, err := svc.Refresh(context.Background(), refresh)
if err == nil {
t.Fatal("expected error for reused token within grace period")
if !errors.Is(err, domainauth.ErrTokenInvalid) {
t.Fatalf("expected ErrTokenInvalid, got %v", err)
}
if familyRevoked {
t.Fatal("family must NOT be revoked within the grace period")
Expand All @@ -236,8 +236,8 @@ func TestRefresh_ReuseOutsideGrace_RevokesFamily(t *testing.T) {

refresh, _ := tm.IssueRefresh("sub", "alice", userdom.RoleUser, "fam1")
_, err := svc.Refresh(context.Background(), refresh)
if err == nil {
t.Fatal("expected error for reused token outside grace period")
if !errors.Is(err, domainauth.ErrSessionInvalidated) {
t.Fatalf("expected ErrSessionInvalidated, got %v", err)
}
if !familyRevoked {
t.Fatal("family must be revoked when reuse is detected outside grace period")
Expand Down
9 changes: 5 additions & 4 deletions services/api/internal/transport/http/handler/auth_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"time"

"github.com/gin-gonic/gin"
"github.com/paca/api/internal/apierr"
domainauth "github.com/paca/api/internal/domain/auth"
"github.com/paca/api/internal/transport/http/dto"
"github.com/paca/api/internal/transport/http/middleware"
Expand Down Expand Up @@ -48,7 +49,7 @@ func (h *AuthHandler) Login(c *gin.Context) {

pair, err := h.svc.Login(c.Request.Context(), req.Username, req.Password)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
presenter.Error(c, err)
return
}

Expand All @@ -62,13 +63,13 @@ func (h *AuthHandler) Login(c *gin.Context) {
func (h *AuthHandler) Refresh(c *gin.Context) {
refreshToken, err := c.Cookie(refreshCookieName)
if err != nil || refreshToken == "" {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing refresh token"})
presenter.Error(c, apierr.New(apierr.CodeMissingToken, "missing refresh token"))
return
}

pair, err := h.svc.Refresh(c.Request.Context(), refreshToken)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
presenter.Error(c, err)
return
}

Expand All @@ -81,7 +82,7 @@ func (h *AuthHandler) Refresh(c *gin.Context) {
func (h *AuthHandler) Logout(c *gin.Context) {
claims := middleware.ClaimsFrom(c)
if claims == nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "unauthenticated"})
presenter.Error(c, apierr.New(apierr.CodeUnauthenticated, "unauthenticated"))
return
}

Expand Down
Loading
Loading