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
9 changes: 8 additions & 1 deletion scripts/sync-blog-posts.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ function slugFromPath(path) {
return path.split('/').pop().replace(/\.md$/, '');
}

function resolveThumbnail(value, articlePath) {
if (!value || /^https?:\/\//.test(value) || value.startsWith('/')) return value || '';

const articleDirectory = articlePath.split('/').slice(0, -1).join('/');
return new URL(value, `https://raw.githubusercontent.com/${BLOG_REPO}/main/${articleDirectory}/`).toString();
}

async function getCommitMeta(path) {
const commits = await requestJson(`https://api.github.com/repos/${BLOG_REPO}/commits?path=${encodeURIComponent(path)}&per_page=100`);
const firstCommit = commits.at(-1);
Expand Down Expand Up @@ -108,7 +115,7 @@ for (const path of articleFiles) {
date: data.date || '',
tags: data.tags || [],
status: data.status || 'draft',
thumbnail: data.thumbnail || data.image || data.cover || '',
thumbnail: resolveThumbnail(data.thumbnail || data.image || data.cover || '', path),
content,
sourceUrl: file.html_url,
releasedAt: commitMeta.releasedAt,
Expand Down
5 changes: 2 additions & 3 deletions src/components/BaseButton.astro
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
---
import { withBase } from '../lib/urls';
import { normalizeHref } from '../lib/urls';

interface Props {
href: string;
variant?: 'primary' | 'secondary' | 'light';
}

const { href, variant = 'primary' } = Astro.props;
const isExternal = /^https?:\/\//.test(href);
const targetHref = isExternal ? href : withBase(href);
const targetHref = normalizeHref(href);

const variants = {
primary: 'border-brand bg-brand text-white hover:bg-brand-dark',
Expand Down
5 changes: 3 additions & 2 deletions src/components/ProjectCard.astro
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ interface Props {
compact?: boolean;
}

import { withBase } from '../lib/urls';
import { normalizeHref, withBase } from '../lib/urls';
import { projectSlug } from '../lib/projects';

const { project, compact = false } = Astro.props;
Expand All @@ -38,6 +38,7 @@ const updatedLabel = updatedDate
const visibleTopics = (project.topics || []).slice(0, 4);
const detailUrl = withBase(`/projects/${projectSlug(project.fullName)}/`);
const repoName = project.fullName.split('/').at(-1) || project.fullName;
const homepageUrl = project.homepage ? normalizeHref(project.homepage) : '';
---

<article
Expand Down Expand Up @@ -98,6 +99,6 @@ const repoName = project.fullName.split('/').at(-1) || project.fullName;
<span class="rounded-full border border-line px-2 py-1">{project.stars.toLocaleString('id-ID')} stars</span>
<span class="rounded-full border border-line px-2 py-1">{project.forks.toLocaleString('id-ID')} forks</span>
{updatedLabel && <span class="rounded-full border border-line px-2 py-1">Update {updatedLabel}</span>}
{project.homepage && <a class="relative z-20 rounded-full border border-line px-2 py-1 hover:text-brand" href={project.homepage}>Homepage</a>}
{homepageUrl && <a class="relative z-20 rounded-full border border-line px-2 py-1 hover:text-brand" href={homepageUrl}>Homepage</a>}
</div>
</article>
6 changes: 6 additions & 0 deletions src/lib/urls.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,9 @@ export function withBase(path: string) {
const baseUrl = import.meta.env.BASE_URL.replace(/\/?$/, '/');
return `${baseUrl}${path.replace(/^\/+/, '')}`;
}

export function normalizeHref(href: string) {
if (/^(https?:)?\/\//.test(href) || href.startsWith('mailto:')) return href;
if (/^[\w.-]+\.[a-z]{2,}(\/.*)?$/i.test(href)) return `https://${href}`;
return withBase(href);
}
59 changes: 58 additions & 1 deletion src/pages/projects/[slug].astro
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,62 @@ const repoName = project.fullName.split('/').at(-1) || project.fullName;

const root = document.querySelector('[data-readme-root]');
const apiUrl = root?.getAttribute('data-readme-api');
const unsafeSelectors = [
'script',
'style',
'iframe',
'object',
'embed',
'link',
'meta',
'svg',
'math',
'form',
'input',
'button',
'textarea',
'select'
].join(',');

function safeUrl(value: string, baseUrl: string) {
if (!value || value.startsWith('#')) return value;

try {
const url = new URL(value, baseUrl);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve repo-root README paths

When a README uses GitHub's supported repo-root-relative syntax such as [docs](/docs/guide.md) or ![logo](/assets/logo.png), resolving it with new URL(value, data.html_url/download_url) treats the leading slash as the domain root, producing https://github.com/docs/guide.md or https://raw.githubusercontent.com/assets/logo.png and dropping the owner/repo/branch. This breaks those README links and images on the project detail page; root-relative paths need to be resolved against the repository root URL rather than the file URL.

Useful? React with 👍 / 👎.

if (!['http:', 'https:', 'mailto:'].includes(url.protocol)) return '';
return url.toString();
} catch {
return '';
}
}

function sanitizeReadme(html: string, linkBaseUrl: string, assetBaseUrl: string) {
const document = new DOMParser().parseFromString(html, 'text/html');
document.querySelectorAll(unsafeSelectors).forEach((element) => element.remove());

document.body.querySelectorAll('*').forEach((element) => {
Array.from(element.attributes).forEach((attribute) => {
const name = attribute.name.toLowerCase();

if (name.startsWith('on') || name === 'style' || name === 'srcdoc') {
element.removeAttribute(attribute.name);
return;
}

if (name === 'href') {
const nextUrl = safeUrl(attribute.value, linkBaseUrl);
nextUrl ? element.setAttribute(attribute.name, nextUrl) : element.removeAttribute(attribute.name);
}

if (name === 'src') {
const nextUrl = safeUrl(attribute.value, assetBaseUrl);
nextUrl ? element.setAttribute(attribute.name, nextUrl) : element.removeAttribute(attribute.name);
}
});
});

return document.body.innerHTML;
}

async function loadReadme() {
if (!root || !apiUrl) return;
Expand All @@ -112,7 +168,8 @@ const repoName = project.fullName.split('/').at(-1) || project.fullName;
const binary = atob(data.content.replace(/\n/g, ''));
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
const markdown = new TextDecoder().decode(bytes);
root.innerHTML = await marked.parse(markdown);
const html = await marked.parse(markdown);
root.innerHTML = sanitizeReadme(html, data.html_url, data.download_url);
} catch (error) {
root.innerHTML = '<p>README belum bisa dimuat otomatis. Buka README langsung dari GitHub.</p>';
}
Expand Down
Loading