@vulcantech/blog 0.1.0 → 0.2.0
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 +101 -23
- package/dist/index.d.mts +77 -3
- package/dist/index.d.ts +77 -3
- package/dist/index.js +13 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +13 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
- package/src/index.ts +66 -2
- package/src/sanitize.ts +34 -1
package/README.md
CHANGED
|
@@ -2,30 +2,65 @@
|
|
|
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` 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
|
+
### Fetching and failure mode
|
|
48
|
+
|
|
49
|
+
`fetchBlogPosts(options?)` accepts server-side filters — `category`, `routePrefix`, `tag`, `search`, `limit`, and `startAfter` (a pagination cursor: the `id` of the last post of the previous page) — plus the caching knobs `revalidate` (default 60s), `extraTags`, and `noStore`. Prefer these filters over fetching everything and filtering client-side.
|
|
50
|
+
|
|
51
|
+
**The fetchers never throw.** On any CMS error (unreachable, non-2xx, unconfigured env) they log a warning and return `[]` / `null`. So: no try/catch error UI — it can never fire. Instead, handle the empty list on index pages and call `notFound()` on a `null` post.
|
|
52
|
+
|
|
9
53
|
## Integration
|
|
10
54
|
|
|
11
55
|
Wire blog into a consumer site (Next.js App Router):
|
|
12
56
|
|
|
13
|
-
**1. Add the dependency
|
|
14
|
-
```
|
|
15
|
-
|
|
57
|
+
**1. Add the dependency**:
|
|
58
|
+
```bash
|
|
59
|
+
npm install @vulcantech/blog
|
|
16
60
|
```
|
|
61
|
+
(Inside the VulcanTech monorepo, use the workspace wiring in `MONOREPO.md` instead.)
|
|
17
62
|
|
|
18
|
-
**2.
|
|
19
|
-
```js
|
|
20
|
-
transpilePackages: ["@vulcantech/blog", /* ... */],
|
|
21
|
-
webpack: (config) => {
|
|
22
|
-
config.resolve.alias["@vulcantech/blog"] = path.join(__dirname, "../../packages/blog");
|
|
23
|
-
return config;
|
|
24
|
-
},
|
|
25
|
-
turbopack: {
|
|
26
|
-
resolveAlias: { "@vulcantech/blog": "./../../packages/blog/src/index.ts" },
|
|
27
|
-
},
|
|
28
|
-
```
|
|
63
|
+
**2. Set the env** — see [Required env](#required-env) below.
|
|
29
64
|
|
|
30
65
|
**3. (Optional) thin re-export** `src/lib/cms/blog.ts` to preserve `@/lib/cms/blog` import paths:
|
|
31
66
|
```ts
|
|
@@ -59,6 +94,55 @@ The CMS mints a signed token and links to `/api/preview?token=…&slug=…`; the
|
|
|
59
94
|
|
|
60
95
|
**6. ISR invalidation** — ensure `src/app/api/revalidate/route.ts` exists; the CMS purges `blog:{projectId}` (list) and `blog:{projectId}:{slug}` (single) on edit.
|
|
61
96
|
|
|
97
|
+
**7. (Optional) video styling** — authors can drop videos into post content. They
|
|
98
|
+
arrive as real, playable markup (`<video class="cms-video">` for CMS-hosted files,
|
|
99
|
+
a pinned `youtube-nocookie.com` `<iframe class="cms-video">` for YouTube), so a
|
|
100
|
+
site that does nothing still plays them. Add this to your global CSS to size them:
|
|
101
|
+
|
|
102
|
+
```css
|
|
103
|
+
.cms-video {
|
|
104
|
+
display: block;
|
|
105
|
+
width: 100%;
|
|
106
|
+
max-width: 40rem;
|
|
107
|
+
aspect-ratio: 16 / 9;
|
|
108
|
+
border: 0;
|
|
109
|
+
border-radius: 0.5rem;
|
|
110
|
+
}
|
|
111
|
+
/* YouTube Shorts — 9:16 */
|
|
112
|
+
.cms-video--short {
|
|
113
|
+
max-width: 20rem;
|
|
114
|
+
aspect-ratio: 9 / 16;
|
|
115
|
+
}
|
|
116
|
+
/* Only present when the author wrote a caption */
|
|
117
|
+
.cms-video-figure { margin: 1.5rem 0; }
|
|
118
|
+
.cms-video-figure figcaption { margin-top: 0.5rem; font-size: 0.875rem; opacity: 0.7; }
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
**8. (Optional) featured video** — a post may carry `featuredVideo` beside
|
|
122
|
+
`featuredImage`: structured metadata, not markup, so **your site decides the
|
|
123
|
+
treatment** (hero player, card thumbnail, or ignore it). Most posts have none.
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
type CMSVideoDescriptor =
|
|
127
|
+
| { provider: "youtube"; videoId: string }
|
|
128
|
+
| { provider: "youtube-short"; videoId: string } // 9:16
|
|
129
|
+
| { provider: "file"; url: string; poster?: string }; // CMS media library
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
The CMS pins both halves on write — `videoId` is safe to interpolate into a
|
|
133
|
+
YouTube embed URL, and `url` is always on the media host — so there is nothing
|
|
134
|
+
to re-validate before rendering. Inside the monorepo, `ui` ships a ready-made
|
|
135
|
+
player rather than each site hand-rolling the iframe:
|
|
136
|
+
|
|
137
|
+
```tsx
|
|
138
|
+
import { VideoEmbed } from "ui/src/video";
|
|
139
|
+
|
|
140
|
+
{post.featuredVideo && <VideoEmbed video={post.featuredVideo} className="rounded-xl" />}
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
This is separate from videos the author placed *within* the article — those
|
|
144
|
+
arrive as playable markup inside `content` (step 7 above) and need no code.
|
|
145
|
+
|
|
62
146
|
## Scoped routes (`routePrefix`)
|
|
63
147
|
|
|
64
148
|
Posts carry an optional `routePrefix` that decides which URL space they live in
|
|
@@ -71,8 +155,8 @@ Wiring a scoped route (e.g. documentation) takes three pieces:
|
|
|
71
155
|
|
|
72
156
|
**1. A scope predicate — keep `/blog` clean.** `fetchBlogPosts()` returns every
|
|
73
157
|
published post regardless of prefix, so the blog list/related-posts must filter,
|
|
74
|
-
or scoped posts leak onto `/blog`. Centralize the predicate
|
|
75
|
-
|
|
158
|
+
or scoped posts leak onto `/blog`. Centralize the predicate in one module (e.g.
|
|
159
|
+
`src/lib/cms/postScope.ts`) instead of scattering `!== "legal"` checks:
|
|
76
160
|
|
|
77
161
|
```ts
|
|
78
162
|
export const BLOG_ROUTE_PREFIX = "blog";
|
|
@@ -102,12 +186,6 @@ if (!post || post.routePrefix !== "documentation") notFound();
|
|
|
102
186
|
tags on edit, so scoped pages revalidate with the blog as long as they use this
|
|
103
187
|
package's fetchers (which attach those tags).
|
|
104
188
|
|
|
105
|
-
Live examples: `apps/dry-ice-pro-auto/src/app/legal/` (prefix `"legal"`, with the
|
|
106
|
-
`postScope.ts` predicate keeping `/blog` scoped) and the CMS's own
|
|
107
|
-
`apps/vulcantech-cms/src/app/(theme)/documentation/` (prefix `"documentation"` —
|
|
108
|
-
note the CMS reads its own Firestore via Admin SDK in `src/lib/blog/posts.ts`
|
|
109
|
-
instead of this package, but the scoping workflow is identical).
|
|
110
|
-
|
|
111
189
|
### Required env
|
|
112
190
|
`VULCANTECH_PROJECT_ID`, `VULCANTECH_API_KEY` (required) · `VULCANTECH_CMS_URL` (optional, default `https://cms.vulcantech.io`) · `VULCANTECH_BLOG_NO_CACHE` (optional, `1`/`true` to bypass ISR while debugging).
|
|
113
191
|
|
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,44 @@ 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
|
-
/**
|
|
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
|
+
*/
|
|
67
99
|
content: string;
|
|
100
|
+
/** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */
|
|
68
101
|
excerpt: string;
|
|
102
|
+
/** Single editorial bucket (one per post) — distinct from the free-form `tags`. */
|
|
69
103
|
category?: string;
|
|
70
104
|
/** URL route segment the post lives under, e.g. "blog" or "documentation". */
|
|
71
105
|
routePrefix?: string;
|
|
@@ -76,17 +110,41 @@ interface CMSBlogPost {
|
|
|
76
110
|
* `Metadata.keywords`; absent when the post has no keywords set.
|
|
77
111
|
*/
|
|
78
112
|
keywords?: string;
|
|
113
|
+
/** An object, not a string — display `author.name`. */
|
|
79
114
|
author: CMSBlogAuthor;
|
|
115
|
+
/** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */
|
|
80
116
|
featuredImage?: string;
|
|
117
|
+
/**
|
|
118
|
+
* Optional supplementary video for the post. Purely advisory — render it as a
|
|
119
|
+
* hero player, a card thumbnail, or ignore it; nothing breaks when it's
|
|
120
|
+
* absent, and it is absent on most posts. Videos placed *inside* the article
|
|
121
|
+
* arrive as playable markup within `content` instead.
|
|
122
|
+
*/
|
|
123
|
+
featuredVideo?: CMSVideoDescriptor;
|
|
124
|
+
/** The public fetchers only ever return "published" posts (or a token-unlocked draft). */
|
|
81
125
|
status: "draft" | "in_review" | "published" | "archived";
|
|
126
|
+
/** ISO 8601 timestamp. Always present on published posts. */
|
|
82
127
|
publishedAt?: string;
|
|
128
|
+
/** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */
|
|
83
129
|
scheduledAt?: string;
|
|
130
|
+
/** ISO 8601 timestamp. */
|
|
84
131
|
createdAt: string;
|
|
132
|
+
/** ISO 8601 timestamp. */
|
|
85
133
|
updatedAt: string;
|
|
134
|
+
/** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */
|
|
86
135
|
seoTitle?: string;
|
|
136
|
+
/** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */
|
|
87
137
|
seoDescription?: string;
|
|
138
|
+
/** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */
|
|
88
139
|
ogImage?: string;
|
|
140
|
+
/** Defaults to "article" when absent (the field predates postType). */
|
|
89
141
|
postType?: "article" | "case-study" | "announcement";
|
|
142
|
+
/**
|
|
143
|
+
* Spec-sheet pairs for case studies (e.g. `{ label: "Make", value: "1969
|
|
144
|
+
* Camaro" }`) — the CMS only shows this editor when `postType` is
|
|
145
|
+
* "case-study". Render as a spec table on case-study layouts; ignore
|
|
146
|
+
* everywhere else.
|
|
147
|
+
*/
|
|
90
148
|
metadata?: {
|
|
91
149
|
label: string;
|
|
92
150
|
value: string;
|
|
@@ -100,13 +158,22 @@ interface FetchOptions {
|
|
|
100
158
|
/** Skip Next's ISR cache for this call. */
|
|
101
159
|
noStore?: boolean;
|
|
102
160
|
}
|
|
161
|
+
/**
|
|
162
|
+
* List filters, all applied server-side by the CMS — prefer these over
|
|
163
|
+
* fetching everything and filtering client-side.
|
|
164
|
+
*/
|
|
103
165
|
interface FetchPostsOptions extends FetchOptions {
|
|
166
|
+
/** Exact-match on the post's `category`. */
|
|
104
167
|
category?: string;
|
|
105
168
|
/** Only return posts under this route prefix (e.g. "documentation"). */
|
|
106
169
|
routePrefix?: string;
|
|
170
|
+
/** Posts whose `tags` include this tag. */
|
|
107
171
|
tag?: string;
|
|
172
|
+
/** Full-text search across title/content. */
|
|
108
173
|
search?: string;
|
|
174
|
+
/** Page size; combine with `startAfter` to paginate. */
|
|
109
175
|
limit?: number;
|
|
176
|
+
/** Pagination cursor: the `id` of the last post from the previous page. */
|
|
110
177
|
startAfter?: string;
|
|
111
178
|
}
|
|
112
179
|
interface FetchPostOptions extends FetchOptions {
|
|
@@ -124,12 +191,19 @@ declare function tagsForBlogList(projectId: string): string[];
|
|
|
124
191
|
declare function tagsForBlogPost(projectId: string, slug: string): string[];
|
|
125
192
|
/**
|
|
126
193
|
* Fetch published posts for the configured project. Optional filters
|
|
127
|
-
* (category/tag/search/limit/startAfter) are forwarded to the CMS.
|
|
194
|
+
* (category/routePrefix/tag/search/limit/startAfter) are forwarded to the CMS.
|
|
195
|
+
*
|
|
196
|
+
* Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it
|
|
197
|
+
* logs a warning and returns `[]` — render an empty state instead of wrapping
|
|
198
|
+
* in try/catch.
|
|
128
199
|
*/
|
|
129
200
|
declare function fetchBlogPosts(options?: FetchPostsOptions): Promise<CMSBlogPost[]>;
|
|
130
201
|
/**
|
|
131
202
|
* Fetch a single post by slug. Returns null when not found.
|
|
132
203
|
*
|
|
204
|
+
* Never throws: CMS errors also return `null` (with a logged warning), so
|
|
205
|
+
* treat `null` as "show notFound()" rather than catching exceptions.
|
|
206
|
+
*
|
|
133
207
|
* Pass `previewToken` (minted by the CMS) to render an unpublished draft for
|
|
134
208
|
* review — that automatically bypasses the cache.
|
|
135
209
|
*/
|
|
@@ -160,4 +234,4 @@ declare function GET(request: NextRequest): Promise<Response>;
|
|
|
160
234
|
*/
|
|
161
235
|
declare function resolvePreviewToken(): Promise<string | undefined>;
|
|
162
236
|
|
|
163
|
-
export { type CMSBlogAuthor, type CMSBlogPost, type FetchOptions, type FetchPostOptions, type FetchPostsOptions, GET, fetchBlogPostBySlug, fetchBlogPosts, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
|
|
237
|
+
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,44 @@ 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
|
-
/**
|
|
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
|
+
*/
|
|
67
99
|
content: string;
|
|
100
|
+
/** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */
|
|
68
101
|
excerpt: string;
|
|
102
|
+
/** Single editorial bucket (one per post) — distinct from the free-form `tags`. */
|
|
69
103
|
category?: string;
|
|
70
104
|
/** URL route segment the post lives under, e.g. "blog" or "documentation". */
|
|
71
105
|
routePrefix?: string;
|
|
@@ -76,17 +110,41 @@ interface CMSBlogPost {
|
|
|
76
110
|
* `Metadata.keywords`; absent when the post has no keywords set.
|
|
77
111
|
*/
|
|
78
112
|
keywords?: string;
|
|
113
|
+
/** An object, not a string — display `author.name`. */
|
|
79
114
|
author: CMSBlogAuthor;
|
|
115
|
+
/** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */
|
|
80
116
|
featuredImage?: string;
|
|
117
|
+
/**
|
|
118
|
+
* Optional supplementary video for the post. Purely advisory — render it as a
|
|
119
|
+
* hero player, a card thumbnail, or ignore it; nothing breaks when it's
|
|
120
|
+
* absent, and it is absent on most posts. Videos placed *inside* the article
|
|
121
|
+
* arrive as playable markup within `content` instead.
|
|
122
|
+
*/
|
|
123
|
+
featuredVideo?: CMSVideoDescriptor;
|
|
124
|
+
/** The public fetchers only ever return "published" posts (or a token-unlocked draft). */
|
|
81
125
|
status: "draft" | "in_review" | "published" | "archived";
|
|
126
|
+
/** ISO 8601 timestamp. Always present on published posts. */
|
|
82
127
|
publishedAt?: string;
|
|
128
|
+
/** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */
|
|
83
129
|
scheduledAt?: string;
|
|
130
|
+
/** ISO 8601 timestamp. */
|
|
84
131
|
createdAt: string;
|
|
132
|
+
/** ISO 8601 timestamp. */
|
|
85
133
|
updatedAt: string;
|
|
134
|
+
/** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */
|
|
86
135
|
seoTitle?: string;
|
|
136
|
+
/** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */
|
|
87
137
|
seoDescription?: string;
|
|
138
|
+
/** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */
|
|
88
139
|
ogImage?: string;
|
|
140
|
+
/** Defaults to "article" when absent (the field predates postType). */
|
|
89
141
|
postType?: "article" | "case-study" | "announcement";
|
|
142
|
+
/**
|
|
143
|
+
* Spec-sheet pairs for case studies (e.g. `{ label: "Make", value: "1969
|
|
144
|
+
* Camaro" }`) — the CMS only shows this editor when `postType` is
|
|
145
|
+
* "case-study". Render as a spec table on case-study layouts; ignore
|
|
146
|
+
* everywhere else.
|
|
147
|
+
*/
|
|
90
148
|
metadata?: {
|
|
91
149
|
label: string;
|
|
92
150
|
value: string;
|
|
@@ -100,13 +158,22 @@ interface FetchOptions {
|
|
|
100
158
|
/** Skip Next's ISR cache for this call. */
|
|
101
159
|
noStore?: boolean;
|
|
102
160
|
}
|
|
161
|
+
/**
|
|
162
|
+
* List filters, all applied server-side by the CMS — prefer these over
|
|
163
|
+
* fetching everything and filtering client-side.
|
|
164
|
+
*/
|
|
103
165
|
interface FetchPostsOptions extends FetchOptions {
|
|
166
|
+
/** Exact-match on the post's `category`. */
|
|
104
167
|
category?: string;
|
|
105
168
|
/** Only return posts under this route prefix (e.g. "documentation"). */
|
|
106
169
|
routePrefix?: string;
|
|
170
|
+
/** Posts whose `tags` include this tag. */
|
|
107
171
|
tag?: string;
|
|
172
|
+
/** Full-text search across title/content. */
|
|
108
173
|
search?: string;
|
|
174
|
+
/** Page size; combine with `startAfter` to paginate. */
|
|
109
175
|
limit?: number;
|
|
176
|
+
/** Pagination cursor: the `id` of the last post from the previous page. */
|
|
110
177
|
startAfter?: string;
|
|
111
178
|
}
|
|
112
179
|
interface FetchPostOptions extends FetchOptions {
|
|
@@ -124,12 +191,19 @@ declare function tagsForBlogList(projectId: string): string[];
|
|
|
124
191
|
declare function tagsForBlogPost(projectId: string, slug: string): string[];
|
|
125
192
|
/**
|
|
126
193
|
* Fetch published posts for the configured project. Optional filters
|
|
127
|
-
* (category/tag/search/limit/startAfter) are forwarded to the CMS.
|
|
194
|
+
* (category/routePrefix/tag/search/limit/startAfter) are forwarded to the CMS.
|
|
195
|
+
*
|
|
196
|
+
* Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it
|
|
197
|
+
* logs a warning and returns `[]` — render an empty state instead of wrapping
|
|
198
|
+
* in try/catch.
|
|
128
199
|
*/
|
|
129
200
|
declare function fetchBlogPosts(options?: FetchPostsOptions): Promise<CMSBlogPost[]>;
|
|
130
201
|
/**
|
|
131
202
|
* Fetch a single post by slug. Returns null when not found.
|
|
132
203
|
*
|
|
204
|
+
* Never throws: CMS errors also return `null` (with a logged warning), so
|
|
205
|
+
* treat `null` as "show notFound()" rather than catching exceptions.
|
|
206
|
+
*
|
|
133
207
|
* Pass `previewToken` (minted by the CMS) to render an unpublished draft for
|
|
134
208
|
* review — that automatically bypasses the cache.
|
|
135
209
|
*/
|
|
@@ -160,4 +234,4 @@ declare function GET(request: NextRequest): Promise<Response>;
|
|
|
160
234
|
*/
|
|
161
235
|
declare function resolvePreviewToken(): Promise<string | undefined>;
|
|
162
236
|
|
|
163
|
-
export { type CMSBlogAuthor, type CMSBlogPost, type FetchOptions, type FetchPostOptions, type FetchPostsOptions, GET, fetchBlogPostBySlug, fetchBlogPosts, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
|
|
237
|
+
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*("[^"]*"|'[^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;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(/:/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&/gi, \"&\");\n}\n\n/** Drop spaces and C0 control chars (code point <= 0x20) used to break up schemes. */\nfunction stripBlankAndControl(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch.codePointAt(0)! > 0x20) out += ch;\n }\n return out;\n}\n\n/**\n * 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,QAAA;AAAA,EAAU,OAAA;AAAA,EAAS,MAAA;AAAA,EAAQ,OAAA;AAAA,EAAS,UAAA;AAAA,EAC9C,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,QAAA;AAAA,EACtD,OAAA;AAAA,EAAS,UAAA;AAAA,EAAY,OAAA;AAAA,EAAS,OAAA;AAAA,EAAS,KAAA;AAAA,EAAO,MAAA;AAAA,EAAQ,KAAA;AAAA,EACtD,UAAA;AAAA,EAAY;AACd,CAAA;AASA,IAAM,iBAAA,GACJ,qGAAA;AAEF,SAAS,cAAc,CAAA,EAAmB;AACxC,EAAA,IAAI,CAAC,OAAO,QAAA,CAAS,CAAC,KAAK,CAAA,GAAI,CAAA,IAAK,CAAA,GAAI,OAAA,EAAU,OAAO,EAAA;AACzD,EAAA,IAAI;AACF,IAAA,OAAO,MAAA,CAAO,cAAc,CAAC,CAAA;AAAA,EAC/B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAA;AAAA,EACT;AACF;AAGA,SAAS,eAAe,CAAA,EAAmB;AACzC,EAAA,OAAO,EACJ,OAAA,CAAQ,oBAAA,EAAsB,CAAC,CAAA,EAAG,MAAM,aAAA,CAAc,QAAA,CAAS,CAAA,EAAG,EAAE,CAAC,CAAC,CA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C,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\", \"object\", \"embed\", \"form\", \"input\", \"textarea\",\n \"button\", \"select\", \"option\", \"link\", \"meta\", \"base\", \"applet\",\n \"frame\", \"frameset\", \"layer\", \"style\", \"svg\", \"math\", \"xmp\",\n \"noscript\", \"template\",\n];\n\n/**\n * `iframe` is NOT in the blocklist above: blog HTML may carry a YouTube video\n * embed (BL-321). It is filtered by origin instead — an iframe pointing\n * anywhere but YouTube's embed path is deleted, element and content alike, by\n * {@link stripForeignIframes}. `<video>` needs no rule: it was never blocked\n * here, and its `src` still goes through the URL-scheme pass below.\n */\nconst YOUTUBE_EMBED_SRC =\n /^https:\\/\\/(?:www\\.)?(?:youtube-nocookie\\.com|youtube\\.com)\\/embed\\/[A-Za-z0-9_-]{6,20}(?:[?#].*)?$/;\n\nfunction safeCodePoint(n: number): string {\n if (!Number.isFinite(n) || n < 0 || n > 0x10ffff) return \"\";\n try {\n return String.fromCodePoint(n);\n } catch {\n return \"\";\n }\n}\n\n/** Decode numeric and a few named HTML entities used to obfuscate URL schemes. */\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&#x([0-9a-f]+);?/gi, (_, h) => safeCodePoint(parseInt(h, 16)))\n .replace(/&#(\\d+);?/g, (_, d) => safeCodePoint(parseInt(d, 10)))\n .replace(/:/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&/gi, \"&\");\n}\n\n/** Drop spaces and C0 control chars (code point <= 0x20) used to break up schemes. */\nfunction stripBlankAndControl(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch.codePointAt(0)! > 0x20) out += ch;\n }\n return out;\n}\n\n/**\n * Remove every `<iframe>` whose `src` is not a YouTube embed URL, taking any\n * content between the tags with it.\n */\nfunction stripForeignIframes(html: string): string {\n return html.replace(\n /<iframe\\b[^>]*>(?:[\\s\\S]*?<\\/iframe>)?/gi,\n (element) => {\n const match = /\\bsrc\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/i.exec(element);\n const raw = match ? (match[2] ?? match[3] ?? match[4] ?? \"\") : \"\";\n const src = stripBlankAndControl(decodeEntities(raw));\n return YOUTUBE_EMBED_SRC.test(src) ? element : \"\";\n },\n );\n}\n\n/**\n * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe\n * URL schemes. Returns the cleaned HTML string.\n *\n * The package's fetchers already run every post's `content` through this, so\n * call it only for CMS HTML obtained some other way (legacy exports, custom\n * endpoints).\n */\nexport function sanitizeHtml(html: string): string {\n if (!html) return \"\";\n\n let clean = html.replace(\n /<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/gi,\n \"\",\n );\n\n for (const tag of DANGEROUS_TAGS) {\n clean = clean.replace(\n new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"gi\"),\n \"\",\n );\n clean = clean.replace(new RegExp(`<${tag}\\\\b[^>]*\\\\/?>`, \"gi\"), \"\");\n }\n\n // Keep YouTube video embeds, drop every other iframe.\n clean = stripForeignIframes(clean);\n\n clean = clean.replace(\n /\\s+on\\w+\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\s+style\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\b(href|src)\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/gi,\n (match, attr, _raw, dq, sq, uq) => {\n const value = dq ?? sq ?? uq ?? \"\";\n const decoded = stripBlankAndControl(decodeEntities(value)).toLowerCase();\n if (/^(javascript|data|vbscript):/.test(decoded)) {\n return `${attr}=\"about:blank\"`;\n }\n return match;\n },\n );\n\n return clean;\n}\n","/**\n * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer\n * sites.\n *\n * Reads published blog posts from the CMS with Next.js ISR tags so the CMS\n * can purge a post (via /api/revalidate) the moment it changes, and supports\n * signed draft-preview tokens so an unpublished post can be rendered on the\n * real site for review.\n *\n * Config comes from the same env vars every consumer already sets — no\n * per-app wiring beyond importing this package:\n * VULCANTECH_CMS_URL (default https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID (required)\n * VULCANTECH_API_KEY (required)\n * VULCANTECH_BLOG_NO_CACHE (\"1\" | \"true\" → bypass ISR everywhere)\n *\n * SERVER-ONLY: relies on VULCANTECH_API_KEY (no NEXT_PUBLIC_ prefix), so it\n * must only be imported from server components / route handlers.\n *\n * Errors are graceful by design — a CMS hiccup returns [] / null and logs a\n * warning rather than throwing, so a marketing site never hard-crashes on a\n * transient CMS outage.\n *\n * Draft preview (Next.js Draft Mode):\n * - Re-export `GET` from app/api/preview/route.ts on each consumer.\n * - Call `resolvePreviewToken()` in the blog post page and pass the result\n * to fetchBlogPostBySlug as { previewToken }.\n * The public /blog/[slug] route stays static/ISR; only a request carrying\n * the Draft Mode cookie renders the unpublished draft.\n */\n\nimport { cookies, draftMode } from \"next/headers\";\nimport { NextResponse, type NextRequest } from \"next/server\";\nimport { sanitizeHtml } from \"./sanitize\";\n\nconst DEFAULT_REVALIDATE_SECONDS = 60;\n\nexport interface CMSBlogAuthor {\n uid?: string;\n name: string;\n avatar?: string;\n}\n\n/**\n * A supplementary video attached to a post, normalized by the CMS.\n *\n * Structural copy of the CMS's canonical `VideoDescriptor`\n * (`packages/blog-editor-shared/src/lib/video.ts`) — inlined rather than\n * imported so this package stays dependency-free for consumer sites. Keep the\n * shape in sync; the CMS validates every write against the original.\n *\n * `videoId` is safe to interpolate into a YouTube embed URL and `url` is always\n * on the CMS media host — the CMS pins both, so a consumer never has to\n * re-validate before rendering.\n */\nexport type CMSVideoDescriptor =\n | { provider: \"youtube\"; videoId: string }\n | { provider: \"youtube-short\"; videoId: string }\n | { provider: \"file\"; url: string; poster?: string };\n\nexport interface CMSBlogPost {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n /**\n * Sanitized HTML (TipTap editor output) — NOT markdown. Render with\n * `dangerouslySetInnerHTML`; do not run it through a markdown renderer.\n * Sanitized on write by the CMS and re-sanitized by this package's fetchers,\n * so it is safe to inject as-is.\n */\n content: string;\n /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */\n excerpt: string;\n /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */\n category?: string;\n /** URL route segment the post lives under, e.g. \"blog\" or \"documentation\". */\n routePrefix?: string;\n tags: string[];\n /**\n * Comma-separated SEO keywords the CMS derives from the post's dedicated\n * keyword fields (target keyword first). Feed straight into\n * `Metadata.keywords`; absent when the post has no keywords set.\n */\n keywords?: string;\n /** An object, not a string — display `author.name`. */\n author: CMSBlogAuthor;\n /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */\n featuredImage?: string;\n /**\n * Optional supplementary video for the post. Purely advisory — render it as a\n * hero player, a card thumbnail, or ignore it; nothing breaks when it's\n * absent, and it is absent on most posts. Videos placed *inside* the article\n * arrive as playable markup within `content` instead.\n */\n featuredVideo?: CMSVideoDescriptor;\n /** The public fetchers only ever return \"published\" posts (or a token-unlocked draft). */\n status: \"draft\" | \"in_review\" | \"published\" | \"archived\";\n /** ISO 8601 timestamp. Always present on published posts. */\n publishedAt?: string;\n /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */\n scheduledAt?: string;\n /** ISO 8601 timestamp. */\n createdAt: string;\n /** ISO 8601 timestamp. */\n updatedAt: string;\n /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */\n seoTitle?: string;\n /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */\n seoDescription?: string;\n /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */\n ogImage?: string;\n /** Defaults to \"article\" when absent (the field predates postType). */\n postType?: \"article\" | \"case-study\" | \"announcement\";\n /**\n * Spec-sheet pairs for case studies (e.g. `{ label: \"Make\", value: \"1969\n * Camaro\" }`) — the CMS only shows this editor when `postType` is\n * \"case-study\". Render as a spec table on case-study layouts; ignore\n * everywhere else.\n */\n metadata?: { label: string; value: string }[];\n}\n\nexport interface FetchOptions {\n /** Override the per-fetch revalidate window. Default: 60 seconds. */\n revalidate?: number;\n /** Extra ISR tags to attach to the fetch. */\n extraTags?: string[];\n /** Skip Next's ISR cache for this call. */\n noStore?: boolean;\n}\n\n/**\n * List filters, all applied server-side by the CMS — prefer these over\n * fetching everything and filtering client-side.\n */\nexport interface FetchPostsOptions extends FetchOptions {\n /** Exact-match on the post's `category`. */\n category?: string;\n /** Only return posts under this route prefix (e.g. \"documentation\"). */\n routePrefix?: string;\n /** Posts whose `tags` include this tag. */\n tag?: string;\n /** Full-text search across title/content. */\n search?: string;\n /** Page size; combine with `startAfter` to paginate. */\n limit?: number;\n /** Pagination cursor: the `id` of the last post from the previous page. */\n startAfter?: string;\n}\n\nexport interface FetchPostOptions extends FetchOptions {\n /**\n * A signed preview token (from the CMS) that unlocks an unpublished post.\n * When set, the cache is bypassed automatically — preview content must\n * never be cached or served to the public.\n */\n previewToken?: string;\n}\n\nfunction cmsUrl(): string {\n return process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n}\n\nfunction bypassCache(): boolean {\n return (\n process.env.VULCANTECH_BLOG_NO_CACHE === \"1\" ||\n process.env.VULCANTECH_BLOG_NO_CACHE === \"true\"\n );\n}\n\nfunction assertConfig(): { projectId: string; apiKey: string } | null {\n const projectId = process.env.VULCANTECH_PROJECT_ID;\n const apiKey = process.env.VULCANTECH_API_KEY;\n if (!projectId || !apiKey) {\n console.warn(\n \"[cms/blog] CMS not configured — set VULCANTECH_PROJECT_ID and VULCANTECH_API_KEY\",\n );\n return null;\n }\n return { projectId, apiKey };\n}\n\nexport { sanitizeHtml };\n\n/** Sanitize a post's HTML body so every consumer render is safe by default. */\nfunction sanitizePost(post: CMSBlogPost): CMSBlogPost {\n if (post && typeof post.content === \"string\") {\n return { ...post, content: sanitizeHtml(post.content) };\n }\n return post;\n}\n\n/** ISR tag for a project's blog list. */\nexport function tagsForBlogList(projectId: string): string[] {\n return [`blog:${projectId}`];\n}\n\n/** ISR tags for a single post (post-specific + project-wide). */\nexport function tagsForBlogPost(projectId: string, slug: string): string[] {\n return [`blog:${projectId}:${slug}`, `blog:${projectId}`];\n}\n\nfunction buildInit(\n tags: string[],\n options: FetchOptions,\n): RequestInit & { next?: { revalidate?: number; tags?: string[] } } {\n const skipCache = options.noStore || bypassCache();\n if (skipCache) return { cache: \"no-store\" };\n return {\n next: {\n revalidate: options.revalidate ?? DEFAULT_REVALIDATE_SECONDS,\n tags: [...tags, ...(options.extraTags ?? [])],\n },\n };\n}\n\n/**\n * Fetch published posts for the configured project. Optional filters\n * (category/routePrefix/tag/search/limit/startAfter) are forwarded to the CMS.\n *\n * Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it\n * logs a warning and returns `[]` — render an empty state instead of wrapping\n * in try/catch.\n */\nexport async function fetchBlogPosts(\n options: FetchPostsOptions = {},\n): Promise<CMSBlogPost[]> {\n const config = assertConfig();\n if (!config) return [];\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey, status: \"published\" });\n if (options.category) params.set(\"category\", options.category);\n if (options.routePrefix) params.set(\"routePrefix\", options.routePrefix);\n if (options.tag) params.set(\"tag\", options.tag);\n if (options.search) params.set(\"search\", options.search);\n if (options.limit) params.set(\"limit\", String(options.limit));\n if (options.startAfter) params.set(\"startAfter\", options.startAfter);\n\n const url = `${cmsUrl()}/api/blog?${params.toString()}`;\n const init = buildInit(tagsForBlogList(projectId), options);\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\"[cms/blog] CMS unreachable:\", (err as Error).message);\n return [];\n }\n if (res.status === 404) {\n console.warn(\"[cms/blog] /api/blog returned 404 — CMS may need redeployment\");\n return [];\n }\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog returned ${res.status}`);\n return [];\n }\n\n const json = (await res.json()) as { posts: CMSBlogPost[] };\n return (json.posts ?? []).map(sanitizePost);\n}\n\n/**\n * Fetch a single post by slug. Returns null when not found.\n *\n * Never throws: CMS errors also return `null` (with a logged warning), so\n * treat `null` as \"show notFound()\" rather than catching exceptions.\n *\n * Pass `previewToken` (minted by the CMS) to render an unpublished draft for\n * review — that automatically bypasses the cache.\n */\nexport async function fetchBlogPostBySlug(\n slug: string,\n options: FetchPostOptions = {},\n): Promise<CMSBlogPost | null> {\n const config = assertConfig();\n if (!config) return null;\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey });\n if (options.previewToken) params.set(\"preview\", options.previewToken);\n\n const url = `${cmsUrl()}/api/blog/${encodeURIComponent(slug)}?${params.toString()}`;\n // Preview responses must never be cached.\n const init = buildInit(tagsForBlogPost(projectId, slug), {\n ...options,\n noStore: options.noStore || !!options.previewToken,\n });\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\n `[cms/blog] CMS unreachable for \"${slug}\":`,\n (err as Error).message,\n );\n return null;\n }\n if (res.status === 404) return null;\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);\n return null;\n }\n\n const json = (await res.json()) as { post: CMSBlogPost };\n return json.post ? sanitizePost(json.post) : null;\n}\n\n/* ─── Draft preview (Next.js Draft Mode) ─── */\n\nconst PREVIEW_COOKIE = \"vt_preview_token\";\nconst PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60; // 2 hours\n\n/**\n * Route handler for `/api/preview?token=…&slug=…`.\n *\n * Validates the token against the CMS, enables Next Draft Mode, stores the\n * token in an httpOnly cookie, and redirects to the post — which then renders\n * the draft (see resolvePreviewToken). On an invalid/expired token it just\n * redirects to the public page (which 404s if the post isn't published).\n *\n * Each consumer wires it up with one line:\n * // app/api/preview/route.ts\n * export { GET } from \"@vulcantech/blog\";\n */\nexport async function GET(request: NextRequest): Promise<Response> {\n const { searchParams } = new URL(request.url);\n const token = searchParams.get(\"token\");\n const slug = searchParams.get(\"slug\");\n\n if (!token || !slug) {\n return NextResponse.json(\n { error: \"token and slug are required\" },\n { status: 400 },\n );\n }\n\n const target = new URL(`/blog/${encodeURIComponent(slug)}`, request.url);\n\n // Validate by asking the CMS to resolve the draft with this token.\n const post = await fetchBlogPostBySlug(slug, { previewToken: token });\n if (!post) {\n return NextResponse.redirect(target);\n }\n\n (await draftMode()).enable();\n (await cookies()).set(PREVIEW_COOKIE, token, {\n httpOnly: true,\n sameSite: \"lax\",\n secure: process.env.NODE_ENV === \"production\",\n path: \"/\",\n maxAge: PREVIEW_MAX_AGE_SECONDS,\n });\n\n return NextResponse.redirect(target);\n}\n\n/**\n * Page helper: returns the active preview token when Draft Mode is on, else\n * undefined. Call it in the blog post server component and spread the result\n * into the fetch:\n *\n * const previewToken = await resolvePreviewToken();\n * const post = await fetchBlogPostBySlug(slug, { previewToken });\n *\n * Reading the cookie only happens when Draft Mode is enabled, so the public\n * route stays statically rendered for normal visitors.\n */\nexport async function resolvePreviewToken(): Promise<string | undefined> {\n const { isEnabled } = await draftMode();\n if (!isEnabled) return undefined;\n const store = await cookies();\n return store.get(PREVIEW_COOKIE)?.value;\n}\n"]}
|
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
|
""
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sanitize.ts","../src/index.ts"],"names":[],"mappings":";;;;;;AAiBA,IAAM,cAAA,GAAiB;AAAA,EACrB,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,OAAA;AAAA,EAAS,MAAA;AAAA,EAAQ,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Tap) 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(/:/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&/gi, \"&\");\n}\n\n/** Drop spaces and C0 control chars (code point <= 0x20) used to break up schemes. */\nfunction stripBlankAndControl(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch.codePointAt(0)! > 0x20) out += ch;\n }\n return out;\n}\n\n/**\n * 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,I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M,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(/:/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&/gi, \"&\");\n}\n\n/** Drop spaces and C0 control chars (code point <= 0x20) used to break up schemes. */\nfunction stripBlankAndControl(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch.codePointAt(0)! > 0x20) out += ch;\n }\n return out;\n}\n\n/**\n * Remove every `<iframe>` whose `src` is not a YouTube embed URL, taking any\n * content between the tags with it.\n */\nfunction stripForeignIframes(html: string): string {\n return html.replace(\n /<iframe\\b[^>]*>(?:[\\s\\S]*?<\\/iframe>)?/gi,\n (element) => {\n const match = /\\bsrc\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/i.exec(element);\n const raw = match ? (match[2] ?? match[3] ?? match[4] ?? \"\") : \"\";\n const src = stripBlankAndControl(decodeEntities(raw));\n return YOUTUBE_EMBED_SRC.test(src) ? element : \"\";\n },\n );\n}\n\n/**\n * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe\n * URL schemes. Returns the cleaned HTML string.\n *\n * The package's fetchers already run every post's `content` through this, so\n * call it only for CMS HTML obtained some other way (legacy exports, custom\n * endpoints).\n */\nexport function sanitizeHtml(html: string): string {\n if (!html) return \"\";\n\n let clean = html.replace(\n /<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/gi,\n \"\",\n );\n\n for (const tag of DANGEROUS_TAGS) {\n clean = clean.replace(\n new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"gi\"),\n \"\",\n );\n clean = clean.replace(new RegExp(`<${tag}\\\\b[^>]*\\\\/?>`, \"gi\"), \"\");\n }\n\n // Keep YouTube video embeds, drop every other iframe.\n clean = stripForeignIframes(clean);\n\n clean = clean.replace(\n /\\s+on\\w+\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\s+style\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\b(href|src)\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/gi,\n (match, attr, _raw, dq, sq, uq) => {\n const value = dq ?? sq ?? uq ?? \"\";\n const decoded = stripBlankAndControl(decodeEntities(value)).toLowerCase();\n if (/^(javascript|data|vbscript):/.test(decoded)) {\n return `${attr}=\"about:blank\"`;\n }\n return match;\n },\n );\n\n return clean;\n}\n","/**\n * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer\n * sites.\n *\n * Reads published blog posts from the CMS with Next.js ISR tags so the CMS\n * can purge a post (via /api/revalidate) the moment it changes, and supports\n * signed draft-preview tokens so an unpublished post can be rendered on the\n * real site for review.\n *\n * Config comes from the same env vars every consumer already sets — no\n * per-app wiring beyond importing this package:\n * VULCANTECH_CMS_URL (default https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID (required)\n * VULCANTECH_API_KEY (required)\n * VULCANTECH_BLOG_NO_CACHE (\"1\" | \"true\" → bypass ISR everywhere)\n *\n * SERVER-ONLY: relies on VULCANTECH_API_KEY (no NEXT_PUBLIC_ prefix), so it\n * must only be imported from server components / route handlers.\n *\n * Errors are graceful by design — a CMS hiccup returns [] / null and logs a\n * warning rather than throwing, so a marketing site never hard-crashes on a\n * transient CMS outage.\n *\n * Draft preview (Next.js Draft Mode):\n * - Re-export `GET` from app/api/preview/route.ts on each consumer.\n * - Call `resolvePreviewToken()` in the blog post page and pass the result\n * to fetchBlogPostBySlug as { previewToken }.\n * The public /blog/[slug] route stays static/ISR; only a request carrying\n * the Draft Mode cookie renders the unpublished draft.\n */\n\nimport { cookies, draftMode } from \"next/headers\";\nimport { NextResponse, type NextRequest } from \"next/server\";\nimport { sanitizeHtml } from \"./sanitize\";\n\nconst DEFAULT_REVALIDATE_SECONDS = 60;\n\nexport interface CMSBlogAuthor {\n uid?: string;\n name: string;\n avatar?: string;\n}\n\n/**\n * A supplementary video attached to a post, normalized by the CMS.\n *\n * Structural copy of the CMS's canonical `VideoDescriptor`\n * (`packages/blog-editor-shared/src/lib/video.ts`) — inlined rather than\n * imported so this package stays dependency-free for consumer sites. Keep the\n * shape in sync; the CMS validates every write against the original.\n *\n * `videoId` is safe to interpolate into a YouTube embed URL and `url` is always\n * on the CMS media host — the CMS pins both, so a consumer never has to\n * re-validate before rendering.\n */\nexport type CMSVideoDescriptor =\n | { provider: \"youtube\"; videoId: string }\n | { provider: \"youtube-short\"; videoId: string }\n | { provider: \"file\"; url: string; poster?: string };\n\nexport interface CMSBlogPost {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n /**\n * Sanitized HTML (TipTap editor output) — NOT markdown. Render with\n * `dangerouslySetInnerHTML`; do not run it through a markdown renderer.\n * Sanitized on write by the CMS and re-sanitized by this package's fetchers,\n * so it is safe to inject as-is.\n */\n content: string;\n /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */\n excerpt: string;\n /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */\n category?: string;\n /** URL route segment the post lives under, e.g. \"blog\" or \"documentation\". */\n routePrefix?: string;\n tags: string[];\n /**\n * Comma-separated SEO keywords the CMS derives from the post's dedicated\n * keyword fields (target keyword first). Feed straight into\n * `Metadata.keywords`; absent when the post has no keywords set.\n */\n keywords?: string;\n /** An object, not a string — display `author.name`. */\n author: CMSBlogAuthor;\n /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */\n featuredImage?: string;\n /**\n * Optional supplementary video for the post. Purely advisory — render it as a\n * hero player, a card thumbnail, or ignore it; nothing breaks when it's\n * absent, and it is absent on most posts. Videos placed *inside* the article\n * arrive as playable markup within `content` instead.\n */\n featuredVideo?: CMSVideoDescriptor;\n /** The public fetchers only ever return \"published\" posts (or a token-unlocked draft). */\n status: \"draft\" | \"in_review\" | \"published\" | \"archived\";\n /** ISO 8601 timestamp. Always present on published posts. */\n publishedAt?: string;\n /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */\n scheduledAt?: string;\n /** ISO 8601 timestamp. */\n createdAt: string;\n /** ISO 8601 timestamp. */\n updatedAt: string;\n /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */\n seoTitle?: string;\n /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */\n seoDescription?: string;\n /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */\n ogImage?: string;\n /** Defaults to \"article\" when absent (the field predates postType). */\n postType?: \"article\" | \"case-study\" | \"announcement\";\n /**\n * Spec-sheet pairs for case studies (e.g. `{ label: \"Make\", value: \"1969\n * Camaro\" }`) — the CMS only shows this editor when `postType` is\n * \"case-study\". Render as a spec table on case-study layouts; ignore\n * everywhere else.\n */\n metadata?: { label: string; value: string }[];\n}\n\nexport interface FetchOptions {\n /** Override the per-fetch revalidate window. Default: 60 seconds. */\n revalidate?: number;\n /** Extra ISR tags to attach to the fetch. */\n extraTags?: string[];\n /** Skip Next's ISR cache for this call. */\n noStore?: boolean;\n}\n\n/**\n * List filters, all applied server-side by the CMS — prefer these over\n * fetching everything and filtering client-side.\n */\nexport interface FetchPostsOptions extends FetchOptions {\n /** Exact-match on the post's `category`. */\n category?: string;\n /** Only return posts under this route prefix (e.g. \"documentation\"). */\n routePrefix?: string;\n /** Posts whose `tags` include this tag. */\n tag?: string;\n /** Full-text search across title/content. */\n search?: string;\n /** Page size; combine with `startAfter` to paginate. */\n limit?: number;\n /** Pagination cursor: the `id` of the last post from the previous page. */\n startAfter?: string;\n}\n\nexport interface FetchPostOptions extends FetchOptions {\n /**\n * A signed preview token (from the CMS) that unlocks an unpublished post.\n * When set, the cache is bypassed automatically — preview content must\n * never be cached or served to the public.\n */\n previewToken?: string;\n}\n\nfunction cmsUrl(): string {\n return process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n}\n\nfunction bypassCache(): boolean {\n return (\n process.env.VULCANTECH_BLOG_NO_CACHE === \"1\" ||\n process.env.VULCANTECH_BLOG_NO_CACHE === \"true\"\n );\n}\n\nfunction assertConfig(): { projectId: string; apiKey: string } | null {\n const projectId = process.env.VULCANTECH_PROJECT_ID;\n const apiKey = process.env.VULCANTECH_API_KEY;\n if (!projectId || !apiKey) {\n console.warn(\n \"[cms/blog] CMS not configured — set VULCANTECH_PROJECT_ID and VULCANTECH_API_KEY\",\n );\n return null;\n }\n return { projectId, apiKey };\n}\n\nexport { sanitizeHtml };\n\n/** Sanitize a post's HTML body so every consumer render is safe by default. */\nfunction sanitizePost(post: CMSBlogPost): CMSBlogPost {\n if (post && typeof post.content === \"string\") {\n return { ...post, content: sanitizeHtml(post.content) };\n }\n return post;\n}\n\n/** ISR tag for a project's blog list. */\nexport function tagsForBlogList(projectId: string): string[] {\n return [`blog:${projectId}`];\n}\n\n/** ISR tags for a single post (post-specific + project-wide). */\nexport function tagsForBlogPost(projectId: string, slug: string): string[] {\n return [`blog:${projectId}:${slug}`, `blog:${projectId}`];\n}\n\nfunction buildInit(\n tags: string[],\n options: FetchOptions,\n): RequestInit & { next?: { revalidate?: number; tags?: string[] } } {\n const skipCache = options.noStore || bypassCache();\n if (skipCache) return { cache: \"no-store\" };\n return {\n next: {\n revalidate: options.revalidate ?? DEFAULT_REVALIDATE_SECONDS,\n tags: [...tags, ...(options.extraTags ?? [])],\n },\n };\n}\n\n/**\n * Fetch published posts for the configured project. Optional filters\n * (category/routePrefix/tag/search/limit/startAfter) are forwarded to the CMS.\n *\n * Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it\n * logs a warning and returns `[]` — render an empty state instead of wrapping\n * in try/catch.\n */\nexport async function fetchBlogPosts(\n options: FetchPostsOptions = {},\n): Promise<CMSBlogPost[]> {\n const config = assertConfig();\n if (!config) return [];\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey, status: \"published\" });\n if (options.category) params.set(\"category\", options.category);\n if (options.routePrefix) params.set(\"routePrefix\", options.routePrefix);\n if (options.tag) params.set(\"tag\", options.tag);\n if (options.search) params.set(\"search\", options.search);\n if (options.limit) params.set(\"limit\", String(options.limit));\n if (options.startAfter) params.set(\"startAfter\", options.startAfter);\n\n const url = `${cmsUrl()}/api/blog?${params.toString()}`;\n const init = buildInit(tagsForBlogList(projectId), options);\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\"[cms/blog] CMS unreachable:\", (err as Error).message);\n return [];\n }\n if (res.status === 404) {\n console.warn(\"[cms/blog] /api/blog returned 404 — CMS may need redeployment\");\n return [];\n }\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog returned ${res.status}`);\n return [];\n }\n\n const json = (await res.json()) as { posts: CMSBlogPost[] };\n return (json.posts ?? []).map(sanitizePost);\n}\n\n/**\n * Fetch a single post by slug. Returns null when not found.\n *\n * Never throws: CMS errors also return `null` (with a logged warning), so\n * treat `null` as \"show notFound()\" rather than catching exceptions.\n *\n * Pass `previewToken` (minted by the CMS) to render an unpublished draft for\n * review — that automatically bypasses the cache.\n */\nexport async function fetchBlogPostBySlug(\n slug: string,\n options: FetchPostOptions = {},\n): Promise<CMSBlogPost | null> {\n const config = assertConfig();\n if (!config) return null;\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey });\n if (options.previewToken) params.set(\"preview\", options.previewToken);\n\n const url = `${cmsUrl()}/api/blog/${encodeURIComponent(slug)}?${params.toString()}`;\n // Preview responses must never be cached.\n const init = buildInit(tagsForBlogPost(projectId, slug), {\n ...options,\n noStore: options.noStore || !!options.previewToken,\n });\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\n `[cms/blog] CMS unreachable for \"${slug}\":`,\n (err as Error).message,\n );\n return null;\n }\n if (res.status === 404) return null;\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);\n return null;\n }\n\n const json = (await res.json()) as { post: CMSBlogPost };\n return json.post ? sanitizePost(json.post) : null;\n}\n\n/* ─── Draft preview (Next.js Draft Mode) ─── */\n\nconst PREVIEW_COOKIE = \"vt_preview_token\";\nconst PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60; // 2 hours\n\n/**\n * Route handler for `/api/preview?token=…&slug=…`.\n *\n * Validates the token against the CMS, enables Next Draft Mode, stores the\n * token in an httpOnly cookie, and redirects to the post — which then renders\n * the draft (see resolvePreviewToken). On an invalid/expired token it just\n * redirects to the public page (which 404s if the post isn't published).\n *\n * Each consumer wires it up with one line:\n * // app/api/preview/route.ts\n * export { GET } from \"@vulcantech/blog\";\n */\nexport async function GET(request: NextRequest): Promise<Response> {\n const { searchParams } = new URL(request.url);\n const token = searchParams.get(\"token\");\n const slug = searchParams.get(\"slug\");\n\n if (!token || !slug) {\n return NextResponse.json(\n { error: \"token and slug are required\" },\n { status: 400 },\n );\n }\n\n const target = new URL(`/blog/${encodeURIComponent(slug)}`, request.url);\n\n // Validate by asking the CMS to resolve the draft with this token.\n const post = await fetchBlogPostBySlug(slug, { previewToken: token });\n if (!post) {\n return NextResponse.redirect(target);\n }\n\n (await draftMode()).enable();\n (await cookies()).set(PREVIEW_COOKIE, token, {\n httpOnly: true,\n sameSite: \"lax\",\n secure: process.env.NODE_ENV === \"production\",\n path: \"/\",\n maxAge: PREVIEW_MAX_AGE_SECONDS,\n });\n\n return NextResponse.redirect(target);\n}\n\n/**\n * Page helper: returns the active preview token when Draft Mode is on, else\n * undefined. Call it in the blog post server component and spread the result\n * into the fetch:\n *\n * const previewToken = await resolvePreviewToken();\n * const post = await fetchBlogPostBySlug(slug, { previewToken });\n *\n * Reading the cookie only happens when Draft Mode is enabled, so the public\n * route stays statically rendered for normal visitors.\n */\nexport async function resolvePreviewToken(): Promise<string | undefined> {\n const { isEnabled } = await draftMode();\n if (!isEnabled) return undefined;\n const store = await cookies();\n return store.get(PREVIEW_COOKIE)?.value;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vulcantech/blog",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
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",
|
|
@@ -30,7 +30,7 @@
|
|
|
30
30
|
"next": ">=14.0.0"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
|
-
"next": "16.
|
|
33
|
+
"next": "16.3.1",
|
|
34
34
|
"tsup": "^8.0.0",
|
|
35
35
|
"typescript": "^5.9.3"
|
|
36
36
|
},
|
package/src/index.ts
CHANGED
|
@@ -41,14 +41,38 @@ 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
|
-
/**
|
|
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
|
+
*/
|
|
50
72
|
content: string;
|
|
73
|
+
/** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */
|
|
51
74
|
excerpt: string;
|
|
75
|
+
/** Single editorial bucket (one per post) — distinct from the free-form `tags`. */
|
|
52
76
|
category?: string;
|
|
53
77
|
/** URL route segment the post lives under, e.g. "blog" or "documentation". */
|
|
54
78
|
routePrefix?: string;
|
|
@@ -59,17 +83,41 @@ export interface CMSBlogPost {
|
|
|
59
83
|
* `Metadata.keywords`; absent when the post has no keywords set.
|
|
60
84
|
*/
|
|
61
85
|
keywords?: string;
|
|
86
|
+
/** An object, not a string — display `author.name`. */
|
|
62
87
|
author: CMSBlogAuthor;
|
|
88
|
+
/** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */
|
|
63
89
|
featuredImage?: string;
|
|
90
|
+
/**
|
|
91
|
+
* Optional supplementary video for the post. Purely advisory — render it as a
|
|
92
|
+
* hero player, a card thumbnail, or ignore it; nothing breaks when it's
|
|
93
|
+
* absent, and it is absent on most posts. Videos placed *inside* the article
|
|
94
|
+
* arrive as playable markup within `content` instead.
|
|
95
|
+
*/
|
|
96
|
+
featuredVideo?: CMSVideoDescriptor;
|
|
97
|
+
/** The public fetchers only ever return "published" posts (or a token-unlocked draft). */
|
|
64
98
|
status: "draft" | "in_review" | "published" | "archived";
|
|
99
|
+
/** ISO 8601 timestamp. Always present on published posts. */
|
|
65
100
|
publishedAt?: string;
|
|
101
|
+
/** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */
|
|
66
102
|
scheduledAt?: string;
|
|
103
|
+
/** ISO 8601 timestamp. */
|
|
67
104
|
createdAt: string;
|
|
105
|
+
/** ISO 8601 timestamp. */
|
|
68
106
|
updatedAt: string;
|
|
107
|
+
/** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */
|
|
69
108
|
seoTitle?: string;
|
|
109
|
+
/** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */
|
|
70
110
|
seoDescription?: string;
|
|
111
|
+
/** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */
|
|
71
112
|
ogImage?: string;
|
|
113
|
+
/** Defaults to "article" when absent (the field predates postType). */
|
|
72
114
|
postType?: "article" | "case-study" | "announcement";
|
|
115
|
+
/**
|
|
116
|
+
* Spec-sheet pairs for case studies (e.g. `{ label: "Make", value: "1969
|
|
117
|
+
* Camaro" }`) — the CMS only shows this editor when `postType` is
|
|
118
|
+
* "case-study". Render as a spec table on case-study layouts; ignore
|
|
119
|
+
* everywhere else.
|
|
120
|
+
*/
|
|
73
121
|
metadata?: { label: string; value: string }[];
|
|
74
122
|
}
|
|
75
123
|
|
|
@@ -82,13 +130,22 @@ export interface FetchOptions {
|
|
|
82
130
|
noStore?: boolean;
|
|
83
131
|
}
|
|
84
132
|
|
|
133
|
+
/**
|
|
134
|
+
* List filters, all applied server-side by the CMS — prefer these over
|
|
135
|
+
* fetching everything and filtering client-side.
|
|
136
|
+
*/
|
|
85
137
|
export interface FetchPostsOptions extends FetchOptions {
|
|
138
|
+
/** Exact-match on the post's `category`. */
|
|
86
139
|
category?: string;
|
|
87
140
|
/** Only return posts under this route prefix (e.g. "documentation"). */
|
|
88
141
|
routePrefix?: string;
|
|
142
|
+
/** Posts whose `tags` include this tag. */
|
|
89
143
|
tag?: string;
|
|
144
|
+
/** Full-text search across title/content. */
|
|
90
145
|
search?: string;
|
|
146
|
+
/** Page size; combine with `startAfter` to paginate. */
|
|
91
147
|
limit?: number;
|
|
148
|
+
/** Pagination cursor: the `id` of the last post from the previous page. */
|
|
92
149
|
startAfter?: string;
|
|
93
150
|
}
|
|
94
151
|
|
|
@@ -160,7 +217,11 @@ function buildInit(
|
|
|
160
217
|
|
|
161
218
|
/**
|
|
162
219
|
* Fetch published posts for the configured project. Optional filters
|
|
163
|
-
* (category/tag/search/limit/startAfter) are forwarded to the CMS.
|
|
220
|
+
* (category/routePrefix/tag/search/limit/startAfter) are forwarded to the CMS.
|
|
221
|
+
*
|
|
222
|
+
* Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it
|
|
223
|
+
* logs a warning and returns `[]` — render an empty state instead of wrapping
|
|
224
|
+
* in try/catch.
|
|
164
225
|
*/
|
|
165
226
|
export async function fetchBlogPosts(
|
|
166
227
|
options: FetchPostsOptions = {},
|
|
@@ -203,6 +264,9 @@ export async function fetchBlogPosts(
|
|
|
203
264
|
/**
|
|
204
265
|
* Fetch a single post by slug. Returns null when not found.
|
|
205
266
|
*
|
|
267
|
+
* Never throws: CMS errors also return `null` (with a logged warning), so
|
|
268
|
+
* treat `null` as "show notFound()" rather than catching exceptions.
|
|
269
|
+
*
|
|
206
270
|
* Pass `previewToken` (minted by the CMS) to render an unpublished draft for
|
|
207
271
|
* review — that automatically bypasses the cache.
|
|
208
272
|
*/
|
package/src/sanitize.ts
CHANGED
|
@@ -16,12 +16,22 @@
|
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
18
|
const DANGEROUS_TAGS = [
|
|
19
|
-
"script", "
|
|
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
|
"",
|