Search by

hibira-io / symfony-bundle

deflinhec

Hibira realtime for Symfony: UX Turbo Streams and Messenger without running a Mercure hub, plus channel auth, webhooks and push

Package info

github.com/hibira-io/symfony

Homepage

Documentation

Type:symfony-bundle

pkg:composer/hibira-io/symfony-bundle

Statistics

Installs: 6

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.5.0 2026-11-30 16:53 UTC

README

ci

Realtime Symfony apps on Hibira, without running a Mercure hub. Symfony UX Turbo Streams, Doctrine #[Broadcast] entities and Symfony Messenger send their updates to Hibira, and the browser receives them over WebSockets.

Desktop Phone
Live board example, desktop Live board example, phone, dark

What the bundle gives you:

  • UX Turbo transport. #[Broadcast] entities, turbo_stream_listen() and turbo_stream_from() / <twig:Turbo:Stream:From> work as they do with Mercure, with the transport named hibira.
  • Messenger. Every event is a PublishEvent message. Route it to an async transport and a worker sends it, so a slow network never slows the request that saved the entity.
  • Signed channels. Each Turbo topic is a private channel that a browser can only join with the signature the page rendered for it.
  • Size limit handling. A stream over your plan's event size limit becomes a Turbo page refresh instead of an error.
  • Channel auth, webhooks and push. POST /hibira/auth for your own private and presence channels, a verified webhook route that dispatches Symfony events, and push user tokens for iOS, Android and the web.
  • bin/console hibira:check to check the credentials and connection.

Supports Symfony 6.4, 7.x and 8.x (PHP 8.1+), UX Turbo 2 and 3.

Install

composer require hibira-io/symfony-bundle

Symfony Flex enables the bundle, adds the Stimulus controller to assets/controllers.json and pusher-js to your import map (or package.json with Webpack Encore).

Copy the app ID, key and secret from your app page on hibira.io/portal into .env.local (the Free plan needs no card). The secret is shown once, when you create the app or rotate it.

HIBIRA_APP_ID=your-app-id
HIBIRA_APP_KEY=your-app-key
HIBIRA_APP_SECRET=your-app-secret

Import the routes:

# config/routes/hibira.yaml
hibira:
    resource: '@HibiraSymfonyBundle/config/routes.php'
    prefix: /hibira

Then check the setup:

php bin/console hibira:check

On your app page, add your site's origin (for example https://shop.example.com) to Allowed origins, or browsers can't connect.

Configuration

Everything is optional. These are the defaults:

# config/packages/hibira.yaml
hibira:
    app_id: '%env(default::HIBIRA_APP_ID)%'
    key: '%env(default::HIBIRA_APP_KEY)%'
    secret: '%env(default::HIBIRA_APP_SECRET)%'
    host: ws.hibira.io        # the WebSocket host on your app page
    port: 443
    scheme: https
    turbo:
        enabled: auto         # on when symfony/ux-turbo is installed
        oversize: refresh     # or "throw"
    messenger:
        enabled: auto         # on when symfony/messenger is installed
        bus: messenger.default_bus
    live_chat:
        workspace: '%env(default::HIBIRA_LIVECHAT_WORKSPACE)%'
        identity_secret: '%env(default::HIBIRA_LIVECHAT_IDENTITY_SECRET)%'
    push:
        instance_id: '%env(default::HIBIRA_PUSH_INSTANCE_ID)%'
        secret_key: '%env(default::HIBIRA_PUSH_SECRET_KEY)%'
        endpoint: https://ws.hibira.io

host, port and scheme take env placeholders too, such as '%env(int:HIBIRA_PORT)%'.

Turbo Streams

Mark an entity with #[Broadcast] and give it a stream template, exactly as in the UX Turbo docs:

use Symfony\UX\Turbo\Attribute\Broadcast;

