@conloca/cloud-astro 0.2.2 → 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 (176) hide show
  1. package/README.md +261 -208
  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 -408
  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/_resolve-opts.d.ts +16 -10
  73. package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
  74. package/dist/src/preview/_resolve-opts.js +21 -10
  75. package/dist/src/preview/_resolve-opts.js.map +1 -1
  76. package/dist/src/preview/banner.d.ts.map +1 -1
  77. package/dist/src/preview/banner.js +2 -4
  78. package/dist/src/preview/banner.js.map +1 -1
  79. package/dist/src/preview/cookie.d.ts +5 -2
  80. package/dist/src/preview/cookie.d.ts.map +1 -1
  81. package/dist/src/preview/cookie.js +5 -2
  82. package/dist/src/preview/cookie.js.map +1 -1
  83. package/dist/src/preview/label.d.ts +8 -0
  84. package/dist/src/preview/label.d.ts.map +1 -0
  85. package/dist/src/preview/label.js +14 -0
  86. package/dist/src/preview/label.js.map +1 -0
  87. package/dist/src/preview/landing.d.ts +2 -2
  88. package/dist/src/preview/landing.js +2 -2
  89. package/dist/src/preview/middleware.d.ts +25 -20
  90. package/dist/src/preview/middleware.d.ts.map +1 -1
  91. package/dist/src/preview/middleware.js +56 -51
  92. package/dist/src/preview/middleware.js.map +1 -1
  93. package/dist/src/preview/preview-path.d.ts +18 -5
  94. package/dist/src/preview/preview-path.d.ts.map +1 -1
  95. package/dist/src/preview/preview-path.js +24 -8
  96. package/dist/src/preview/preview-path.js.map +1 -1
  97. package/dist/src/preview/site-middleware.d.ts +5 -5
  98. package/dist/src/preview/site-middleware.d.ts.map +1 -1
  99. package/dist/src/preview/site-middleware.js +16 -16
  100. package/dist/src/preview/site-middleware.js.map +1 -1
  101. package/dist/src/preview-build.d.ts +18 -15
  102. package/dist/src/preview-build.d.ts.map +1 -1
  103. package/dist/src/preview-build.js +36 -21
  104. package/dist/src/preview-build.js.map +1 -1
  105. package/dist/src/preview.d.ts +1 -1
  106. package/dist/src/preview.d.ts.map +1 -1
  107. package/dist/src/preview.js +1 -1
  108. package/dist/src/preview.js.map +1 -1
  109. package/dist/src/repository.d.ts +1 -1
  110. package/dist/src/repository.js +1 -1
  111. package/dist/src/resolve-options.d.ts +17 -0
  112. package/dist/src/resolve-options.d.ts.map +1 -0
  113. package/dist/src/resolve-options.js +21 -0
  114. package/dist/src/resolve-options.js.map +1 -0
  115. package/dist/src/site-id.d.ts +0 -2
  116. package/dist/src/site-id.d.ts.map +1 -1
  117. package/dist/src/site-id.js +2 -3
  118. package/dist/src/site-id.js.map +1 -1
  119. package/dist/src/types.d.ts +21 -69
  120. package/dist/src/types.d.ts.map +1 -1
  121. package/package.json +37 -13
  122. package/src/component-manifest.ts +11 -8
  123. package/src/constants.ts +5 -14
  124. package/src/descriptors.ts +2 -2
  125. package/src/doctor/checks-address.ts +190 -0
  126. package/src/doctor/checks-live.ts +256 -268
  127. package/src/doctor/checks-offline.ts +24 -262
  128. package/src/doctor/config-scan.ts +21 -9
  129. package/src/doctor/run.ts +14 -16
  130. package/src/doctor/types.ts +7 -7
  131. package/src/editor-page/bundle.ts +482 -0
  132. package/src/editor-page/emit.ts +246 -0
  133. package/src/editor-page/framing.ts +62 -0
  134. package/src/editor-page/page.ts +37 -0
  135. package/src/editor-page/site-base.ts +11 -0
  136. package/src/git.ts +29 -10
  137. package/src/index.ts +20 -6
  138. package/src/integration.ts +255 -461
  139. package/src/node.ts +18 -2
  140. package/src/preview/_resolve-opts.ts +29 -11
  141. package/src/preview/banner.ts +2 -4
  142. package/src/preview/cookie.ts +5 -2
  143. package/src/preview/label.ts +12 -0
  144. package/src/preview/landing.ts +2 -2
  145. package/src/preview/middleware.ts +77 -66
  146. package/src/preview/preview-path.ts +26 -8
  147. package/src/preview/site-middleware.ts +16 -21
  148. package/src/preview-build.ts +42 -26
  149. package/src/preview-handler.astro +10 -8
  150. package/src/preview.ts +0 -1
  151. package/src/repository.ts +1 -1
  152. package/src/resolve-options.ts +37 -0
  153. package/src/site-id.ts +2 -4
  154. package/src/skill/SKILL.md +51 -55
  155. package/src/types.ts +21 -70
  156. package/src/virtual-modules.d.ts +4 -1
  157. package/dist/src/build-commit.d.ts +0 -19
  158. package/dist/src/build-commit.d.ts.map +0 -1
  159. package/dist/src/build-commit.js +0 -6
  160. package/dist/src/build-commit.js.map +0 -1
  161. package/dist/src/bundle.d.ts +0 -181
  162. package/dist/src/bundle.d.ts.map +0 -1
  163. package/dist/src/bundle.js +0 -413
  164. package/dist/src/bundle.js.map +0 -1
  165. package/dist/src/discovery.d.ts +0 -58
  166. package/dist/src/discovery.d.ts.map +0 -1
  167. package/dist/src/discovery.js +0 -133
  168. package/dist/src/discovery.js.map +0 -1
  169. package/dist/src/register.d.ts +0 -98
  170. package/dist/src/register.d.ts.map +0 -1
  171. package/dist/src/register.js +0 -103
  172. package/dist/src/register.js.map +0 -1
  173. package/src/build-commit.ts +0 -22
  174. package/src/bundle.ts +0 -570
  175. package/src/discovery.ts +0 -183
  176. 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';
