cryden

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 9, 2026 License: MIT Imports: 4 Imported by: 0

README ΒΆ

CrydenSync πŸ”

Embeddable authentication engine for Go β€” offline-first, framework-agnostic.

Go Reference Go Report Card GitHub Release Build Status

🎯 The Problem

Authentication is not business logic, yet every project rewrites it. Developers face three painful choices:

  1. Rewrite auth logic for every project β€” risky, inconsistent, time-consuming
  2. Use hosted auth services β€” vendor lock-in, users aren't yours, requires internet
  3. Use framework-specific tools β€” tied to Express, Django, Next.js β€” not reusable

πŸ’‘ The Solution

CrydenSync is an embeddable authentication engine that gives you a standard, reusable auth system you control:

package main

import (
    "context"
    "fmt"
    "log"
    
    "github.com/crydensync/cryden"
)

func main() {
    // Create context
    ctx := context.Background()
    
    // 1. Create engine (in-memory storage - perfect for testing)
    engine := cryden.New()
    fmt.Println("βœ… Engine created")
    
    // 2. Sign up a new user
    email := "alice@example.com"
    password := "SecurePass123"
    
    user, err := cryden.SignUp(ctx, engine, email, password)
    if err != nil {
        log.Fatalf("❌ SignUp failed: %v", err)
    }
    fmt.Printf("βœ… User created: %s (%s)\n", user.ID, user.Email)
    
    // 3. Login
    tokens, rateLimit, err := cryden.Login(ctx, engine, email, password)
    if err != nil {
        log.Fatalf("❌ Login failed: %v", err)
    }
    fmt.Printf("βœ… Login successful!\n")
    fmt.Printf("   Access Token: %s...\n", tokens.AccessToken[:50])
    fmt.Printf("   Refresh Token: %s...\n", tokens.RefreshToken[:50])
    fmt.Printf("   Rate Limit Remaining: %d\n", rateLimit.Remaining)
    
    // 4. Verify token
    userID, err := cryden.VerifyToken(engine, tokens.AccessToken)
    if err != nil {
        log.Fatalf("❌ Token verification failed: %v", err)
    }
    fmt.Printf("βœ… Token verified for user: %s\n", userID)
    
    // 5. Logout
    err = cryden.Logout(ctx, engine, tokens.RefreshToken)
    if err != nil {
        log.Fatalf("❌ Logout failed: %v", err)
    }
    fmt.Println("βœ… Logout successful")
    
    // 6. Try to use logged out token (should fail)
    _, err = cryden.RefreshToken(ctx, engine, tokens.RefreshToken)
    if err != nil {
        fmt.Printf("βœ… Expected error after logout: %v\n", err)
    }
    
    fmt.Println("\nπŸŽ‰ All tests passed!")
}  
  

View full example β†’

✨ Features

βœ… v1.0.0 (Current)

Β· Email/password authentication β€” Secure, bcrypt hashed Β· JWT access tokens β€” Short-lived, stateless Β· Opaque refresh tokens β€” Stored in DB for revocation Β· Rate limiting β€” Per IP with headers (X-RateLimit-*) Β· Audit logging β€” Track every auth event Β· Session management β€” Logout single device or all devices Β· Multiple storage backends β€” Memory, SQLite, PostgreSQL, MongoDB Β· Complete test suite β€” 90%+ coverage Β· Offline-first β€” Works without internet, SQLite by default

🚧 Coming Soon

Feature Status Target gRPC API 🚧 Planned v1.1.0 CLI tool (csax) 🚧 Planned v1.1.0 Language SDKs (JS, Python, PHP) 🚧 Planned v1.2.0 MFA/2FA (TOTP) πŸ“… Future v1.3.0 Magic Links πŸ“… Future v1.3.0 WebAuthn/Passkeys πŸ“… Future v2.0.0

πŸ“¦ Installation

go get github.com/crydensync/cryden@v1.0.0

πŸ“– Documentation

Section Description πŸ“š Getting Started 60-second working auth 🎯 Philosophy Why Cryden exists πŸ—οΈ Architecture How it works πŸ“ Design Decisions Why we built it this way πŸ”§ Guide Installation, config, middleware, testing πŸ”Œ Adapters Interface implementations πŸ“˜ API Reference Complete API docs πŸ’‘ Examples Copy-paste working code

πŸ§ͺ Testing

CrydenSync is designed for maximum testability:

func TestLogin(t *testing.T) {
    engine := cryden.New()  // In-memory storage
    
    // Optional: Use mock hasher for faster tests
    engine.WithHasher(&core.MockHasher{})
    
    // Optional: Disable rate limiting
    engine.WithRateLimiter(&core.NoopRateLimiter{})
    
    ctx := context.Background()
    cryden.SignUp(ctx, engine, "test@example.com", "pass")
    tokens, _, err := cryden.Login(ctx, engine, "test@example.com", "pass")
    
    assert.NoError(t, err)
    assert.NotEmpty(t, tokens.AccessToken)
}

πŸ“– Testing Guide β†’

πŸ”§ Configuration

// With SQLite persistence
engine, err := cryden.WithSQLite("users.db")

// With custom JWT secret (required in production)
cryden.WithJWTSecret(engine, os.Getenv("JWT_SECRET"))

// With custom rate limiter
engine.WithRateLimiter(redis.NewRateLimiter())

// With custom audit logger
engine.WithAuditLogger(file.NewAuditLogger("auth.log"))

πŸ“Š Storage Backends

Backend Status Use Case Memory βœ… Stable Testing SQLite βœ… Stable Offline-first, development PostgreSQL βœ… Stable Production MongoDB βœ… Stable Document stores MySQL 🚧 Planned v1.1.0 Redis 🚧 Planned v1.1.0 (rate limiting)

πŸ“› About the Name

CrydenSync is the full name of the project, but the Go package is simply cryden for brevity.

import "github.com/crydensync/cryden"  // Notice: crydensync/cryden

auth := cryden.New()  // Short and sweet!

πŸ”’ Security Notes v1.0.0

βœ… Implemented
  • Password hashing with bcrypt
  • JWT signing with HMAC-SHA256
  • Rate limiting to prevent brute force
  • Audit logging for all auth events
⚠️ Planned for v1.1.0
  • Refresh token hashing in database
  • Session token hashing
  • Device fingerprinting
  • Argon2id hasher option
Future Security Enhancements
  • Email verification (v1.1)
  • Password reset flow (v1.1)
  • MFA/2FA (v1.2)
  • Login notifications (v1.2)
  • Breached password detection (v1.2)
πŸ” Best Practices
  1. Always use HTTPS in production
  2. Set strong JWT secrets via environment variables
  3. Monitor audit logs for suspicious activity
  4. Add email verification before sensitive actions

🀝 Contributing

We welcome contributions! See CONTRIBUTING.md for:

Β· Code of Conduct Β· Development setup Β· Pull request process Β· Coding standards

πŸ“„ License

MIT Β© Crydensync

⭐ Support

If you find Cryden useful, please star the repo!

πŸ—ΊοΈ Roadmap

Current: v1.0.0 (March 2026)

βœ… Core authentication with email/password. βœ… JWT + refresh tokens. βœ… Rate limiting & audit logs. βœ… Multiple databases (SQLite, PostgreSQL, MongoDB)

Coming in v1.1.0 (Q2 2026)

πŸš€ CLI tool (csax) πŸ“± Device tracking (IP, user agent, last seen) πŸ” Argon2id hasher ⚑ Redis rate limiter le audit logger 🐬 MySQL support

Coming in v1.2.0 (Q3 2026)

πŸ”Œ gRPC API 🌐 Language SDKs (JS, Python, PHP) πŸ”” Webhooks πŸ”„ Migration tools (Clerk, Auth0, Supabase)

Coming in v1.3.0 (Q4 2026)

πŸ” Multi-Factor Authentication (TOTP) πŸ“§ Magic links & passwordless πŸ”‘ WebAuthn / Passkeys 🌍 Social login (OAuth2)

Future (2027+)

☁️ Optional cloud sync πŸ“Š Enterprise features πŸ”Œ More adapters πŸš€ v2.0.0 (breaking changes if needed)

View full roadmap β†’


Built with ❀️ in Africa · Own your users, not vendor lock-in

Documentation ΒΆ

Overview ΒΆ

