Skip to content

Commit ba1dc80

Browse files
authored
Merge pull request #29 from JonDevOps/claude/security-headers
Built-in docs at /docs, and security headers (#467)
2 parents 1b8e701 + 04a48d5 commit ba1dc80

29 files changed

Lines changed: 290 additions & 162 deletions

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ next dev` (see `src/firebase/initialize-app.ts` for the port settings).
5454
| `src/lib/types.ts` | Firestore document types |
5555
| `firestore.rules` | Who can read and write what |
5656
| `tests/rules` | Emulator tests for `firestore.rules` |
57-
| `docs-site` | The public docs at docs.w3develops.org (Mintlify: `docs.json` and `.mdx` pages) |
57+
| `src/content/docs` | The public docs at /docs: Markdown pages and `menu.json`, rendered by `src/app/docs` |
5858
| `src/lib/member-posts.ts` | Limits, blocked words and report reasons for the community feed (`/feed`) and `/moderation` |
5959

6060
## Rules to follow

‎docs-site/contributing/overview.mdx‎

Lines changed: 0 additions & 15 deletions
This file was deleted.

‎docs-site/docs.json‎

Lines changed: 0 additions & 51 deletions
This file was deleted.

‎docs-site/index.mdx‎

Lines changed: 0 additions & 27 deletions
This file was deleted.

‎docs-site/logo/logo.png‎

-142 KB
Binary file not shown.

‎docs-site/quickstart.mdx‎

Lines changed: 0 additions & 21 deletions
This file was deleted.

‎next.config.js‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,23 @@ const nextConfig = {
1616
// The community forum is the w3Develops Discord for now. Temporary (307)
1717
// redirects, so /forum can become a real page later without search
1818
// engines remembering the old destination.
19+
// Basic security headers on every page (issue #467). HSTS tells browsers
20+
// to use HTTPS only; the others stop the site being framed by other sites,
21+
// stop browsers guessing file types, limit what referrers reveal, and turn
22+
// off browser features the site doesn't use. Camera and microphone stay
23+
// allowed for the site itself.
24+
async headers() {
25+
return [{
26+
source: '/:path*',
27+
headers: [
28+
{ key: 'Strict-Transport-Security', value: 'max-age=63072000; includeSubDomains' },
29+
{ key: 'X-Frame-Options', value: 'SAMEORIGIN' },
30+
{ key: 'X-Content-Type-Options', value: 'nosniff' },
31+
{ key: 'Referrer-Policy', value: 'strict-origin-when-cross-origin' },
32+
{ key: 'Permissions-Policy', value: 'camera=(self), microphone=(self), geolocation=(), payment=(), usb=()' },
33+
],
34+
}];
35+
},
1936
async redirects() {
2037
return [
2138
{ source: '/forum', destination: 'https://discord.gg/ckQ52gA', permanent: false },

‎src/app/docs/[[...slug]]/page.tsx‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import type { Metadata } from 'next';
2+
import Link from 'next/link';
3+
import { notFound } from 'next/navigation';
4+
import { ChevronLeft, ChevronRight } from 'lucide-react';
5+
import Markdown, { headingId } from '@/components/articles/Markdown';
6+
import { DOCS_MENU, DOC_SLUGS, docHref, readDoc } from '@/lib/docs';
7+
import { sharePreview, SITE_NAME } from '@/lib/site-pages';
8+
9+
type Props = { params: Promise<{ slug?: string[] }> };
10+
11+
export function generateStaticParams() {
12+
return DOC_SLUGS.map(slug => ({ slug: slug === 'index' ? [] : slug.split('/') }));
13+
}
14+
15+
function slugOf(parts: string[] | undefined): string {
16+
return parts?.length ? parts.join('/') : 'index';
17+
}
18+
19+
export async function generateMetadata({ params }: Props): Promise<Metadata> {
20+
const page = readDoc(slugOf((await params).slug));
21+
if (!page) return { title: 'Docs', robots: { index: false } };
22+
const title = `${page.title} | Docs`;
23+
return { title, description: page.description, alternates: { canonical: docHref(page.slug) }, ...sharePreview(`${title} | ${SITE_NAME}`, page.description, docHref(page.slug)) };
24+
}
25+
26+
/** A Mintlify-style docs page: the menu, the page, and its headings */
27+
export default async function DocsPage({ params }: Props) {
28+
const page = readDoc(slugOf((await params).slug));
29+
if (!page) notFound();
30+
const index = DOC_SLUGS.indexOf(page.slug);
31+
const previous = index > 0 ? readDoc(DOC_SLUGS[index - 1]) : null;
32+
const next = index < DOC_SLUGS.length - 1 ? readDoc(DOC_SLUGS[index + 1]) : null;
33+
const headings = [...page.body.matchAll(/^## (.+)$/gm)].map(match => match[1]);
34+
35+
return (
36+
<div className="mx-auto grid max-w-7xl gap-8 p-4 md:p-10 lg:grid-cols-[220px_minmax(0,1fr)_200px]">
37+
<nav aria-label="Docs" className="space-y-6 text-sm lg:sticky lg:top-20 lg:max-h-[calc(100vh-6rem)] lg:self-start lg:overflow-y-auto">
38+
{DOCS_MENU.map(tab => (
39+
<div key={tab.tab} className="space-y-4">
40+
<p className="font-semibold uppercase tracking-wide text-muted-foreground text-xs">{tab.tab}</p>
41+
{tab.groups.map(group => (
42+
<div key={group.group} className="space-y-1">
43+
<p className="font-semibold">{group.group}</p>
44+
<ul className="space-y-1 border-l">
45+
{group.pages.map(slug => {
46+
const item = readDoc(slug);
47+
const current = slug === page.slug;
48+
return (
49+
<li key={slug}>
50+
<Link href={docHref(slug)} aria-current={current ? 'page' : undefined}
51+
className={`-ml-px block border-l py-1 pl-3 hover:text-foreground ${current ? 'border-primary font-medium text-foreground' : 'border-transparent text-muted-foreground'}`}>
52+
{item?.title}
53+
</Link>
54+
</li>
55+
);
56+
})}
57+
</ul>
58+
</div>
59+
))}
60+
</div>
61+
))}
62+
</nav>
63+
64+
<article className="min-w-0 space-y-6">
65+
<header className="space-y-2 border-b pb-6">
66+
<h1 className="text-3xl font-headline md:text-4xl">{page.title}</h1>
67+
<p className="text-lg text-muted-foreground">{page.description}</p>
68+
</header>
69+
<Markdown text={page.body} />
70+
<div className="flex justify-between gap-4 border-t pt-6 text-sm">
71+
{previous ? <Link href={docHref(previous.slug)} className="flex items-center gap-1 hover:text-primary"><ChevronLeft className="h-4 w-4" aria-hidden="true" />{previous.title}</Link> : <span />}
72+
{next && <Link href={docHref(next.slug)} className="flex items-center gap-1 text-right hover:text-primary">{next.title}<ChevronRight className="h-4 w-4" aria-hidden="true" /></Link>}
73+
</div>
74+
</article>
75+
76+
{headings.length > 0 && (
77+
<aside aria-label="On this page" className="hidden text-sm lg:sticky lg:top-20 lg:block lg:self-start">
78+
<p className="mb-2 font-semibold">On this page</p>
79+
<ul className="space-y-1">
80+
{headings.map(heading => <li key={heading}><a href={`#${headingId(heading)}`} className="text-muted-foreground hover:text-foreground">{heading}</a></li>)}
81+
</ul>
82+
</aside>
83+
)}
84+
</div>
85+
);
86+
}