@@ -2,12 +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;
9
8
  /** The commit the preview build was built from; page-status compares the branch's latest commit with it. */
10
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
+ );
11
25
  }
12
26
 
13
27
  /**
@@ -15,17 +29,18 @@ export interface BakedPreviewOpts {
15
29
  * falling back to the runtime environment.
16
30
  *
17
31
  * Baking is what removes the deployer's setup burden: every value is already
18
- * known while the preview build runs — the secret arrived with registration,
19
- * the endpoint and audience are integration options — so a correctly built
20
- * preview artifact needs NO env vars on the deployment. It also removes a
21
- * chicken-and-egg loop: the secret is generated during the build but the
22
- * 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.
23
36
  *
24
- * The environment still wins when set, so one artifact can be promoted across
25
- * 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.
26
41
  *
27
- * Throws naming the missing variable — a misconfigured preview runtime must
28
- * not silently accept requests.
42
+ * Throws naming the missing value — a misconfigured preview runtime must not
43
+ * silently accept requests.
29
44
  */
30
45
  export function resolveFromBaked(
31
46
  baked: BakedPreviewOpts,
@@ -42,10 +57,13 @@ export function resolveFromBaked(
42
57
  );
43
58
  };
44
59
  return {
45
- secret: pick('CONLOCA_PREVIEW_SECRET', baked.secret),
46
60
  saasEndpoint: pick('CONLOCA_SAAS_ENDPOINT', baked.saasEndpoint),
47
61
  saasIssuer: pick('CONLOCA_SAAS_ISSUER', baked.saasIssuer),
48
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 || '/',
49
67
  // Optional: an artifact built before this was baked has none, and the
50
68
  // endpoint then falls back to the branch's registered build.
51
69
  ...(baked.buildCommit ? { buildCommit: baked.buildCommit } : {}),
@@ -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,17 @@ 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;
25
41
  /**
26
42
  * The commit this preview artifact was built from. Page-status compares the
27
43
  * branch's committed head with it; absent (an older artifact) ⇒ the
@@ -40,7 +56,7 @@ export interface PreviewMiddlewareOptions {
40
56
  * What to do when the request carries no valid preview credential.
41
57
  *
42
58
  * - `'landing'` (default) — the no-preview landing page. Correct for the
43
- * secret-prefixed entry route, which nobody reaches by accident.
59
+ * preview entry route, which nobody reaches by accident.
44
60
  * - `'pass-through'` — let the request continue to the ordinary page. Correct
45
61
  * for the site-wide interceptor, which sees every request in the preview
46
62
  * build: an uncredentialed visitor must get the normal site, not a landing
@@ -89,8 +105,8 @@ declare global {
89
105
  * - `pass-through` — the caller MAY delegate to the ordinary page or
90
106
  * static-asset handler. Returned when `onMiss: 'pass-through'` is set —
91
107
  * 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.
108
+ * get the normal site. The preview entry route omits `onMiss` and never
109
+ * sees this verdict.
94
110
  */
95
111
  export type PreviewVerdict =
96
112
  | { kind: 'pass-through' }
@@ -103,52 +119,58 @@ export type PreviewVerdict =
103
119
  * the caller contract.
104
120
  *
105
121
  * 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.
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.
110
128
  * 3. Neither present → no-preview landing page response.
111
129
  *
112
130
  * Invalid JWTs (tampered signature, expired, missing required claim, wrong
113
- * 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
114
133
  * NOT return 401 — a 401 to an unauthenticated caller would confirm that
115
134
  * a particular path is preview-only, which leaks information about what
116
135
  * the branch contains.
117
136
  */
118
137
  export async function handlePreviewRequest(request: Request, opts: PreviewMiddlewareOptions): Promise<PreviewVerdict> {
119
138
  const url = new URL(request.url);
120
- const queryName = previewParamName(opts.secret);
121
- const cookieName = previewParamName(opts.secret);
122
139
 
123
140
  // 0. Exit route: the banner's "Exit Preview" target. The cookie is HttpOnly
124
141
  // on purpose, so leaving preview needs a server response that expires it.
125
142
  // 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) };
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) };
129
148
  }
