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
36 changes: 35 additions & 1 deletion .github/workflows/php.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ jobs:
uses: shivammathur/setup-php@v2
with:
php-version: ${{ matrix.php }}
extensions: curl, intl, mbstring, pdo_sqlite
extensions: curl, intl, mbstring, mongodb, pcntl, pdo_sqlite, posix, sockets
tools: composer:v2
github-token: ${{ secrets.GITHUB_TOKEN }}
coverage: none
Expand All @@ -48,3 +48,37 @@ jobs:
else
echo 'No test script is declared for this package.'
fi

mongo-integration:
name: MongoDB integration
runs-on: ubuntu-24.04
services:
mongodb:
image: mongo:7.0
ports:
- 27017:27017
options: >-
--health-cmd "mongosh --quiet --eval 'db.adminCommand({ ping: 1 }).ok'"
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- name: Checkout
uses: actions/checkout@v7

- name: Set up PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.5'
extensions: mongodb
tools: composer:v2
github-token: ${{ secrets.GITHUB_TOKEN }}
coverage: none

- name: Install dependencies
run: composer install --prefer-dist --no-interaction --no-progress --no-scripts

- name: Run MongoDB integration test
run: composer test:mongo --no-interaction
env:
MONGODB_URI: mongodb://127.0.0.1:27017
31 changes: 9 additions & 22 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,31 +1,18 @@
# Changelog

