PHPackages                             teoprayoga/teobiefy-laravel-api-response - 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. [Security](/categories/security)
4. /
5. teoprayoga/teobiefy-laravel-api-response

ActiveLibrary[Security](/categories/security)

teoprayoga/teobiefy-laravel-api-response
========================================

Laravel API response helpers with server-configured payload compression and encryption.

v0.3.0(1mo ago)0642MITPHPPHP ^8.1CI failing

Since Jun 3Pushed 1mo agoCompare

[ Source](https://github.com/teoprayoga/teobiefy-laravel-api-response)[ Packagist](https://packagist.org/packages/teoprayoga/teobiefy-laravel-api-response)[ Docs](https://github.com/teoprayoga/teobiefy-laravel-api-response)[ RSS](/packages/teoprayoga-teobiefy-laravel-api-response/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (5)Versions (3)Used By (0)

Teobiefy Laravel API Response
=============================

[](#teobiefy-laravel-api-response)

Laravel API response helpers with server-configured payload **compression** (zstd) and **authenticated encryption** (xchacha20-poly1305 / chacha20-poly1305-ietf via libsodium).

Inspired by [`obiefy/api-response`](https://github.com/obiefy/api-response), with first-class support for per-route payload profiles (plain / compressed / encrypted / compressed\_encrypted).

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

[](#requirements)

- PHP `^8.1`
- Laravel 10, 11, 12, or 13
- `ext-json`
- `ext-zstd` only when `teobiefy.compression.driver` is `zstd`
- `ext-sodium` (recommended) **or** `paragonie/sodium_compat` (optional fallback)

Installation
------------

[](#installation)

```
composer require teoprayoga/teobiefy-laravel-api-response
```

The service provider and `API` facade are auto-discovered.

Publish the config to `config/teobiefy.php`:

```
php artisan vendor:publish --tag=api-response
```

Optionally publish translations:

```
php artisan vendor:publish --tag=api-response-lang
```

Quick start
-----------

[](#quick-start)

```
return api()->ok('Success message', $data);
return api()->response(400, 'Bad request', $errors);
return api()->validation('Validation failed', $errors);
return api()->notFound();
return api()->forbidden();
return api()->error();
```

Global helpers `ok()` and `success()` are also available.

Payload profiles
----------------

[](#payload-profiles)

Each request/response can be transformed by a named profile resolved from the matched route:

ProfileBehavior`plain`No transformation`compressed`Optional zstd compression on `data``encrypted`libsodium AEAD on `data`, replaced with `data_enc` + `nonce``compressed_encrypted`compress, then encrypt`signed`HMAC-SHA256 tag attached as `sig`; integrity without encryption`compressed_signed`compress, then attach HMAC tagConfigure per-route in `config/teobiefy.php`:

```
'response' => [
    'default_profile' => 'plain',
    'route_profiles' => [
        'api/v1/users/*'   => 'encrypted',
        'api/v1/reports/*' => 'compressed_encrypted',
    ],
],

'request' => [
    'default_profile' => 'plain',
    'route_profiles' => [
        'api/v1/auth/*' => 'encrypted',
    ],
],
```

Inbound decryption is handled by `PayloadDecryptMiddleware` — register it in your HTTP kernel for routes that accept encrypted payloads.

Transformed response/request envelopes include:

FieldMeaning`data_comp`Base64 JSON payload for compressed and signed profiles`data_enc`Base64 encrypted payload for encrypted profiles`nonce`Base64 nonce used by encrypted profiles`cipher`Encryption driver recorded in the payload`compression``none` or `zstd`, so receivers know whether decompression is required`kid`Encryption key id; emitted only when key rotation is configured`sig` / `sig_alg` / `sig_kid`HMAC tag, algorithm, and signing key id for signed profilesProfile via PHP attribute
-------------------------

[](#profile-via-php-attribute)

In addition to the `route_profiles` map, you can mark a controller method or controller class directly:

```
use Teoprayoga\TeobiefyLaravelApiResponse\Attributes\RequestProfile;
use Teoprayoga\TeobiefyLaravelApiResponse\Attributes\ResponseProfile;
use Teoprayoga\TeobiefyLaravelApiResponse\Profile;

#[RequestProfile(Profile::ENCRYPTED)]
class UserController
{
    #[ResponseProfile(Profile::COMPRESSED_ENCRYPTED)]
    public function show(int $id) { /* ... */ }
}
```

Resolution order: **attribute on method → attribute on class → `route_profiles`pattern match → `default_profile`**. Closure routes fall through to the config pattern stage.

Key rotation
------------

[](#key-rotation)

To rotate the encryption key without breaking outstanding payloads, configure a named keyring and pick an active key id:

```
'encryption' => [
    'driver' => 'xchacha20-poly1305',
    'key' => env('TEOBIEFY_ENCRYPTION_KEY'),               // legacy fallback
    'keys' => [
        'v1' => env('TEOBIEFY_ENCRYPTION_KEY_V1'),
        'v2' => env('TEOBIEFY_ENCRYPTION_KEY_V2'),
    ],
    'active' => env('TEOBIEFY_ENCRYPTION_ACTIVE_KID'),     // e.g. 'v2'
],
```

Envelopes encrypted with `active = 'v2'` carry `"kid": "v2"`; rotate by adding `v3` to `keys` and setting `active = 'v3'`. Older envelopes with `kid = v1` or `kid = v2` continue to decrypt as long as those keys remain in `keys`.

If `keys` is empty and `active` is null, the package runs in legacy single-key mode and the envelope omits `kid` (byte-for-byte identical with pre-rotation deployments).

Response signing
----------------

[](#response-signing)

Use `signed` / `compressed_signed` profiles when you want integrity without confidentiality (e.g. publicly cacheable responses that must not be tampered with).

```
'signing' => [
    'algorithm' => 'hmac-sha256',
    'key' => env('TEOBIEFY_SIGNING_KEY'),                  // legacy fallback
    'keys' => [
        'v1' => env('TEOBIEFY_SIGNING_KEY_V1'),
    ],
    'active' => env('TEOBIEFY_SIGNING_ACTIVE_KID'),
],
```

Generate a key:

```
php artisan teobiefy:signing-key
```

On inbound signed requests, `PayloadDecryptMiddleware` verifies before decompression and rejects with **HTTP 401** plus `WWW-Authenticate: TeobiefySig` on tampering, unknown `sig_kid`, or an algorithm that is not in the allowlist.

AEAD-encrypted profiles already carry an integrity tag, so the package intentionally does not ship an `encrypted_signed` profile.

Replay protection
-----------------

[](#replay-protection)

Optional, off by default. When enabled, encrypted and signed payloads wrap their inner content with a `{ts, rnonce, payload}` envelope **inside** the AEAD/HMAC scope, and inbound requests are rejected if (a) the timestamp falls outside the configured window or (b) the random nonce has already been seen. Plain and compressed-only profiles are never wrapped (no integrity guarantee).

```
'replay_protection' => [
    'enabled' => env('TEOBIEFY_REPLAY_PROTECTION', false),
    'cache_store' => null,            // null = default cache
    'cache_prefix' => 'teobiefy:rp:',
    'window_seconds' => 300,
    'nonce_ttl_seconds' => 600,       // must be >= 2 * window_seconds
],
```

Replay failures are reported as **HTTP 409 Conflict**. The nonce store uses the Laravel cache (`Repository::add()` for atomic check-and-set), so the `cache_store` should be one that is shared across workers in production (e.g. Redis); the default `array` driver only protects within a single process.

Encryption key
--------------

[](#encryption-key)

Set a base64-encoded 32-byte key in `.env`:

```
TEOBIEFY_ENCRYPTION_KEY=base64:...
```

Generate one:

```
php artisan teobiefy:key
```

Config reference
----------------

[](#config-reference)

See [`config/teobiefy.php`](config/teobiefy.php) for all options (response keys, status stringification, compression, encryption, signing, replay\_protection, sodium\_compat fallback toggle, etc.).

Compression options:

```
'compression' => [
    'driver' => 'zstd', // zstd or none
    'level' => 3,
    'min_bytes' => 1024,
    'max_decompressed_bytes' => 10485760,
],
```

Set `driver` to `none` to keep compressed profiles in the same envelope format without requiring `ext-zstd`. `min_bytes` controls the smallest JSON payload that will be zstd-compressed; smaller payloads are sent with `compression: none`.

Encryption uses `TEOBIEFY_ENCRYPTION_KEY` by default:

```
'encryption' => [
    'driver' => 'xchacha20-poly1305',
    'key' => env('TEOBIEFY_ENCRYPTION_KEY'),
    'allow_sodium_compat_fallback' => false,
],
```

Migrating from `config/api.php`
-------------------------------

[](#migrating-from-configapiphp)

This release renames the package config namespace from `api` to `teobiefy` to avoid colliding with application config. Move any previous package settings from `config/api.php` to `config/teobiefy.php`, then update custom runtime reads from `config('api...')` to `config('teobiefy...')`.

Support
-------

[](#support)

If this package saves you time, consider supporting its development 🙏

[![Sponsor on GitHub](https://camo.githubusercontent.com/a51267a55d529338abcb445f92a41401ee9e4395a6c6b9019ab37ceb12149781/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f53706f6e736f722d4769744875622d4541344141413f6c6f676f3d67697468756273706f6e736f7273266c6f676f436f6c6f723d7768697465)](https://github.com/sponsors/teoprayoga)[![Ko-fi](https://camo.githubusercontent.com/339aff6082a7504833522141edaa717cb414682bddf2331cd8ec2f3dfc297702/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4b6f2d2d66692d4275792532306d6525323061253230636f666665652d4646354535423f6c6f676f3d6b6f6669266c6f676f436f6c6f723d7768697465)](https://ko-fi.com/teoprayoga)[![Saweria](https://camo.githubusercontent.com/5c6c56e0d7f301adf58821c163b187de18e8de932ba74bf82c9d92725e278446/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f536177657269612d44756b756e672d4641414230303f6c6f676f436f6c6f723d7768697465)](https://saweria.co/teoprayoga)

Maintained by **Teo Prayoga** ([@teoprayoga](https://github.com/teoprayoga)).

License
-------

[](#license)

MIT — see [LICENSE](LICENSE).

###  Health Score

39

—

LowBetter than 84% of packages

Maintenance91

Actively maintained with recent releases

Popularity19

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity33

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% 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

2

Last Release

51d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/36a7d4a48df13c4d526004c150f3728c4c4126f132f6740b8603a3255ea80ba8?d=identicon)[teoprayoga](/maintainers/teoprayoga)

---

Top Contributors

[![teoprayoga](https://avatars.githubusercontent.com/u/19910443?v=4)](https://github.com/teoprayoga "teoprayoga (11 commits)")

---

Tags

laravelencryptionsigninglibsodiumXChaCha20-Poly1305hmackey-rotationapi-responsezstdreplay-protection

### Embed Badge

![Health badge](/badges/teoprayoga-teobiefy-laravel-api-response/health.svg)

```
[![Health](https://phpackages.com/badges/teoprayoga-teobiefy-laravel-api-response/health.svg)](https://phpackages.com/packages/teoprayoga-teobiefy-laravel-api-response)
```

###  Alternatives

[spatie/laravel-responsecache

Speed up a Laravel application by caching the entire response

2.8k9.0M69](/packages/spatie-laravel-responsecache)[laravel/pulse

Laravel Pulse is a real-time application performance monitoring tool and dashboard for your Laravel application.

1.7k15.1M136](/packages/laravel-pulse)[mike-bronner/laravel-model-caching

Automatic caching for Eloquent models.

2.4k96.5k1](/packages/mike-bronner-laravel-model-caching)[roots/acorn

Framework for Roots WordPress projects built with Laravel components.

9762.4M133](/packages/roots-acorn)[laravel/mcp

Rapidly build MCP servers for your Laravel applications.

77922.3M186](/packages/laravel-mcp)[propaganistas/laravel-disposable-email

Disposable email validator

6023.0M7](/packages/propaganistas-laravel-disposable-email)

PHPackages © 2026

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