diff --git a/.drone.yml b/.drone.yml new file mode 100644 index 0000000..2d0858c --- /dev/null +++ b/.drone.yml @@ -0,0 +1,89 @@ +kind: pipeline +type: docker +name: default + +steps: + - name: test backend + image: golang:1.25-alpine3.21 + commands: + - cd kotosoft-id-backend + - go mod tidy + - go test ./... + + - name: lint frontend + image: node:20-alpine + commands: + - cd kotosoft-id-frontend + - npm ci + - npm run lint + + - name: build and push backend + image: docker:24 + volumes: + - name: dockersock + path: /var/run/docker.sock + commands: + - docker build + -t localhost:5000/kotosoft_id_backend:latest + -f kotosoft-id-backend/Dockerfile + kotosoft-id-backend + - docker push localhost:5000/kotosoft_id_backend:latest + + - name: build and push frontend + image: docker:24 + volumes: + - name: dockersock + path: /var/run/docker.sock + commands: + - docker build + -t localhost:5000/kotosoft_id_frontend:latest + -f kotosoft-id-frontend/Dockerfile + kotosoft-id-frontend + - docker push localhost:5000/kotosoft_id_frontend:latest + + - name: deploy + image: docker:24 + volumes: + - name: dockersock + path: /var/run/docker.sock + - name: appdir + path: /opt/app + environment: + FRONTEND_URL: + from_secret: FRONTEND_URL + POSTGRES_URL: + from_secret: POSTGRES_URL + REDIS_URL: + from_secret: REDIS_URL + JWT_SECRET: + from_secret: JWT_SECRET + CLIENT_ID: + from_secret: CLIENT_ID + CLIENT_SECRET: + from_secret: CLIENT_SECRET + CLIENT_NAME: + from_secret: CLIENT_NAME + CLIENT_REDIRECT_URIS: + from_secret: CLIENT_REDIRECT_URIS + DOMAIN: + from_secret: DOMAIN + LETSENCRYPT_EMAIL: + from_secret: LETSENCRYPT_EMAIL + commands: + - apk add --no-cache docker-cli-compose + - cp docker-compose.yml /opt/app/docker-compose.yml + - cd /opt/app + - docker compose pull + - docker compose up -d --remove-orphans + +volumes: + - name: dockersock + host: + path: /var/run/docker.sock + - name: appdir + host: + path: /opt/drone/kotosoft-id + +trigger: + branch: + - main \ No newline at end of file diff --git a/.gitignore b/.gitignore index 67d4849..af66f58 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ kotosoft-id-frontend/node_modules -kotosoft-id-frontend/.next/ +kotosoft-id-frontend/.next +kotosoft-id-frontend/output kotosoft-id-frontend/.env kotosoft-id-frontend/next-env.d.ts diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..fb5927d --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,52 @@ +services: + kotosoft_id_backend: + image: host.docker.internal:5000/kotosoft_id_backend:latest + restart: unless-stopped + environment: + SERVER_ADDR: ":8080" + FRONTEND_URL: ${FRONTEND_URL} + POSTGRES_URL: ${POSTGRES_URL} + POSTGRES_MIGRATION_FILE_PATH: ./migrations/migrations.sql + REDIS_URL: ${REDIS_URL} + JWT_SECRET: ${JWT_SECRET} + JWT_EXPIRATION_HOURS: ${JWT_EXPIRATION_HOURS:-24h} + + CLIENT_ID: ${CLIENT_ID} + CLIENT_SECRET: ${CLIENT_SECRET} + CLIENT_NAME: ${CLIENT_NAME} + CLIENT_REDIRECT_URIS: ${CLIENT_REDIRECT_URIS} + expose: + - "8080" + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + networks: + - kotosoft_id_network + + kotosoft_id_frontend: + image: host.docker.internal:5000/kotosoft_id_frontend:latest + restart: unless-stopped + environment: + PUBLIC_URL: ${FRONTEND_URL} + KOTOSOFT_ID_API_URL: http://kotosoft_id_backend:8080 + CLIENT_ID: ${CLIENT_ID} + CLIENT_SECRET: ${CLIENT_SECRET} + VIRTUAL_HOST: ${DOMAIN} + VIRTUAL_PORT: 3000 + LETSENCRYPT_HOST: ${DOMAIN} + LETSENCRYPT_EMAIL: ${LETSENCRYPT_EMAIL} + expose: + - "3000" + depends_on: + - kotosoft_id_backend + networks: + - kotosoft_id_network + - proxy + +networks: + kotosoft_id_net: + driver: bridge + proxy: + external: true \ No newline at end of file diff --git a/kotosoft-id-backend/cmd/main.go b/kotosoft-id-backend/cmd/main.go index 875a15e..0213573 100644 --- a/kotosoft-id-backend/cmd/main.go +++ b/kotosoft-id-backend/cmd/main.go @@ -8,7 +8,7 @@ import ( "github.com/dusiburg/kotosoft-id/internal/config" "github.com/dusiburg/kotosoft-id/internal/db" "github.com/dusiburg/kotosoft-id/internal/handlers" - apphttp "github.com/dusiburg/kotosoft-id/internal/http" + http "github.com/dusiburg/kotosoft-id/internal/http" "github.com/dusiburg/kotosoft-id/internal/models" "github.com/dusiburg/kotosoft-id/internal/repositories" "github.com/dusiburg/kotosoft-id/internal/services" @@ -17,64 +17,70 @@ import ( func main() { cfg, err := config.New() if err != nil { - log.Fatal(err) + log.Fatalf("config: %v", err) } - pg, err := db.ConnectPostgres(cfg.Postgres.URL) + postgres, err := db.ConnectPostgres(cfg.Postgres.URL) if err != nil { - log.Fatal(err) + log.Fatalf("postgres: %v", err) + } + if err := db.RunMigrations(cfg.Postgres.MigrationFilePath, postgres.Pool); err != nil { + log.Fatalf("migrations: %v", err) } - if err := db.RunMigrations(cfg.Postgres.MigrationFilePath, pg.Pool); err != nil { - log.Fatal(err) - } - - rdb, err := db.ConnectRedis(cfg.Redis.URL) + redis, err := db.ConnectRedis(cfg.Redis.URL) if err != nil { - log.Fatal(err) + log.Fatalf("redis: %v", err) } - userRepo := repositories.NewUserRepository(pg.Pool) - oauthRepo := repositories.NewOAuthRepository(pg.Pool) + userRepo := repositories.NewUserRepository(postgres.Pool) + oauthRepo := repositories.NewOAuthRepository(postgres.Pool) - ctx := context.Background() - - basicClient, err := ensureBasicClient(ctx, cfg, oauthRepo) - if err != nil { - log.Fatal(err) + if err := seedClient(context.Background(), oauthRepo, cfg.Client); err != nil { + log.Fatalf("seed client: %v", err) } - svc := services.New(userRepo, oauthRepo, rdb.Client, services.TokenConfig{ - AccessTTL: cfg.JWT.TTL, - RefreshTTL: cfg.JWT.TTL * 7, - }, basicClient) + svc := services.New( + userRepo, + oauthRepo, + redis.Client, + services.TokenConfig{ + AccessTTL: cfg.JWT.TTL, + RefreshTTL: cfg.JWT.TTL * 7, + }, + ) + + limiter := services.NewRateLimiter(redis.Client) authHandler := handlers.NewAuthHandler(svc) oauthHandler := handlers.NewOAuthHandler(svc, cfg.Server.FrontendURL) consentHandler := handlers.NewConsentHandler(svc) - r := apphttp.NewRouter(authHandler, oauthHandler, consentHandler, svc, oauthRepo) - log.Fatal(r.Run(cfg.Server.Addr)) + router := http.NewRouter(authHandler, oauthHandler, consentHandler, svc, oauthRepo, limiter) + + log.Printf("starting server on %s", cfg.Server.Addr) + if err := router.Run(cfg.Server.Addr); err != nil { + log.Fatalf("server: %v", err) + } } -func ensureBasicClient(ctx context.Context, cfg *config.Conf, repo *repositories.OAuthRepository) (*models.OAuthClient, error) { - client, err := repo.GetOAuthClientByClientID(ctx, cfg.Client.ID) - if err == nil { - return client, nil - } - - hashedSecret, err := services.HashClientSecret(cfg.Client.Secret) +func seedClient(ctx context.Context, repo *repositories.OAuthRepository, cfg config.Client) error { + hashedSecret, err := services.HashClientSecret(cfg.Secret) if err != nil { - return nil, err + return err } - return repo.CreateOAuthClient(ctx, models.OAuthClient{ - ClientID: cfg.Client.ID, + redirectURIsJSON, _ := json.Marshal(cfg.RedirectURIs) + grantTypesJSON, _ := json.Marshal(cfg.GrantTypes) + scopesJSON, _ := json.Marshal(cfg.Scopes) + + return repo.UpsertClient(ctx, models.OAuthClient{ + ClientID: cfg.ID, ClientSecret: hashedSecret, - Name: cfg.Client.Name, - RedirectURIs: json.RawMessage(cfg.Client.RedirectURIsJSON()), - GrantTypes: json.RawMessage(cfg.Client.GrantTypesJSON()), - Scopes: json.RawMessage(cfg.Client.ScopesJSON()), + Name: cfg.Name, + RedirectURIs: redirectURIsJSON, + GrantTypes: grantTypesJSON, + Scopes: scopesJSON, Trusted: true, }) } diff --git a/kotosoft-id-backend/dockerfile b/kotosoft-id-backend/dockerfile new file mode 100644 index 0000000..224f66f --- /dev/null +++ b/kotosoft-id-backend/dockerfile @@ -0,0 +1,30 @@ +FROM golang:1.23-alpine AS builder + +WORKDIR /app + +COPY go.mod go.sum ./ +RUN go mod download + +COPY . . + +RUN CGO_ENABLED=0 GOOS=linux go build \ + -trimpath \ + -ldflags="-s -w" \ + -o /app/server \ + ./cmd/server + +FROM alpine:3.20 + +RUN apk add --no-cache ca-certificates tzdata + +WORKDIR /app + +COPY --from=builder /app/server . +COPY --from=builder /app/migrations ./migrations + +RUN addgroup -S app && adduser -S app -G app +USER app + +EXPOSE 8080 + +CMD ["./server"] \ No newline at end of file diff --git a/kotosoft-id-backend/internal/handlers/auth.go b/kotosoft-id-backend/internal/handlers/auth.go index fa1c202..f10463c 100644 --- a/kotosoft-id-backend/internal/handlers/auth.go +++ b/kotosoft-id-backend/internal/handlers/auth.go @@ -30,13 +30,15 @@ func (h *AuthHandler) Register(c *gin.Context) { return } - service, err := h.svc.AuthenticateClient(c.Request.Context(), services.ClientAuth{ClientID: id, ClientSecret: secret}) + client, err := h.svc.AuthenticateClient(c.Request.Context(), services.ClientAuth{ + ClientID: id, + ClientSecret: secret, + }) if err != nil { c.Error(models.ErrUnauthorized) return } - - if !service.Trusted { + if !client.Trusted { c.Error(models.ErrForbidden) return } @@ -59,12 +61,23 @@ func (h *AuthHandler) Refresh(c *gin.Context) { return } - pair, err := h.svc.RefreshTokens(c.Request.Context(), input.RefreshToken) - if err != nil { - c.Error(err) + id, secret, ok := c.Request.BasicAuth() + if !ok { + c.Error(models.ErrUnauthorized) return } + pair, err := h.svc.ExchangeRefreshToken( + c.Request.Context(), + services.ClientAuth{ClientID: id, ClientSecret: secret}, + input.RefreshToken, + ) + if err != nil { + c.Error(models.ErrUnauthorized) + return + } + + pair.User = nil c.JSON(http.StatusOK, pair) } diff --git a/kotosoft-id-backend/internal/http/router.go b/kotosoft-id-backend/internal/http/router.go index 6395fe0..842f2d1 100644 --- a/kotosoft-id-backend/internal/http/router.go +++ b/kotosoft-id-backend/internal/http/router.go @@ -4,6 +4,7 @@ import ( "strings" "github.com/dusiburg/kotosoft-id/internal/handlers" + "github.com/dusiburg/kotosoft-id/internal/middleware" "github.com/dusiburg/kotosoft-id/internal/models" "github.com/dusiburg/kotosoft-id/internal/repositories" "github.com/dusiburg/kotosoft-id/internal/services" @@ -11,7 +12,7 @@ import ( "github.com/google/uuid" ) -func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consents *handlers.ConsentHandler, svc *services.Service, repo *repositories.OAuthRepository) *gin.Engine { +func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consents *handlers.ConsentHandler, svc *services.Service, repo *repositories.OAuthRepository, limiter *services.RateLimiter) *gin.Engine { r := gin.Default() r.Use(errorMiddleware()) @@ -19,7 +20,7 @@ func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consent { o.GET("/authorize", oauth.Authorize) o.GET("/session/:token", oauth.GetSession) - o.POST("/session/login", oauth.SessionLogin) + o.POST("/session/login", middleware.RateLimit(limiter, services.LoginRateLimit, middleware.LoginKeyFn), oauth.SessionLogin) o.POST("/session/attach", oauth.SessionAttach) o.POST("/session/approve", oauth.SessionApprove) o.POST("/token", oauth.Token) @@ -29,7 +30,7 @@ func NewRouter(auth *handlers.AuthHandler, oauth *handlers.OAuthHandler, consent api := r.Group("/api/v1") { a := api.Group("/auth") - a.POST("/register", auth.Register) + a.POST("/register", middleware.RateLimit(limiter, services.RegisterRateLimit, middleware.IPKeyFn("register")), auth.Register) a.POST("/refresh", auth.Refresh) me := api.Group("/me") @@ -65,7 +66,7 @@ func authMiddleware(svc *services.Service, repo *repositories.OAuthRepository, r return } - if err, _ := repo.GetOAuthClientByID(c.Request.Context(), info.ClientID); err != nil { + if _, err := repo.GetOAuthClientByID(c.Request.Context(), info.ClientID); err != nil { c.Error(models.ErrForbidden) c.Abort() return @@ -93,16 +94,6 @@ func errorMiddleware() gin.HandlerFunc { } } -func clientAuthFromRequest(c *gin.Context) services.ClientAuth { - if id, secret, ok := c.Request.BasicAuth(); ok { - return services.ClientAuth{ClientID: id, ClientSecret: secret} - } - return services.ClientAuth{ - ClientID: c.PostForm("client_id"), - ClientSecret: c.PostForm("client_secret"), - } -} - func bearerToken(c *gin.Context) (string, bool) { return strings.CutPrefix(c.GetHeader("Authorization"), "Bearer ") } diff --git a/kotosoft-id-backend/internal/middleware/ratelimiter.go b/kotosoft-id-backend/internal/middleware/ratelimiter.go new file mode 100644 index 0000000..451d4d0 --- /dev/null +++ b/kotosoft-id-backend/internal/middleware/ratelimiter.go @@ -0,0 +1,67 @@ +package middleware + +import ( + "net/http" + + "github.com/dusiburg/kotosoft-id/internal/models" + "github.com/dusiburg/kotosoft-id/internal/services" + "github.com/gin-gonic/gin" +) + +func RateLimit( + limiter *services.RateLimiter, + cfg services.RateLimitConfig, + keyFn func(c *gin.Context) string, +) gin.HandlerFunc { + return func(c *gin.Context) { + key := keyFn(c) + + allowed, remaining, _ := limiter.Allow(c.Request.Context(), key, cfg) + + c.Header("X-RateLimit-Limit", itoa(cfg.Max)) + c.Header("X-RateLimit-Remaining", itoa(remaining)) + + if !allowed { + c.JSON(http.StatusTooManyRequests, models.ErrTooManyRequests) + c.Abort() + return + } + + c.Next() + } +} + +func LoginKeyFn(c *gin.Context) string { + var body struct { + Email string `json:"email"` + } + + _ = c.ShouldBindBodyWithJSON(&body) + if body.Email != "" { + return "login:" + c.ClientIP() + ":" + body.Email + } + return "login:" + c.ClientIP() +} + +func IPKeyFn(prefix string) func(c *gin.Context) string { + return func(c *gin.Context) string { + return prefix + ":" + c.ClientIP() + } +} + +func itoa(n int) string { + if n < 0 { + return "0" + } + + buf := make([]byte, 0, 10) + if n == 0 { + return "0" + } + + for n > 0 { + buf = append([]byte{byte('0' + n%10)}, buf...) + n /= 10 + } + return string(buf) +} diff --git a/kotosoft-id-backend/internal/models/error.go b/kotosoft-id-backend/internal/models/error.go index 320c3cc..d8d620b 100644 --- a/kotosoft-id-backend/internal/models/error.go +++ b/kotosoft-id-backend/internal/models/error.go @@ -14,6 +14,7 @@ var ( ErrInsufficientScope = &APIError{Code: 403, Slug: "insufficient_scope", Message: "The access token does not contain the required scope"} ErrNotFound = &APIError{Code: 404, Slug: "not_found", Message: "Resource not found"} ErrAlreadyExists = &APIError{Code: 409, Slug: "already_exists", Message: "Resource already exists"} + ErrTooManyRequests = &APIError{Code: 429, Slug: "too_many_requests", Message: "Too many requests"} ErrInternal = &APIError{Code: 500, Slug: "internal", Message: "Internal server error"} ) diff --git a/kotosoft-id-backend/internal/repositories/oauth.go b/kotosoft-id-backend/internal/repositories/oauth.go index cc628d1..206d68d 100644 --- a/kotosoft-id-backend/internal/repositories/oauth.go +++ b/kotosoft-id-backend/internal/repositories/oauth.go @@ -20,12 +20,11 @@ func NewOAuthRepository(db *pgxpool.Pool) *OAuthRepository { func (r *OAuthRepository) CreateOAuthClient(ctx context.Context, client models.OAuthClient) (*models.OAuthClient, error) { err := r.db.QueryRow(ctx, ` - INSERT INTO oauth_clients (client_id, client_secret, name, redirect_uris, grant_types, scopes, trusted) - VALUES ($1, $2, $3, $4, $5, $6, $7) - RETURNING id, is_active, created_at, updated_at - `, client.ClientID, client.ClientSecret, client.Name, client.RedirectURIs, client.GrantTypes, client.Scopes, client.Trusted). + INSERT INTO oauth_clients (client_id, client_secret, name, redirect_uris, grant_types, scopes, trusted) + VALUES ($1, $2, $3, $4, $5, $6, $7) + RETURNING id, is_active, created_at, updated_at + `, client.ClientID, client.ClientSecret, client.Name, client.RedirectURIs, client.GrantTypes, client.Scopes, client.Trusted). Scan(&client.ID, &client.IsActive, &client.CreatedAt, &client.UpdatedAt) - if err != nil { return nil, fmt.Errorf("failed to create OAuth client: %w", err) } @@ -37,7 +36,11 @@ func (r *OAuthRepository) GetOAuthClientByClientID(ctx context.Context, clientID err := r.db.QueryRow(ctx, ` SELECT id, client_id, client_secret, name, redirect_uris, grant_types, scopes, is_active, trusted, created_at, updated_at FROM oauth_clients WHERE client_id = $1 AND is_active = true - `, clientID).Scan(&client.ID, &client.ClientID, &client.ClientSecret, &client.Name, &client.RedirectURIs, &client.GrantTypes, &client.Scopes, &client.IsActive, &client.Trusted, &client.CreatedAt, &client.UpdatedAt) + `, clientID).Scan( + &client.ID, &client.ClientID, &client.ClientSecret, &client.Name, + &client.RedirectURIs, &client.GrantTypes, &client.Scopes, + &client.IsActive, &client.Trusted, &client.CreatedAt, &client.UpdatedAt, + ) if err != nil { return nil, err } @@ -49,7 +52,11 @@ func (r *OAuthRepository) GetOAuthClientByID(ctx context.Context, id uuid.UUID) err := r.db.QueryRow(ctx, ` SELECT id, client_id, client_secret, name, redirect_uris, grant_types, scopes, is_active, trusted, created_at, updated_at FROM oauth_clients WHERE id = $1 AND is_active = true - `, id).Scan(&client.ID, &client.ClientID, &client.ClientSecret, &client.Name, &client.RedirectURIs, &client.GrantTypes, &client.Scopes, &client.IsActive, &client.Trusted, &client.CreatedAt, &client.UpdatedAt) + `, id).Scan( + &client.ID, &client.ClientID, &client.ClientSecret, &client.Name, + &client.RedirectURIs, &client.GrantTypes, &client.Scopes, + &client.IsActive, &client.Trusted, &client.CreatedAt, &client.UpdatedAt, + ) if err != nil { return nil, err } @@ -61,8 +68,11 @@ func (r *OAuthRepository) CreateAuthorizationCode(ctx context.Context, row model INSERT INTO authorization_codes (code_hash, user_id, client_id, redirect_uri, scopes, code_challenge, code_challenge_method, expires_at, consumed_at, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10) RETURNING id, code_hash, user_id, client_id, redirect_uri, scopes, code_challenge, code_challenge_method, expires_at, consumed_at, created_at - `, row.CodeHash, row.UserID, row.ClientID, row.RedirectURI, row.Scopes, row.CodeChallenge, row.CodeChallengeMethod, row.ExpiresAt, row.ConsumedAt, row.CreatedAt). - Scan(&row.ID, &row.CodeHash, &row.UserID, &row.ClientID, &row.RedirectURI, &row.Scopes, &row.CodeChallenge, &row.CodeChallengeMethod, &row.ExpiresAt, &row.ConsumedAt, &row.CreatedAt) + `, row.CodeHash, row.UserID, row.ClientID, row.RedirectURI, row.Scopes, + row.CodeChallenge, row.CodeChallengeMethod, row.ExpiresAt, row.ConsumedAt, row.CreatedAt). + Scan(&row.ID, &row.CodeHash, &row.UserID, &row.ClientID, &row.RedirectURI, + &row.Scopes, &row.CodeChallenge, &row.CodeChallengeMethod, + &row.ExpiresAt, &row.ConsumedAt, &row.CreatedAt) if err != nil { return nil, fmt.Errorf("create authorization code: %w", err) } @@ -74,7 +84,11 @@ func (r *OAuthRepository) GetAuthorizationCodeByHash(ctx context.Context, codeHa err := r.db.QueryRow(ctx, ` SELECT id, code_hash, user_id, client_id, redirect_uri, scopes, code_challenge, code_challenge_method, expires_at, consumed_at, created_at FROM authorization_codes WHERE code_hash = $1 - `, codeHash).Scan(&row.ID, &row.CodeHash, &row.UserID, &row.ClientID, &row.RedirectURI, &row.Scopes, &row.CodeChallenge, &row.CodeChallengeMethod, &row.ExpiresAt, &row.ConsumedAt, &row.CreatedAt) + `, codeHash).Scan( + &row.ID, &row.CodeHash, &row.UserID, &row.ClientID, &row.RedirectURI, + &row.Scopes, &row.CodeChallenge, &row.CodeChallengeMethod, + &row.ExpiresAt, &row.ConsumedAt, &row.CreatedAt, + ) if err != nil { return nil, err } @@ -107,7 +121,10 @@ func (r *OAuthRepository) GetRefreshTokenByHash(ctx context.Context, tokenHash s err := r.db.QueryRow(ctx, ` SELECT id, token_hash, user_id, client_id, scopes, expires_at, created_at FROM refresh_tokens WHERE token_hash = $1 - `, tokenHash).Scan(&row.ID, &row.TokenHash, &row.UserID, &row.ClientID, &row.Scopes, &row.ExpiresAt, &row.CreatedAt) + `, tokenHash).Scan( + &row.ID, &row.TokenHash, &row.UserID, &row.ClientID, + &row.Scopes, &row.ExpiresAt, &row.CreatedAt, + ) if err != nil { return nil, err } @@ -119,32 +136,27 @@ func (r *OAuthRepository) DeleteRefreshTokenByID(ctx context.Context, id uuid.UU return err } +func (r *OAuthRepository) DeleteRefreshTokensByUserID(ctx context.Context, userID uuid.UUID) error { + _, err := r.db.Exec(ctx, `DELETE FROM refresh_tokens WHERE user_id = $1`, userID) + return err +} + func (r *OAuthRepository) RecordUserConsent( ctx context.Context, userID, clientID uuid.UUID, scopes []string, ) error { - scopeJSON, err := json.Marshal(scopes) if err != nil { return err } _, err = r.db.Exec(ctx, ` - INSERT INTO user_consents ( - user_id, - client_id, - scopes, - authorized_at, - last_used_at, - revoked_at - ) + INSERT INTO user_consents (user_id, client_id, scopes, authorized_at, last_used_at, revoked_at) VALUES ($1, $2, $3, now(), now(), NULL) ON CONFLICT (user_id, client_id) WHERE revoked_at IS NULL - DO UPDATE SET - scopes = EXCLUDED.scopes, - last_used_at = now() + DO UPDATE SET scopes = EXCLUDED.scopes, last_used_at = now() `, userID, clientID, scopeJSON) return err @@ -154,14 +166,13 @@ func (r *OAuthRepository) GetUserConsents( ctx context.Context, userID uuid.UUID, ) ([]models.UserConsent, error) { - rows, err := r.db.Query(ctx, ` - SELECT + SELECT uc.id, uc.user_id, uc.client_id, oc.client_id AS client_identifier, - oc.name AS client_name, + oc.name AS client_name, uc.scopes, uc.authorized_at, uc.last_used_at, @@ -173,52 +184,18 @@ func (r *OAuthRepository) GetUserConsents( AND (uc.expires_at IS NULL OR uc.expires_at > now()) ORDER BY uc.authorized_at DESC `, userID) - if err != nil { return nil, err } defer rows.Close() - var consents []models.UserConsent - - for rows.Next() { - var c models.UserConsent - var scopeJSON []byte - - err := rows.Scan( - &c.ID, - &c.UserID, - &c.ClientID, - &c.ClientIdentifier, - &c.ClientName, - &scopeJSON, - &c.AuthorizedAt, - &c.LastUsedAt, - &c.RevokedAt, - ) - if err != nil { - return nil, err - } - - if err := json.Unmarshal(scopeJSON, &c.Scopes); err != nil { - return nil, err - } - - consents = append(consents, c) - } - - if err := rows.Err(); err != nil { - return nil, err - } - - return consents, nil + return scanConsents(rows) } func (r *OAuthRepository) UpdateConsentLastUsed( ctx context.Context, userID, clientID uuid.UUID, ) error { - _, err := r.db.Exec(ctx, ` UPDATE user_consents SET last_used_at = now() @@ -227,12 +204,7 @@ func (r *OAuthRepository) UpdateConsentLastUsed( AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > now()) `, userID, clientID) - - if err != nil { - return err - } - - return nil + return err } func (r *OAuthRepository) GetUserConsentsByClientID( @@ -240,49 +212,96 @@ func (r *OAuthRepository) GetUserConsentsByClientID( userID uuid.UUID, clientID uuid.UUID, ) ([]models.UserConsent, error) { - rows, err := r.db.Query(ctx, ` - SELECT + SELECT uc.id, uc.user_id, uc.client_id, oc.client_id AS client_identifier, - oc.name AS client_name, + oc.name AS client_name, uc.scopes, uc.authorized_at, + uc.last_used_at, uc.revoked_at FROM user_consents uc JOIN oauth_clients oc ON uc.client_id = oc.id WHERE uc.user_id = $1 + AND uc.client_id = $2 AND uc.revoked_at IS NULL AND (uc.expires_at IS NULL OR uc.expires_at > now()) - AND uo.id = $2 ORDER BY uc.authorized_at DESC `, userID, clientID) - if err != nil { return nil, err } defer rows.Close() + return scanConsents(rows) +} + +func (r *OAuthRepository) RevokeConsent( + ctx context.Context, + userID, clientID uuid.UUID, + revokedBy *uuid.UUID, +) error { + tx, err := r.db.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + + _, err = tx.Exec(ctx, ` + UPDATE user_consents + SET revoked_at = now(), revoked_by = $3 + WHERE user_id = $1 AND client_id = $2 AND revoked_at IS NULL + `, userID, clientID, revokedBy) + if err != nil { + return err + } + + _, err = tx.Exec(ctx, ` + DELETE FROM refresh_tokens WHERE user_id = $1 AND client_id = $2 + `, userID, clientID) + if err != nil { + return err + } + + return tx.Commit(ctx) +} + +func (r *OAuthRepository) UpsertClient(ctx context.Context, client models.OAuthClient) error { + _, err := r.db.Exec(ctx, ` + INSERT INTO oauth_clients (client_id, client_secret, name, redirect_uris, grant_types, scopes, trusted) + VALUES ($1, $2, $3, $4, $5, $6, $7) + ON CONFLICT (client_id) DO UPDATE SET + client_secret = EXCLUDED.client_secret, + name = EXCLUDED.name, + redirect_uris = EXCLUDED.redirect_uris, + grant_types = EXCLUDED.grant_types, + scopes = EXCLUDED.scopes, + updated_at = now() + `, client.ClientID, client.ClientSecret, client.Name, + client.RedirectURIs, client.GrantTypes, client.Scopes, client.Trusted) + return err +} + +func scanConsents(rows interface { + Next() bool + Scan(...any) error + Err() error +}) ([]models.UserConsent, error) { var consents []models.UserConsent for rows.Next() { var c models.UserConsent var scopeJSON []byte - err := rows.Scan( - &c.ID, - &c.UserID, - &c.ClientID, - &c.ClientIdentifier, - &c.ClientName, + if err := rows.Scan( + &c.ID, &c.UserID, &c.ClientID, + &c.ClientIdentifier, &c.ClientName, &scopeJSON, - &c.AuthorizedAt, - &c.LastUsedAt, - &c.RevokedAt, - ) - if err != nil { + &c.AuthorizedAt, &c.LastUsedAt, &c.RevokedAt, + ); err != nil { return nil, err } @@ -299,41 +318,3 @@ func (r *OAuthRepository) GetUserConsentsByClientID( return consents, nil } - -func (r *OAuthRepository) RevokeConsent( - ctx context.Context, - userID, clientID uuid.UUID, - revokedBy *uuid.UUID, -) error { - - tx, err := r.db.Begin(ctx) - if err != nil { - return err - } - defer tx.Rollback(ctx) - - _, err = tx.Exec(ctx, ` - UPDATE user_consents - SET revoked_at = now(), - revoked_by = $3 - WHERE user_id = $1 - AND client_id = $2 - AND revoked_at IS NULL - `, userID, clientID, revokedBy) - - if err != nil { - return err - } - - _, err = tx.Exec(ctx, ` - DELETE FROM refresh_tokens - WHERE user_id = $1 - AND client_id = $2 - `, userID, clientID) - - if err != nil { - return err - } - - return tx.Commit(ctx) -} diff --git a/kotosoft-id-backend/internal/services/auth.go b/kotosoft-id-backend/internal/services/auth.go index 0e1f376..9a2342a 100644 --- a/kotosoft-id-backend/internal/services/auth.go +++ b/kotosoft-id-backend/internal/services/auth.go @@ -41,38 +41,6 @@ func (s *Service) Register(ctx context.Context, input models.UserRegisterInput) }) } -func (s *Service) RefreshTokens(ctx context.Context, rawToken string) (*TokenPair, error) { - row, err := s.oauth.GetRefreshTokenByHash(ctx, sha256Hex(rawToken)) - if err != nil { - return nil, models.ErrUnauthorized - } - - if time.Now().After(row.ExpiresAt) { - return nil, models.ErrUnauthorized - } - - client, err := s.oauth.GetOAuthClientByID(ctx, row.ClientID) - if err != nil { - return nil, models.ErrInternal - } - - scopes := scopesFromJSON(row.Scopes) - if !ScopesAllowed(client.Scopes, scopes) { - return nil, ErrInvalidGrant - } - - if err := s.oauth.DeleteRefreshTokenByID(ctx, row.ID); err != nil { - return nil, models.ErrInternal - } - - user, err := s.users.GetUserByID(ctx, row.UserID) - if err != nil { - return nil, models.ErrUnauthorized - } - - return s.issuePair(ctx, user, client.ID, scopes) -} - func (s *Service) ValidateAccessToken(ctx context.Context, token string) (*TokenInfo, error) { token = strings.TrimSpace(token) if token == "" { @@ -105,15 +73,19 @@ func (s *Service) UpdateProfile(ctx context.Context, userID uuid.UUID, input mod if input.FirstName != "" { user.FirstName = input.FirstName } + if input.SecondName != "" { user.SecondName = input.SecondName } + if input.BirthDate != nil { user.BirthDate = input.BirthDate } + if input.Sex != "" { user.Sex = input.Sex } + if input.Password != "" { hash, err := bcrypt.GenerateFromPassword([]byte(input.Password), bcrypt.DefaultCost) if err != nil { @@ -121,15 +93,22 @@ func (s *Service) UpdateProfile(ctx context.Context, userID uuid.UUID, input mod } user.PasswordHash = string(hash) } + user.UpdatedAt = time.Now() return s.users.UpdateUser(ctx, *user) } func (s *Service) DeleteProfile(ctx context.Context, userID uuid.UUID, accessToken string) error { + if err := s.oauth.DeleteRefreshTokensByUserID(ctx, userID); err != nil { + return models.ErrInternal + } + if err := s.users.DeleteUser(ctx, userID); err != nil { return models.ErrInternal } + _ = s.redis.Del(ctx, accessTokenPrefix+accessToken) + return nil } diff --git a/kotosoft-id-backend/internal/services/oauth.go b/kotosoft-id-backend/internal/services/oauth.go index cac2c33..7ba8845 100644 --- a/kotosoft-id-backend/internal/services/oauth.go +++ b/kotosoft-id-backend/internal/services/oauth.go @@ -96,12 +96,12 @@ func (s *Service) saveSession(ctx context.Context, token string, sess *OAuthSess func (s *Service) SessionLogin(ctx context.Context, token, email, password string) (string, error) { sess, err := s.GetOAuthSession(ctx, token) if err != nil { - return "", err + return "", ErrInvalidGrant } user, err := s.users.GetUserByEmail(ctx, email) if err != nil || bcryptCompare(user.PasswordHash, password) != nil { - return "", models.ErrUnauthorized + return "", ErrAccessDenied } sess.UserID = user.ID @@ -114,12 +114,7 @@ func (s *Service) SessionLogin(ctx context.Context, token, email, password strin return "", ErrInvalidClient } - if client.Trusted { - return s.SessionApprove(ctx, token) - } - - hasUserConsents := s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes) - if hasUserConsents { + if client.Trusted || s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes) { return s.SessionApprove(ctx, token) } @@ -129,12 +124,12 @@ func (s *Service) SessionLogin(ctx context.Context, token, email, password strin func (s *Service) SessionAttach(ctx context.Context, sessionToken, accessToken string) (string, error) { info, err := s.ValidateAccessToken(ctx, accessToken) if err != nil { - return "", models.ErrUnauthorized + return "", ErrAccessDenied } sess, err := s.GetOAuthSession(ctx, sessionToken) if err != nil { - return "", err + return "", ErrInvalidGrant } sess.UserID = info.UserID @@ -146,12 +141,8 @@ func (s *Service) SessionAttach(ctx context.Context, sessionToken, accessToken s if err != nil { return "", ErrInvalidClient } - if client.Trusted { - return s.SessionApprove(ctx, sessionToken) - } - hasUserConsents := s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes) - if hasUserConsents { + if client.Trusted || s.HasUserConsent(ctx, sess.UserID, client.ID, sess.Scopes) { return s.SessionApprove(ctx, sessionToken) } @@ -161,7 +152,7 @@ func (s *Service) SessionAttach(ctx context.Context, sessionToken, accessToken s func (s *Service) SessionApprove(ctx context.Context, token string) (string, error) { sess, err := s.GetOAuthSession(ctx, token) if err != nil { - return "", err + return "", ErrInvalidGrant } if sess.UserID == uuid.Nil { return "", ErrInvalidGrant @@ -178,7 +169,7 @@ func (s *Service) SessionApprove(ctx context.Context, token string) (string, err } _ = s.redis.Del(ctx, oauthSessionPrefix+token) - s.oauth.RecordUserConsent(ctx, sess.UserID, client.ID, sess.Scopes) + _ = s.oauth.RecordUserConsent(ctx, sess.UserID, client.ID, sess.Scopes) redirectURL, _ := url.Parse(sess.RedirectURI) q := redirectURL.Query() @@ -221,7 +212,7 @@ func (s *Service) ExchangeCode(ctx context.Context, auth ClientAuth, code, redir return nil, models.ErrInternal } - s.oauth.UpdateConsentLastUsed(ctx, row.UserID, client.ID) + _ = s.oauth.UpdateConsentLastUsed(ctx, row.UserID, client.ID) return s.issuePair(ctx, user, client.ID, scopesFromJSON(row.Scopes)) } @@ -241,22 +232,22 @@ func (s *Service) ExchangeRefreshToken(ctx context.Context, auth ClientAuth, raw return nil, ErrInvalidGrant } + scopes := scopesFromJSON(row.Scopes) + if !ScopesAllowed(client.Scopes, scopes) { + return nil, ErrInvalidGrant + } + if err := s.oauth.DeleteRefreshTokenByID(ctx, row.ID); err != nil { return nil, models.ErrInternal } - s.oauth.UpdateConsentLastUsed(ctx, row.UserID, client.ID) + _ = s.oauth.UpdateConsentLastUsed(ctx, row.UserID, client.ID) user, err := s.users.GetUserByID(ctx, row.UserID) if err != nil { return nil, models.ErrInternal } - scopes := scopesFromJSON(row.Scopes) - if !ScopesAllowed(client.Scopes, scopes) { - return nil, ErrInvalidGrant - } - return s.issuePair(ctx, user, client.ID, scopes) } @@ -275,13 +266,7 @@ func (s *Service) RevokeToken(ctx context.Context, auth ClientAuth, rawToken str return nil } -func (s *Service) createAuthCode( - ctx context.Context, - userID, clientID uuid.UUID, - redirectURI string, - scopes []string, - codeChallenge string, -) (string, error) { +func (s *Service) createAuthCode(ctx context.Context, userID, clientID uuid.UUID, redirectURI string, scopes []string, codeChallenge string) (string, error) { rawCode, err := newOpaqueToken(32) if err != nil { return "", models.ErrInternal @@ -330,6 +315,7 @@ func (s *Service) issuePair(ctx context.Context, user *models.User, clientID uui Scopes: scopes, ClientID: clientID, } + data, _ := json.Marshal(accessData) if err := s.redis.Set(ctx, accessTokenPrefix+accessToken, data, s.tokens.AccessTTL).Err(); err != nil { return nil, models.ErrInternal diff --git a/kotosoft-id-backend/internal/services/ratelimiter.go b/kotosoft-id-backend/internal/services/ratelimiter.go new file mode 100644 index 0000000..b166bed --- /dev/null +++ b/kotosoft-id-backend/internal/services/ratelimiter.go @@ -0,0 +1,77 @@ +package services + +import ( + "context" + "fmt" + "time" + + "github.com/redis/go-redis/v9" +) + +type RateLimitConfig struct { + Max int + Window time.Duration + BlockFor time.Duration +} + +var ( + LoginRateLimit = RateLimitConfig{ + Max: 10, + Window: 15 * time.Minute, + BlockFor: 15 * time.Minute, + } + + RegisterRateLimit = RateLimitConfig{ + Max: 5, + Window: time.Hour, + } +) + +type RateLimiter struct { + redis *redis.Client +} + +func NewRateLimiter(rdb *redis.Client) *RateLimiter { + return &RateLimiter{redis: rdb} +} + +func (r *RateLimiter) Allow(ctx context.Context, key string, cfg RateLimitConfig) (bool, int, error) { + blockKey := fmt.Sprintf("rl_block:%s", key) + counterKey := fmt.Sprintf("rl_count:%s", key) + + if cfg.BlockFor > 0 { + blocked, err := r.redis.Exists(ctx, blockKey).Result() + if err != nil { + return true, 0, nil + } + if blocked > 0 { + return false, 0, nil + } + } + + pipe := r.redis.Pipeline() + incrCmd := pipe.Incr(ctx, counterKey) + pipe.Expire(ctx, counterKey, cfg.Window) + if _, err := pipe.Exec(ctx); err != nil { + return true, 0, nil + } + + count := int(incrCmd.Val()) + remaining := cfg.Max - count + if remaining < 0 { + remaining = 0 + } + + if count > cfg.Max { + if cfg.BlockFor > 0 { + _ = r.redis.Set(ctx, blockKey, 1, cfg.BlockFor).Err() + } + return false, 0, nil + } + + return true, remaining, nil +} + +func (r *RateLimiter) Reset(ctx context.Context, key string) { + _ = r.redis.Del(ctx, fmt.Sprintf("rl_count:%s", key), fmt.Sprintf("rl_block:%s", key)) +} diff --git a/kotosoft-id-backend/internal/services/service.go b/kotosoft-id-backend/internal/services/service.go index 04e2bdb..dce369c 100644 --- a/kotosoft-id-backend/internal/services/service.go +++ b/kotosoft-id-backend/internal/services/service.go @@ -37,6 +37,7 @@ type OAuthRepo interface { CreateRefreshToken(ctx context.Context, row models.RefreshTokenRow) (*models.RefreshTokenRow, error) GetRefreshTokenByHash(ctx context.Context, tokenHash string) (*models.RefreshTokenRow, error) DeleteRefreshTokenByID(ctx context.Context, id uuid.UUID) error + DeleteRefreshTokensByUserID(ctx context.Context, userID uuid.UUID) error RecordUserConsent(ctx context.Context, userID, clientID uuid.UUID, scopes []string) error GetUserConsents(ctx context.Context, userID uuid.UUID) ([]models.UserConsent, error) UpdateConsentLastUsed(ctx context.Context, userID, clientID uuid.UUID) error @@ -55,11 +56,10 @@ type ClientAuth struct { } type Service struct { - users UserRepo - oauth OAuthRepo - redis *redis.Client - tokens TokenConfig - basicClient *models.OAuthClient + users UserRepo + oauth OAuthRepo + redis *redis.Client + tokens TokenConfig } func New( @@ -67,14 +67,12 @@ func New( oauth OAuthRepo, rdb *redis.Client, tokenCfg TokenConfig, - basicClient *models.OAuthClient, ) *Service { return &Service{ - users: users, - oauth: oauth, - redis: rdb, - tokens: tokenCfg, - basicClient: basicClient, + users: users, + oauth: oauth, + redis: rdb, + tokens: tokenCfg, } } diff --git a/kotosoft-id-frontend/actions/auth.ts b/kotosoft-id-frontend/actions/auth.ts index 1555c64..7aae35f 100644 --- a/kotosoft-id-frontend/actions/auth.ts +++ b/kotosoft-id-frontend/actions/auth.ts @@ -27,7 +27,7 @@ export async function clearTokens() { store.delete("refresh_token"); } -async function tryRefresh(): Promise { +export async function tryRefresh(): Promise { if (refreshPromise) return refreshPromise; refreshPromise = (async () => { diff --git a/kotosoft-id-frontend/actions/consents.ts b/kotosoft-id-frontend/actions/consents.ts index a0b61e7..24b335a 100644 --- a/kotosoft-id-frontend/actions/consents.ts +++ b/kotosoft-id-frontend/actions/consents.ts @@ -2,6 +2,7 @@ import { Consent } from "@/types" import { cookies } from "next/headers" +import { clearTokens, tryRefresh } from "./auth" export async function getConsents() { const store = await cookies() @@ -15,15 +16,24 @@ export async function getConsents() { }, } ) + + if (response.status === 401) { + const refreshed = await tryRefresh(); + if (!refreshed) { + await clearTokens(); + return null; + } + return getConsents(); + } if (!response.ok) return [] var consents = await response.json() as Consent[]; consents.forEach((consent: Consent) => { if (consent.client_id == process.env.CLIENT_ID) { - consent.isRevokable == false + consent.isRevokable = false } else { - consent.isRevokable == true + consent.isRevokable = true } }); @@ -35,7 +45,7 @@ export async function revokeConsent(clientId: string) { const accessToken = store.get("access_token")?.value const response = await fetch( - `${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/applications/${clientId}`, + `${process.env.KOTOSOFT_ID_API_URL}/api/v1/me/consents/${clientId}`, { method: "DELETE", headers: { diff --git a/kotosoft-id-frontend/app/me/component.tsx b/kotosoft-id-frontend/app/me/component.tsx index 09bcd31..44edb50 100644 --- a/kotosoft-id-frontend/app/me/component.tsx +++ b/kotosoft-id-frontend/app/me/component.tsx @@ -13,7 +13,7 @@ import Applications from "./items/applications"; interface Props { userData: User | null; - consentsData: Consent[] | []; + consentsData: Consent[] | null; } export default function MeClient({ userData, consentsData }: Props) { diff --git a/kotosoft-id-frontend/app/me/items/applications.tsx b/kotosoft-id-frontend/app/me/items/applications.tsx index a23de50..8f78eb2 100644 --- a/kotosoft-id-frontend/app/me/items/applications.tsx +++ b/kotosoft-id-frontend/app/me/items/applications.tsx @@ -9,7 +9,7 @@ import { enUS } from "date-fns/locale"; import { format } from "date-fns"; interface Props { - consents: Consent[] | []; + consents: Consent[] | null; setConsents: (consents: Consent[]) => void; } @@ -24,7 +24,7 @@ export default function Applications({ consents, setConsents }: Props) {

{t("title")}

- {consents.map((consent) => ( + {consents?.map((consent) => ( {consent.client_name} diff --git a/kotosoft-id-frontend/app/oauth/page.ts b/kotosoft-id-frontend/app/oauth/page.ts index f5ff292..d8c353a 100644 --- a/kotosoft-id-frontend/app/oauth/page.ts +++ b/kotosoft-id-frontend/app/oauth/page.ts @@ -1,7 +1,10 @@ import { getSession } from "@/actions/oauth"; import { isRedirectError } from "next/dist/client/components/redirect-error"; +import { cookies } from "next/headers"; import { redirect } from "next/navigation"; +export const dynamic = "force-dynamic"; + export default async function OAuthPage({ searchParams, }: { @@ -14,10 +17,28 @@ export default async function OAuthPage({ const data = await getSession(session); if (!data) redirect("/oauth/error"); - const isAuthenticated = - data.user_id && data.user_id !== "00000000-0000-0000-0000-000000000000"; + const store = await cookies(); + const accessToken = store.get("access_token")?.value; - redirect(isAuthenticated ? `/consent?session=${session}` : `/login?session=${session}`); + if (accessToken) { + const res = await fetch(`${process.env.KOTOSOFT_ID_API_URL}/oauth/session/attach`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${accessToken}` + }, + body: JSON.stringify({ session }), + cache: "no-store", + }); + + if (res.ok) { + const body = await res.json(); + if (body.redirect_url) redirect(body.redirect_url); + redirect(`/consent?session=${session}`); + } + } + + redirect(`/login?session=${session}`); } catch (error) { if (isRedirectError(error)) throw error; console.error("OAuth page error:", error); diff --git a/kotosoft-id-frontend/dockerfile b/kotosoft-id-frontend/dockerfile new file mode 100644 index 0000000..d1adb4a --- /dev/null +++ b/kotosoft-id-frontend/dockerfile @@ -0,0 +1,19 @@ +FROM node:20 AS builder +WORKDIR /app +COPY package.json package-lock.json* ./ +RUN npm install --include=dev +COPY . . +RUN npm run build + +FROM node:20 AS production +WORKDIR /app +COPY package.json package-lock.json* ./ +COPY --from=builder /app/node_modules ./node_modules +COPY --from=builder /app/.next ./.next +COPY --from=builder /app/public ./public +COPY --from=builder /app/messages ./messages +RUN npm prune --omit=dev +EXPOSE 80 +CMD ["npm", "start", "--", "-p", "80", "-H", "0.0.0.0"] +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ + CMD wget -q --spider http://localhost:80/ || exit 1 \ No newline at end of file diff --git a/kotosoft-id-frontend/next.config.ts b/kotosoft-id-frontend/next.config.ts index 397856c..d8462cc 100644 --- a/kotosoft-id-frontend/next.config.ts +++ b/kotosoft-id-frontend/next.config.ts @@ -1,10 +1,7 @@ import type { NextConfig } from "next"; import createNextIntlPlugin from "next-intl/plugin"; -const nextConfig: NextConfig = { - /* config options here */ -}; - +const nextConfig: NextConfig = {}; const withNextIntl = createNextIntlPlugin(); export default withNextIntl(nextConfig);