‎src/app/sitemap.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import type { MetadataRoute } from 'next';
22
import { INDEXABLE_PATHS, SITE_URL } from '@/lib/site-pages';
33
import { listPublicItemPages } from '@/lib/public-items';
4+
import { DOC_SLUGS, docHref } from '@/lib/docs';
45

56
// Rebuilt at most once an hour, so new groups, meetups and jobs get listed
67
export const revalidate = 3600;
@@ -18,5 +19,7 @@ export default async function sitemap(): Promise<MetadataRoute.Sitemap> {
1819
url: `${SITE_URL}${path}`,
1920
...(lastModified && { lastModified }),
2021
}));
21-
return [...mainPages, ...itemPages];
22+
// The docs (/docs and its pages)
23+
const docPages = DOC_SLUGS.map(slug => ({ url: `${SITE_URL}${docHref(slug)}` }));
24+
return [...mainPages, ...docPages.filter(doc => !mainPages.some(main => main.url === doc.url)), ...itemPages];
2225
}

‎src/components/articles/Markdown.tsx‎

Lines changed: 32 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,17 @@ import { Fragment, type ReactNode } from 'react';
22

33
// A small, safe Markdown renderer for member articles: headings (## and ###),
44
// paragraphs, bullet and numbered lists, block quotes, fenced code blocks,
5-
// and inline `code`, **bold**, *italic* and [links](https://...). It builds
6-
// React elements and never inserts HTML, so nothing an author writes can run
7-
// as script. Only https links are made clickable.
5+
// simple tables, and inline `code`, **bold**, *italic* and
6+
// [links](https://...). It builds React elements and never inserts HTML, so
7+
// nothing an author writes can run as script. Only https links and links to
8+
// pages on this site (starting with "/") are made clickable.
89

