@conloca/cloud-astro 0.2.4 → 0.2.6

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.
Files changed (171) hide show
  1. package/README.md +69 -22
  2. package/dist/.build-inputs.json +36 -23
  3. package/dist/src/constants.d.ts +4 -4
  4. package/dist/src/constants.js +4 -4
  5. package/dist/src/d3-build.d.ts +6 -2
  6. package/dist/src/d3-build.d.ts.map +1 -1
  7. package/dist/src/d3-build.js +15 -11
  8. package/dist/src/d3-build.js.map +1 -1
  9. package/dist/src/d8-adapters.d.ts +10 -0
  10. package/dist/src/d8-adapters.d.ts.map +1 -0
  11. package/dist/src/d8-adapters.js +19 -0
  12. package/dist/src/d8-adapters.js.map +1 -0
  13. package/dist/src/d8-build.d.ts +99 -0
  14. package/dist/src/d8-build.d.ts.map +1 -0
  15. package/dist/src/d8-build.js +265 -0
  16. package/dist/src/d8-build.js.map +1 -0
  17. package/dist/src/d8-guards.d.ts +29 -0
  18. package/dist/src/d8-guards.d.ts.map +1 -0
  19. package/dist/src/d8-guards.js +145 -0
  20. package/dist/src/d8-guards.js.map +1 -0
  21. package/dist/src/d8-middleware.d.ts +7 -0
  22. package/dist/src/d8-middleware.d.ts.map +1 -0
  23. package/dist/src/d8-middleware.js +15 -0
  24. package/dist/src/d8-middleware.js.map +1 -0
  25. package/dist/src/d8-render.d.ts +9 -0
  26. package/dist/src/d8-render.d.ts.map +1 -0
  27. package/dist/src/d8-render.js +52 -0
  28. package/dist/src/d8-render.js.map +1 -0
  29. package/dist/src/doctor/checks-d8.d.ts +7 -0
  30. package/dist/src/doctor/checks-d8.d.ts.map +1 -0
  31. package/dist/src/doctor/checks-d8.js +240 -0
  32. package/dist/src/doctor/checks-d8.js.map +1 -0
  33. package/dist/src/doctor/checks-live.d.ts.map +1 -1
  34. package/dist/src/doctor/checks-live.js +3 -5
  35. package/dist/src/doctor/checks-live.js.map +1 -1
  36. package/dist/src/doctor/checks-offline.d.ts +2 -0
  37. package/dist/src/doctor/checks-offline.d.ts.map +1 -1
  38. package/dist/src/doctor/checks-offline.js +17 -8
  39. package/dist/src/doctor/checks-offline.js.map +1 -1
  40. package/dist/src/doctor/checks-preview-live.d.ts +7 -2
  41. package/dist/src/doctor/checks-preview-live.d.ts.map +1 -1
  42. package/dist/src/doctor/checks-preview-live.js +107 -7
  43. package/dist/src/doctor/checks-preview-live.js.map +1 -1
  44. package/dist/src/doctor/checks-preview.d.ts.map +1 -1
  45. package/dist/src/doctor/checks-preview.js +9 -4
  46. package/dist/src/doctor/checks-preview.js.map +1 -1
  47. package/dist/src/doctor/config-scan.d.ts +24 -6
  48. package/dist/src/doctor/config-scan.d.ts.map +1 -1
  49. package/dist/src/doctor/config-scan.js +89 -18
  50. package/dist/src/doctor/config-scan.js.map +1 -1
  51. package/dist/src/doctor/run.d.ts.map +1 -1
  52. package/dist/src/doctor/run.js +2 -0
  53. package/dist/src/doctor/run.js.map +1 -1
  54. package/dist/src/doctor/types.d.ts +7 -0
  55. package/dist/src/doctor/types.d.ts.map +1 -1
  56. package/dist/src/doctor/types.js +7 -0
  57. package/dist/src/doctor/types.js.map +1 -1
  58. package/dist/src/editor-page/emit.d.ts +4 -3
  59. package/dist/src/editor-page/emit.d.ts.map +1 -1
  60. package/dist/src/editor-page/emit.js +9 -9
  61. package/dist/src/editor-page/emit.js.map +1 -1
  62. package/dist/src/integration.d.ts.map +1 -1
  63. package/dist/src/integration.js +228 -124
  64. package/dist/src/integration.js.map +1 -1
  65. package/dist/src/node.d.ts +2 -0
  66. package/dist/src/node.d.ts.map +1 -1
  67. package/dist/src/node.js +4 -0
  68. package/dist/src/node.js.map +1 -1
  69. package/dist/src/preview/_resolve-opts.d.ts +26 -1
  70. package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
  71. package/dist/src/preview/_resolve-opts.js.map +1 -1
  72. package/dist/src/preview/content-api.d.ts +15 -0
  73. package/dist/src/preview/content-api.d.ts.map +1 -1
  74. package/dist/src/preview/content-api.js +57 -6
  75. package/dist/src/preview/content-api.js.map +1 -1
  76. package/dist/src/preview/d8-middleware.d.ts +25 -0
  77. package/dist/src/preview/d8-middleware.d.ts.map +1 -0
  78. package/dist/src/preview/d8-middleware.js +94 -0
  79. package/dist/src/preview/d8-middleware.js.map +1 -0
  80. package/dist/src/preview/dispatcher.d.ts +3 -16
  81. package/dist/src/preview/dispatcher.d.ts.map +1 -1
  82. package/dist/src/preview/dispatcher.js +46 -134
  83. package/dist/src/preview/dispatcher.js.map +1 -1
  84. package/dist/src/preview/headers.d.ts +3 -0
  85. package/dist/src/preview/headers.d.ts.map +1 -1
  86. package/dist/src/preview/headers.js +10 -1
  87. package/dist/src/preview/headers.js.map +1 -1
  88. package/dist/src/preview/links.d.ts +23 -0
  89. package/dist/src/preview/links.d.ts.map +1 -0
  90. package/dist/src/preview/links.js +168 -0
  91. package/dist/src/preview/links.js.map +1 -0
  92. package/dist/src/preview/middleware.d.ts +9 -3
  93. package/dist/src/preview/middleware.d.ts.map +1 -1
  94. package/dist/src/preview/middleware.js +36 -16
  95. package/dist/src/preview/middleware.js.map +1 -1
  96. package/dist/src/preview/prefix-router.d.ts +67 -0
  97. package/dist/src/preview/prefix-router.d.ts.map +1 -0
  98. package/dist/src/preview/prefix-router.js +153 -0
  99. package/dist/src/preview/prefix-router.js.map +1 -0
  100. package/dist/src/preview/preview-path.d.ts +8 -3
  101. package/dist/src/preview/preview-path.d.ts.map +1 -1
  102. package/dist/src/preview/preview-path.js +16 -4
  103. package/dist/src/preview/preview-path.js.map +1 -1
  104. package/dist/src/preview/site-middleware.d.ts +8 -2
  105. package/dist/src/preview/site-middleware.d.ts.map +1 -1
  106. package/dist/src/preview/site-middleware.js +90 -31
  107. package/dist/src/preview/site-middleware.js.map +1 -1
  108. package/dist/src/preview/site-page-sources.d.ts +21 -0
  109. package/dist/src/preview/site-page-sources.d.ts.map +1 -0
  110. package/dist/src/preview/site-page-sources.js +129 -0
  111. package/dist/src/preview/site-page-sources.js.map +1 -0
  112. package/dist/src/preview/site-pages.d.ts +18 -0
  113. package/dist/src/preview/site-pages.d.ts.map +1 -0
  114. package/dist/src/preview/site-pages.js +7 -0
  115. package/dist/src/preview/site-pages.js.map +1 -0
  116. package/dist/src/preview-build.d.ts +17 -16
  117. package/dist/src/preview-build.d.ts.map +1 -1
  118. package/dist/src/preview-build.js +37 -40
  119. package/dist/src/preview-build.js.map +1 -1
  120. package/dist/src/preview-image-endpoint.d.ts +8 -0
  121. package/dist/src/preview-image-endpoint.d.ts.map +1 -0
  122. package/dist/src/preview-image-endpoint.js +34 -0
  123. package/dist/src/preview-image-endpoint.js.map +1 -0
  124. package/dist/src/preview-render-seams.d.ts +7 -0
  125. package/dist/src/preview-render-seams.d.ts.map +1 -0
  126. package/dist/src/preview-render-seams.js +27 -0
  127. package/dist/src/preview-render-seams.js.map +1 -0
  128. package/dist/src/site-middleware.d.ts +2 -4
  129. package/dist/src/site-middleware.d.ts.map +1 -1
  130. package/dist/src/site-middleware.js +6 -22
  131. package/dist/src/site-middleware.js.map +1 -1
  132. package/dist/src/types.d.ts +15 -16
  133. package/dist/src/types.d.ts.map +1 -1
  134. package/package.json +138 -6
  135. package/src/constants.ts +4 -4
  136. package/src/d3-build.ts +20 -14
  137. package/src/d8-adapters.ts +19 -0
  138. package/src/d8-build.ts +356 -0
  139. package/src/d8-guards.ts +177 -0
  140. package/src/d8-middleware.ts +17 -0
  141. package/src/d8-render.ts +61 -0
  142. package/src/doctor/checks-d8.ts +256 -0
  143. package/src/doctor/checks-live.ts +3 -4
  144. package/src/doctor/checks-offline.ts +21 -8
  145. package/src/doctor/checks-preview-live.ts +114 -8
  146. package/src/doctor/checks-preview.ts +9 -4
  147. package/src/doctor/config-scan.ts +86 -15
  148. package/src/doctor/run.ts +2 -0
  149. package/src/doctor/types.ts +8 -0
  150. package/src/editor-page/emit.ts +23 -14
  151. package/src/integration.ts +274 -135
  152. package/src/node.ts +4 -0
  153. package/src/preview/_resolve-opts.ts +17 -1
  154. package/src/preview/content-api.ts +60 -5
  155. package/src/preview/d8-middleware.ts +124 -0
  156. package/src/preview/dispatcher.ts +55 -150
  157. package/src/preview/headers.ts +10 -1
  158. package/src/preview/links.ts +175 -0
  159. package/src/preview/middleware.ts +41 -19
  160. package/src/preview/prefix-router.ts +197 -0
  161. package/src/preview/preview-path.ts +24 -6
  162. package/src/preview/site-middleware.ts +109 -38
  163. package/src/preview/site-page-sources.ts +146 -0
  164. package/src/preview/site-pages.ts +22 -0
  165. package/src/preview-build.ts +43 -42
  166. package/src/preview-image-endpoint.ts +35 -0
  167. package/src/preview-render-seams.ts +31 -0
  168. package/src/site-middleware.ts +6 -24
  169. package/src/skill/SKILL.md +19 -1
  170. package/src/types.ts +15 -16
  171. package/src/virtual-modules.d.ts +17 -2