130
149
 
131
150
  // 1. Query-param init path.
132
- const queryToken = url.searchParams.get(queryName);
151
+ const queryToken = url.searchParams.get(PREVIEW_QUERY_PARAM);
133
152
  if (queryToken !== null) {
134
153
  const ctx = await tryValidate(queryToken, opts);
135
154
  if (ctx) {
136
155
  return {
137
156
  kind: 'response',
138
- response: makeInitRedirect(url, queryName, queryToken, opts.secret, ctx.expiresInSeconds),
157
+ response: makeInitRedirect(url, queryToken, opts.base, ctx.expiresInSeconds),
139
158
  };
140
159
  }
141
160
  // Invalid query-param JWT — fall through to the landing page rather than
142
161
  // issuing a 401 (see docstring).
143
162
  return {
144
163
  kind: 'response',
145
- response: renderNoPreviewLanding({ pathname: stripPreviewPrefix(url.pathname), saasEndpoint: opts.saasEndpoint }),
164
+ response: renderNoPreviewLanding({
165
+ pathname: stripPreviewPrefix(url.pathname, opts.base),
166
+ saasEndpoint: opts.saasEndpoint,
167
+ }),
146
168
  };
147
169
  }
148
170
 
149
171
  // 2. Cookie path.
150
172
  const cookies = parseCookies(request.headers.get('cookie'));
151
- const cookieToken = cookies.get(cookieName);
173
+ const cookieToken = cookies.get(PREVIEW_COOKIE_NAME);
152
174
  if (cookieToken !== undefined) {
153
175
  const ctx = await tryValidate(cookieToken, opts);
154
176
  if (ctx) {
@@ -163,21 +185,14 @@ export async function handlePreviewRequest(request: Request, opts: PreviewMiddle
163
185
  return {
164
186
  kind: 'response',
165
187
  // 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 }),
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
+ }),
168
193
  };
169
194
  }
170
195
 
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
196
  /**
182
197
  * Validates a JWT and projects its claims into a {@link PreviewContext}.
183
198
  * Returns `null` on any validation failure — the failure reason is not
@@ -191,7 +206,7 @@ async function tryValidate(token: string, opts: PreviewMiddlewareOptions): Promi
191
206
  issuer: opts.saasIssuer,
192
207
  audience: opts.saasAudience,
193
208
  });
194
- return projectContext(payload, token);
209
+ return projectContext(payload, token, opts);
195
210
  } catch {
196
211
  return null;
197
212
  }
@@ -224,14 +239,19 @@ function defaultJwksResolver(endpoint: string, fetchFn?: typeof fetch): JWTVerif
224
239
  * Project a verified JWT payload into the preview context envelope. Returns
225
240
  * `null` if any required claim is missing or wrong type — a JWT that
226
241
  * validates cryptographically but lacks `branch` names no branch to read,
227
- * 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).
228
246
  */
229
- function projectContext(payload: JWTPayload, jwt: string): PreviewContext | null {
247
+ function projectContext(payload: JWTPayload, jwt: string, opts: PreviewMiddlewareOptions): PreviewContext | null {
230
248
  if (payload.scope !== 'preview') return null;
231
249
  const branch = readStringClaim(payload, 'branch');
232
250
  const org = readStringClaim(payload, 'org');
233
251
  const repo = readStringClaim(payload, 'repo');
234
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;
235
255
  // Remaining token lifetime, so the cookie can be bounded to the credential
236
256
  // it carries rather than living for the whole browser session. `exp` is
237
257
  // already verified by `jwtVerify` above, so it is present and in the future.
@@ -245,51 +265,42 @@ function readStringClaim(payload: JWTPayload, name: string): string | undefined
245
265
  return typeof value === 'string' && value.length > 0 ? value : undefined;
246
266
  }
247
267
 
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
268
  /**
259
269
  * Builds the 302 that expires the preview cookie and returns the visitor to
260
270
  * the published page. `?to=` names the page the banner was on; only a
261
271
  * 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 `/`.
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.
263
274
  */
264
- function makeExitRedirect(url: URL, secret: string): Response {
265
- const to = url.searchParams.get('to') ?? '/';
266
- 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;
267
278
  return new Response(null, {
268
279
  status: 302,
269
280
  headers: {
270
281
  location: target,
271
- 'set-cookie': serializePreviewCookie(previewParamName(secret), '', 0),
282
+ 'set-cookie': serializePreviewCookie(PREVIEW_COOKIE_NAME, '', 0),
272
283
  'cache-control': 'private, no-store',
284
+ [PREVIEW_LABEL_HEADER]: label,
273
285
  },
274
286
  });
275
287
  }
276
288
 
277
- function makeInitRedirect(
278
- url: URL,
279
- queryName: string,
280
- token: string,
281
- secret: string,
282
- maxAgeSeconds?: number,
283
- ): 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 {
284
295
  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
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
288
299
  // before any cookie exists. Once the cookie is set (Path=/), every
289
300
  // same-origin request carries the credential, so the visitor belongs on the
290
301
  // 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);
302
+ // route, escapes preview, and silently shows published content.
303
+ cleaned.pathname = stripPreviewPrefix(cleaned.pathname, base);
293
304
  // Normalise the search string: when the only param was the preview JWT,
294
305
  // URL.search becomes '' but URL.toString() still emits a trailing `?` only
295
306
  // if it was already empty. Re-serialising via URL strips that automatically;
@@ -302,7 +313,7 @@ function makeInitRedirect(
302
313
  status: 302,
303
314
  headers: {
304
315
  location,
305
- 'set-cookie': serializePreviewCookie(previewParamName(secret), token, maxAgeSeconds),
316
+ 'set-cookie': serializePreviewCookie(PREVIEW_COOKIE_NAME, token, maxAgeSeconds),
306
317
  'cache-control': 'private, no-store',
307
318
  },
308
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' },
@@ -184,7 +179,7 @@ export function createPreviewSiteMiddleware(resolveOpts: () => PreviewMiddleware
184
179
  await rendered.text(),
185
180
  verdict.ctx,
186
181
  opts.saasEndpoint,
187
- `/${previewParamName(opts.secret)}/__exit`,
182
+ `${previewRoutePrefix(opts.base)}/__exit`,
188
183
  );
189
184
  return applyPreviewHeaders(new Response(html, { status: rendered.status, headers: rendered.headers }));
190
185
  };
@@ -204,7 +199,7 @@ function warnUnconfiguredOnce(error: unknown): void {
204
199
  console.warn(
205
200
  `[@conloca/cloud-astro] draft preview is INERT — ${detail}\n` +
206
201
  ' Requests are being served as the ordinary published site.\n' +
207
- ' 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 ' +
208
203
  '(see the cloud-astro README "Draft previews").',
209
204
  );
210
205
  }