@conloca/cloud-astro 0.2.1 → 0.2.3

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 (181) hide show
  1. package/README.md +261 -207
  2. package/dist/.build-inputs.json +60 -0
  3. package/dist/src/component-manifest.d.ts +5 -3
  4. package/dist/src/component-manifest.d.ts.map +1 -1
  5. package/dist/src/component-manifest.js +7 -7
  6. package/dist/src/component-manifest.js.map +1 -1
  7. package/dist/src/constants.d.ts +5 -13
  8. package/dist/src/constants.d.ts.map +1 -1
  9. package/dist/src/constants.js +5 -13
  10. package/dist/src/constants.js.map +1 -1
  11. package/dist/src/descriptors.d.ts +2 -2
  12. package/dist/src/descriptors.d.ts.map +1 -1
  13. package/dist/src/doctor/checks-address.d.ts +18 -0
  14. package/dist/src/doctor/checks-address.d.ts.map +1 -0
  15. package/dist/src/doctor/checks-address.js +163 -0
  16. package/dist/src/doctor/checks-address.js.map +1 -0
  17. package/dist/src/doctor/checks-live.d.ts +8 -5
  18. package/dist/src/doctor/checks-live.d.ts.map +1 -1
  19. package/dist/src/doctor/checks-live.js +220 -188
  20. package/dist/src/doctor/checks-live.js.map +1 -1
  21. package/dist/src/doctor/checks-offline.d.ts +8 -23
  22. package/dist/src/doctor/checks-offline.d.ts.map +1 -1
  23. package/dist/src/doctor/checks-offline.js +22 -239
  24. package/dist/src/doctor/checks-offline.js.map +1 -1
  25. package/dist/src/doctor/config-scan.d.ts +6 -3
  26. package/dist/src/doctor/config-scan.d.ts.map +1 -1
  27. package/dist/src/doctor/config-scan.js +21 -11
  28. package/dist/src/doctor/config-scan.js.map +1 -1
  29. package/dist/src/doctor/run.d.ts.map +1 -1
  30. package/dist/src/doctor/run.js +12 -10
  31. package/dist/src/doctor/run.js.map +1 -1
  32. package/dist/src/doctor/types.d.ts +7 -7
  33. package/dist/src/doctor/types.d.ts.map +1 -1
  34. package/dist/src/doctor/types.js +7 -7
  35. package/dist/src/doctor/types.js.map +1 -1
  36. package/dist/src/editor-page/bundle.d.ts +88 -0
  37. package/dist/src/editor-page/bundle.d.ts.map +1 -0
  38. package/dist/src/editor-page/bundle.js +370 -0
  39. package/dist/src/editor-page/bundle.js.map +1 -0
  40. package/dist/src/editor-page/emit.d.ts +33 -0
  41. package/dist/src/editor-page/emit.d.ts.map +1 -0
  42. package/dist/src/editor-page/emit.js +183 -0
  43. package/dist/src/editor-page/emit.js.map +1 -0
  44. package/dist/src/editor-page/framing.d.ts +23 -0
  45. package/dist/src/editor-page/framing.d.ts.map +1 -0
  46. package/dist/src/editor-page/framing.js +39 -0
  47. package/dist/src/editor-page/framing.js.map +1 -0
  48. package/dist/src/editor-page/page.d.ts +9 -0
  49. package/dist/src/editor-page/page.d.ts.map +1 -0
  50. package/dist/src/editor-page/page.js +31 -0
  51. package/dist/src/editor-page/page.js.map +1 -0
  52. package/dist/src/editor-page/site-base.d.ts +4 -0
  53. package/dist/src/editor-page/site-base.d.ts.map +1 -0
  54. package/dist/src/editor-page/site-base.js +13 -0
  55. package/dist/src/editor-page/site-base.js.map +1 -0
  56. package/dist/src/git.d.ts +11 -8
  57. package/dist/src/git.d.ts.map +1 -1
  58. package/dist/src/git.js +25 -8
  59. package/dist/src/git.js.map +1 -1
  60. package/dist/src/index.d.ts +3 -1
  61. package/dist/src/index.d.ts.map +1 -1
  62. package/dist/src/index.js +9 -6
  63. package/dist/src/index.js.map +1 -1
  64. package/dist/src/integration.d.ts +1 -1
  65. package/dist/src/integration.d.ts.map +1 -1
  66. package/dist/src/integration.js +245 -396
  67. package/dist/src/integration.js.map +1 -1
  68. package/dist/src/node.d.ts +3 -1
  69. package/dist/src/node.d.ts.map +1 -1
  70. package/dist/src/node.js +7 -2
  71. package/dist/src/node.js.map +1 -1
  72. package/dist/src/preview/_dispatch.d.ts +5 -2
  73. package/dist/src/preview/_dispatch.d.ts.map +1 -1
  74. package/dist/src/preview/_dispatch.js +2 -0
  75. package/dist/src/preview/_dispatch.js.map +1 -1
  76. package/dist/src/preview/_resolve-opts.d.ts +18 -10
  77. package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
  78. package/dist/src/preview/_resolve-opts.js +24 -10
  79. package/dist/src/preview/_resolve-opts.js.map +1 -1
  80. package/dist/src/preview/banner.d.ts.map +1 -1
  81. package/dist/src/preview/banner.js +2 -4
  82. package/dist/src/preview/banner.js.map +1 -1
  83. package/dist/src/preview/cookie.d.ts +5 -2
  84. package/dist/src/preview/cookie.d.ts.map +1 -1
  85. package/dist/src/preview/cookie.js +5 -2
  86. package/dist/src/preview/cookie.js.map +1 -1
  87. package/dist/src/preview/label.d.ts +8 -0
  88. package/dist/src/preview/label.d.ts.map +1 -0
  89. package/dist/src/preview/label.js +14 -0
  90. package/dist/src/preview/label.js.map +1 -0
  91. package/dist/src/preview/landing.d.ts +2 -2
  92. package/dist/src/preview/landing.js +2 -2
  93. package/dist/src/preview/middleware.d.ts +31 -20
  94. package/dist/src/preview/middleware.d.ts.map +1 -1
  95. package/dist/src/preview/middleware.js +56 -51
  96. package/dist/src/preview/middleware.js.map +1 -1
  97. package/dist/src/preview/preview-path.d.ts +18 -5
  98. package/dist/src/preview/preview-path.d.ts.map +1 -1
  99. package/dist/src/preview/preview-path.js +24 -8
  100. package/dist/src/preview/preview-path.js.map +1 -1
  101. package/dist/src/preview/site-middleware.d.ts +5 -5
  102. package/dist/src/preview/site-middleware.d.ts.map +1 -1
  103. package/dist/src/preview/site-middleware.js +17 -16
  104. package/dist/src/preview/site-middleware.js.map +1 -1
  105. package/dist/src/preview-build.d.ts +18 -15
  106. package/dist/src/preview-build.d.ts.map +1 -1
  107. package/dist/src/preview-build.js +36 -21
  108. package/dist/src/preview-build.js.map +1 -1
  109. package/dist/src/preview.d.ts +1 -1
  110. package/dist/src/preview.d.ts.map +1 -1
  111. package/dist/src/preview.js +1 -1
  112. package/dist/src/preview.js.map +1 -1
  113. package/dist/src/repository.d.ts +1 -1
  114. package/dist/src/repository.js +1 -1
  115. package/dist/src/resolve-options.d.ts +17 -0
  116. package/dist/src/resolve-options.d.ts.map +1 -0
  117. package/dist/src/resolve-options.js +21 -0
  118. package/dist/src/resolve-options.js.map +1 -0
  119. package/dist/src/site-id.d.ts +0 -2
  120. package/dist/src/site-id.d.ts.map +1 -1
  121. package/dist/src/site-id.js +2 -3
  122. package/dist/src/site-id.js.map +1 -1
  123. package/dist/src/types.d.ts +21 -59
  124. package/dist/src/types.d.ts.map +1 -1
  125. package/package.json +44 -15
  126. package/src/component-manifest.ts +11 -8
  127. package/src/constants.ts +5 -14
  128. package/src/descriptors.ts +2 -2
  129. package/src/doctor/checks-address.ts +190 -0
  130. package/src/doctor/checks-live.ts +256 -268
  131. package/src/doctor/checks-offline.ts +24 -262
  132. package/src/doctor/config-scan.ts +21 -9
  133. package/src/doctor/run.ts +14 -16
  134. package/src/doctor/types.ts +7 -7
  135. package/src/editor-page/bundle.ts +482 -0
  136. package/src/editor-page/emit.ts +246 -0
  137. package/src/editor-page/framing.ts +62 -0
  138. package/src/editor-page/page.ts +37 -0
  139. package/src/editor-page/site-base.ts +11 -0
  140. package/src/git.ts +29 -10
  141. package/src/index.ts +20 -6
  142. package/src/integration.ts +255 -449
  143. package/src/node.ts +18 -2
  144. package/src/preview/_dispatch.ts +6 -2
  145. package/src/preview/_resolve-opts.ts +34 -11
  146. package/src/preview/banner.ts +2 -4
  147. package/src/preview/cookie.ts +5 -2
  148. package/src/preview/label.ts +12 -0
  149. package/src/preview/landing.ts +2 -2
  150. package/src/preview/middleware.ts +83 -66
  151. package/src/preview/preview-path.ts +26 -8
  152. package/src/preview/site-middleware.ts +17 -21
  153. package/src/preview-build.ts +42 -26
  154. package/src/preview-handler.astro +10 -8
  155. package/src/preview.ts +0 -1
  156. package/src/repository.ts +1 -1
  157. package/src/resolve-options.ts +37 -0
  158. package/src/site-id.ts +2 -4
  159. package/src/skill/SKILL.md +51 -55
  160. package/src/types.ts +21 -60
  161. package/src/virtual-modules.d.ts +5 -1
  162. package/dist/src/build-commit.d.ts +0 -19
  163. package/dist/src/build-commit.d.ts.map +0 -1
  164. package/dist/src/build-commit.js +0 -6
  165. package/dist/src/build-commit.js.map +0 -1
  166. package/dist/src/bundle.d.ts +0 -173
  167. package/dist/src/bundle.d.ts.map +0 -1
  168. package/dist/src/bundle.js +0 -413
  169. package/dist/src/bundle.js.map +0 -1
  170. package/dist/src/discovery.d.ts +0 -58
  171. package/dist/src/discovery.d.ts.map +0 -1
  172. package/dist/src/discovery.js +0 -133
  173. package/dist/src/discovery.js.map +0 -1
  174. package/dist/src/register.d.ts +0 -98
  175. package/dist/src/register.d.ts.map +0 -1
  176. package/dist/src/register.js +0 -103
  177. package/dist/src/register.js.map +0 -1
  178. package/src/build-commit.ts +0 -22
  179. package/src/bundle.ts +0 -563
  180. package/src/discovery.ts +0 -183
  181. package/src/register.ts +0 -180