9-
const INLINE = /(`[^`]+`)|(\*\*[^*]+\*\*)|(\*[^*]+\*)|(\[[^\]]+\]\(https:\/\/[^)\s]+\))/g;
10+
/** "Writing a good PR" → "writing-a-good-pr", for heading links */
11+
export function headingId(text: string): string {
12+
return text.toLowerCase().replace(/[`*]/g, '').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
13+
}
14+
15+
const INLINE = /(`[^`]+`)|(\*\*(?:\[[^\]]+\]\([^)\s]+\)|[^*])+\*\*)|(\*[^*]+\*)|(\[[^\]]+\]\((?:https:\/\/|\/(?!\/))[^)\s]*\))/g;
1016

1117
function inline(text: string): ReactNode[] {
1218
const parts: ReactNode[] = [];
@@ -16,11 +22,13 @@ function inline(text: string): ReactNode[] {
1622
const token = match[0];
1723
const key = parts.length;
1824
if (token.startsWith('`')) parts.push(<code key={key} className="rounded bg-muted px-1 py-0.5 text-sm">{token.slice(1, -1)}</code>);
19-
else if (token.startsWith('**')) parts.push(<strong key={key}>{token.slice(2, -2)}</strong>);
25+
else if (token.startsWith('**')) parts.push(<strong key={key}>{inline(token.slice(2, -2))}</strong>);
2026
else if (token.startsWith('*')) parts.push(<em key={key}>{token.slice(1, -1)}</em>);
2127
else {
2228
const [, label, href] = token.match(/^\[([^\]]+)\]\(([^)]+)\)$/)!;
23-
parts.push(<a key={key} href={href} target="_blank" rel="nofollow ugc noopener noreferrer" className="text-primary underline">{label}</a>);
29+
parts.push(href.startsWith('/')
30+
? <a key={key} href={href} className="text-primary underline">{label}</a>
31+
: <a key={key} href={href} target="_blank" rel="nofollow ugc noopener noreferrer" className="text-primary underline">{label}</a>);
2432
}
2533
last = match.index + token.length;
2634
}
@@ -42,10 +50,10 @@ export default function Markdown({ text }: { text: string }) {
4250
i++;
4351
blocks.push(<pre key={key} className="overflow-x-auto rounded-md bg-muted p-3 text-sm"><code>{code.join('\n')}</code></pre>);
4452
} else if (/^###\s/.test(line)) {
45-
blocks.push(<h3 key={key} className="mt-6 text-lg font-semibold">{inline(line.slice(4))}</h3>);
53+
blocks.push(<h3 key={key} id={headingId(line.slice(4))} className="mt-6 scroll-mt-20 text-lg font-semibold">{inline(line.slice(4))}</h3>);
4654
i++;
4755
} else if (/^##?\s/.test(line)) {
48-
blocks.push(<h2 key={key} className="mt-8 text-xl font-semibold">{inline(line.replace(/^##?\s/, ''))}</h2>);
56+
blocks.push(<h2 key={key} id={headingId(line.replace(/^##?\s/, ''))} className="mt-8 scroll-mt-20 text-xl font-semibold">{inline(line.replace(/^##?\s/, ''))}</h2>);
4957
i++;
5058
} else if (/^\s*[-*]\s/.test(line)) {
5159
const items: string[] = [];
@@ -55,6 +63,21 @@ export default function Markdown({ text }: { text: string }) {
5563
const items: string[] = [];
5664
while (i < lines.length && /^\s*\d+\.\s/.test(lines[i])) items.push(lines[i++].replace(/^\s*\d+\.\s/, ''));
5765
blocks.push(<ol key={key} className="list-decimal space-y-1 pl-6">{items.map((item, j) => <li key={j}>{inline(item)}</li>)}</ol>);
66+
} else if (line.startsWith('|')) {
67+
const rows: string[][] = [];
68+
while (i < lines.length && lines[i].startsWith('|')) {
69+
const cells = lines[i++].replace(/^\||\|$/g, '').split('|').map(cell => cell.trim());
70+
if (!cells.every(cell => /^:?-+:?$/.test(cell))) rows.push(cells);
71+
}
72+
const [head, ...body] = rows;
73+
blocks.push(
74+
<div key={key} className="overflow-x-auto">
75+
<table className="w-full border-collapse text-sm">
76+
<thead><tr>{head.map((cell, j) => <th key={j} className="border-b p-2 text-left font-semibold">{inline(cell)}</th>)}</tr></thead>
77+
<tbody>{body.map((row, r) => <tr key={r}>{row.map((cell, j) => <td key={j} className="border-b p-2 align-top">{inline(cell)}</td>)}</tr>)}</tbody>
78+
</table>
79+
</div>,
80+
);
5881
} else if (line.startsWith('>')) {
5982
const quote: string[] = [];
6083
while (i < lines.length && lines[i].startsWith('>')) quote.push(lines[i++].replace(/^>\s?/, ''));
@@ -63,7 +86,7 @@ export default function Markdown({ text }: { text: string }) {
6386
i++;
6487
} else {
6588
const paragraph: string[] = [];
66-
while (i < lines.length && lines[i].trim() && !/^(```|#{2,3}\s|\s*[-*]\s|\s*\d+\.\s|>)/.test(lines[i])) paragraph.push(lines[i++]);
89+
while (i < lines.length && lines[i].trim() && !/^(```|#{2,3}\s|\s*[-*]\s|\s*\d+\.\s|>|\|)/.test(lines[i])) paragraph.push(lines[i++]);
6790
blocks.push(<p key={key}>{paragraph.map((part, j) => <Fragment key={j}>{j > 0 && ' '}{inline(part)}</Fragment>)}</p>);
6891
}
6992
}

0 commit comments

Comments
 (0)