sitecms-next 0.3.0 → 0.5.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.
@@ -0,0 +1,368 @@
1
+ /**
2
+ * Live-förhandsgranskning för Next.js App Router (sitecms-next 0.4).
3
+ *
4
+ * // app/api/sitecms/preview/route.ts
5
+ * export { GET } from "sitecms-next/preview";
6
+ *
7
+ * // app/layout.tsx, sist i <body>
8
+ * import { SitecmsPreview } from "sitecms-next/preview";
9
+ * <SitecmsPreview />
10
+ *
11
+ * // next.config.ts — låt panelen bädda in sajten
12
+ * import { previewFrameHeaders } from "sitecms-next/preview";
13
+ * headers: async () => [{ source: "/:path*", headers: previewFrameHeaders() }]
14
+ *
15
+ * Panelen öppnar `/api/sitecms/preview?token=…&path=/` i en iframe. Routen
16
+ * verifierar token mot sitecms, slår på draft mode och sätter cookies som
17
+ * fungerar i en iframe från en annan domän (partitioned, SameSite=None).
18
+ * `getContent()` hämtar då osparade ändringar, och `<SitecmsPreview />`
19
+ * pratar med panelen via postMessage.
20
+ *
21
+ * `next/headers` importeras dynamiskt: modulen går att importera utanför
22
+ * Next (t.ex. i next.config) och statiska sidor förblir statiska.
23
+ */
24
+ import {
25
+ DEFAULT_API_URL,
26
+ PREVIEW_COOKIE,
27
+ PREVIEW_HEADER,
28
+ PREVIEW_ORIGIN_COOKIE,
29
+ apiBase,
30
+ isPreview,
31
+ } from "./index.js";
32
+ import { SitecmsPreviewClient } from "./preview-client.js";
33
+
34
+ export { isPreview };
35
+ export type { SitecmsPreviewClientProps } from "./preview-client.js";
36
+
37
+ /** Sökvägen som `sitecms-next init` skapar routen på. */
38
+ export const PREVIEW_ROUTE_PATH = "/api/sitecms/preview";
39
+
40
+ /** Nexts draft mode-cookie. */
41
+ const BYPASS_COOKIE = "__prerender_bypass";
42
+ /** Preview-cookiernas livslängd i sekunder (som sessionen i sitecms). */
43
+ const PREVIEW_MAX_AGE = 7200;
44
+
45
+ // ---------------------------------------------------------------------------
46
+ // Meddelandeprotokoll (v1) — typer för den som vill bygga egen klient/panel
47
+ // ---------------------------------------------------------------------------
48
+
49
+ export type PreviewField = { page: string; key: string };
50
+
51
+ /** Panel → sajt (`source: "sitecms"`). */
52
+ export type PreviewPanelMessage = { source: "sitecms"; v: 1 } & (
53
+ | { type: "refresh" }
54
+ | { type: "patch"; page: string; key: string; kind: "text" | "image"; value: string; alt?: string | null }
55
+ | { type: "highlight"; page: string; key: string }
56
+ | { type: "overlays"; enabled: boolean }
57
+ );
58
+
59
+ /** Sajt → panel (`source: "sitecms-preview"`). */
60
+ export type PreviewSiteMessage = { source: "sitecms-preview"; v: 1 } & (
61
+ | { type: "ready"; path: string; title: string; fields: PreviewField[] }
62
+ | { type: "refreshed"; path: string }
63
+ | { type: "focus"; page: string; key: string }
64
+ );
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // Hjälpfunktioner
68
+ // ---------------------------------------------------------------------------
69
+
70
+ function env(name: string): string {
71
+ return (typeof process !== "undefined" && process.env?.[name]?.trim()) || "";
72
+ }
73
+
74
+ type CookieOptions = {
75
+ name: string;
76
+ value: string;
77
+ httpOnly?: boolean;
78
+ secure?: boolean;
79
+ sameSite?: "lax" | "none" | "strict";
80
+ partitioned?: boolean;
81
+ path?: string;
82
+ maxAge?: number;
83
+ expires?: Date;
84
+ };
85
+
86
+ type CookieStoreLike = {
87
+ get(name: string): { value?: string } | undefined;
88
+ set(options: CookieOptions): unknown;
89
+ };
90
+
91
+ type DraftModeLike = { isEnabled: boolean; enable(): void; disable(): void };
92
+
93
+ /** Det som används från `next/headers`. Värdena kan vara synkrona (Next 14) eller promises (Next 15+). */
94
+ export type NextHeadersLike = {
95
+ draftMode: () => unknown;
96
+ cookies: () => unknown;
97
+ };
98
+
99
+ async function loadNextHeaders(): Promise<NextHeadersLike | null> {
100
+ try {
101
+ return (await import("next/headers.js")) as unknown as NextHeadersLike;
102
+ } catch {
103
+ return null;
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Sökvägen att skicka vidare till efter routen: måste börja med `/` men inte
109
+ * `//` eller `/\` (annars `/`), så att routen aldrig blir en öppen redirect.
110
+ * Behåller query och hash.
111
+ */
112
+ export function safePreviewPath(raw: string | null | undefined): string {
113
+ const value = (raw ?? "").trim();
114
+ if (!value.startsWith("/") || value.startsWith("//")) return "/";
115
+ // Webbläsare tolkar \ som / och kontrolltecken tas bort: "/\evil.se" blir "//evil.se".
116
+ if (/[\\\u0000-\u001f\u007f]/.test(value)) return "/";
117
+ try {
118
+ const base = "http://sitecms.invalid";
119
+ const url = new URL(value, base);
120
+ if (url.origin !== base) return "/";
121
+ return `${url.pathname}${url.search}${url.hash}`;
122
+ } catch {
123
+ return "/";
124
+ }
125
+ }
126
+
127
+ /** En origin (`https://sitecms.se`) eller null. Accepterar bara http(s) utan sökväg. */
128
+ function normalizeOrigin(value: unknown): string | null {
129
+ if (typeof value !== "string" || !value.trim()) return null;
130
+ try {
131
+ const url = new URL(value.trim());
132
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
133
+ if (url.username || url.password) return null;
134
+ if (url.pathname !== "/" || url.search || url.hash) return null;
135
+ return url.origin;
136
+ } catch {
137
+ return null;
138
+ }
139
+ }
140
+
141
+ function isLoopbackHost(hostname: string): boolean {
142
+ const host = hostname.toLowerCase();
143
+ return host === "localhost" || host.endsWith(".localhost") || host === "127.0.0.1" || host === "[::1]";
144
+ }
145
+
146
+ /**
147
+ * http://localhost (dev): cookies utan Secure/Partitioned och SameSite=Lax.
148
+ * `next start` bygger request.url från sin egen adress (localhost) om proxyn
149
+ * inte skickar x-forwarded-proto, så även Host/x-forwarded-host måste vara
150
+ * localhost — annars antas en riktig (https-)sajt bakom proxy.
151
+ */
152
+ function isLocalHttp(url: URL, headers: Headers): boolean {
153
+ if (url.protocol !== "http:" || !isLoopbackHost(url.hostname)) return false;
154
+ const hostHeader = (headers.get("x-forwarded-host") ?? headers.get("host") ?? "").split(",")[0].trim();
155
+ if (!hostHeader) return true;
156
+ try {
157
+ return isLoopbackHost(new URL(`http://${hostHeader}`).hostname);
158
+ } catch {
159
+ return false;
160
+ }
161
+ }
162
+
163
+ function cookieAttributes(localDev: boolean): Omit<CookieOptions, "name" | "value"> {
164
+ return localDev
165
+ ? { httpOnly: true, secure: false, sameSite: "lax", path: "/" }
166
+ : { httpOnly: true, secure: true, sameSite: "none", partitioned: true, path: "/" };
167
+ }
168
+
169
+ function escapeHtml(value: string): string {
170
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
171
+ }
172
+
173
+ const NO_STORE = { "Cache-Control": "private, no-store", "Referrer-Policy": "no-referrer" };
174
+
175
+ /** Enkel felsida på svenska. Token ekas aldrig tillbaka. */
176
+ function errorPage(status: number, message: string): Response {
177
+ const html = `<!doctype html>
178
+ <html lang="sv">
179
+ <head>
180
+ <meta charset="utf-8">
181
+ <meta name="viewport" content="width=device-width, initial-scale=1">
182
+ <meta name="robots" content="noindex">
183
+ <title>Förhandsgranskningen kunde inte startas</title>
184
+ <style>
185
+ :root { color-scheme: light dark; }
186
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px; box-sizing: border-box;
187
+ font: 15px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; background: #f6f7f9; color: #171717; }
188
+ main { max-width: 440px; background: #fff; border: 1px solid #e5e5e5; border-radius: 12px; padding: 24px; }
189
+ h1 { font-size: 17px; margin: 0 0 8px; }
190
+ p { margin: 0; color: #525252; }
191
+ @media (prefers-color-scheme: dark) {
192
+ body { background: #0a0a0a; color: #f5f5f5; }
193
+ main { background: #171717; border-color: #262626; }
194
+ p { color: #a3a3a3; }
195
+ }
196
+ </style>
197
+ </head>
198
+ <body>
199
+ <main>
200
+ <h1>Förhandsgranskningen kunde inte startas</h1>
201
+ <p>${escapeHtml(message)}</p>
202
+ </main>
203
+ </body>
204
+ </html>
205
+ `;
206
+ return new Response(html, { status, headers: { "Content-Type": "text/html; charset=utf-8", ...NO_STORE } });
207
+ }
208
+
209
+ function redirectTo(path: string): Response {
210
+ // Relativ Location: rätt värd även bakom proxy.
211
+ return new Response(null, { status: 307, headers: { Location: path, ...NO_STORE } });
212
+ }
213
+
214
+ // ---------------------------------------------------------------------------
215
+ // Route: GET /api/sitecms/preview
216
+ // ---------------------------------------------------------------------------
217
+
218
+ export type PreviewRouteOptions = {
219
+ /** Bas-URL till sitecms. Default CMS_API_URL, annars "https://sitecms.se". */
220
+ apiUrl?: string;
221
+ /** Sajtens slug (valfri, som klienten). Default CMS_SITE om apiKey inte anges. */
222
+ site?: string;
223
+ /** API-nyckel. Default CMS_API_KEY. */
224
+ apiKey?: string;
225
+ /** Egen fetch, t.ex. för tester. Default globalThis.fetch. */
226
+ fetch?: typeof fetch;
227
+ /** Ersätter `next/headers` (för tester). */
228
+ nextHeaders?: () => Promise<NextHeadersLike | null> | NextHeadersLike | null;
229
+ };
230
+
231
+ const MSG_INVALID = "Länken har gått ut eller är ogiltig. Öppna förhandsgranskningen igen i sitecms.";
232
+ const MSG_UNREACHABLE = "sitecms gick inte att nå just nu. Försök igen om en stund.";
233
+ const MSG_NO_KEY =
234
+ "CMS_API_KEY saknas på sajten. Lägg in den som miljövariabel hos webbhotellet och deploya om.";
235
+ const MSG_NO_NEXT = "Routen kräver Next.js App Router (next/headers saknas).";
236
+
237
+ /**
238
+ * Skapar preview-routen. Utelämnade värden läses från miljön på samma sätt
239
+ * som `createSitecms` (CMS_API_KEY, CMS_API_URL, CMS_SITE).
240
+ *
241
+ * - `GET ?token=<t>&path=<p>` verifierar token mot `{apiBase}/preview`, slår
242
+ * på draft mode, sätter cookies och skickar vidare (307) till `path`.
243
+ * - `GET ?disable=1&path=<p>` stänger av draft mode, rensar cookies och
244
+ * skickar vidare till `path`.
245
+ */
246
+ export function createPreviewRoute(options: PreviewRouteOptions = {}) {
247
+ return async function GET(request: Request): Promise<Response> {
248
+ const url = new URL(request.url);
249
+ const path = safePreviewPath(url.searchParams.get("path"));
250
+ const attrs = cookieAttributes(isLocalHttp(url, request.headers));
251
+
252
+ const next = await (options.nextHeaders ? options.nextHeaders() : loadNextHeaders());
253
+ if (!next) return errorPage(500, MSG_NO_NEXT);
254
+
255
+ if (url.searchParams.has("disable")) {
256
+ const draft = (await next.draftMode()) as DraftModeLike;
257
+ draft.disable();
258
+ const store = (await next.cookies()) as CookieStoreLike;
259
+ // Samma attribut som när de sattes: en partitioned cookie raderas bara
260
+ // av en Set-Cookie som också är partitioned.
261
+ for (const name of [BYPASS_COOKIE, PREVIEW_COOKIE, PREVIEW_ORIGIN_COOKIE]) {
262
+ store.set({ name, value: "", ...attrs, expires: new Date(0) });
263
+ }
264
+ return redirectTo(path);
265
+ }
266
+
267
+ const token = url.searchParams.get("token")?.trim() ?? "";
268
+ if (!token || token.length > 512) return errorPage(401, MSG_INVALID);
269
+
270
+ const explicitKey = options.apiKey !== undefined;
271
+ const apiKey = (options.apiKey ?? env("CMS_API_KEY")).trim();
272
+ if (!apiKey) return errorPage(500, MSG_NO_KEY);
273
+ const base = apiBase(options.apiUrl ?? env("CMS_API_URL"), options.site ?? (explicitKey ? "" : env("CMS_SITE")));
274
+ const doFetch = options.fetch ?? globalThis.fetch;
275
+
276
+ let res: Response;
277
+ try {
278
+ res = await doFetch(`${base}/preview`, {
279
+ headers: { "x-api-key": apiKey, [PREVIEW_HEADER]: token },
280
+ cache: "no-store",
281
+ });
282
+ } catch {
283
+ return errorPage(401, MSG_UNREACHABLE);
284
+ }
285
+ if (!res.ok) return errorPage(401, res.status >= 500 ? MSG_UNREACHABLE : MSG_INVALID);
286
+ const body = (await res.json().catch(() => null)) as { ok?: unknown; panelOrigin?: unknown } | null;
287
+ const panelOrigin = normalizeOrigin(body?.panelOrigin);
288
+ if (body?.ok !== true || !panelOrigin) return errorPage(401, MSG_INVALID);
289
+
290
+ const draft = (await next.draftMode()) as DraftModeLike;
291
+ draft.enable();
292
+ const store = (await next.cookies()) as CookieStoreLike;
293
+ // Skriv om Nexts draft mode-cookie så att den skickas i en iframe från en
294
+ // annan domän (samma trick som next-sanity).
295
+ const bypass = store.get(BYPASS_COOKIE)?.value;
296
+ if (bypass) store.set({ name: BYPASS_COOKIE, value: bypass, ...attrs });
297
+ store.set({ name: PREVIEW_COOKIE, value: token, ...attrs, maxAge: PREVIEW_MAX_AGE });
298
+ store.set({ name: PREVIEW_ORIGIN_COOKIE, value: panelOrigin, ...attrs, maxAge: PREVIEW_MAX_AGE });
299
+ return redirectTo(path);
300
+ };
301
+ }
302
+
303
+ /** Preview-routen med standardinställningar (läser CMS_API_KEY, CMS_API_URL, CMS_SITE). */
304
+ export const GET = createPreviewRoute();
305
+
306
+ // ---------------------------------------------------------------------------
307
+ // <SitecmsPreview /> — i app/layout.tsx
308
+ // ---------------------------------------------------------------------------
309
+
310
+ export type SitecmsPreviewProps = {
311
+ /** Sökvägen till preview-routen (för "Avsluta"). Default "/api/sitecms/preview". */
312
+ routePath?: string;
313
+ };
314
+
315
+ /**
316
+ * Async serverkomponent. Renderar ingenting om draft mode inte är på (och
317
+ * läser då inga cookies, så statiska sidor förblir statiska). Annars
318
+ * klientkomponenten som pratar med panelen, med panelens origin från cookien.
319
+ */
320
+ export async function SitecmsPreview(props: SitecmsPreviewProps = {}) {
321
+ const next = await loadNextHeaders();
322
+ if (!next) return null;
323
+ let panelOrigin: string | null = null;
324
+ try {
325
+ const draft = (await next.draftMode()) as DraftModeLike | null;
326
+ if (!draft?.isEnabled) return null;
327
+ const store = (await next.cookies()) as CookieStoreLike;
328
+ panelOrigin = normalizeOrigin(store.get(PREVIEW_ORIGIN_COOKIE)?.value);
329
+ } catch {
330
+ return null;
331
+ }
332
+ const routePath = safePreviewPath(props.routePath ?? PREVIEW_ROUTE_PATH).replace(/[?#].*$/, "");
333
+ return <SitecmsPreviewClient panelOrigin={panelOrigin} exitHref={`${routePath}?disable=1`} />;
334
+ }
335
+
336
+ // ---------------------------------------------------------------------------
337
+ // Frame-headers — i next.config
338
+ // ---------------------------------------------------------------------------
339
+
340
+ const WILDCARD_SOURCE = /^https:\/\/\*\.[a-z0-9-]+(\.[a-z0-9-]+)+(:\d{1,5})?$/i;
341
+
342
+ /**
343
+ * Headers som låter panelen bädda in sajten i en iframe:
344
+ *
345
+ * // next.config.ts
346
+ * async headers() {
347
+ * return [{ source: "/:path*", headers: previewFrameHeaders() }];
348
+ * }
349
+ *
350
+ * Default: origin för CMS_API_URL (annars https://sitecms.se) plus
351
+ * https://www.sitecms.se. Ta bort `X-Frame-Options` på sajten — CSP
352
+ * `frame-ancestors` ersätter den.
353
+ */
354
+ export function previewFrameHeaders(panelOrigins?: string[]): { key: string; value: string }[] {
355
+ const input =
356
+ panelOrigins ?? [normalizeOrigin(env("CMS_API_URL").replace(/\/+$/, "")) ?? DEFAULT_API_URL, "https://www.sitecms.se"];
357
+ const sources: string[] = [];
358
+ for (const raw of input) {
359
+ const value = String(raw ?? "").trim().replace(/\/+$/, "");
360
+ const source = WILDCARD_SOURCE.test(value) ? value.toLowerCase() : normalizeOrigin(value);
361
+ if (!source) {
362
+ console.warn(`sitecms: previewFrameHeaders hoppar över ${JSON.stringify(raw)} (inte en origin, t.ex. https://sitecms.se).`);
363
+ continue;
364
+ }
365
+ if (!sources.includes(source)) sources.push(source);
366
+ }
367
+ return [{ key: "Content-Security-Policy", value: ["frame-ancestors", "'self'", ...sources].join(" ") }];
368
+ }