Search by

masilia / ibexa-consent

masilia

Cookie consent for the front sites of Ibexa 5: one policy per site of the registry, texts in the language of the siteaccess, scripts of other packages blocked until accepted, themable banner

Package info

github.com/MasiliaLabs/ibexa-consent

Type:ibexa-bundle

pkg:composer/masilia/ibexa-consent

Statistics

Installs: 3

Dependents: 0

Suggesters: 1

Stars: 0

Open Issues: 0

0.2.0 2026-11-26 16:39 UTC

README

Cookie consent for the front sites of Ibexa 5. One policy per site of the masilia/ibexa-sites registry, texts in the language of the siteaccess, scripts of other packages held back until the visitor accepts their category, a banner and a preferences panel (React) that a theme can restyle.

Admin → Cookie manager lists the policies of the sites the user may see, with where each site is served (each address with the language it serves) and where the policy stands (no policy, draft, published, changes not published). A line opens the editor of that site (/consent/<site>), and a site without a policy gets one from the list.

Permissions

The roles of the user decide, from whichever admin siteaccess he works in: the policy masilia_consent with the function view (see the list and open a policy, read only) or manage (change, publish, import; it includes view: a role with manage and no view sees the menu entry, the list and the editor of the sites it manages). Both take the limitation Site, which names the sites of the registry a role reaches. A role without that limitation reaches every site: to keep an editor to his own site, give him the limitation. A site the roles do not allow is not in the list, and its editor answers 403.

Where the menu entry is. Under Admin for those who see that group. Ibexa takes the whole Admin group away from a user who lacks the policy setup/administrate, which is only a menu switch (it shows the Admin group and the Languages entry; every page keeps its own policy): for him "Cookie manager" is a first-level entry of the sidebar, right after "Content". Either way it needs masilia_consent/view or /manage.

A site without a front siteaccess is served nowhere, so nothing of its policy is shown to visitors: the list and the editor say so.

Install

composer require masilia/ibexa-consent
php bin/console doctrine:migrations:migrate
php bin/console masilia:consent:init <site identifier>   # default policy, as a draft: 4 categories, texts in en/fr/ar

Register the bundle and import its routes (@MasiliaIbexaConsentBundle/Resources/config/routes.yaml). Publish the policy from the Cookie manager page of the admin.

Front office

The banner is a small standalone app (TypeScript, the React API on Preact: about 15 kB gzip with its styles). It reads its configuration by API (GET /masilia/consent/config, cacheable, language of the siteaccess) and keeps the visitor's choice in a cookie of the browser, so the HTML of a page is the same for every visitor and Varnish can keep it.

1. Build it with the Encore of the host. The package gives a build of its own, named consent (one JavaScript and one CSS file, no shared runtime chunk). In the webpack.config.js of the host, after the config of the project:

const consentConfig = require('./vendor/masilia/ibexa-consent/src/bundle/Resources/encore/consent.config.js');
module.exports = [ibexaConfig, ...customConfigs, projectConfig, consentConfig(Encore)];
yarn add preact          # optional: the banner is built with Preact when it is there (~15 kB gzip), with the React of the host otherwise (~45 kB)
yarn encore dev          # or production

The bundle declares the Symfony side itself (the build consent of webpack_encore): nothing to write in config/packages/.

2. Print it with one call in the layout of each front theme:

{{ masilia_consent() }}

It prints the preload of the configuration, the stylesheet and the script of the banner (<script defer data-masilia-consent data-api="…">, which mounts the app by itself), and the services the editor switched on, held back. Nothing is printed for a site without a published policy, and if the configuration cannot be read nothing is shown and everything stays held.

Cache. The answer of GET /masilia/consent/config and every page that prints held services carry the cache tag masilia-consent-<site> (xkey header). Publishing a policy purges that tag through Ibexa's purge client (Varnish, or the local cache in development), so visitors get the new policy at once; the configuration is also kept five minutes in cache.app at most. A purge that fails is logged and never undoes the publication.

Outside Twig: MasiliaConsent.mount({ api: '/masilia/consent/config' }), MasiliaConsent.mount({ config }) with a configuration you give, and the function it returns takes the app away again.

Integrating with the consent

A package that sets cookies (analytics, maps, chat…)

Never print the script: implement Masilia\Contracts\IbexaConsent\ConsentServiceProvider. It is found by autoconfiguration (tag masilia.consent.service) and listed in the catalogue of the admin, where the editor adds it to a site and gives its settings.

