@decocms/nextjs 7.28.2 → 8.0.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,147 @@
1
+ import { NextRequest, NextResponse } from "next/server";
2
+ import { afterEach, beforeEach, describe, expect, it } from "vitest";
3
+
4
+ import { DRAFT_COOKIE } from "./draft";
5
+ import { applyDraft, prepareDraft, rewriteToDraftRoute } from "./draftMiddleware";
6
+
7
+ beforeEach(() => {
8
+ // The middleware is host-gated; these tests run as the allowed host.
9
+ process.env.DECO_ALLOWED_PREVIEW_HOSTS = "site.example";
10
+ });
11
+ afterEach(() => {
12
+ delete process.env.DECO_ALLOWED_PREVIEW_HOSTS;
13
+ });
14
+
15
+ function request(url: string, cookie?: string): NextRequest {
16
+ const req = new NextRequest(new URL(url), {
17
+ headers: cookie ? { cookie: `${DRAFT_COOKIE}=${cookie}` } : {},
18
+ });
19
+ return req;
20
+ }
21
+
22
+ describe("prepareDraft", () => {
23
+ it("reads the pointer from the param", () => {
24
+ expect(prepareDraft(request("https://site.example/p?__draft=abc.localhost@v1")).pointer).toBe(
25
+ "abc.localhost@v1",
26
+ );
27
+ });
28
+
29
+ it("reads the pointer from the cookie on a plain navigation", () => {
30
+ expect(prepareDraft(request("https://site.example/p", "abc.localhost@v1")).pointer).toBe(
31
+ "abc.localhost@v1",
32
+ );
33
+ });
34
+
35
+ it("passes through when no env override is set — the page gate is authoritative", () => {
36
+ // The site-block hosts live in the server-components graph; middleware
37
+ // can't see them, so without the env kill switch it must not block.
38
+ delete process.env.DECO_ALLOWED_PREVIEW_HOSTS;
39
+ const req = request("https://anything.example/p?__draft=abc.localhost@v1");
40
+ expect(prepareDraft(req).pointer).toBe("abc.localhost@v1");
41
+ });
42
+
43
+ it("is inert on a host outside the allowlist — the production domain", () => {
44
+ // Same build, different Host: no cookie, no rewrite, nothing touched.
45
+ const req = request("https://fila.com.br/p?__draft=abc@v1");
46
+ process.env.DECO_ALLOWED_PREVIEW_HOSTS = "fila.vtex.app";
47
+ expect(prepareDraft(req)).toEqual({ pointer: null, setCookie: null, clearCookie: false });
48
+ expect(rewriteToDraftRoute(req, prepareDraft(req))).toBeNull();
49
+ });
50
+
51
+ it("ignores a client-supplied draft header — the page owns the decision", () => {
52
+ // There is no request-header path any more; the page reads searchParams
53
+ // and cookies itself, so a forged header is simply not an input.
54
+ const req = new NextRequest(new URL("https://site.example/p"), {
55
+ headers: { "x-deco-draft": "attacker.localhost@v1" },
56
+ });
57
+ expect(prepareDraft(req).pointer).toBeNull();
58
+ });
59
+ });
60
+
61
+ describe("applyDraft", () => {
62
+ it("sets a partitioned cross-site cookie when entering draft mode", () => {
63
+ const decision = prepareDraft(request("https://site.example/p?__draft=abc.localhost@v1"));
64
+ const res = applyDraft(NextResponse.next(), decision);
65
+
66
+ const setCookie = res.headers.get("set-cookie") ?? "";
67
+ expect(setCookie).toContain(`${DRAFT_COOKIE}=abc.localhost%40v1`);
68
+ // The preview iframe is cross-site, so these attributes are what make the
69
+ // cookie survive at all — not hardening extras.
70
+ expect(setCookie).toMatch(/SameSite=None/i);
71
+ expect(setCookie).toMatch(/Secure/i);
72
+ expect(setCookie).toMatch(/Partitioned/i);
73
+ expect(setCookie).toMatch(/HttpOnly/i);
74
+ });
75
+
76
+ it("marks a draft response uncacheable and unindexable", () => {
77
+ // With the pointer in a cookie, draft and published share a URL — a CDN
78
+ // keyed on URL alone would serve unpublished content to a real visitor.
79
+ const decision = prepareDraft(request("https://site.example/p", "abc.localhost@v1"));
80
+ const res = applyDraft(NextResponse.next(), decision);
81
+
82
+ expect(res.headers.get("cache-control")).toBe("no-store, private");
83
+ expect(res.headers.get("vary")).toBe("Cookie");
84
+ expect(res.headers.get("x-robots-tag")).toBe("noindex, nofollow");
85
+ });
86
+
87
+ it("leaves an ordinary response completely untouched", () => {
88
+ const decision = prepareDraft(request("https://site.example/p"));
89
+ const res = applyDraft(NextResponse.next(), decision);
90
+
91
+ expect(res.headers.get("cache-control")).toBeNull();
92
+ expect(res.headers.get("vary")).toBeNull();
93
+ expect(res.headers.get("x-robots-tag")).toBeNull();
94
+ expect(res.headers.get("set-cookie")).toBeNull();
95
+ });
96
+
97
+ it("clears the cookie on ?__draft=off", () => {
98
+ const decision = prepareDraft(
99
+ request("https://site.example/p?__draft=off", "abc.localhost@v1"),
100
+ );
101
+ expect(decision.clearCookie).toBe(true);
102
+
103
+ const res = applyDraft(NextResponse.next(), decision);
104
+ const setCookie = res.headers.get("set-cookie") ?? "";
105
+ // Deletion is a set with an immediate expiry.
106
+ expect(setCookie).toContain(DRAFT_COOKIE);
107
+ expect(setCookie).toMatch(/Max-Age=0|Expires=Thu, 01 Jan 1970/i);
108
+ // And the response is not treated as a draft render.
109
+ expect(res.headers.get("cache-control")).toBeNull();
110
+ });
111
+ });
112
+
113
+ describe("rewriteToDraftRoute", () => {
114
+ it("rewrites a drafted request onto the dynamic draft route", () => {
115
+ const req = request("https://site.example/blog/hello?__draft=abc.localhost@v1");
116
+ const res = rewriteToDraftRoute(req, prepareDraft(req));
117
+ const target = new URL(res?.headers.get("x-middleware-rewrite") ?? "");
118
+ expect(target.pathname).toBe("/_draft/blog/hello");
119
+ // The pointer must survive: the draft page reads it from searchParams.
120
+ expect(target.searchParams.get("__draft")).toBe("abc.localhost@v1");
121
+ });
122
+
123
+ it("rewrites a cookie-only navigation too", () => {
124
+ const req = request("https://site.example/blog/hello", "abc.localhost@v1");
125
+ const res = rewriteToDraftRoute(req, prepareDraft(req));
126
+ expect(new URL(res?.headers.get("x-middleware-rewrite") ?? "").pathname).toBe(
127
+ "/_draft/blog/hello",
128
+ );
129
+ });
130
+
131
+ it("leaves an ordinary request alone — ISR must not be disturbed", () => {
132
+ // The whole point: only drafted requests go dynamic. A shopper's request
133
+ // must reach the real, statically rendered route untouched.
134
+ const req = request("https://site.example/blog/hello");
135
+ expect(rewriteToDraftRoute(req, prepareDraft(req))).toBeNull();
136
+ });
137
+
138
+ it("never nests the prefix when middleware re-runs on the rewritten URL", () => {
139
+ const req = request("https://site.example/_draft/blog/hello?__draft=abc.localhost@v1");
140
+ expect(rewriteToDraftRoute(req, prepareDraft(req))).toBeNull();
141
+ });
142
+
143
+ it("does not rewrite when leaving draft mode", () => {
144
+ const req = request("https://site.example/blog/hello?__draft=off", "abc.localhost@v1");
145
+ expect(rewriteToDraftRoute(req, prepareDraft(req))).toBeNull();
146
+ });
147
+ });
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Draft preview — middleware half.
3
+ *
4
+ * Two composable calls, because sites already own their middleware and this
5
+ * must slot into it rather than replace it:
6
+ *
7
+ * ```ts
8
+ * // middleware.ts (Next <16) / proxy.ts (Next 16+)
9
+ * export function middleware(request: NextRequest) {
10
+ * const decision = prepareDraft(request);
11
+ * return applyDraft(NextResponse.next(), decision);
12
+ * }
13
+ * ```
14
+ *
15
+ * The middleware owns only the cookie and the cache/indexing headers — a
16
+ * Server Component can read cookies but cannot set them, so that part has to
17
+ * live here. The pointer itself is read by the page.
18
+ *
19
+ * Lives on its own subpath so middleware (edge runtime) never imports the root
20
+ * barrel, which pulls in the client component graph.
21
+ */
22
+
23
+ import { isDraftHostAllowed } from "@decocms/blocks/cms";
24
+ import { type NextRequest, NextResponse } from "next/server";
25
+ import {
26
+ DRAFT_COOKIE,
27
+ DRAFT_COOKIE_OPTIONS,
28
+ type DraftMiddlewareDecision,
29
+ decideDraft,
30
+ } from "./draft";
31
+
32
+ /**
33
+ * Compute the draft decision for a request.
34
+ *
35
+ * Only the cookie and the response headers are the middleware's business now —
36
+ * the page reads the pointer itself from `searchParams` + `cookies()`, so
37
+ * nothing has to be forwarded through the request. That also means a draft
38
+ * still works on routes this middleware never matches.
39
+ */
40
+ const INERT: DraftMiddlewareDecision = { pointer: null, setCookie: null, clearCookie: false };
41
+
42
+ export function prepareDraft(request: NextRequest): DraftMiddlewareDecision {
43
+ // The AUTHORITATIVE host gate lives page-side (`ensureDraft`): the site
44
+ // block's `previewHosts` are installed in the server-components graph, and
45
+ // middleware runs in a separate module graph/runtime that never sees them.
46
+ // Middleware therefore hard-gates only on the env override — keeping
47
+ // DECO_ALLOWED_PREVIEW_HOSTS a full kill switch — and otherwise passes the
48
+ // decision through. Worst case on a non-preview host is a cookie the
49
+ // page-side gate then ignores; drafts never render there.
50
+ if (process.env.DECO_ALLOWED_PREVIEW_HOSTS) {
51
+ const host =
52
+ request.headers.get("x-forwarded-host") ??
53
+ request.headers.get("host") ??
54
+ request.nextUrl.host;
55
+ if (!isDraftHostAllowed(host)) return INERT;
56
+ }
57
+ return decideDraft(new URL(request.url), request.cookies.get(DRAFT_COOKIE)?.value ?? null);
58
+ }
59
+
60
+ /**
61
+ * URL prefix a drafted request is rewritten onto.
62
+ *
63
+ * The site must mount the matching route as `app/%5Fdraft/...` — URL-encoded.
64
+ * A literal `_draft/` directory is a Next "private folder", excluded from
65
+ * routing entirely, so the rewrite would fall through to whatever catch-all
66
+ * follows and 404. The encoded directory serves the same `/_draft` URL while
67
+ * staying routable.
68
+ */
69
+ export const DRAFT_ROUTE_PREFIX = "/_draft";
70
+
71
+ /**
72
+ * Rewrite a drafted request onto the dynamic draft route.
73
+ *
74
+ * This exists because `dynamic` / `revalidate` are STATIC route exports: a
75
+ * statically rendered page cannot become dynamic for one request. Making the
76
+ * real route dynamic to support drafts would cost every shopper their cached
77
+ * page, and — worse — a statically rendered draft would be cached and served to
78
+ * them. Rewriting sends only drafted requests to a route that is dynamic by
79
+ * construction, leaving ordinary traffic's ISR completely untouched.
80
+ *
81
+ * The original path is preserved in the rewritten pathname, so the draft route
82
+ * can resolve exactly the page the visitor asked for.
83
+ *
84
+ * Returns null when this request is not drafted, so callers fall through to
85
+ * their normal response.
86
+ */
87
+ export function rewriteToDraftRoute(
88
+ request: NextRequest,
89
+ decision: DraftMiddlewareDecision,
90
+ ): NextResponse | null {
91
+ if (!decision.pointer) return null;
92
+ const url = request.nextUrl.clone();
93
+ // Already rewritten (Next re-runs middleware on the rewritten URL in some
94
+ // configurations) — never nest the prefix.
95
+ if (url.pathname.startsWith(`${DRAFT_ROUTE_PREFIX}/`)) return null;
96
+ url.pathname = `${DRAFT_ROUTE_PREFIX}${url.pathname}`;
97
+ return NextResponse.rewrite(url);
98
+ }
99
+
100
+ /**
101
+ * Apply the cookie and the cache/indexing headers a draft response requires.
102
+ *
103
+ * The caching headers are the difference between a preview and a **leak**.
104
+ * With the pointer in a cookie, a draft response and a published one share an
105
+ * identical URL, so a CDN keyed on URL alone would happily serve unpublished
106
+ * content to a real visitor. `no-store` is what actually prevents that;
107
+ * `Vary: Cookie` keeps any intermediary that *does* respect it from mixing the
108
+ * two; `X-Robots-Tag` keeps a leaked draft out of search results.
109
+ */
110
+ export function applyDraft(
111
+ response: NextResponse,
112
+ decision: DraftMiddlewareDecision,
113
+ ): NextResponse {
114
+ if (decision.clearCookie) {
115
+ response.cookies.delete(DRAFT_COOKIE);
116
+ } else if (decision.setCookie) {
117
+ response.cookies.set(DRAFT_COOKIE, decision.setCookie, DRAFT_COOKIE_OPTIONS);
118
+ }
119
+
120
+ if (decision.pointer) {
121
+ response.headers.set("cache-control", "no-store, private");
122
+ response.headers.set("vary", "Cookie");
123
+ response.headers.set("x-robots-tag", "noindex, nofollow");
124
+ }
125
+
126
+ return response;
127
+ }
128
+
129
+ /**
130
+ * Convenience for sites with no middleware of their own: prepare, continue,
131
+ * apply. Sites that already have middleware should call the two halves
132
+ * directly so their own logic sits in between.
133
+ */
134
+ export function draftMiddleware(request: NextRequest): NextResponse {
135
+ return applyDraft(NextResponse.next(), prepareDraft(request));
136
+ }
package/src/index.ts CHANGED
@@ -8,6 +8,31 @@ export {
8
8
  export { DecoPageRenderer } from "./DecoPageRenderer";
9
9
  export { DecoRootLayout, type DecoRootLayoutProps } from "./DecoRootLayout";
10
10
  export { DeferredSectionBoundary } from "./DeferredSection";
11
+ export {
12
+ buildExitUrl,
13
+ buildShareUrl,
14
+ DraftPreviewBadge,
15
+ type DraftPreviewBadgeProps,
16
+ } from "./DraftPreviewBadge";
17
+ export { DraftPreviewIndicator } from "./DraftPreviewIndicator";
18
+ export {
19
+ DRAFT_COOKIE,
20
+ DRAFT_COOKIE_OPTIONS,
21
+ DRAFT_PARAM,
22
+ type DraftMiddlewareDecision,
23
+ type DraftSearchParams,
24
+ decideDraft,
25
+ ensureDraft,
26
+ getActiveDraftPointer,
27
+ registerDraftOverride,
28
+ selectDraftPointer,
29
+ } from "./draft";
30
+ export {
31
+ applyDraft,
32
+ DRAFT_ROUTE_PREFIX,
33
+ prepareDraft,
34
+ rewriteToDraftRoute,
35
+ } from "./draftMiddleware";
11
36
  export {
12
37
  decofileGET,
13
38
  decofilePOST,
package/src/setup.ts CHANGED
@@ -38,7 +38,7 @@
38
38
  * deploys must ship the directory alongside the server bundle).
39
39
  */
40
40
  import type { ApplySectionConventionsInput } from "@decocms/blocks/cms";
41
- import { applySectionConventions, loadBlocks } from "@decocms/blocks/cms";
41
+ import { applySectionConventions, loadBlocks, setDraftPreviewHosts } from "@decocms/blocks/cms";
42
42
  import { loadDecofileDirectory } from "@decocms/blocks/cms/loadDecofileDirectory";
43
43
  import { createSiteSetup, type SiteSetupOptions } from "@decocms/blocks/setup";
44
44
 
@@ -110,9 +110,29 @@ export interface NextSetupOptions {
110
110
  * instead, nothing imports the JSON, so edits invalidate nothing and dev
111
111
  * serves stale content until a full restart.
112
112
  */
113
+ /**
114
+ * Install the site block's `previewHosts` as the draft-preview allowlist.
115
+ *
116
+ * Reads the BASE blocks handed to setup — never `loadBlocks()` at request
117
+ * time, where the draft override is merged in: an allowlist readable through
118
+ * the override could be rewritten by the very draft it gates.
119
+ * `DECO_ALLOWED_PREVIEW_HOSTS` remains an operational override that replaces
120
+ * this list when set.
121
+ */
122
+ function installPreviewHosts(blocks: Record<string, unknown> | undefined): void {
123
+ const site = blocks?.site as { previewHosts?: unknown } | undefined;
124
+ if (Array.isArray(site?.previewHosts)) setDraftPreviewHosts(site.previewHosts);
125
+ }
126
+
113
127
  export function createNextSetup(options: NextSetupOptions): () => Promise<void> {
114
128
  let setupPromise: Promise<void> | null = null;
115
129
 
130
+ // Draft preview opt-in from the repo: read SYNCHRONOUSLY at createNextSetup
131
+ // time (module evaluation), not inside the lazy ensureSetup — pages call
132
+ // `ensureDraft` BEFORE they resolve CMS content, so hosts installed lazily
133
+ // would arrive after the gate already said no on the first request.
134
+ installPreviewHosts(options.blocks);
135
+
116
136
  return function ensureSetup(): Promise<void> {
117
137
  setupPromise ??= (async () => {
118
138
  const dirBlocks =
@@ -120,6 +140,8 @@ export function createNextSetup(options: NextSetupOptions): () => Promise<void>
120
140
  ? {}
121
141
  : await loadDecofileDirectory(options.blocksDir ?? ".deco/blocks");
122
142
  const blocks = { ...dirBlocks, ...options.blocks };
143
+ // Covers the blocksDir mode, where blocks only exist after the fs read.
144
+ installPreviewHosts(blocks);
123
145
 
124
146
  createSiteSetup({
125
147
  sections: options.sections,