@nocode-factory/sanity-kit 2.10.2 → 2.12.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/dist/index.d.ts +1 -1
- package/dist/index.js +104 -74
- package/dist/index.js.map +1 -1
- package/dist/web-server.d.ts +50 -1
- package/dist/web-server.js +158 -16
- package/dist/web-server.js.map +1 -1
- package/dist/web.js +44 -3
- package/dist/web.js.map +1 -1
- package/package.json +1 -1
- package/src/hooks/useOpenOnline.ts +5 -3
- package/src/hooks/usePreviewTarget.ts +9 -6
- package/src/lib/studioLinks.ts +39 -5
- package/src/tools/navbar/PreviewLauncher.tsx +47 -57
- package/src/tools/pages/PreviewTarget.tsx +5 -1
- package/src/version.ts +1 -1
- package/src/web/PreviewBanner.tsx +67 -2
- package/src/web/dataMode.ts +27 -0
- package/src/web/draftModeToggle.ts +14 -3
- package/src/web/enableDraftMode.ts +62 -0
- package/src/web/previewGrant.ts +56 -14
- package/src/web/previewSession.ts +54 -0
- package/src/web/server.ts +4 -0
|
@@ -3,13 +3,19 @@ import {useRouter} from 'sanity/router'
|
|
|
3
3
|
import type {ToolMenuProps} from 'sanity'
|
|
4
4
|
import {InlinePopover} from '../../ui/Popover'
|
|
5
5
|
import {KitProvider, useKitConfig} from '../../context/KitContext'
|
|
6
|
-
import {presentationPath,
|
|
6
|
+
import {presentationPath, previewTargets, type PreviewPerspective} from '../../lib/studioLinks'
|
|
7
7
|
import {useOpenOnline} from '../../hooks/useOpenOnline'
|
|
8
8
|
import type {ConfigIssue, NcfEnvironment, ResolvedKitConfig} from '../../config/types'
|
|
9
9
|
import {EyeOpenIcon} from '@sanity/icons/EyeOpen'
|
|
10
10
|
import {LaunchIcon} from '@sanity/icons/Launch'
|
|
11
|
-
import {BORDER} from '../../ui/tokens'
|
|
12
11
|
import {NcfKitUpdate} from './KitUpdate'
|
|
12
|
+
|
|
13
|
+
/** Couleurs des trois cibles : brouillons (jaune pastel), préprod en ligne (vert pastel), prod (vert plein). */
|
|
14
|
+
const TARGET_TONES = {
|
|
15
|
+
draft: {background: '#fdf1c7', color: '#4a3a07'},
|
|
16
|
+
live: {background: '#d9f2df', color: '#14532d'},
|
|
17
|
+
prod: {background: '#15803d', color: '#ffffff'},
|
|
18
|
+
} as const
|
|
13
19
|
import {NcfToolButtons} from './ToolButtons'
|
|
14
20
|
|
|
15
21
|
/**
|
|
@@ -88,62 +94,46 @@ export function NcfPreviewLauncher(props: ToolMenuProps) {
|
|
|
88
94
|
Cliquer : ouvre dans le Studio. L'icône ↗ : ouvre le site en ligne.
|
|
89
95
|
</Text>
|
|
90
96
|
</Box>
|
|
91
|
-
{environments.map((
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
title="Ouvrir dans le Studio (Presentation)"
|
|
116
|
-
onMouseEnter={(event) => {
|
|
117
|
-
event.currentTarget.style.background =
|
|
118
|
-
'var(--card-muted-bg-color, rgba(127,127,127,0.12))'
|
|
119
|
-
}}
|
|
120
|
-
onMouseLeave={(event) => {
|
|
121
|
-
event.currentTarget.style.background = 'transparent'
|
|
122
|
-
}}
|
|
123
|
-
>
|
|
124
|
-
<Stack gap={1} style={{minWidth: 0}}>
|
|
125
|
-
<Text size={1}>{option.label}</Text>
|
|
126
|
-
<Text size={0} muted textOverflow="ellipsis">
|
|
127
|
-
{option.hint}
|
|
128
|
-
</Text>
|
|
129
|
-
</Stack>
|
|
130
|
-
</Flex>
|
|
131
|
-
<Button
|
|
132
|
-
mode="bleed"
|
|
133
|
-
padding={2}
|
|
134
|
-
fontSize={1}
|
|
135
|
-
icon={LaunchIcon}
|
|
136
|
-
title="Ouvrir le site en ligne, dans un nouvel onglet"
|
|
137
|
-
aria-label={`Ouvrir ${environment.label} en ligne (${option.label})`}
|
|
138
|
-
onClick={() => {
|
|
139
|
-
openOnline(environment, option.id)
|
|
140
|
-
close()
|
|
141
|
-
}}
|
|
142
|
-
/>
|
|
97
|
+
{previewTargets(environments, config.previewUrl).map((target) => {
|
|
98
|
+
const tone = TARGET_TONES[target.tone]
|
|
99
|
+
return (
|
|
100
|
+
<Flex key={`${target.environment.id}-${target.perspective}`} align="center" gap={1}>
|
|
101
|
+
<Flex
|
|
102
|
+
align="center"
|
|
103
|
+
gap={2}
|
|
104
|
+
flex={1}
|
|
105
|
+
padding={2}
|
|
106
|
+
onClick={() => {
|
|
107
|
+
openInStudio(target.environment, target.perspective)
|
|
108
|
+
close()
|
|
109
|
+
}}
|
|
110
|
+
style={{cursor: 'pointer', borderRadius: 6, minWidth: 0, background: tone.background, color: tone.color}}
|
|
111
|
+
title="Ouvrir dans le Studio (Presentation)"
|
|
112
|
+
>
|
|
113
|
+
<Stack gap={1} style={{minWidth: 0}}>
|
|
114
|
+
<Text size={1} weight="semibold" style={{color: tone.color}}>
|
|
115
|
+
{target.label}
|
|
116
|
+
</Text>
|
|
117
|
+
<Text size={0} style={{color: tone.color, opacity: 0.8}} textOverflow="ellipsis">
|
|
118
|
+
{target.hint}
|
|
119
|
+
</Text>
|
|
120
|
+
</Stack>
|
|
143
121
|
</Flex>
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
122
|
+
<Button
|
|
123
|
+
mode="bleed"
|
|
124
|
+
padding={2}
|
|
125
|
+
fontSize={1}
|
|
126
|
+
icon={LaunchIcon}
|
|
127
|
+
title="Ouvrir le site en ligne, dans un nouvel onglet"
|
|
128
|
+
aria-label={`Ouvrir ${target.label} dans un nouvel onglet`}
|
|
129
|
+
onClick={() => {
|
|
130
|
+
openOnline(target.environment, target.perspective)
|
|
131
|
+
close()
|
|
132
|
+
}}
|
|
133
|
+
/>
|
|
134
|
+
</Flex>
|
|
135
|
+
)
|
|
136
|
+
})}
|
|
147
137
|
</Stack>
|
|
148
138
|
)}
|
|
149
139
|
</InlinePopover>
|
|
@@ -42,6 +42,8 @@ export function PreviewTarget(props: PreviewTargetProps) {
|
|
|
42
42
|
const {environments, environmentId, perspective, onEnvironment, onPerspective} = props
|
|
43
43
|
const {onCustomUrl, customUrl, productionUrl} = props
|
|
44
44
|
const current = environments.find((environment) => environment.id === environmentId)
|
|
45
|
+
// La production n'a pas de brouillons : seul « En ligne » est proposé.
|
|
46
|
+
const onProduction = Boolean(current && productionUrl && current.url.replace(/\/+$/, '') === productionUrl.replace(/\/+$/, '')) || current?.id === 'production'
|
|
45
47
|
|
|
46
48
|
return (
|
|
47
49
|
<Box style={{flex: 'none'}}>
|
|
@@ -49,15 +51,17 @@ export function PreviewTarget(props: PreviewTargetProps) {
|
|
|
49
51
|
<Flex gap={1} align="center">
|
|
50
52
|
{PERSPECTIVES.map((option) => {
|
|
51
53
|
const active = option.id === perspective
|
|
54
|
+
const unavailable = onProduction && option.id === 'drafts'
|
|
52
55
|
return (
|
|
53
56
|
<Button
|
|
54
57
|
key={option.id}
|
|
58
|
+
disabled={unavailable}
|
|
55
59
|
mode={active ? 'default' : 'bleed'}
|
|
56
60
|
tone={active ? 'primary' : 'default'}
|
|
57
61
|
fontSize={1}
|
|
58
62
|
padding={2}
|
|
59
63
|
text={option.label}
|
|
60
|
-
title={option.hint}
|
|
64
|
+
title={unavailable ? "La production ne montre que le contenu en ligne : les brouillons se relisent sur la préprod." : option.hint}
|
|
61
65
|
aria-pressed={active}
|
|
62
66
|
onClick={() => onPerspective(option.id)}
|
|
63
67
|
/>
|
package/src/version.ts
CHANGED
|
@@ -1,7 +1,24 @@
|
|
|
1
1
|
'use client'
|
|
2
2
|
|
|
3
3
|
import {usePathname} from 'next/navigation'
|
|
4
|
-
import type
|
|
4
|
+
import {useEffect, useState, useSyncExternalStore, type CSSProperties} from 'react'
|
|
5
|
+
|
|
6
|
+
/** Mêmes noms que le garde (`previewGrant.ts`), sans importer de code serveur. */
|
|
7
|
+
const GRANT_PARAM = 'ncf_preview'
|
|
8
|
+
const GRANT_COOKIE = 'ncf_preview_grant'
|
|
9
|
+
|
|
10
|
+
const noSubscribe = () => () => {}
|
|
11
|
+
function readGrant(): string | null {
|
|
12
|
+
const match = document.cookie.match(new RegExp(`(?:^|; )${GRANT_COOKIE}=([^;]*)`))
|
|
13
|
+
return match?.[1] ? decodeURIComponent(match[1]) : null
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Adresse courante avec la clé de préversion (partageable telle quelle). */
|
|
17
|
+
function shareableUrl(grant: string): string {
|
|
18
|
+
const url = new URL(window.location.href)
|
|
19
|
+
url.searchParams.set(GRANT_PARAM, grant)
|
|
20
|
+
return url.toString()
|
|
21
|
+
}
|
|
5
22
|
|
|
6
23
|
export interface PreviewBannerProps {
|
|
7
24
|
/** Le site affiche-t-il actuellement les brouillons ? */
|
|
@@ -31,7 +48,35 @@ export interface PreviewBannerProps {
|
|
|
31
48
|
export function NcfPreviewBanner(props: PreviewBannerProps) {
|
|
32
49
|
const {isDraft, togglePath = '/api/draft-mode/toggle', label = 'Préversion'} = props
|
|
33
50
|
const pathname = usePathname()
|
|
34
|
-
|
|
51
|
+
// Clé de préversion mémorisée par le garde (absente avec une session Presentation).
|
|
52
|
+
const grant = useSyncExternalStore(noSubscribe, readGrant, () => null)
|
|
53
|
+
const [copied, setCopied] = useState(false)
|
|
54
|
+
|
|
55
|
+
// Après une navigation côté client, Next affiche l'URL du lien, sans la clé : on
|
|
56
|
+
// la remet, pour que l'adresse copiée depuis la barre ouvre la préversion chez
|
|
57
|
+
// n'importe qui (un client, sans compte).
|
|
58
|
+
useEffect(() => {
|
|
59
|
+
if (!grant) return
|
|
60
|
+
const url = new URL(window.location.href)
|
|
61
|
+
if (url.searchParams.get(GRANT_PARAM) === grant) return
|
|
62
|
+
url.searchParams.set(GRANT_PARAM, grant)
|
|
63
|
+
window.history.replaceState(window.history.state, '', url.toString())
|
|
64
|
+
}, [grant, pathname])
|
|
65
|
+
|
|
66
|
+
// Retour de bascule sur la même page, clé comprise.
|
|
67
|
+
const backPath = grant ? `${pathname || '/'}?${GRANT_PARAM}=${encodeURIComponent(grant)}` : pathname || '/'
|
|
68
|
+
const back = encodeURIComponent(backPath)
|
|
69
|
+
|
|
70
|
+
const share = async () => {
|
|
71
|
+
if (!grant) return
|
|
72
|
+
try {
|
|
73
|
+
await navigator.clipboard.writeText(shareableUrl(grant))
|
|
74
|
+
setCopied(true)
|
|
75
|
+
window.setTimeout(() => setCopied(false), 2000)
|
|
76
|
+
} catch {
|
|
77
|
+
// Presse-papiers refusé : l'adresse de la barre contient déjà la clé.
|
|
78
|
+
}
|
|
79
|
+
}
|
|
35
80
|
|
|
36
81
|
const href = (enable: boolean) => `${togglePath}?enable=${enable}&redirect=${back}`
|
|
37
82
|
|
|
@@ -66,6 +111,15 @@ export function NcfPreviewBanner(props: PreviewBannerProps) {
|
|
|
66
111
|
En ligne
|
|
67
112
|
</a>
|
|
68
113
|
</span>
|
|
114
|
+
|
|
115
|
+
{grant && (
|
|
116
|
+
<>
|
|
117
|
+
<span aria-hidden style={divider} />
|
|
118
|
+
<button type="button" onClick={share} title="Copier l'adresse de cette page, clé de préversion comprise" style={shareButton}>
|
|
119
|
+
{copied ? 'Lien copié' : 'Copier le lien'}
|
|
120
|
+
</button>
|
|
121
|
+
</>
|
|
122
|
+
)}
|
|
69
123
|
</div>
|
|
70
124
|
</div>
|
|
71
125
|
)
|
|
@@ -113,3 +167,14 @@ const segmentBase: CSSProperties = {
|
|
|
113
167
|
|
|
114
168
|
const segmentOn: CSSProperties = {...segmentBase, background: '#451a03', color: '#fffbeb'}
|
|
115
169
|
const segmentOff: CSSProperties = {...segmentBase, color: '#451a03', opacity: 0.7}
|
|
170
|
+
|
|
171
|
+
const shareButton: CSSProperties = {
|
|
172
|
+
...segmentBase,
|
|
173
|
+
border: 'none',
|
|
174
|
+
background: 'transparent',
|
|
175
|
+
color: '#451a03',
|
|
176
|
+
cursor: 'pointer',
|
|
177
|
+
font: 'inherit',
|
|
178
|
+
textDecoration: 'underline',
|
|
179
|
+
textUnderlineOffset: 3,
|
|
180
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import {cookies, draftMode} from 'next/headers'
|
|
2
|
+
import {isProductionSite} from './environment'
|
|
3
|
+
|
|
4
|
+
/** Cookie de perspective posé par Presentation (`@sanity/preview-url-secret`). */
|
|
5
|
+
export const PERSPECTIVE_COOKIE = 'sanity-preview-perspective'
|
|
6
|
+
|
|
7
|
+
export type DataPerspective = 'published' | 'drafts'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Le site lit-il les brouillons ? JAMAIS en production : un cookie de mode brouillon
|
|
11
|
+
* présent sur le domaine public (posé par un ancien aperçu, copié, forgé) est ignoré.
|
|
12
|
+
* À utiliser partout à la place de `draftMode().isEnabled`.
|
|
13
|
+
*/
|
|
14
|
+
export async function isDraftData(): Promise<boolean> {
|
|
15
|
+
if (isProductionSite()) return false
|
|
16
|
+
return (await draftMode()).isEnabled
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Données réellement affichées : `published` hors mode brouillon (et toujours en
|
|
21
|
+
* production) ; en mode brouillon, la perspective choisie (Presentation ou bascule).
|
|
22
|
+
*/
|
|
23
|
+
export async function dataPerspective(): Promise<DataPerspective> {
|
|
24
|
+
if (!(await isDraftData())) return 'published'
|
|
25
|
+
const value = (await cookies()).get(PERSPECTIVE_COOKIE)?.value
|
|
26
|
+
return value === 'published' ? 'published' : 'drafts'
|
|
27
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {draftMode} from 'next/headers'
|
|
1
|
+
import {cookies, draftMode} from 'next/headers'
|
|
2
2
|
import {NextResponse} from 'next/server'
|
|
3
3
|
import {isProductionSite} from './environment'
|
|
4
|
+
import {PERSPECTIVE_COOKIE} from './dataMode'
|
|
4
5
|
|
|
5
6
|
export interface DraftModeToggleOptions {
|
|
6
7
|
/**
|
|
@@ -33,6 +34,7 @@ export function ncfDraftModeToggle(options: DraftModeToggleOptions = {}) {
|
|
|
33
34
|
return {
|
|
34
35
|
async GET(request: Request): Promise<Response> {
|
|
35
36
|
if (isProductionSite()) {
|
|
37
|
+
;(await draftMode()).disable()
|
|
36
38
|
return NextResponse.json(
|
|
37
39
|
{error: 'Le mode brouillon est désactivé en production.'},
|
|
38
40
|
{status: 403},
|
|
@@ -42,8 +44,17 @@ export function ncfDraftModeToggle(options: DraftModeToggleOptions = {}) {
|
|
|
42
44
|
const url = new URL(request.url)
|
|
43
45
|
const draft = await draftMode()
|
|
44
46
|
|
|
45
|
-
|
|
46
|
-
|
|
47
|
+
// La perspective suit la bascule : sans ça, un passage préalable par Presentation
|
|
48
|
+
// en « publié » laisserait « Brouillons » afficher le contenu en ligne.
|
|
49
|
+
const jar = await cookies()
|
|
50
|
+
const secure = url.protocol === 'https:'
|
|
51
|
+
if (url.searchParams.get('enable') === 'false') {
|
|
52
|
+
draft.disable()
|
|
53
|
+
jar.delete(PERSPECTIVE_COOKIE)
|
|
54
|
+
} else {
|
|
55
|
+
draft.enable()
|
|
56
|
+
jar.set({name: PERSPECTIVE_COOKIE, value: 'drafts', httpOnly: true, path: '/', secure, sameSite: secure ? 'none' : 'lax'})
|
|
57
|
+
}
|
|
47
58
|
|
|
48
59
|
// On revient d'où l'on vient : basculer les données ne doit pas faire
|
|
49
60
|
// perdre sa place au relecteur. Un chemin relatif seulement — une URL
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import {cookies, draftMode} from 'next/headers'
|
|
2
|
+
import {PERSPECTIVE_COOKIE} from './dataMode'
|
|
3
|
+
import {NextResponse} from 'next/server'
|
|
4
|
+
import {isProductionSite} from './environment'
|
|
5
|
+
import {previewSecret, SESSION_COOKIE, SESSION_TTL_MS, signPreviewSession} from './previewSession'
|
|
6
|
+
|
|
7
|
+
type Handler = {GET: (request: Request) => Promise<Response>}
|
|
8
|
+
|
|
9
|
+
const isRedirect = (error: unknown): boolean =>
|
|
10
|
+
typeof error === 'object' && error !== null && String((error as {digest?: unknown}).digest ?? '').startsWith('NEXT_REDIRECT')
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Enveloppe de la route d'activation du mode brouillon de Sanity (Presentation).
|
|
14
|
+
*
|
|
15
|
+
* ```ts
|
|
16
|
+
* // app/api/draft-mode/enable/route.ts
|
|
17
|
+
* export const {GET} = ncfEnableDraftMode(defineEnableDraftMode({client: client.withConfig({token})}))
|
|
18
|
+
* ```
|
|
19
|
+
*
|
|
20
|
+
* - **Production : refusée** (et un éventuel mode brouillon est coupé). Le site public
|
|
21
|
+
* ne montre jamais de brouillons : on édite sur la préproduction.
|
|
22
|
+
* - **Préproduction :** une fois le secret validé par Sanity, pose aussi une session de
|
|
23
|
+
* préproduction signée, pour que la garde laisse passer l'iframe de Presentation
|
|
24
|
+
* sans laissez-passer ni connexion.
|
|
25
|
+
*/
|
|
26
|
+
export function ncfEnableDraftMode(handler: Handler): Handler {
|
|
27
|
+
return {
|
|
28
|
+
async GET(request: Request): Promise<Response> {
|
|
29
|
+
if (isProductionSite()) {
|
|
30
|
+
// Aucun brouillon en production : on coupe un éventuel mode brouillon et on
|
|
31
|
+
// affiche la page demandée telle qu'en ligne (Presentation la montre sans
|
|
32
|
+
// édition). Chemin relatif seulement : jamais de redirection ouverte.
|
|
33
|
+
;(await draftMode()).disable()
|
|
34
|
+
;(await cookies()).delete(PERSPECTIVE_COOKIE)
|
|
35
|
+
const wanted = new URL(request.url).searchParams.get('sanity-preview-pathname') ?? '/'
|
|
36
|
+
const target = wanted.startsWith('/') && !wanted.startsWith('//') ? wanted : '/'
|
|
37
|
+
return NextResponse.redirect(new URL(target, request.url))
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
return await handler.GET(request)
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (isRedirect(error) && process.env.VERCEL_ENV === 'preview') {
|
|
43
|
+
const secret = previewSecret()
|
|
44
|
+
if (secret) {
|
|
45
|
+
const iframe = request.headers.get('sec-fetch-dest') === 'iframe' && request.headers.get('sec-fetch-site') === 'cross-site'
|
|
46
|
+
;(await cookies()).set({
|
|
47
|
+
name: SESSION_COOKIE,
|
|
48
|
+
value: await signPreviewSession(secret),
|
|
49
|
+
httpOnly: true,
|
|
50
|
+
path: '/',
|
|
51
|
+
secure: true,
|
|
52
|
+
sameSite: 'none',
|
|
53
|
+
partitioned: iframe,
|
|
54
|
+
maxAge: SESSION_TTL_MS / 1000,
|
|
55
|
+
})
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
throw error
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
}
|
|
62
|
+
}
|
package/src/web/previewGrant.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import {cookies} from 'next/headers'
|
|
2
2
|
import {NextResponse, type NextRequest} from 'next/server'
|
|
3
|
+
import {previewSecret, SESSION_COOKIE, verifyPreviewSession} from './previewSession'
|
|
3
4
|
|
|
4
5
|
/** Paramètre d'URL porteur du laissez-passer, et cookie qui le mémorise. */
|
|
5
6
|
export const GRANT_PARAM = 'ncf_preview'
|
|
@@ -44,6 +45,36 @@ export async function hasPreviewGrant(endpoint = DEFAULT_ENDPOINT): Promise<bool
|
|
|
44
45
|
return token ? checkGrant(token, endpoint) : false
|
|
45
46
|
}
|
|
46
47
|
|
|
48
|
+
/**
|
|
49
|
+
* Mémorise le laissez-passer en cookie.
|
|
50
|
+
*
|
|
51
|
+
* SameSite=None en HTTPS : il doit aussi valoir dans l'iframe de Presentation (site
|
|
52
|
+
* tiers vu du Studio), où un cookie Lax n'est pas envoyé. Lisible par le navigateur
|
|
53
|
+
* (pas httpOnly) : le bandeau de préversion le remet dans l'URL après une navigation
|
|
54
|
+
* côté client. La clé est faite pour circuler dans les URL ; la cacher au script de
|
|
55
|
+
* la page ne protégerait rien.
|
|
56
|
+
*/
|
|
57
|
+
function rememberGrant(request: NextRequest, response: NextResponse, token: string) {
|
|
58
|
+
const https = request.nextUrl.protocol === 'https:'
|
|
59
|
+
response.cookies.set(GRANT_COOKIE, token, {
|
|
60
|
+
httpOnly: false,
|
|
61
|
+
sameSite: https ? 'none' : 'lax',
|
|
62
|
+
secure: https,
|
|
63
|
+
path: '/',
|
|
64
|
+
maxAge: 60 * 60 * 24 * 30,
|
|
65
|
+
})
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Chargement complet d'une page (pas une requête de données de Next ni un préchargement). */
|
|
69
|
+
function isPageLoad(request: NextRequest): boolean {
|
|
70
|
+
if (request.method !== 'GET') return false
|
|
71
|
+
const h = request.headers
|
|
72
|
+
if (h.get('rsc') || h.get('next-router-prefetch') || h.get('next-router-state-tree') || h.get('purpose') === 'prefetch') return false
|
|
73
|
+
const dest = h.get('sec-fetch-dest')
|
|
74
|
+
if (dest) return dest === 'document' || dest === 'iframe'
|
|
75
|
+
return (h.get('accept') ?? '').includes('text/html')
|
|
76
|
+
}
|
|
77
|
+
|
|
47
78
|
const ALWAYS_OPEN = ['/_next/', '/favicon', '/robots.txt', '/sitemap.xml', '/api/draft-mode/']
|
|
48
79
|
|
|
49
80
|
/**
|
|
@@ -84,32 +115,43 @@ export async function ncfPreviewGuard(
|
|
|
84
115
|
|
|
85
116
|
const endpoint = options.endpoint ?? DEFAULT_ENDPOINT
|
|
86
117
|
|
|
87
|
-
// Un laissez-passer dans l'URL : on le valide
|
|
88
|
-
//
|
|
89
|
-
//
|
|
118
|
+
// Un laissez-passer dans l'URL : on le valide et on le mémorise en cookie, en le
|
|
119
|
+
// LAISSANT dans l'URL. L'adresse affichée est ainsi toujours partageable telle
|
|
120
|
+
// quelle : copiée depuis la barre d'adresse et envoyée à un client, elle ouvre la
|
|
121
|
+
// préversion sans compte ni connexion.
|
|
90
122
|
const fromUrl = searchParams.get(GRANT_PARAM)
|
|
91
123
|
if (fromUrl) {
|
|
92
124
|
if (!(await checkGrant(fromUrl, endpoint))) return refuse(request)
|
|
125
|
+
// Déjà mémorisé : la requête suit son cours (le middleware hôte poursuit).
|
|
126
|
+
if (request.cookies.get(GRANT_COOKIE)?.value === fromUrl) return null
|
|
93
127
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
response.cookies.set(GRANT_COOKIE, fromUrl, {
|
|
98
|
-
httpOnly: true,
|
|
99
|
-
sameSite: 'lax',
|
|
100
|
-
secure: request.nextUrl.protocol === 'https:',
|
|
101
|
-
path: '/',
|
|
102
|
-
maxAge: 60 * 60 * 24 * 30,
|
|
103
|
-
})
|
|
128
|
+
// Même adresse, clé comprise : le cookie est posé au passage, la page suit.
|
|
129
|
+
const response = NextResponse.redirect(request.nextUrl.clone(), {headers: NOINDEX_HEADERS})
|
|
130
|
+
rememberGrant(request, response, fromUrl)
|
|
104
131
|
return response
|
|
105
132
|
}
|
|
106
133
|
|
|
134
|
+
// Session signée posée par l'activation du mode brouillon (Presentation, après
|
|
135
|
+
// validation du secret par Sanity) : vérifiée localement, sans réseau.
|
|
136
|
+
if (await verifyPreviewSession(request.cookies.get(SESSION_COOKIE)?.value, previewSecret())) return null
|
|
137
|
+
|
|
107
138
|
const fromCookie = request.cookies.get(GRANT_COOKIE)?.value
|
|
108
139
|
// `null` et non `NextResponse.next()` : le garde se monte en tête d'un
|
|
109
140
|
// middleware qui fait autre chose ensuite — langues, redirections, en-têtes.
|
|
110
141
|
// Rendre une réponse ici court-circuiterait tout ce qui suit, et les pages
|
|
111
142
|
// localisées tomberaient en 404.
|
|
112
|
-
if (fromCookie && (await checkGrant(fromCookie, endpoint)))
|
|
143
|
+
if (fromCookie && (await checkGrant(fromCookie, endpoint))) {
|
|
144
|
+
// Chargement d'une page sans la clé (lien interne, favori, retour) : on la remet
|
|
145
|
+
// dans l'URL, pour que l'adresse affichée reste partageable. Les requêtes de
|
|
146
|
+
// données de Next (navigation côté client) ne sont pas redirigées : c'est le
|
|
147
|
+
// bandeau de préversion qui y remet la clé, sans recharger.
|
|
148
|
+
if (isPageLoad(request)) {
|
|
149
|
+
const withKey = request.nextUrl.clone()
|
|
150
|
+
withKey.searchParams.set(GRANT_PARAM, fromCookie)
|
|
151
|
+
return NextResponse.redirect(withKey, {headers: NOINDEX_HEADERS})
|
|
152
|
+
}
|
|
153
|
+
return null
|
|
154
|
+
}
|
|
113
155
|
|
|
114
156
|
return refuse(request)
|
|
115
157
|
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session de préproduction signée (HMAC-SHA256), sans appel réseau.
|
|
3
|
+
*
|
|
4
|
+
* Délivrée par la route d'activation du mode brouillon APRÈS que Sanity a validé le
|
|
5
|
+
* secret de Presentation : l'éditeur connecté au Studio peut ainsi voir la préproduction
|
|
6
|
+
* dans l'iframe de Presentation sans laissez-passer ni connexion. Vérifiée par
|
|
7
|
+
* `ncfPreviewGuard` en Web Crypto (middleware compatible Edge et Node).
|
|
8
|
+
*
|
|
9
|
+
* Clé : `NCF_PREVIEW_SECRET`, sinon le jeton de lecture Sanity du site
|
|
10
|
+
* (`SANITY_API_READ_TOKEN`), secret côté serveur. Sans clé : pas de session.
|
|
11
|
+
*/
|
|
12
|
+
export const SESSION_COOKIE = 'ncf_preview_session'
|
|
13
|
+
export const SESSION_TTL_MS = 12 * 60 * 60 * 1000
|
|
14
|
+
|
|
15
|
+
const encoder = new TextEncoder()
|
|
16
|
+
|
|
17
|
+
export function previewSecret(env: Record<string, string | undefined> = process.env): string | null {
|
|
18
|
+
return env.NCF_PREVIEW_SECRET?.trim() || env.SANITY_API_READ_TOKEN?.trim() || null
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function base64url(bytes: ArrayBuffer): string {
|
|
22
|
+
let binary = ''
|
|
23
|
+
for (const b of new Uint8Array(bytes)) binary += String.fromCharCode(b)
|
|
24
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async function hmac(secret: string, message: string): Promise<string> {
|
|
28
|
+
const key = await crypto.subtle.importKey('raw', encoder.encode(secret), {name: 'HMAC', hash: 'SHA-256'}, false, ['sign'])
|
|
29
|
+
return base64url(await crypto.subtle.sign('HMAC', key, encoder.encode(message)))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Comparaison à temps constant (pas d'indice sur la signature attendue). */
|
|
33
|
+
function sameString(a: string, b: string): boolean {
|
|
34
|
+
if (a.length !== b.length) return false
|
|
35
|
+
let diff = 0
|
|
36
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i)
|
|
37
|
+
return diff === 0
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** Valeur de cookie signée, valable `ttl` ms. */
|
|
41
|
+
export async function signPreviewSession(secret: string, now = Date.now(), ttl = SESSION_TTL_MS): Promise<string> {
|
|
42
|
+
const expires = now + ttl
|
|
43
|
+
return `${expires}.${await hmac(secret, `ncf-preview-session:${expires}`)}`
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Vraie seulement pour une session signée avec cette clé et non expirée. */
|
|
47
|
+
export async function verifyPreviewSession(value: string | undefined | null, secret: string | null, now = Date.now()): Promise<boolean> {
|
|
48
|
+
if (!value || !secret) return false
|
|
49
|
+
const dot = value.indexOf('.')
|
|
50
|
+
if (dot <= 0) return false
|
|
51
|
+
const expires = Number(value.slice(0, dot))
|
|
52
|
+
if (!Number.isFinite(expires) || expires <= now || expires > now + SESSION_TTL_MS + 60_000) return false
|
|
53
|
+
return sameString(value.slice(dot + 1), await hmac(secret, `ncf-preview-session:${expires}`))
|
|
54
|
+
}
|
package/src/web/server.ts
CHANGED
|
@@ -7,6 +7,10 @@
|
|
|
7
7
|
* ```
|
|
8
8
|
*/
|
|
9
9
|
export {ncfDraftModeToggle} from './draftModeToggle'
|
|
10
|
+
export {ncfEnableDraftMode} from './enableDraftMode'
|
|
11
|
+
export {isDraftData, dataPerspective, PERSPECTIVE_COOKIE} from './dataMode'
|
|
12
|
+
export type {DataPerspective} from './dataMode'
|
|
13
|
+
export {signPreviewSession, verifyPreviewSession, previewSecret, SESSION_COOKIE} from './previewSession'
|
|
10
14
|
export type {DraftModeToggleOptions} from './draftModeToggle'
|
|
11
15
|
export {isProductionSite, isPreviewSite} from './environment'
|
|
12
16
|
export {
|