final class AcmeChatProvider implements ConsentServiceProvider
{
    public function definition(): ServiceDefinition
    {
        return new ServiceDefinition(
            'acme_chat', 'Acme Chat', 'preferences',
            cookies: ['acme_*'],                    // names or patterns, removed when the category is withdrawn
            requiredSettings: ['key'],
            details: ['acme_*' => new CookieDetail(['en' => 'Keeps the conversation'], ['en' => '1 year'])],  // shown in the panel
            storage: ['acme_open'],                 // keys of localStorage / sessionStorage removed with the cookies
            multiple: false,                        // true: the editor may add it several times, each with its own name
        );
    }

    public function script(array $settings): ?ScriptSpec  // null: no script of its own (frames and cookies only)
    {
        // throw \InvalidArgumentException for a setting that is not valid: it is shown to the editor, never printed
        return new ScriptSpec(src: 'https://chat.acme.example/widget.js', inline: 'window.acmeKey = ' . json_encode($settings['key']) . ';', async: true);
    }
}

Provided: Google Analytics 4, Google Tag Manager, Matomo, Meta Pixel, Hotjar, LinkedIn Insight, YouTube, Vimeo, Google Maps and a Custom script (an https address, added by the editor, as many times as needed).

Features of the project that use cookies, storage or third parties

Hold back what loads or runs, and let the browser decide; the page stays the same for every visitor.