@@ -0,0 +1,175 @@
1
+ /**
2
+ * Moving a page's own links under the preview route, so a visitor clicking through a draft stays in the draft. The
3
+ * dispatcher applies these rules with Cloudflare's `HTMLRewriter`; `rewritePreviewLinks` applies them anywhere else.
4
+ */
5
+
6
+ import { Tokenizer } from 'htmlparser2';
7
+
8
+ /**
9
+ * `value` under the preview route when it names a page of this site, else null (left as it is). It is resolved
10
+ * against `page`, the unprefixed URL the page was rendered for, so `../x` and `?q` keep their meaning. Files, built
11
+ * assets, the image endpoint, `/_conloca/` and other sites stay where they are.
12
+ */
13
+ export function previewHref(
14
+ value: string,
15
+ page: URL,
16
+ route: string,
17
+ root: string,
18
+ hosts: ReadonlySet<string>,
19
+ ): string | null {
20
+ if (value === '' || value.startsWith('#')) return null;
21
+ let target: URL;
22
+ try {
23
+ target = new URL(value, page);
24
+ } catch {
25
+ return null;
26
+ }
27
+ if (target.protocol !== 'http:' && target.protocol !== 'https:') return null;
28
+ const own = target.host === page.host;
29
+ if (!own && !hosts.has(target.hostname)) return null;
30
+ const { pathname } = target;
31
+ if (root !== '' && pathname !== root && !pathname.startsWith(`${root}/`)) return null;
32
+ const rest = pathname.slice(root.length) || '/';
33
+ if (rest.startsWith('/_conloca/') || rest.startsWith('/_astro/') || rest === '/_image') return null;
34
+ const last = rest.slice(rest.lastIndexOf('/') + 1);
35
+ if (last.includes('.') && !last.endsWith('.html')) return null;
36
+ const moved = `${route}${rest}${target.search}${target.hash}`;
37
+ return own ? moved : `${target.origin}${moved}`;
38
+ }
39
+
40
+ /** A navigation, the only request that may receive draft HTML; without Sec-Fetch-*, one that asks for HTML. */
41
+ export function isNavigation(request: Request): boolean {
42
+ const mode = request.headers.get('sec-fetch-mode');
43
+ if (mode !== null) return mode === 'navigate';
44
+ return (request.headers.get('accept') ?? '').includes('text/html');
45
+ }
46
+
47
+ /**
48
+ * `srcset` with each candidate URL that `move` answers for replaced, everything else kept byte for byte; null when none
49
+ * moved. A URL runs to the next whitespace, as the HTML parser reads it, so a `data:` URL's commas stay inside it.
50
+ */
51
+ export function movedSrcset(value: string, move: (href: string) => string | null): string | null {
52
+ let out = '';
53
+ let rest = value;
54
+ let moved = false;
55
+ while (rest !== '') {
56
+ const gap = /^[\s,]*/u.exec(rest)?.[0] ?? '';
57
+ const token = /^\S*/u.exec(rest.slice(gap.length))?.[0] ?? '';
58
+ const commas = /,*$/u.exec(token)?.[0] ?? '';
59
+ const href = token.slice(0, token.length - commas.length);
60
+ rest = rest.slice(gap.length + token.length);
61
+ // Descriptors (`1x`, `400w`) run to the next comma, unless the URL already ended at one.
62
+ const descriptor = commas === '' ? (/^[^,]*/u.exec(rest)?.[0] ?? '') : '';
63
+ rest = rest.slice(descriptor.length);
64
+ const target = href === '' ? null : move(href);
65
+ if (target !== null) moved = true;
66
+ out += `${gap}${target ?? href}${commas}${descriptor}`;
67
+ }
68
+ return moved ? out : null;
69
+ }
70
+
71
+ /** An attribute the rewriter may change: where its `=value` runs in the source, and its decoded value. */
72
+ interface Found {
73
+ start: number;
74
+ end: number;
75
+ value: string;
76
+ }
77
+
78
+ const ignore = () => {};
79
+
80
+ /**
81
+ * `html` with the links `linkRewriter` moves moved, every other byte kept. Only moved attributes are rewritten, in
82
+ * double quotes; comments and raw text (`script`, `style`, `textarea`, `title`) are the tokenizer's own states.
83
+ */
84
+ export function rewritePreviewLinks(
85
+ html: string,
86
+ page: URL,
87
+ route: string,
88
+ root: string,
89
+ hosts: ReadonlySet<string>,
90
+ ): string {
91
+ // A `<base href>` changes what relative links resolve against for every link after it.
92
+ let resolveAgainst = page;
93
+ const edits: { start: number; end: number; text: string }[] = [];
94
+ let tag = '';
95
+ let attributes = new Map<string, Found>();
96
+ let current: Found | null = null;
97
+ const replace = (name: string, found: Found, value: string) => {
98
+ edits.push({
99
+ start: found.start,
100
+ end: found.end,
101
+ text: `="${value.replaceAll('&', '&amp;').replaceAll('"', '&quot;')}"`,
102
+ });
103
+ if (name !== 'href' || (tag !== 'a' && tag !== 'area')) return;
104
+ // Astro's prefetch would spend the visitor's 60 requests per 10 s on links they never open.
105
+ const prefetch = attributes.get('data-astro-prefetch');
106
+ if (prefetch === undefined) edits.push({ start: found.end, end: found.end, text: ' data-astro-prefetch="false"' });
107
+ else edits.push({ start: prefetch.start, end: prefetch.end, text: '="false"' });
108
+ };
109
+ const move = (name: string) => {
110
+ const found = attributes.get(name);
111
+ const moved = found === undefined ? null : previewHref(found.value, resolveAgainst, route, root, hosts);
112
+ if (found !== undefined && moved !== null) replace(name, found, moved);
113
+ };
114
+ const finish = () => {
115
+ if (tag === 'base') {
116
+ const value = attributes.get('href')?.value;
117
+ if (value !== undefined && URL.canParse(value, page.href)) resolveAgainst = new URL(value, page);
118
+ }
119
+ if (tag === 'base' || tag === 'a' || tag === 'area') move('href');
120
+ if (tag === 'form') move('action');
121
+ const srcset = attributes.get('srcset');
122
+ const moved =
123
+ srcset === undefined
124
+ ? null
125
+ : movedSrcset(srcset.value, (href) => previewHref(href, resolveAgainst, route, root, hosts));
126
+ if (srcset !== undefined && moved !== null) replace('srcset', srcset, moved);
127
+ tag = '';
128
+ };
129
+ const tokenizer = new Tokenizer(
130
+ { xmlMode: false, decodeEntities: true },
131
+ {
132
+ onopentagname(start, end) {
133
+ tag = html.slice(start, end).toLowerCase();
134
+ attributes = new Map();
135
+ },
136
+ onattribname(start, end) {
137
+ const name = html.slice(start, end).toLowerCase();
138
+ // The first of two same-named attributes is the one the browser keeps.
139
+ current = attributes.has(name) ? null : { start: end, end, value: '' };
140
+ if (current !== null) attributes.set(name, current);
141
+ },
142
+ onattribdata(start, end) {
143
+ if (current !== null) current.value += html.slice(start, end);
144
+ },
145
+ onattribentity(codepoint) {
146
+ if (current !== null) current.value += String.fromCodePoint(codepoint);
147
+ },
148
+ onattribend(_quote, end) {
149
+ if (current !== null) current.end = end;
150
+ current = null;
151
+ },
152
+ onopentagend: finish,
153
+ onselfclosingtag: finish,
154
+ oncdata: ignore,
155
+ onclosetag: ignore,
156
+ oncomment: ignore,
157
+ ondeclaration: ignore,
158
+ onend: ignore,
159
+ onprocessinginstruction: ignore,
160
+ ontext: ignore,
161
+ ontextentity: ignore,
162
+ },
163
+ );
164
+ tokenizer.write(html);
165
+ tokenizer.end();
166
+ const out: string[] = [];
167
+ let cursor = 0;
168
+ // oxlint-disable-next-line unicorn/no-array-sort -- the target lib predates toSorted; this sorts its own array.
169
+ for (const edit of edits.sort((a, b) => a.start - b.start || a.end - b.end)) {
170
+ out.push(html.slice(cursor, edit.start), edit.text);
171
+ cursor = edit.end;
172
+ }
173
+ out.push(html.slice(cursor));
174
+ return out.join('');
175
+ }
@@ -1,4 +1,4 @@
1
- import { PREVIEW_PROTOCOL, previewBranchSlug } from '@conloca/content-api/editor-host';
1
+ import { isSluggedPreviewMode, PREVIEW_PROTOCOL, previewBranchSlug } from '@conloca/content-api/editor-host';
2
2
  import { createRemoteJWKSet, customFetch, type JWTPayload, type JWTVerifyGetKey, jwtVerify } from 'jose';
