@websolutespa/bom-next 4.0.0-next.11 → 4.0.0-next.13
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/CHANGELOG.md +21 -0
- package/README.md +5 -1
- package/dist/cache-handler/redis.d.ts +20 -3
- package/dist/cache-handler/redis.d.ts.map +1 -1
- package/dist/cache-handler/redis.js +54 -8
- package/dist/cache-handler/redis.js.map +1 -1
- package/dist/client/user.d.ts.map +1 -1
- package/dist/client/user.js.map +1 -1
- package/dist/exports/cache-handlers-isr.d.ts +2 -2
- package/dist/exports/cache-handlers-isr.js +2 -2
- package/dist/exports/server.d.ts +4 -3
- package/dist/exports/server.js +4 -3
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/instrumentation/server.d.ts.map +1 -1
- package/dist/instrumentation/server.js +4 -0
- package/dist/instrumentation/server.js.map +1 -1
- package/dist/lib/const.d.ts +9 -1
- package/dist/lib/const.d.ts.map +1 -1
- package/dist/lib/const.js +16 -1
- package/dist/lib/const.js.map +1 -1
- package/dist/lib/page-metadata.d.ts +13 -2
- package/dist/lib/page-metadata.d.ts.map +1 -1
- package/dist/lib/page-metadata.js +10 -3
- package/dist/lib/page-metadata.js.map +1 -1
- package/dist/server/cache/inspector/redis.js +2 -2
- package/dist/server/cache/inspector/redis.js.map +1 -1
- package/dist/server/handlers/preview.handler.d.ts +27 -3
- package/dist/server/handlers/preview.handler.d.ts.map +1 -1
- package/dist/server/handlers/preview.handler.js +57 -6
- package/dist/server/handlers/preview.handler.js.map +1 -1
- package/dist/server/metadata.d.ts +1 -1
- package/dist/server/mixer.d.ts +1 -1
- package/dist/server/mixer.d.ts.map +1 -1
- package/dist/server/mixer.js +11 -2
- package/dist/server/mixer.js.map +1 -1
- package/package.json +2 -2
- package/src/cache-handler/redis.test.ts +78 -1
- package/src/cache-handler/redis.ts +70 -8
- package/src/client/user.tsx +3 -2
- package/src/exports/cache-handlers-isr.ts +7 -1
- package/src/instrumentation/server.ts +6 -0
- package/src/lib/const.ts +10 -0
- package/src/lib/page-metadata.test.ts +33 -1
- package/src/lib/page-metadata.ts +20 -1
- package/src/server/cache/inspector/redis.ts +8 -2
- package/src/server/handlers/preview.handler.test.ts +92 -0
- package/src/server/handlers/preview.handler.ts +85 -53
- package/src/server/mixer.ts +19 -2
|
@@ -3,8 +3,12 @@
|
|
|
3
3
|
* Redis, shared by every instance of a site. Set it in `next.config` with `withBom()`, or directly:
|
|
4
4
|
* `cacheHandler: require.resolve('@websolutespa/bom-next/cache-handlers/isr')`, `cacheMaxMemorySize: 0`.
|
|
5
5
|
*
|
|
6
|
-
* - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, value }` (in
|
|
7
|
-
* order: the cache panel reads the head of the value without parsing the page).
|
|
6
|
+
* - Entries: `${REDIS_PREFIX}:next:<key>`, written as `{ lastModified, tags, revalidate, cacheControl, value }` (in
|
|
7
|
+
* this order: the cache panel reads the head of the value without parsing the page). `get` returns the stored
|
|
8
|
+
* `cacheControl`: Next.js (16.4+) otherwise knows the lifetime only of paths this instance rendered or
|
|
9
|
+
* prerendered, and treats an entry written by another instance as revalidate 1 s (served stale, re-rendered).
|
|
10
|
+
* - Client: one connection per process (`globalThis`), shared by this handler, which Next.js loads from
|
|
11
|
+
* node_modules, and the bundled server code (cache panel inspector, `registerIntrumentation` warm-up).
|
|
8
12
|
* - Meta: `${REDIS_PREFIX}:next-meta:<key>`, a small JSON per entry that the cache panel lists with SCAN.
|
|
9
13
|
* - Tags: `${REDIS_PREFIX}:next-tag:<tag>` is when the tag expired (the next request waits for a fresh render),
|
|
10
14
|
* `${REDIS_PREFIX}:next-tag-stale:<tag>` when it went stale (served once more, regenerated in the background).
|
|
@@ -87,13 +91,28 @@ type CacheValue = {
|
|
|
87
91
|
headers?: Record<string, string | string[] | undefined>;
|
|
88
92
|
};
|
|
89
93
|
|
|
94
|
+
/** The lifetime Next.js keeps per route (`CacheControl`); `expire` in seconds. */
|
|
95
|
+
type StoredCacheControl = { revalidate: number | false; expire: number | undefined };
|
|
96
|
+
|
|
90
97
|
type StoredEntry = {
|
|
91
98
|
lastModified: number;
|
|
92
99
|
tags: string[];
|
|
93
100
|
revalidate: number | false | null;
|
|
101
|
+
/** Absent on entries written before 4.0.0-next.12. */
|
|
102
|
+
cacheControl?: StoredCacheControl;
|
|
94
103
|
value: CacheValue;
|
|
95
104
|
};
|
|
96
105
|
|
|
106
|
+
/** The lifetime returned with an entry, so every instance applies the one it was written with. */
|
|
107
|
+
function cacheControlOf(entry: StoredEntry): StoredCacheControl | undefined {
|
|
108
|
+
if (entry.cacheControl) {
|
|
109
|
+
return entry.cacheControl;
|
|
110
|
+
}
|
|
111
|
+
return typeof entry.revalidate === 'number' || entry.revalidate === false
|
|
112
|
+
? { revalidate: entry.revalidate, expire: undefined }
|
|
113
|
+
: undefined;
|
|
114
|
+
}
|
|
115
|
+
|
|
97
116
|
/** Explicit tags of a value: the context tags plus the `x-next-cache-tags` header of pages and route handlers. */
|
|
98
117
|
export function entryTags(
|
|
99
118
|
value: CacheValue | null | undefined,
|
|
@@ -120,18 +139,28 @@ function revalidateOf(
|
|
|
120
139
|
|
|
121
140
|
type ConnectingClient = RedisLike & {
|
|
122
141
|
on(event: 'error' | 'ready', listener: (error: Error) => void): unknown;
|
|
142
|
+
once(event: 'ready', listener: () => void): unknown;
|
|
143
|
+
off(event: 'ready', listener: () => void): unknown;
|
|
123
144
|
connect(): Promise<unknown>;
|
|
124
145
|
};
|
|
125
146
|
|
|
126
|
-
|
|
147
|
+
/**
|
|
148
|
+
* The client lives on `globalThis`: Next.js loads this handler from node_modules while the inspector and the
|
|
149
|
+
* instrumentation are bundled into the app, and module state would give each its own connection.
|
|
150
|
+
*/
|
|
151
|
+
const shared = globalThis as typeof globalThis & { __bomRedisClient?: ConnectingClient };
|
|
127
152
|
|
|
128
153
|
/** A connecting client used only while ready: awaiting `connect()` would hang every request while Redis is down. */
|
|
129
154
|
export async function getRedisClient(): Promise<RedisLike | undefined> {
|
|
130
155
|
if (!process.env.REDIS_URL) {
|
|
131
156
|
return undefined;
|
|
132
157
|
}
|
|
133
|
-
if (!
|
|
158
|
+
if (!shared.__bomRedisClient) {
|
|
134
159
|
const { createClient } = await import('redis');
|
|
160
|
+
// another caller may have created it while the module loaded
|
|
161
|
+
if (shared.__bomRedisClient) {
|
|
162
|
+
return getRedisClient();
|
|
163
|
+
}
|
|
135
164
|
const client = createClient({
|
|
136
165
|
url: process.env.REDIS_URL,
|
|
137
166
|
// fail fast while disconnected instead of queueing commands behind a dead socket
|
|
@@ -141,7 +170,7 @@ export async function getRedisClient(): Promise<RedisLike | undefined> {
|
|
|
141
170
|
reconnectStrategy: (retries: number) => Math.min(retries * 200, 5000),
|
|
142
171
|
},
|
|
143
172
|
}) as unknown as ConnectingClient;
|
|
144
|
-
|
|
173
|
+
shared.__bomRedisClient = client;
|
|
145
174
|
let logged = false;
|
|
146
175
|
client.on('error', (error: Error) => {
|
|
147
176
|
if (!logged) {
|
|
@@ -156,9 +185,37 @@ export async function getRedisClient(): Promise<RedisLike | undefined> {
|
|
|
156
185
|
/* reported by the error listener, retried by reconnectStrategy */
|
|
157
186
|
});
|
|
158
187
|
}
|
|
188
|
+
const sharedClient = shared.__bomRedisClient;
|
|
159
189
|
return sharedClient.isReady ? sharedClient : undefined;
|
|
160
190
|
}
|
|
161
191
|
|
|
192
|
+
/**
|
|
193
|
+
* Starts the shared client and waits until it is ready, up to `timeout` ms (the connect timeout). For callers that
|
|
194
|
+
* may wait, unlike a page lookup: the cache panel, and the startup warm-up, so the first request of a cold instance
|
|
195
|
+
* already reads Redis.
|
|
196
|
+
*/
|
|
197
|
+
export async function connectRedisClient(timeout = 2000): Promise<RedisLike | undefined> {
|
|
198
|
+
const ready = await getRedisClient();
|
|
199
|
+
const client = shared.__bomRedisClient;
|
|
200
|
+
if (ready || !client) {
|
|
201
|
+
return ready;
|
|
202
|
+
}
|
|
203
|
+
await new Promise<void>((resolve) => {
|
|
204
|
+
const done = { timer: undefined as ReturnType<typeof setTimeout> | undefined };
|
|
205
|
+
const onReady = () => {
|
|
206
|
+
clearTimeout(done.timer);
|
|
207
|
+
resolve();
|
|
208
|
+
};
|
|
209
|
+
// no listener left behind while Redis stays down and the panel keeps asking
|
|
210
|
+
done.timer = setTimeout(() => {
|
|
211
|
+
client.off('ready', onReady);
|
|
212
|
+
resolve();
|
|
213
|
+
}, timeout);
|
|
214
|
+
client.once('ready', onReady);
|
|
215
|
+
});
|
|
216
|
+
return client.isReady ? client : undefined;
|
|
217
|
+
}
|
|
218
|
+
|
|
162
219
|
/** Builds the handler class around a client getter, so tests can inject one. */
|
|
163
220
|
export function createRedisCacheHandler(
|
|
164
221
|
getClient: () => Promise<RedisLike | undefined> = getRedisClient,
|
|
@@ -182,8 +239,9 @@ export function createRedisCacheHandler(
|
|
|
182
239
|
const tags = [
|
|
183
240
|
...new Set([...(entry.tags ?? []), ...(ctx?.tags ?? []), ...(ctx?.softTags ?? [])]),
|
|
184
241
|
];
|
|
242
|
+
const cacheControl = cacheControlOf(entry);
|
|
185
243
|
if (!tags.length) {
|
|
186
|
-
return { lastModified: entry.lastModified, value: entry.value };
|
|
244
|
+
return { lastModified: entry.lastModified, value: entry.value, cacheControl };
|
|
187
245
|
}
|
|
188
246
|
const [expired, stale] = await Promise.all([
|
|
189
247
|
client.mGet(tags.map((tag) => k.expired + tag)),
|
|
@@ -203,9 +261,10 @@ export function createRedisCacheHandler(
|
|
|
203
261
|
return {
|
|
204
262
|
lastModified: Math.min(entry.lastModified, now - entry.revalidate * 1000 - 1),
|
|
205
263
|
value: entry.value,
|
|
264
|
+
cacheControl,
|
|
206
265
|
};
|
|
207
266
|
}
|
|
208
|
-
return { lastModified: entry.lastModified, value: entry.value };
|
|
267
|
+
return { lastModified: entry.lastModified, value: entry.value, cacheControl };
|
|
209
268
|
} catch {
|
|
210
269
|
return null;
|
|
211
270
|
}
|
|
@@ -221,10 +280,13 @@ export function createRedisCacheHandler(
|
|
|
221
280
|
await client.del([k.entry + key, k.meta + key]);
|
|
222
281
|
return;
|
|
223
282
|
}
|
|
283
|
+
const revalidate = revalidateOf(data, ctx);
|
|
224
284
|
const entry: StoredEntry = {
|
|
225
285
|
lastModified: Date.now(),
|
|
226
286
|
tags: entryTags(data, ctx),
|
|
227
|
-
revalidate
|
|
287
|
+
revalidate,
|
|
288
|
+
cacheControl:
|
|
289
|
+
revalidate === null ? undefined : { revalidate, expire: ctx?.cacheControl?.expire },
|
|
228
290
|
value: data,
|
|
229
291
|
};
|
|
230
292
|
const raw = encode(entry);
|
package/src/client/user.tsx
CHANGED
|
@@ -17,8 +17,9 @@ export const UserContext = createContext<UserContextType>({
|
|
|
17
17
|
},
|
|
18
18
|
});
|
|
19
19
|
|
|
20
|
-
// One `/auth/me` request per
|
|
21
|
-
//
|
|
20
|
+
// One `/auth/me` request per page load, shared by every UserProvider mount and client navigation;
|
|
21
|
+
// `setUser` and `invalidateUser` keep it current after login/logout. Not persisted (sessionStorage): a stored user
|
|
22
|
+
// would go stale after a logout or login in another tab. Pass `initialUser` where the server knows the user.
|
|
22
23
|
let mePromise: Promise<UserValue> | undefined;
|
|
23
24
|
|
|
24
25
|
function getMe(): Promise<UserValue> {
|
|
@@ -1,3 +1,9 @@
|
|
|
1
1
|
// `next.config` `cacheHandler`: the shared Redis incremental cache (ISR, route handlers, data cache).
|
|
2
|
-
export {
|
|
2
|
+
export {
|
|
3
|
+
connectRedisClient,
|
|
4
|
+
createRedisCacheHandler,
|
|
5
|
+
decode,
|
|
6
|
+
encode,
|
|
7
|
+
getRedisClient,
|
|
8
|
+
} from '../cache-handler/redis';
|
|
3
9
|
export { default } from '../cache-handler/redis';
|
|
@@ -6,6 +6,12 @@ export async function registerIntrumentation() {
|
|
|
6
6
|
// the cache panel (Bowl admin) reaches this site runtime in process instead of over HTTP
|
|
7
7
|
const { registerLocalCacheExecutor } = await import('../server/cache/local-executor');
|
|
8
8
|
registerLocalCacheExecutor();
|
|
9
|
+
if (process.env.REDIS_URL && process.env.NEXT_PHASE !== 'phase-production-build') {
|
|
10
|
+
// connect the shared cache client before the first request, so a cold instance already reads Redis (at most
|
|
11
|
+
// the 2 s connect timeout while Redis is down; pages then render uncached)
|
|
12
|
+
const { connectRedisClient } = await import('../cache-handler/redis');
|
|
13
|
+
await connectRedisClient();
|
|
14
|
+
}
|
|
9
15
|
}
|
|
10
16
|
if (process.env.NEXT_PUBLIC_SENTRY_DSN) {
|
|
11
17
|
if (process.env.NEXT_RUNTIME === 'nodejs') {
|
package/src/lib/const.ts
CHANGED
|
@@ -2,6 +2,16 @@ import type { Config, User } from '@websolutespa/payload-plugin-bowl';
|
|
|
2
2
|
|
|
3
3
|
export const guest = { collection: 'users', roles: ['guest'] } as User & Config['user'];
|
|
4
4
|
|
|
5
|
+
/** Roles that read drafts and may turn Draft Mode on: Bowl's editing roles (`rolesUser`). */
|
|
6
|
+
export const PREVIEW_ROLES = ['admin', 'contributor', 'editor'];
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The reader of Draft Mode renders without an editor session (static templates pass no headers; the admin may run
|
|
10
|
+
* on another origin). Draft Mode is turned on only for editors (`getPreviewHandler`) and Bowl serves drafts to the
|
|
11
|
+
* editing roles only, so these reads use an editing role. `getPayload` uses it only while Next.js Draft Mode is on.
|
|
12
|
+
*/
|
|
13
|
+
export const previewer = { collection: 'users', roles: ['editor'] } as User & Config['user'];
|
|
14
|
+
|
|
5
15
|
/**
|
|
6
16
|
* Default population depth for page documents read by `createPageContext`.
|
|
7
17
|
*
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @vitest-environment node
|
|
2
2
|
|
|
3
3
|
import type { ILayout, IPage } from '@websolutespa/bom-core';
|
|
4
|
-
import { describe, expect, test } from 'vitest';
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
|
|
5
5
|
import {
|
|
6
6
|
buildPageMetadata,
|
|
7
7
|
getPaginationQuery,
|
|
@@ -56,6 +56,38 @@ describe('getPaginationQuery', () => {
|
|
|
56
56
|
});
|
|
57
57
|
|
|
58
58
|
describe('buildPageMetadata', () => {
|
|
59
|
+
// the page's own robots apply in production; elsewhere every page is noindex (tested below)
|
|
60
|
+
beforeEach(() => {
|
|
61
|
+
process.env.PRODUCTION = 'true';
|
|
62
|
+
});
|
|
63
|
+
afterEach(() => {
|
|
64
|
+
delete process.env.PRODUCTION;
|
|
65
|
+
delete process.env.NOINDEX;
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('is noindex outside production, with NOINDEX=true, or when not indexable', () => {
|
|
69
|
+
const indexed = { ...page, meta: { robots: 'index, follow' } } as unknown as IPage;
|
|
70
|
+
expect(buildPageMetadata(indexed, layout, { baseUrl }).robots).toBe('index, follow');
|
|
71
|
+
expect(buildPageMetadata(indexed, layout, { baseUrl, indexable: false }).robots).toBe(
|
|
72
|
+
'noindex, nofollow'
|
|
73
|
+
);
|
|
74
|
+
expect(
|
|
75
|
+
buildPageMetadata(indexed, layout, {
|
|
76
|
+
baseUrl,
|
|
77
|
+
indexable: (item) => item.title !== page.title,
|
|
78
|
+
}).robots
|
|
79
|
+
).toBe('noindex, nofollow');
|
|
80
|
+
process.env.NOINDEX = 'true';
|
|
81
|
+
expect(buildPageMetadata(indexed, layout, { baseUrl }).robots).toBe('noindex, nofollow');
|
|
82
|
+
delete process.env.NOINDEX;
|
|
83
|
+
delete process.env.PRODUCTION;
|
|
84
|
+
expect(buildPageMetadata(indexed, layout, { baseUrl }).robots).toBe('noindex, nofollow');
|
|
85
|
+
// an explicit decision wins over the deployment policy
|
|
86
|
+
expect(buildPageMetadata(indexed, layout, { baseUrl, indexable: true }).robots).toBe(
|
|
87
|
+
'index, follow'
|
|
88
|
+
);
|
|
89
|
+
});
|
|
90
|
+
|
|
59
91
|
test('builds title, description, canonical, hreflang, robots and social tags', () => {
|
|
60
92
|
const metadata = buildPageMetadata(page, layout, {
|
|
61
93
|
baseUrl,
|
package/src/lib/page-metadata.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
defaultLocale,
|
|
3
3
|
defaultMarket,
|
|
4
|
+
getIsProduction,
|
|
4
5
|
getMetaRobots,
|
|
5
6
|
ILayout,
|
|
6
7
|
IMedia,
|
|
@@ -36,10 +37,24 @@ export type PageMetadataOptions = {
|
|
|
36
37
|
baseUrl?: string;
|
|
37
38
|
/** Request search params; `pagination[page]` > 1 is kept in the canonical URL. */
|
|
38
39
|
searchParams?: PageMetadataSearchParams;
|
|
40
|
+
/**
|
|
41
|
+
* Whether search engines may index the page. When false (or a function returning false), `robots` is
|
|
42
|
+
* `noindex, nofollow`, over the page's own `meta.robots`. Default: {@link isIndexableDeployment}, so staging
|
|
43
|
+
* and preview deployments are never indexed.
|
|
44
|
+
*/
|
|
45
|
+
indexable?: boolean | ((page: IPage) => boolean);
|
|
39
46
|
/** Per-page override applied to the computed metadata. */
|
|
40
47
|
extend?: (metadata: Metadata, context: PageMetadataContext) => Metadata;
|
|
41
48
|
};
|
|
42
49
|
|
|
50
|
+
/**
|
|
51
|
+
* The deployment policy: pages are indexable only in production (`PRODUCTION=true`, as the BOM 3 `Meta` component
|
|
52
|
+
* required) and unless `NOINDEX=true`. Every other deployment (staging, previews, local) is `noindex`.
|
|
53
|
+
*/
|
|
54
|
+
export function isIndexableDeployment(env: NodeJS.ProcessEnv = process.env): boolean {
|
|
55
|
+
return getIsProduction() && env.NOINDEX !== 'true';
|
|
56
|
+
}
|
|
57
|
+
|
|
43
58
|
type PageMetaFields = {
|
|
44
59
|
title?: string;
|
|
45
60
|
description?: string;
|
|
@@ -194,7 +209,11 @@ export function buildPageMetadata(
|
|
|
194
209
|
const canonical = canonicalBase
|
|
195
210
|
? `${canonicalBase}${getPaginationQuery(options.searchParams)}`
|
|
196
211
|
: undefined;
|
|
197
|
-
const
|
|
212
|
+
const indexable =
|
|
213
|
+
typeof options.indexable === 'function'
|
|
214
|
+
? options.indexable(page)
|
|
215
|
+
: (options.indexable ?? isIndexableDeployment());
|
|
216
|
+
const robots = indexable ? getMetaRobots(meta) : 'noindex, nofollow';
|
|
198
217
|
|
|
199
218
|
const languages: Record<string, string> = {};
|
|
200
219
|
if (layout) {
|
|
@@ -1,4 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import {
|
|
2
|
+
connectRedisClient,
|
|
3
|
+
keys,
|
|
4
|
+
redisPrefix,
|
|
5
|
+
type RedisLike,
|
|
6
|
+
} from '../../../cache-handler/redis';
|
|
2
7
|
import { tagState, type UseCacheMeta } from '../../../cache-handlers/default';
|
|
3
8
|
import { explicitTags } from './filesystem';
|
|
4
9
|
import { parseRouteCacheKey } from './route-cache-key';
|
|
@@ -26,7 +31,8 @@ const maxEntries = 20_000;
|
|
|
26
31
|
* Entries written by an older handler without meta keys are not listed.
|
|
27
32
|
*/
|
|
28
33
|
export function createRedisInspector({
|
|
29
|
-
|
|
34
|
+
// the panel may wait for the connection: on a cold instance the client is not ready yet
|
|
35
|
+
getClient = connectRedisClient as () => Promise<RedisScanner | undefined>,
|
|
30
36
|
prefix = redisPrefix(),
|
|
31
37
|
}: { getClient?: () => Promise<RedisScanner | undefined>; prefix?: string } = {}): CacheInspector {
|
|
32
38
|
const k = keys(prefix);
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// @vitest-environment node
|
|
2
|
+
|
|
3
|
+
import { NextRequest } from 'next/server';
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
|
|
5
|
+
|
|
6
|
+
const enable = vi.fn();
|
|
7
|
+
vi.mock('next/headers', () => ({ draftMode: async () => ({ enable, isEnabled: false }) }));
|
|
8
|
+
|
|
9
|
+
// the users the mocked Payload knows, by Authorization header or cookie
|
|
10
|
+
const sessions: Record<string, { roles: string[] }> = {
|
|
11
|
+
'JWT editor-token': { roles: ['editor'] },
|
|
12
|
+
'JWT user-token': { roles: ['user'] },
|
|
13
|
+
'payload-token=admin-cookie': { roles: ['admin'] },
|
|
14
|
+
};
|
|
15
|
+
vi.mock('payload', () => ({
|
|
16
|
+
getPayload: async () => ({
|
|
17
|
+
auth: async ({ headers }: { headers: Headers }) => ({
|
|
18
|
+
user:
|
|
19
|
+
sessions[headers.get('authorization') ?? ''] ??
|
|
20
|
+
sessions[headers.get('cookie') ?? ''] ??
|
|
21
|
+
null,
|
|
22
|
+
}),
|
|
23
|
+
}),
|
|
24
|
+
}));
|
|
25
|
+
|
|
26
|
+
const { getPreviewHandler, previewHandler } = await import('./preview.handler');
|
|
27
|
+
|
|
28
|
+
const page = 'marketId=ww&localeId=en&templateId=contact&documentId=6a6b33177d8f191df34b33a3';
|
|
29
|
+
const request = (query: string, headers: Record<string, string> = {}) =>
|
|
30
|
+
new NextRequest(`http://localhost:3000/api/-preview?${query}`, { headers });
|
|
31
|
+
const handler = getPreviewHandler(Promise.resolve({} as never));
|
|
32
|
+
|
|
33
|
+
beforeEach(() => {
|
|
34
|
+
process.env.NEXT_PUBLIC_URL = 'http://localhost:3000';
|
|
35
|
+
process.env.MIXER_SECRET = 'mixer-secret';
|
|
36
|
+
enable.mockClear();
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
afterEach(() => {
|
|
40
|
+
delete process.env.MIXER_SECRET;
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
describe('getPreviewHandler', () => {
|
|
44
|
+
test('refuses an anonymous visitor and sets no Draft Mode cookie', async () => {
|
|
45
|
+
const res = await handler(request(page));
|
|
46
|
+
expect(res.status).toBe(401);
|
|
47
|
+
expect(enable).not.toHaveBeenCalled();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
test('refuses a logged-in visitor without an editing role, and an invalid token', async () => {
|
|
51
|
+
expect((await handler(request(page, { authorization: 'JWT user-token' }))).status).toBe(401);
|
|
52
|
+
expect((await handler(request(`${page}&_token=forged`))).status).toBe(401);
|
|
53
|
+
expect(enable).not.toHaveBeenCalled();
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
test('lets an editor in through the admin session cookie or the _token of the preview URL', async () => {
|
|
57
|
+
const byCookie = await handler(request(page, { cookie: 'payload-token=admin-cookie' }));
|
|
58
|
+
expect(byCookie.status).toBe(303);
|
|
59
|
+
expect(byCookie.headers.get('location')).toBe(
|
|
60
|
+
'http://localhost:3000/ww/en/contact/6a6b33177d8f191df34b33a3'
|
|
61
|
+
);
|
|
62
|
+
const byToken = await handler(request(`${page}&_token=editor-token&_live=true`));
|
|
63
|
+
expect(byToken.status).toBe(303);
|
|
64
|
+
expect(byToken.headers.get('location')).toMatch(/\?_live=true$/);
|
|
65
|
+
expect(enable).toHaveBeenCalledTimes(2);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
test('accepts MIXER_SECRET, never an empty one', async () => {
|
|
69
|
+
expect((await handler(request(`${page}&secret=mixer-secret`))).status).toBe(303);
|
|
70
|
+
delete process.env.MIXER_SECRET;
|
|
71
|
+
expect((await handler(request(`${page}&secret=`))).status).toBe(401);
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
test('keeps the redirect on this site', async () => {
|
|
75
|
+
const res = await handler(
|
|
76
|
+
request('marketId=ww&localeId=en&templateId=..%2F%2Fevil.com&documentId=1', {
|
|
77
|
+
cookie: 'payload-token=admin-cookie',
|
|
78
|
+
})
|
|
79
|
+
);
|
|
80
|
+
expect(res.status).toBe(400);
|
|
81
|
+
expect(enable).not.toHaveBeenCalled();
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
describe('previewHandler (deprecated)', () => {
|
|
86
|
+
test('turns Draft Mode on only with MIXER_SECRET', async () => {
|
|
87
|
+
expect(
|
|
88
|
+
(await previewHandler(request(page, { cookie: 'payload-token=admin-cookie' }))).status
|
|
89
|
+
).toBe(401);
|
|
90
|
+
expect((await previewHandler(request(`${page}&secret=mixer-secret`))).status).toBe(303);
|
|
91
|
+
});
|
|
92
|
+
});
|
|
@@ -1,63 +1,95 @@
|
|
|
1
1
|
import { draftMode } from 'next/headers';
|
|
2
2
|
import { NextRequest, NextResponse } from 'next/server';
|
|
3
|
+
import { getPayload, SanitizedConfig } from 'payload';
|
|
4
|
+
import { PREVIEW_ROLES } from '../../lib/const';
|
|
3
5
|
|
|
4
6
|
// http://localhost:3000/api/-preview?marketId=ww&localeId=it&templateId=homepage&documentId=6a6b33177d8f191df34b33a3
|
|
5
7
|
|
|
6
|
-
export
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
8
|
+
export { PREVIEW_ROLES };
|
|
9
|
+
|
|
10
|
+
type PreviewParams = {
|
|
11
|
+
marketId?: string;
|
|
12
|
+
localeId?: string;
|
|
13
|
+
templateId?: string;
|
|
14
|
+
documentId?: string;
|
|
15
|
+
_live?: string;
|
|
16
|
+
/** the editor's token, added by Bowl to the admin's preview URL */
|
|
17
|
+
_token?: string;
|
|
18
|
+
/** `MIXER_SECRET`, for a caller without an editor session */
|
|
19
|
+
secret?: string;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
// path segments only: the destination stays on this site
|
|
23
|
+
const SEGMENT = /^[\w-]+$/;
|
|
24
|
+
|
|
25
|
+
function hasSecret(params: PreviewParams): boolean {
|
|
26
|
+
return Boolean(process.env.MIXER_SECRET) && params.secret === process.env.MIXER_SECRET;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Turns Draft Mode on and redirects to the internal page path. */
|
|
30
|
+
async function enablePreview(params: PreviewParams): Promise<Response> {
|
|
31
|
+
const { marketId, localeId, templateId, documentId, _live } = params;
|
|
32
|
+
if (
|
|
33
|
+
![marketId, localeId, templateId, documentId].every((value) => value && SEGMENT.test(value))
|
|
34
|
+
) {
|
|
35
|
+
return new Response('Bad Request', { status: 400 });
|
|
20
36
|
}
|
|
21
|
-
*/
|
|
22
|
-
/*
|
|
23
|
-
const headersList = await headers()
|
|
24
|
-
const userAgent = headersList.get('user-agent')
|
|
25
|
-
*/
|
|
26
|
-
const { marketId, localeId, templateId, documentId, _status, _live } = params;
|
|
27
37
|
const destination = `/${marketId}/${localeId}/${templateId}/${documentId}${_live ? '?_live=true' : ''}`;
|
|
28
|
-
/*
|
|
29
|
-
response.setPreviewData({ _status });
|
|
30
|
-
response.setDraftMode({ enable: true });
|
|
31
|
-
response.redirect(307, destination);
|
|
32
|
-
redirect(destination, RedirectType.replace);
|
|
33
|
-
*/
|
|
34
38
|
const draft = await draftMode();
|
|
35
39
|
draft.enable();
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
40
|
+
return NextResponse.redirect(`${process.env.NEXT_PUBLIC_URL}${destination}`, { status: 303 });
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* The `/api/-preview` route: turns Draft Mode on for an editor and redirects to the page. Draft Mode shows
|
|
45
|
+
* unpublished content (bom-next reads it with an editing role), so only these callers get the cookie:
|
|
46
|
+
* - a logged-in editor: the admin session cookie (admin and site on one origin), or the `_token` Bowl adds to
|
|
47
|
+
* the admin's preview URL (admin on another origin);
|
|
48
|
+
* - `secret` equal to `MIXER_SECRET`.
|
|
49
|
+
* Everyone else gets 401 and no cookie.
|
|
50
|
+
*
|
|
51
|
+
* ```ts
|
|
52
|
+
* // src/app/api/-preview/route.ts
|
|
53
|
+
* export const GET = getPreviewHandler(config);
|
|
54
|
+
* ```
|
|
55
|
+
*/
|
|
56
|
+
export function getPreviewHandler(
|
|
57
|
+
config: Promise<SanitizedConfig>,
|
|
58
|
+
{ roles = PREVIEW_ROLES }: { roles?: string[] } = {}
|
|
59
|
+
) {
|
|
60
|
+
return async function (request: NextRequest): Promise<Response> {
|
|
61
|
+
const params = Object.fromEntries(request.nextUrl.searchParams) as PreviewParams;
|
|
62
|
+
if (!hasSecret(params)) {
|
|
63
|
+
const payload = await getPayload({ config });
|
|
64
|
+
const isEditor = async (headers: Headers) => {
|
|
65
|
+
try {
|
|
66
|
+
const { user } = await payload.auth({ headers });
|
|
67
|
+
const userRoles = (user as { roles?: string[] } | null)?.roles ?? [];
|
|
68
|
+
return userRoles.some((role) => roles.includes(role));
|
|
69
|
+
} catch {
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
const allowed =
|
|
74
|
+
(await isEditor(request.headers)) ||
|
|
75
|
+
(Boolean(params._token) &&
|
|
76
|
+
(await isEditor(new Headers({ authorization: `JWT ${params._token}` }))));
|
|
77
|
+
if (!allowed) {
|
|
78
|
+
return new Response('Unauthorized', { status: 401 });
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return enablePreview(params);
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* @deprecated Use `getPreviewHandler(config)`, which also accepts an editor session. Without the config this
|
|
87
|
+
* handler cannot authenticate a user, so it turns Draft Mode on only with `secret` equal to `MIXER_SECRET`.
|
|
88
|
+
*/
|
|
89
|
+
export async function previewHandler(request: NextRequest): Promise<Response> {
|
|
90
|
+
const params = Object.fromEntries(request.nextUrl.searchParams) as PreviewParams;
|
|
91
|
+
if (!hasSecret(params)) {
|
|
92
|
+
return new Response('Unauthorized', { status: 401 });
|
|
93
|
+
}
|
|
94
|
+
return enablePreview(params);
|
|
63
95
|
}
|
package/src/server/mixer.ts
CHANGED
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
TypedLocale,
|
|
25
25
|
} from 'payload';
|
|
26
26
|
import { cache } from 'react';
|
|
27
|
-
import { guest } from '../lib/const';
|
|
27
|
+
import { guest, PREVIEW_ROLES, previewer } from '../lib/const';
|
|
28
28
|
import { debug } from '../lib/debug';
|
|
29
29
|
import { TtlCache } from '../lib/ttl-cache';
|
|
30
30
|
import type {
|
|
@@ -272,6 +272,12 @@ async function loadMixerContext({
|
|
|
272
272
|
};
|
|
273
273
|
}
|
|
274
274
|
|
|
275
|
+
/** Whether the user has an editing role, the ones Bowl serves drafts to. */
|
|
276
|
+
function hasPreviewRole(user: User | null | undefined): boolean {
|
|
277
|
+
const roles = ((user as { roles?: string[] } | null)?.roles ?? []) as string[];
|
|
278
|
+
return roles.some((role) => PREVIEW_ROLES.includes(role));
|
|
279
|
+
}
|
|
280
|
+
|
|
275
281
|
/**
|
|
276
282
|
* Resolves a draft option to a boolean.
|
|
277
283
|
* Defaults to `false`. `'auto'` is an explicit opt-in that reads Next's `draftMode()`
|
|
@@ -304,7 +310,7 @@ export async function resolveDraft(draft: DraftOption = false): Promise<boolean>
|
|
|
304
310
|
export async function getPayload({
|
|
305
311
|
config,
|
|
306
312
|
headers,
|
|
307
|
-
draft = false,
|
|
313
|
+
draft: requestedDraft = false,
|
|
308
314
|
}: {
|
|
309
315
|
config: Promise<SanitizedConfig>;
|
|
310
316
|
headers?: ReadonlyHeaders;
|
|
@@ -325,6 +331,17 @@ export async function getPayload({
|
|
|
325
331
|
}
|
|
326
332
|
}
|
|
327
333
|
|
|
334
|
+
// a draft read as a non-editor: the previewer identity while Draft Mode is on (an editor turned it on, see
|
|
335
|
+
// getPreviewHandler), the published site otherwise. Bowl serves drafts to the editing roles only.
|
|
336
|
+
let draft = requestedDraft;
|
|
337
|
+
if (draft && !hasPreviewRole(user)) {
|
|
338
|
+
// only an actual Draft Mode request: the cookie read happens on the draft path alone, which is dynamic anyway
|
|
339
|
+
draft = await resolveDraft('auto');
|
|
340
|
+
if (draft) {
|
|
341
|
+
user = previewer;
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
328
345
|
// Draft contexts bypass the shared cache, so share them at least between
|
|
329
346
|
// the callers of this instance (one request when obtained per request).
|
|
330
347
|
const contexts = new Map<string, Promise<MixerContext>>();
|