@vulcantech/blog 0.1.1 → 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 CHANGED
@@ -2,10 +2,75 @@
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`, and the `CMSBlogPost` / `CMSBlogAuthor` 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
 
9
+ ## Post shape (`CMSBlogPost`)
10
+
11
+ `content` is **sanitized HTML** (TipTap editor output), **not markdown** — render it with `dangerouslySetInnerHTML`, never through a markdown renderer. It is sanitized on write by the CMS and re-sanitized by this package's fetchers, so injecting it as-is is safe by default. The exported `sanitizeHtml` is the same boundary pass — only needed for CMS HTML obtained some other way.
12
+
13
+ ```ts
14
+ interface CMSBlogPost {
15
+ id: string;
16
+ projectId: string;
17
+ title: string;
18
+ slug: string;
19
+ content: string; // sanitized HTML — see above
20
+ excerpt: string; // plain-text summary
21
+ author: { uid?: string; name: string; avatar?: string }; // object, not a string
22
+ tags: string[];
23
+ category?: string; // single editorial bucket (vs free-form tags)
24
+ routePrefix?: string; // URL space; absent = "blog" (see Scoped routes)
25
+ keywords?: string; // comma-separated SEO keywords, target keyword first
26
+ featuredImage?: string; // in-page hero / card image
27
+ featuredVideo?: CMSVideoDescriptor; // advisory; most posts have none (see step 8)
28
+ ogImage?: string; // social card; fall back: ogImage ?? featuredImage
29
+ seoTitle?: string; // fall back: seoTitle ?? title
30
+ seoDescription?: string; // fall back: seoDescription ?? excerpt
31
+ status: "draft" | "in_review" | "published" | "archived";
32
+ publishedAt?: string; // ISO 8601; always present on published posts
33
+ scheduledAt?: string; // ISO 8601
34
+ createdAt: string; // ISO 8601
35
+ updatedAt: string; // ISO 8601
36
+ postType?: "article" | "case-study" | "announcement"; // absent = "article"
37
+ metadata?: { label: string; value: string }[]; // case-study spec sheet — see below
38
+ }
39
+ ```
40
+
41
+ Field notes:
42
+
43
+ - **`seoTitle` / `seoDescription` / `ogImage`** are per-post SEO overrides. In `generateMetadata`, use the fallback chains shown above — that is the convention every VulcanTech site follows.
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
+ - **`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
+
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
+
64
+ ### Fetching and failure mode
65
+
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`.
71
+
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.
73
+
9
74
  ## Integration
10
75
 
11
76
  Wire blog into a consumer site (Next.js App Router):
@@ -50,6 +115,55 @@ The CMS mints a signed token and links to `/api/preview?token=…&slug=…`; the
50
115
 
51
116
  **6. ISR invalidation** — ensure `src/app/api/revalidate/route.ts` exists; the CMS purges `blog:{projectId}` (list) and `blog:{projectId}:{slug}` (single) on edit.
52
117
 
118
+ **7. (Optional) video styling** — authors can drop videos into post content. They
119
+ arrive as real, playable markup (`<video class="cms-video">` for CMS-hosted files,
120
+ a pinned `youtube-nocookie.com` `<iframe class="cms-video">` for YouTube), so a
121
+ site that does nothing still plays them. Add this to your global CSS to size them:
122
+
123
+ ```css
124
+ .cms-video {
125
+ display: block;
126
+ width: 100%;
127
+ max-width: 40rem;
128
+ aspect-ratio: 16 / 9;
129
+ border: 0;
130
+ border-radius: 0.5rem;
131
+ }
132
+ /* YouTube Shorts — 9:16 */
133
+ .cms-video--short {
134
+ max-width: 20rem;
135
+ aspect-ratio: 9 / 16;
136
+ }
137
+ /* Only present when the author wrote a caption */
138
+ .cms-video-figure { margin: 1.5rem 0; }
139
+ .cms-video-figure figcaption { margin-top: 0.5rem; font-size: 0.875rem; opacity: 0.7; }
140
+ ```
141
+
142
+ **8. (Optional) featured video** — a post may carry `featuredVideo` beside
143
+ `featuredImage`: structured metadata, not markup, so **your site decides the
144
+ treatment** (hero player, card thumbnail, or ignore it). Most posts have none.
145
+
146
+ ```ts
147
+ type CMSVideoDescriptor =
148
+ | { provider: "youtube"; videoId: string }
149
+ | { provider: "youtube-short"; videoId: string } // 9:16
150
+ | { provider: "file"; url: string; poster?: string }; // CMS media library
151
+ ```
152
+
153
+ The CMS pins both halves on write — `videoId` is safe to interpolate into a
154
+ YouTube embed URL, and `url` is always on the media host — so there is nothing
155
+ to re-validate before rendering. Inside the monorepo, `ui` ships a ready-made
156
+ player rather than each site hand-rolling the iframe:
157
+
158
+ ```tsx
159
+ import { VideoEmbed } from "ui/src/video";
160
+
161
+ {post.featuredVideo && <VideoEmbed video={post.featuredVideo} className="rounded-xl" />}
162
+ ```
163
+
164
+ This is separate from videos the author placed *within* the article — those
165
+ arrive as playable markup inside `content` (step 7 above) and need no code.
166
+
53
167
  ## Scoped routes (`routePrefix`)
54
168
 
55
169
  Posts carry an optional `routePrefix` that decides which URL space they live in
package/dist/index.d.mts CHANGED
@@ -19,6 +19,10 @@ import { NextRequest } from 'next/server';
19
19
  /**
20
20
  * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe
21
21
  * URL schemes. Returns the cleaned HTML string.
22
+ *
23
+ * The package's fetchers already run every post's `content` through this, so
24
+ * call it only for CMS HTML obtained some other way (legacy exports, custom
25
+ * endpoints).
22
26
  */
23
27
  declare function sanitizeHtml(html: string): string;
24
28
 
@@ -58,14 +62,51 @@ interface CMSBlogAuthor {
58
62
  name: string;
59
63
  avatar?: string;
60
64
  }
65
+ /**
66
+ * A supplementary video attached to a post, normalized by the CMS.
67
+ *
68
+ * Structural copy of the CMS's canonical `VideoDescriptor`
69
+ * (`packages/blog-editor-shared/src/lib/video.ts`) — inlined rather than
70
+ * imported so this package stays dependency-free for consumer sites. Keep the
71
+ * shape in sync; the CMS validates every write against the original.
72
+ *
73
+ * `videoId` is safe to interpolate into a YouTube embed URL and `url` is always
74
+ * on the CMS media host — the CMS pins both, so a consumer never has to
75
+ * re-validate before rendering.
76
+ */
77
+ type CMSVideoDescriptor = {
78
+ provider: "youtube";
79
+ videoId: string;
80
+ } | {
81
+ provider: "youtube-short";
82
+ videoId: string;
83
+ } | {
84
+ provider: "file";
85
+ url: string;
86
+ poster?: string;
87
+ };
61
88
  interface CMSBlogPost {
62
89
  id: string;
63
90
  projectId: string;
64
91
  title: string;
65
92
  slug: string;
66
- /** HTML content (TipTap output). */
93
+ /**
94
+ * Sanitized HTML (TipTap editor output) — NOT markdown. Render with
95
+ * `dangerouslySetInnerHTML`; do not run it through a markdown renderer.
96
+ * Sanitized on write by the CMS and re-sanitized by this package's fetchers,
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).
105
+ */
67
106
  content: string;
107
+ /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */
68
108
  excerpt: string;
109
+ /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */
69
110
  category?: string;
70
111
  /** URL route segment the post lives under, e.g. "blog" or "documentation". */
71
112
  routePrefix?: string;
@@ -76,17 +117,41 @@ interface CMSBlogPost {
76
117
  * `Metadata.keywords`; absent when the post has no keywords set.
77
118
  */
78
119
  keywords?: string;
120
+ /** An object, not a string — display `author.name`. */
79
121
  author: CMSBlogAuthor;
122
+ /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */
80
123
  featuredImage?: string;
124
+ /**
125
+ * Optional supplementary video for the post. Purely advisory — render it as a
126
+ * hero player, a card thumbnail, or ignore it; nothing breaks when it's
127
+ * absent, and it is absent on most posts. Videos placed *inside* the article
128
+ * arrive as playable markup within `content` instead.
129
+ */
130
+ featuredVideo?: CMSVideoDescriptor;
131
+ /** The public fetchers only ever return "published" posts (or a token-unlocked draft). */
81
132
  status: "draft" | "in_review" | "published" | "archived";
133
+ /** ISO 8601 timestamp. Always present on published posts. */
82
134
  publishedAt?: string;
135
+ /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */
83
136
  scheduledAt?: string;
137
+ /** ISO 8601 timestamp. */
84
138
  createdAt: string;
139
+ /** ISO 8601 timestamp. */
85
140
  updatedAt: string;
141
+ /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */
86
142
  seoTitle?: string;
143
+ /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */
87
144
  seoDescription?: string;
145
+ /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */
88
146
  ogImage?: string;
147
+ /** Defaults to "article" when absent (the field predates postType). */
89
148
  postType?: "article" | "case-study" | "announcement";
149
+ /**
150
+ * Spec-sheet pairs for case studies (e.g. `{ label: "Make", value: "1969
151
+ * Camaro" }`) — the CMS only shows this editor when `postType` is
152
+ * "case-study". Render as a spec table on case-study layouts; ignore
153
+ * everywhere else.
154
+ */
90
155
  metadata?: {
91
156
  label: string;
92
157
  value: string;
@@ -100,13 +165,31 @@ interface FetchOptions {
100
165
  /** Skip Next's ISR cache for this call. */
101
166
  noStore?: boolean;
102
167
  }
168
+ /**
169
+ * List filters, all applied server-side by the CMS — prefer these over
170
+ * fetching everything and filtering client-side.
171
+ */
103
172
  interface FetchPostsOptions extends FetchOptions {
173
+ /** Exact-match on the post's `category`. */
104
174
  category?: string;
105
- /** Only return posts under this route prefix (e.g. "documentation"). */
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
+ */
106
181
  routePrefix?: string;
182
+ /** Posts whose `tags` include this tag. */
107
183
  tag?: string;
184
+ /** Full-text search across title/content. */
108
185
  search?: string;
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
+ */
109
191
  limit?: number;
192
+ /** Pagination cursor: the `id` of the last post from the previous page. */
110
193
  startAfter?: string;
111
194
  }
112
195
  interface FetchPostOptions extends FetchOptions {
@@ -123,13 +206,22 @@ declare function tagsForBlogList(projectId: string): string[];
123
206
  /** ISR tags for a single post (post-specific + project-wide). */
124
207
  declare function tagsForBlogPost(projectId: string, slug: string): string[];
125
208
  /**
126
- * Fetch published posts for the configured project. Optional filters
127
- * (category/tag/search/limit/startAfter) are forwarded to the CMS.
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.
213
+ *
214
+ * Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it
215
+ * logs a warning and returns `[]` — render an empty state instead of wrapping
216
+ * in try/catch.
128
217
  */
129
218
  declare function fetchBlogPosts(options?: FetchPostsOptions): Promise<CMSBlogPost[]>;
130
219
  /**
131
220
  * Fetch a single post by slug. Returns null when not found.
132
221
  *
222
+ * Never throws: CMS errors also return `null` (with a logged warning), so
223
+ * treat `null` as "show notFound()" rather than catching exceptions.
224
+ *
133
225
  * Pass `previewToken` (minted by the CMS) to render an unpublished draft for
134
226
  * review — that automatically bypasses the cache.
135
227
  */
@@ -160,4 +252,4 @@ declare function GET(request: NextRequest): Promise<Response>;
160
252
  */
161
253
  declare function resolvePreviewToken(): Promise<string | undefined>;
162
254
 
163
- export { type CMSBlogAuthor, type CMSBlogPost, type FetchOptions, type FetchPostOptions, type FetchPostsOptions, GET, fetchBlogPostBySlug, fetchBlogPosts, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
255
+ export { type CMSBlogAuthor, type CMSBlogPost, type CMSVideoDescriptor, type FetchOptions, type FetchPostOptions, type FetchPostsOptions, GET, fetchBlogPostBySlug, fetchBlogPosts, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
package/dist/index.d.ts CHANGED
@@ -19,6 +19,10 @@ import { NextRequest } from 'next/server';
19
19
  /**
20
20
  * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe
21
21
  * URL schemes. Returns the cleaned HTML string.
22
+ *
23
+ * The package's fetchers already run every post's `content` through this, so
24
+ * call it only for CMS HTML obtained some other way (legacy exports, custom
25
+ * endpoints).
22
26
  */
23
27
  declare function sanitizeHtml(html: string): string;
24
28
 
@@ -58,14 +62,51 @@ interface CMSBlogAuthor {
58
62
  name: string;
59
63
  avatar?: string;
60
64
  }
65
+ /**
66
+ * A supplementary video attached to a post, normalized by the CMS.
67
+ *
68
+ * Structural copy of the CMS's canonical `VideoDescriptor`
69
+ * (`packages/blog-editor-shared/src/lib/video.ts`) — inlined rather than
70
+ * imported so this package stays dependency-free for consumer sites. Keep the
71
+ * shape in sync; the CMS validates every write against the original.
72
+ *
73
+ * `videoId` is safe to interpolate into a YouTube embed URL and `url` is always
74
+ * on the CMS media host — the CMS pins both, so a consumer never has to
75
+ * re-validate before rendering.
76
+ */
77
+ type CMSVideoDescriptor = {
78
+ provider: "youtube";
79
+ videoId: string;
80
+ } | {
81
+ provider: "youtube-short";
82
+ videoId: string;
83
+ } | {
84
+ provider: "file";
85
+ url: string;
86
+ poster?: string;
87
+ };
61
88
  interface CMSBlogPost {
62
89
  id: string;
63
90
  projectId: string;
64
91
  title: string;
65
92
  slug: string;
66
- /** HTML content (TipTap output). */
93
+ /**
94
+ * Sanitized HTML (TipTap editor output) — NOT markdown. Render with
95
+ * `dangerouslySetInnerHTML`; do not run it through a markdown renderer.
96
+ * Sanitized on write by the CMS and re-sanitized by this package's fetchers,
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).
105
+ */
67
106
  content: string;
107
+ /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */
68
108
  excerpt: string;
109
+ /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */
69
110
  category?: string;
70
111
  /** URL route segment the post lives under, e.g. "blog" or "documentation". */
71
112
  routePrefix?: string;
@@ -76,17 +117,41 @@ interface CMSBlogPost {
76
117
  * `Metadata.keywords`; absent when the post has no keywords set.
77
118
  */
78
119
  keywords?: string;
120
+ /** An object, not a string — display `author.name`. */
79
121
  author: CMSBlogAuthor;
122
+ /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */
80
123
  featuredImage?: string;
124
+ /**
125
+ * Optional supplementary video for the post. Purely advisory — render it as a
126
+ * hero player, a card thumbnail, or ignore it; nothing breaks when it's
127
+ * absent, and it is absent on most posts. Videos placed *inside* the article
128
+ * arrive as playable markup within `content` instead.
129
+ */
130
+ featuredVideo?: CMSVideoDescriptor;
131
+ /** The public fetchers only ever return "published" posts (or a token-unlocked draft). */
81
132
  status: "draft" | "in_review" | "published" | "archived";
133
+ /** ISO 8601 timestamp. Always present on published posts. */
82
134
  publishedAt?: string;
135
+ /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */
83
136
  scheduledAt?: string;
137
+ /** ISO 8601 timestamp. */
84
138
  createdAt: string;
139
+ /** ISO 8601 timestamp. */
85
140
  updatedAt: string;
141
+ /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */
86
142
  seoTitle?: string;
143
+ /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */
87
144
  seoDescription?: string;
145
+ /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */
88
146
  ogImage?: string;
147
+ /** Defaults to "article" when absent (the field predates postType). */
89
148
  postType?: "article" | "case-study" | "announcement";
149
+ /**
150
+ * Spec-sheet pairs for case studies (e.g. `{ label: "Make", value: "1969
151
+ * Camaro" }`) — the CMS only shows this editor when `postType` is
152
+ * "case-study". Render as a spec table on case-study layouts; ignore
153
+ * everywhere else.
154
+ */
90
155
  metadata?: {
91
156
  label: string;
92
157
  value: string;
@@ -100,13 +165,31 @@ interface FetchOptions {
100
165
  /** Skip Next's ISR cache for this call. */
101
166
  noStore?: boolean;
102
167
  }
168
+ /**
169
+ * List filters, all applied server-side by the CMS — prefer these over
170
+ * fetching everything and filtering client-side.
171
+ */
103
172
  interface FetchPostsOptions extends FetchOptions {
173
+ /** Exact-match on the post's `category`. */
104
174
  category?: string;
105
- /** Only return posts under this route prefix (e.g. "documentation"). */
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
+ */
106
181
  routePrefix?: string;
182
+ /** Posts whose `tags` include this tag. */
107
183
  tag?: string;
184
+ /** Full-text search across title/content. */
108
185
  search?: string;
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
+ */
109
191
  limit?: number;
192
+ /** Pagination cursor: the `id` of the last post from the previous page. */
110
193
  startAfter?: string;
111
194
  }
112
195
  interface FetchPostOptions extends FetchOptions {
@@ -123,13 +206,22 @@ declare function tagsForBlogList(projectId: string): string[];
123
206
  /** ISR tags for a single post (post-specific + project-wide). */
124
207
  declare function tagsForBlogPost(projectId: string, slug: string): string[];
125
208
  /**
126
- * Fetch published posts for the configured project. Optional filters
127
- * (category/tag/search/limit/startAfter) are forwarded to the CMS.
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.
213
+ *
214
+ * Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it
215
+ * logs a warning and returns `[]` — render an empty state instead of wrapping
216
+ * in try/catch.
128
217
  */
129
218
  declare function fetchBlogPosts(options?: FetchPostsOptions): Promise<CMSBlogPost[]>;
130
219
  /**
131
220
  * Fetch a single post by slug. Returns null when not found.
132
221
  *
222
+ * Never throws: CMS errors also return `null` (with a logged warning), so
223
+ * treat `null` as "show notFound()" rather than catching exceptions.
224
+ *
133
225
  * Pass `previewToken` (minted by the CMS) to render an unpublished draft for
134
226
  * review — that automatically bypasses the cache.
135
227
  */
@@ -160,4 +252,4 @@ declare function GET(request: NextRequest): Promise<Response>;
160
252
  */
161
253
  declare function resolvePreviewToken(): Promise<string | undefined>;
162
254
 
163
- export { type CMSBlogAuthor, type CMSBlogPost, type FetchOptions, type FetchPostOptions, type FetchPostsOptions, GET, fetchBlogPostBySlug, fetchBlogPosts, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
255
+ export { type CMSBlogAuthor, type CMSBlogPost, type CMSVideoDescriptor, type FetchOptions, type FetchPostOptions, type FetchPostsOptions, GET, fetchBlogPostBySlug, fetchBlogPosts, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
package/dist/index.js CHANGED
@@ -8,7 +8,6 @@ var server = require('next/server');
8
8
  // src/sanitize.ts
9
9
  var DANGEROUS_TAGS = [
10
10
  "script",
11
- "iframe",
12
11
  "object",
13
12
  "embed",
14
13
  "form",
@@ -31,6 +30,7 @@ var DANGEROUS_TAGS = [
31
30
  "noscript",
32
31
  "template"
33
32
  ];
33
+ var YOUTUBE_EMBED_SRC = /^https:\/\/(?:www\.)?(?:youtube-nocookie\.com|youtube\.com)\/embed\/[A-Za-z0-9_-]{6,20}(?:[?#].*)?$/;
34
34
  function safeCodePoint(n) {
35
35
  if (!Number.isFinite(n) || n < 0 || n > 1114111) return "";
36
36
  try {
@@ -49,6 +49,17 @@ function stripBlankAndControl(s) {
49
49
  }
50
50
  return out;
51
51
  }
52
+ function stripForeignIframes(html) {
53
+ return html.replace(
54
+ /<iframe\b[^>]*>(?:[\s\S]*?<\/iframe>)?/gi,
55
+ (element) => {
56
+ const match = /\bsrc\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(element);
57
+ const raw = match ? match[2] ?? match[3] ?? match[4] ?? "" : "";
58
+ const src = stripBlankAndControl(decodeEntities(raw));
59
+ return YOUTUBE_EMBED_SRC.test(src) ? element : "";
60
+ }
61
+ );
62
+ }
52
63
  function sanitizeHtml(html) {
53
64
  if (!html) return "";
54
65
  let clean = html.replace(
@@ -62,6 +73,7 @@ function sanitizeHtml(html) {
62
73
  );
63
74
  clean = clean.replace(new RegExp(`<${tag}\\b[^>]*\\/?>`, "gi"), "");
64
75
  }
76
+ clean = stripForeignIframes(clean);
65
77
  clean = clean.replace(
66
78
  /\s+on\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]*)/gi,
67
79
  ""
@@ -153,7 +165,13 @@ async function fetchBlogPosts(options = {}) {
153
165
  console.warn(`[cms/blog] /api/blog returned ${res.status}`);
154
166
  return [];
155
167
  }
156
- const json = await res.json();
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
+ }
157
175
  return (json.posts ?? []).map(sanitizePost);
158
176
  }
159
177
  async function fetchBlogPostBySlug(slug, options = {}) {
@@ -182,7 +200,13 @@ async function fetchBlogPostBySlug(slug, options = {}) {
182
200
  console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);
183
201
  return null;
184
202
  }
185
- const json = await res.json();
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
+ }
186
210
  return json.post ? sanitizePost(json.post) : null;
187
211
  }
188
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,QAAA;AAAA,EAAU,OAAA;AAAA,EAAS,MAAA;AAAA,EAAQ,OAAA;AAAA,EAAS,UAAA;AAAA,EACxD,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,QAAA;AA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AC,KAAA,IAAS,CAAC,IAAA,EAAM;AACnB,IAAA,OAAOA,mBAAA,CAAa,IAAA;AAAA,MAClB,EAAE,OAAO,6BAAA,EAA8B;AAAA,MACvC,EAAE,QAAQ,GAAA;AAAI,KAChB;AAAA,EACF;AAEA,EAAA,MAAM,MAAA,GAAS,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\", \"iframe\", \"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\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(/&colon;/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&amp;/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 * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe\n * URL schemes. Returns the cleaned HTML string.\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 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\nexport interface CMSBlogPost {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n /** HTML content (TipTap output). */\n content: string;\n excerpt: string;\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 author: CMSBlogAuthor;\n featuredImage?: string;\n status: \"draft\" | \"in_review\" | \"published\" | \"archived\";\n publishedAt?: string;\n scheduledAt?: string;\n createdAt: string;\n updatedAt: string;\n seoTitle?: string;\n seoDescription?: string;\n ogImage?: string;\n postType?: \"article\" | \"case-study\" | \"announcement\";\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\nexport interface FetchPostsOptions extends FetchOptions {\n category?: string;\n /** Only return posts under this route prefix (e.g. \"documentation\"). */\n routePrefix?: string;\n tag?: string;\n search?: string;\n limit?: number;\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/tag/search/limit/startAfter) are forwarded to the CMS.\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 * 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,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AAQ,GAAA;AAAI,KAChB;AAAA,EACF;AAEA,EAAA,MAAM,MAAA,GAAS,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(/&colon;/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&amp;/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
@@ -6,7 +6,6 @@ import { NextResponse } from 'next/server';
6
6
  // src/sanitize.ts
7
7
  var DANGEROUS_TAGS = [
8
8
  "script",
9
- "iframe",
10
9
  "object",
11
10
  "embed",
12
11
  "form",
@@ -29,6 +28,7 @@ var DANGEROUS_TAGS = [
29
28
  "noscript",
30
29
  "template"
31
30
  ];
31
+ var YOUTUBE_EMBED_SRC = /^https:\/\/(?:www\.)?(?:youtube-nocookie\.com|youtube\.com)\/embed\/[A-Za-z0-9_-]{6,20}(?:[?#].*)?$/;
32
32
  function safeCodePoint(n) {
33
33
  if (!Number.isFinite(n) || n < 0 || n > 1114111) return "";
34
34
  try {
@@ -47,6 +47,17 @@ function stripBlankAndControl(s) {
47
47
  }
48
48
  return out;
49
49
  }
50
+ function stripForeignIframes(html) {
51
+ return html.replace(
52
+ /<iframe\b[^>]*>(?:[\s\S]*?<\/iframe>)?/gi,
53
+ (element) => {
54
+ const match = /\bsrc\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(element);
55
+ const raw = match ? match[2] ?? match[3] ?? match[4] ?? "" : "";
56
+ const src = stripBlankAndControl(decodeEntities(raw));
57
+ return YOUTUBE_EMBED_SRC.test(src) ? element : "";
58
+ }
59
+ );
60
+ }
50
61
  function sanitizeHtml(html) {
51
62
  if (!html) return "";
52
63
  let clean = html.replace(
@@ -60,6 +71,7 @@ function sanitizeHtml(html) {
60
71
  );
61
72
  clean = clean.replace(new RegExp(`<${tag}\\b[^>]*\\/?>`, "gi"), "");
62
73
  }
74
+ clean = stripForeignIframes(clean);
63
75
  clean = clean.replace(
64
76
  /\s+on\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]*)/gi,
65
77
  ""
@@ -151,7 +163,13 @@ async function fetchBlogPosts(options = {}) {
151
163
  console.warn(`[cms/blog] /api/blog returned ${res.status}`);
152
164
  return [];
153
165
  }
154
- const json = await res.json();
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
+ }
155
173
  return (json.posts ?? []).map(sanitizePost);
156
174
  }
157
175
  async function fetchBlogPostBySlug(slug, options = {}) {
@@ -180,7 +198,13 @@ async function fetchBlogPostBySlug(slug, options = {}) {
180
198
  console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);
181
199
  return null;
182
200
  }
183
- const json = await res.json();
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
+ }
184
208
  return json.post ? sanitizePost(json.post) : null;
185
209
  }
186
210
  var PREVIEW_COOKIE = "vt_preview_token";
@@ -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,QAAA;AAAA,EAAU,OAAA;AAAA,EAAS,MAAA;AAAA,EAAQ,OAAA;AAAA,EAAS,UAAA;AAAA,EACxD,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;AAC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mB,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,OAAO,YAAA,CAAa,SAAS,MAAM,CAAA;AAAA,EACrC;AAEA,EAAA,CAAC,MAAM,SAAA,EAAU,EAAG,MAAA,EAAO;AAC3B,EAAA,CAAC,MAAM,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\", \"iframe\", \"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\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(/&colon;/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&amp;/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 * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe\n * URL schemes. Returns the cleaned HTML string.\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 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\nexport interface CMSBlogPost {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n /** HTML content (TipTap output). */\n content: string;\n excerpt: string;\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 author: CMSBlogAuthor;\n featuredImage?: string;\n status: \"draft\" | \"in_review\" | \"published\" | \"archived\";\n publishedAt?: string;\n scheduledAt?: string;\n createdAt: string;\n updatedAt: string;\n seoTitle?: string;\n seoDescription?: string;\n ogImage?: string;\n postType?: \"article\" | \"case-study\" | \"announcement\";\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\nexport interface FetchPostsOptions extends FetchOptions {\n category?: string;\n /** Only return posts under this route prefix (e.g. \"documentation\"). */\n routePrefix?: string;\n tag?: string;\n search?: string;\n limit?: number;\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/tag/search/limit/startAfter) are forwarded to the CMS.\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 * 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;A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C,IAAA,EAAM;AACT,IAAA,OAAO,YAAA,CAAa,SAAS,MAAM,CAAA;AAAA,EACrC;AAEA,EAAA,CAAC,MAAM,SAAA,EAAU,EAAG,MAAA,EAAO;AAC3B,EAAA,CAAC,MAAM,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(/&colon;/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&amp;/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.1.1",
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": "./src/index.ts"
15
+ "default": "./dist/index.mjs"
16
16
  }
17
17
  },
18
18
  "files": [
@@ -30,7 +30,7 @@
30
30
  "next": ">=14.0.0"
31
31
  },
32
32
  "devDependencies": {
33
- "next": "16.0.10",
33
+ "next": "16.3.1",
34
34
  "tsup": "^8.0.0",
35
35
  "typescript": "^5.9.3"
36
36
  },
@@ -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
@@ -41,14 +41,45 @@ export interface CMSBlogAuthor {
41
41
  avatar?: string;
42
42
  }
43
43
 
44
+ /**
45
+ * A supplementary video attached to a post, normalized by the CMS.
46
+ *
47
+ * Structural copy of the CMS's canonical `VideoDescriptor`
48
+ * (`packages/blog-editor-shared/src/lib/video.ts`) — inlined rather than
49
+ * imported so this package stays dependency-free for consumer sites. Keep the
50
+ * shape in sync; the CMS validates every write against the original.
51
+ *
52
+ * `videoId` is safe to interpolate into a YouTube embed URL and `url` is always
53
+ * on the CMS media host — the CMS pins both, so a consumer never has to
54
+ * re-validate before rendering.
55
+ */
56
+ export type CMSVideoDescriptor =
57
+ | { provider: "youtube"; videoId: string }
58
+ | { provider: "youtube-short"; videoId: string }
59
+ | { provider: "file"; url: string; poster?: string };
60
+
44
61
  export interface CMSBlogPost {
45
62
  id: string;
46
63
  projectId: string;
47
64
  title: string;
48
65
  slug: string;
49
- /** HTML content (TipTap output). */
66
+ /**
67
+ * Sanitized HTML (TipTap editor output) — NOT markdown. Render with
68
+ * `dangerouslySetInnerHTML`; do not run it through a markdown renderer.
69
+ * Sanitized on write by the CMS and re-sanitized by this package's fetchers,
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).
78
+ */
50
79
  content: string;
80
+ /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */
51
81
  excerpt: string;
82
+ /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */
52
83
  category?: string;
53
84
  /** URL route segment the post lives under, e.g. "blog" or "documentation". */
54
85
  routePrefix?: string;
@@ -59,17 +90,41 @@ export interface CMSBlogPost {
59
90
  * `Metadata.keywords`; absent when the post has no keywords set.
60
91
  */
61
92
  keywords?: string;
93
+ /** An object, not a string — display `author.name`. */
62
94
  author: CMSBlogAuthor;
95
+ /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */
63
96
  featuredImage?: string;
97
+ /**
98
+ * Optional supplementary video for the post. Purely advisory — render it as a
99
+ * hero player, a card thumbnail, or ignore it; nothing breaks when it's
100
+ * absent, and it is absent on most posts. Videos placed *inside* the article
101
+ * arrive as playable markup within `content` instead.
102
+ */
103
+ featuredVideo?: CMSVideoDescriptor;
104
+ /** The public fetchers only ever return "published" posts (or a token-unlocked draft). */
64
105
  status: "draft" | "in_review" | "published" | "archived";
106
+ /** ISO 8601 timestamp. Always present on published posts. */
65
107
  publishedAt?: string;
108
+ /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */
66
109
  scheduledAt?: string;
110
+ /** ISO 8601 timestamp. */
67
111
  createdAt: string;
112
+ /** ISO 8601 timestamp. */
68
113
  updatedAt: string;
114
+ /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */
69
115
  seoTitle?: string;
116
+ /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */
70
117
  seoDescription?: string;
118
+ /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */
71
119
  ogImage?: string;
120
+ /** Defaults to "article" when absent (the field predates postType). */
72
121
  postType?: "article" | "case-study" | "announcement";
122
+ /**
123
+ * Spec-sheet pairs for case studies (e.g. `{ label: "Make", value: "1969
124
+ * Camaro" }`) — the CMS only shows this editor when `postType` is
125
+ * "case-study". Render as a spec table on case-study layouts; ignore
126
+ * everywhere else.
127
+ */
73
128
  metadata?: { label: string; value: string }[];
74
129
  }
75
130
 
@@ -82,13 +137,31 @@ export interface FetchOptions {
82
137
  noStore?: boolean;
83
138
  }
84
139
 
140
+ /**
141
+ * List filters, all applied server-side by the CMS — prefer these over
142
+ * fetching everything and filtering client-side.
143
+ */
85
144
  export interface FetchPostsOptions extends FetchOptions {
145
+ /** Exact-match on the post's `category`. */
86
146
  category?: string;
87
- /** Only return posts under this route prefix (e.g. "documentation"). */
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
+ */
88
153
  routePrefix?: string;
154
+ /** Posts whose `tags` include this tag. */
89
155
  tag?: string;
156
+ /** Full-text search across title/content. */
90
157
  search?: string;
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
+ */
91
163
  limit?: number;
164
+ /** Pagination cursor: the `id` of the last post from the previous page. */
92
165
  startAfter?: string;
93
166
  }
94
167
 
@@ -159,8 +232,14 @@ function buildInit(
159
232
  }
160
233
 
161
234
  /**
162
- * Fetch published posts for the configured project. Optional filters
163
- * (category/tag/search/limit/startAfter) are forwarded to the CMS.
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.
239
+ *
240
+ * Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it
241
+ * logs a warning and returns `[]` — render an empty state instead of wrapping
242
+ * in try/catch.
164
243
  */
165
244
  export async function fetchBlogPosts(
166
245
  options: FetchPostsOptions = {},
@@ -196,13 +275,22 @@ export async function fetchBlogPosts(
196
275
  return [];
197
276
  }
198
277
 
199
- const json = (await res.json()) as { posts: CMSBlogPost[] };
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
+ }
200
285
  return (json.posts ?? []).map(sanitizePost);
201
286
  }
202
287
 
203
288
  /**
204
289
  * Fetch a single post by slug. Returns null when not found.
205
290
  *
291
+ * Never throws: CMS errors also return `null` (with a logged warning), so
292
+ * treat `null` as "show notFound()" rather than catching exceptions.
293
+ *
206
294
  * Pass `previewToken` (minted by the CMS) to render an unpublished draft for
207
295
  * review — that automatically bypasses the cache.
208
296
  */
@@ -240,7 +328,13 @@ export async function fetchBlogPostBySlug(
240
328
  return null;
241
329
  }
242
330
 
243
- const json = (await res.json()) as { post: CMSBlogPost };
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
+ }
244
338
  return json.post ? sanitizePost(json.post) : null;
245
339
  }
246
340
 
package/src/sanitize.ts CHANGED
@@ -16,12 +16,22 @@
16
16
  */
17
17
 
18
18
  const DANGEROUS_TAGS = [
19
- "script", "iframe", "object", "embed", "form", "input", "textarea",
19
+ "script", "object", "embed", "form", "input", "textarea",
20
20
  "button", "select", "option", "link", "meta", "base", "applet",
21
21
  "frame", "frameset", "layer", "style", "svg", "math", "xmp",
22
22
  "noscript", "template",
23
23
  ];
24
24
 
25
+ /**
26
+ * `iframe` is NOT in the blocklist above: blog HTML may carry a YouTube video
27
+ * embed (BL-321). It is filtered by origin instead — an iframe pointing
28
+ * anywhere but YouTube's embed path is deleted, element and content alike, by
29
+ * {@link stripForeignIframes}. `<video>` needs no rule: it was never blocked
30
+ * here, and its `src` still goes through the URL-scheme pass below.
31
+ */
32
+ const YOUTUBE_EMBED_SRC =
33
+ /^https:\/\/(?:www\.)?(?:youtube-nocookie\.com|youtube\.com)\/embed\/[A-Za-z0-9_-]{6,20}(?:[?#].*)?$/;
34
+
25
35
  function safeCodePoint(n: number): string {
26
36
  if (!Number.isFinite(n) || n < 0 || n > 0x10ffff) return "";
27
37
  try {
@@ -51,9 +61,29 @@ function stripBlankAndControl(s: string): string {
51
61
  return out;
52
62
  }
53
63
 
64
+ /**
65
+ * Remove every `<iframe>` whose `src` is not a YouTube embed URL, taking any
66
+ * content between the tags with it.
67
+ */
68
+ function stripForeignIframes(html: string): string {
69
+ return html.replace(
70
+ /<iframe\b[^>]*>(?:[\s\S]*?<\/iframe>)?/gi,
71
+ (element) => {
72
+ const match = /\bsrc\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/i.exec(element);
73
+ const raw = match ? (match[2] ?? match[3] ?? match[4] ?? "") : "";
74
+ const src = stripBlankAndControl(decodeEntities(raw));
75
+ return YOUTUBE_EMBED_SRC.test(src) ? element : "";
76
+ },
77
+ );
78
+ }
79
+
54
80
  /**
55
81
  * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe
56
82
  * URL schemes. Returns the cleaned HTML string.
83
+ *
84
+ * The package's fetchers already run every post's `content` through this, so
85
+ * call it only for CMS HTML obtained some other way (legacy exports, custom
86
+ * endpoints).
57
87
  */
58
88
  export function sanitizeHtml(html: string): string {
59
89
  if (!html) return "";
@@ -71,6 +101,9 @@ export function sanitizeHtml(html: string): string {
71
101
  clean = clean.replace(new RegExp(`<${tag}\\b[^>]*\\/?>`, "gi"), "");
72
102
  }
73
103
 
104
+ // Keep YouTube video embeds, drop every other iframe.
105
+ clean = stripForeignIframes(clean);
106
+
74
107
  clean = clean.replace(
75
108
  /\s+on\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]*)/gi,
76
109
  "",