Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

</div>

A blog for Saucebase: posts, categories, tags, RSS and SEO, managed from the admin.
A Laravel blog for Saucebase: posts, categories, tags, RSS and SEO, managed from the admin, on Vue or React.

A module for [Saucebase](https://github.com/saucebase-dev/saucebase), the AI-ready Laravel SaaS kit. Modules are Composer packages you add to a Saucebase app; once installed, the code is yours to change.

Expand Down
25 changes: 24 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,29 @@
{
"name": "saucebase/blog",
"description": "A blog for Saucebase: posts, categories, tags, RSS and SEO, managed from the admin.",
"description": "Laravel blog module for Saucebase: posts with a rich text editor, categories, tags, scheduling, draft preview, RSS feed and SEO (meta tags, JSON-LD structured data, server-rendered pages), with a Filament admin. Vue and React (Inertia).",
"keywords": [
"saucebase",
"saucebase-module",
"laravel",
"laravel-package",
"filament",
"inertiajs",
"vuejs",
"reactjs",
"blog",
"laravel-blog",
"blog-engine",
"cms",
"content-management",
"rss",
"rss-feed",
"seo",
"json-ld",
"structured-data",
"rich-text-editor",
"scheduled-posts"
],
"homepage": "https://saucebase-dev.github.io/docs/modules/blog/",
"type": "saucebase-module",
"license": "MIT",
"version": "v3.5.0",
Expand Down
2 changes: 1 addition & 1 deletion resources/boost/skills/saucebase-blog-development/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ The card's title link stretches over the whole card (`after:absolute after:inset

The rich-editor HTML is rendered with `v-html` / `dangerouslySetInnerHTML`. `Post::content` is cast with core's `SanitizedHtml`, which runs `Str::sanitizeHtml()` (Filament's Symfony sanitizer) on every read and stores what was written, so scripts and event handlers never reach a page, whichever endpoint sends it. Keep the cast (sc-1131).

The JSON-LD `<script>` escapes `<` as `<` so a title containing `</script>` cannot break out of it.
The JSON-LD is built in `BlogController::jsonLd()` and sent as `json_ld` (Article and BreadcrumbList); both stacks print it as is. `JSON_HEX_TAG` escapes `<` and `>`, so a title containing `</script>` cannot break out of the script tag (sc-1198).

### PHP → TypeScript Contract

Expand Down
65 changes: 10 additions & 55 deletions resources/js/react/pages/Show.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,53 +20,13 @@
related: Modules.Blog.Data.PostData[];
/** An admin viewing a post that is not public yet. */
preview: boolean;
/** Article and BreadcrumbList, built and escaped on the server. */
json_ld: string[];
}

// `<` is escaped so a title containing a closing script tag cannot end the
// JSON-LD block.
const toJsonLd = (data: object) =>
JSON.stringify(data).replaceAll('<', String.raw`\u003c`);

