feat(ext-tracking): Add tracking extension for HTML/JS snippets

Adds a new extension allowing injection of custom code into the page head. Includes an admin interface for saving snippets, secure save routes with CSRF protection, and tests verifying the functionality. Also updates core Extensions.php to support callable HTML blocks for lazy evaluation.
This commit is contained in:
2026-11-30 22:51:03 +01:00
parent cc9c03e580
commit 515e4cac1f
7 changed files with 290 additions and 3 deletions
@@ -0,0 +1,26 @@
<?php
$snippet = \Plugi\Setting::get('ext--tracking--head') ?? '';
?>
<section class="card border border-base-300/60 bg-base-100 shadow-sm" aria-labelledby="tracking-settings-title">
<div class="card-body gap-5 p-4 sm:p-6 lg:p-8">
<div>
<h2 class="card-title text-xl" id="tracking-settings-title">Tracking snippet</h2>
<p class="mt-1 text-sm text-base-content/60">Add one HTML or JavaScript snippet to the public page head.</p>
</div>
<div class="alert alert-warning" role="alert">
<i class="ph ph-warning-circle" aria-hidden="true"></i>
<span>Saved code is inserted as-is and executes on every public page. Only save code you trust.</span>
</div>
<form method="post" action="<?= phpb_e(phpb_full_url('/ext--tracking/save')) ?>" class="space-y-4">
<?php phpb_csrf_field(); ?>
<div class="form-control w-full">
<label class="label" for="tracking-snippet">
<span class="label-text">HTML / JavaScript</span>
</label>
<textarea id="tracking-snippet" name="snippet" rows="14" spellcheck="false" class="textarea textarea-bordered w-full font-mono"><?= phpb_e($snippet) ?></textarea>
</div>
<button type="submit" class="btn btn-primary">Save snippet</button>
</form>
</div>
</section>
+9
View File
@@ -0,0 +1,9 @@
<?php
return [
'title' => 'Tracking',
'author' => 'Paul Spenke',
'identifier' => 'tracking',
'licence' => 'MIT',
'version' => '1.0.0',
];
@@ -0,0 +1,16 @@
<?php
use Plugi\Extensions;
use Plugi\Setting;
Extensions::addRoutes([
'/ext--tracking/save' => __DIR__ . '/routes/save.php',
]);
Extensions::registerBackend('tracking', [
'title' => 'Tracking',
'include' => __DIR__ . '/admin/tracking.php',
'icon' => '<i class="ph ph-code"></i>',
]);
Extensions::registerHtmlBlock(static fn (): string => Setting::get('ext--tracking--head') ?? '', 'head');
@@ -0,0 +1,22 @@
<?php
phpb_requires_authenticated();
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !phpb_validate_csrf()) {
http_response_code(403);
exit('Forbidden');
}
if (!isset($_POST['snippet']) || !is_string($_POST['snippet'])) {
http_response_code(400);
exit('Invalid snippet');
}
$saved = (new \Plugi\Repositories\SettingRepository())->updateSettings([
'ext--tracking--head' => $_POST['snippet'],
]);
phpb_redirect(phpb_url('website_manager', ['tab' => 'ext--tracking']), [
'message-type' => $saved ? 'success' : 'error',
'message' => $saved ? 'Tracking snippet saved.' : 'Tracking snippet could not be saved.',
]);
@@ -0,0 +1,185 @@
<?php
require_once __DIR__ . '/../../../plugi-core/src/Contracts/SettingRepositoryContract.php';
require_once __DIR__ . '/../../../plugi-core/src/Core/DB.php';
require_once __DIR__ . '/../../../plugi-core/src/Extensions.php';
require_once __DIR__ . '/../../../plugi-core/src/Repositories/BaseRepository.php';
require_once __DIR__ . '/../../../plugi-core/src/Repositories/SettingRepository.php';
require_once __DIR__ . '/../../../plugi-core/src/Contracts/SettingContract.php';
require_once __DIR__ . '/../../../plugi-core/src/Setting.php';
function phpb_remove_non_alpha_numeric(string $value): string
{
return preg_replace('/\W*/', '', $value);
}
class TrackingTestDatabase extends \Plugi\Core\DB
{
public function __construct()
{
$this->pdo = new PDO('sqlite::memory:');
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->pdo->exec('CREATE TABLE settings (id INTEGER PRIMARY KEY AUTOINCREMENT, setting TEXT NOT NULL UNIQUE, value TEXT NOT NULL, is_array INTEGER NOT NULL DEFAULT 0)');
$this->databaseName = 'tracking_test';
}
}
class TrackingTestRedirect extends RuntimeException
{
public function __construct(public string $url, public array $flashData)
{
parent::__construct('Redirect requested.');
}
}
class TrackingTestAuthenticationRequired extends RuntimeException
{
}
function phpb_requires_authenticated(): void
{
if (!($GLOBALS['trackingTestAuthenticated'] ?? false)) {
throw new TrackingTestAuthenticationRequired();
}
}
function phpb_validate_csrf(): bool
{
return $GLOBALS['trackingTestCsrfValid'] ?? false;
}
function phpb_e(string $value): string
{
return htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
}
function phpb_csrf_field(): void
{
echo '<input type="hidden" name="_token" value="test">';
}
function phpb_full_url(string $path): string
{
return '/plugi' . $path;
}
function phpb_url(string $module, array $parameters = []): string
{
return $module . '?' . http_build_query($parameters);
}
function phpb_redirect(string $url, array $flashData = [], int $statusCode = 302): void
{
throw new TrackingTestRedirect($url, $flashData);
}
require __DIR__ . '/../extension.php';
if (realpath(\Plugi\Extensions::getRoute('/ext--tracking/save')) !== realpath(__DIR__ . '/../routes/save.php')) {
throw new RuntimeException('The Tracking save route should be registered.');
}
if (realpath(\Plugi\Extensions::getBackends()['ext--tracking']['include'] ?? '') !== realpath(__DIR__ . '/../admin/tracking.php')) {
throw new RuntimeException('The Tracking Website Manager backend should be registered.');
}
$_ENV['DATABASE_PREFIX'] = '';
$phpb_db = new TrackingTestDatabase();
ob_start();
require __DIR__ . '/../admin/tracking.php';
$trackingEditor = ob_get_clean();
if (!str_contains($trackingEditor, 'action="/plugi/ext--tracking/save"')) {
throw new RuntimeException('The Tracking editor should post to its registered extension route.');
}
if (($argv[1] ?? null) === 'csrf-rejection') {
$snippet = '<script>window.tracking = "saved";</script>';
(new \Plugi\Repositories\SettingRepository())->updateSettings([
'ext--tracking--head' => $snippet,
]);
$GLOBALS['trackingTestAuthenticated'] = true;
$GLOBALS['trackingTestCsrfValid'] = false;
$_SERVER['REQUEST_METHOD'] = 'POST';
$_POST = ['snippet' => '<script>window.tracking = "invalid-csrf";</script>'];
register_shutdown_function(static function () use ($phpb_db, $snippet): void {
if (http_response_code() !== 403) {
fwrite(STDERR, "Invalid CSRF should return HTTP 403.\n");
exit(1);
}
$saved = $phpb_db->select('SELECT value FROM settings WHERE setting = ?', ['ext--tracking--head']);
if (($saved[0]['value'] ?? null) !== $snippet) {
fwrite(STDERR, "Invalid CSRF must not change the saved snippet.\n");
exit(1);
}
fwrite(STDOUT, "PASS: authenticated invalid-CSRF requests are rejected without changing the saved snippet.\n");
});
require __DIR__ . '/../routes/save.php';
throw new RuntimeException('Authenticated requests with invalid CSRF should be rejected.');
}
if (\Plugi\Extensions::getHtmlBlocks('head') !== '') {
throw new RuntimeException('An unset tracking snippet should add no head output.');
}
$GLOBALS['trackingTestAuthenticated'] = true;
$GLOBALS['trackingTestCsrfValid'] = true;
$_SERVER['REQUEST_METHOD'] = 'POST';
$snippet = "<script>window.tracking = 'saved';</script>";
$_POST = ['snippet' => $snippet];
try {
require __DIR__ . '/../routes/save.php';
} catch (TrackingTestRedirect $redirect) {
if ($redirect->url !== 'website_manager?tab=ext--tracking' || $redirect->flashData['message-type'] !== 'success') {
throw new RuntimeException('Saving should redirect back to the Tracking editor with success feedback.');
}
}
$saved = $phpb_db->select('SELECT value FROM settings WHERE setting = ?', ['ext--tracking--head']);
if (($saved[0]['value'] ?? null) !== $snippet) {
throw new RuntimeException('The submitted snippet should be persisted unchanged.');
}
$settingsProperty = new ReflectionProperty(\Plugi\Setting::class, 'settings');
$settingsProperty->setValue(null, null);
if (\Plugi\Extensions::getHtmlBlocks('head') !== $snippet) {
throw new RuntimeException('The saved tracking snippet should be emitted unchanged in head output.');
}
$GLOBALS['trackingTestAuthenticated'] = false;
$_POST['snippet'] = '<script>window.tracking = "unauthorized";</script>';
try {
require __DIR__ . '/../routes/save.php';
throw new RuntimeException('Unauthenticated requests should be rejected.');
} catch (TrackingTestAuthenticationRequired) {
}
$saved = $phpb_db->select('SELECT value FROM settings WHERE setting = ?', ['ext--tracking--head']);
if (($saved[0]['value'] ?? null) !== $snippet) {
throw new RuntimeException('Unauthenticated requests must not change the saved snippet.');
}
$process = proc_open([PHP_BINARY, __FILE__, 'csrf-rejection'], [
0 => ['pipe', 'r'],
1 => ['pipe', 'w'],
2 => ['pipe', 'w'],
], $pipes);
if (!is_resource($process)) {
throw new RuntimeException('Could not start the invalid-CSRF route test.');
}
fclose($pipes[0]);
$output = stream_get_contents($pipes[1]);
$error = stream_get_contents($pipes[2]);
fclose($pipes[1]);
fclose($pipes[2]);
$status = proc_close($process);
if ($status !== 0 || !str_contains($output, 'PASS: authenticated invalid-CSRF requests are rejected')) {
throw new RuntimeException(sprintf('The invalid-CSRF route test failed (status %d): %s%s', $status, $output, $error));
}
fwrite(STDOUT, "PASS: tracking snippets are saved unchanged; authentication and CSRF are required.\n");
+7 -3
View File
@@ -68,10 +68,10 @@ class Extensions
/**
* Register an HtmlBlock.
* @param string $html
* @param string|callable $html
* @param string $location
*/
public static function registerHtmlBlock(string $html, string $location = 'head') {
public static function registerHtmlBlock(string|callable $html, string $location = 'head') {
self::$htmlBlocks[$location][] = $html;
}
@@ -245,7 +245,11 @@ class Extensions
*/
public static function getHtmlBlocks(string $location = 'head'): string
{
return implode('', self::$htmlBlocks[$location]);
$html = '';
foreach (self::$htmlBlocks[$location] as $block) {
$html .= is_string($block) ? $block : $block();
}
return $html;
}
/**
@@ -0,0 +1,25 @@
<?php
use Plugi\Extensions;
require_once __DIR__ . '/../src/Extensions.php';
$callbackValue = '<script>window.tracking = "first";</script>';
Extensions::registerHtmlBlock('<meta name="static" content="unchanged">', 'head');
Extensions::registerHtmlBlock(static function () use (&$callbackValue): string {
return $callbackValue;
}, 'head');
$expected = '<meta name="static" content="unchanged">' . $callbackValue;
if (Extensions::getHtmlBlocks('head') !== $expected) {
throw new RuntimeException('Static and callback HTML blocks should render in registration order.');
}
$callbackValue = '<script>window.tracking = "updated";</script>';
$expected = '<meta name="static" content="unchanged">' . $callbackValue;
if (Extensions::getHtmlBlocks('head') !== $expected) {
throw new RuntimeException('HTML-block callbacks should be evaluated each time their location is retrieved.');
}
fwrite(STDOUT, "PASS: HTML blocks render strings and lazy callbacks.\n");