package/src/node.ts CHANGED
@@ -1,5 +1,21 @@
1
1
  // Node-only build-hook entry for `@conloca/cloud-astro`. The site wires
2
- // the integration into `astro.config.mjs` via this subpath.
2
+ // the integration into `astro.config.mjs` via this subpath; every build
3
+ // writes your site's editor page to /_conloca/editor/.
3
4
 
4
- export { conlocaCloud, PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG } from './integration.js';
5
+ export {
6
+ DEFAULT_EDITOR_ENDPOINT,
7
+ EDITOR_HOST_PROTOCOL,
8
+ EDITOR_PAGE_PATH,
9
+ type EditorHostPageData,
10
+ type EditorPageInfo,
11
+ } from '@conloca/content-api/editor-host';
12
+ // The /_conloca/editor/ header rules that `conloca connect` writes and doctor checks.
13
+ export {
14
+ type FramingBlocker,
15
+ type FramingSnippets,
16
+ findFramingBlockers,
17
+ framingSnippets,
18
+ } from './editor-page/framing.js';
19
+ // The default export is what `astro add @conloca/cloud-astro` wires in.
20
+ export { conlocaCloud as default, conlocaCloud, PACKAGE_NAME, PREVIEW_BUILD_ENV_FLAG } from './integration.js';
5
21
  export type { ConlocaCloudOptions, PreviewBuildOptions } from './types.js';
@@ -4,8 +4,9 @@ import type { PreviewContext } from './middleware.js';
4
4
  /**
5
5
  * Four-verdict response of the endpoint's page-status route.
6
6
  *
7
- * - `unchanged` — page render graph is byte-equivalent to the production
8
- * build; serve the ordinary page.
7
+ * - `unchanged` — page render graph is byte-equivalent to the build this
8
+ * deployment serves (nothing edited or committed on the branch since that
9
+ * build's registered commit); serve the ordinary page.
9
10
  * - `changed` — page or one of its dependencies has been edited in the
10
11
  * branch; carry the (possibly empty) embedded payload map into the
11
12
  * preview reader so dependency reads short-circuit when the endpoint
@@ -33,6 +34,8 @@ interface FetchPageStatusInput {
33
34
  * embedded map is locale-keyed so a mismatch silently never hits. */
34
35
  site?: string;
35
36
  locale?: string;
37
+ /** The commit this preview artifact was built from; the endpoint compares the branch's latest commit with it. */
38
+ build?: string;
36
39
  fetchFn?: typeof fetch;
37
40
  }
38
41
 
@@ -50,6 +53,7 @@ export async function fetchPageStatus(input: FetchPageStatusInput): Promise<Page
50
53
  const query = new URLSearchParams();
51
54
  if (input.locale !== undefined) query.set('locale', input.locale);
52
55
  if (input.site !== undefined) query.set('site', input.site);
56
+ if (input.build !== undefined) query.set('build', input.build);
53
57
  const suffix = query.size > 0 ? `?${query.toString()}` : '';
54
58
  const url = `${input.saasEndpoint}/preview/page-status/${normalisedPath}${suffix}`;
