@vulcantech/blog 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +23 -2
- package/dist/index.d.mts +22 -4
- package/dist/index.d.ts +22 -4
- package/dist/index.js +14 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +14 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +36 -6
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Server-side blog fetch layer for VulcanTech consumer sites. Reads published posts from the CMS with Next.js ISR tags, and supports signed draft-preview tokens so unpublished posts can be reviewed on the live site. Shared so each site stops duplicating `lib/cms/blog.ts`.
|
|
4
4
|
|
|
5
|
-
**Exports**: `fetchBlogPosts`, `fetchBlogPostBySlug`, `resolvePreviewToken`, `GET` (the draft-preview route handler), `tagsForBlogList` / `tagsForBlogPost`, `sanitizeHtml`, and the `CMSBlogPost` / `CMSBlogAuthor` / `CMSVideoDescriptor` types.
|
|
5
|
+
**Exports**: `fetchBlogPosts`, `fetchBlogPostBySlug`, `resolvePreviewToken`, `GET` (the draft-preview route handler), `tagsForBlogList` / `tagsForBlogPost`, `sanitizeHtml`, and the `CMSBlogPost` / `CMSBlogAuthor` / `CMSVideoDescriptor` / `FetchOptions` / `FetchPostsOptions` / `FetchPostOptions` types.
|
|
6
6
|
|
|
7
7
|
**Server-only** — uses `VULCANTECH_API_KEY`; import from server components / route handlers only.
|
|
8
8
|
|
|
@@ -44,9 +44,30 @@ Field notes:
|
|
|
44
44
|
- **`metadata`** is a case-study spec sheet (e.g. `Make: 1969 Camaro`, `Engine: LS3`). The CMS only offers the editor when `postType` is `"case-study"`; render it as a spec/details table on case-study layouts and ignore it everywhere else — do not dump it onto regular articles.
|
|
45
45
|
- **`status`** — the public fetchers only ever return `published` posts (or a token-unlocked draft in preview mode), so you never need to filter by status yourself.
|
|
46
46
|
|
|
47
|
+
### What's inside `content`
|
|
48
|
+
|
|
49
|
+
The editor is TipTap (StarterKit + a few nodes), and the CMS sanitizes on write against a fixed allowlist, so the markup vocabulary is small and known:
|
|
50
|
+
|
|
51
|
+
- **Blocks**: `p`, `h2`–`h6`, `ul`/`ol`/`li`, `blockquote`, `pre > code`, `hr`, tables, `details`/`summary` (native toggles, used by documentation posts). Headings start at `h2` by convention — the editor toolbar offers H2–H6 and `h1` is left for your `<h1>{post.title}</h1>` — though the sanitizer permits `h1`, so imported/legacy content *may* carry one. There are no task lists.
|
|
52
|
+
- **Inline**: `strong`/`em`/`u`/`s`, inline `code`, `sub`/`sup`/`mark`, and `a` — links are written with `target="_blank" rel="noopener noreferrer"` already set.
|
|
53
|
+
- **Images** arrive as plain `<img>` with `class="rounded-lg my-4 max-w-full h-auto"` and **no width/height attributes**. Two consequences: `next/image` is not usable inside `content` (no dimensions, and it's raw HTML) — render the body as-is; and Tailwind cannot scan CMS content, so those utility classes only take effect if your build already emits them. Add a plain CSS rule to be safe (this is the most common overflow bug, more so than videos):
|
|
54
|
+
|
|
55
|
+
```css
|
|
56
|
+
.blog-content img { max-width: 100%; height: auto; border-radius: 0.5rem; margin: 1rem 0; }
|
|
57
|
+
```
|
|
58
|
+
- **Image galleries** serialize to an *empty* `<div class="cms-gallery" data-gallery='[…]'>` — it renders as **nothing** unless you hydrate it. Inside the monorepo, `BlogCarousel` from `ui/src/portfolio` reads `data-gallery`; without a hydrator, expect a silent gap where the gallery was.
|
|
59
|
+
- **Tables** arrive unstyled and non-resizable (no width attributes, every cell's text `<p>`-wrapped) — borders, padding, and overflow scrolling are entirely your CSS's job.
|
|
60
|
+
- **Inline styling does not survive.** Both sanitizers strip `style` attributes and `<style>` tags on write, so any inline color/size/alignment an editor applies silently disappears on the consumer site. That is by design (CSS-injection surface) — editors reporting "my formatting vanished" are seeing this, not a bug in your site.
|
|
61
|
+
|
|
62
|
+
Because of all this, a typographic wrapper (`@tailwindcss/typography`'s `prose`, or hand-written styles scoped to your content container) is expected — the HTML itself carries no presentation beyond the image classes above.
|
|
63
|
+
|
|
47
64
|
### Fetching and failure mode
|
|
48
65
|
|
|
49
|
-
`fetchBlogPosts(options?)` accepts server-side filters — `category`, `routePrefix`, `tag`, `search`, `limit`, and `startAfter` (a pagination cursor: the `id` of the last post of the previous page) — plus the caching knobs `revalidate` (default 60s), `extraTags`, and `noStore`. Prefer these filters over fetching everything and filtering client-side
|
|
66
|
+
`fetchBlogPosts(options?)` returns posts **newest-first by `publishedAt`** — the CMS orders them; do not add your own sort. It accepts server-side filters — `category`, `routePrefix`, `tag`, `search`, `limit`, and `startAfter` (a pagination cursor: the `id` of the last post of the previous page) — plus the caching knobs `revalidate` (default 60s), `extraTags`, and `noStore`. Prefer these filters over fetching everything and filtering client-side, with one exception:
|
|
67
|
+
|
|
68
|
+
- **Don't pass `routePrefix: "blog"` for the blog itself.** Legacy posts predate the field and have no prefix, so that filter would exclude them. Filter the blog list client-side with an `isBlogPost` predicate (see Scoped routes below); pass `routePrefix` only for non-blog scopes like `"documentation"`.
|
|
69
|
+
|
|
70
|
+
**Pagination**: the response is a bare post list — there is no `hasMore` or `total`. To paginate, fetch `limit + 1`: if you get more than `limit` posts there is another page — drop the extra and pass the last *kept* post's `id` as the next `startAfter`.
|
|
50
71
|
|
|
51
72
|
**The fetchers never throw.** On any CMS error (unreachable, non-2xx, unconfigured env) they log a warning and return `[]` / `null`. So: no try/catch error UI — it can never fire. Instead, handle the empty list on index pages and call `notFound()` on a `null` post.
|
|
52
73
|
|
package/dist/index.d.mts
CHANGED
|
@@ -95,6 +95,13 @@ interface CMSBlogPost {
|
|
|
95
95
|
* `dangerouslySetInnerHTML`; do not run it through a markdown renderer.
|
|
96
96
|
* Sanitized on write by the CMS and re-sanitized by this package's fetchers,
|
|
97
97
|
* so it is safe to inject as-is.
|
|
98
|
+
*
|
|
99
|
+
* Markup contract (see the README's "What's inside content" for the full
|
|
100
|
+
* story): headings start at h2 (h1 is yours, for the title); images are
|
|
101
|
+
* plain `<img>` with no dimensions — `next/image` is not usable here, style
|
|
102
|
+
* `img` with CSS; galleries are empty `div.cms-gallery[data-gallery]` nodes
|
|
103
|
+
* that render as nothing unless hydrated; inline `style` never survives the
|
|
104
|
+
* sanitizers, so bring your own typography (e.g. a `prose` wrapper).
|
|
98
105
|
*/
|
|
99
106
|
content: string;
|
|
100
107
|
/** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */
|
|
@@ -165,13 +172,22 @@ interface FetchOptions {
|
|
|
165
172
|
interface FetchPostsOptions extends FetchOptions {
|
|
166
173
|
/** Exact-match on the post's `category`. */
|
|
167
174
|
category?: string;
|
|
168
|
-
/**
|
|
175
|
+
/**
|
|
176
|
+
* Only return posts under this route prefix (e.g. "documentation"). Don't
|
|
177
|
+
* pass "blog" for the blog itself — legacy posts predate the field and have
|
|
178
|
+
* no prefix, so they'd be excluded; filter the blog list client-side instead
|
|
179
|
+
* (see the README's Scoped routes section).
|
|
180
|
+
*/
|
|
169
181
|
routePrefix?: string;
|
|
170
182
|
/** Posts whose `tags` include this tag. */
|
|
171
183
|
tag?: string;
|
|
172
184
|
/** Full-text search across title/content. */
|
|
173
185
|
search?: string;
|
|
174
|
-
/**
|
|
186
|
+
/**
|
|
187
|
+
* Page size; combine with `startAfter` to paginate. The response carries no
|
|
188
|
+
* `hasMore`/`total` — fetch `limit + 1`, and if more than `limit` arrive
|
|
189
|
+
* there is another page (drop the extra).
|
|
190
|
+
*/
|
|
175
191
|
limit?: number;
|
|
176
192
|
/** Pagination cursor: the `id` of the last post from the previous page. */
|
|
177
193
|
startAfter?: string;
|
|
@@ -190,8 +206,10 @@ declare function tagsForBlogList(projectId: string): string[];
|
|
|
190
206
|
/** ISR tags for a single post (post-specific + project-wide). */
|
|
191
207
|
declare function tagsForBlogPost(projectId: string, slug: string): string[];
|
|
192
208
|
/**
|
|
193
|
-
* Fetch published posts for the configured project
|
|
194
|
-
* (
|
|
209
|
+
* Fetch published posts for the configured project, newest-first by
|
|
210
|
+
* `publishedAt` (the CMS orders them — no client-side sort needed). Optional
|
|
211
|
+
* filters (category/routePrefix/tag/search/limit/startAfter) are forwarded to
|
|
212
|
+
* the CMS.
|
|
195
213
|
*
|
|
196
214
|
* Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it
|
|
197
215
|
* logs a warning and returns `[]` — render an empty state instead of wrapping
|
package/dist/index.d.ts
CHANGED
|
@@ -95,6 +95,13 @@ interface CMSBlogPost {
|
|
|
95
95
|
* `dangerouslySetInnerHTML`; do not run it through a markdown renderer.
|
|
96
96
|
* Sanitized on write by the CMS and re-sanitized by this package's fetchers,
|
|
97
97
|
* so it is safe to inject as-is.
|
|
98
|
+
*
|
|
99
|
+
* Markup contract (see the README's "What's inside content" for the full
|
|
100
|
+
* story): headings start at h2 (h1 is yours, for the title); images are
|
|
101
|
+
* plain `<img>` with no dimensions — `next/image` is not usable here, style
|
|
102
|
+
* `img` with CSS; galleries are empty `div.cms-gallery[data-gallery]` nodes
|
|
103
|
+
* that render as nothing unless hydrated; inline `style` never survives the
|
|
104
|
+
* sanitizers, so bring your own typography (e.g. a `prose` wrapper).
|
|
98
105
|
*/
|
|
99
106
|
content: string;
|
|
100
107
|
/** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */
|
|
@@ -165,13 +172,22 @@ interface FetchOptions {
|
|
|
165
172
|
interface FetchPostsOptions extends FetchOptions {
|
|
166
173
|
/** Exact-match on the post's `category`. */
|
|
167
174
|
category?: string;
|
|
168
|
-
/**
|
|
175
|
+
/**
|
|
176
|
+
* Only return posts under this route prefix (e.g. "documentation"). Don't
|
|
177
|
+
* pass "blog" for the blog itself — legacy posts predate the field and have
|
|
178
|
+
* no prefix, so they'd be excluded; filter the blog list client-side instead
|
|
179
|
+
* (see the README's Scoped routes section).
|
|
180
|
+
*/
|
|
169
181
|
routePrefix?: string;
|
|
170
182
|
/** Posts whose `tags` include this tag. */
|
|
171
183
|
tag?: string;
|
|
172
184
|
/** Full-text search across title/content. */
|
|
173
185
|
search?: string;
|
|
174
|
-
/**
|
|
186
|
+
/**
|
|
187
|
+
* Page size; combine with `startAfter` to paginate. The response carries no
|
|
188
|
+
* `hasMore`/`total` — fetch `limit + 1`, and if more than `limit` arrive
|
|
189
|
+
* there is another page (drop the extra).
|
|
190
|
+
*/
|
|
175
191
|
limit?: number;
|
|
176
192
|
/** Pagination cursor: the `id` of the last post from the previous page. */
|
|
177
193
|
startAfter?: string;
|
|
@@ -190,8 +206,10 @@ declare function tagsForBlogList(projectId: string): string[];
|
|
|
190
206
|
/** ISR tags for a single post (post-specific + project-wide). */
|
|
191
207
|
declare function tagsForBlogPost(projectId: string, slug: string): string[];
|
|
192
208
|
/**
|
|
193
|
-
* Fetch published posts for the configured project
|
|
194
|
-
* (
|
|
209
|
+
* Fetch published posts for the configured project, newest-first by
|
|
210
|
+
* `publishedAt` (the CMS orders them — no client-side sort needed). Optional
|
|
211
|
+
* filters (category/routePrefix/tag/search/limit/startAfter) are forwarded to
|
|
212
|
+
* the CMS.
|
|
195
213
|
*
|
|
196
214
|
* Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it
|
|
197
215
|
* logs a warning and returns `[]` — render an empty state instead of wrapping
|
package/dist/index.js
CHANGED
|
@@ -165,7 +165,13 @@ async function fetchBlogPosts(options = {}) {
|
|
|
165
165
|
console.warn(`[cms/blog] /api/blog returned ${res.status}`);
|
|
166
166
|
return [];
|
|
167
167
|
}
|
|
168
|
-
|
|
168
|
+
let json;
|
|
169
|
+
try {
|
|
170
|
+
json = await res.json();
|
|
171
|
+
} catch (err) {
|
|
172
|
+
console.warn("[cms/blog] /api/blog returned non-JSON:", err.message);
|
|
173
|
+
return [];
|
|
174
|
+
}
|
|
169
175
|
return (json.posts ?? []).map(sanitizePost);
|
|
170
176
|
}
|
|
171
177
|
async function fetchBlogPostBySlug(slug, options = {}) {
|
|
@@ -194,7 +200,13 @@ async function fetchBlogPostBySlug(slug, options = {}) {
|
|
|
194
200
|
console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);
|
|
195
201
|
return null;
|
|
196
202
|
}
|
|
197
|
-
|
|
203
|
+
let json;
|
|
204
|
+
try {
|
|
205
|
+
json = await res.json();
|
|
206
|
+
} catch (err) {
|
|
207
|
+
console.warn(`[cms/blog] /api/blog/${slug} returned non-JSON:`, err.message);
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
198
210
|
return json.post ? sanitizePost(json.post) : null;
|
|
199
211
|
}
|
|
200
212
|
var PREVIEW_COOKIE = "vt_preview_token";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sanitize.ts","../src/index.ts"],"names":["NextResponse","draftMode","cookies"],"mappings":";;;;;;;;AAiBA,IAAM,cAAA,GAAiB;AAAA,EACrB,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,OAAA;AAAA,EAAS,MAAA;AAAA,EAAQ,OAAA;AAAA,EAAS,UAAA;AAAA,EAC9C,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,QAAA;AAAA,EACtD,OAAA;AAAA,EAAS,UAAA;AAAA,EAAY,OAAA;AAAA,EAAS,OAAA;AAAA,EAAS,KAAA;AAAA,EAAO,MAAA;AAAA,EAAQ,KAAA;AAAA,EACtD,UAAA;AAAA,EAAY;AACd,CAAA;AASA,IAAM,iBAAA,GACJ,qGAAA;AAEF,SAAS,cAAc,CAAA,EAAmB;AACxC,EAAA,IAAI,CAAC,OAAO,QAAA,CAAS,CAAC,KAAK,CAAA,GAAI,CAAA,IAAK,CAAA,GAAI,OAAA,EAAU,OAAO,EAAA;AACzD,EAAA,IAAI;AACF,IAAA,OAAO,MAAA,CAAO,cAAc,CAAC,CAAA;AAAA,EAC/B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAA;AAAA,EACT;AACF;AAGA,SAAS,eAA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sync. Duplicated rather than\n * imported so this package stays dependency-free (no `ui` workspace coupling).\n *\n * Defense-in-depth only. As of audit L4 / BL-023, blog HTML is sanitized ON\n * WRITE by the CMS's parser-based DOMPurify sanitizer\n * (apps/vulcantech-cms/src/lib/html/sanitizeHtml.ts), so the content this\n * package fetches is already clean. This boundary pass is a safety net for\n * legacy/unexpected data, not the primary guarantee.\n *\n * Strips dangerous tags and attributes and neutralizes dangerous URL schemes,\n * decoding HTML entities first so entity-encoded `javascript:` payloads can't\n * slip past the scheme check.\n */\n\nconst DANGEROUS_TAGS = [\n \"script\", \"object\", \"embed\", \"form\", \"input\", \"textarea\",\n \"button\", \"select\", \"option\", \"link\", \"meta\", \"base\", \"applet\",\n \"frame\", \"frameset\", \"layer\", \"style\", \"svg\", \"math\", \"xmp\",\n \"noscript\", \"template\",\n];\n\n/**\n * `iframe` is NOT in the blocklist above: blog HTML may carry a YouTube video\n * embed (BL-321). It is filtered by origin instead — an iframe pointing\n * anywhere but YouTube's embed path is deleted, element and content alike, by\n * {@link stripForeignIframes}. `<video>` needs no rule: it was never blocked\n * here, and its `src` still goes through the URL-scheme pass below.\n */\nconst YOUTUBE_EMBED_SRC =\n /^https:\\/\\/(?:www\\.)?(?:youtube-nocookie\\.com|youtube\\.com)\\/embed\\/[A-Za-z0-9_-]{6,20}(?:[?#].*)?$/;\n\nfunction safeCodePoint(n: number): string {\n if (!Number.isFinite(n) || n < 0 || n > 0x10ffff) return \"\";\n try {\n return String.fromCodePoint(n);\n } catch {\n return \"\";\n }\n}\n\n/** Decode numeric and a few named HTML entities used to obfuscate URL schemes. */\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&#x([0-9a-f]+);?/gi, (_, h) => safeCodePoint(parseInt(h, 16)))\n .replace(/&#(\\d+);?/g, (_, d) => safeCodePoint(parseInt(d, 10)))\n .replace(/:/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&/gi, \"&\");\n}\n\n/** Drop spaces and C0 control chars (code point <= 0x20) used to break up schemes. */\nfunction stripBlankAndControl(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch.codePointAt(0)! > 0x20) out += ch;\n }\n return out;\n}\n\n/**\n * Remove every `<iframe>` whose `src` is not a YouTube embed URL, taking any\n * content between the tags with it.\n */\nfunction stripForeignIframes(html: string): string {\n return html.replace(\n /<iframe\\b[^>]*>(?:[\\s\\S]*?<\\/iframe>)?/gi,\n (element) => {\n const match = /\\bsrc\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/i.exec(element);\n const raw = match ? (match[2] ?? match[3] ?? match[4] ?? \"\") : \"\";\n const src = stripBlankAndControl(decodeEntities(raw));\n return YOUTUBE_EMBED_SRC.test(src) ? element : \"\";\n },\n );\n}\n\n/**\n * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe\n * URL schemes. Returns the cleaned HTML string.\n *\n * The package's fetchers already run every post's `content` through this, so\n * call it only for CMS HTML obtained some other way (legacy exports, custom\n * endpoints).\n */\nexport function sanitizeHtml(html: string): string {\n if (!html) return \"\";\n\n let clean = html.replace(\n /<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/gi,\n \"\",\n );\n\n for (const tag of DANGEROUS_TAGS) {\n clean = clean.replace(\n new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"gi\"),\n \"\",\n );\n clean = clean.replace(new RegExp(`<${tag}\\\\b[^>]*\\\\/?>`, \"gi\"), \"\");\n }\n\n // Keep YouTube video embeds, drop every other iframe.\n clean = stripForeignIframes(clean);\n\n clean = clean.replace(\n /\\s+on\\w+\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\s+style\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\b(href|src)\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/gi,\n (match, attr, _raw, dq, sq, uq) => {\n const value = dq ?? sq ?? uq ?? \"\";\n const decoded = stripBlankAndControl(decodeEntities(value)).toLowerCase();\n if (/^(javascript|data|vbscript):/.test(decoded)) {\n return `${attr}=\"about:blank\"`;\n }\n return match;\n },\n );\n\n return clean;\n}\n","/**\n * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer\n * sites.\n *\n * Reads published blog posts from the CMS with Next.js ISR tags so the CMS\n * can purge a post (via /api/revalidate) the moment it changes, and supports\n * signed draft-preview tokens so an unpublished post can be rendered on the\n * real site for review.\n *\n * Config comes from the same env vars every consumer already sets — no\n * per-app wiring beyond importing this package:\n * VULCANTECH_CMS_URL (default https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID (required)\n * VULCANTECH_API_KEY (required)\n * VULCANTECH_BLOG_NO_CACHE (\"1\" | \"true\" → bypass ISR everywhere)\n *\n * SERVER-ONLY: relies on VULCANTECH_API_KEY (no NEXT_PUBLIC_ prefix), so it\n * must only be imported from server components / route handlers.\n *\n * Errors are graceful by design — a CMS hiccup returns [] / null and logs a\n * warning rather than throwing, so a marketing site never hard-crashes on a\n * transient CMS outage.\n *\n * Draft preview (Next.js Draft Mode):\n * - Re-export `GET` from app/api/preview/route.ts on each consumer.\n * - Call `resolvePreviewToken()` in the blog post page and pass the result\n * to fetchBlogPostBySlug as { previewToken }.\n * The public /blog/[slug] route stays static/ISR; only a request carrying\n * the Draft Mode cookie renders the unpublished draft.\n */\n\nimport { cookies, draftMode } from \"next/headers\";\nimport { NextResponse, type NextRequest } from \"next/server\";\nimport { sanitizeHtml } from \"./sanitize\";\n\nconst DEFAULT_REVALIDATE_SECONDS = 60;\n\nexport interface CMSBlogAuthor {\n uid?: string;\n name: string;\n avatar?: string;\n}\n\n/**\n * A supplementary video attached to a post, normalized by the CMS.\n *\n * Structural copy of the CMS's canonical `VideoDescriptor`\n * (`packages/blog-editor-shared/src/lib/video.ts`) — inlined rather than\n * imported so this package stays dependency-free for consumer sites. Keep the\n * shape in sync; the CMS validates every write against the original.\n *\n * `videoId` is safe to interpolate into a YouTube embed URL and `url` is always\n * on the CMS media host — the CMS pins both, so a consumer never has to\n * re-validate before rendering.\n */\nexport type CMSVideoDescriptor =\n | { provider: \"youtube\"; videoId: string }\n | { provider: \"youtube-short\"; videoId: string }\n | { provider: \"file\"; url: string; poster?: string };\n\nexport interface CMSBlogPost {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n /**\n * Sanitized HTML (TipTap editor output) — NOT markdown. Render with\n * `dangerouslySetInnerHTML`; do not run it through a markdown renderer.\n * Sanitized on write by the CMS and re-sanitized by this package's fetchers,\n * so it is safe to inject as-is.\n */\n content: string;\n /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */\n excerpt: string;\n /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */\n category?: string;\n /** URL route segment the post lives under, e.g. \"blog\" or \"documentation\". */\n routePrefix?: string;\n tags: string[];\n /**\n * Comma-separated SEO keywords the CMS derives from the post's dedicated\n * keyword fields (target keyword first). Feed straight into\n * `Metadata.keywords`; absent when the post has no keywords set.\n */\n keywords?: string;\n /** An object, not a string — display `author.name`. */\n author: CMSBlogAuthor;\n /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */\n featuredImage?: string;\n /**\n * Optional supplementary video for the post. Purely advisory — render it as a\n * hero player, a card thumbnail, or ignore it; nothing breaks when it's\n * absent, and it is absent on most posts. Videos placed *inside* the article\n * arrive as playable markup within `content` instead.\n */\n featuredVideo?: CMSVideoDescriptor;\n /** The public fetchers only ever return \"published\" posts (or a token-unlocked draft). */\n status: \"draft\" | \"in_review\" | \"published\" | \"archived\";\n /** ISO 8601 timestamp. Always present on published posts. */\n publishedAt?: string;\n /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */\n scheduledAt?: string;\n /** ISO 8601 timestamp. */\n createdAt: string;\n /** ISO 8601 timestamp. */\n updatedAt: string;\n /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */\n seoTitle?: string;\n /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */\n seoDescription?: string;\n /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */\n ogImage?: string;\n /** Defaults to \"article\" when absent (the field predates postType). */\n postType?: \"article\" | \"case-study\" | \"announcement\";\n /**\n * Spec-sheet pairs for case studies (e.g. `{ label: \"Make\", value: \"1969\n * Camaro\" }`) — the CMS only shows this editor when `postType` is\n * \"case-study\". Render as a spec table on case-study layouts; ignore\n * everywhere else.\n */\n metadata?: { label: string; value: string }[];\n}\n\nexport interface FetchOptions {\n /** Override the per-fetch revalidate window. Default: 60 seconds. */\n revalidate?: number;\n /** Extra ISR tags to attach to the fetch. */\n extraTags?: string[];\n /** Skip Next's ISR cache for this call. */\n noStore?: boolean;\n}\n\n/**\n * List filters, all applied server-side by the CMS — prefer these over\n * fetching everything and filtering client-side.\n */\nexport interface FetchPostsOptions extends FetchOptions {\n /** Exact-match on the post's `category`. */\n category?: string;\n /** Only return posts under this route prefix (e.g. \"documentation\"). */\n routePrefix?: string;\n /** Posts whose `tags` include this tag. */\n tag?: string;\n /** Full-text search across title/content. */\n search?: string;\n /** Page size; combine with `startAfter` to paginate. */\n limit?: number;\n /** Pagination cursor: the `id` of the last post from the previous page. */\n startAfter?: string;\n}\n\nexport interface FetchPostOptions extends FetchOptions {\n /**\n * A signed preview token (from the CMS) that unlocks an unpublished post.\n * When set, the cache is bypassed automatically — preview content must\n * never be cached or served to the public.\n */\n previewToken?: string;\n}\n\nfunction cmsUrl(): string {\n return process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n}\n\nfunction bypassCache(): boolean {\n return (\n process.env.VULCANTECH_BLOG_NO_CACHE === \"1\" ||\n process.env.VULCANTECH_BLOG_NO_CACHE === \"true\"\n );\n}\n\nfunction assertConfig(): { projectId: string; apiKey: string } | null {\n const projectId = process.env.VULCANTECH_PROJECT_ID;\n const apiKey = process.env.VULCANTECH_API_KEY;\n if (!projectId || !apiKey) {\n console.warn(\n \"[cms/blog] CMS not configured — set VULCANTECH_PROJECT_ID and VULCANTECH_API_KEY\",\n );\n return null;\n }\n return { projectId, apiKey };\n}\n\nexport { sanitizeHtml };\n\n/** Sanitize a post's HTML body so every consumer render is safe by default. */\nfunction sanitizePost(post: CMSBlogPost): CMSBlogPost {\n if (post && typeof post.content === \"string\") {\n return { ...post, content: sanitizeHtml(post.content) };\n }\n return post;\n}\n\n/** ISR tag for a project's blog list. */\nexport function tagsForBlogList(projectId: string): string[] {\n return [`blog:${projectId}`];\n}\n\n/** ISR tags for a single post (post-specific + project-wide). */\nexport function tagsForBlogPost(projectId: string, slug: string): string[] {\n return [`blog:${projectId}:${slug}`, `blog:${projectId}`];\n}\n\nfunction buildInit(\n tags: string[],\n options: FetchOptions,\n): RequestInit & { next?: { revalidate?: number; tags?: string[] } } {\n const skipCache = options.noStore || bypassCache();\n if (skipCache) return { cache: \"no-store\" };\n return {\n next: {\n revalidate: options.revalidate ?? DEFAULT_REVALIDATE_SECONDS,\n tags: [...tags, ...(options.extraTags ?? [])],\n },\n };\n}\n\n/**\n * Fetch published posts for the configured project. Optional filters\n * (category/routePrefix/tag/search/limit/startAfter) are forwarded to the CMS.\n *\n * Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it\n * logs a warning and returns `[]` — render an empty state instead of wrapping\n * in try/catch.\n */\nexport async function fetchBlogPosts(\n options: FetchPostsOptions = {},\n): Promise<CMSBlogPost[]> {\n const config = assertConfig();\n if (!config) return [];\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey, status: \"published\" });\n if (options.category) params.set(\"category\", options.category);\n if (options.routePrefix) params.set(\"routePrefix\", options.routePrefix);\n if (options.tag) params.set(\"tag\", options.tag);\n if (options.search) params.set(\"search\", options.search);\n if (options.limit) params.set(\"limit\", String(options.limit));\n if (options.startAfter) params.set(\"startAfter\", options.startAfter);\n\n const url = `${cmsUrl()}/api/blog?${params.toString()}`;\n const init = buildInit(tagsForBlogList(projectId), options);\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\"[cms/blog] CMS unreachable:\", (err as Error).message);\n return [];\n }\n if (res.status === 404) {\n console.warn(\"[cms/blog] /api/blog returned 404 — CMS may need redeployment\");\n return [];\n }\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog returned ${res.status}`);\n return [];\n }\n\n const json = (await res.json()) as { posts: CMSBlogPost[] };\n return (json.posts ?? []).map(sanitizePost);\n}\n\n/**\n * Fetch a single post by slug. Returns null when not found.\n *\n * Never throws: CMS errors also return `null` (with a logged warning), so\n * treat `null` as \"show notFound()\" rather than catching exceptions.\n *\n * Pass `previewToken` (minted by the CMS) to render an unpublished draft for\n * review — that automatically bypasses the cache.\n */\nexport async function fetchBlogPostBySlug(\n slug: string,\n options: FetchPostOptions = {},\n): Promise<CMSBlogPost | null> {\n const config = assertConfig();\n if (!config) return null;\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey });\n if (options.previewToken) params.set(\"preview\", options.previewToken);\n\n const url = `${cmsUrl()}/api/blog/${encodeURIComponent(slug)}?${params.toString()}`;\n // Preview responses must never be cached.\n const init = buildInit(tagsForBlogPost(projectId, slug), {\n ...options,\n noStore: options.noStore || !!options.previewToken,\n });\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\n `[cms/blog] CMS unreachable for \"${slug}\":`,\n (err as Error).message,\n );\n return null;\n }\n if (res.status === 404) return null;\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);\n return null;\n }\n\n const json = (await res.json()) as { post: CMSBlogPost };\n return json.post ? sanitizePost(json.post) : null;\n}\n\n/* ─── Draft preview (Next.js Draft Mode) ─── */\n\nconst PREVIEW_COOKIE = \"vt_preview_token\";\nconst PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60; // 2 hours\n\n/**\n * Route handler for `/api/preview?token=…&slug=…`.\n *\n * Validates the token against the CMS, enables Next Draft Mode, stores the\n * token in an httpOnly cookie, and redirects to the post — which then renders\n * the draft (see resolvePreviewToken). On an invalid/expired token it just\n * redirects to the public page (which 404s if the post isn't published).\n *\n * Each consumer wires it up with one line:\n * // app/api/preview/route.ts\n * export { GET } from \"@vulcantech/blog\";\n */\nexport async function GET(request: NextRequest): Promise<Response> {\n const { searchParams } = new URL(request.url);\n const token = searchParams.get(\"token\");\n const slug = searchParams.get(\"slug\");\n\n if (!token || !slug) {\n return NextResponse.json(\n { error: \"token and slug are required\" },\n { status: 400 },\n );\n }\n\n const target = new URL(`/blog/${encodeURIComponent(slug)}`, request.url);\n\n // Validate by asking the CMS to resolve the draft with this token.\n const post = await fetchBlogPostBySlug(slug, { previewToken: token });\n if (!post) {\n return NextResponse.redirect(target);\n }\n\n (await draftMode()).enable();\n (await cookies()).set(PREVIEW_COOKIE, token, {\n httpOnly: true,\n sameSite: \"lax\",\n secure: process.env.NODE_ENV === \"production\",\n path: \"/\",\n maxAge: PREVIEW_MAX_AGE_SECONDS,\n });\n\n return NextResponse.redirect(target);\n}\n\n/**\n * Page helper: returns the active preview token when Draft Mode is on, else\n * undefined. Call it in the blog post server component and spread the result\n * into the fetch:\n *\n * const previewToken = await resolvePreviewToken();\n * const post = await fetchBlogPostBySlug(slug, { previewToken });\n *\n * Reading the cookie only happens when Draft Mode is enabled, so the public\n * route stays statically rendered for normal visitors.\n */\nexport async function resolvePreviewToken(): Promise<string | undefined> {\n const { isEnabled } = await draftMode();\n if (!isEnabled) return undefined;\n const store = await cookies();\n return store.get(PREVIEW_COOKIE)?.value;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/sanitize.ts","../src/index.ts"],"names":["NextResponse","draftMode","cookies"],"mappings":";;;;;;;;AAiBA,IAAM,cAAA,GAAiB;AAAA,EACrB,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,OAAA;AAAA,EAAS,MAAA;AAAA,EAAQ,OAAA;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AS,IAAI,GAAA,CAAI,CAAA,MAAA,EAAS,mBAAmB,IAAI,CAAC,CAAA,CAAA,EAAI,OAAA,CAAQ,GAAG,CAAA;AAGvE,EAAA,MAAM,OAAO,MAAM,mBAAA,CAAoB,MAAM,EAAE,YAAA,EAAc,OAAO,CAAA;AACpE,EAAA,IAAI,CAAC,IAAA,EAAM;AACT,IAAA,OAAOA,mBAAA,CAAa,SAAS,MAAM,CAAA;AAAA,EACrC;AAEA,EAAA,CAAC,MAAMC,iBAAA,EAAU,EAAG,MAAA,EAAO;AAC3B,EAAA,CAAC,MAAMC,eAAA,EAAQ,EAAG,GAAA,CAAI,gBAAgB,KAAA,EAAO;AAAA,IAC3C,QAAA,EAAU,IAAA;AAAA,IACV,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,OAAA,CAAQ,GAAA,CAAI,QAAA,KAAa,YAAA;AAAA,IACjC,IAAA,EAAM,GAAA;AAAA,IACN,MAAA,EAAQ;AAAA,GACT,CAAA;AAED,EAAA,OAAOF,mBAAA,CAAa,SAAS,MAAM,CAAA;AACrC;AAaA,eAAsB,mBAAA,GAAmD;AACvE,EAAA,MAAM,EAAE,SAAA,EAAU,GAAI,MAAMC,iBAAA,EAAU;AACtC,EAAA,IAAI,CAAC,WAAW,OAAO,MAAA;AACvB,EAAA,MAAM,KAAA,GAAQ,MAAMC,eAAA,EAAQ;AAC5B,EAAA,OAAO,KAAA,CAAM,GAAA,CAAI,cAAc,CAAA,EAAG,KAAA;AACpC","file":"index.js","sourcesContent":["/**\n * HTML sanitizer for user-generated (TipTap) content.\n *\n * MIRROR of packages/ui/sanitize.ts — keep in sync. Duplicated rather than\n * imported so this package stays dependency-free (no `ui` workspace coupling).\n *\n * Defense-in-depth only. As of audit L4 / BL-023, blog HTML is sanitized ON\n * WRITE by the CMS's parser-based DOMPurify sanitizer\n * (apps/vulcantech-cms/src/lib/html/sanitizeHtml.ts), so the content this\n * package fetches is already clean. This boundary pass is a safety net for\n * legacy/unexpected data, not the primary guarantee.\n *\n * Strips dangerous tags and attributes and neutralizes dangerous URL schemes,\n * decoding HTML entities first so entity-encoded `javascript:` payloads can't\n * slip past the scheme check.\n */\n\nconst DANGEROUS_TAGS = [\n \"script\", \"object\", \"embed\", \"form\", \"input\", \"textarea\",\n \"button\", \"select\", \"option\", \"link\", \"meta\", \"base\", \"applet\",\n \"frame\", \"frameset\", \"layer\", \"style\", \"svg\", \"math\", \"xmp\",\n \"noscript\", \"template\",\n];\n\n/**\n * `iframe` is NOT in the blocklist above: blog HTML may carry a YouTube video\n * embed (BL-321). It is filtered by origin instead — an iframe pointing\n * anywhere but YouTube's embed path is deleted, element and content alike, by\n * {@link stripForeignIframes}. `<video>` needs no rule: it was never blocked\n * here, and its `src` still goes through the URL-scheme pass below.\n */\nconst YOUTUBE_EMBED_SRC =\n /^https:\\/\\/(?:www\\.)?(?:youtube-nocookie\\.com|youtube\\.com)\\/embed\\/[A-Za-z0-9_-]{6,20}(?:[?#].*)?$/;\n\nfunction safeCodePoint(n: number): string {\n if (!Number.isFinite(n) || n < 0 || n > 0x10ffff) return \"\";\n try {\n return String.fromCodePoint(n);\n } catch {\n return \"\";\n }\n}\n\n/** Decode numeric and a few named HTML entities used to obfuscate URL schemes. */\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&#x([0-9a-f]+);?/gi, (_, h) => safeCodePoint(parseInt(h, 16)))\n .replace(/&#(\\d+);?/g, (_, d) => safeCodePoint(parseInt(d, 10)))\n .replace(/:/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&/gi, \"&\");\n}\n\n/** Drop spaces and C0 control chars (code point <= 0x20) used to break up schemes. */\nfunction stripBlankAndControl(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch.codePointAt(0)! > 0x20) out += ch;\n }\n return out;\n}\n\n/**\n * Remove every `<iframe>` whose `src` is not a YouTube embed URL, taking any\n * content between the tags with it.\n */\nfunction stripForeignIframes(html: string): string {\n return html.replace(\n /<iframe\\b[^>]*>(?:[\\s\\S]*?<\\/iframe>)?/gi,\n (element) => {\n const match = /\\bsrc\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/i.exec(element);\n const raw = match ? (match[2] ?? match[3] ?? match[4] ?? \"\") : \"\";\n const src = stripBlankAndControl(decodeEntities(raw));\n return YOUTUBE_EMBED_SRC.test(src) ? element : \"\";\n },\n );\n}\n\n/**\n * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe\n * URL schemes. Returns the cleaned HTML string.\n *\n * The package's fetchers already run every post's `content` through this, so\n * call it only for CMS HTML obtained some other way (legacy exports, custom\n * endpoints).\n */\nexport function sanitizeHtml(html: string): string {\n if (!html) return \"\";\n\n let clean = html.replace(\n /<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/gi,\n \"\",\n );\n\n for (const tag of DANGEROUS_TAGS) {\n clean = clean.replace(\n new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"gi\"),\n \"\",\n );\n clean = clean.replace(new RegExp(`<${tag}\\\\b[^>]*\\\\/?>`, \"gi\"), \"\");\n }\n\n // Keep YouTube video embeds, drop every other iframe.\n clean = stripForeignIframes(clean);\n\n clean = clean.replace(\n /\\s+on\\w+\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\s+style\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\b(href|src)\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/gi,\n (match, attr, _raw, dq, sq, uq) => {\n const value = dq ?? sq ?? uq ?? \"\";\n const decoded = stripBlankAndControl(decodeEntities(value)).toLowerCase();\n if (/^(javascript|data|vbscript):/.test(decoded)) {\n return `${attr}=\"about:blank\"`;\n }\n return match;\n },\n );\n\n return clean;\n}\n","/**\n * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer\n * sites.\n *\n * Reads published blog posts from the CMS with Next.js ISR tags so the CMS\n * can purge a post (via /api/revalidate) the moment it changes, and supports\n * signed draft-preview tokens so an unpublished post can be rendered on the\n * real site for review.\n *\n * Config comes from the same env vars every consumer already sets — no\n * per-app wiring beyond importing this package:\n * VULCANTECH_CMS_URL (default https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID (required)\n * VULCANTECH_API_KEY (required)\n * VULCANTECH_BLOG_NO_CACHE (\"1\" | \"true\" → bypass ISR everywhere)\n *\n * SERVER-ONLY: relies on VULCANTECH_API_KEY (no NEXT_PUBLIC_ prefix), so it\n * must only be imported from server components / route handlers.\n *\n * Errors are graceful by design — a CMS hiccup returns [] / null and logs a\n * warning rather than throwing, so a marketing site never hard-crashes on a\n * transient CMS outage.\n *\n * Draft preview (Next.js Draft Mode):\n * - Re-export `GET` from app/api/preview/route.ts on each consumer.\n * - Call `resolvePreviewToken()` in the blog post page and pass the result\n * to fetchBlogPostBySlug as { previewToken }.\n * The public /blog/[slug] route stays static/ISR; only a request carrying\n * the Draft Mode cookie renders the unpublished draft.\n */\n\nimport { cookies, draftMode } from \"next/headers\";\nimport { NextResponse, type NextRequest } from \"next/server\";\nimport { sanitizeHtml } from \"./sanitize\";\n\nconst DEFAULT_REVALIDATE_SECONDS = 60;\n\nexport interface CMSBlogAuthor {\n uid?: string;\n name: string;\n avatar?: string;\n}\n\n/**\n * A supplementary video attached to a post, normalized by the CMS.\n *\n * Structural copy of the CMS's canonical `VideoDescriptor`\n * (`packages/blog-editor-shared/src/lib/video.ts`) — inlined rather than\n * imported so this package stays dependency-free for consumer sites. Keep the\n * shape in sync; the CMS validates every write against the original.\n *\n * `videoId` is safe to interpolate into a YouTube embed URL and `url` is always\n * on the CMS media host — the CMS pins both, so a consumer never has to\n * re-validate before rendering.\n */\nexport type CMSVideoDescriptor =\n | { provider: \"youtube\"; videoId: string }\n | { provider: \"youtube-short\"; videoId: string }\n | { provider: \"file\"; url: string; poster?: string };\n\nexport interface CMSBlogPost {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n /**\n * Sanitized HTML (TipTap editor output) — NOT markdown. Render with\n * `dangerouslySetInnerHTML`; do not run it through a markdown renderer.\n * Sanitized on write by the CMS and re-sanitized by this package's fetchers,\n * so it is safe to inject as-is.\n *\n * Markup contract (see the README's \"What's inside content\" for the full\n * story): headings start at h2 (h1 is yours, for the title); images are\n * plain `<img>` with no dimensions — `next/image` is not usable here, style\n * `img` with CSS; galleries are empty `div.cms-gallery[data-gallery]` nodes\n * that render as nothing unless hydrated; inline `style` never survives the\n * sanitizers, so bring your own typography (e.g. a `prose` wrapper).\n */\n content: string;\n /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */\n excerpt: string;\n /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */\n category?: string;\n /** URL route segment the post lives under, e.g. \"blog\" or \"documentation\". */\n routePrefix?: string;\n tags: string[];\n /**\n * Comma-separated SEO keywords the CMS derives from the post's dedicated\n * keyword fields (target keyword first). Feed straight into\n * `Metadata.keywords`; absent when the post has no keywords set.\n */\n keywords?: string;\n /** An object, not a string — display `author.name`. */\n author: CMSBlogAuthor;\n /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */\n featuredImage?: string;\n /**\n * Optional supplementary video for the post. Purely advisory — render it as a\n * hero player, a card thumbnail, or ignore it; nothing breaks when it's\n * absent, and it is absent on most posts. Videos placed *inside* the article\n * arrive as playable markup within `content` instead.\n */\n featuredVideo?: CMSVideoDescriptor;\n /** The public fetchers only ever return \"published\" posts (or a token-unlocked draft). */\n status: \"draft\" | \"in_review\" | \"published\" | \"archived\";\n /** ISO 8601 timestamp. Always present on published posts. */\n publishedAt?: string;\n /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */\n scheduledAt?: string;\n /** ISO 8601 timestamp. */\n createdAt: string;\n /** ISO 8601 timestamp. */\n updatedAt: string;\n /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */\n seoTitle?: string;\n /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */\n seoDescription?: string;\n /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */\n ogImage?: string;\n /** Defaults to \"article\" when absent (the field predates postType). */\n postType?: \"article\" | \"case-study\" | \"announcement\";\n /**\n * Spec-sheet pairs for case studies (e.g. `{ label: \"Make\", value: \"1969\n * Camaro\" }`) — the CMS only shows this editor when `postType` is\n * \"case-study\". Render as a spec table on case-study layouts; ignore\n * everywhere else.\n */\n metadata?: { label: string; value: string }[];\n}\n\nexport interface FetchOptions {\n /** Override the per-fetch revalidate window. Default: 60 seconds. */\n revalidate?: number;\n /** Extra ISR tags to attach to the fetch. */\n extraTags?: string[];\n /** Skip Next's ISR cache for this call. */\n noStore?: boolean;\n}\n\n/**\n * List filters, all applied server-side by the CMS — prefer these over\n * fetching everything and filtering client-side.\n */\nexport interface FetchPostsOptions extends FetchOptions {\n /** Exact-match on the post's `category`. */\n category?: string;\n /**\n * Only return posts under this route prefix (e.g. \"documentation\"). Don't\n * pass \"blog\" for the blog itself — legacy posts predate the field and have\n * no prefix, so they'd be excluded; filter the blog list client-side instead\n * (see the README's Scoped routes section).\n */\n routePrefix?: string;\n /** Posts whose `tags` include this tag. */\n tag?: string;\n /** Full-text search across title/content. */\n search?: string;\n /**\n * Page size; combine with `startAfter` to paginate. The response carries no\n * `hasMore`/`total` — fetch `limit + 1`, and if more than `limit` arrive\n * there is another page (drop the extra).\n */\n limit?: number;\n /** Pagination cursor: the `id` of the last post from the previous page. */\n startAfter?: string;\n}\n\nexport interface FetchPostOptions extends FetchOptions {\n /**\n * A signed preview token (from the CMS) that unlocks an unpublished post.\n * When set, the cache is bypassed automatically — preview content must\n * never be cached or served to the public.\n */\n previewToken?: string;\n}\n\nfunction cmsUrl(): string {\n return process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n}\n\nfunction bypassCache(): boolean {\n return (\n process.env.VULCANTECH_BLOG_NO_CACHE === \"1\" ||\n process.env.VULCANTECH_BLOG_NO_CACHE === \"true\"\n );\n}\n\nfunction assertConfig(): { projectId: string; apiKey: string } | null {\n const projectId = process.env.VULCANTECH_PROJECT_ID;\n const apiKey = process.env.VULCANTECH_API_KEY;\n if (!projectId || !apiKey) {\n console.warn(\n \"[cms/blog] CMS not configured — set VULCANTECH_PROJECT_ID and VULCANTECH_API_KEY\",\n );\n return null;\n }\n return { projectId, apiKey };\n}\n\nexport { sanitizeHtml };\n\n/** Sanitize a post's HTML body so every consumer render is safe by default. */\nfunction sanitizePost(post: CMSBlogPost): CMSBlogPost {\n if (post && typeof post.content === \"string\") {\n return { ...post, content: sanitizeHtml(post.content) };\n }\n return post;\n}\n\n/** ISR tag for a project's blog list. */\nexport function tagsForBlogList(projectId: string): string[] {\n return [`blog:${projectId}`];\n}\n\n/** ISR tags for a single post (post-specific + project-wide). */\nexport function tagsForBlogPost(projectId: string, slug: string): string[] {\n return [`blog:${projectId}:${slug}`, `blog:${projectId}`];\n}\n\nfunction buildInit(\n tags: string[],\n options: FetchOptions,\n): RequestInit & { next?: { revalidate?: number; tags?: string[] } } {\n const skipCache = options.noStore || bypassCache();\n if (skipCache) return { cache: \"no-store\" };\n return {\n next: {\n revalidate: options.revalidate ?? DEFAULT_REVALIDATE_SECONDS,\n tags: [...tags, ...(options.extraTags ?? [])],\n },\n };\n}\n\n/**\n * Fetch published posts for the configured project, newest-first by\n * `publishedAt` (the CMS orders them — no client-side sort needed). Optional\n * filters (category/routePrefix/tag/search/limit/startAfter) are forwarded to\n * the CMS.\n *\n * Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it\n * logs a warning and returns `[]` — render an empty state instead of wrapping\n * in try/catch.\n */\nexport async function fetchBlogPosts(\n options: FetchPostsOptions = {},\n): Promise<CMSBlogPost[]> {\n const config = assertConfig();\n if (!config) return [];\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey, status: \"published\" });\n if (options.category) params.set(\"category\", options.category);\n if (options.routePrefix) params.set(\"routePrefix\", options.routePrefix);\n if (options.tag) params.set(\"tag\", options.tag);\n if (options.search) params.set(\"search\", options.search);\n if (options.limit) params.set(\"limit\", String(options.limit));\n if (options.startAfter) params.set(\"startAfter\", options.startAfter);\n\n const url = `${cmsUrl()}/api/blog?${params.toString()}`;\n const init = buildInit(tagsForBlogList(projectId), options);\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\"[cms/blog] CMS unreachable:\", (err as Error).message);\n return [];\n }\n if (res.status === 404) {\n console.warn(\"[cms/blog] /api/blog returned 404 — CMS may need redeployment\");\n return [];\n }\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog returned ${res.status}`);\n return [];\n }\n\n let json: { posts: CMSBlogPost[] };\n try {\n json = (await res.json()) as { posts: CMSBlogPost[] };\n } catch (err) {\n console.warn(\"[cms/blog] /api/blog returned non-JSON:\", (err as Error).message);\n return [];\n }\n return (json.posts ?? []).map(sanitizePost);\n}\n\n/**\n * Fetch a single post by slug. Returns null when not found.\n *\n * Never throws: CMS errors also return `null` (with a logged warning), so\n * treat `null` as \"show notFound()\" rather than catching exceptions.\n *\n * Pass `previewToken` (minted by the CMS) to render an unpublished draft for\n * review — that automatically bypasses the cache.\n */\nexport async function fetchBlogPostBySlug(\n slug: string,\n options: FetchPostOptions = {},\n): Promise<CMSBlogPost | null> {\n const config = assertConfig();\n if (!config) return null;\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey });\n if (options.previewToken) params.set(\"preview\", options.previewToken);\n\n const url = `${cmsUrl()}/api/blog/${encodeURIComponent(slug)}?${params.toString()}`;\n // Preview responses must never be cached.\n const init = buildInit(tagsForBlogPost(projectId, slug), {\n ...options,\n noStore: options.noStore || !!options.previewToken,\n });\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\n `[cms/blog] CMS unreachable for \"${slug}\":`,\n (err as Error).message,\n );\n return null;\n }\n if (res.status === 404) return null;\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);\n return null;\n }\n\n let json: { post: CMSBlogPost };\n try {\n json = (await res.json()) as { post: CMSBlogPost };\n } catch (err) {\n console.warn(`[cms/blog] /api/blog/${slug} returned non-JSON:`, (err as Error).message);\n return null;\n }\n return json.post ? sanitizePost(json.post) : null;\n}\n\n/* ─── Draft preview (Next.js Draft Mode) ─── */\n\nconst PREVIEW_COOKIE = \"vt_preview_token\";\nconst PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60; // 2 hours\n\n/**\n * Route handler for `/api/preview?token=…&slug=…`.\n *\n * Validates the token against the CMS, enables Next Draft Mode, stores the\n * token in an httpOnly cookie, and redirects to the post — which then renders\n * the draft (see resolvePreviewToken). On an invalid/expired token it just\n * redirects to the public page (which 404s if the post isn't published).\n *\n * Each consumer wires it up with one line:\n * // app/api/preview/route.ts\n * export { GET } from \"@vulcantech/blog\";\n */\nexport async function GET(request: NextRequest): Promise<Response> {\n const { searchParams } = new URL(request.url);\n const token = searchParams.get(\"token\");\n const slug = searchParams.get(\"slug\");\n\n if (!token || !slug) {\n return NextResponse.json(\n { error: \"token and slug are required\" },\n { status: 400 },\n );\n }\n\n const target = new URL(`/blog/${encodeURIComponent(slug)}`, request.url);\n\n // Validate by asking the CMS to resolve the draft with this token.\n const post = await fetchBlogPostBySlug(slug, { previewToken: token });\n if (!post) {\n return NextResponse.redirect(target);\n }\n\n (await draftMode()).enable();\n (await cookies()).set(PREVIEW_COOKIE, token, {\n httpOnly: true,\n sameSite: \"lax\",\n secure: process.env.NODE_ENV === \"production\",\n path: \"/\",\n maxAge: PREVIEW_MAX_AGE_SECONDS,\n });\n\n return NextResponse.redirect(target);\n}\n\n/**\n * Page helper: returns the active preview token when Draft Mode is on, else\n * undefined. Call it in the blog post server component and spread the result\n * into the fetch:\n *\n * const previewToken = await resolvePreviewToken();\n * const post = await fetchBlogPostBySlug(slug, { previewToken });\n *\n * Reading the cookie only happens when Draft Mode is enabled, so the public\n * route stays statically rendered for normal visitors.\n */\nexport async function resolvePreviewToken(): Promise<string | undefined> {\n const { isEnabled } = await draftMode();\n if (!isEnabled) return undefined;\n const store = await cookies();\n return store.get(PREVIEW_COOKIE)?.value;\n}\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -163,7 +163,13 @@ async function fetchBlogPosts(options = {}) {
|
|
|
163
163
|
console.warn(`[cms/blog] /api/blog returned ${res.status}`);
|
|
164
164
|
return [];
|
|
165
165
|
}
|
|
166
|
-
|
|
166
|
+
let json;
|
|
167
|
+
try {
|
|
168
|
+
json = await res.json();
|
|
169
|
+
} catch (err) {
|
|
170
|
+
console.warn("[cms/blog] /api/blog returned non-JSON:", err.message);
|
|
171
|
+
return [];
|
|
172
|
+
}
|
|
167
173
|
return (json.posts ?? []).map(sanitizePost);
|
|
168
174
|
}
|
|
169
175
|
async function fetchBlogPostBySlug(slug, options = {}) {
|
|
@@ -192,7 +198,13 @@ async function fetchBlogPostBySlug(slug, options = {}) {
|
|
|
192
198
|
console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);
|
|
193
199
|
return null;
|
|
194
200
|
}
|
|
195
|
-
|
|
201
|
+
let json;
|
|
202
|
+
try {
|
|
203
|
+
json = await res.json();
|
|
204
|
+
} catch (err) {
|
|
205
|
+
console.warn(`[cms/blog] /api/blog/${slug} returned non-JSON:`, err.message);
|
|
206
|
+
return null;
|
|
207
|
+
}
|
|
196
208
|
return json.post ? sanitizePost(json.post) : null;
|
|
197
209
|
}
|
|
198
210
|
var PREVIEW_COOKIE = "vt_preview_token";
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sanitize.ts","../src/index.ts"],"names":[],"mappings":";;;;;;AAiBA,IAAM,cAAA,GAAiB;AAAA,EACrB,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,OAAA;AAAA,EAAS,MAAA;AAAA,EAA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OAAA,EAAQ,EAAG,GAAA,CAAI,gBAAgB,KAAA,EAAO;AAAA,IAC3C,QAAA,EAAU,IAAA;AAAA,IACV,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,OAAA,CAAQ,GAAA,CAAI,QAAA,KAAa,YAAA;AAAA,IACjC,IAAA,EAAM,GAAA;AAAA,IACN,MAAA,EAAQ;AAAA,GACT,CAAA;AAED,EAAA,OAAO,YAAA,CAAa,SAAS,MAAM,CAAA;AACrC;AAaA,eAAsB,mBAAA,GAAmD;AACvE,EAAA,MAAM,EAAE,SAAA,EAAU,GAAI,MAAM,SAAA,EAAU;AACtC,EAAA,IAAI,CAAC,WAAW,OAAO,MAAA;AACvB,EAAA,MAAM,KAAA,GAAQ,MAAM,OAAA,EAAQ;AAC5B,EAAA,OAAO,KAAA,CAAM,GAAA,CAAI,cAAc,CAAA,EAAG,KAAA;AACpC","file":"index.mjs","sourcesContent":["/**\n * HTML sanitizer for user-generated (TipTap) content.\n *\n * MIRROR of packages/ui/sanitize.ts — keep in sync. Duplicated rather than\n * imported so this package stays dependency-free (no `ui` workspace coupling).\n *\n * Defense-in-depth only. As of audit L4 / BL-023, blog HTML is sanitized ON\n * WRITE by the CMS's parser-based DOMPurify sanitizer\n * (apps/vulcantech-cms/src/lib/html/sanitizeHtml.ts), so the content this\n * package fetches is already clean. This boundary pass is a safety net for\n * legacy/unexpected data, not the primary guarantee.\n *\n * Strips dangerous tags and attributes and neutralizes dangerous URL schemes,\n * decoding HTML entities first so entity-encoded `javascript:` payloads can't\n * slip past the scheme check.\n */\n\nconst DANGEROUS_TAGS = [\n \"script\", \"object\", \"embed\", \"form\", \"input\", \"textarea\",\n \"button\", \"select\", \"option\", \"link\", \"meta\", \"base\", \"applet\",\n \"frame\", \"frameset\", \"layer\", \"style\", \"svg\", \"math\", \"xmp\",\n \"noscript\", \"template\",\n];\n\n/**\n * `iframe` is NOT in the blocklist above: blog HTML may carry a YouTube video\n * embed (BL-321). It is filtered by origin instead — an iframe pointing\n * anywhere but YouTube's embed path is deleted, element and content alike, by\n * {@link stripForeignIframes}. `<video>` needs no rule: it was never blocked\n * here, and its `src` still goes through the URL-scheme pass below.\n */\nconst YOUTUBE_EMBED_SRC =\n /^https:\\/\\/(?:www\\.)?(?:youtube-nocookie\\.com|youtube\\.com)\\/embed\\/[A-Za-z0-9_-]{6,20}(?:[?#].*)?$/;\n\nfunction safeCodePoint(n: number): string {\n if (!Number.isFinite(n) || n < 0 || n > 0x10ffff) return \"\";\n try {\n return String.fromCodePoint(n);\n } catch {\n return \"\";\n }\n}\n\n/** Decode numeric and a few named HTML entities used to obfuscate URL schemes. */\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&#x([0-9a-f]+);?/gi, (_, h) => safeCodePoint(parseInt(h, 16)))\n .replace(/&#(\\d+);?/g, (_, d) => safeCodePoint(parseInt(d, 10)))\n .replace(/:/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&/gi, \"&\");\n}\n\n/** Drop spaces and C0 control chars (code point <= 0x20) used to break up schemes. */\nfunction stripBlankAndControl(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch.codePointAt(0)! > 0x20) out += ch;\n }\n return out;\n}\n\n/**\n * Remove every `<iframe>` whose `src` is not a YouTube embed URL, taking any\n * content between the tags with it.\n */\nfunction stripForeignIframes(html: string): string {\n return html.replace(\n /<iframe\\b[^>]*>(?:[\\s\\S]*?<\\/iframe>)?/gi,\n (element) => {\n const match = /\\bsrc\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/i.exec(element);\n const raw = match ? (match[2] ?? match[3] ?? match[4] ?? \"\") : \"\";\n const src = stripBlankAndControl(decodeEntities(raw));\n return YOUTUBE_EMBED_SRC.test(src) ? element : \"\";\n },\n );\n}\n\n/**\n * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe\n * URL schemes. Returns the cleaned HTML string.\n *\n * The package's fetchers already run every post's `content` through this, so\n * call it only for CMS HTML obtained some other way (legacy exports, custom\n * endpoints).\n */\nexport function sanitizeHtml(html: string): string {\n if (!html) return \"\";\n\n let clean = html.replace(\n /<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/gi,\n \"\",\n );\n\n for (const tag of DANGEROUS_TAGS) {\n clean = clean.replace(\n new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"gi\"),\n \"\",\n );\n clean = clean.replace(new RegExp(`<${tag}\\\\b[^>]*\\\\/?>`, \"gi\"), \"\");\n }\n\n // Keep YouTube video embeds, drop every other iframe.\n clean = stripForeignIframes(clean);\n\n clean = clean.replace(\n /\\s+on\\w+\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\s+style\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\b(href|src)\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/gi,\n (match, attr, _raw, dq, sq, uq) => {\n const value = dq ?? sq ?? uq ?? \"\";\n const decoded = stripBlankAndControl(decodeEntities(value)).toLowerCase();\n if (/^(javascript|data|vbscript):/.test(decoded)) {\n return `${attr}=\"about:blank\"`;\n }\n return match;\n },\n );\n\n return clean;\n}\n","/**\n * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer\n * sites.\n *\n * Reads published blog posts from the CMS with Next.js ISR tags so the CMS\n * can purge a post (via /api/revalidate) the moment it changes, and supports\n * signed draft-preview tokens so an unpublished post can be rendered on the\n * real site for review.\n *\n * Config comes from the same env vars every consumer already sets — no\n * per-app wiring beyond importing this package:\n * VULCANTECH_CMS_URL (default https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID (required)\n * VULCANTECH_API_KEY (required)\n * VULCANTECH_BLOG_NO_CACHE (\"1\" | \"true\" → bypass ISR everywhere)\n *\n * SERVER-ONLY: relies on VULCANTECH_API_KEY (no NEXT_PUBLIC_ prefix), so it\n * must only be imported from server components / route handlers.\n *\n * Errors are graceful by design — a CMS hiccup returns [] / null and logs a\n * warning rather than throwing, so a marketing site never hard-crashes on a\n * transient CMS outage.\n *\n * Draft preview (Next.js Draft Mode):\n * - Re-export `GET` from app/api/preview/route.ts on each consumer.\n * - Call `resolvePreviewToken()` in the blog post page and pass the result\n * to fetchBlogPostBySlug as { previewToken }.\n * The public /blog/[slug] route stays static/ISR; only a request carrying\n * the Draft Mode cookie renders the unpublished draft.\n */\n\nimport { cookies, draftMode } from \"next/headers\";\nimport { NextResponse, type NextRequest } from \"next/server\";\nimport { sanitizeHtml } from \"./sanitize\";\n\nconst DEFAULT_REVALIDATE_SECONDS = 60;\n\nexport interface CMSBlogAuthor {\n uid?: string;\n name: string;\n avatar?: string;\n}\n\n/**\n * A supplementary video attached to a post, normalized by the CMS.\n *\n * Structural copy of the CMS's canonical `VideoDescriptor`\n * (`packages/blog-editor-shared/src/lib/video.ts`) — inlined rather than\n * imported so this package stays dependency-free for consumer sites. Keep the\n * shape in sync; the CMS validates every write against the original.\n *\n * `videoId` is safe to interpolate into a YouTube embed URL and `url` is always\n * on the CMS media host — the CMS pins both, so a consumer never has to\n * re-validate before rendering.\n */\nexport type CMSVideoDescriptor =\n | { provider: \"youtube\"; videoId: string }\n | { provider: \"youtube-short\"; videoId: string }\n | { provider: \"file\"; url: string; poster?: string };\n\nexport interface CMSBlogPost {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n /**\n * Sanitized HTML (TipTap editor output) — NOT markdown. Render with\n * `dangerouslySetInnerHTML`; do not run it through a markdown renderer.\n * Sanitized on write by the CMS and re-sanitized by this package's fetchers,\n * so it is safe to inject as-is.\n */\n content: string;\n /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */\n excerpt: string;\n /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */\n category?: string;\n /** URL route segment the post lives under, e.g. \"blog\" or \"documentation\". */\n routePrefix?: string;\n tags: string[];\n /**\n * Comma-separated SEO keywords the CMS derives from the post's dedicated\n * keyword fields (target keyword first). Feed straight into\n * `Metadata.keywords`; absent when the post has no keywords set.\n */\n keywords?: string;\n /** An object, not a string — display `author.name`. */\n author: CMSBlogAuthor;\n /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */\n featuredImage?: string;\n /**\n * Optional supplementary video for the post. Purely advisory — render it as a\n * hero player, a card thumbnail, or ignore it; nothing breaks when it's\n * absent, and it is absent on most posts. Videos placed *inside* the article\n * arrive as playable markup within `content` instead.\n */\n featuredVideo?: CMSVideoDescriptor;\n /** The public fetchers only ever return \"published\" posts (or a token-unlocked draft). */\n status: \"draft\" | \"in_review\" | \"published\" | \"archived\";\n /** ISO 8601 timestamp. Always present on published posts. */\n publishedAt?: string;\n /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */\n scheduledAt?: string;\n /** ISO 8601 timestamp. */\n createdAt: string;\n /** ISO 8601 timestamp. */\n updatedAt: string;\n /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */\n seoTitle?: string;\n /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */\n seoDescription?: string;\n /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */\n ogImage?: string;\n /** Defaults to \"article\" when absent (the field predates postType). */\n postType?: \"article\" | \"case-study\" | \"announcement\";\n /**\n * Spec-sheet pairs for case studies (e.g. `{ label: \"Make\", value: \"1969\n * Camaro\" }`) — the CMS only shows this editor when `postType` is\n * \"case-study\". Render as a spec table on case-study layouts; ignore\n * everywhere else.\n */\n metadata?: { label: string; value: string }[];\n}\n\nexport interface FetchOptions {\n /** Override the per-fetch revalidate window. Default: 60 seconds. */\n revalidate?: number;\n /** Extra ISR tags to attach to the fetch. */\n extraTags?: string[];\n /** Skip Next's ISR cache for this call. */\n noStore?: boolean;\n}\n\n/**\n * List filters, all applied server-side by the CMS — prefer these over\n * fetching everything and filtering client-side.\n */\nexport interface FetchPostsOptions extends FetchOptions {\n /** Exact-match on the post's `category`. */\n category?: string;\n /** Only return posts under this route prefix (e.g. \"documentation\"). */\n routePrefix?: string;\n /** Posts whose `tags` include this tag. */\n tag?: string;\n /** Full-text search across title/content. */\n search?: string;\n /** Page size; combine with `startAfter` to paginate. */\n limit?: number;\n /** Pagination cursor: the `id` of the last post from the previous page. */\n startAfter?: string;\n}\n\nexport interface FetchPostOptions extends FetchOptions {\n /**\n * A signed preview token (from the CMS) that unlocks an unpublished post.\n * When set, the cache is bypassed automatically — preview content must\n * never be cached or served to the public.\n */\n previewToken?: string;\n}\n\nfunction cmsUrl(): string {\n return process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n}\n\nfunction bypassCache(): boolean {\n return (\n process.env.VULCANTECH_BLOG_NO_CACHE === \"1\" ||\n process.env.VULCANTECH_BLOG_NO_CACHE === \"true\"\n );\n}\n\nfunction assertConfig(): { projectId: string; apiKey: string } | null {\n const projectId = process.env.VULCANTECH_PROJECT_ID;\n const apiKey = process.env.VULCANTECH_API_KEY;\n if (!projectId || !apiKey) {\n console.warn(\n \"[cms/blog] CMS not configured — set VULCANTECH_PROJECT_ID and VULCANTECH_API_KEY\",\n );\n return null;\n }\n return { projectId, apiKey };\n}\n\nexport { sanitizeHtml };\n\n/** Sanitize a post's HTML body so every consumer render is safe by default. */\nfunction sanitizePost(post: CMSBlogPost): CMSBlogPost {\n if (post && typeof post.content === \"string\") {\n return { ...post, content: sanitizeHtml(post.content) };\n }\n return post;\n}\n\n/** ISR tag for a project's blog list. */\nexport function tagsForBlogList(projectId: string): string[] {\n return [`blog:${projectId}`];\n}\n\n/** ISR tags for a single post (post-specific + project-wide). */\nexport function tagsForBlogPost(projectId: string, slug: string): string[] {\n return [`blog:${projectId}:${slug}`, `blog:${projectId}`];\n}\n\nfunction buildInit(\n tags: string[],\n options: FetchOptions,\n): RequestInit & { next?: { revalidate?: number; tags?: string[] } } {\n const skipCache = options.noStore || bypassCache();\n if (skipCache) return { cache: \"no-store\" };\n return {\n next: {\n revalidate: options.revalidate ?? DEFAULT_REVALIDATE_SECONDS,\n tags: [...tags, ...(options.extraTags ?? [])],\n },\n };\n}\n\n/**\n * Fetch published posts for the configured project. Optional filters\n * (category/routePrefix/tag/search/limit/startAfter) are forwarded to the CMS.\n *\n * Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it\n * logs a warning and returns `[]` — render an empty state instead of wrapping\n * in try/catch.\n */\nexport async function fetchBlogPosts(\n options: FetchPostsOptions = {},\n): Promise<CMSBlogPost[]> {\n const config = assertConfig();\n if (!config) return [];\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey, status: \"published\" });\n if (options.category) params.set(\"category\", options.category);\n if (options.routePrefix) params.set(\"routePrefix\", options.routePrefix);\n if (options.tag) params.set(\"tag\", options.tag);\n if (options.search) params.set(\"search\", options.search);\n if (options.limit) params.set(\"limit\", String(options.limit));\n if (options.startAfter) params.set(\"startAfter\", options.startAfter);\n\n const url = `${cmsUrl()}/api/blog?${params.toString()}`;\n const init = buildInit(tagsForBlogList(projectId), options);\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\"[cms/blog] CMS unreachable:\", (err as Error).message);\n return [];\n }\n if (res.status === 404) {\n console.warn(\"[cms/blog] /api/blog returned 404 — CMS may need redeployment\");\n return [];\n }\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog returned ${res.status}`);\n return [];\n }\n\n const json = (await res.json()) as { posts: CMSBlogPost[] };\n return (json.posts ?? []).map(sanitizePost);\n}\n\n/**\n * Fetch a single post by slug. Returns null when not found.\n *\n * Never throws: CMS errors also return `null` (with a logged warning), so\n * treat `null` as \"show notFound()\" rather than catching exceptions.\n *\n * Pass `previewToken` (minted by the CMS) to render an unpublished draft for\n * review — that automatically bypasses the cache.\n */\nexport async function fetchBlogPostBySlug(\n slug: string,\n options: FetchPostOptions = {},\n): Promise<CMSBlogPost | null> {\n const config = assertConfig();\n if (!config) return null;\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey });\n if (options.previewToken) params.set(\"preview\", options.previewToken);\n\n const url = `${cmsUrl()}/api/blog/${encodeURIComponent(slug)}?${params.toString()}`;\n // Preview responses must never be cached.\n const init = buildInit(tagsForBlogPost(projectId, slug), {\n ...options,\n noStore: options.noStore || !!options.previewToken,\n });\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\n `[cms/blog] CMS unreachable for \"${slug}\":`,\n (err as Error).message,\n );\n return null;\n }\n if (res.status === 404) return null;\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);\n return null;\n }\n\n const json = (await res.json()) as { post: CMSBlogPost };\n return json.post ? sanitizePost(json.post) : null;\n}\n\n/* ─── Draft preview (Next.js Draft Mode) ─── */\n\nconst PREVIEW_COOKIE = \"vt_preview_token\";\nconst PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60; // 2 hours\n\n/**\n * Route handler for `/api/preview?token=…&slug=…`.\n *\n * Validates the token against the CMS, enables Next Draft Mode, stores the\n * token in an httpOnly cookie, and redirects to the post — which then renders\n * the draft (see resolvePreviewToken). On an invalid/expired token it just\n * redirects to the public page (which 404s if the post isn't published).\n *\n * Each consumer wires it up with one line:\n * // app/api/preview/route.ts\n * export { GET } from \"@vulcantech/blog\";\n */\nexport async function GET(request: NextRequest): Promise<Response> {\n const { searchParams } = new URL(request.url);\n const token = searchParams.get(\"token\");\n const slug = searchParams.get(\"slug\");\n\n if (!token || !slug) {\n return NextResponse.json(\n { error: \"token and slug are required\" },\n { status: 400 },\n );\n }\n\n const target = new URL(`/blog/${encodeURIComponent(slug)}`, request.url);\n\n // Validate by asking the CMS to resolve the draft with this token.\n const post = await fetchBlogPostBySlug(slug, { previewToken: token });\n if (!post) {\n return NextResponse.redirect(target);\n }\n\n (await draftMode()).enable();\n (await cookies()).set(PREVIEW_COOKIE, token, {\n httpOnly: true,\n sameSite: \"lax\",\n secure: process.env.NODE_ENV === \"production\",\n path: \"/\",\n maxAge: PREVIEW_MAX_AGE_SECONDS,\n });\n\n return NextResponse.redirect(target);\n}\n\n/**\n * Page helper: returns the active preview token when Draft Mode is on, else\n * undefined. Call it in the blog post server component and spread the result\n * into the fetch:\n *\n * const previewToken = await resolvePreviewToken();\n * const post = await fetchBlogPostBySlug(slug, { previewToken });\n *\n * Reading the cookie only happens when Draft Mode is enabled, so the public\n * route stays statically rendered for normal visitors.\n */\nexport async function resolvePreviewToken(): Promise<string | undefined> {\n const { isEnabled } = await draftMode();\n if (!isEnabled) return undefined;\n const store = await cookies();\n return store.get(PREVIEW_COOKIE)?.value;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/sanitize.ts","../src/index.ts"],"names":[],"mappings":";;;;;;AAiBA,IAAM,cAAA,GAAiB;AAAA,EACrB,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,OAAA;AAAA,EAAS,MAAA;AAAA,EAAQ,OAAA;AAAA,EAAS,UAAA;AAAA,EAC9C,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,QAAA;AAAA,EACtD,OAAA;AAAA,EAAS,UAAA;AAAA,EAAY,OAAA;AAAA,EAAS,OAAA;AAAA,EAAS,KAAA;AAAA,EAAO,MAAA;AAAA,EAAQ,KAAA;AAAA,EACtD,UAAA;AAAA,EAAY;AACd,CAAA;AASA,IAAM,iBAAA,GACJ,qGAAA;AAEF,SAAS,cAAc,CAAA,EAAmB;AACxC,EAAA,IAAI,CAAC,OAAO,QAAA,CAAS,CAAC,KAAK,CAAA,GAAI,CAAA,IAAK,CAAA,GAAI,OAAA,EAAU,OAAO,EAAA;AACzD,EAAA,IAAI;AACF,IAAA,OAAO,MAAA,CAAO,cAAc,CAAC,CAAA;AAAA,EAC/B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,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AED,EAAA,OAAO,YAAA,CAAa,SAAS,MAAM,CAAA;AACrC;AAaA,eAAsB,mBAAA,GAAmD;AACvE,EAAA,MAAM,EAAE,SAAA,EAAU,GAAI,MAAM,SAAA,EAAU;AACtC,EAAA,IAAI,CAAC,WAAW,OAAO,MAAA;AACvB,EAAA,MAAM,KAAA,GAAQ,MAAM,OAAA,EAAQ;AAC5B,EAAA,OAAO,KAAA,CAAM,GAAA,CAAI,cAAc,CAAA,EAAG,KAAA;AACpC","file":"index.mjs","sourcesContent":["/**\n * HTML sanitizer for user-generated (TipTap) content.\n *\n * MIRROR of packages/ui/sanitize.ts — keep in sync. Duplicated rather than\n * imported so this package stays dependency-free (no `ui` workspace coupling).\n *\n * Defense-in-depth only. As of audit L4 / BL-023, blog HTML is sanitized ON\n * WRITE by the CMS's parser-based DOMPurify sanitizer\n * (apps/vulcantech-cms/src/lib/html/sanitizeHtml.ts), so the content this\n * package fetches is already clean. This boundary pass is a safety net for\n * legacy/unexpected data, not the primary guarantee.\n *\n * Strips dangerous tags and attributes and neutralizes dangerous URL schemes,\n * decoding HTML entities first so entity-encoded `javascript:` payloads can't\n * slip past the scheme check.\n */\n\nconst DANGEROUS_TAGS = [\n \"script\", \"object\", \"embed\", \"form\", \"input\", \"textarea\",\n \"button\", \"select\", \"option\", \"link\", \"meta\", \"base\", \"applet\",\n \"frame\", \"frameset\", \"layer\", \"style\", \"svg\", \"math\", \"xmp\",\n \"noscript\", \"template\",\n];\n\n/**\n * `iframe` is NOT in the blocklist above: blog HTML may carry a YouTube video\n * embed (BL-321). It is filtered by origin instead — an iframe pointing\n * anywhere but YouTube's embed path is deleted, element and content alike, by\n * {@link stripForeignIframes}. `<video>` needs no rule: it was never blocked\n * here, and its `src` still goes through the URL-scheme pass below.\n */\nconst YOUTUBE_EMBED_SRC =\n /^https:\\/\\/(?:www\\.)?(?:youtube-nocookie\\.com|youtube\\.com)\\/embed\\/[A-Za-z0-9_-]{6,20}(?:[?#].*)?$/;\n\nfunction safeCodePoint(n: number): string {\n if (!Number.isFinite(n) || n < 0 || n > 0x10ffff) return \"\";\n try {\n return String.fromCodePoint(n);\n } catch {\n return \"\";\n }\n}\n\n/** Decode numeric and a few named HTML entities used to obfuscate URL schemes. */\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&#x([0-9a-f]+);?/gi, (_, h) => safeCodePoint(parseInt(h, 16)))\n .replace(/&#(\\d+);?/g, (_, d) => safeCodePoint(parseInt(d, 10)))\n .replace(/:/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&/gi, \"&\");\n}\n\n/** Drop spaces and C0 control chars (code point <= 0x20) used to break up schemes. */\nfunction stripBlankAndControl(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch.codePointAt(0)! > 0x20) out += ch;\n }\n return out;\n}\n\n/**\n * Remove every `<iframe>` whose `src` is not a YouTube embed URL, taking any\n * content between the tags with it.\n */\nfunction stripForeignIframes(html: string): string {\n return html.replace(\n /<iframe\\b[^>]*>(?:[\\s\\S]*?<\\/iframe>)?/gi,\n (element) => {\n const match = /\\bsrc\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/i.exec(element);\n const raw = match ? (match[2] ?? match[3] ?? match[4] ?? \"\") : \"\";\n const src = stripBlankAndControl(decodeEntities(raw));\n return YOUTUBE_EMBED_SRC.test(src) ? element : \"\";\n },\n );\n}\n\n/**\n * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe\n * URL schemes. Returns the cleaned HTML string.\n *\n * The package's fetchers already run every post's `content` through this, so\n * call it only for CMS HTML obtained some other way (legacy exports, custom\n * endpoints).\n */\nexport function sanitizeHtml(html: string): string {\n if (!html) return \"\";\n\n let clean = html.replace(\n /<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/gi,\n \"\",\n );\n\n for (const tag of DANGEROUS_TAGS) {\n clean = clean.replace(\n new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"gi\"),\n \"\",\n );\n clean = clean.replace(new RegExp(`<${tag}\\\\b[^>]*\\\\/?>`, \"gi\"), \"\");\n }\n\n // Keep YouTube video embeds, drop every other iframe.\n clean = stripForeignIframes(clean);\n\n clean = clean.replace(\n /\\s+on\\w+\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\s+style\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\b(href|src)\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/gi,\n (match, attr, _raw, dq, sq, uq) => {\n const value = dq ?? sq ?? uq ?? \"\";\n const decoded = stripBlankAndControl(decodeEntities(value)).toLowerCase();\n if (/^(javascript|data|vbscript):/.test(decoded)) {\n return `${attr}=\"about:blank\"`;\n }\n return match;\n },\n );\n\n return clean;\n}\n","/**\n * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer\n * sites.\n *\n * Reads published blog posts from the CMS with Next.js ISR tags so the CMS\n * can purge a post (via /api/revalidate) the moment it changes, and supports\n * signed draft-preview tokens so an unpublished post can be rendered on the\n * real site for review.\n *\n * Config comes from the same env vars every consumer already sets — no\n * per-app wiring beyond importing this package:\n * VULCANTECH_CMS_URL (default https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID (required)\n * VULCANTECH_API_KEY (required)\n * VULCANTECH_BLOG_NO_CACHE (\"1\" | \"true\" → bypass ISR everywhere)\n *\n * SERVER-ONLY: relies on VULCANTECH_API_KEY (no NEXT_PUBLIC_ prefix), so it\n * must only be imported from server components / route handlers.\n *\n * Errors are graceful by design — a CMS hiccup returns [] / null and logs a\n * warning rather than throwing, so a marketing site never hard-crashes on a\n * transient CMS outage.\n *\n * Draft preview (Next.js Draft Mode):\n * - Re-export `GET` from app/api/preview/route.ts on each consumer.\n * - Call `resolvePreviewToken()` in the blog post page and pass the result\n * to fetchBlogPostBySlug as { previewToken }.\n * The public /blog/[slug] route stays static/ISR; only a request carrying\n * the Draft Mode cookie renders the unpublished draft.\n */\n\nimport { cookies, draftMode } from \"next/headers\";\nimport { NextResponse, type NextRequest } from \"next/server\";\nimport { sanitizeHtml } from \"./sanitize\";\n\nconst DEFAULT_REVALIDATE_SECONDS = 60;\n\nexport interface CMSBlogAuthor {\n uid?: string;\n name: string;\n avatar?: string;\n}\n\n/**\n * A supplementary video attached to a post, normalized by the CMS.\n *\n * Structural copy of the CMS's canonical `VideoDescriptor`\n * (`packages/blog-editor-shared/src/lib/video.ts`) — inlined rather than\n * imported so this package stays dependency-free for consumer sites. Keep the\n * shape in sync; the CMS validates every write against the original.\n *\n * `videoId` is safe to interpolate into a YouTube embed URL and `url` is always\n * on the CMS media host — the CMS pins both, so a consumer never has to\n * re-validate before rendering.\n */\nexport type CMSVideoDescriptor =\n | { provider: \"youtube\"; videoId: string }\n | { provider: \"youtube-short\"; videoId: string }\n | { provider: \"file\"; url: string; poster?: string };\n\nexport interface CMSBlogPost {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n /**\n * Sanitized HTML (TipTap editor output) — NOT markdown. Render with\n * `dangerouslySetInnerHTML`; do not run it through a markdown renderer.\n * Sanitized on write by the CMS and re-sanitized by this package's fetchers,\n * so it is safe to inject as-is.\n *\n * Markup contract (see the README's \"What's inside content\" for the full\n * story): headings start at h2 (h1 is yours, for the title); images are\n * plain `<img>` with no dimensions — `next/image` is not usable here, style\n * `img` with CSS; galleries are empty `div.cms-gallery[data-gallery]` nodes\n * that render as nothing unless hydrated; inline `style` never survives the\n * sanitizers, so bring your own typography (e.g. a `prose` wrapper).\n */\n content: string;\n /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */\n excerpt: string;\n /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */\n category?: string;\n /** URL route segment the post lives under, e.g. \"blog\" or \"documentation\". */\n routePrefix?: string;\n tags: string[];\n /**\n * Comma-separated SEO keywords the CMS derives from the post's dedicated\n * keyword fields (target keyword first). Feed straight into\n * `Metadata.keywords`; absent when the post has no keywords set.\n */\n keywords?: string;\n /** An object, not a string — display `author.name`. */\n author: CMSBlogAuthor;\n /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */\n featuredImage?: string;\n /**\n * Optional supplementary video for the post. Purely advisory — render it as a\n * hero player, a card thumbnail, or ignore it; nothing breaks when it's\n * absent, and it is absent on most posts. Videos placed *inside* the article\n * arrive as playable markup within `content` instead.\n */\n featuredVideo?: CMSVideoDescriptor;\n /** The public fetchers only ever return \"published\" posts (or a token-unlocked draft). */\n status: \"draft\" | \"in_review\" | \"published\" | \"archived\";\n /** ISO 8601 timestamp. Always present on published posts. */\n publishedAt?: string;\n /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */\n scheduledAt?: string;\n /** ISO 8601 timestamp. */\n createdAt: string;\n /** ISO 8601 timestamp. */\n updatedAt: string;\n /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */\n seoTitle?: string;\n /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */\n seoDescription?: string;\n /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */\n ogImage?: string;\n /** Defaults to \"article\" when absent (the field predates postType). */\n postType?: \"article\" | \"case-study\" | \"announcement\";\n /**\n * Spec-sheet pairs for case studies (e.g. `{ label: \"Make\", value: \"1969\n * Camaro\" }`) — the CMS only shows this editor when `postType` is\n * \"case-study\". Render as a spec table on case-study layouts; ignore\n * everywhere else.\n */\n metadata?: { label: string; value: string }[];\n}\n\nexport interface FetchOptions {\n /** Override the per-fetch revalidate window. Default: 60 seconds. */\n revalidate?: number;\n /** Extra ISR tags to attach to the fetch. */\n extraTags?: string[];\n /** Skip Next's ISR cache for this call. */\n noStore?: boolean;\n}\n\n/**\n * List filters, all applied server-side by the CMS — prefer these over\n * fetching everything and filtering client-side.\n */\nexport interface FetchPostsOptions extends FetchOptions {\n /** Exact-match on the post's `category`. */\n category?: string;\n /**\n * Only return posts under this route prefix (e.g. \"documentation\"). Don't\n * pass \"blog\" for the blog itself — legacy posts predate the field and have\n * no prefix, so they'd be excluded; filter the blog list client-side instead\n * (see the README's Scoped routes section).\n */\n routePrefix?: string;\n /** Posts whose `tags` include this tag. */\n tag?: string;\n /** Full-text search across title/content. */\n search?: string;\n /**\n * Page size; combine with `startAfter` to paginate. The response carries no\n * `hasMore`/`total` — fetch `limit + 1`, and if more than `limit` arrive\n * there is another page (drop the extra).\n */\n limit?: number;\n /** Pagination cursor: the `id` of the last post from the previous page. */\n startAfter?: string;\n}\n\nexport interface FetchPostOptions extends FetchOptions {\n /**\n * A signed preview token (from the CMS) that unlocks an unpublished post.\n * When set, the cache is bypassed automatically — preview content must\n * never be cached or served to the public.\n */\n previewToken?: string;\n}\n\nfunction cmsUrl(): string {\n return process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n}\n\nfunction bypassCache(): boolean {\n return (\n process.env.VULCANTECH_BLOG_NO_CACHE === \"1\" ||\n process.env.VULCANTECH_BLOG_NO_CACHE === \"true\"\n );\n}\n\nfunction assertConfig(): { projectId: string; apiKey: string } | null {\n const projectId = process.env.VULCANTECH_PROJECT_ID;\n const apiKey = process.env.VULCANTECH_API_KEY;\n if (!projectId || !apiKey) {\n console.warn(\n \"[cms/blog] CMS not configured — set VULCANTECH_PROJECT_ID and VULCANTECH_API_KEY\",\n );\n return null;\n }\n return { projectId, apiKey };\n}\n\nexport { sanitizeHtml };\n\n/** Sanitize a post's HTML body so every consumer render is safe by default. */\nfunction sanitizePost(post: CMSBlogPost): CMSBlogPost {\n if (post && typeof post.content === \"string\") {\n return { ...post, content: sanitizeHtml(post.content) };\n }\n return post;\n}\n\n/** ISR tag for a project's blog list. */\nexport function tagsForBlogList(projectId: string): string[] {\n return [`blog:${projectId}`];\n}\n\n/** ISR tags for a single post (post-specific + project-wide). */\nexport function tagsForBlogPost(projectId: string, slug: string): string[] {\n return [`blog:${projectId}:${slug}`, `blog:${projectId}`];\n}\n\nfunction buildInit(\n tags: string[],\n options: FetchOptions,\n): RequestInit & { next?: { revalidate?: number; tags?: string[] } } {\n const skipCache = options.noStore || bypassCache();\n if (skipCache) return { cache: \"no-store\" };\n return {\n next: {\n revalidate: options.revalidate ?? DEFAULT_REVALIDATE_SECONDS,\n tags: [...tags, ...(options.extraTags ?? [])],\n },\n };\n}\n\n/**\n * Fetch published posts for the configured project, newest-first by\n * `publishedAt` (the CMS orders them — no client-side sort needed). Optional\n * filters (category/routePrefix/tag/search/limit/startAfter) are forwarded to\n * the CMS.\n *\n * Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it\n * logs a warning and returns `[]` — render an empty state instead of wrapping\n * in try/catch.\n */\nexport async function fetchBlogPosts(\n options: FetchPostsOptions = {},\n): Promise<CMSBlogPost[]> {\n const config = assertConfig();\n if (!config) return [];\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey, status: \"published\" });\n if (options.category) params.set(\"category\", options.category);\n if (options.routePrefix) params.set(\"routePrefix\", options.routePrefix);\n if (options.tag) params.set(\"tag\", options.tag);\n if (options.search) params.set(\"search\", options.search);\n if (options.limit) params.set(\"limit\", String(options.limit));\n if (options.startAfter) params.set(\"startAfter\", options.startAfter);\n\n const url = `${cmsUrl()}/api/blog?${params.toString()}`;\n const init = buildInit(tagsForBlogList(projectId), options);\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\"[cms/blog] CMS unreachable:\", (err as Error).message);\n return [];\n }\n if (res.status === 404) {\n console.warn(\"[cms/blog] /api/blog returned 404 — CMS may need redeployment\");\n return [];\n }\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog returned ${res.status}`);\n return [];\n }\n\n let json: { posts: CMSBlogPost[] };\n try {\n json = (await res.json()) as { posts: CMSBlogPost[] };\n } catch (err) {\n console.warn(\"[cms/blog] /api/blog returned non-JSON:\", (err as Error).message);\n return [];\n }\n return (json.posts ?? []).map(sanitizePost);\n}\n\n/**\n * Fetch a single post by slug. Returns null when not found.\n *\n * Never throws: CMS errors also return `null` (with a logged warning), so\n * treat `null` as \"show notFound()\" rather than catching exceptions.\n *\n * Pass `previewToken` (minted by the CMS) to render an unpublished draft for\n * review — that automatically bypasses the cache.\n */\nexport async function fetchBlogPostBySlug(\n slug: string,\n options: FetchPostOptions = {},\n): Promise<CMSBlogPost | null> {\n const config = assertConfig();\n if (!config) return null;\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey });\n if (options.previewToken) params.set(\"preview\", options.previewToken);\n\n const url = `${cmsUrl()}/api/blog/${encodeURIComponent(slug)}?${params.toString()}`;\n // Preview responses must never be cached.\n const init = buildInit(tagsForBlogPost(projectId, slug), {\n ...options,\n noStore: options.noStore || !!options.previewToken,\n });\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\n `[cms/blog] CMS unreachable for \"${slug}\":`,\n (err as Error).message,\n );\n return null;\n }\n if (res.status === 404) return null;\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);\n return null;\n }\n\n let json: { post: CMSBlogPost };\n try {\n json = (await res.json()) as { post: CMSBlogPost };\n } catch (err) {\n console.warn(`[cms/blog] /api/blog/${slug} returned non-JSON:`, (err as Error).message);\n return null;\n }\n return json.post ? sanitizePost(json.post) : null;\n}\n\n/* ─── Draft preview (Next.js Draft Mode) ─── */\n\nconst PREVIEW_COOKIE = \"vt_preview_token\";\nconst PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60; // 2 hours\n\n/**\n * Route handler for `/api/preview?token=…&slug=…`.\n *\n * Validates the token against the CMS, enables Next Draft Mode, stores the\n * token in an httpOnly cookie, and redirects to the post — which then renders\n * the draft (see resolvePreviewToken). On an invalid/expired token it just\n * redirects to the public page (which 404s if the post isn't published).\n *\n * Each consumer wires it up with one line:\n * // app/api/preview/route.ts\n * export { GET } from \"@vulcantech/blog\";\n */\nexport async function GET(request: NextRequest): Promise<Response> {\n const { searchParams } = new URL(request.url);\n const token = searchParams.get(\"token\");\n const slug = searchParams.get(\"slug\");\n\n if (!token || !slug) {\n return NextResponse.json(\n { error: \"token and slug are required\" },\n { status: 400 },\n );\n }\n\n const target = new URL(`/blog/${encodeURIComponent(slug)}`, request.url);\n\n // Validate by asking the CMS to resolve the draft with this token.\n const post = await fetchBlogPostBySlug(slug, { previewToken: token });\n if (!post) {\n return NextResponse.redirect(target);\n }\n\n (await draftMode()).enable();\n (await cookies()).set(PREVIEW_COOKIE, token, {\n httpOnly: true,\n sameSite: \"lax\",\n secure: process.env.NODE_ENV === \"production\",\n path: \"/\",\n maxAge: PREVIEW_MAX_AGE_SECONDS,\n });\n\n return NextResponse.redirect(target);\n}\n\n/**\n * Page helper: returns the active preview token when Draft Mode is on, else\n * undefined. Call it in the blog post server component and spread the result\n * into the fetch:\n *\n * const previewToken = await resolvePreviewToken();\n * const post = await fetchBlogPostBySlug(slug, { previewToken });\n *\n * Reading the cookie only happens when Draft Mode is enabled, so the public\n * route stays statically rendered for normal visitors.\n */\nexport async function resolvePreviewToken(): Promise<string | undefined> {\n const { isEnabled } = await draftMode();\n if (!isEnabled) return undefined;\n const store = await cookies();\n return store.get(PREVIEW_COOKIE)?.value;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vulcantech/blog",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.1",
|
|
4
4
|
"description": "Server-side blog fetch layer for VulcanTech consumer sites — ISR-tagged reads from the CMS, with signed draft-preview support. Shared so each site doesn't duplicate the fetch code.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"source": "./src/index.ts",
|
|
@@ -12,7 +12,7 @@
|
|
|
12
12
|
"types": "./dist/index.d.ts",
|
|
13
13
|
"import": "./dist/index.mjs",
|
|
14
14
|
"require": "./dist/index.js",
|
|
15
|
-
"default": "./
|
|
15
|
+
"default": "./dist/index.mjs"
|
|
16
16
|
}
|
|
17
17
|
},
|
|
18
18
|
"files": [
|
|
@@ -43,7 +43,7 @@
|
|
|
43
43
|
],
|
|
44
44
|
"repository": {
|
|
45
45
|
"type": "git",
|
|
46
|
-
"url": "https://github.com/vulcantech/vulcantech"
|
|
46
|
+
"url": "git+https://github.com/vulcantech/vulcantech.git"
|
|
47
47
|
},
|
|
48
48
|
"author": "VulcanTech <vulcantechnologies.io@gmail.com>",
|
|
49
49
|
"publishConfig": {
|
package/src/index.ts
CHANGED
|
@@ -68,6 +68,13 @@ export interface CMSBlogPost {
|
|
|
68
68
|
* `dangerouslySetInnerHTML`; do not run it through a markdown renderer.
|
|
69
69
|
* Sanitized on write by the CMS and re-sanitized by this package's fetchers,
|
|
70
70
|
* so it is safe to inject as-is.
|
|
71
|
+
*
|
|
72
|
+
* Markup contract (see the README's "What's inside content" for the full
|
|
73
|
+
* story): headings start at h2 (h1 is yours, for the title); images are
|
|
74
|
+
* plain `<img>` with no dimensions — `next/image` is not usable here, style
|
|
75
|
+
* `img` with CSS; galleries are empty `div.cms-gallery[data-gallery]` nodes
|
|
76
|
+
* that render as nothing unless hydrated; inline `style` never survives the
|
|
77
|
+
* sanitizers, so bring your own typography (e.g. a `prose` wrapper).
|
|
71
78
|
*/
|
|
72
79
|
content: string;
|
|
73
80
|
/** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */
|
|
@@ -137,13 +144,22 @@ export interface FetchOptions {
|
|
|
137
144
|
export interface FetchPostsOptions extends FetchOptions {
|
|
138
145
|
/** Exact-match on the post's `category`. */
|
|
139
146
|
category?: string;
|
|
140
|
-
/**
|
|
147
|
+
/**
|
|
148
|
+
* Only return posts under this route prefix (e.g. "documentation"). Don't
|
|
149
|
+
* pass "blog" for the blog itself — legacy posts predate the field and have
|
|
150
|
+
* no prefix, so they'd be excluded; filter the blog list client-side instead
|
|
151
|
+
* (see the README's Scoped routes section).
|
|
152
|
+
*/
|
|
141
153
|
routePrefix?: string;
|
|
142
154
|
/** Posts whose `tags` include this tag. */
|
|
143
155
|
tag?: string;
|
|
144
156
|
/** Full-text search across title/content. */
|
|
145
157
|
search?: string;
|
|
146
|
-
/**
|
|
158
|
+
/**
|
|
159
|
+
* Page size; combine with `startAfter` to paginate. The response carries no
|
|
160
|
+
* `hasMore`/`total` — fetch `limit + 1`, and if more than `limit` arrive
|
|
161
|
+
* there is another page (drop the extra).
|
|
162
|
+
*/
|
|
147
163
|
limit?: number;
|
|
148
164
|
/** Pagination cursor: the `id` of the last post from the previous page. */
|
|
149
165
|
startAfter?: string;
|
|
@@ -216,8 +232,10 @@ function buildInit(
|
|
|
216
232
|
}
|
|
217
233
|
|
|
218
234
|
/**
|
|
219
|
-
* Fetch published posts for the configured project
|
|
220
|
-
* (
|
|
235
|
+
* Fetch published posts for the configured project, newest-first by
|
|
236
|
+
* `publishedAt` (the CMS orders them — no client-side sort needed). Optional
|
|
237
|
+
* filters (category/routePrefix/tag/search/limit/startAfter) are forwarded to
|
|
238
|
+
* the CMS.
|
|
221
239
|
*
|
|
222
240
|
* Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it
|
|
223
241
|
* logs a warning and returns `[]` — render an empty state instead of wrapping
|
|
@@ -257,7 +275,13 @@ export async function fetchBlogPosts(
|
|
|
257
275
|
return [];
|
|
258
276
|
}
|
|
259
277
|
|
|
260
|
-
|
|
278
|
+
let json: { posts: CMSBlogPost[] };
|
|
279
|
+
try {
|
|
280
|
+
json = (await res.json()) as { posts: CMSBlogPost[] };
|
|
281
|
+
} catch (err) {
|
|
282
|
+
console.warn("[cms/blog] /api/blog returned non-JSON:", (err as Error).message);
|
|
283
|
+
return [];
|
|
284
|
+
}
|
|
261
285
|
return (json.posts ?? []).map(sanitizePost);
|
|
262
286
|
}
|
|
263
287
|
|
|
@@ -304,7 +328,13 @@ export async function fetchBlogPostBySlug(
|
|
|
304
328
|
return null;
|
|
305
329
|
}
|
|
306
330
|
|
|
307
|
-
|
|
331
|
+
let json: { post: CMSBlogPost };
|
|
332
|
+
try {
|
|
333
|
+
json = (await res.json()) as { post: CMSBlogPost };
|
|
334
|
+
} catch (err) {
|
|
335
|
+
console.warn(`[cms/blog] /api/blog/${slug} returned non-JSON:`, (err as Error).message);
|
|
336
|
+
return null;
|
|
337
|
+
}
|
|
308
338
|
return json.post ? sanitizePost(json.post) : null;
|
|
309
339
|
}
|
|
310
340
|
|