#[ORM\Entity]
#[Broadcast]
class Message
{
    // ...
}
{# templates/broadcast/Message.stream.html.twig #}
{% block create %}
<turbo-stream action="append" target="messages">
    <template>{{ include('message/_message.html.twig', { message: entity }) }}</template>
</turbo-stream>
{% endblock %}

{% block remove %}
<turbo-stream action="remove" target="message_{{ id }}"></turbo-stream>
{% endblock %}

Listen in a page. A class name follows every entity of that class, an entity follows that one entity, and any other string is a topic of your own:

{# UX Turbo 2 and 3 #}
<ul id="messages" {{ turbo_stream_listen('App\\Entity\\Message') }}>

{# UX Turbo 3.1+ #}
{{ turbo_stream_from(message) }}
<twig:Turbo:Stream:From topics="chat" />

Without Mercure installed, hibira becomes UX Turbo's default transport. With both, pass it by name: turbo_stream_listen(topic, 'hibira'), or set turbo.default_transport: hibira. #[Broadcast(transports: ['hibira'])] limits an entity to Hibira.

Send a stream from anywhere, for example a Messenger handler reporting progress:

public function __construct(private Hibira $hibira) {}

$this->hibira->turboStream('import-42', '<turbo-stream action="update" target="progress"><template>80%</template></turbo-stream>');

Each topic becomes the private channel private-turbo-<sha256(topic)>, and the page carries an HMAC of that name, so a browser can't subscribe to a topic its page didn't render. Free plans take events up to 4 KB, Hobby and Starter 10 KB. A stream over the limit is replaced by <turbo-stream action="refresh">, which reloads the page in place (set turbo.oversize: throw to get a PayloadTooLargeException instead).

Messenger

Hibira::publish() and every Turbo broadcast dispatch Hibira\SymfonyBundle\Message\PublishEvent. With no routing it is handled during the request. Route it to a transport to send events from a worker:

# config/packages/messenger.yaml
framework:
    messenger:
        transports:
            async: '%env(MESSENGER_TRANSPORT_DSN)%'
        routing:
            Hibira\SymfonyBundle\Message\PublishEvent: async
php bin/console messenger:consume async

Hibira::trigger() always sends right away.

Your own channels

use Hibira\SymfonyBundle\Hibira;

$hibira->publish('private-orders.42', 'shipped', ['id' => 42]);

Private and presence channels are authorized by POST /hibira/auth, which asks your listeners. Nobody gets in until a listener calls allow():

use Hibira\SymfonyBundle\Event\ChannelAuthorizationEvent;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;

#[AsEventListener]
final class AuthorizeChannels
{
    public function __invoke(ChannelAuthorizationEvent $event): void
    {
        if ($event->channel === 'private-orders.'.$event->user?->getId()) {
            $event->allow();
        }

        if ($event->channel === 'presence-team' && $event->user !== null) {
            // Member ID defaults to the user identifier.
            $event->allow(memberInfo: ['name' => $event->user->getName()]);
        }
    }
}

In the browser, add {{ hibira_meta_tags() }} to your layout's <head> and use the shared client:

import { hibira } from "@hibira-io/symfony-bundle/hibira.js"

hibira().subscribe("private-orders.42").bind("shipped", (order) => console.log(order))

With AssetMapper, add the module to importmap.php once: '@hibira-io/symfony-bundle/hibira.js' => ['path' => '@hibira-io/symfony-bundle/hibira.js'].

Webhooks

Point your app's webhook at https://your-site/hibira/webhook. The bundle checks X-Pusher-Signature (and, during a secret rotation, X-Hibira-Previous-Signature) and dispatches one WebhookReceivedEvent per event:

#[AsEventListener]
public function onWebhook(WebhookReceivedEvent $event): void
{
    if ($event->name === 'member_removed') {
        // $event->channel, $event->payload['user_id']
    }
}

Live Chat

Put the Hibira Live Chat widget on your pages, and let signed-in users chat as themselves. In your base template, before </body>:

{{ hibira_live_chat() }}
{# options: {{ hibira_live_chat({color: '#0a7', lang: 'ja', launcher: false, nonce: csp_nonce('script')}) }} #}

Set HIBIRA_LIVECHAT_WORKSPACE (or hibira.live_chat.workspace) to the workspace ID from Live Chat › Settings › Widget. With HIBIRA_LIVECHAT_IDENTITY_SECRET set too (Verified visitors, Starter plan and up), the signed-in user is sent with data-user-hash, an HMAC of their ID, so the inbox shows their name and email and nobody can pretend to be them. The ID is getId() (or getUserIdentifier()), the name getFullName() or getName(), the email getEmail(); change it with LiveChat::describeUserUsing(). In an SPA, the LiveChat service's identity($user) gives the fields for HibiraLiveChat.identify().

Push notifications

composer require pusher/pusher-push-notifications
HIBIRA_PUSH_INSTANCE_ID=your-instance-id
HIBIRA_PUSH_SECRET_KEY=your-secret-key
$hibira->push()->publishToUsers(['ada'], [
    'web' => ['notification' => ['title' => 'Order shipped', 'deep_link' => 'https://shop.example.com/orders/42']],
]);

GET /hibira/push/token?user_id=... returns a user token for the signed-in user, for setUserId() in the web, Android and iOS SDKs.

Waiting room

Put a Hibira waiting room in front of a ticket drop or launch page with the #[WaitingRoom] attribute (on a controller method or class):

use Hibira\SymfonyBundle\WaitingRoom\WaitingRoom;
use Hibira\SymfonyBundle\WaitingRoom\WaitingRoomPass;

#[Route('/drop/{id}')]
#[WaitingRoom('presale')]
public function drop(Request $request): Response
{
    $pass = $request->attributes->get('hibira_pass'); // WaitingRoomPass: number, ticketId, expiresAt
    // ...
}

Or protect path prefixes:

# config/packages/hibira.yaml
hibira:
    waiting_room:
        paths: { '/drop': presale }
        # lang: ja
        # previous_secret: '%env(HIBIRA_PREVIOUS_SECRET)%'
        # fail_open: true          # let visitors in if the waiting page can't be reached
        # fail_open_timeout: 1.5

With fail_open, a visitor without a pass is let through (request attribute hibira_fail_open is true) when the waiting page doesn't answer within fail_open_timeout seconds or answers with a 5xx. One check per room is kept for 15 seconds.

Visitors without a pass are redirected to the hosted queue page (non-GET requests get a 403). When it's their turn they come back with a signed pass, which is checked and kept in an HttpOnly cookie. Create the room (rate, start time, return_urls) with the waiting rooms API. A pass is valid for 30 minutes by default and works in any browser; if each queue number may check out once, record $pass->ticketId and refuse a repeat. WaitingRooms::verifyPass($token, $secret, 'presale') checks a pass anywhere.

Approvals

Ask a person for a decision from a controller, a Messenger handler or an agent (Hibira Approvals), then act on the answer:

$approval = $hibira->requestApproval('Refund order #1042 for $89?', [
    'details' => 'Customer says the parcel arrived damaged.',
    'options' => ['Refund', 'Decline'],     // the first option approves
    'channel' => 'private-ops',             // optional: an "approval" event on request and decision
    'expires_in_minutes' => 120,
]);
// share $approval['url'] with whoever decides, then
$approval = $hibira->waitForApproval($approval['approval_id'], timeout: 600);
if ($approval['status'] === 'approved') {
    $refunds->refund($order);
}

$hibira->approval($id, wait: 25) reads one status, holding the request up to 25 seconds until it is answered. API errors throw ApprovalException (getCode() is the HTTP status). When an approver asks a question instead of deciding ($approval['awaiting_reply']), answer with $hibira->replyToApproval($id, '...'). approvers, quorum and callback_url are passed through for Approvals workspaces.

Chat API

Conversations with stored history, read receipts and offline push (Chat API, in beta per account), from $hibira->chat():

$chat = $hibira->chat();
$chat->putConversation('order-1042', ['name' => 'Order #1042', 'members' => ['buyer-7', 'seller-3']]);
$chat->sendMessage('order-1042', 'seller-3', 'Shipped today!', ['push' => 'offline']);
$chat->systemMessage('order-1042', 'Tracking number added');

$page = $chat->listMessages('order-1042', after: 0, limit: 50);
$chat->markRead('order-1042', 'buyer-7', seq: 12);
$inbox = $chat->userConversations('buyer-7', limit: 20);

getConversation(), deleteConversation(), addMembers() and removeMember() cover the rest, and $chat->request('POST', '/conversations/order-1042/typing') reaches any other route, signed. Clients receive chat.* events on #server-to-user-<user_id> after pusher.signin. Errors throw ChatException (getCode() is the HTTP status). The reference is https://hibira.io/chat-api/reference.

Coming from Mercure

Mercure Hibira
symfony/mercure-bundle and a hub to run hibira-io/symfony-bundle, hosted
MERCURE_URL, MERCURE_PUBLIC_URL, MERCURE_JWT_SECRET HIBIRA_APP_ID, HIBIRA_APP_KEY, HIBIRA_APP_SECRET
turbo_stream_listen(topic) unchanged (transport hibira)
#[Broadcast] unchanged
HubInterface::publish(new Update(...)) Hibira::turboStream() or Hibira::publish()
Update routed through Messenger PublishEvent routed through Messenger
Private updates with JWT cookies Signed private channels, ChannelAuthorizationEvent

Example

example/ is a live board on FrankenPHP: Doctrine #[Broadcast] → Messenger worker → Hibira → Turbo Streams. Put your credentials in example/.env.local, then:

docker compose -f example/compose.yaml up --build

and open http://localhost:8000 in two windows.

Development

composer install
vendor/bin/phpunit

中文摘要

hibira-io/symfony-bundle 讓 Symfony 專案不用自己架 Mercure hub,就能用 Hibira 推送即時更新:

  • UX Turbo:#[Broadcast] 實體、turbo_stream_listen()、 turbo_stream_from() 照原本寫法使用,傳輸名稱為 hibira。每個 topic 都是帶簽章的私有頻道。超過方案單一事件大小上限(Free 4 KB)時,自動改送 Turbo 頁面重新整理。

  • Messenger:所有事件都是 PublishEvent 訊息,路由到 async transport 就會改由 worker 發送。

  • 頻道授權、Webhook、推播:POST /hibira/auth(以 ChannelAuthorizationEvent 決定)、驗證簽章的 webhook 路由(派發 WebhookReceivedEvent)、推播 user token。

  • Live Chat:在 base 模板加 {{ hibira_live_chat() }} 就會放上 Hibira Live Chat 聊天視窗;設定 identity secret 後,登入使用者以 HMAC 簽名的本人身分聊天。

  • 安裝:composer require hibira-io/symfony-bundle,在 .env.local 填入 HIBIRA_APP_ID / HIBIRA_APP_KEY / HIBIRA_APP_SECRET,匯入路由後執行 php bin/console hibira:check。記得在應用頁面的 Allowed origins 加入網站網域。

  • 支援 Symfony 6.4、7.x、8.x(PHP 8.1+),UX Turbo 2 與 3。 example/ 是跑在 FrankenPHP 上的即時留言板範例。

  • 等候室(waiting room):在 controller 加 #[WaitingRoom('presale')],或在 hibira.waiting_room.paths 設定路徑,沒有 pass 的訪客會被導到 Hibira 託管的排隊頁,輪到時帶著簽名 pass 回來並存成 HttpOnly cookie。設 fail_open: true 後,等候頁連不上時(逾時、網路錯誤或 5xx)會直接放行訪客。

  • Approvals:$hibira->requestApproval() 發出需要人決定的請求,把回傳的 url 分享給決策者,再用 waitForApproval() 等待結果(approved、rejected 或 expired)。

  • Chat API:$hibira->chat() 建立對話、以成員身分發訊息、讀取歷史、標記已讀與查詢使用者的對話列表;錯誤會丟出 ChatException。