{"id":21030972,"url":"https://github.com/azutoolkit/session","last_synced_at":"2026-03-08T15:03:09.434Z","repository":{"id":40262769,"uuid":"492590321","full_name":"azutoolkit/session","owner":"azutoolkit","description":"Session Management Library","archived":false,"fork":false,"pushed_at":"2026-01-25T23:18:50.000Z","size":171,"stargazers_count":7,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2026-01-26T14:13:21.704Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Crystal","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/azutoolkit.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":"roadmap.md","authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2022-05-15T19:59:08.000Z","updated_at":"2026-01-25T23:18:53.000Z","dependencies_parsed_at":"2024-12-01T14:28:06.514Z","dependency_job_id":"09ef1488-68ee-48d8-ba6a-79459286fdbf","html_url":"https://github.com/azutoolkit/session","commit_stats":null,"previous_names":[],"tags_count":19,"template":false,"template_full_name":null,"purl":"pkg:github/azutoolkit/session","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/azutoolkit%2Fsession","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/azutoolkit%2Fsession/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/azutoolkit%2Fsession/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/azutoolkit%2Fsession/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/azutoolkit","download_url":"https://codeload.github.com/azutoolkit/session/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/azutoolkit%2Fsession/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28926259,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-30T22:32:35.345Z","status":"ssl_error","status_checked_at":"2026-01-30T22:32:31.927Z","response_time":66,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-19T12:22:43.531Z","updated_at":"2026-03-08T15:03:09.429Z","avatar_url":"https://github.com/azutoolkit.png","language":"Crystal","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Session\n\n**Type-safe, production-ready session management for Crystal.**\n\n[![Crystal CI](https://github.com/azutoolkit/session/workflows/Crystal%20CI/badge.svg?branch=master)](https://github.com/azutoolkit/session/actions)\n[![Codacy Badge](https://api.codacy.com/project/badge/Grade/9a663614a1844a188270ba015cd14651)](https://app.codacy.com/gh/azutoolkit/session)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n\n---\n\n## Why Session?\n\n| | |\n|---|---|\n| **Type-Safe** | Define sessions as Crystal classes with compile-time guarantees |\n| **Multiple Backends** | Cookie, Memory, Redis, or Clustered Redis—pick what fits |\n| **Battle-Tested Security** | AES-256 encryption, HMAC-SHA256, PBKDF2, client binding |\n| **Production Resilience** | Circuit breakers, retry logic, graceful degradation |\n| **346 Tests** | Comprehensive coverage you can rely on |\n\n---\n\n## Quick Start\n\n**Install** (add to `shard.yml`):\n\n```yaml\ndependencies:\n  session:\n    github: azutoolkit/session\n```\n\n**Use** (\u003c 30 seconds to your first session):\n\n```crystal\nrequire \"session\"\n\n# Define your session data\nclass UserSession \u003c Session::Base\n  property? authenticated : Bool = false\n  property username : String? = nil\nend\n\n# Configure once\nSession.configure do |config|\n  config.secret = ENV[\"SESSION_SECRET\"]\n  config.store = Session::MemoryStore(UserSession).new\nend\n\n# Create and use sessions\nstore = Session.config.store.not_nil!\nsession = store.create\nsession.username = \"alice\"\n```\n\nThat's it. You're ready to build.\n\n---\n\n## Key Features\n\n### Storage Backends\n\n| Backend | Best For | Persistence | Multi-Node |\n|---------|----------|-------------|------------|\n| **CookieStore** | Stateless apps, serverless | Client-side | Yes |\n| **MemoryStore** | Development, single-server | None | No |\n| **RedisStore** | Production deployments | Redis | Yes |\n| **ClusteredRedisStore** | High-scale, multi-node | Redis + local cache | Yes |\n\n```crystal\n# Cookie (stateless, client-side)\nconfig.store = Session::CookieStore(UserSession).new\n\n# Memory (development)\nconfig.store = Session::MemoryStore(UserSession).new\n\n# Redis (production)\nconfig.store = Session::RedisStore(UserSession).new(client: Redis.new)\n\n# Clustered Redis (high-scale production)\nconfig.cluster.enabled = true\nconfig.store = Session::ClusteredRedisStore(UserSession).new(client: Redis.new)\n```\n\n### Security\n\n- **Encryption** — AES-256-CBC with random IV per operation\n- **Signing** — HMAC-SHA256 to detect tampering\n- **Key Derivation** — Optional PBKDF2 with configurable iterations\n- **Client Binding** — Lock sessions to IP and/or User-Agent\n- **Size Protection** — Automatic cookie size validation (4KB limit)\n\n```crystal\nSession.configure do |config|\n  config.secret = ENV[\"SESSION_SECRET\"]       # 32+ chars recommended\n  config.use_kdf = true                       # Enable PBKDF2\n  config.kdf_iterations = 100_000             # OWASP recommended\n  config.bind_to_ip = true                    # Prevent session hijacking\n  config.bind_to_user_agent = true\nend\n```\n\n### Resilience\n\n- **Circuit Breaker** — Fail fast when backends are down\n- **Retry Logic** — Exponential backoff with jitter\n- **Compression** — Gzip for large session payloads\n\n```crystal\nSession.configure do |config|\n  config.circuit_breaker_enabled = true\n  config.circuit_breaker_config = Session::CircuitBreakerConfig.new(\n    failure_threshold: 5,\n    reset_timeout: 30.seconds\n  )\n\n  config.enable_retry = true\n  config.retry_config = Session::RetryConfig.new(\n    max_attempts: 3,\n    base_delay: 100.milliseconds,\n    backoff_multiplier: 2.0\n  )\nend\n```\n\n### Clustering\n\nMulti-node session management with Redis Pub/Sub invalidation and local caching.\n\n```mermaid\nflowchart LR\n    subgraph Node_A[\"Node A\"]\n        A_Cache[\"Local Cache\"]\n    end\n    subgraph Node_B[\"Node B\"]\n        B_Cache[\"Local Cache\"]\n    end\n    Redis[(\"Redis\")]\n    PubSub{{\"Pub/Sub\"}}\n\n    A_Cache \u003c--\u003e Redis\n    B_Cache \u003c--\u003e Redis\n    A_Cache -.-\u003e|invalidate| PubSub -.-\u003e|evict| B_Cache\n```\n\n```crystal\nSession.configure do |config|\n  config.cluster.enabled = true\n  config.cluster.node_id = ENV[\"POD_NAME\"]? || UUID.random.to_s\n  config.cluster.local_cache_ttl = 30.seconds\n  config.cluster.local_cache_max_size = 10_000\n\n  config.store = Session::ClusteredRedisStore(UserSession).new(\n    client: Redis.new(url: ENV[\"REDIS_URL\"])\n  )\nend\n```\n\n---\n\n## API Essentials\n\n### Store Operations\n\n```crystal\nstore = Session.config.store.not_nil!\n\nstore.create              # New session\nstore.delete              # Destroy session\nstore.regenerate_id       # New ID, keep data (post-login security)\nstore.valid?              # Check validity\nstore.current_session     # Access your typed session data\nstore.flash               # One-request flash messages\n```\n\n### Session Object\n\n```crystal\nsession = store.current_session\n\nsession.session_id           # Unique ID\nsession.username             # Your session properties directly\nsession.valid?               # Not expired?\nsession.expired?             # Past expiration?\nsession.time_until_expiry    # Remaining lifetime\nsession.touch                # Extend expiration\n```\n\n### Flash Messages\n\n```crystal\n# Set (available next request)\nstore.flash[\"notice\"] = \"Saved successfully\"\nstore.flash[\"error\"] = \"Something went wrong\"\n\n# Read (clears after access)\nstore.flash.now[\"notice\"]  # =\u003e \"Saved successfully\"\n```\n\n### Query \u0026 Bulk Operations\n\n```crystal\nstore = Session::MemoryStore(UserSession).new\n\n# Iterate sessions\nstore.each_session { |s| puts s.username }\n\n# Find by criteria\nadmins = store.find_by { |s| s.roles.includes?(\"admin\") }\n\n# Bulk delete (e.g., revoke compromised user)\nstore.bulk_delete { |s| s.user_id == compromised_id }\n```\n\n---\n\n## HTTP Integration\n\n```crystal\nrequire \"http/server\"\n\nSession.configure do |config|\n  config.secret = ENV[\"SESSION_SECRET\"]\n  config.store = Session::MemoryStore(UserSession).new\nend\n\nstore = Session.config.store.not_nil!\n\nserver = HTTP::Server.new([\n  Session::SessionHandler.new(store),\n  YourAppHandler.new,\n])\n\nserver.listen(8080)\n```\n\nThe handler automatically loads sessions from cookies, validates bindings, handles corruption gracefully, and sets response cookies.\n\n---\n\n## Configuration Reference\n\n```crystal\nSession.configure do |config|\n  # Core\n  config.secret = ENV[\"SESSION_SECRET\"]   # Required\n  config.timeout = 1.hour                 # Session lifetime\n  config.session_key = \"_session\"         # Cookie name\n  config.sliding_expiration = true        # Extend on access\n\n  # Security\n  config.use_kdf = true                   # PBKDF2 key derivation\n  config.kdf_iterations = 100_000\n  config.bind_to_ip = true\n  config.bind_to_user_agent = true\n  config.encrypt_redis_data = true\n\n  # Performance\n  config.compress_data = true\n  config.compression_threshold = 256\n\n  # Resilience\n  config.enable_retry = true\n  config.circuit_breaker_enabled = true\n\n  # Clustering\n  config.cluster.enabled = true\n  config.cluster.local_cache_ttl = 30.seconds\n  config.cluster.local_cache_max_size = 10_000\n\n  # Callbacks\n  config.on_started = -\u003e(id : String, session : Session::Base) { Log.info { \"Session #{id} created\" } }\n  config.on_deleted = -\u003e(id : String, session : Session::Base) { Log.info { \"Session #{id} destroyed\" } }\n\n  # Metrics\n  config.metrics_backend = Session::Metrics::LogBackend.new\nend\n```\n\n---\n\n## Documentation\n\nFull documentation available at [GitBook](https://azutoolkit.gitbook.io/session) (or see the `docs/` directory).\n\n- [Getting Started](docs/getting-started/quick-start.md)\n- [Configuration Guide](docs/configuration/basic.md)\n- [Storage Backends](docs/storage-backends/overview.md)\n- [Clustering Guide](docs/clustering/overview.md)\n- [Security Best Practices](docs/configuration/security.md)\n- [AZU Framework Integration](docs/integrations/azu-framework.md)\n- [HTTP::Server Integration](docs/integrations/http-server.md)\n- [Upgrade Guide](UPGRADE.md)\n\n---\n\n## Contributing\n\n1. Fork it\n2. Create your branch (`git checkout -b feature/awesome`)\n3. Write tests\n4. Make sure `crystal spec` passes\n5. Commit and push\n6. Open a PR\n\n---\n\n## License\n\nMIT — see [LICENSE](LICENSE)\n\n---\n\nBuilt with Crystal. Maintained by [@eliasjpr](https://github.com/eliasjpr).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fazutoolkit%2Fsession","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fazutoolkit%2Fsession","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fazutoolkit%2Fsession/lists"}