Package cryden is the main entry point for the CrydennSync authentication engine.

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
var (
	ErrUserExists         = core.ErrUserExists
	ErrUserNotFound       = core.ErrUserNotFound
	ErrInvalidCredentials = core.ErrInvalidCredentials
	ErrInvalidEmail       = core.ErrInvalidEmail
	ErrPasswordTooShort   = core.ErrPasswordTooShort
	ErrPasswordTooLong    = core.ErrPasswordTooLong
	ErrPasswordNoUpper    = core.ErrPasswordNoUpper
	ErrPasswordNoLower    = core.ErrPasswordNoLower
	ErrPasswordNoNumber   = core.ErrPasswordNoNumber
	ErrTooManyAttempts    = core.ErrTooManyAttempts
	ErrInvalidToken       = core.ErrInvalidToken
	ErrSessionNotFound    = core.ErrSessionNotFound
)

Functions ΒΆ

func ChangeEmail ΒΆ

func ChangeEmail(ctx context.Context, engine *Engine, userID, newEmail string) error

ChangeEmail updates user's email

func ChangePassword ΒΆ

func ChangePassword(ctx context.Context, engine *Engine, userID, oldPassword, newPassword string) error

ChangePassword updates user's password and logs out all devices

func DeleteAccount ΒΆ

func DeleteAccount(ctx context.Context, engine *Engine, userID string) error

DeleteAccount removes user and all sessions

func Login ΒΆ

func Login(ctx context.Context, engine *Engine, email, password string) (*TokenPair, *LimitResult, error)

Login authenticates a user and returns tokens

func Logout ΒΆ

func Logout(ctx context.Context, engine *Engine, refreshToken string) error

Logout revokes the current session

func LogoutAll ΒΆ

func LogoutAll(ctx context.Context, engine *Engine, userID string) error

LogoutAll revokes ALL sessions for a user

func RevokeSession ΒΆ

func RevokeSession(ctx context.Context, engine *Engine, sessionID string) error

RevokeSession manually revokes a specific session

func VerifyToken ΒΆ

func VerifyToken(engine *Engine, tokenString string) (string, error)

VerifyToken validates a JWT access token and returns the user ID

Types ΒΆ

type AuditEntry ΒΆ

type AuditEntry = core.AuditEntry

type AuditLogger ΒΆ

type AuditLogger = core.AuditLogger

type Claims ΒΆ

type Claims = core.Claims

type Engine ΒΆ

type Engine = core.Engine

Engine is the main authentication engine

func New ΒΆ

func New() *Engine

New creates an in-memory engine (perfect for testing)

func WithAuditLogger ΒΆ

func WithAuditLogger(engine *Engine, logger AuditLogger) *Engine

WithAuditLogger sets a custom audit logger

func WithHasher ΒΆ

func WithHasher(engine *Engine, hasher Hasher) *Engine

WithHasher sets a custom password hasher

func WithJWTSecret ΒΆ

func WithJWTSecret(engine *Engine, secret string) *Engine

WithJWTSecret sets a custom JWT secret

func WithRateLimiter ΒΆ

func WithRateLimiter(engine *Engine, limiter RateLimiter) *Engine

WithRateLimiter sets a custom rate limiter

func WithSQLite ΒΆ

func WithSQLite(dbPath string) (*Engine, error)

WithSQLite creates an engine with persistent SQLite storage

type Hasher ΒΆ

type Hasher = core.Hasher

type LimitResult ΒΆ

type LimitResult = core.LimitResult

type RateLimiter ΒΆ

type RateLimiter = core.RateLimiter

type Session ΒΆ

type Session = core.Session

func ListSessions ΒΆ

func ListSessions(ctx context.Context, engine *Engine, userID string) ([]Session, error)

ListSessions returns all active sessions for a user

type SessionStore ΒΆ

type SessionStore = core.SessionStore

type TokenPair ΒΆ

type TokenPair = core.TokenPair

func RefreshToken ΒΆ

func RefreshToken(ctx context.Context, engine *Engine, refreshToken string) (*TokenPair, error)

RefreshToken issues new tokens and rotates the refresh token

type User ΒΆ

type User = core.User

func GetUser ΒΆ

func GetUser(ctx context.Context, engine *Engine, userID string) (*User, error)

GetUser retrieves a user by ID

func GetUserByEmail ΒΆ

func GetUserByEmail(ctx context.Context, engine *Engine, email string) (*User, error)

GetUserByEmail retrieves a user by email

func SignUp ΒΆ

func SignUp(ctx context.Context, engine *Engine, email, password string) (*User, error)

SignUp creates a new user account

type UserStore ΒΆ

type UserStore = core.UserStore

Interfaces

Directories ΒΆ

Path Synopsis
examples
basic command
complete command
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL