PHPackages                             zobayer/encapsula - 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. [API Development](/categories/api)
4. /
5. zobayer/encapsula

ActiveLibrary[API Development](/categories/api)

zobayer/encapsula
=================

Laravel API response encryption middleware with frontend decoding support.

v0.3.2(1mo ago)06↓100%MITPHPPHP ^8.2|^8.3CI failing

Since May 6Pushed 1mo agoCompare

[ Source](https://github.com/shudhuiami/Encapsula)[ Packagist](https://packagist.org/packages/zobayer/encapsula)[ Docs](https://github.com/shudhuiami/Encapsula)[ RSS](/packages/zobayer-encapsula/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (6)Versions (20)Used By (0)

Encapsula
=========

[](#encapsula)

Laravel API response encryption middleware with frontend decoding support.

Encapsula encrypts JSON API responses at the middleware level using AES-256-GCM authenticated encryption. The frontend receives an encrypted payload envelope and decrypts it before use. This adds a layer of obfuscation to API responses visible in browser developer tools, while keeping integration simple for Laravel APIs and modern frontend applications.

> **Important:** Encapsula does not replace HTTPS. TLS is still required for transport security. This package provides application-level payload encryption as an additional layer. Authenticated users can still access the decrypted data in their browser after the frontend decrypts it.

Packages
--------

[](#packages)

Encapsula has two package layers in the same repository:

PackageRegistry LinkPurposePath`zobayer/encapsula`Laravel backend middleware for protected API responsesrepository root`encapsula-client`JavaScript/TypeScript frontend decoder for Vue, React, Next.js, Nuxt, Vite, Axios, Fetch, and Node clients`packages/client`For simple projects without npm, standalone copy-paste helpers are kept in `frontend/`.

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 10, 11, 12, or 13
- OpenSSL extension with AES-256-GCM support
- Node.js/npm only if you want to use the optional frontend client package

Backend Installation
--------------------

[](#backend-installation)

Install the Laravel package:

```
composer require zobayer/encapsula
```

### Quick Setup Command (recommended)

[](#quick-setup-command-recommended)

You can scaffold the required `.env` values with:

```
php artisan encapsula:setup
```

Common usages:

```
# Static mode (default): prints env lines, including a freshly generated key
php artisan encapsula:setup --mode=static

# Session mode: prints env lines for handshake mode
php artisan encapsula:setup --mode=session --handshake

# Write into .env (won't overwrite existing keys)
php artisan encapsula:setup --mode=static --write

# Overwrite existing keys
php artisan encapsula:setup --mode=session --handshake --write --force
```

The service provider is auto-discovered. To register manually, add to `config/app.php`:

```
'providers' => [
    // ...
    Zobayer\Encapsula\EncapsulaServiceProvider::class,
],
```

### Publish Configuration

[](#publish-configuration)

```
php artisan vendor:publish --tag=encapsula-config
```

### Set Encryption Key

[](#set-encryption-key)

Add to your `.env` file:

```
ENCAPSULA_KEY=your-base64-encoded-32-byte-key
```

### Enable/Disable Encryption

[](#enabledisable-encryption)

To disable encryption globally at runtime (feature flag):

```
ENCAPSULA_ENABLED=false
```

Generate a key:

```
php -r "echo base64_encode(random_bytes(32));"
```

### Optional: Override Algorithm

[](#optional-override-algorithm)

```
ENCAPSULA_ALGORITHM=aes-256-gcm
```

### Optional: Session Key Handshake (no static frontend secret)

[](#optional-session-key-handshake-no-static-frontend-secret)

If you don't want to ship a long-lived `ENCAPSULA_KEY` in your frontend bundle, you can enable **session mode**. In this mode, the frontend establishes a **per-session** AES key using ECDH (P-256) + HKDF-SHA256, and the backend stores it in the server session.

Backend `.env`:

```
ENCAPSULA_ENABLED=true
ENCAPSULA_KEY_MODE=session
ENCAPSULA_HANDSHAKE_ENABLED=true
ENCAPSULA_KEY=
```

Important:

- The handshake route must run under **session middleware** (default is `web`).
- You should add your own auth middleware to the handshake route via `config/encapsula.php` if needed.
- After the handshake succeeds, subsequent responses encrypted by `encapsula.encrypt` will use the **session key**.

Frontend Installation
---------------------

[](#frontend-installation)

For npm-based projects, install the client package:

```
npm install encapsula-client
```

Use this package in Vue, React, Next.js, Nuxt, Vite, Axios, Fetch, or Node-based frontend projects.

For non-npm projects, use the standalone helper files in:

```
frontend/
packages/client/examples/vanilla-js/
```

Quick Start
-----------

[](#quick-start)

### 1. Apply Middleware to Laravel Routes

[](#1-apply-middleware-to-laravel-routes)

```
// In routes/api.php
Route::middleware('encapsula.encrypt')->group(function () {
    Route::get('/users', [UserController::class, 'index']);
    Route::get('/orders', [OrderController::class, 'index']);
});
```

### 2. Encrypted Response Format

[](#2-encrypted-response-format)

When middleware is active, JSON responses are wrapped in an encrypted envelope:

```
{
    "encrypted": true,
    "payload": "base64-encoded-ciphertext",
    "iv": "base64-encoded-iv",
    "tag": "base64-encoded-auth-tag",
    "alg": "AES-256-GCM"
}
```

### 3. Decode in Frontend with the npm Package

[](#3-decode-in-frontend-with-the-npm-package)

```
import { decodeEncapsulaResponse } from 'encapsula-client';
import { createEncapsulaSessionKey } from 'encapsula-client';

const key = await createEncapsulaSessionKey({ handshakeUrl: '/encapsula/handshake' });
const response = await fetch('/api/users');
const body = await response.json();

const users = await decodeEncapsulaResponse(body, {
  key,
});
```

### 4. Axios Usage

[](#4-axios-usage)

```
import axios from 'axios';
import { attachEncapsulaAxiosInterceptor } from 'encapsula-client';

const api = axios.create({
  baseURL: '/api',
});

attachEncapsulaAxiosInterceptor(api, {
  key: import.meta.env.VITE_ENCAPSULA_KEY,
});

const { data: users } = await api.get('/users');
```

### 5. Fetch Wrapper Usage

[](#5-fetch-wrapper-usage)

```
import { createEncapsulaFetch } from 'encapsula-client';

const apiFetch = createEncapsulaFetch({
  key: import.meta.env.VITE_ENCAPSULA_KEY,
});

const users = await apiFetch('/api/users');
```

### 6. Node Usage

[](#6-node-usage)

```
import { decodeEncapsulaResponse } from 'encapsula-client';

const response = await fetch('https://example.com/api/users');
const body = await response.json();

const users = await decodeEncapsulaResponse(body, {
  key: process.env.ENCAPSULA_KEY,
});
```

### 7. Vanilla JavaScript Usage

[](#7-vanilla-javascript-usage)

For projects without npm, copy the standalone helper from:

```
packages/client/examples/vanilla-js/encapsula-helper.js
```

Example:

```

  fetch('/api/users')
    .then((response) => response.json())
    .then((body) => Encapsula.decode(body, 'your-base64-key'))
    .then((users) => console.log(users));

```

Configuration
-------------

[](#configuration)

After publishing (`php artisan vendor:publish --tag=encapsula-config`), edit `config/encapsula.php`:

OptionTypeDefaultDescription`enabled``bool``true`Enable or disable response encryption globally.`key_mode``string``'static'`Key source: `'static'` (single key) or `'session'` (derived per session).`key``string``env('ENCAPSULA_KEY')`Base64-encoded 32-byte encryption key (used when `key_mode=static`).`handshake.enabled``bool``false`Enable the session handshake endpoint (required when `key_mode=session`).`handshake.path``string``'/encapsula/handshake'`Path for the handshake route.`handshake.middleware``array``['web']`Middleware applied to handshake route (must include sessions).`handshake.session_key``string``'encapsula.session_key'`Session key name used to store derived base64 AES key.`algorithm``string``'aes-256-gcm'`OpenSSL cipher algorithm (`ENCAPSULA_ALGORITHM`).`exclude``array``[]`Route name patterns to skip encryption (e.g. `'login'`, `'health.*'`).`envelope.encrypted_field``string``'encrypted'`Name of the boolean flag field in the envelope.`envelope.payload_field``string``'payload'`Name of the ciphertext field.`envelope.iv_field``string``'iv'`Name of the initialization vector field.`envelope.tag_field``string``'tag'`Name of the authentication tag field.`envelope.algorithm_field``string``'alg'`Name of the algorithm identifier field.Middleware Behavior
-------------------

[](#middleware-behavior)

The middleware:

- **Encrypts** JSON responses (`Content-Type: application/json`).
- **Skips** redirects, streamed responses, binary/file downloads, empty responses, and non-JSON content.
- **Skips** routes matching the `exclude` patterns.
- **Passes through** unchanged when `enabled` is `false` or no key is configured.

Security Limitations
--------------------

[](#security-limitations)

- **Not a replacement for HTTPS.** Always use TLS for transport-layer security.
- **Browser-side decryption** means authenticated users can access decrypted data. This prevents casual inspection of network responses but does not hide data from the authenticated user.
- **Frontend keys are visible** in built frontend apps when they are shipped to the browser. If you want to avoid shipping a long-lived key, use the optional **session handshake mode**.
- **Key management** is the application's responsibility. Rotate keys carefully and consider a key rotation strategy for production.
- **This is obfuscation, not access control.** Use proper authorization (policies, gates, scopes) to restrict which data is returned by your API.

Development
-----------

[](#development)

```
# Install PHP dependencies
composer install

# Run PHP tests
vendor/bin/phpunit

# Run static analysis
vendor/bin/phpstan analyse

# Check PHP code style
vendor/bin/pint --test

# Fix PHP code style
vendor/bin/pint

# Work on frontend client
cd packages/client
npm install
npm run typecheck
npm test
npm run build
```

License
-------

[](#license)

MIT. See [LICENSE](LICENSE) for details.

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance93

Actively maintained with recent releases

Popularity6

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity47

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 89.5% 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 ~0 days

Total

5

Last Release

34d ago

PHP version history (2 changes)v0.1.0PHP ^8.2

v0.2.0PHP ^8.2|^8.3

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/98706?v=4)[Zobayer Hasan](/maintainers/zobayer)[@zobayer](https://github.com/zobayer)

---

Top Contributors

[![shudhuiami](https://avatars.githubusercontent.com/u/29300834?v=4)](https://github.com/shudhuiami "shudhuiami (17 commits)")[![cursoragent](https://avatars.githubusercontent.com/u/199161495?v=4)](https://github.com/cursoragent "cursoragent (2 commits)")

---

Tags

middlewareapilaravelsecurityencryptionAES-GCMresponse-encryptionfrontend-decoding

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StyleLaravel Pint

### Embed Badge

![Health badge](/badges/zobayer-encapsula/health.svg)

```
[![Health](https://phpackages.com/badges/zobayer-encapsula/health.svg)](https://phpackages.com/packages/zobayer-encapsula)
```

###  Alternatives

[propaganistas/laravel-disposable-email

Disposable email validator

6012.9M7](/packages/propaganistas-laravel-disposable-email)[shahghasiadil/laravel-api-versioning

Elegant attribute-based API versioning solution for Laravel applications with built-in deprecation management and version inheritance

2915.0k](/packages/shahghasiadil-laravel-api-versioning)[jasara/php-amzn-selling-partner-api

A fluent interface for Amazon's Selling Partner API in PHP

1348.1k1](/packages/jasara-php-amzn-selling-partner-api)[imliam/laravel-throttle-simultaneous-requests

Throttle the current user's requests based on how many requests are currently being executed.

4623.0k](/packages/imliam-laravel-throttle-simultaneous-requests)

PHPackages © 2026

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