@conloca/cloud-astro 0.0.0-stage → 0.2.2

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 (196) hide show
  1. package/README.md +328 -2
  2. package/dist/src/build-commit.d.ts +19 -0
  3. package/dist/src/build-commit.d.ts.map +1 -0
  4. package/dist/src/build-commit.js +6 -0
  5. package/dist/src/build-commit.js.map +1 -0
  6. package/dist/src/bundle.d.ts +181 -0
  7. package/dist/src/bundle.d.ts.map +1 -0
  8. package/dist/src/bundle.js +413 -0
  9. package/dist/src/bundle.js.map +1 -0
  10. package/dist/src/component-manifest.d.ts +29 -0
  11. package/dist/src/component-manifest.d.ts.map +1 -0
  12. package/dist/src/component-manifest.js +53 -0
  13. package/dist/src/component-manifest.js.map +1 -0
  14. package/dist/src/constants.d.ts +26 -0
  15. package/dist/src/constants.d.ts.map +1 -0
  16. package/dist/src/constants.js +26 -0
  17. package/dist/src/constants.js.map +1 -0
  18. package/dist/src/descriptors.d.ts +25 -0
  19. package/dist/src/descriptors.d.ts.map +1 -0
  20. package/dist/src/descriptors.js +65 -0
  21. package/dist/src/descriptors.js.map +1 -0
  22. package/dist/src/discovery.d.ts +58 -0
  23. package/dist/src/discovery.d.ts.map +1 -0
  24. package/dist/src/discovery.js +133 -0
  25. package/dist/src/discovery.js.map +1 -0
  26. package/dist/src/doctor/checks-live.d.ts +15 -0
  27. package/dist/src/doctor/checks-live.d.ts.map +1 -0
  28. package/dist/src/doctor/checks-live.js +229 -0
  29. package/dist/src/doctor/checks-live.js.map +1 -0
  30. package/dist/src/doctor/checks-offline.d.ts +36 -0
  31. package/dist/src/doctor/checks-offline.d.ts.map +1 -0
  32. package/dist/src/doctor/checks-offline.js +301 -0
  33. package/dist/src/doctor/checks-offline.js.map +1 -0
  34. package/dist/src/doctor/config-scan.d.ts +55 -0
  35. package/dist/src/doctor/config-scan.d.ts.map +1 -0
  36. package/dist/src/doctor/config-scan.js +178 -0
  37. package/dist/src/doctor/config-scan.js.map +1 -0
  38. package/dist/src/doctor/run.d.ts +4 -0
  39. package/dist/src/doctor/run.d.ts.map +1 -0
  40. package/dist/src/doctor/run.js +29 -0
  41. package/dist/src/doctor/run.js.map +1 -0
  42. package/dist/src/doctor/types.d.ts +60 -0
  43. package/dist/src/doctor/types.d.ts.map +1 -0
  44. package/dist/src/doctor/types.js +18 -0
  45. package/dist/src/doctor/types.js.map +1 -0
  46. package/dist/src/doctor.d.ts +9 -0
  47. package/dist/src/doctor.d.ts.map +1 -0
  48. package/dist/src/doctor.js +12 -0
  49. package/dist/src/doctor.js.map +1 -0
  50. package/dist/src/git.d.ts +38 -0
  51. package/dist/src/git.d.ts.map +1 -0
  52. package/dist/src/git.js +43 -0
  53. package/dist/src/git.js.map +1 -0
  54. package/dist/src/index.d.ts +3 -0
  55. package/dist/src/index.d.ts.map +1 -0
  56. package/dist/src/index.js +7 -0
  57. package/dist/src/index.js.map +1 -0
  58. package/dist/src/integration.d.ts +6 -0
  59. package/dist/src/integration.d.ts.map +1 -0
  60. package/dist/src/integration.js +544 -0
  61. package/dist/src/integration.js.map +1 -0
  62. package/dist/src/message-of.d.ts +3 -0
  63. package/dist/src/message-of.d.ts.map +1 -0
  64. package/dist/src/message-of.js +5 -0
  65. package/dist/src/message-of.js.map +1 -0
  66. package/dist/src/node.d.ts +3 -0
  67. package/dist/src/node.d.ts.map +1 -0
  68. package/dist/src/node.js +4 -0
  69. package/dist/src/node.js.map +1 -0
  70. package/dist/src/package-version.d.ts +7 -0
  71. package/dist/src/package-version.d.ts.map +1 -0
  72. package/dist/src/package-version.js +17 -0
  73. package/dist/src/package-version.js.map +1 -0
  74. package/dist/src/preview/_dispatch.d.ts +55 -0
  75. package/dist/src/preview/_dispatch.d.ts.map +1 -0
  76. package/dist/src/preview/_dispatch.js +72 -0
  77. package/dist/src/preview/_dispatch.js.map +1 -0
  78. package/dist/src/preview/_resolve-opts.d.ts +30 -0
  79. package/dist/src/preview/_resolve-opts.d.ts.map +1 -0
  80. package/dist/src/preview/_resolve-opts.js +73 -0
  81. package/dist/src/preview/_resolve-opts.js.map +1 -0
  82. package/dist/src/preview/banner.d.ts +29 -0
  83. package/dist/src/preview/banner.d.ts.map +1 -0
  84. package/dist/src/preview/banner.js +94 -0
  85. package/dist/src/preview/banner.js.map +1 -0
  86. package/dist/src/preview/content-api.d.ts +110 -0
  87. package/dist/src/preview/content-api.d.ts.map +1 -0
  88. package/dist/src/preview/content-api.js +216 -0
  89. package/dist/src/preview/content-api.js.map +1 -0
  90. package/dist/src/preview/cookie.d.ts +36 -0
  91. package/dist/src/preview/cookie.d.ts.map +1 -0
  92. package/dist/src/preview/cookie.js +59 -0
  93. package/dist/src/preview/cookie.js.map +1 -0
  94. package/dist/src/preview/headers.d.ts +25 -0
  95. package/dist/src/preview/headers.d.ts.map +1 -0
  96. package/dist/src/preview/headers.js +31 -0
  97. package/dist/src/preview/headers.js.map +1 -0
  98. package/dist/src/preview/landing.d.ts +22 -0
  99. package/dist/src/preview/landing.d.ts.map +1 -0
  100. package/dist/src/preview/landing.js +70 -0
  101. package/dist/src/preview/landing.js.map +1 -0
  102. package/dist/src/preview/middleware.d.ts +118 -0
  103. package/dist/src/preview/middleware.d.ts.map +1 -0
  104. package/dist/src/preview/middleware.js +197 -0
  105. package/dist/src/preview/middleware.js.map +1 -0
  106. package/dist/src/preview/preview-path.d.ts +21 -0
  107. package/dist/src/preview/preview-path.d.ts.map +1 -0
  108. package/dist/src/preview/preview-path.js +29 -0
  109. package/dist/src/preview/preview-path.js.map +1 -0
  110. package/dist/src/preview/satteri-workerd.d.ts +17 -0
  111. package/dist/src/preview/satteri-workerd.d.ts.map +1 -0
  112. package/dist/src/preview/satteri-workerd.js +18 -0
  113. package/dist/src/preview/satteri-workerd.js.map +1 -0
  114. package/dist/src/preview/site-middleware.d.ts +69 -0
  115. package/dist/src/preview/site-middleware.d.ts.map +1 -0
  116. package/dist/src/preview/site-middleware.js +160 -0
  117. package/dist/src/preview/site-middleware.js.map +1 -0
  118. package/dist/src/preview/workerd-shim.d.ts +19 -0
  119. package/dist/src/preview/workerd-shim.d.ts.map +1 -0
  120. package/dist/src/preview/workerd-shim.js +33 -0
  121. package/dist/src/preview/workerd-shim.js.map +1 -0
  122. package/dist/src/preview-build.d.ts +71 -0
  123. package/dist/src/preview-build.d.ts.map +1 -0
  124. package/dist/src/preview-build.js +115 -0
  125. package/dist/src/preview-build.js.map +1 -0
  126. package/dist/src/preview.d.ts +6 -0
  127. package/dist/src/preview.d.ts.map +1 -0
  128. package/dist/src/preview.js +12 -0
  129. package/dist/src/preview.js.map +1 -0
  130. package/dist/src/register.d.ts +98 -0
  131. package/dist/src/register.d.ts.map +1 -0
  132. package/dist/src/register.js +103 -0
  133. package/dist/src/register.js.map +1 -0
  134. package/dist/src/repository.d.ts +18 -0
  135. package/dist/src/repository.d.ts.map +1 -0
  136. package/dist/src/repository.js +46 -0
  137. package/dist/src/repository.js.map +1 -0
  138. package/dist/src/site-id.d.ts +18 -0
  139. package/dist/src/site-id.d.ts.map +1 -0
  140. package/dist/src/site-id.js +70 -0
  141. package/dist/src/site-id.js.map +1 -0
  142. package/dist/src/site-middleware.d.ts +18 -0
  143. package/dist/src/site-middleware.d.ts.map +1 -0
  144. package/dist/src/site-middleware.js +47 -0
  145. package/dist/src/site-middleware.js.map +1 -0
  146. package/dist/src/skill.d.ts +26 -0
  147. package/dist/src/skill.d.ts.map +1 -0
  148. package/dist/src/skill.js +67 -0
  149. package/dist/src/skill.js.map +1 -0
  150. package/dist/src/types.d.ts +135 -0
  151. package/dist/src/types.d.ts.map +1 -0
  152. package/dist/src/types.js +2 -0
  153. package/dist/src/types.js.map +1 -0
  154. package/package.json +182 -4
  155. package/src/build-commit.ts +22 -0
  156. package/src/bundle.ts +570 -0
  157. package/src/component-manifest.ts +75 -0
  158. package/src/constants.ts +28 -0
  159. package/src/descriptors.ts +92 -0
  160. package/src/discovery.ts +183 -0
  161. package/src/doctor/checks-live.ts +324 -0
  162. package/src/doctor/checks-offline.ts +325 -0
  163. package/src/doctor/config-scan.ts +205 -0
  164. package/src/doctor/run.ts +39 -0
  165. package/src/doctor/types.ts +71 -0
  166. package/src/doctor.ts +14 -0
  167. package/src/git.ts +66 -0
  168. package/src/index.ts +8 -0
  169. package/src/integration.ts +607 -0
  170. package/src/message-of.ts +4 -0
  171. package/src/node.ts +5 -0
  172. package/src/package-version.ts +16 -0
  173. package/src/preview/_dispatch.ts +105 -0
  174. package/src/preview/_resolve-opts.ts +89 -0
  175. package/src/preview/banner.ts +96 -0
  176. package/src/preview/content-api.ts +293 -0
  177. package/src/preview/cookie.ts +54 -0
  178. package/src/preview/headers.ts +30 -0
  179. package/src/preview/landing.ts +73 -0
  180. package/src/preview/middleware.ts +309 -0
  181. package/src/preview/preview-path.ts +28 -0
  182. package/src/preview/satteri-workerd.ts +24 -0
  183. package/src/preview/site-middleware.ts +210 -0
  184. package/src/preview/workerd-shim.ts +31 -0
  185. package/src/preview-build.ts +147 -0
  186. package/src/preview-handler.astro +55 -0
  187. package/src/preview-handler.d.ts +6 -0
  188. package/src/preview.ts +22 -0
  189. package/src/register.ts +180 -0
  190. package/src/repository.ts +54 -0
  191. package/src/site-id.ts +86 -0
  192. package/src/site-middleware.ts +55 -0
  193. package/src/skill/SKILL.md +69 -0
  194. package/src/skill.ts +66 -0
  195. package/src/types.ts +137 -0
  196. package/src/virtual-modules.d.ts +52 -0
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Renders the "no preview context" landing page returned when a request
3
+ * hits the secret-scoped preview route but carries neither a fresh query
4
+ * param nor a valid cookie.
5
+ *
6
+ * With no preview context the page must offer two routes out:
7
+ * - "Log in to edit" deep-link, preserving the requested pathname so
8
+ * the editor knows which page the user was trying to preview.
9
+ * - "Go to production" link pointing at the same path on the production
10
+ * domain. The middleware does not know the production hostname here
11
+ * (preview can run on a separate `previewDomain` or on the production
12
+ * host itself), so the link is rendered as a same-path relative URL
13
+ * and the user navigates from there.
14
+ *
15
+ * The page is wrapped with `x-robots-tag: noindex` so a leak of the URL
16
+ * cannot get indexed.
17
+ */
18
+ export function renderNoPreviewLanding(opts: { pathname: string; saasEndpoint: string }): Response {
19
+ // The deep-link to the endpoint's editor preserves both the path the user
20
+ // was trying to preview and the endpoint that issues the JWT.
21
+ const loginUrl = new URL('/login', opts.saasEndpoint);
22
+ loginUrl.searchParams.set('return', opts.pathname);
23
+ const escapedPath = escapeHtml(opts.pathname);
24
+ const escapedLogin = escapeHtml(loginUrl.toString());
25
+
26
+ const body = [
27
+ '<!doctype html>',
28
+ '<html lang="en">',
29
+ '<head>',
30
+ '<meta charset="utf-8">',
31
+ '<meta name="viewport" content="width=device-width, initial-scale=1">',
32
+ '<meta name="robots" content="noindex, nofollow">',
33
+ '<title>Conloca preview</title>',
34
+ '<style>body{font-family:system-ui,sans-serif;max-width:32rem;margin:8rem auto;padding:0 1rem;line-height:1.5;color:#1a1a1a}h1{margin-bottom:1rem}a.btn{display:inline-block;padding:0.75rem 1.25rem;margin-right:0.5rem;border-radius:6px;text-decoration:none}a.btn.primary{background:#111;color:#fff}a.btn.secondary{border:1px solid #ccc;color:#1a1a1a}</style>',
35
+ '</head>',
36
+ '<body>',
37
+ '<h1>This is a Conloca preview environment</h1>',
38
+ '<p>To preview unreleased content you need to log in. Otherwise visit the production site.</p>',
39
+ '<p>',
40
+ `<a class="btn primary" href="${escapedLogin}">Log in to edit</a>`,
41
+ `<a class="btn secondary" href="${escapedPath}">Go to production</a>`,
42
+ '</p>',
43
+ '</body>',
44
+ '</html>',
45
+ ].join('');
46
+
47
+ return new Response(body, {
48
+ status: 200,
49
+ headers: {
50
+ 'content-type': 'text/html; charset=utf-8',
51
+ 'x-robots-tag': 'noindex',
52
+ 'cache-control': 'private, no-store',
53
+ // This is a Conloca-authored page (only an inline <style>, no scripts),
54
+ // so it carries a tight own CSP — no script execution, no framing.
55
+ 'content-security-policy':
56
+ "default-src 'none'; style-src 'unsafe-inline'; img-src 'self' data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
57
+ },
58
+ });
59
+ }
60
+
61
+ /**
62
+ * Minimal HTML attribute/text escaper — enough to prevent the rendered
63
+ * pathname from breaking out of an attribute or injecting markup. We do
64
+ * not pull in a dependency for one helper used in one place.
65
+ */
66
+ function escapeHtml(value: string): string {
67
+ return value
68
+ .replace(/&/g, '&amp;')
69
+ .replace(/</g, '&lt;')
70
+ .replace(/>/g, '&gt;')
71
+ .replace(/"/g, '&quot;')
72
+ .replace(/'/g, '&#39;');
73
+ }
@@ -0,0 +1,309 @@
1
+ import { createRemoteJWKSet, customFetch, type JWTPayload, type JWTVerifyGetKey, jwtVerify } from 'jose';
2
+ import { parseCookies, serializePreviewCookie } from './cookie.js';
3
+ import { renderNoPreviewLanding } from './landing.js';
4
+ import { stripPreviewPrefix } from './preview-path.js';
5
+
6
+ /**
7
+ * Options consumed by {@link handlePreviewRequest}.
8
+ *
9
+ * `secret` is the per-branch preview secret the endpoint issued at
10
+ * registration time. It scopes both the query-parameter name
11
+ * (`?conloca_preview_${secret}=`) and the cookie name, and must never land in
12
+ * a browser bundle.
13
+ *
14
+ * `getKey` is an optional JWKS resolver injection seam. When omitted, the
15
+ * middleware constructs a `createRemoteJWKSet` pointed at
16
+ * `${saasEndpoint}/.well-known/jwks.json` and uses jose's built-in JWKS
17
+ * cache. Tests inject a local public-key resolver so JWT validation runs
18
+ * deterministically without touching the network.
19
+ */
20
+ export interface PreviewMiddlewareOptions {
21
+ secret: string;
22
+ saasEndpoint: string;
23
+ saasIssuer: string;
24
+ saasAudience: string;
25
+ /**
26
+ * The commit this preview artifact was built from. Page-status compares the
27
+ * branch's committed head with it; absent (an older artifact) ⇒ the
28
+ * endpoint compares with the branch's registered build instead.
29
+ */
30
+ buildCommit?: string;
31
+ getKey?: JWTVerifyGetKey;
32
+ /**
33
+ * Transport for the JWKS fetch. A deployment that cannot reach the endpoint
34
+ * with a plain fetch by hostname supplies a Cloudflare binding's fetch here;
35
+ * otherwise key discovery gets another server's answer and every token
36
+ * looks forged.
37
+ */
38
+ fetchFn?: typeof fetch;
39
+ /**
40
+ * What to do when the request carries no valid preview credential.
41
+ *
42
+ * - `'landing'` (default) — the no-preview landing page. Correct for the
43
+ * secret-prefixed entry route, which nobody reaches by accident.
44
+ * - `'pass-through'` — let the request continue to the ordinary page. Correct
45
+ * for the site-wide interceptor, which sees every request in the preview
46
+ * build: an uncredentialed visitor must get the normal site, not a landing
47
+ * screen on every URL.
48
+ */
49
+ onMiss?: 'landing' | 'pass-through';
50
+ }
51
+
52
+ /**
53
+ * Decoded preview context placed on `Astro.locals.conlocaPreview` for the
54
+ * downstream renderer.
55
+ *
56
+ * The `PreviewContentAPI` reader consumes the same shape; this module owns
57
+ * the type rather than importing it from the reader, so the middleware stands
58
+ * alone.
59
+ */
60
+ export interface PreviewContext {
61
+ branch: string;
62
+ org: string;
63
+ repo: string;
64
+ jwt: string;
65
+ /** Seconds until the JWT expires — bounds the preview cookie's Max-Age. */
66
+ expiresInSeconds?: number;
67
+ }
68
+
69
+ // Augments Astro's `Locals` so a site's .astro files that read
70
+ // `Astro.locals.conlocaPreview` get the proper type. The augmentation ships in
71
+ // this module's declarations, so a site opts in by adding
72
+ // `/// <reference types="@conloca/cloud-astro/preview" />` to its project's
73
+ // `env.d.ts`.
74
+ declare global {
75
+ namespace App {
76
+ interface Locals {
77
+ conlocaPreview?: PreviewContext;
78
+ }
79
+ }
80
+ }
81
+
82
+ /**
83
+ * The three verdicts the preview middleware can return to its caller.
84
+ *
85
+ * - `response` — the caller MUST return this Response unchanged (used for
86
+ * the 302 init redirect and the no-preview landing page).
87
+ * - `preview` — the caller MUST set `Astro.locals.conlocaPreview = ctx`
88
+ * and dispatch to the preview renderer.
89
+ * - `pass-through` — the caller MAY delegate to the ordinary page or
90
+ * static-asset handler. Returned when `onMiss: 'pass-through'` is set —
91
+ * the site-wide interceptor's mode, where an uncredentialed request must
92
+ * get the normal site. The secret-prefixed entry route omits `onMiss`
93
+ * and never sees this verdict.
94
+ */
95
+ export type PreviewVerdict =
96
+ | { kind: 'pass-through' }
97
+ | { kind: 'preview'; ctx: PreviewContext }
98
+ | { kind: 'response'; response: Response };
99
+
100
+ /**
101
+ * Inspects a preview-route request and decides whether to validate, redirect,
102
+ * or render a landing page. See the docstring on {@link PreviewVerdict} for
103
+ * the caller contract.
104
+ *
105
+ * Order of checks:
106
+ * 1. `?conloca_preview_${secret}=<JWT>` query param → validate; on
107
+ * success issue a 302 with the cookie set and the query stripped.
108
+ * 2. `conloca_preview_${secret}=<JWT>` cookie → validate; on success
109
+ * return a `preview` verdict with the decoded context.
110
+ * 3. Neither present → no-preview landing page response.
111
+ *
112
+ * Invalid JWTs (tampered signature, expired, missing required claim, wrong
113
+ * issuer/audience/scope) fall through to the landing page. We deliberately do
114
+ * NOT return 401 — a 401 to an unauthenticated caller would confirm that
115
+ * a particular path is preview-only, which leaks information about what
116
+ * the branch contains.
117
+ */
118
+ export async function handlePreviewRequest(request: Request, opts: PreviewMiddlewareOptions): Promise<PreviewVerdict> {
119
+ const url = new URL(request.url);
120
+ const queryName = previewParamName(opts.secret);
121
+ const cookieName = previewParamName(opts.secret);
122
+
123
+ // 0. Exit route: the banner's "Exit Preview" target. The cookie is HttpOnly
124
+ // on purpose, so leaving preview needs a server response that expires it.
125
+ // Handled before the credential checks — an expired cookie must not strand
126
+ // the visitor in a preview they can no longer exit.
127
+ if (url.pathname === `/${previewParamName(opts.secret)}/__exit`) {
128
+ return { kind: 'response', response: makeExitRedirect(url, opts.secret) };
129
+ }
130
+
131
+ // 1. Query-param init path.
132
+ const queryToken = url.searchParams.get(queryName);
133
+ if (queryToken !== null) {
134
+ const ctx = await tryValidate(queryToken, opts);
135
+ if (ctx) {
136
+ return {
137
+ kind: 'response',
138
+ response: makeInitRedirect(url, queryName, queryToken, opts.secret, ctx.expiresInSeconds),
139
+ };
140
+ }
141
+ // Invalid query-param JWT — fall through to the landing page rather than
142
+ // issuing a 401 (see docstring).
143
+ return {
144
+ kind: 'response',
145
+ response: renderNoPreviewLanding({ pathname: stripPreviewPrefix(url.pathname), saasEndpoint: opts.saasEndpoint }),
146
+ };
147
+ }
148
+
149
+ // 2. Cookie path.
150
+ const cookies = parseCookies(request.headers.get('cookie'));
151
+ const cookieToken = cookies.get(cookieName);
152
+ if (cookieToken !== undefined) {
153
+ const ctx = await tryValidate(cookieToken, opts);
154
+ if (ctx) {
155
+ return { kind: 'preview', ctx };
156
+ }
157
+ }
158
+
159
+ // 3. No valid preview context.
160
+ if (opts.onMiss === 'pass-through') {
161
+ return { kind: 'pass-through' };
162
+ }
163
+ return {
164
+ kind: 'response',
165
+ // Stripped: the landing's "Go to production" link is the same path
166
+ // relative — rendered with the secret prefix it loops back to itself.
167
+ response: renderNoPreviewLanding({ pathname: stripPreviewPrefix(url.pathname), saasEndpoint: opts.saasEndpoint }),
168
+ };
169
+ }
170
+
171
+ /**
172
+ * Derives the query-param / cookie name from the per-branch secret. The
173
+ * name doubles as a load guard: a same-domain request-runtime wrapper
174
+ * checks for this exact string before invoking the SSR handler, so random
175
+ * `?conloca_preview_*` query strings cannot wake the preview path.
176
+ */
177
+ export function previewParamName(secret: string): string {
178
+ return `conloca_preview_${secret}`;
179
+ }
180
+
181
+ /**
182
+ * Validates a JWT and projects its claims into a {@link PreviewContext}.
183
+ * Returns `null` on any validation failure — the failure reason is not
184
+ * surfaced because callers fall through to the same landing-page path
185
+ * regardless of which check failed.
186
+ */
187
+ async function tryValidate(token: string, opts: PreviewMiddlewareOptions): Promise<PreviewContext | null> {
188
+ const getKey = opts.getKey ?? defaultJwksResolver(opts.saasEndpoint, opts.fetchFn);
189
+ try {
190
+ const { payload } = await jwtVerify(token, getKey, {
191
+ issuer: opts.saasIssuer,
192
+ audience: opts.saasAudience,
193
+ });
194
+ return projectContext(payload, token);
195
+ } catch {
196
+ return null;
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Lazily constructed `createRemoteJWKSet` for the given endpoint. We
202
+ * cache one resolver per endpoint string so jose's built-in cooldown +
203
+ * cache TTL apply across requests (constructing a fresh JWKS resolver on
204
+ * every request would defeat the cache). Tests inject their own resolver
205
+ * via `opts.getKey` and never hit this path.
206
+ */
207
+ const jwksCache = new Map<string, JWTVerifyGetKey>();
208
+ function defaultJwksResolver(endpoint: string, fetchFn?: typeof fetch): JWTVerifyGetKey {
209
+ // The transport is part of the cache key: the same endpoint reached through a
210
+ // Cloudflare binding and over the public internet are different resolvers.
211
+ const key = fetchFn ? `service:${endpoint}` : `public:${endpoint}`;
212
+ let resolver = jwksCache.get(key);
213
+ if (!resolver) {
214
+ resolver = createRemoteJWKSet(
215
+ new URL('/.well-known/jwks.json', endpoint),
216
+ fetchFn ? { [customFetch]: fetchFn } : undefined,
217
+ );
218
+ jwksCache.set(key, resolver);
219
+ }
220
+ return resolver;
221
+ }
222
+
223
+ /**
224
+ * Project a verified JWT payload into the preview context envelope. Returns
225
+ * `null` if any required claim is missing or wrong type — a JWT that
226
+ * validates cryptographically but lacks `branch` names no branch to read,
227
+ * so it is treated as invalid here.
228
+ */
229
+ function projectContext(payload: JWTPayload, jwt: string): PreviewContext | null {
230
+ if (payload.scope !== 'preview') return null;
231
+ const branch = readStringClaim(payload, 'branch');
232
+ const org = readStringClaim(payload, 'org');
233
+ const repo = readStringClaim(payload, 'repo');
234
+ if (!branch || !org || !repo) return null;
235
+ // Remaining token lifetime, so the cookie can be bounded to the credential
236
+ // it carries rather than living for the whole browser session. `exp` is
237
+ // already verified by `jwtVerify` above, so it is present and in the future.
238
+ const expiresInSeconds =
239
+ typeof payload.exp === 'number' ? Math.max(0, payload.exp - Math.floor(Date.now() / 1000)) : undefined;
240
+ return { branch, org, repo, jwt, expiresInSeconds };
241
+ }
242
+
243
+ function readStringClaim(payload: JWTPayload, name: string): string | undefined {
244
+ const value: unknown = payload[name];
245
+ return typeof value === 'string' && value.length > 0 ? value : undefined;
246
+ }
247
+
248
+ /**
249
+ * Builds the 302 response that strips the preview query parameter from
250
+ * the requested URL and sets the preview cookie. Preserves every other
251
+ * query parameter so analytics / utm tags survive the redirect.
252
+ *
253
+ * The caller passes both the query-param name (so we know which key to
254
+ * strip) and the raw secret (so we can derive the cookie name without a
255
+ * roundtrip parse). The two are bound by `previewParamName(secret)` ===
256
+ * `queryName` at the call site.
257
+ */
258
+ /**
259
+ * Builds the 302 that expires the preview cookie and returns the visitor to
260
+ * the published page. `?to=` names the page the banner was on; only a
261
+ * same-origin absolute path is accepted (a full URL or `//host` would turn
262
+ * this route into an open redirect), anything else falls back to `/`.
263
+ */
264
+ function makeExitRedirect(url: URL, secret: string): Response {
265
+ const to = url.searchParams.get('to') ?? '/';
266
+ const target = to.startsWith('/') && !to.startsWith('//') ? to : '/';
267
+ return new Response(null, {
268
+ status: 302,
269
+ headers: {
270
+ location: target,
271
+ 'set-cookie': serializePreviewCookie(previewParamName(secret), '', 0),
272
+ 'cache-control': 'private, no-store',
273
+ },
274
+ });
275
+ }
276
+
277
+ function makeInitRedirect(
278
+ url: URL,
279
+ queryName: string,
280
+ token: string,
281
+ secret: string,
282
+ maxAgeSeconds?: number,
283
+ ): Response {
284
+ const cleaned = new URL(url.toString());
285
+ cleaned.searchParams.delete(queryName);
286
+ // Land the browser on the REAL site path, not the secret-prefixed one.
287
+ // The prefix is an entry door: it exists so the endpoint has a URL to link to
288
+ // before any cookie exists. Once the cookie is set (Path=/), every
289
+ // same-origin request carries the credential, so the visitor belongs on the
290
+ // canonical path — otherwise the first internal link they click drops the
291
+ // prefix, escapes preview, and silently shows published content.
292
+ cleaned.pathname = stripPreviewPrefix(cleaned.pathname);
293
+ // Normalise the search string: when the only param was the preview JWT,
294
+ // URL.search becomes '' but URL.toString() still emits a trailing `?` only
295
+ // if it was already empty. Re-serialising via URL strips that automatically;
296
+ // double-check by explicitly clearing the `?` when no params remain.
297
+ let location = cleaned.toString();
298
+ if (cleaned.search === '' && location.endsWith('?')) {
299
+ location = location.slice(0, -1);
300
+ }
301
+ return new Response(null, {
302
+ status: 302,
303
+ headers: {
304
+ location,
305
+ 'set-cookie': serializePreviewCookie(previewParamName(secret), token, maxAgeSeconds),
306
+ 'cache-control': 'private, no-store',
307
+ },
308
+ });
309
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Strip a leading `/conloca_preview_<secret>` segment from a pathname.
3
+ *
4
+ * Lives in its own module because the entry-hop middleware, the site
5
+ * middleware and the page-status client all need it without depending on
6
+ * each other.
7
+ *
8
+ * The match is anchored at the FIRST segment only — a path like
9
+ * `/posts/conloca_preview_x/about` is left untouched, so a page that merely
10
+ * mentions the prefix mid-tree is never re-anchored to a different page.
11
+ */
12
+ export function stripPreviewPrefix(pathname: string): string {
13
+ const match = /^\/conloca_preview_[^/]+(\/.*)?$/.exec(pathname);
14
+ if (!match) return pathname;
15
+ return match[1] ?? '/';
16
+ }
17
+
18
+ /**
19
+ * Canonical path form for page-status lookups and production rewrites: no
20
+ * trailing slash, except the root itself. Browser-facing links carry trailing
21
+ * slashes ('/faq/') the canonical entry pathnames don't; the endpoint resolves
22
+ * pathnames by exact match. Mirrors astro-cms's `normalizePathname` — kept
23
+ * separate so this module stays dependency-free (see the note above).
24
+ */
25
+ export function normalizeTrailingSlash(pathname: string): string {
26
+ const stripped = pathname.replace(/\/+$/u, '');
27
+ return stripped === '' ? '/' : stripped;
28
+ }
@@ -0,0 +1,24 @@
1
+ import { fromHtml } from 'hast-util-from-html';
2
+
3
+ /** The options satteri's `htmlToHast` accepts. */
4
+ export interface HtmlToHastOptions {
5
+ fragment?: boolean;
6
+ space?: 'html' | 'svg';
7
+ }
8
+
9
+ /**
10
+ * Stands in for satteri's `htmlToHast` in the Cloudflare preview build:
11
+ * satteri's Cloudflare Workers binding can be neither installed nor run on workerd, so
12
+ * the preview build resolves bare `satteri` here instead. Only `htmlToHast`
13
+ * exists on purpose — any other satteri import then fails the build loudly
14
+ * rather than crashing at render time. SVG input is wrapped in `<svg>` because
15
+ * satteri parses it in SVG context (a self-closing `<path/>` stays a sibling),
16
+ * while `hast-util-from-html` would tokenize it as HTML and nest the elements.
17
+ */
18
+ export function htmlToHast(html: string, options: HtmlToHastOptions = {}): ReturnType<typeof fromHtml> {
19
+ if (options.space === 'svg') {
20
+ const [svg] = fromHtml(`<svg>${html}</svg>`, { fragment: true }).children;
21
+ return { type: 'root', children: svg?.type === 'element' ? svg.children : [] };
22
+ }
23
+ return fromHtml(html, { fragment: options.fragment, space: options.space });
24
+ }
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Site-wide preview middleware for the recursive preview build — the SERVING
3
+ * SURFACE of draft preview.
4
+ *
5
+ * WHY THIS EXISTS — the secret path prefix is an entry door, not the serving
6
+ * surface. Without this, preview survives exactly one page view: the visitor
7
+ * lands on `/conloca_preview_<secret>/about`, clicks a link, and the
8
+ * root-absolute `/blog` the site's template emitted drops the prefix and
9
+ * silently serves the PUBLISHED page. The preview cookie is already `Path=/`,
10
+ * so the browser is sending the credential on that request — this listens.
11
+ *
12
+ * WHY THE RENDER HAPPENS HERE, VIA `next()` — a middleware rewrite onto the
13
+ * secret-prefixed handler (the previous design) forced the render through
14
+ * `Astro.rewrite`, whose route matching does not fall through prerendered
15
+ * routes: with two root catch-alls (the CMS pages route on demand, a docs
16
+ * integration's route prerendered) the rewrite matched the prerendered one
17
+ * and threw. Request-level routing — what `next()` continues into — DOES fall
18
+ * through a prerendered dynamic match to the first on-demand route, i.e. the
19
+ * CMS handler for CMS pathnames. So the middleware validates the credential,
20
+ * asks the endpoint for the page's render-graph status, installs the branch
21
+ * reader on `locals.contentApi`, and lets the site's own route render it;
22
+ * the response then gets the banner + robots/cache headers.
23
+ *
24
+ * Mounted only inside the recursive preview build; never in the site's
25
+ * production build. Deliberately fail-open: any request without a valid
26
+ * preview credential passes straight through to the ordinary page.
27
+ */
28
+
29
+ import type { ContentAPI } from '@conloca/content-api';
30
+ import { fetchPageStatus, type PageStatus } from './_dispatch.js';
31
+ import { injectPreviewBanner } from './banner.js';
32
+ import { PreviewContentAPI } from './content-api.js';
33
+ import { applyPreviewHeaders } from './headers.js';
34
+ import {
35
+ handlePreviewRequest,
36
+ type PreviewContext,
37
+ type PreviewMiddlewareOptions,
38
+ previewParamName,
39
+ } from './middleware.js';
40
+ import { normalizeTrailingSlash, stripPreviewPrefix } from './preview-path.js';
41
+
42
+ /** The subset of Astro's middleware context this middleware touches. */
43
+ export interface PreviewMiddlewareContext {
44
+ request: Request;
45
+ locals: { conlocaPreview?: PreviewContext; contentApi?: ContentAPI };
46
+ url: URL;
47
+ }
48
+
49
+ export type PreviewMiddlewareNext = () => Promise<Response>;
50
+
51
+ /**
52
+ * Render dependencies the binding entry supplies. A seam object (not module
53
+ * imports) because the collection-backed baseline needs `astro:content` and
54
+ * the routing config — both exist only inside the site's own build graph,
55
+ * which the entry module (`src/site-middleware.ts`) is compiled into.
56
+ */
57
+ export interface PreviewRenderSeams {
58
+ /** Lazily builds the collection-backed baseline reader. Called per preview render. */
59
+ baselineApi: () => Promise<ContentAPI>;
60
+ /** Site/locale from the routing config, threaded into the page-status call. */
61
+ site?: string;
62
+ locale?: string;
63
+ /**
64
+ * Transport for every endpoint call this middleware makes (JWKS,
65
+ * page-status, content reads). The binding entry supplies a binding's fetch
66
+ * when the Cloudflare Workers runtime exposes the endpoint binding (see
67
+ * `resolveEndpointFetch`), for deployments that cannot reach the endpoint
68
+ * with a plain fetch by hostname.
69
+ */
70
+ fetchFn?: typeof fetch;
71
+ }
72
+
73
+ /**
74
+ * Builds the Astro middleware `onRequest` handler.
75
+ *
76
+ * `resolveOpts` is a thunk so the (throwing) env-var resolution happens per
77
+ * request rather than at module load — a misconfigured runtime should fail the
78
+ * request with a diagnosable error, not prevent the whole site from booting.
79
+ */
80
+ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddlewareOptions, seams: PreviewRenderSeams) {
81
+ return async function onRequest(context: PreviewMiddlewareContext, next: PreviewMiddlewareNext): Promise<Response> {
82
+ // Already inside a preview render — don't re-run the credential check.
83
+ if (context.locals.conlocaPreview) return next();
84
+
85
+ // Resolving the runtime env throws when preview was never configured — and
86
+ // ALSO at build time, where Astro runs middleware while prerendering pages
87
+ // and the deployer's runtime vars do not exist yet. Neither is a reason to
88
+ // break the site's build or the whole site over a feature it may
89
+ // not use, so pass through and warn once. The secret-prefixed entry route
90
+ // still fails loudly: reaching it means someone explicitly asked to preview.
91
+ let opts: PreviewMiddlewareOptions;
92
+ try {
93
+ opts = resolveOpts();
94
+ } catch (error) {
95
+ warnUnconfiguredOnce(error);
96
+ return next();
97
+ }
98
+
99
+ const verdict = await handlePreviewRequest(context.request, {
100
+ ...opts,
101
+ onMiss: 'pass-through',
102
+ fetchFn: opts.fetchFn ?? seams.fetchFn,
103
+ });
104
+ if (verdict.kind === 'response') return verdict.response;
105
+ if (verdict.kind !== 'preview') return next();
106
+
107
+ // A valid credential on the LITERAL secret-prefixed URL: canonicalize to
108
+ // the clean site path instead of rendering under the prefix — links,
109
+ // assets and the page lookup all assume clean paths.
110
+ const rawPath = context.url.pathname;
111
+ const path = normalizeTrailingSlash(stripPreviewPrefix(rawPath));
112
+ if (stripPreviewPrefix(rawPath) !== rawPath) {
113
+ return new Response(null, {
114
+ status: 302,
115
+ headers: { location: path, 'cache-control': 'private, no-store' },
116
+ });
117
+ }
118
+
119
+ context.locals.conlocaPreview = verdict.ctx;
120
+ // An endpoint failure (5xx mid-deploy, auth envelope, network) must not 500
121
+ // the whole site for a visitor holding the HttpOnly cookie they cannot
122
+ // remove — degrade to published bytes, keeping the preview headers.
123
+ let status: PageStatus;
124
+ try {
125
+ status = await fetchPageStatus({
126
+ saasEndpoint: opts.saasEndpoint,
127
+ ctx: verdict.ctx,
128
+ path,
129
+ site: seams.site,
130
+ locale: seams.locale,
131
+ build: opts.buildCommit,
132
+ fetchFn: seams.fetchFn,
133
+ });
134
+ } catch (error) {
135
+ console.warn(
136
+ `[@conloca/cloud-astro] preview page-status failed for ${path} — serving the published page instead: ` +
137
+ `${error instanceof Error ? error.message : String(error)}`,
138
+ );
139
+ return applyPreviewHeaders(await next());
140
+ }
141
+
142
+ if (status.kind === 'unchanged') {
143
+ // Production-equivalent bytes: render the ordinary route against the
144
+ // build's own collections. No banner — same delegated semantics as
145
+ // before — but preview responses always carry the robots/cache headers.
146
+ return applyPreviewHeaders(await next());
147
+ }
148
+
149
+ if (status.kind === 'redirect') {
150
+ // Always 302 (fetchPageStatus already downgraded 301) so a stale preview
151
+ // redirect can never be cached by intermediaries.
152
+ return new Response(null, {
153
+ status: 302,
154
+ headers: { location: status.target, 'cache-control': 'private, no-store' },
155
+ });
156
+ }
157
+
158
+ // 'changed' and 'deleted' both render through the site's own route with
159
+ // the branch reader installed. For 'deleted' the branch listing no longer
160
+ // contains the page, so the site's own not-found flow runs (astro-cms:
161
+ // PAGE_NOT_FOUND → the configured fallback), which is the truthful render
162
+ // of a branch that removed the page.
163
+ const previewApi = new PreviewContentAPI({
164
+ saasEndpoint: opts.saasEndpoint,
165
+ ctx: verdict.ctx,
166
+ baselineApi: await seams.baselineApi(),
167
+ embeddedPayloads: status.kind === 'changed' ? status.embedded : new Map(),
168
+ fetchFn: seams.fetchFn,
169
+ });
170
+ // Prime the branch page listing before the renderer enumerates content:
171
+ // `listAllContent` is synchronous, and a page created on the branch is
172
+ // absent from the build baseline entirely.
173
+ await previewApi.loadBranchManifests();
174
+ context.locals.contentApi = previewApi;
175
+
176
+ const rendered = await next();
177
+ const contentType = rendered.headers.get('content-type') ?? '';
178
+ if (!contentType.includes('text/html')) {
179
+ // Redirects (e.g. the not-found fallback) and non-HTML responses pass
180
+ // through with the preview headers only.
181
+ return applyPreviewHeaders(rendered);
182
+ }
183
+ const html = injectPreviewBanner(
184
+ await rendered.text(),
185
+ verdict.ctx,
186
+ opts.saasEndpoint,
187
+ `/${previewParamName(opts.secret)}/__exit`,
188
+ );
189
+ return applyPreviewHeaders(new Response(html, { status: rendered.status, headers: rendered.headers }));
190
+ };
191
+ }
192
+
193
+ /**
194
+ * Warn once per process that the middleware is inert.
195
+ *
196
+ * Once, not per request: this runs on every request in the preview build, and
197
+ * a per-request warning would bury the site's own build/server output.
198
+ */
199
+ let warned = false;
200
+ function warnUnconfiguredOnce(error: unknown): void {
201
+ if (warned) return;
202
+ warned = true;
203
+ const detail = error instanceof Error ? error.message : String(error);
204
+ console.warn(
205
+ `[@conloca/cloud-astro] draft preview is INERT — ${detail}\n` +
206
+ ' Requests are being served as the ordinary published site.\n' +
207
+ ' Draft previews on your own deployment are not available yet: keep previewBuild: false ' +
208
+ '(see the cloud-astro README "Draft previews").',
209
+ );
210
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Strips the `[object process]` masquerade from workerd's nodejs_compat
3
+ * `process` shim.
4
+ *
5
+ * Astro picks its response-body strategy with
6
+ * `Object.prototype.toString.call(process) === '[object process]'`
7
+ * (astro/dist/runtime/server/render/util.js). Under nodejs_compat at some
8
+ * compatibility dates (observed broken at 2026-01-01, fixed by 2026-03-15)
9
+ * workerd tags its emulated process exactly like Node's, so Astro takes the
10
+ * Node branch and returns a bare async-iterable as the body — which the
11
+ * Cloudflare Workers `Response` cannot consume and coerces to the literal string
12
+ * "[object Object]" for every on-demand page.
13
+ *
14
+ * The Node branch is ALWAYS wrong on workerd, so the shim removes the tag —
15
+ * on workerd only (identified by its fixed `navigator.userAgent`), before any
16
+ * render runs. On real Node the tag is native and stays.
17
+ */
18
+ export function untagWorkerdProcess(
19
+ proc: unknown = (globalThis as { process?: unknown }).process,
20
+ userAgent: string | undefined = (globalThis as { navigator?: { userAgent?: string } }).navigator?.userAgent,
21
+ ): boolean {
22
+ if (userAgent !== 'Cloudflare-Workers') return false;
23
+ if (typeof proc !== 'object' || proc === null) return false;
24
+ if (Object.prototype.toString.call(proc) !== '[object process]') return false;
25
+ try {
26
+ delete (proc as Record<PropertyKey, unknown>)[Symbol.toStringTag];
27
+ } catch {
28
+ return false;
29
+ }
30
+ return Object.prototype.toString.call(proc) !== '[object process]';
31
+ }