3
3
  import { parseCookieValues, serializePreviewCookie } from './cookie.js';
4
4
  import { exchangeEntryCode } from './entry-code.js';
@@ -17,7 +17,7 @@ import {
17
17
  previewScope,
18
18
  stripPreviewPrefix,
19
19
  } from './preview-path.js';
20
- import { GRANT_REF_RE, grantRef } from './redeem-url.js';
20
+ import { GRANT_REF_RE, grantRef, orgToken } from './redeem-url.js';
21
21
 
22
22
  /**
23
23
  * Options consumed by {@link handlePreviewRequest}.
@@ -76,11 +76,12 @@ export interface PreviewMiddlewareOptions {
76
76
  /**
77
77
  * How this build serves previews. `d2` (default): on the site's own deploy, where a share viewer whose pass
78
78
  * expires opens the share link again. `d3`: behind the dispatcher next to a static site, under the route and the
79
- * branch slug, with cookies scoped there. `d4`: on a separate preview deploy that has no other visitors. Under D3 and
80
- * D4 a grant cookie lets an expired pass renew through the share link.
79
+ * branch slug, with cookies scoped there. `d4`: on a separate preview deploy that has no other visitors. `d8`: on
80
+ * the site's own server under the route and the branch slug. Under D3 and D4 a grant cookie lets an expired pass
81
+ * renew through the share link.
81
82
  */
