Skip to content

Commit 3ab0052

Browse files
committed
Patched XSS & CSRF
1 parent 4f2d0ce commit 3ab0052

File tree

4 files changed

+47
-1
lines changed

4 files changed

+47
-1
lines changed

app/Http/Middleware/VerifyCsrfToken.php

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
namespace App\Http\Middleware;
44

55
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
6+
use Override;
7+
use Symfony\Component\HttpFoundation\Cookie;
68

79
class VerifyCsrfToken extends Middleware
810
{
@@ -14,4 +16,21 @@ class VerifyCsrfToken extends Middleware
1416
protected $except = [
1517
//
1618
];
19+
20+
#[Override]
21+
protected function newCookie($request, $config)
22+
{
23+
return new Cookie(
24+
'XSRF-TOKEN',
25+
$request->session()->token(),
26+
$this->availableAt(60 * $config['lifetime']),
27+
$config['path'],
28+
$config['domain'],
29+
$config['secure'],
30+
true,
31+
false,
32+
$config['same_site'] ?? null,
33+
$config['partitioned'] ?? false
34+
);
35+
}
1736
}

resources/helpers.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,20 @@ function replace_links(string $markdown): string
5454
}
5555
}
5656

57+
if (! function_exists('md_to_safe_html')) {
58+
/**
59+
* Converts Markdown to a safe HTML string.
60+
*/
61+
function md_to_safe_html(string $markdown): string
62+
{
63+
return str($markdown)->markdown([
64+
'html_input' => 'escape',
65+
'max_nesting_level' => 10,
66+
'allow_unsafe_links' => false,
67+
])->toString();
68+
}
69+
}
70+
5771
if (! function_exists('canonical')) {
5872
/**
5973
* Generate a canonical URL to the given route and allowed list of query params.

resources/views/articles/show.blade.php

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ class="w-full bg-center {{ $article->hasHeroImage() ? 'bg-cover' : '' }} bg-gray
106106
x-init="$nextTick(function () { highlightCode($el); })"
107107
class="prose prose-lg text-gray-800 prose-lio"
108108
>
109-
<x-buk-markdown>{!! $article->body() !!}</x-buk-markdown>
109+
<x-buk-markdown>{!! md_to_safe_html($article->body) !!}</x-buk-markdown>
110110
</div>
111111

112112
@if ($article->isUpdated())
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
<?php
2+
3+
test('converts markdown to safe html', function () {
4+
$body = 'Hello, World! ![](image.png).';
5+
6+
expect(md_to_safe_html($body))->toBe('<p>Hello, World! <img src="image.png" alt="" />.</p>' . "\n");
7+
});
8+
9+
test('prevents unsafe links', function () {
10+
$body = "[Unsafe Link](javascript:alert('Hello'))";
11+
12+
expect(md_to_safe_html($body))->toBe('<p><a>Unsafe Link</a></p>' . "\n");
13+
});

0 commit comments

Comments
 (0)