@vulcantech/blog 0.1.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/src/index.ts ADDED
@@ -0,0 +1,312 @@
1
+ /**
2
+ * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer
3
+ * sites.
4
+ *
5
+ * Reads published blog posts from the CMS with Next.js ISR tags so the CMS
6
+ * can purge a post (via /api/revalidate) the moment it changes, and supports
7
+ * signed draft-preview tokens so an unpublished post can be rendered on the
8
+ * real site for review.
9
+ *
10
+ * Config comes from the same env vars every consumer already sets — no
11
+ * per-app wiring beyond importing this package:
12
+ * VULCANTECH_CMS_URL (default https://cms.vulcantech.io)
13
+ * VULCANTECH_PROJECT_ID (required)
14
+ * VULCANTECH_API_KEY (required)
15
+ * VULCANTECH_BLOG_NO_CACHE ("1" | "true" → bypass ISR everywhere)
16
+ *
17
+ * SERVER-ONLY: relies on VULCANTECH_API_KEY (no NEXT_PUBLIC_ prefix), so it
18
+ * must only be imported from server components / route handlers.
19
+ *
20
+ * Errors are graceful by design — a CMS hiccup returns [] / null and logs a
21
+ * warning rather than throwing, so a marketing site never hard-crashes on a
22
+ * transient CMS outage.
23
+ *
24
+ * Draft preview (Next.js Draft Mode):
25
+ * - Re-export `GET` from app/api/preview/route.ts on each consumer.
26
+ * - Call `resolvePreviewToken()` in the blog post page and pass the result
27
+ * to fetchBlogPostBySlug as { previewToken }.
28
+ * The public /blog/[slug] route stays static/ISR; only a request carrying
29
+ * the Draft Mode cookie renders the unpublished draft.
30
+ */
31
+
32
+ import { cookies, draftMode } from "next/headers";
33
+ import { NextResponse, type NextRequest } from "next/server";
34
+ import { sanitizeHtml } from "./sanitize";
35
+
36
+ const DEFAULT_REVALIDATE_SECONDS = 60;
37
+
38
+ export interface CMSBlogAuthor {
39
+ uid?: string;
40
+ name: string;
41
+ avatar?: string;
42
+ }
43
+
44
+ export interface CMSBlogPost {
45
+ id: string;
46
+ projectId: string;
47
+ title: string;
48
+ slug: string;
49
+ /** HTML content (TipTap output). */
50
+ content: string;
51
+ excerpt: string;
52
+ category?: string;
53
+ /** URL route segment the post lives under, e.g. "blog" or "documentation". */
54
+ routePrefix?: string;
55
+ tags: string[];
56
+ /**
57
+ * Comma-separated SEO keywords the CMS derives from the post's dedicated
58
+ * keyword fields (target keyword first). Feed straight into
59
+ * `Metadata.keywords`; absent when the post has no keywords set.
60
+ */
61
+ keywords?: string;
62
+ author: CMSBlogAuthor;
63
+ featuredImage?: string;
64
+ status: "draft" | "in_review" | "published" | "archived";
65
+ publishedAt?: string;
66
+ scheduledAt?: string;
67
+ createdAt: string;
68
+ updatedAt: string;
69
+ seoTitle?: string;
70
+ seoDescription?: string;
71
+ ogImage?: string;
72
+ postType?: "article" | "case-study" | "announcement";
73
+ metadata?: { label: string; value: string }[];
74
+ }
75
+
76
+ export interface FetchOptions {
77
+ /** Override the per-fetch revalidate window. Default: 60 seconds. */
78
+ revalidate?: number;
79
+ /** Extra ISR tags to attach to the fetch. */
80
+ extraTags?: string[];
81
+ /** Skip Next's ISR cache for this call. */
82
+ noStore?: boolean;
83
+ }
84
+
85
+ export interface FetchPostsOptions extends FetchOptions {
86
+ category?: string;
87
+ /** Only return posts under this route prefix (e.g. "documentation"). */
88
+ routePrefix?: string;
89
+ tag?: string;
90
+ search?: string;
91
+ limit?: number;
92
+ startAfter?: string;
93
+ }
94
+
95
+ export interface FetchPostOptions extends FetchOptions {
96
+ /**
97
+ * A signed preview token (from the CMS) that unlocks an unpublished post.
98
+ * When set, the cache is bypassed automatically — preview content must
99
+ * never be cached or served to the public.
100
+ */
101
+ previewToken?: string;
102
+ }
103
+
104
+ function cmsUrl(): string {
105
+ return process.env.VULCANTECH_CMS_URL || "https://cms.vulcantech.io";
106
+ }
107
+
108
+ function bypassCache(): boolean {
109
+ return (
110
+ process.env.VULCANTECH_BLOG_NO_CACHE === "1" ||
111
+ process.env.VULCANTECH_BLOG_NO_CACHE === "true"
112
+ );
113
+ }
114
+
115
+ function assertConfig(): { projectId: string; apiKey: string } | null {
116
+ const projectId = process.env.VULCANTECH_PROJECT_ID;
117
+ const apiKey = process.env.VULCANTECH_API_KEY;
118
+ if (!projectId || !apiKey) {
119
+ console.warn(
120
+ "[cms/blog] CMS not configured — set VULCANTECH_PROJECT_ID and VULCANTECH_API_KEY",
121
+ );
122
+ return null;
123
+ }
124
+ return { projectId, apiKey };
125
+ }
126
+
127
+ export { sanitizeHtml };
128
+
129
+ /** Sanitize a post's HTML body so every consumer render is safe by default. */
130
+ function sanitizePost(post: CMSBlogPost): CMSBlogPost {
131
+ if (post && typeof post.content === "string") {
132
+ return { ...post, content: sanitizeHtml(post.content) };
133
+ }
134
+ return post;
135
+ }
136
+
137
+ /** ISR tag for a project's blog list. */
138
+ export function tagsForBlogList(projectId: string): string[] {
139
+ return [`blog:${projectId}`];
140
+ }
141
+
142
+ /** ISR tags for a single post (post-specific + project-wide). */
143
+ export function tagsForBlogPost(projectId: string, slug: string): string[] {
144
+ return [`blog:${projectId}:${slug}`, `blog:${projectId}`];
145
+ }
146
+
147
+ function buildInit(
148
+ tags: string[],
149
+ options: FetchOptions,
150
+ ): RequestInit & { next?: { revalidate?: number; tags?: string[] } } {
151
+ const skipCache = options.noStore || bypassCache();
152
+ if (skipCache) return { cache: "no-store" };
153
+ return {
154
+ next: {
155
+ revalidate: options.revalidate ?? DEFAULT_REVALIDATE_SECONDS,
156
+ tags: [...tags, ...(options.extraTags ?? [])],
157
+ },
158
+ };
159
+ }
160
+
161
+ /**
162
+ * Fetch published posts for the configured project. Optional filters
163
+ * (category/tag/search/limit/startAfter) are forwarded to the CMS.
164
+ */
165
+ export async function fetchBlogPosts(
166
+ options: FetchPostsOptions = {},
167
+ ): Promise<CMSBlogPost[]> {
168
+ const config = assertConfig();
169
+ if (!config) return [];
170
+ const { projectId, apiKey } = config;
171
+
172
+ const params = new URLSearchParams({ projectId, apiKey, status: "published" });
173
+ if (options.category) params.set("category", options.category);
174
+ if (options.routePrefix) params.set("routePrefix", options.routePrefix);
175
+ if (options.tag) params.set("tag", options.tag);
176
+ if (options.search) params.set("search", options.search);
177
+ if (options.limit) params.set("limit", String(options.limit));
178
+ if (options.startAfter) params.set("startAfter", options.startAfter);
179
+
180
+ const url = `${cmsUrl()}/api/blog?${params.toString()}`;
181
+ const init = buildInit(tagsForBlogList(projectId), options);
182
+
183
+ let res: Response;
184
+ try {
185
+ res = await fetch(url, init);
186
+ } catch (err) {
187
+ console.warn("[cms/blog] CMS unreachable:", (err as Error).message);
188
+ return [];
189
+ }
190
+ if (res.status === 404) {
191
+ console.warn("[cms/blog] /api/blog returned 404 — CMS may need redeployment");
192
+ return [];
193
+ }
194
+ if (!res.ok) {
195
+ console.warn(`[cms/blog] /api/blog returned ${res.status}`);
196
+ return [];
197
+ }
198
+
199
+ const json = (await res.json()) as { posts: CMSBlogPost[] };
200
+ return (json.posts ?? []).map(sanitizePost);
201
+ }
202
+
203
+ /**
204
+ * Fetch a single post by slug. Returns null when not found.
205
+ *
206
+ * Pass `previewToken` (minted by the CMS) to render an unpublished draft for
207
+ * review — that automatically bypasses the cache.
208
+ */
209
+ export async function fetchBlogPostBySlug(
210
+ slug: string,
211
+ options: FetchPostOptions = {},
212
+ ): Promise<CMSBlogPost | null> {
213
+ const config = assertConfig();
214
+ if (!config) return null;
215
+ const { projectId, apiKey } = config;
216
+
217
+ const params = new URLSearchParams({ projectId, apiKey });
218
+ if (options.previewToken) params.set("preview", options.previewToken);
219
+
220
+ const url = `${cmsUrl()}/api/blog/${encodeURIComponent(slug)}?${params.toString()}`;
221
+ // Preview responses must never be cached.
222
+ const init = buildInit(tagsForBlogPost(projectId, slug), {
223
+ ...options,
224
+ noStore: options.noStore || !!options.previewToken,
225
+ });
226
+
227
+ let res: Response;
228
+ try {
229
+ res = await fetch(url, init);
230
+ } catch (err) {
231
+ console.warn(
232
+ `[cms/blog] CMS unreachable for "${slug}":`,
233
+ (err as Error).message,
234
+ );
235
+ return null;
236
+ }
237
+ if (res.status === 404) return null;
238
+ if (!res.ok) {
239
+ console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);
240
+ return null;
241
+ }
242
+
243
+ const json = (await res.json()) as { post: CMSBlogPost };
244
+ return json.post ? sanitizePost(json.post) : null;
245
+ }
246
+
247
+ /* ─── Draft preview (Next.js Draft Mode) ─── */
248
+
249
+ const PREVIEW_COOKIE = "vt_preview_token";
250
+ const PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60; // 2 hours
251
+
252
+ /**
253
+ * Route handler for `/api/preview?token=…&slug=…`.
254
+ *
255
+ * Validates the token against the CMS, enables Next Draft Mode, stores the
256
+ * token in an httpOnly cookie, and redirects to the post — which then renders
257
+ * the draft (see resolvePreviewToken). On an invalid/expired token it just
258
+ * redirects to the public page (which 404s if the post isn't published).
259
+ *
260
+ * Each consumer wires it up with one line:
261
+ * // app/api/preview/route.ts
262
+ * export { GET } from "@vulcantech/blog";
263
+ */
264
+ export async function GET(request: NextRequest): Promise<Response> {
265
+ const { searchParams } = new URL(request.url);
266
+ const token = searchParams.get("token");
267
+ const slug = searchParams.get("slug");
268
+
269
+ if (!token || !slug) {
270
+ return NextResponse.json(
271
+ { error: "token and slug are required" },
272
+ { status: 400 },
273
+ );
274
+ }
275
+
276
+ const target = new URL(`/blog/${encodeURIComponent(slug)}`, request.url);
277
+
278
+ // Validate by asking the CMS to resolve the draft with this token.
279
+ const post = await fetchBlogPostBySlug(slug, { previewToken: token });
280
+ if (!post) {
281
+ return NextResponse.redirect(target);
282
+ }
283
+
284
+ (await draftMode()).enable();
285
+ (await cookies()).set(PREVIEW_COOKIE, token, {
286
+ httpOnly: true,
287
+ sameSite: "lax",
288
+ secure: process.env.NODE_ENV === "production",
289
+ path: "/",
290
+ maxAge: PREVIEW_MAX_AGE_SECONDS,
291
+ });
292
+
293
+ return NextResponse.redirect(target);
294
+ }
295
+
296
+ /**
297
+ * Page helper: returns the active preview token when Draft Mode is on, else
298
+ * undefined. Call it in the blog post server component and spread the result
299
+ * into the fetch:
300
+ *
301
+ * const previewToken = await resolvePreviewToken();
302
+ * const post = await fetchBlogPostBySlug(slug, { previewToken });
303
+ *
304
+ * Reading the cookie only happens when Draft Mode is enabled, so the public
305
+ * route stays statically rendered for normal visitors.
306
+ */
307
+ export async function resolvePreviewToken(): Promise<string | undefined> {
308
+ const { isEnabled } = await draftMode();
309
+ if (!isEnabled) return undefined;
310
+ const store = await cookies();
311
+ return store.get(PREVIEW_COOKIE)?.value;
312
+ }
@@ -0,0 +1,97 @@
1
+ /**
2
+ * HTML sanitizer for user-generated (TipTap) content.
3
+ *
4
+ * MIRROR of packages/ui/sanitize.ts — keep in sync. Duplicated rather than
5
+ * imported so this package stays dependency-free (no `ui` workspace coupling).
6
+ *
7
+ * Defense-in-depth only. As of audit L4 / BL-023, blog HTML is sanitized ON
8
+ * WRITE by the CMS's parser-based DOMPurify sanitizer
9
+ * (apps/vulcantech-cms/src/lib/html/sanitizeHtml.ts), so the content this
10
+ * package fetches is already clean. This boundary pass is a safety net for
11
+ * legacy/unexpected data, not the primary guarantee.
12
+ *
13
+ * Strips dangerous tags and attributes and neutralizes dangerous URL schemes,
14
+ * decoding HTML entities first so entity-encoded `javascript:` payloads can't
15
+ * slip past the scheme check.
16
+ */
17
+
18
+ const DANGEROUS_TAGS = [
19
+ "script", "iframe", "object", "embed", "form", "input", "textarea",
20
+ "button", "select", "option", "link", "meta", "base", "applet",
21
+ "frame", "frameset", "layer", "style", "svg", "math", "xmp",
22
+ "noscript", "template",
23
+ ];
24
+
25
+ function safeCodePoint(n: number): string {
26
+ if (!Number.isFinite(n) || n < 0 || n > 0x10ffff) return "";
27
+ try {
28
+ return String.fromCodePoint(n);
29
+ } catch {
30
+ return "";
31
+ }
32
+ }
33
+
34
+ /** Decode numeric and a few named HTML entities used to obfuscate URL schemes. */
35
+ function decodeEntities(s: string): string {
36
+ return s
37
+ .replace(/&#x([0-9a-f]+);?/gi, (_, h) => safeCodePoint(parseInt(h, 16)))
38
+ .replace(/&#(\d+);?/g, (_, d) => safeCodePoint(parseInt(d, 10)))
39
+ .replace(/&colon;/gi, ":")
40
+ .replace(/&tab;/gi, "\t")
41
+ .replace(/&newline;/gi, "\n")
42
+ .replace(/&amp;/gi, "&");
43
+ }
44
+
45
+ /** Drop spaces and C0 control chars (code point <= 0x20) used to break up schemes. */
46
+ function stripBlankAndControl(s: string): string {
47
+ let out = "";
48
+ for (const ch of s) {
49
+ if (ch.codePointAt(0)! > 0x20) out += ch;
50
+ }
51
+ return out;
52
+ }
53
+
54
+ /**
55
+ * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe
56
+ * URL schemes. Returns the cleaned HTML string.
57
+ */
58
+ export function sanitizeHtml(html: string): string {
59
+ if (!html) return "";
60
+
61
+ let clean = html.replace(
62
+ /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
63
+ "",
64
+ );
65
+
66
+ for (const tag of DANGEROUS_TAGS) {
67
+ clean = clean.replace(
68
+ new RegExp(`<${tag}\\b[^>]*>[\\s\\S]*?<\\/${tag}>`, "gi"),
69
+ "",
70
+ );
71
+ clean = clean.replace(new RegExp(`<${tag}\\b[^>]*\\/?>`, "gi"), "");
72
+ }
73
+
74
+ clean = clean.replace(
75
+ /\s+on\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]*)/gi,
76
+ "",
77
+ );
78
+
79
+ clean = clean.replace(
80
+ /\s+style\s*=\s*("[^"]*"|'[^']*'|[^\s>]*)/gi,
81
+ "",
82
+ );
83
+
84
+ clean = clean.replace(
85
+ /\b(href|src)\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/gi,
86
+ (match, attr, _raw, dq, sq, uq) => {
87
+ const value = dq ?? sq ?? uq ?? "";
88
+ const decoded = stripBlankAndControl(decodeEntities(value)).toLowerCase();
89
+ if (/^(javascript|data|vbscript):/.test(decoded)) {
90
+ return `${attr}="about:blank"`;
91
+ }
92
+ return match;
93
+ },
94
+ );
95
+
96
+ return clean;
97
+ }