PHPackages                             monkeyscloud/monkeyslegion-session - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. monkeyscloud/monkeyslegion-session

ActiveLibrary

monkeyscloud/monkeyslegion-session
==================================

1.0.5(2mo ago)0954↑250%2MITPHPPHP ^8.4

Since Feb 21Pushed 1mo agoCompare

[ Source](https://github.com/MonkeysCloud/MonkeysLegion-Session)[ Packagist](https://packagist.org/packages/monkeyscloud/monkeyslegion-session)[ RSS](/packages/monkeyscloud-monkeyslegion-session/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependencies (18)Versions (7)Used By (2)

MonkeysLegion Session
=====================

[](#monkeyslegion-session)

1. Session Composition (The Core)
---------------------------------

[](#1-session-composition-the-core)

A session instance in MonkeysLegion will consist of the following data points:

ComponentDescriptionExample / Value**Session ID**Unique, cryptographically secure identifier.`ml_sess_8f2d9c1a...`**Payload**Persistent data stored for the user.`{"user_id": 42, "role": "admin"}`**Flash Data**Temporary data that is deleted after the next request.`{"status": "Profile updated!"}`**Created At**Timestamp of when the session was first generated.`1707782400` (Unix)**Last Activity**Timestamp updated on every request (for idle timeout).`1707782900` (Unix)**Expiration**Hard cutoff time when the session becomes invalid.`1707786000` (Unix)---

2. Security Fingerprinting (Validation)
---------------------------------------

[](#2-security-fingerprinting-validation)

To prevent session hijacking, we store and verify these browser/network traits:

- **User-Agent (UA):** The browser string. If it changes mid-session, we immediately **kill** the session (High-risk indicator).
- **IP Address:** The user's network address.
    - *Strict Mode:* Invalidate session if IP changes.
    - *Relaxed Mode:* Ignore (better for mobile users moving between Wi-Fi and 5G).
- **CSRF Token:** A unique token linked to this specific Session ID to prevent Cross-Site Request Forgery.

---

3. Session State Lifecycle
--------------------------

[](#3-session-state-lifecycle)

1. **Generation:** Create ID → Set Cookie → Initialize Storage.
2. **Validation:** Check Cookie ID → Match with Driver → Verify IP/UA.
3. **Update:** Refresh `Last Activity` → Write new Payload/Flash data.
4. **Destruction:** Clear Storage → Expire Cookie.

---

4. Architecture Overview
------------------------

[](#4-architecture-overview)

### SessionDriverInterface

[](#sessiondriverinterface)

MethodArgumentsReturnsDescription**open**`path`, `name``bool`Initialize the storage resource.**close**-`bool`Close the storage resource.**read**`id``?array`Retrieve session data (payload + metadata) by ID.**write**`id`, `payload`, `metadata``bool`Save serialized session data and metadata.**destroy**`id``bool`Delete the session data from storage.**gc**`maxLifetime``int/false`Garbage Collection: Delete sessions older than X.**lock**`id`, `timeout``bool`Acquire an exclusive lock on the session ID.**unlock**`id``bool`Release the lock so other requests can proceed.### SessionManager Details

[](#sessionmanager-details)

The `SessionManager` is the high-level class your application code will actually interact with. It manages the **Session Object** (the data) and coordinates with the **Driver** (the storage).

#### Responsibilities of the Manager

[](#responsibilities-of-the-manager)

1. **Bootstrapping:** Reading the Session ID from the request cookies and asking the Driver for the data.
2. **Serialization:** Turning the PHP array into a string (and back) so the Driver can save it.
3. **Flash Management:** Handling data that only lasts for one "hop" (request).
4. **Security Checks:** Comparing the User-Agent or IP before allowing access.

#### SessionManager Methods

[](#sessionmanager-methods)

MethodDescription**start($id)**Resumes or starts a new session with given ID.**save()**Saves the current session data to the driver.**getId()**Get the current Session ID.**get($key, $default)**Retrieve data (supports dot notation).**set($key, $value)**Store data in the session.**has($key)**Returns `true` if the key is present.**forget($key)**Remove a key from the session.**flash($key, $value)**Store data for the next request only.**getFlash($key, $default)**Retrieve flash data.**reflash()**Keep all flash data for the next request.**regenerate($destroy)**Change the Session ID (Crucial for login to prevent fixation).**setIpAddress($ip)**Set the user's IP address for validation.**setUserAgent($ua)**Set the user's browser string for validation.**setUserId($id)**Associate a User ID with the session.---

5. Session Middleware: The Request Lifecycle
--------------------------------------------

[](#5-session-middleware-the-request-lifecycle)

The Middleware bridges the HTTP Request/Response with the Session Manager. It ensures data is consistent and atomic.

PhaseActionDetail**1. Extract**`getCookie()`Look for the session cookie (e.g., `ML_SESS`) in the Request.**2. Start**`manager->start()`The Manager triggers `driver->lock()` and `driver->read()`.**3. Inject**`withAttribute()`The Session object is attached to the Request for use in Controllers.**4. Process**`handler->handle()`The actual application logic runs (Routes, Controllers, Actions).**5. Capture**`getResponse()`The Middleware catches the resulting Response object.**6. Commit**`manager->save()`The Manager triggers `driver->write()` and `driver->unlock()`.**7. Finalize**`set-cookie`If the session is new or regenerated, add the `Set-Cookie` header to the Response.### Logic Flow Diagram (Conceptual)

[](#logic-flow-diagram-conceptual)

1. **Request In** ↓
2. **SessionMiddleware::process()**→ \[Manager\] → \[Driver\] → (LOCK &amp; READ) ↓
3. **Controller / Logic** → `$request->getAttribute('session')->set('key', 'value')`↓
4. **SessionMiddleware (Post-Process)**→ \[Manager\] → \[Driver\] → (WRITE &amp; UNLOCK) ↓
5. **Response Out** (with Set-Cookie header)

Since we are using **Atomic Locking**, the Middleware must be careful. If an exception occurs during the "App Phase" (Step 4), the Middleware should still trigger the **Unlock** mechanism in a `finally` block to ensure the session isn't stuck in a locked state for other requests. (probably re throw in catch if user didn't already catch that occurred exception)

---

6. Project Structure
--------------------

[](#6-project-structure)

Since we are aligning with the **monkeyslegion-** ecosystem, the architecture needs to be modular, interface-driven, and ready for PSR-11 (Dependency Injection).

```
monkeyslegion-session/
├── config/
│   └── session.php                # Session configuration options
├── docs/
│   └── usage.md                   # Usage documentation and examples
├── migrations/
│   └── sessions.sql               # Database migration for sessions table
├── src/
│   ├── Cli/
│   │   └── Command/
│   │       └── ConfigPublisher.php    # CLI command to publish config files
│   ├── Contracts/
│   │   ├── DataHandlerInterface.php   # Serialization contract (e.g., JSON, encryption)
│   │   ├── SessionDriverInterface.php # Storage driver contract (with lock/unlock)
│   │   └── SessionInterface.php       # Session manager API contract
│   ├── Drivers/
│   │   ├── DatabaseDriver.php         # PDO/DB session storage implementation
│   │   ├── FileDriver.php             # Filesystem session storage implementation
│   │   └── RedisDriver.php            # Redis session storage implementation
│   ├── EncryptedSerializer.php        # AES-256-GCM encryption layer (implements DataHandlerInterface)
│   ├── Exceptions/
│   │   ├── SessionException.php       # Generic session exception
│   │   └── SessionLockException.php   # Lock acquisition failure exception
│   ├── Factory/
│   │   └── DriverFactory.php          # Factory for creating driver instances
│   ├── Middleware/
│   │   ├── SessionMiddleware.php      # PSR-15 session middleware logic
│   │   └── VerifyCsrfToken.php        # CSRF token validation middleware
│   ├── NativeSerializer.php           # Default JSON serializer (implements DataHandlerInterface)
│   ├── SessionBag.php                 # Data container (handles flash/payload)
│   └── SessionManager.php             # Session orchestrator (coordinates Bag + Drivers)
├── tests/

```

### Component Breakdown

[](#component-breakdown)

#### 1. The `SessionBag`

[](#1-the-sessionbag)

Instead of putting all logic in the Manager, a `SessionBag` holds the actual data array. It handles the "Dot Notation" (e.g., `$session->get('user.profile.name')`) and manages which keys are **Flash** (one-time use) vs. **Persistent**. It uses `put()` for storing attributes and `flash()` for temporary data.

#### 2. The `SessionManager` (The Orchestrator)

[](#2-the-sessionmanager-the-orchestrator)

This class should be injected into your Middleware or Controllers.

- It uses the `DriverInterface` to fetch data.
- It uses a `Serializer` to decode that data into the `SessionBag`.
- **Important:** It must handle the `regenerate()` method, which creates a new ID but keeps the data (crucial to prevent Session Fixation attacks during login).

#### 3. The `Driver` Implementations

[](#3-the-driver-implementations)

- **Database:** Needs a table with `id` (string), `payload` (text), and `last_activity` (integer/timestamp).
- **Redis:** Should use `EXPIRE` to let Redis handle the "Garbage Collection" automatically.
- **File:** Needs `flock()` to handle the **Atomic Locking**.

---

Roadmap
-------

[](#roadmap)

### Phase 1: Core Foundation

[](#phase-1-core-foundation)

- Implement `SessionInterface` contract
- Implement `DriverInterface` contract
- Create `SessionBag` with dot notation support
- Create `SessionManager` orchestrator
- Add basic exception handling

### Phase 2: Driver Implementations

[](#phase-2-driver-implementations)

- Implement `FileDriver` with `flock()` support
- Implement `DatabaseDriver` with PDO
- Implement `RedisDriver` with atomic operations
- Add driver-specific tests

### Phase 3: Middleware &amp; Integration

[](#phase-3-middleware--integration)

- Implement PSR-15 `SessionMiddleware`
- Add atomic locking with `finally` block
- Cookie management (secure, httpOnly, sameSite)

### Phase 4: Security Features

[](#phase-4-security-features)

- \[/\] User-Agent validation (implemented in Middleware/Manager)
- \[/\] IP address validation (implemented in Middleware/Manager)
- CSRF token generation and validation
- Session fixation prevention (via `regenerate()`)

### Phase 5: Advanced Features

[](#phase-5-advanced-features)

- Flash data management
- Garbage collection automation
- Session encryption option (AES-256-GCM)
- PSR-11 container integration (via Factory/Service providers)

### Phase 6: Documentation &amp; Release

[](#phase-6-documentation--release)

- Complete API documentation
- Usage examples and tutorials
- Performance benchmarks
- v1.0.0 stable release

---

Contributing
------------

[](#contributing)

**Welcome to contribute!**

This is an open-source project and we appreciate any help from the community. Whether it's a bug fix, new feature, or documentation improvement, all contributions are valued.

### How to Contribute

[](#how-to-contribute)

1. **Fork** the repository
2. **Clone** your fork locally
3. **Create** a new branch for your feature/fix (`git checkout -b feature/amazing-feature`)
4. **Make** your changes
5. **Test** your changes thoroughly
6. **Commit** your changes (`git commit -m 'Add amazing feature'`)
7. **Push** the branch to your fork
8. **Submit** a Pull Request

### Guidelines

[](#guidelines)

- Follow PSR-12 coding standards
- Write unit tests for new features (Or it gonna need to be tested by us before merge)
- Update documentation as needed
- Keep commits atomic and well-described
- Be respectful and constructive in discussions

We look forward to your contributions!

###  Health Score

47

—

FairBetter than 94% of packages

Maintenance89

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 83.3% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~5 days

Total

6

Last Release

60d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/51e4df19377776baa8eafb605d9e7d2374b855c686f552c20d6856e94e3597c3?d=identicon)[yorchperaza](/maintainers/yorchperaza)

---

Top Contributors

[![Amanar-Marouane](https://avatars.githubusercontent.com/u/155680356?v=4)](https://github.com/Amanar-Marouane "Amanar-Marouane (15 commits)")[![yorchperaza](https://avatars.githubusercontent.com/u/2913369?v=4)](https://github.com/yorchperaza "yorchperaza (3 commits)")

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/monkeyscloud-monkeyslegion-session/health.svg)

```
[![Health](https://phpackages.com/badges/monkeyscloud-monkeyslegion-session/health.svg)](https://phpackages.com/packages/monkeyscloud-monkeyslegion-session)
```

###  Alternatives

[cakephp/cakephp

The CakePHP framework

8.8k18.5M1.6k](/packages/cakephp-cakephp)[neos/flow

Flow Application Framework

862.0M451](/packages/neos-flow)[neos/flow-development-collection

Flow packages in a joined repository for pull requests.

144179.3k3](/packages/neos-flow-development-collection)[windwalker/framework

The next generation PHP framework.

25639.1k1](/packages/windwalker-framework)[selective/samesite-cookie

Secure your site with SameSite cookies

10144.0k](/packages/selective-samesite-cookie)[eliashaeussler/typo3-solver

Extension for TYPO3 CMS to extend TYPO3's exception handling with AI generated solutions

292.1k](/packages/eliashaeussler-typo3-solver)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