export default function Show({ post, related, preview }: ShowProps) {
export default function Show({ post, related, preview, json_ld }: ShowProps) {
const t = useT();

const jsonLd = {
'@context': 'https://schema.org',
'@type': 'Article',
headline: post.title,
description: post.excerpt ?? undefined,
image: post.cover_url || undefined,
datePublished: post.published_at ?? undefined,
dateModified: post.updated_at ?? undefined,
author: post.author
? { '@type': 'Person', name: post.author.name }
: undefined,
url: post.url,
};

// The same trail as the visible breadcrumbs, which search results can show
// in place of the raw URL.
const breadcrumbJsonLd = {
'@context': 'https://schema.org',
'@type': 'BreadcrumbList',
itemListElement: [
{ name: t('Blog'), item: route('blog.index') },
...(post.category
? [
{
name: post.category.name,
item: route('blog.category', post.category.slug),
},
]
: []),
{ name: post.title, item: post.url },
].map((crumb, index) => ({
'@type': 'ListItem',
position: index + 1,
...crumb,
})),
};

return (
<SiteLayout
title={post.title}
Expand All @@ -89,18 +49,13 @@
content={post.author.name}
/>
)}
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: toJsonLd(jsonLd),
}}
/>
<script
type="application/ld+json"
dangerouslySetInnerHTML={{
__html: toJsonLd(breadcrumbJsonLd),
}}
/>
{json_ld.map((block, index) => (
<script
key={index}

Check warning on line 54 in resources/js/react/pages/Show.tsx

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Use a stable ID as key, because the index changes when the list changes.

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_blog&issues=AaIzDs3YFYDvqLZwfWSX&open=AaIzDs3YFYDvqLZwfWSX&pullRequest=17
type="application/ld+json"
dangerouslySetInnerHTML={{ __html: block }}
/>
))}
</Head>
<main className="mx-auto w-full max-w-3xl flex-1 px-6 py-28">
{preview && (
Expand Down
69 changes: 11 additions & 58 deletions resources/js/vue/pages/Show.vue
Original file line number Diff line number Diff line change
Expand Up @@ -8,69 +8,20 @@ import {
BreadcrumbSeparator,
} from '@/components/ui/breadcrumb';
import SiteLayout from '@/layouts/SiteLayout.vue';
import { trans } from 'laravel-vue-i18n';
import { Head, Link } from '@inertiajs/vue3';
import { computed } from 'vue';

import PostCard from '../components/PostCard.vue';
import PostMeta from '../components/PostMeta.vue';
import PostCategory from '../components/PostCategory.vue';
import PostTags from '../components/PostTags.vue';
const props = defineProps<{
defineProps<{
post: Modules.Blog.Data.PostData;
related: Modules.Blog.Data.PostData[];
/** An admin viewing a post that is not public yet. */
preview: boolean;
/** Article and BreadcrumbList, built and escaped on the server. */
json_ld: string[];
}>();

// Inertia's Head renders text children but drops v-html. `<` is escaped so a
// title containing a closing script tag cannot end the JSON-LD block.
const toJsonLd = (data: object) =>
JSON.stringify(data).replaceAll('<', String.raw`\u003c`);

const jsonLd = computed(() =>
toJsonLd({
'@context': 'https://schema.org',
'@type': 'Article',
headline: props.post.title,
description: props.post.excerpt ?? undefined,
image: props.post.cover_url || undefined,
datePublished: props.post.published_at ?? undefined,
dateModified: props.post.updated_at ?? undefined,
author: props.post.author
? { '@type': 'Person', name: props.post.author.name }
: undefined,
url: props.post.url,
}),
);

// The same trail as the visible breadcrumbs, which search results can show in
// place of the raw URL.
const breadcrumbJsonLd = computed(() =>
toJsonLd({
'@context': 'https://schema.org',
'@type': 'BreadcrumbList',
itemListElement: [
{ name: trans('Blog'), item: route('blog.index') },
...(props.post.category
? [
{
name: props.post.category.name,
item: route(
'blog.category',
props.post.category.slug,
),
},
]
: []),
{ name: props.post.title, item: props.post.url },
].map((crumb, index) => ({
'@type': 'ListItem',
position: index + 1,
...crumb,
})),
}),
);
</script>

<template>
Expand All @@ -93,12 +44,14 @@ const breadcrumbJsonLd = computed(() =>
property="article:author"
:content="post.author.name"
/>
<component :is="'script'" type="application/ld+json">{{
jsonLd
}}</component>
<component :is="'script'" type="application/ld+json">{{
breadcrumbJsonLd
}}</component>
<!-- Head renders text children but drops v-html. -->
<component
:is="'script'"
v-for="(block, index) in json_ld"
:key="index"
type="application/ld+json"
>{{ block }}</component
>
</Head>
<main class="mx-auto w-full max-w-3xl flex-1 px-6 py-28">
<p
Expand Down
48 changes: 47 additions & 1 deletion src/Http/Controllers/BlogController.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,56 @@
->get()
->map(fn (Post $p) => PostData::fromPost($p));

$data = PostData::fromPost($post, content: $post->content);

return Inertia::render('Blog::Show', [
'post' => PostData::fromPost($post, content: $post->content),
'post' => $data,
'related' => $related,
'preview' => $preview,
'json_ld' => $this->jsonLd($post, $data),
])->withSSR();
}

/**
* The Article and BreadcrumbList blocks, ready to print. Built here once for both
* stacks: JSON_HEX_TAG escapes `<` and `>`, so a title holding `</script>` cannot
* end the script tag the page prints them in.
*
* @return list<string>
*/
private function jsonLd(Post $post, PostData $data): array
{
$article = array_filter([
'@context' => 'https://schema.org',
'@type' => 'Article',
'headline' => $data->title,
'description' => $data->excerpt,
'image' => $data->cover_url ?: null,
'datePublished' => $data->published_at,
'dateModified' => $data->updated_at,
'author' => $post->author ? ['@type' => 'Person', 'name' => $post->author->name] : null,
'url' => $data->url,
], fn ($value) => $value !== null);

// The same trail as the visible breadcrumbs, which search results can show in place of the URL.
$crumbs = [
['name' => __('Blog'), 'item' => route('blog.index')],
...($post->category ? [['name' => $post->category->name, 'item' => route('blog.category', $post->category->slug)]] : []),

Check warning on line 171 in src/Http/Controllers/BlogController.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 133 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_blog&issues=AaIzDs49FYDvqLZwfWSY&open=AaIzDs49FYDvqLZwfWSY&pullRequest=17
['name' => $data->title, 'item' => $data->url],
];

$breadcrumbs = [
'@context' => 'https://schema.org',
'@type' => 'BreadcrumbList',
'itemListElement' => array_map(
fn (array $crumb, int $index) => ['@type' => 'ListItem', 'position' => $index + 1, ...$crumb],
$crumbs,
array_keys($crumbs),
),
];

$flags = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR;

return [json_encode($article, $flags), json_encode($breadcrumbs, $flags)];
}
}
24 changes: 24 additions & 0 deletions tests/Feature/BlogControllerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,30 @@
);
}

/** Built once on the server for both stacks: a title can never close the script tag. */
public function test_show_sends_the_json_ld_with_tags_escaped(): void
{
$category = Category::factory()->create();
$post = Post::factory()->published()->create([
'category_id' => $category->id,
'title' => '</script><script>alert(1)</script>',
]);

$this->get($post->url())
->assertOk()
->assertInertia(fn ($page) => $page
->has('json_ld', 2)
->where('json_ld', function ($blocks) use ($post, $category) {
[$article, $breadcrumbs] = collect($blocks)->all();

return ! str_contains($article.$breadcrumbs, '<')
&& json_decode($article, true)['headline'] === $post->title
&& json_decode($article, true)['@type'] === 'Article'
&& array_column(json_decode($breadcrumbs, true)['itemListElement'], 'name') === ['Blog', $category->name, $post->title];

Check warning on line 211 in tests/Feature/BlogControllerTest.php

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Split this 144 characters long line (which is greater than 120 authorized).

See more on https://sonarcloud.io/project/issues?id=saucebase-dev_blog&issues=AaIzDs5DFYDvqLZwfWSZ&open=AaIzDs5DFYDvqLZwfWSZ&pullRequest=17
})
);
}

public function test_post_resource_includes_expected_fields(): void
{
$author = User::factory()->create();
Expand Down