55
59
  const response = await fetchImpl(url, {
@@ -2,10 +2,26 @@ import type { PreviewMiddlewareOptions } from './middleware.js';
2
2
 
3
3
  /** Values the preview build can bake into the artifact at build time. */
4
4
  export interface BakedPreviewOpts {
5
- secret?: string;
6
5
  saasEndpoint?: string;
7
6
  saasIssuer?: string;
8
7
  saasAudience?: string;
8
+ /** The commit the preview build was built from; page-status compares the branch's latest commit with it. */
9
+ buildCommit?: string;
10
+ /** The repository, site and branch the preview build was made from: what every pass must match. */
11
+ repo?: string;
12
+ siteId?: string;
13
+ branch?: string;
14
+ /** Astro's `base` at build time. */
15
+ base?: string;
16
+ }
17
+
18
+ /** A value only the build can bake; the deployment cannot supply it. */
19
+ function bakedOnly(name: string, bakedValue: string | undefined): string {
20
+ if (bakedValue) return bakedValue;
21
+ throw new Error(
22
+ `@conloca/cloud-astro: the preview server is missing the baked ${name}; the preview build bakes it ` +
23
+ 'when previewBuild is given as an object, so rebuild',
24
+ );
9
25
  }
10
26
 
11
27
  /**
@@ -13,17 +29,18 @@ export interface BakedPreviewOpts {
13
29
  * falling back to the runtime environment.
14
30
  *
15
31
  * Baking is what removes the deployer's setup burden: every value is already
16
- * known while the preview build runs — the secret arrived with registration,
17
- * the endpoint and audience are integration options — so a correctly built
18
- * preview artifact needs NO env vars on the deployment. It also removes a
19
- * chicken-and-egg loop: the secret is generated during the build but the
20
- * deployment that would carry it happens afterwards.
32
+ * known while the preview build runs — the endpoint and audience are
33
+ * integration options, the repository, site and branch are what the build
34
+ * was made from — so a correctly built preview artifact needs NO env vars on
35
+ * the deployment.
21
36
  *
22
- * The environment still wins when set, so one artifact can be promoted across
23
- * environments without a rebuild.
37
+ * For the endpoint, issuer and audience the environment still wins when set,
38
+ * so one artifact can be promoted across environments without a rebuild. The
39
+ * repository, site and branch come only from the build: they are what a pass
40
+ * must match, and the deployment cannot change what the artifact serves.
24
41
  *
25
- * Throws naming the missing variable — a misconfigured preview runtime must
26
- * not silently accept requests.
42
+ * Throws naming the missing value — a misconfigured preview runtime must not
43
+ * silently accept requests.
27
44
  */
28
45
  export function resolveFromBaked(
29
46
  baked: BakedPreviewOpts,
@@ -40,10 +57,16 @@ export function resolveFromBaked(
40
57
  );
41
58
  };
42
59
  return {
43
- secret: pick('CONLOCA_PREVIEW_SECRET', baked.secret),
44
60
  saasEndpoint: pick('CONLOCA_SAAS_ENDPOINT', baked.saasEndpoint),
45
61
  saasIssuer: pick('CONLOCA_SAAS_ISSUER', baked.saasIssuer),
46
62
  saasAudience: pick('CONLOCA_SAAS_AUDIENCE', baked.saasAudience),
63
+ repo: bakedOnly('repo', baked.repo),
64
+ siteId: bakedOnly('siteId', baked.siteId),
65
+ branch: bakedOnly('branch', baked.branch),
66
+ base: baked.base || '/',
67
+ // Optional: an artifact built before this was baked has none, and the
68
+ // endpoint then falls back to the branch's registered build.
69
+ ...(baked.buildCommit ? { buildCommit: baked.buildCommit } : {}),
47
70
  };
48
71
  }
49
72
 
@@ -28,10 +28,8 @@ export function getBannerScriptText(ctx: PreviewContext, endpoint?: string, exit
28
28
  // cookie is HttpOnly, so the button reads the JWT from here). Absent an
29
29
  // endpoint the button is inert. `endpoint: undefined` drops out of the JSON.
30
30
  //
31
- // `exitPath` is the server-side exit route (secret-prefixed). Embedding it
32
- // here does not widen the secret's exposure: this script is served only to
33
- // credentialed preview visitors, who already hold the secret — it is in the
34
- // entry/share URL they arrived through — and the response is no-store.
31
+ // `exitPath` is the server-side exit route, the fixed public
32
+ // `<base>/_conloca/preview/__exit`; it reveals nothing.
35
33
  const ctxJson = JSON.stringify({ ...ctx, endpoint, exitPath }).replace(/</g, '\\u003c');
36
34
  return [
37
35
  `var __conlocaPreview = ${ctxJson};`,
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * Minimal cookie-header parser. We only need to look up cookies by exact name
3
- * (the secret-derived preview cookie); a full RFC 6265 parser would be
3
+ * (the fixed `__Host-conloca_preview` cookie); a full RFC 6265 parser would be
4
4
  * overkill, and pulling in a dependency for this would be YAGNI.
5
5
  *
6
6
  * The parser intentionally rejects malformed segments silently rather than
@@ -30,7 +30,10 @@ export function parseCookies(cookieHeader: string | null | undefined): Map<strin
30
30
  *
31
31
  * Splitting this out from the middleware keeps the request handler
32
32
  * declarative and lets the cookie defaults be reviewed in one place: the
33
- * secret must never leak into a script-readable cookie.
33
+ * pass must never leak into a script-readable cookie.
34
+ *
35
+ * These defaults meet the `__Host-` prefix rules the cookie name relies on:
36
+ * Secure, `Path=/` and no `Domain`, so no other host can set or read it.
34
37
  *
35
38
  * `SameSite=Lax`, not `Strict`: the share link always arrives from the editor
36
39
  * origin, and Chrome withholds a `Strict` cookie on the request that FOLLOWS a
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The public label the exit route answers with: the first 22 characters of
3
+ * unpadded base64url(SHA-256(`repo\nsite\nbranch`)). It names nothing readable,
4
+ * but lets Conloca's probe tell that an address serves previews for this
5
+ * repository, site and branch. WebCrypto, so it runs on workerd and Node alike.
6
+ */
7
+ export async function previewLabel(repo: string, siteId: string, branch: string): Promise<string> {
8
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`${repo}\n${siteId}\n${branch}`));
9
+ let binary = '';
10
+ for (const byte of new Uint8Array(digest)) binary += String.fromCharCode(byte);
11
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '').slice(0, 22);
12
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
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.
3
+ * hits the preview route but carries neither a fresh query param nor a
4
+ * valid cookie, or carries a pass for another repository, site or branch.
5
5
  *
6
6
  * With no preview context the page must offer two routes out:
7
7
  * - "Log in to edit" deep-link, preserving the requested pathname so
@@ -1,15 +1,24 @@
1
1
  import { createRemoteJWKSet, customFetch, type JWTPayload, type JWTVerifyGetKey, jwtVerify } from 'jose';
2
2
  import { parseCookies, serializePreviewCookie } from './cookie.js';
3
+ import { previewLabel } from './label.js';
3
4
  import { renderNoPreviewLanding } from './landing.js';
4
- import { stripPreviewPrefix } from './preview-path.js';
5
+ import {
6
+ PREVIEW_COOKIE_NAME,
7
+ PREVIEW_LABEL_HEADER,
8
+ PREVIEW_QUERY_PARAM,
9
+ previewRoutePrefix,
10
+ stripPreviewPrefix,
11
+ } from './preview-path.js';
5
12
 
6
13
  /**
7
14
  * Options consumed by {@link handlePreviewRequest}.
8
15
  *
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.
16
+ * `repo`, `siteId` and `branch` name what the preview build was made from. A
17
+ * pass is accepted only when it names the same repository and site, and either
18
+ * the same branch or, in `served_by`, this build's branch (a branch with no
19
+ * build of its own borrows the default branch's server; a branch's own build
20
+ * serves its own passes). `base` is Astro's `base`; the fixed preview route
21
+ * sits under it.
13
22
  *
14
23
  * `getKey` is an optional JWKS resolver injection seam. When omitted, the
15
24
  * middleware constructs a `createRemoteJWKSet` pointed at
@@ -18,10 +27,23 @@ import { stripPreviewPrefix } from './preview-path.js';
18
27
  * deterministically without touching the network.
19
28
  */
20
29
  export interface PreviewMiddlewareOptions {
21
- secret: string;
22
30
  saasEndpoint: string;
23
31
  saasIssuer: string;
24
32
  saasAudience: string;
33
+ /** The repository the preview build was made from, as passes name it (`owner/name`). */
34
+ repo: string;
35
+ /** The site the preview build serves. */
36
+ siteId: string;
37
+ /** The branch the preview build was made from. */
38
+ branch: string;
39
+ /** Astro's `base`; the preview route and its redirects stay under it. */
40
+ base: string;
41
+ /**
42
+ * The commit this preview artifact was built from. Page-status compares the
43
+ * branch's committed head with it; absent (an older artifact) ⇒ the
44
+ * endpoint compares with the branch's registered build instead.
45
+ */
46
+ buildCommit?: string;
25
47
  getKey?: JWTVerifyGetKey;
26
48
  /**
27
49
  * Transport for the JWKS fetch. A deployment that cannot reach the endpoint
@@ -34,7 +56,7 @@ export interface PreviewMiddlewareOptions {
34
56
  * What to do when the request carries no valid preview credential.
35
57
  *
36
58
  * - `'landing'` (default) — the no-preview landing page. Correct for the
37
- * secret-prefixed entry route, which nobody reaches by accident.
59
+ * preview entry route, which nobody reaches by accident.
38
60
  * - `'pass-through'` — let the request continue to the ordinary page. Correct
39
61
  * for the site-wide interceptor, which sees every request in the preview
40
62
  * build: an uncredentialed visitor must get the normal site, not a landing
@@ -83,8 +105,8 @@ declare global {
83
105
  * - `pass-through` — the caller MAY delegate to the ordinary page or
84
106
  * static-asset handler. Returned when `onMiss: 'pass-through'` is set —
85
107
  * the site-wide interceptor's mode, where an uncredentialed request must
86
- * get the normal site. The secret-prefixed entry route omits `onMiss`
87
- * and never sees this verdict.
108
+ * get the normal site. The preview entry route omits `onMiss` and never
109
+ * sees this verdict.
88
110
  */
89
111
  export type PreviewVerdict =
90
112
  | { kind: 'pass-through' }
@@ -97,52 +119,58 @@ export type PreviewVerdict =
97
119
  * the caller contract.
98
120
  *
99
121
  * Order of checks:
100
- * 1. `?conloca_preview_${secret}=<JWT>` query param → validate; on
101
- * success issue a 302 with the cookie set and the query stripped.
102
- * 2. `conloca_preview_${secret}=<JWT>` cookie → validate; on success
103
- * return a `preview` verdict with the decoded context.
122
+ * 0. `<base>/_conloca/preview/__exit` → expire the cookie and redirect,
123
+ * carrying this build's public label.
124
+ * 1. `?conloca_preview=<JWT>` query param → validate; on success issue a
125
+ * 302 with the cookie set and the query stripped.
126
+ * 2. `__Host-conloca_preview=<JWT>` cookie → validate; on success return a
127
+ * `preview` verdict with the decoded context.
104
128
  * 3. Neither present → no-preview landing page response.
105
129
  *
106
130
  * Invalid JWTs (tampered signature, expired, missing required claim, wrong
107
- * issuer/audience/scope) fall through to the landing page. We deliberately do
131
+ * issuer/audience/scope, or naming another repository, site or branch than
132
+ * this build serves) fall through to the landing page. We deliberately do
108
133
  * NOT return 401 — a 401 to an unauthenticated caller would confirm that
109
134
  * a particular path is preview-only, which leaks information about what
110
135
  * the branch contains.
111
136
  */
112
137
  export async function handlePreviewRequest(request: Request, opts: PreviewMiddlewareOptions): Promise<PreviewVerdict> {
113
138
  const url = new URL(request.url);
114
- const queryName = previewParamName(opts.secret);
115
- const cookieName = previewParamName(opts.secret);
116
139
 
117
140
  // 0. Exit route: the banner's "Exit Preview" target. The cookie is HttpOnly
118
141
  // on purpose, so leaving preview needs a server response that expires it.
119
142
  // Handled before the credential checks — an expired cookie must not strand
120
- // the visitor in a preview they can no longer exit.
121
- if (url.pathname === `/${previewParamName(opts.secret)}/__exit`) {
122
- return { kind: 'response', response: makeExitRedirect(url, opts.secret) };
143
+ // the visitor in a preview they can no longer exit. Its label lets the
144
+ // endpoint's probe tell which repository, site and branch this server serves.
145
+ if (url.pathname === `${previewRoutePrefix(opts.base)}/__exit`) {
146
+ const label = await previewLabel(opts.repo, opts.siteId, opts.branch);
147
+ return { kind: 'response', response: makeExitRedirect(url, opts.base, label) };
123
148
  }
124
149
 
125
150
  // 1. Query-param init path.
126
- const queryToken = url.searchParams.get(queryName);
151
+ const queryToken = url.searchParams.get(PREVIEW_QUERY_PARAM);
127
152
  if (queryToken !== null) {
128
153
  const ctx = await tryValidate(queryToken, opts);
129
154
  if (ctx) {
130
155
  return {
131
156
  kind: 'response',
132
- response: makeInitRedirect(url, queryName, queryToken, opts.secret, ctx.expiresInSeconds),
157
+ response: makeInitRedirect(url, queryToken, opts.base, ctx.expiresInSeconds),
133
158
  };
134
159
  }
135
160
  // Invalid query-param JWT — fall through to the landing page rather than
136
161
  // issuing a 401 (see docstring).
137
162
  return {
138
163
  kind: 'response',
139
- response: renderNoPreviewLanding({ pathname: stripPreviewPrefix(url.pathname), saasEndpoint: opts.saasEndpoint }),
164
+ response: renderNoPreviewLanding({
165
+ pathname: stripPreviewPrefix(url.pathname, opts.base),
166
+ saasEndpoint: opts.saasEndpoint,
167
+ }),
140
168
  };
141
169
  }
142
170
 
143
171
  // 2. Cookie path.
144
172
  const cookies = parseCookies(request.headers.get('cookie'));
145
- const cookieToken = cookies.get(cookieName);
173
+ const cookieToken = cookies.get(PREVIEW_COOKIE_NAME);
146
174
  if (cookieToken !== undefined) {
147
175
  const ctx = await tryValidate(cookieToken, opts);
148
176
  if (ctx) {
@@ -157,21 +185,14 @@ export async function handlePreviewRequest(request: Request, opts: PreviewMiddle
157
185
  return {
158
186
  kind: 'response',
159
187
  // Stripped: the landing's "Go to production" link is the same path
160
- // relative — rendered with the secret prefix it loops back to itself.
161
- response: renderNoPreviewLanding({ pathname: stripPreviewPrefix(url.pathname), saasEndpoint: opts.saasEndpoint }),
188
+ // relative — rendered under the preview route it loops back to itself.
189
+ response: renderNoPreviewLanding({
190
+ pathname: stripPreviewPrefix(url.pathname, opts.base),
191
+ saasEndpoint: opts.saasEndpoint,
192
+ }),
162
193
  };
163
194
  }
164
195
 
165
- /**
166
- * Derives the query-param / cookie name from the per-branch secret. The
167
- * name doubles as a load guard: a same-domain request-runtime wrapper
168
- * checks for this exact string before invoking the SSR handler, so random
169
- * `?conloca_preview_*` query strings cannot wake the preview path.
170
- */
171
- export function previewParamName(secret: string): string {
172
- return `conloca_preview_${secret}`;
173
- }
174
-
175
196
  /**
176
197
  * Validates a JWT and projects its claims into a {@link PreviewContext}.
177
198
  * Returns `null` on any validation failure — the failure reason is not
@@ -185,7 +206,7 @@ async function tryValidate(token: string, opts: PreviewMiddlewareOptions): Promi
185
206
  issuer: opts.saasIssuer,
186
207
  audience: opts.saasAudience,
187
208
  });
188
- return projectContext(payload, token);
209
+ return projectContext(payload, token, opts);
189
210
  } catch {
190
211
  return null;
191
212
  }
@@ -218,14 +239,19 @@ function defaultJwksResolver(endpoint: string, fetchFn?: typeof fetch): JWTVerif
218
239
  * Project a verified JWT payload into the preview context envelope. Returns
219
240
  * `null` if any required claim is missing or wrong type — a JWT that
220
241
  * validates cryptographically but lacks `branch` names no branch to read,
221
- * so it is treated as invalid here.
242
+ * so it is treated as invalid here — and when the pass is for another build:
243
+ * its `repo` and `site_id` must be the ones this build serves, and its
244
+ * `branch` must be this build's branch unless `served_by` names it (only
245
+ * Conloca sets `served_by`, and only to the default branch).
222
246
  */
223
- function projectContext(payload: JWTPayload, jwt: string): PreviewContext | null {
247
+ function projectContext(payload: JWTPayload, jwt: string, opts: PreviewMiddlewareOptions): PreviewContext | null {
224
248
  if (payload.scope !== 'preview') return null;
225
249
  const branch = readStringClaim(payload, 'branch');
226
250
  const org = readStringClaim(payload, 'org');
227
251
  const repo = readStringClaim(payload, 'repo');
228
252
  if (!branch || !org || !repo) return null;
253
+ if (repo !== opts.repo || readStringClaim(payload, 'site_id') !== opts.siteId) return null;
254
+ if (branch !== opts.branch && readStringClaim(payload, 'served_by') !== opts.branch) return null;
229
255
  // Remaining token lifetime, so the cookie can be bounded to the credential
230
256
  // it carries rather than living for the whole browser session. `exp` is
231
257
  // already verified by `jwtVerify` above, so it is present and in the future.
@@ -239,51 +265,42 @@ function readStringClaim(payload: JWTPayload, name: string): string | undefined
239
265
  return typeof value === 'string' && value.length > 0 ? value : undefined;
240
266
  }
241
267
 
242
- /**
243
- * Builds the 302 response that strips the preview query parameter from
244
- * the requested URL and sets the preview cookie. Preserves every other
245
- * query parameter so analytics / utm tags survive the redirect.
246
- *
247
- * The caller passes both the query-param name (so we know which key to
248
- * strip) and the raw secret (so we can derive the cookie name without a
249
- * roundtrip parse). The two are bound by `previewParamName(secret)` ===
250
- * `queryName` at the call site.
251
- */
252
268
  /**
253
269
  * Builds the 302 that expires the preview cookie and returns the visitor to
254
270
  * the published page. `?to=` names the page the banner was on; only a
255
271
  * same-origin absolute path is accepted (a full URL or `//host` would turn
256
- * this route into an open redirect), anything else falls back to `/`.
272
+ * this route into an open redirect), anything else falls back to the site's
273
+ * base. The `conloca-preview` header carries this build's public label.
257
274
  */
258
- function makeExitRedirect(url: URL, secret: string): Response {
259
- const to = url.searchParams.get('to') ?? '/';
260
- const target = to.startsWith('/') && !to.startsWith('//') ? to : '/';
275
+ function makeExitRedirect(url: URL, base: string, label: string): Response {
276
+ const to = url.searchParams.get('to') ?? base;
277
+ const target = to.startsWith('/') && !to.startsWith('//') ? to : base;
261
278
  return new Response(null, {
262
279
  status: 302,
263
280
  headers: {
264
281
  location: target,
265
- 'set-cookie': serializePreviewCookie(previewParamName(secret), '', 0),
282
+ 'set-cookie': serializePreviewCookie(PREVIEW_COOKIE_NAME, '', 0),
266
283
  'cache-control': 'private, no-store',
284
+ [PREVIEW_LABEL_HEADER]: label,
267
285
  },
268
286
  });
269
287
  }
270
288
 
271
- function makeInitRedirect(
272
- url: URL,
273
- queryName: string,
274
- token: string,
275
- secret: string,
276
- maxAgeSeconds?: number,
277
- ): Response {
289
+ /**
290
+ * Builds the 302 response that strips the preview query parameter from
291
+ * the requested URL and sets the preview cookie. Preserves every other
292
+ * query parameter so analytics / utm tags survive the redirect.
293
+ */
294
+ function makeInitRedirect(url: URL, token: string, base: string, maxAgeSeconds?: number): Response {
278
295
  const cleaned = new URL(url.toString());
279
- cleaned.searchParams.delete(queryName);
280
- // Land the browser on the REAL site path, not the secret-prefixed one.
281
- // The prefix is an entry door: it exists so the endpoint has a URL to link to
296
+ cleaned.searchParams.delete(PREVIEW_QUERY_PARAM);
297
+ // Land the browser on the REAL site path, not the preview route.
298
+ // The route is an entry door: it exists so the endpoint has a URL to link to
282
299
  // before any cookie exists. Once the cookie is set (Path=/), every
283
300
  // same-origin request carries the credential, so the visitor belongs on the
284
301
  // canonical path — otherwise the first internal link they click drops the
285
- // prefix, escapes preview, and silently shows published content.
286
- cleaned.pathname = stripPreviewPrefix(cleaned.pathname);
302
+ // route, escapes preview, and silently shows published content.
303
+ cleaned.pathname = stripPreviewPrefix(cleaned.pathname, base);
287
304
  // Normalise the search string: when the only param was the preview JWT,
288
305
  // URL.search becomes '' but URL.toString() still emits a trailing `?` only
289
306
  // if it was already empty. Re-serialising via URL strips that automatically;
@@ -296,7 +313,7 @@ function makeInitRedirect(
296
313
  status: 302,
297
314
  headers: {
298
315
  location,
299
- 'set-cookie': serializePreviewCookie(previewParamName(secret), token, maxAgeSeconds),
316
+ 'set-cookie': serializePreviewCookie(PREVIEW_COOKIE_NAME, token, maxAgeSeconds),
300
317
  'cache-control': 'private, no-store',
301
318
  },
302
319
  });
@@ -1,18 +1,36 @@
1
1
  /**
2
- * Strip a leading `/conloca_preview_<secret>` segment from a pathname.
2
+ * The fixed preview route and the names it uses.
3
3
  *
4
4
  * Lives in its own module because the entry-hop middleware, the site
5
5
  * middleware and the page-status client all need it without depending on
6
6
  * each other.
7
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.
8
+ * The route is public and the same on every site: the signed pass is the
9
+ * lock, checked against the repository, site and branch the preview build
10
+ * was made from.
11
11
  */
12
- export function stripPreviewPrefix(pathname: string): string {
13
- const match = /^\/conloca_preview_[^/]+(\/.*)?$/.exec(pathname);
14
- if (!match) return pathname;
15
- return match[1] ?? '/';
12
+ export const PREVIEW_ROUTE_SEGMENT = '/_conloca/preview';
13
+ export const PREVIEW_QUERY_PARAM = 'conloca_preview';
14
+ export const PREVIEW_COOKIE_NAME = '__Host-conloca_preview';
15
+ /** Response header on the exit route's redirect that carries the public label. */
16
+ export const PREVIEW_LABEL_HEADER = 'conloca-preview';
17
+
18
+ /** The preview route under Astro's `base` (`'/'` → `/_conloca/preview`, `'/docs/'` → `/docs/_conloca/preview`). */
19
+ export function previewRoutePrefix(base: string): string {
20
+ return `${base.replace(/\/+$/u, '')}${PREVIEW_ROUTE_SEGMENT}`;
21
+ }
22
+
23
+ /**
24
+ * Strip the preview route from a pathname, leaving the page path under the
25
+ * base. Only the route at the base matches: `/blog/_conloca/preview/x` and
26
+ * `/_conloca/previewer/x` are left untouched, so a page that merely mentions
27
+ * the route is never re-anchored to a different page.
28
+ */
29
+ export function stripPreviewPrefix(pathname: string, base: string): string {
30
+ const prefix = previewRoutePrefix(base);
31
+ if (pathname !== prefix && !pathname.startsWith(`${prefix}/`)) return pathname;
32
+ const rest = pathname.slice(prefix.length);
33
+ return `${base.replace(/\/+$/u, '')}${rest === '' ? '/' : rest}`;
16
34
  }
17
35
 
18
36
  /**
@@ -2,15 +2,15 @@
2
2
  * Site-wide preview middleware for the recursive preview build — the SERVING
3
3
  * SURFACE of draft preview.
4
4
  *
5
- * WHY THIS EXISTS — the secret path prefix is an entry door, not the serving
5
+ * WHY THIS EXISTS — the fixed preview route is an entry door, not the serving
6
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=/`,
7
+ * lands on `/_conloca/preview/about`, clicks a link, and the root-absolute
8
+ * `/blog` the site's template emitted drops the route and silently serves the
9
+ * PUBLISHED page. The preview cookie is already `Path=/`,
10
10
  * so the browser is sending the credential on that request — this listens.
11
11
  *
12
12
  * WHY THE RENDER HAPPENS HERE, VIA `next()` — a middleware rewrite onto the
13
- * secret-prefixed handler (the previous design) forced the render through
13
+ * preview route's handler (an earlier design) forced the render through
14
14
  * `Astro.rewrite`, whose route matching does not fall through prerendered
15
15
  * routes: with two root catch-alls (the CMS pages route on demand, a docs
16
16
  * integration's route prerendered) the rewrite matched the prerendered one
@@ -31,13 +31,8 @@ import { fetchPageStatus, type PageStatus } from './_dispatch.js';
31
31
  import { injectPreviewBanner } from './banner.js';
32
32
  import { PreviewContentAPI } from './content-api.js';
33
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';
34
+ import { handlePreviewRequest, type PreviewContext, type PreviewMiddlewareOptions } from './middleware.js';
35
+ import { normalizeTrailingSlash, previewRoutePrefix, stripPreviewPrefix } from './preview-path.js';
41
36
 
42
37
  /** The subset of Astro's middleware context this middleware touches. */
43
38
  export interface PreviewMiddlewareContext {
@@ -86,8 +81,8 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
86
81
  // ALSO at build time, where Astro runs middleware while prerendering pages
87
82
  // and the deployer's runtime vars do not exist yet. Neither is a reason to
88
83
  // 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.
84
+ // not use, so pass through and warn once. The preview entry route still
85
+ // fails loudly: reaching it means someone explicitly asked to preview.
91
86
  let opts: PreviewMiddlewareOptions;
92
87
  try {
93
88
  opts = resolveOpts();
@@ -104,12 +99,12 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
104
99
  if (verdict.kind === 'response') return verdict.response;
105
100
  if (verdict.kind !== 'preview') return next();
106
101
 
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.
102
+ // A valid credential on the preview route itself: canonicalize to the
103
+ // clean site path instead of rendering under the route — links, assets
104
+ // and the page lookup all assume clean paths.
110
105
  const rawPath = context.url.pathname;
111
- const path = normalizeTrailingSlash(stripPreviewPrefix(rawPath));
112
- if (stripPreviewPrefix(rawPath) !== rawPath) {
106
+ const path = normalizeTrailingSlash(stripPreviewPrefix(rawPath, opts.base));
107
+ if (stripPreviewPrefix(rawPath, opts.base) !== rawPath) {
113
108
  return new Response(null, {
114
109
  status: 302,
115
110
  headers: { location: path, 'cache-control': 'private, no-store' },
@@ -128,6 +123,7 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
128
123
  path,
129
124
  site: seams.site,
130
125
  locale: seams.locale,
126
+ build: opts.buildCommit,
131
127
  fetchFn: seams.fetchFn,
132
128
  });
133
129
  } catch (error) {
@@ -183,7 +179,7 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
183
179
  await rendered.text(),
184
180
  verdict.ctx,
185
181
  opts.saasEndpoint,
186
- `/${previewParamName(opts.secret)}/__exit`,
182
+ `${previewRoutePrefix(opts.base)}/__exit`,
187
183
  );
188
184
  return applyPreviewHeaders(new Response(html, { status: rendered.status, headers: rendered.headers }));
189
185
  };
@@ -203,7 +199,7 @@ function warnUnconfiguredOnce(error: unknown): void {
203
199
  console.warn(
204
200
  `[@conloca/cloud-astro] draft preview is INERT — ${detail}\n` +
205
201
  ' Requests are being served as the ordinary published site.\n' +
206
- ' Draft previews on your own deployment are not available yet: keep previewBuild: false ' +
202
+ ' The preview server is missing its baked settings: rebuild with previewBuild given as an object ' +
207
203
  '(see the cloud-astro README "Draft previews").',
208
204
  );
209
205
  }