{# a frame, a script #}
{{ masilia_consent_script('ga4', {id: 'G-XXXXXXXXXX'}) }}
{{ masilia_consent_iframe('https://www.youtube.com/embed/ID', 'marketing', {title: 'Video'}) }}

{# any block of markup: an embed code, a widget, a map (its scripts run once released) #}
{% apply masilia_consent_hold('marketing') %}
    <script src="https://tiles.example.org/map.js"></script>
    <div id="map"></div>
{% endapply %}

{# any element that loads something #}
<img data-consent-category="marketing" data-consent-src="https://tracker.example.org/p.gif" alt="">
<link rel="stylesheet" data-consent-category="preferences" data-consent-href="https://fonts.example.org/f.css">

{{ masilia_consent_link('Cookies') }}   {# reopens the panel #}

What the project itself stores (a cookie, a localStorage key) is declared the same way: a small provider with no script (script() returns null) for the cookies and the storage keys, or a cookie declared by hand in the "Cookies" tab of the admin.

In the browser: window.masiliaConsent.has('analytics'), .choices(), .open(), .onChange(callback, {immediate: true}) (returns what takes the listener away), and the event masilia:consent. It exists as soon as the script runs, before the configuration is fetched.

In PHP: inject Masilia\Contracts\IbexaConsent\ConsentReader (granted('analytics'), choices(); Twig masilia_consent_granted()). A page that depends on it is no longer the same for every visitor: do not let a shared cache keep it. Listen to Masilia\Contracts\IbexaConsent\Event\ConsentRecorded (site, siteaccess, version, choices, accept_all / reject_all / custom) to react to a choice.

Withdrawing a consent removes the cookies and the storage keys of the services of the category and reloads the page (a script that already ran cannot be taken back); accepting never reloads. Google Consent Mode v2 is set to denied until the visitor decides.

Theming

Every colour and measure is a CSS variable on .masilia-consent:

.masilia-consent { --mc-accent: #b00020; --mc-radius: 0; --mc-font: "Inter", sans-serif; }

The policy sets position (bottom, bottom-left, bottom-right, top), layout (card, bar), theme (light, dark, auto) and an accent colour from the admin.

Editing

The first tab of the Cookie manager page, Banner and panel, shows the banner and the panel as a visitor gets them, drawn from the policy being edited (the stylesheet of the real front build, in a frame: the admin's own styles do not reach it). Switch between the banner, the panel and the button that is left after the choice, and between a desktop and a phone width.

  • Texts: click a text in the preview to edit it where it is (a window opens next to it; what you type is in the preview at once). Every text is also in the form folded under the preview, which shows what the validator refuses. The close button and the button that reopens the panel have no text to see: clicking them edits the label read aloud by screen readers. Buttons and links do nothing in the preview.
  • Settings (button at the end of the toolbar): position, layout, theme, accent colour (colour picker, #RRGGBB, suggestions, a warning when the colour is hard to read on the background), reject / accept emphasis, reopen button, and the consent cookie. Each choice is in the preview as it is made; it still has to be saved and published like a text.

The preview needs the banner to be built (yarn encore dev); without it the tab says so. It shows the banner of the package, not the fonts and --mc-* variables a theme of the site sets. A text that is not written yet is drawn as its label (‹Title›) so it can be clicked and filled in, and the optional button and link are drawn even when empty: a visitor gets the default text of the package for a missing one, and no button or link for an empty optional one.

Commands

Command What it does
masilia:consent:init <site> Creates the policy of a site as a draft (4 categories, texts for the languages of the site).
masilia:consent:publish <site> Publishes the working copy: freezes it as a snapshot, raises the version (visitors are asked again).
masilia:consent:export <site> [file] Exports the working copy (settings, texts of every language, categories, services, cookies, style) as JSON.
masilia:consent:import <file> --site=<id> [--publish] Replaces the working copy by an exported document, creating the policy when needed. This is how what an editor wrote in development reaches production. It lists the settings of the services (ids of measure) the file brings: read them before you publish, they may be those of the development.
masilia:consent:purge-log [--days=N] Removes the log entries older than log.retention_days (the daily counts are kept).

The same export and import are buttons of the admin page. Preview, Export, Import, Discard changes (when the working copy differs from what is published), Save and Publish are in the context menu of the admin (top right, as on the other pages of the admin); Preview is a split button, as the admin's "Save and close": the button opens the draft on the site of the language being edited, the chevron lists the languages of the site and opens the one chosen. The state of the policy (the published version, unpublished changes) is a badge beside the name of the site. The configuration of the bundle (masilia_ibexa_consent):

masilia_ibexa_consent:
    cookie: { name: masilia_consent, retention_days: 180 }   # defaults of a new policy
    log:    { enabled: true, retention_days: 365, anonymize_ip: true }

The statistics tab counts the choices per category and per day without keeping anything about the visitors.

The assistant

With masilia/ibexa-ai installed (nothing to configure: the capabilities are loaded only when it is there), the assistant of the admin can handle the cookie policy of a site: read it, write the texts of the banner in each language of the site, add a service, check the policy and publish it. Nine capabilities, of the domain consent:

Capability Risk masilia_consent What it does
consent.sites read view The sites whose policy the user may see, and where each stands (policy, published, changes not published, counts).
consent.describe(site) read view The working copy: texts by language, categories, services, cookies, style.
consent.catalogue read view The services that can be added and the settings each needs.
consent.check(site) read view Whether the policy can be published, and the fields that stop it. Writes nothing.
consent.stats(site, days?) read view The choices visitors made, aggregated by category and by day.
consent.create(site) write manage The default policy (a draft) of a site that has none.
consent.edit(site, operations) write manage Changes the working copy with a list of operations.
consent.publish(site) write manage Puts the working copy live; visitors are asked again when something changed.
consent.discard(site) destructive manage Gives up the changes made since the latest publication, for good.
  • Rights. The roles of the user decide, as in the admin: masilia_consent/view to read and /manage to change, with the Site limitation (a site the roles do not allow is neither listed nor reachable, and a call about it is refused before and again when it runs). A write also needs the permission of its risk in masilia_ai (write, destructive).
  • Approval. Every write is shown first: consent.edit as one line per change (fr · title: «…» → «…»), consent.publish with the warning that every visitor is asked again, consent.discard with what is lost (the parts of the policy that moved since the publication). consent.create, consent.edit and consent.publish can go in one propose_changes, approved once. What differs there: the card of a batch shows, for each step, its title and its first rows only (so the first three changes of an edit, though all are applied, and no note), which is why the warnings of consent.publish and consent.discard are in their titles; and it is made before the first step has run, so an edit that follows consent.create is shown on the default policy that step makes (the card says so), and a publication never claims that nothing changes.
  • consent.edit operations: set_text, set_style, set_policy, add_category, set_category_text, set_category_default, remove_category, add_service, set_service, set_service_setting, remove_service, add_cookie, set_cookie, set_cookie_text, remove_cookie. They follow the rules of the editor of the admin; the result must pass the same validation as a save (one wrong operation refuses the whole call and nothing is kept). A category added with add_category is named in one language: the others are named with set_category_text, or the policy cannot be published.
  • What it never does. It does not invent the id of a measure or a script address (a service with a missing setting is refused), and it never sees the log of choices (it holds addresses): consent.stats gives counts only. There is no capability to export or import a file.
  • masilia:ai:os:selftest <location> runs this package's steps too (it makes a throwaway site and deletes it, with its policy, at the end).

Tests

vendor/bin/phpunit && vendor/bin/phpstan analyse   # PHP
npm ci && npm run typecheck && npm test            # the banner: types, logic, and the page as jsdom runs it with the real bundle
( cd src/bundle/Resources/public/admin && node --experimental-strip-types --import ./test-hooks/register.mjs --test consent/*.test.ts )