82
83
  mode?: PreviewServeMode;
83
- /** D3: the requested branch slug, as the dispatcher names it; a pass opens only under its own branch's slug. */
84
+ /** D3: the requested branch slug, as the dispatcher names it; a pass opens only under its own branch's slug. D8 reads the slug from the path and ignores this. */
84
85
  slug?: string;
85
86
  }
86
87
 
@@ -182,8 +183,8 @@ export async function handlePreviewRequest(request: Request, opts: PreviewMiddle
182
183
  // Under a D3 slug the dispatcher would move that path back under the route, where the same failing cookie lands
183
184
  // here again: the slug's exit clears it and then leaves for the published page.
184
185
  const liveHref =
185
- mode === 'd3' && opts.slug !== undefined
186
- ? `${previewScope('d3', opts.base, opts.slug).route}/__exit?to=${encodeURIComponent(pathname)}`
186
+ isSluggedPreviewMode(mode) && opts.slug !== undefined
187
+ ? `${previewScope(mode, opts.base, opts.slug).route}/__exit?to=${encodeURIComponent(pathname)}`
187
188
  : undefined;
188
189
  return {
189
190
  kind: 'response',
@@ -195,10 +196,12 @@ export async function handlePreviewRequest(request: Request, opts: PreviewMiddle
195
196
  };
196
197
  };
197
198
  const cookie = request.headers.get('cookie');
198
- const code = url.searchParams.get(PREVIEW_CODE_PARAM);
199
+ // A code that can't be one is no code: this server never calls Conloca for it.
200
+ const raw = url.searchParams.get(PREVIEW_CODE_PARAM);
201
+ const code = raw !== null && isEntryCodeShape(raw) ? raw : null;
199
202
  // Under D3 only the dispatcher's slug makes a request a preview request, except an entry link without one (an older
200
203
  // Conloca's, or a mint that couldn't read the mode): its slug comes from the pass. Anything else is the live site's.
201
- const slugless = mode === 'd3' && opts.slug === undefined;
204
+ const slugless = isSluggedPreviewMode(mode) && opts.slug === undefined;
202
205
  // A code counts only on the preview route: on the live site's own routes, trading it would let anyone make this
203
206
  // server call Conloca once per request.
204
207
  const entering = code !== null && stripPreviewPrefix(url.pathname, opts.base) !== url.pathname;
@@ -222,7 +225,7 @@ export async function handlePreviewRequest(request: Request, opts: PreviewMiddle
222
225
  if (exchanged.ok) {
223
226
  const ctx = await tryValidate(exchanged.pass, opts);
224
227
  if (ctx !== null) {
225
- const entered = scope ?? previewScope('d3', opts.base, previewBranchSlug(ctx.branch));
228
+ const entered = scope ?? previewScope(mode, opts.base, previewBranchSlug(ctx.branch));
226
229
  return { kind: 'response', response: makeInitRedirect(url, exchanged.pass, ctx, opts, entered) };
227
230
  }
228
231
  } else if (exchanged.kind === 'ended') {
@@ -234,7 +237,7 @@ export async function handlePreviewRequest(request: Request, opts: PreviewMiddle
234
237
  // Never the held pass: it may open another branch than the link names. Under D3 the dispatcher forwarded the
235
238
  // entry without its slug, so Retry rebuilds the link it came from; a slugless one is retried as it is.
236
239
  const retryHref =
237
- mode === 'd3' && scope !== null
240
+ isSluggedPreviewMode(mode) && scope !== null
238
241
  ? `${scope.route}${pageUnderBase(path, opts.base)}${url.search}`
239
242
  : `${url.pathname}${url.search}`;
240
243
  return { kind: 'response', response: renderPreviewUnavailable({ retryHref, exitHref }) };
@@ -248,7 +251,7 @@ export async function handlePreviewRequest(request: Request, opts: PreviewMiddle
248
251
 
249
252
  // 2. Query-param init path (protocol 1, read for one release). An invalid
250
253
  // pass gets the landing page rather than a 401 (see docstring). D3 never had protocol-1 links, so it takes none.
251
- const queryToken = mode === 'd3' ? null : url.searchParams.get(PREVIEW_QUERY_PARAM);
254
+ const queryToken = isSluggedPreviewMode(mode) ? null : url.searchParams.get(PREVIEW_QUERY_PARAM);
252
255
  if (queryToken !== null) {
253
256
  const ctx = await tryValidate(queryToken, opts);
254
257
  return ctx === null
@@ -261,12 +264,13 @@ export async function handlePreviewRequest(request: Request, opts: PreviewMiddle
261
264
  if (ctx !== null) return { kind: 'preview', ctx };
262
265
 
263
266
  // 4. No valid preview context.
264
- // Under D3 and D4 a share viewer's expired pass renews through the share link the grant cookie names.
267
+ // Under D3, D4 and D8 a share viewer's expired pass renews through the share link the grant cookie names.
265
268
  const ref =
266
269
  scope.grant === null ? undefined : parseCookieValues(cookie, scope.grant).find((v) => GRANT_REF_RE.test(v));
267
270
  if (ref !== undefined) {
268
271
  const [org, grant] = ref.split('.');
269
- const to = encodeURIComponent(stripPreviewPrefix(url.pathname, opts.base));
272
+ // The page itself: under D8 the request still carries the route and the slug.
273
+ const to = encodeURIComponent(pageOf(url.pathname, opts));
270
274
  return {
271
275
  kind: 'response',
272
276
  response: new Response(null, {
@@ -353,7 +357,8 @@ function projectContext(payload: JWTPayload, jwt: string, opts: PreviewMiddlewar
353
357
  if (branch !== opts.branch && readStringClaim(payload, 'served_by') !== opts.branch) return null;
354
358
  // Under D3 the cookie lives under its branch's slug: a pass for another branch never opens this one's pages. A
355
359
  // slugless entry has no slug yet; its scope comes from this branch (handlePreviewRequest).
356
- if (opts.mode === 'd3' && opts.slug !== undefined && previewBranchSlug(branch) !== opts.slug) return null;
360
+ if (isSluggedPreviewMode(opts.mode) && opts.slug !== undefined && previewBranchSlug(branch) !== opts.slug)
361
+ return null;
357
362
  const expiresInSeconds =
358
363
  typeof payload.exp === 'number' ? Math.max(0, payload.exp - Math.floor(Date.now() / 1000)) : undefined;
359
364
  // A share pass names its link and the link's expiry; a pass that names a link without one is malformed.
@@ -406,7 +411,7 @@ function makeExitRedirect(url: URL, opts: PreviewMiddlewareOptions, label: strin
406
411
  [PREVIEW_MODE_HEADER]: mode,
407
412
  });
408
413
  // The probe asks a D3 server without a slug: it names no cookies, so none are expired.
409
- if (mode === 'd3' && opts.slug === undefined) return new Response(null, { status: 302, headers });
414
+ if (isSluggedPreviewMode(mode) && opts.slug === undefined) return new Response(null, { status: 302, headers });
410
415
  const scope = previewScope(mode, opts.base, opts.slug);
411
416
  headers.append('set-cookie', serializePreviewCookie(scope.pass, '', 0, scope.path));
412
417
  // Without this the renewal would see the grant and send the viewer straight back in.
@@ -440,8 +445,8 @@ function exitTarget(url: URL, opts: PreviewMiddlewareOptions): string {
440
445
 
441
446
  /** A pathname with the preview route stripped; under D3 the branch slug goes with it. */
442
447
  function pageOf(pathname: string, opts: PreviewMiddlewareOptions): string {
443
- if (opts.mode === 'd3' && opts.slug !== undefined) {
444
- const { route } = previewScope('d3', opts.base, opts.slug);
448
+ if (opts.mode !== undefined && isSluggedPreviewMode(opts.mode) && opts.slug !== undefined) {
449
+ const { route } = previewScope(opts.mode, opts.base, opts.slug);
445
450
  if (pathname === route || pathname.startsWith(`${route}/`)) {
446
451
  return `${opts.base.replace(/\/+$/u, '')}${pathname.slice(route.length) || '/'}`;
447
452
  }
@@ -464,7 +469,7 @@ function cleanLocation(url: URL, opts: PreviewMiddlewareOptions, scope: PreviewS
464
469
  cleaned.searchParams.delete(PREVIEW_QUERY_PARAM);
465
470
  cleaned.searchParams.delete(PREVIEW_CODE_PARAM);
466
471
  const page = stripPreviewPrefix(cleaned.pathname, opts.base);
467
- cleaned.pathname = opts.mode === 'd3' ? `${scope.route}${pageUnderBase(page, opts.base)}` : page;
472
+ cleaned.pathname = isSluggedPreviewMode(opts.mode) ? `${scope.route}${pageUnderBase(page, opts.base)}` : page;
468
473
  const location = cleaned.toString();
469
474
  return cleaned.search === '' && location.endsWith('?') ? location.slice(0, -1) : location;
470
475
  }
@@ -494,3 +499,20 @@ function makeCleanRedirect(url: URL, opts: PreviewMiddlewareOptions, scope: Prev
494
499
  headers: { location: cleanLocation(url, opts, scope), ...PREVIEW_CACHE_HEADERS },
495
500
  });
496
501
  }
502
+
503
+ /**
504
+ * Whether a link's code has the shape Conloca mints, `<org token>.<secret>`: the org token is the canonical unpadded
505
+ * base64url of a non-empty UTF-8 id. Checked before the exchange so junk never makes this server call out.
506
+ */
507
+ export function isEntryCodeShape(code: string): boolean {
508
+ const [token = '', secret = '', ...extra] = code.split('.');
509
+ if (extra.length > 0 || !/^[A-Za-z0-9_-]{1,200}$/u.test(token) || !/^[A-Za-z0-9_-]{16,256}$/u.test(secret))
510
+ return false;
511
+ try {
512
+ const binary = atob(token.replace(/-/gu, '+').replace(/_/gu, '/'));
513
+ const org = new TextDecoder('utf-8', { fatal: true }).decode(Uint8Array.from(binary, (c) => c.charCodeAt(0)));
514
+ return org !== '' && orgToken(org) === token;
515
+ } catch {
516
+ return false;
517
+ }
518
+ }
@@ -0,0 +1,197 @@
1
+ /**
2
+ * The preview route's request rules, free of any runtime binding: the D3 dispatcher and the d8 front middleware both
3
+ * classify a request, answer the exit and send a failed load to the same retry page with these.
4
+ */
5
+
6
+ import { IMAGE_EXTENSION_MIME, mediaRefPath } from '@conloca/content-api/draft-media-ref';
7
+ import { branchOfPreviewSlug } from '@conloca/content-api/editor-host';
8
+ import { parseCookieValues } from './cookie.js';
9
+ import { applyPreviewHeaders } from './headers.js';
10
+ import { renderPreviewUnavailable } from './landing.js';
11
+ import { previewHref } from './links.js';
12
+ import { handlePreviewRequest } from './middleware.js';
13
+ import { PREVIEW_CODE_PARAM, previewRoutePrefix, previewScope } from './preview-path.js';
14
+
15
+ /** What the exit route needs to answer without the preview server: the build's own repository, site and branch. */
16
+ export interface PreviewExit {
17
+ repo: string;
18
+ siteId: string;
19
+ branch: string;
20
+ audience: string;
21
+ /** The issuer every pass must name, when the integration options name one. */
22
+ issuer?: string;
23
+ }
24
+
25
+ export type PrefixRoute =
26
+ | { kind: 'outside' }
27
+ /** `<prefix>/_image`: where d8 serves Astro's image endpoint; never a slug. */
28
+ | { kind: 'image' }
29
+ | { kind: 'exit'; slug: string | undefined }
30
+ /** The first segment is not a branch slug: an entry link without one, or a stray path. */
31
+ | { kind: 'slugless'; inner: string; entering: boolean }
32
+ | { kind: 'slugged'; slug: string; rest: string[]; inner: string; route: string; page: URL; entering: boolean }
33
+ /** `<prefix>/<slug>/__media/<path>`: an image of the branch, served from the endpoint; `path` raw, query dropped. */
34
+ | { kind: 'media'; slug: string; path: string; route: string };
35
+
36
+ /** Where a request falls under the preview route; `inner` is the page's own path, base included. */
37
+ export function routePrefixed(url: URL, base: string, mode: 'd3' | 'd8'): PrefixRoute {
38
+ const prefix = previewRoutePrefix(base);
39
+ if (url.pathname !== prefix && !url.pathname.startsWith(`${prefix}/`)) return { kind: 'outside' };
40
+ const root = base.replace(/\/+$/u, '');
41
+ const [first = '', ...rest] = url.pathname.slice(prefix.length + 1).split('/');
42
+ if (first === '__exit' && rest.length === 0) return { kind: 'exit', slug: undefined };
43
+ if (first === '_image' && rest.length === 0) return { kind: 'image' };
44
+ const entering = url.searchParams.has(PREVIEW_CODE_PARAM);
45
+ if (branchOfPreviewSlug(first) === null)
46
+ return { kind: 'slugless', inner: `${root}/${[first, ...rest].join('/')}`, entering };
47
+ if (rest.length === 1 && rest[0] === '__exit') return { kind: 'exit', slug: first };
48
+ if (rest.length > 1 && rest[0] === '__media') {
49
+ return { kind: 'media', slug: first, path: rest.slice(1).join('/'), route: previewScope(mode, base, first).route };
50
+ }
51
+ const inner = `${root}/${rest.join('/')}`;
52
+ return {
53
+ kind: 'slugged',
54
+ slug: first,
55
+ rest,
56
+ inner,
57
+ route: previewScope(mode, base, first).route,
58
+ page: new URL(`${inner}${url.search}`, url.origin),
59
+ entering,
60
+ };
61
+ }
62
+
63
+ /** Whether the request carries the slug's pass or share grant cookie, before anything checks it. */
64
+ export function holdsPreviewCredential(cookie: string | null, mode: 'd3' | 'd8', base: string, slug: string): boolean {
65
+ const scope = previewScope(mode, base, slug);
66
+ return (
67
+ parseCookieValues(cookie, scope.pass).length > 0 ||
68
+ (scope.grant !== null && parseCookieValues(cookie, scope.grant).length > 0)
69
+ );
70
+ }
71
+
72
+ /** The exit route, from the build's own values: the probe never waits for the preview server. */
73
+ export async function answerExit(
74
+ url: URL,
75
+ slug: string | undefined,
76
+ exit: PreviewExit | null,
77
+ base: string,
78
+ endpoint: string,
79
+ mode: 'd3' | 'd8',
80
+ ): Promise<Response> {
81
+ if (exit === null) {
82
+ // No label: Conloca reads "no preview server" and says so, instead of minting a link to a 503 page.
83
+ return applyPreviewHeaders(new Response(null, { status: 302, headers: { location: base } }));
84
+ }
85
+ const verdict = await handlePreviewRequest(
86
+ new Request(`${url.origin}${previewRoutePrefix(base)}/__exit${url.search}`),
87
+ {
88
+ saasEndpoint: endpoint,
89
+ saasAudience: exit.audience,
90
+ repo: exit.repo,
91
+ siteId: exit.siteId,
92
+ branch: exit.branch,
93
+ base,
94
+ mode,
95
+ ...(slug === undefined ? {} : { slug }),
96
+ },
97
+ );
98
+ // The exit branch always answers a response; anything else would be a bug in this call, so fail closed.
99
+ return verdict.kind === 'response'
100
+ ? applyPreviewHeaders(verdict.response)
101
+ : applyPreviewHeaders(new Response(null, { status: 302, headers: { location: base } }));
102
+ }
103
+
104
+ /** "Preview couldn't load the draft": the answer when there is no preview server, or it failed. */
105
+ export function previewUnavailable(retryHref: string, exitHref: string): Response {
106
+ const page = renderPreviewUnavailable({ retryHref, exitHref });
107
+ return applyPreviewHeaders(new Response(page.body, { status: 503, headers: page.headers }));
108
+ }
109
+
110
+ /** An entry answer (a redirect or Conloca's own page) with the preview headers applied and `Location` fixed up. */
111
+ export function finishEntry(
112
+ answer: Response,
113
+ page: URL,
114
+ route: string,
115
+ root: string,
116
+ hosts: ReadonlySet<string>,
117
+ ): Response {
118
+ const out = applyPreviewHeaders(answer);
119
+ const location = out.headers.get('location');
120
+ const moved = location === null ? null : previewHref(location, page, route, root, hosts);
121
+ if (moved !== null) out.headers.set('location', moved);
122
+ return out;
123
+ }
124
+
125
+ function notFound(): Response {
126
+ return applyPreviewHeaders(new Response(null, { status: 404 }));
127
+ }
128
+
129
+ /** A branch SVG opened at this same-origin URL must run no script: no sniffing, a sandboxed resource-free document. */
130
+ const MEDIA_LOCKDOWN = {
131
+ 'x-content-type-options': 'nosniff',
132
+ 'content-security-policy': "default-src 'none'; sandbox",
133
+ };
134
+
135
+ /** A JWT's shape: three base64url parts. */
136
+ const JWT_SHAPE = /^[\w-]+\.[\w-]+\.[\w-]+$/u;
137
+
138
+ /**
139
+ * A branch image, read from the endpoint with the slug's pass. Anything but the image its path names (no pass, a path
140
+ * that is no image ref, a revoked grant, a page, a failing endpoint) is a bodiless 404: refused bytes never reach the page.
141
+ */
142
+ export async function serveDraftMedia(
143
+ request: Request,
144
+ route: Extract<PrefixRoute, { kind: 'media' }>,
145
+ base: string,
146
+ endpoint: string,
147
+ fetchFn: typeof fetch,
148
+ ): Promise<Response> {
149
+ if (request.method !== 'GET' && request.method !== 'HEAD') return notFound();
150
+ const path = mediaRefPath(`/m/${route.path}`, '/m');
151
+ const extension = path?.slice(path.lastIndexOf('.') + 1).toLowerCase() ?? '';
152
+ const mime = Object.hasOwn(IMAGE_EXTENSION_MIME, extension) ? IMAGE_EXTENSION_MIME[extension] : undefined;
153
+ // D3 and d8 name the slug's pass alike. A planted `__Secure-` cookie can come first (`cookie.ts`), so two are tried.
154
+ const passes = parseCookieValues(request.headers.get('cookie'), previewScope('d8', base, route.slug).pass)
155
+ .filter((value) => JWT_SHAPE.test(value))
156
+ .slice(0, 2);
157
+ if (path === undefined || mime === undefined) return notFound();
158
+ const ifNoneMatch = request.headers.get('if-none-match');
159
+ for (const pass of passes) {
160
+ let upstream: Response;
161
+ try {
162
+ // oxlint-disable-next-line no-await-in-loop -- the second pass is read only when the first is refused.
163
+ upstream = await fetchFn(`${endpoint}/preview/media/${path}`, {
164
+ headers: { authorization: `Bearer ${pass}`, ...(ifNoneMatch === null ? {} : { 'if-none-match': ifNoneMatch }) },
165
+ redirect: 'manual',
166
+ });
167
+ } catch (error) {
168
+ console.error('@conloca/cloud-astro: the draft media read failed', error);
169
+ return notFound();
170
+ }
171
+ const etag = upstream.headers.get('etag');
172
+ const headers = new Headers(MEDIA_LOCKDOWN);
173
+ if (etag !== null) headers.set('etag', etag);
174
+ if (upstream.status === 304) return applyPreviewHeaders(new Response(null, { status: 304, headers }));
175
+ const type = upstream.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase();
176
+ if (upstream.status === 200 && type === mime) {
177
+ headers.set('content-type', mime);
178
+ return applyPreviewHeaders(new Response(upstream.body, { status: 200, headers }));
179
+ }
180
+ // oxlint-disable-next-line no-await-in-loop -- as above.
181
+ await upstream.body?.cancel().catch(() => undefined);
182
+ }
183
+ return notFound();
184
+ }
185
+
186
+ /**
187
+ * Astro's image endpoint never reaches the media route (Cloudflare's passthrough reads a local `href` from the static
188
+ * assets only), so an `href` under the route's `__media/` is sent there, where the pass is checked.
189
+ */
190
+ export function mediaImageRedirect(url: URL, base: string, mode: 'd3' | 'd8'): Response | null {
191
+ const href = url.searchParams.get('href');
192
+ if (href === null || !href.startsWith('/') || href.startsWith('//')) return null;
193
+ const target = URL.parse(href, url.origin);
194
+ if (target === null || target.origin !== url.origin || routePrefixed(target, base, mode).kind !== 'media')
195
+ return null;
196
+ return applyPreviewHeaders(new Response(null, { status: 302, headers: { location: target.pathname } }));
197
+ }
@@ -1,3 +1,5 @@
1
+ import { isSluggedPreviewMode, type PreviewMode } from '@conloca/content-api/editor-host';
2
+
1
3
  /**
2
4
  * The fixed preview route and the names it uses.
3
5
  *
@@ -28,8 +30,8 @@ export const PREVIEW_SLUG_HEADER = 'conloca-preview-slug';
28
30
  /** Response header on the exit route's redirect that names how this build serves previews. */
29
31
  export const PREVIEW_MODE_HEADER = 'conloca-preview-mode';
30
32
 
31
- /** How one preview server is reached: D2 and D4 at the page's own path, D3 under the route and the branch slug. */
32
- export type PreviewServeMode = 'd2' | 'd3' | 'd4';
33
+ /** How one preview server is reached: D2 and D4 at the page's own path, D3 and D8 under the route and the branch slug. */
34
+ export type PreviewServeMode = Exclude<PreviewMode, 'off'>;
33
35
 
34
36
  /** One preview's cookie names, the path they live on, and the route its links and exit sit under. */
35
37
  export interface PreviewScope {
@@ -41,12 +43,12 @@ export interface PreviewScope {
41
43
  }
42
44
 
43
45
  /**
44
- * D3 scopes both cookies to `<base>_conloca/preview/<slug>`, so two tabs on two branches keep two passes. D2 and D4
46
+ * D3 and D8 scope both cookies to `<base>_conloca/preview/<slug>`, so two tabs on two branches keep two passes. D2 and D4
45
47
  * keep the `__Host-` names on `Path=/`, which is what lets the pass follow every same-origin link there.
46
48
  */
47
49
  export function previewScope(mode: PreviewServeMode, base: string, slug: string | undefined): PreviewScope {
48
50
  const prefix = previewRoutePrefix(base);
49
- if (mode !== 'd3') {
51
+ if (!isSluggedPreviewMode(mode)) {
50
52
  return {
51
53
  pass: PREVIEW_COOKIE_NAME,
52
54
  grant: mode === 'd4' ? PREVIEW_GRANT_COOKIE_NAME : null,
@@ -54,7 +56,7 @@ export function previewScope(mode: PreviewServeMode, base: string, slug: string
54
56
  route: prefix,
55
57
  };
56
58
  }
57
- if (slug === undefined) throw new Error('@conloca/cloud-astro: a d3 preview scope needs the branch slug');
59
+ if (slug === undefined) throw new Error(`@conloca/cloud-astro: a ${mode} preview scope needs the branch slug`);
58
60
  const route = `${prefix}/${slug}`;
59
61
  return { pass: `__Secure-conloca_preview_${slug}`, grant: `__Secure-conloca_grant_${slug}`, path: route, route };
60
62
  }
@@ -67,7 +69,12 @@ export function previewRoutePrefix(base: string): string {
67
69
  /** The `run_worker_first` entries that belong to the preview, not the site: its route, and the image endpoint drafts use. */
68
70
  export function previewOwnEntries(base: string): string[] {
69
71
  const prefix = previewRoutePrefix(base);
70
- return [prefix, `${prefix}/*`, `${base.replace(/\/+$/u, '')}/_image`];
72
+ return [prefix, `${prefix}/*`, imageEndpointEntry(base)];
73
+ }
74
+
75
+ /** Astro's image endpoint at the base (`'/docs/'` → `/docs/_image`). */
76
+ export function imageEndpointEntry(base: string): string {
77
+ return `${base.replace(/\/+$/u, '')}/_image`;
71
78
  }
72
79
 
73
80
  /**
@@ -101,3 +108,14 @@ export function normalizeTrailingSlash(pathname: string): string {
101
108
  const stripped = pathname.replace(/\/+$/u, '');
102
109
  return stripped === '' ? '/' : stripped;
103
110
  }
111
+
112
+ /** A page path in production's pathname form, so a d8 draft renders at the `Astro.url` its live page has. */
113
+ export function cleanPagePath(
114
+ inner: string,
115
+ trailingSlash: 'always' | 'never' | 'ignore',
116
+ format: 'directory' | 'file' | 'preserve',
117
+ ): string {
118
+ if (inner === '/' || inner.slice(inner.lastIndexOf('/') + 1).includes('.')) return inner;
119
+ const bare = inner.replace(/\/+$/u, '');
120
+ return trailingSlash === 'always' || (trailingSlash === 'ignore' && format === 'directory') ? `${bare}/` : bare;
121
+ }