Skip to content

Commit b7ef46c

Browse files
committed
fix: inline style "display:none" for honeypot field does not work with CSP
1 parent 0a9947e commit b7ef46c

2 files changed

Lines changed: 27 additions & 0 deletions

File tree

app/Config/Honeypot.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@ class Honeypot extends BaseConfig
2828

2929
/**
3030
* Honeypot container
31+
*
32+
* If you enables CSP, you can remove `style="display:none"`.
3133
*/
3234
public string $container = '<div style="display:none">{template}</div>';
35+
36+
/**
37+
* The id attribute for Honeypot container tag
38+
*
39+
* Used when CSP is enabled.
40+
*/
41+
public string $containerId = 'hpc';
3342
}

system/Honeypot/Honeypot.php

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,8 @@ public function __construct(HoneypotConfig $config)
4646
$this->config->container = '<div style="display:none">{template}</div>';
4747
}
4848

49+
$this->config->containerId ??= 'hpc';
50+
4951
if ($this->config->template === '') {
5052
throw HoneypotException::forNoTemplate();
5153
}
@@ -70,10 +72,26 @@ public function hasContent(RequestInterface $request)
7072
*/
7173
public function attachHoneypot(ResponseInterface $response)
7274
{
75+
if ($response->getCSP()->enabled()) {
76+
// Add id attribute to the container tag.
77+
$this->config->container = str_ireplace(
78+
'>{template}',
79+
' id="' . $this->config->containerId . '">{template}',
80+
$this->config->container
81+
);
82+
}
83+
7384
$prepField = $this->prepareTemplate($this->config->template);
7485

7586
$body = $response->getBody();
7687
$body = str_ireplace('</form>', $prepField . '</form>', $body);
88+
89+
if ($response->getCSP()->enabled()) {
90+
// Add style tag for the container tag in the head tag.
91+
$style = '<style ' . csp_style_nonce() . '>#' . $this->config->containerId . ' { display:none }</style>';
92+
$body = str_ireplace('</head>', $style . '</head>', $body);
93+
}
94+
7795
$response->setBody($body);
7896
}
7997

0 commit comments

Comments
 (0)