All notable changes to this project will be documented in this file.
Notable changes are recorded here. This project follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) and [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [2.0.0] - Unreleased

## [1.0.0] - 2025-01-XX - LTS Release
This dependency change requires the next major package release: Engine 9 uses the Server 7 session API, which is not available in the Engine 8.1 / Server 4 dependency graph.

### Added
- Initial LTS release
- Full documentation
- Session management system
- Multiple session drivers (file, redis, database)
- Session encryption
- Session expiration handling
- Flash data support

### Security
- Secure session handling
- Session data encryption
- Compatibility with Triangle Engine 9 and Localzet Server 7.
- Runtime compatibility tests for Engine bootstrap, Server session handlers, and file-backed session round trips.
- A MongoDB integration test for session round trips and persistence behavior.

---

## [Unreleased]

### Planned
- Additional session drivers
- Session clustering support
- Performance optimizations
### Changed

- MongoDB session writes disable PHP object instantiation and reject malformed or non-array payloads.
- MongoDB session reads restore BSON documents and arrays as PHP arrays.
53 changes: 53 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,56 @@
<img src="https://img.shields.io/github/license/Triangle-org/Session?label=%D0%9B%D0%B8%D1%86%D0%B5%D0%BD%D0%B7%D0%B8%D1%8F" alt="Лицензия">
</a>
</p>

# Triangle Session

Triangle Session connects Engine applications to the HTTP session storage provided by Localzet Server. It includes file, Redis, Redis Cluster and MongoDB handlers and a `session()` helper for the current request.

## Requirements

- PHP 8.1 or later
- `triangle/engine` 9.x, which requires Localzet Server 7.1 or later

## Installation

```sh
composer require triangle/session:^2.0
```

Engine 9 loads `Triangle\Session\Bootstrap` with its built-in components. This compatibility update is for the next major release because Engine 8.1 resolves to Server 4 and does not provide the Server 7 session API used by this package. To copy the package configuration into an application that does not publish package configuration automatically, run `Triangle\Session\Install::install()` in the application installation context. The default storage driver is `file`; its path comes from `runtime_path('sessions')`.

## Using a session

The helper operates on the current request's Server session:

```php
session(['user_id' => 42]);

$userId = session('user_id');
$theme = session('preferences.theme', 'light');
```

The helper returns the current session when called without a key, reads values for string keys, and writes the supplied values when given an array. Session storage is request-scoped by Server; use scalar values and arrays. Objects restored from stored payloads are not instantiated.

## Storage drivers

| Driver | Additional requirement | Configuration key |
| --- | --- | --- |
| `file` | Writable runtime directory | `session.config.file` |
| `redis` | PHP Redis extension | `session.config.redis` |
| `redis_cluster` | PHP Redis extension and a configured Redis Cluster | `session.config.redis_cluster` |
| `mongo` | `mongodb/mongodb` and the PHP MongoDB extension | `session.config.mongo` |

Set `SESSION_TYPE` to the selected driver and provide its connection details through the environment or `config/session.php`. For HTTPS deployments, set `SESSION_COOKIE_SECURE=true`; configure the cookie domain and SameSite policy for the application’s deployment topology.

## Development checks

```sh
composer validate --strict --no-check-publish
composer test
composer audit --locked
```

The compatibility test exercises Engine bootstrap loading, Server session-handler contracts, file-backed round trips, and safe handling of serialized values. MongoDB and Redis network services are optional and are not started by this test.

Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved.
52 changes: 52 additions & 0 deletions README.ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Triangle Session

Triangle Session подключает HTTP-сессии Localzet Server к приложениям на Triangle Engine. В пакет входят обработчики для файлов, Redis, Redis Cluster и MongoDB, а также функция `session()` для доступа к сессии текущего запроса.

## Требования

- PHP 8.1 или новее
- `triangle/engine` версии 9.x, которая требует Localzet Server 7.1 или новее

## Установка

```sh
composer require triangle/session:^2.0
```

Engine 9 запускает `Triangle\Session\Bootstrap` вместе со встроенными компонентами. Это обновление совместимости предназначено для следующей основной версии: Engine 8.1 устанавливает Server 4, в котором нет используемого пакетом API сессий Server 7. Если приложение не публикует конфигурацию пакета автоматически, вызовите `Triangle\Session\Install::install()` в контексте установки приложения. По умолчанию используется файловое хранилище в каталоге `runtime_path('sessions')`.

## Работа с сессией

Функция работает с сессией текущего запроса:

```php
session(['user_id' => 42]);

$userId = session('user_id');
$theme = session('preferences.theme', 'light');
```

Вызов без ключа возвращает объект сессии, строковый ключ читает значение, массив записывает несколько значений. Хранилищем и временем жизни запроса управляет Server. Сохраняйте скаляры и массивы: объекты из сохранённого payload не создаются при чтении.

## Хранилища

| Драйвер | Дополнительное требование | Ключ конфигурации |
| --- | --- | --- |
| `file` | Доступный для записи каталог runtime | `session.config.file` |
| `redis` | PHP-расширение Redis | `session.config.redis` |
| `redis_cluster` | PHP-расширение Redis и настроенный Redis Cluster | `session.config.redis_cluster` |
| `mongo` | `mongodb/mongodb` и PHP-расширение MongoDB | `session.config.mongo` |

Укажите драйвер через `SESSION_TYPE`, а параметры подключения задайте в окружении или `config/session.php`. Для HTTPS включите `SESSION_COOKIE_SECURE=true`. Домен cookie и SameSite выберите с учётом схемы размещения приложения.

## Проверки разработки

```sh
composer validate --strict --no-check-publish
composer test
composer audit --locked
```

Тест совместимости проверяет загрузку Engine bootstrap, контракты обработчиков Server, файловый цикл чтения и записи и безопасную обработку сериализованных значений. MongoDB и Redis не запускаются: сетевые сервисы для теста не требуются.

Copyright © 2016-2026 [Localzet Group](https://www.localzet.com/). All rights reserved.
11 changes: 10 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,23 @@
},
"require": {
"php": "^8.1",
"triangle/engine": "^8.1"
"triangle/engine": "^9.0"
},
"require-dev": {
"ext-mongodb": "*",
"mongodb/mongodb": "^2.0"
},
"suggest": {
"ext-redis": "For RedisSessionHandler and RedisClusterSessionHandler",
"mongodb/mongodb": "For MongoSessionHandler"
},
"config": {
"platform": {
"php": "8.1.0"
}
},
"scripts": {
"test": "php tests/session-compatibility.php",
"test:mongo": "php tests/mongo-integration.php"
}
}
2 changes: 1 addition & 1 deletion src/Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2024 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Config/session.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2024 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Handlers/FileSessionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2024 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
18 changes: 14 additions & 4 deletions src/Handlers/MongoSessionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2024 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down Expand Up @@ -109,9 +109,14 @@ public function close(): bool
*/
public function read(string $sessionId): string
{
$session = $this->collection->findOne(['_id' => $sessionId]);
$session = $this->collection->findOne(
['_id' => $sessionId],
['typeMap' => ['root' => 'array', 'document' => 'array', 'array' => 'array']],
);
if ($session !== null) {
return serialize((array)$session);
$data = $session;
unset($data['_id'], $data['updated_at']);
return serialize($data);
}
return '';
}
Expand All @@ -121,7 +126,12 @@ public function read(string $sessionId): string
*/
public function write(string $sessionId, string $sessionData): bool
{
$session = ['_id' => $sessionId] + unserialize($sessionData);
$data = @unserialize($sessionData, ['allowed_classes' => false]);
if (!is_array($data)) {
return false;
}

$session = ['_id' => $sessionId] + $data;
$options = ['upsert' => true];
$this->collection->replaceOne(['_id' => $sessionId], $session, $options);
$this->updateTimestamp($sessionId);
Expand Down
2 changes: 1 addition & 1 deletion src/Handlers/RedisClusterSessionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2024 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Handlers/RedisSessionHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2024 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
2 changes: 1 addition & 1 deletion src/Install.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2024 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down
4 changes: 2 additions & 2 deletions src/functions.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* @link https://github.com/Triangle-org/Session
*
* @author Ivan Zorin <creator@localzet.com>
* @copyright Copyright (c) 2023-2024 Triangle Framework Team
* @copyright Copyright © 2016-2026 Localzet Group. All rights reserved.
* @license https://www.gnu.org/licenses/agpl-3.0 GNU Affero General Public License v3.0
*
* This program is free software: you can redistribute it and/or modify
Expand Down Expand Up @@ -56,4 +56,4 @@ function session(mixed $key = null, mixed $default = null): mixed
}
return $session->get($key, $default);
}
}
}
Loading