@conloca/cloud-astro 0.2.2 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +378 -207
- package/dist/.build-inputs.json +69 -0
- package/dist/src/component-manifest.d.ts +5 -3
- package/dist/src/component-manifest.d.ts.map +1 -1
- package/dist/src/component-manifest.js +7 -7
- package/dist/src/component-manifest.js.map +1 -1
- package/dist/src/constants.d.ts +14 -13
- package/dist/src/constants.d.ts.map +1 -1
- package/dist/src/constants.js +14 -13
- package/dist/src/constants.js.map +1 -1
- package/dist/src/d3-build.d.ts +70 -0
- package/dist/src/d3-build.d.ts.map +1 -0
- package/dist/src/d3-build.js +272 -0
- package/dist/src/d3-build.js.map +1 -0
- package/dist/src/descriptors.d.ts +2 -2
- package/dist/src/descriptors.d.ts.map +1 -1
- package/dist/src/descriptors.js +4 -2
- package/dist/src/descriptors.js.map +1 -1
- package/dist/src/doctor/checks-address.d.ts +18 -0
- package/dist/src/doctor/checks-address.d.ts.map +1 -0
- package/dist/src/doctor/checks-address.js +163 -0
- package/dist/src/doctor/checks-address.js.map +1 -0
- package/dist/src/doctor/checks-live.d.ts +8 -5
- package/dist/src/doctor/checks-live.d.ts.map +1 -1
- package/dist/src/doctor/checks-live.js +226 -188
- package/dist/src/doctor/checks-live.js.map +1 -1
- package/dist/src/doctor/checks-offline.d.ts +6 -25
- package/dist/src/doctor/checks-offline.d.ts.map +1 -1
- package/dist/src/doctor/checks-offline.js +30 -259
- package/dist/src/doctor/checks-offline.js.map +1 -1
- package/dist/src/doctor/checks-preview-limits.d.ts +11 -0
- package/dist/src/doctor/checks-preview-limits.d.ts.map +1 -0
- package/dist/src/doctor/checks-preview-limits.js +133 -0
- package/dist/src/doctor/checks-preview-limits.js.map +1 -0
- package/dist/src/doctor/checks-preview-live.d.ts +14 -0
- package/dist/src/doctor/checks-preview-live.d.ts.map +1 -0
- package/dist/src/doctor/checks-preview-live.js +72 -0
- package/dist/src/doctor/checks-preview-live.js.map +1 -0
- package/dist/src/doctor/checks-preview.d.ts +7 -0
- package/dist/src/doctor/checks-preview.d.ts.map +1 -0
- package/dist/src/doctor/checks-preview.js +287 -0
- package/dist/src/doctor/checks-preview.js.map +1 -0
- package/dist/src/doctor/config-scan.d.ts +12 -3
- package/dist/src/doctor/config-scan.d.ts.map +1 -1
- package/dist/src/doctor/config-scan.js +38 -11
- package/dist/src/doctor/config-scan.js.map +1 -1
- package/dist/src/doctor/run.d.ts.map +1 -1
- package/dist/src/doctor/run.js +16 -10
- package/dist/src/doctor/run.js.map +1 -1
- package/dist/src/doctor/types.d.ts +17 -7
- package/dist/src/doctor/types.d.ts.map +1 -1
- package/dist/src/doctor/types.js +17 -7
- package/dist/src/doctor/types.js.map +1 -1
- package/dist/src/editor-page/bundle.d.ts +90 -0
- package/dist/src/editor-page/bundle.d.ts.map +1 -0
- package/dist/src/editor-page/bundle.js +373 -0
- package/dist/src/editor-page/bundle.js.map +1 -0
- package/dist/src/editor-page/data-schemas.d.ts +16 -0
- package/dist/src/editor-page/data-schemas.d.ts.map +1 -0
- package/dist/src/editor-page/data-schemas.js +39 -0
- package/dist/src/editor-page/data-schemas.js.map +1 -0
- package/dist/src/editor-page/emit.d.ts +69 -0
- package/dist/src/editor-page/emit.d.ts.map +1 -0
- package/dist/src/editor-page/emit.js +254 -0
- package/dist/src/editor-page/emit.js.map +1 -0
- package/dist/src/editor-page/framing.d.ts +23 -0
- package/dist/src/editor-page/framing.d.ts.map +1 -0
- package/dist/src/editor-page/framing.js +39 -0
- package/dist/src/editor-page/framing.js.map +1 -0
- package/dist/src/editor-page/page.d.ts +9 -0
- package/dist/src/editor-page/page.d.ts.map +1 -0
- package/dist/src/editor-page/page.js +31 -0
- package/dist/src/editor-page/page.js.map +1 -0
- package/dist/src/editor-page/site-base.d.ts +4 -0
- package/dist/src/editor-page/site-base.d.ts.map +1 -0
- package/dist/src/editor-page/site-base.js +13 -0
- package/dist/src/editor-page/site-base.js.map +1 -0
- package/dist/src/git.d.ts +11 -8
- package/dist/src/git.d.ts.map +1 -1
- package/dist/src/git.js +25 -8
- package/dist/src/git.js.map +1 -1
- package/dist/src/index.d.ts +4 -1
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +11 -6
- package/dist/src/index.js.map +1 -1
- package/dist/src/integration.d.ts +1 -1
- package/dist/src/integration.d.ts.map +1 -1
- package/dist/src/integration.js +377 -416
- package/dist/src/integration.js.map +1 -1
- package/dist/src/node.d.ts +3 -1
- package/dist/src/node.d.ts.map +1 -1
- package/dist/src/node.js +7 -2
- package/dist/src/node.js.map +1 -1
- package/dist/src/preview/_dispatch.d.ts +12 -0
- package/dist/src/preview/_dispatch.d.ts.map +1 -1
- package/dist/src/preview/_dispatch.js +31 -0
- package/dist/src/preview/_dispatch.js.map +1 -1
- package/dist/src/preview/_resolve-opts.d.ts +19 -10
- package/dist/src/preview/_resolve-opts.d.ts.map +1 -1
- package/dist/src/preview/_resolve-opts.js +24 -11
- package/dist/src/preview/_resolve-opts.js.map +1 -1
- package/dist/src/preview/banner.d.ts +12 -9
- package/dist/src/preview/banner.d.ts.map +1 -1
- package/dist/src/preview/banner.js +46 -43
- package/dist/src/preview/banner.js.map +1 -1
- package/dist/src/preview/cloudflare-adapter.d.ts +35 -0
- package/dist/src/preview/cloudflare-adapter.d.ts.map +1 -0
- package/dist/src/preview/cloudflare-adapter.js +92 -0
- package/dist/src/preview/cloudflare-adapter.js.map +1 -0
- package/dist/src/preview/cookie.d.ts +13 -14
- package/dist/src/preview/cookie.d.ts.map +1 -1
- package/dist/src/preview/cookie.js +19 -26
- package/dist/src/preview/cookie.js.map +1 -1
- package/dist/src/preview/dispatcher.d.ts +73 -0
- package/dist/src/preview/dispatcher.d.ts.map +1 -0
- package/dist/src/preview/dispatcher.js +329 -0
- package/dist/src/preview/dispatcher.js.map +1 -0
- package/dist/src/preview/entry-code.d.ts +33 -0
- package/dist/src/preview/entry-code.d.ts.map +1 -0
- package/dist/src/preview/entry-code.js +33 -0
- package/dist/src/preview/entry-code.js.map +1 -0
- package/dist/src/preview/headers.d.ts +24 -4
- package/dist/src/preview/headers.d.ts.map +1 -1
- package/dist/src/preview/headers.js +35 -7
- package/dist/src/preview/headers.js.map +1 -1
- package/dist/src/preview/label.d.ts +8 -0
- package/dist/src/preview/label.d.ts.map +1 -0
- package/dist/src/preview/label.js +14 -0
- package/dist/src/preview/label.js.map +1 -0
- package/dist/src/preview/landing.d.ts +23 -2
- package/dist/src/preview/landing.d.ts.map +1 -1
- package/dist/src/preview/landing.js +105 -37
- package/dist/src/preview/landing.js.map +1 -1
- package/dist/src/preview/middleware.d.ts +49 -22
- package/dist/src/preview/middleware.d.ts.map +1 -1
- package/dist/src/preview/middleware.js +259 -100
- package/dist/src/preview/middleware.js.map +1 -1
- package/dist/src/preview/preview-path.d.ts +47 -5
- package/dist/src/preview/preview-path.d.ts.map +1 -1
- package/dist/src/preview/preview-path.js +65 -8
- package/dist/src/preview/preview-path.js.map +1 -1
- package/dist/src/preview/redeem-url.d.ts +7 -0
- package/dist/src/preview/redeem-url.d.ts.map +1 -0
- package/dist/src/preview/redeem-url.js +14 -0
- package/dist/src/preview/redeem-url.js.map +1 -0
- package/dist/src/preview/site-middleware.d.ts +5 -5
- package/dist/src/preview/site-middleware.d.ts.map +1 -1
- package/dist/src/preview/site-middleware.js +53 -26
- package/dist/src/preview/site-middleware.js.map +1 -1
- package/dist/src/preview-build.d.ts +29 -15
- package/dist/src/preview-build.d.ts.map +1 -1
- package/dist/src/preview-build.js +66 -25
- package/dist/src/preview-build.js.map +1 -1
- package/dist/src/preview.d.ts +1 -1
- package/dist/src/preview.d.ts.map +1 -1
- package/dist/src/preview.js +1 -1
- package/dist/src/preview.js.map +1 -1
- package/dist/src/repository.d.ts +1 -1
- package/dist/src/repository.js +1 -1
- package/dist/src/resolve-options.d.ts +17 -0
- package/dist/src/resolve-options.d.ts.map +1 -0
- package/dist/src/resolve-options.js +21 -0
- package/dist/src/resolve-options.js.map +1 -0
- package/dist/src/site-id.d.ts +0 -2
- package/dist/src/site-id.d.ts.map +1 -1
- package/dist/src/site-id.js +2 -3
- package/dist/src/site-id.js.map +1 -1
- package/dist/src/skill.d.ts +11 -0
- package/dist/src/skill.d.ts.map +1 -1
- package/dist/src/skill.js +32 -9
- package/dist/src/skill.js.map +1 -1
- package/dist/src/types.d.ts +33 -78
- package/dist/src/types.d.ts.map +1 -1
- package/package.json +63 -13
- package/src/component-manifest.ts +11 -8
- package/src/constants.ts +15 -13
- package/src/d3-build.ts +315 -0
- package/src/descriptors.ts +6 -4
- package/src/doctor/checks-address.ts +190 -0
- package/src/doctor/checks-live.ts +262 -268
- package/src/doctor/checks-offline.ts +32 -279
- package/src/doctor/checks-preview-limits.ts +137 -0
- package/src/doctor/checks-preview-live.ts +77 -0
- package/src/doctor/checks-preview.ts +302 -0
- package/src/doctor/config-scan.ts +35 -9
- package/src/doctor/run.ts +18 -16
- package/src/doctor/types.ts +17 -7
- package/src/editor-page/bundle.ts +487 -0
- package/src/editor-page/data-schemas.ts +47 -0
- package/src/editor-page/emit.ts +362 -0
- package/src/editor-page/framing.ts +62 -0
- package/src/editor-page/page.ts +37 -0
- package/src/editor-page/site-base.ts +11 -0
- package/src/git.ts +29 -10
- package/src/index.ts +22 -6
- package/src/integration.ts +399 -469
- package/src/node.ts +18 -2
- package/src/preview/_dispatch.ts +36 -1
- package/src/preview/_resolve-opts.ts +35 -12
- package/src/preview/banner.ts +61 -43
- package/src/preview/cloudflare-adapter.ts +103 -0
- package/src/preview/cookie.ts +18 -24
- package/src/preview/dispatcher.ts +407 -0
- package/src/preview/entry-code.ts +51 -0
- package/src/preview/headers.ts +35 -7
- package/src/preview/label.ts +12 -0
- package/src/preview/landing.ts +117 -39
- package/src/preview/middleware.ts +302 -115
- package/src/preview/preview-path.ts +83 -8
- package/src/preview/redeem-url.ts +14 -0
- package/src/preview/site-middleware.ts +60 -30
- package/src/preview-build.ts +85 -26
- package/src/preview-handler.astro +12 -9
- package/src/preview.ts +0 -1
- package/src/repository.ts +1 -1
- package/src/resolve-options.ts +37 -0
- package/src/site-id.ts +2 -4
- package/src/skill/SKILL.md +63 -55
- package/src/skill.ts +36 -8
- package/src/types.ts +33 -79
- package/src/virtual-modules.d.ts +4 -1
- package/dist/src/build-commit.d.ts +0 -19
- package/dist/src/build-commit.d.ts.map +0 -1
- package/dist/src/build-commit.js +0 -6
- package/dist/src/build-commit.js.map +0 -1
- package/dist/src/bundle.d.ts +0 -181
- package/dist/src/bundle.d.ts.map +0 -1
- package/dist/src/bundle.js +0 -413
- package/dist/src/bundle.js.map +0 -1
- package/dist/src/discovery.d.ts +0 -58
- package/dist/src/discovery.d.ts.map +0 -1
- package/dist/src/discovery.js +0 -133
- package/dist/src/discovery.js.map +0 -1
- package/dist/src/register.d.ts +0 -98
- package/dist/src/register.d.ts.map +0 -1
- package/dist/src/register.js +0 -103
- package/dist/src/register.js.map +0 -1
- package/src/build-commit.ts +0 -22
- package/src/bundle.ts +0 -570
- package/src/discovery.ts +0 -183
- package/src/register.ts +0 -180
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The dispatcher a static site runs on Cloudflare Workers when draft previews are served next to it (D3). Cloudflare
|
|
3
|
+
* runs it only on the paths `wrangler.jsonc` lists in `run_worker_first`, the preview route and the site's on-demand
|
|
4
|
+
* routes, so a visitor to any other page never starts it. Under the route it answers the exit itself, counts every
|
|
5
|
+
* other request against a per-IP rate limit, refuses a request with no code and no pass before the preview server
|
|
6
|
+
* is loaded, serves published bytes to scripts and, once their pass verifies, to pages the preview build prerendered,
|
|
7
|
+
* and hands draft pages to
|
|
8
|
+
* the preview server at their own path with the branch slug in a request header only it sets.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { branchOfPreviewSlug } from '@conloca/content-api/editor-host';
|
|
12
|
+
import { injectPreviewBanner } from './banner.js';
|
|
13
|
+
import { parseCookieValues } from './cookie.js';
|
|
14
|
+
import { applyPreviewHeaders, PREVIEW_CACHE_HEADERS } from './headers.js';
|
|
15
|
+
import { renderNoPreviewLanding, renderPreviewUnavailable } from './landing.js';
|
|
16
|
+
import { handlePreviewRequest, type PreviewContext, type PreviewMiddlewareOptions } from './middleware.js';
|
|
17
|
+
import {
|
|
18
|
+
normalizeTrailingSlash,
|
|
19
|
+
PREVIEW_CODE_PARAM,
|
|
20
|
+
PREVIEW_SLUG_HEADER,
|
|
21
|
+
previewRoutePrefix,
|
|
22
|
+
previewScope,
|
|
23
|
+
} from './preview-path.js';
|
|
24
|
+
|
|
25
|
+
/** What the exit route needs to answer without the preview server: the build's own repository, site and branch. */
|
|
26
|
+
export interface DispatcherExit {
|
|
27
|
+
repo: string;
|
|
28
|
+
siteId: string;
|
|
29
|
+
branch: string;
|
|
30
|
+
audience: string;
|
|
31
|
+
/** The issuer every pass must name, when the integration options name one. */
|
|
32
|
+
issuer?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** What the build writes next to the dispatcher (`.conloca/dispatcher/dispatcher.json`). */
|
|
36
|
+
export interface DispatcherConfig {
|
|
37
|
+
/** Astro's `base`. */
|
|
38
|
+
base: string;
|
|
39
|
+
/** The editor endpoint the landing page sends a visitor to. */
|
|
40
|
+
endpoint: string;
|
|
41
|
+
/** Pages the preview build prerendered, as request paths without a trailing slash: their published bytes are the preview. */
|
|
42
|
+
prerendered: string[];
|
|
43
|
+
/** Hosts sites.json declares: links to them are links to this site. */
|
|
44
|
+
domains: string[];
|
|
45
|
+
/** The exit route's values; null when the preview build failed, so the probe reads "no preview server". */
|
|
46
|
+
exit: DispatcherExit | null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** A Cloudflare Workers rate-limit binding, as the dispatcher calls it. */
|
|
50
|
+
export interface PreviewLimiter {
|
|
51
|
+
limit(input: { key: string }): Promise<{ success: boolean }>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface DispatcherEnv {
|
|
55
|
+
ASSETS: { fetch(request: Request): Promise<Response> };
|
|
56
|
+
/** wrangler.jsonc `ratelimits`, written by `conloca connect` on the Paid plan: 60 requests per 10 s per key. Absent on Free. */
|
|
57
|
+
conlocaPreviewLimit?: PreviewLimiter;
|
|
58
|
+
/** The same overrides the preview server reads (`resolveFromBaked`), so both check a pass alike. */
|
|
59
|
+
CONLOCA_SAAS_ENDPOINT?: string;
|
|
60
|
+
CONLOCA_SAAS_ISSUER?: string;
|
|
61
|
+
CONLOCA_SAAS_AUDIENCE?: string;
|
|
62
|
+
/** A binding that reaches the endpoint when a plain fetch by hostname can't. */
|
|
63
|
+
CONLOCA_SAAS?: { fetch(input: Request | string | URL, init?: RequestInit): Promise<Response> };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const TOO_MANY =
|
|
67
|
+
'<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Too many preview requests</title></head>' +
|
|
68
|
+
'<body><p>Too many preview requests — try again in a few seconds.</p></body></html>';
|
|
69
|
+
|
|
70
|
+
/** The answer over the preview route's rate limit: the limit's window is 10 s. */
|
|
71
|
+
export function renderTooManyPreviewRequests(): Response {
|
|
72
|
+
return applyPreviewHeaders(
|
|
73
|
+
new Response(TOO_MANY, {
|
|
74
|
+
status: 429,
|
|
75
|
+
headers: { 'content-type': 'text/html; charset=utf-8', 'retry-after': '10' },
|
|
76
|
+
}),
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The limit's key for a client address: IPv4 whole, IPv6 by its /64, since one host holds a whole /64. */
|
|
81
|
+
export function limitKey(ip: string | null): string {
|
|
82
|
+
if (ip === null || ip === '') return 'unknown';
|
|
83
|
+
if (!ip.includes(':')) return ip;
|
|
84
|
+
const [head = '', tail] = ip.split('::');
|
|
85
|
+
const left = head === '' ? [] : head.split(':');
|
|
86
|
+
const right = tail === undefined || tail === '' ? [] : tail.split(':');
|
|
87
|
+
const zeros = Array.from({ length: Math.max(0, 8 - left.length - right.length) }, () => '0');
|
|
88
|
+
const groups = tail === undefined ? left : [...left, ...zeros, ...right];
|
|
89
|
+
return `${groups
|
|
90
|
+
.slice(0, 4)
|
|
91
|
+
.map((group) => group.toLowerCase().replace(/^0+(?=.)/u, ''))
|
|
92
|
+
.join(':')}::/64`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Whether this request is within the preview route's limit. A D3 site on the Free plan has no binding (on Free a
|
|
97
|
+
* blocked request still counts against the daily quota, so a limiter adds nothing), and a limiter that
|
|
98
|
+
* fails at run time must not take every preview down with it, so both are served.
|
|
99
|
+
*/
|
|
100
|
+
async function withinLimit(request: Request, env: DispatcherEnv): Promise<boolean> {
|
|
101
|
+
const limiter = env.conlocaPreviewLimit;
|
|
102
|
+
if (limiter === undefined) return true;
|
|
103
|
+
try {
|
|
104
|
+
return (await limiter.limit({ key: limitKey(request.headers.get('cf-connecting-ip')) })).success;
|
|
105
|
+
} catch {
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface PreviewServerModule {
|
|
111
|
+
default: { fetch(request: Request, env: unknown, ctx: unknown): Promise<Response> };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The element surface the rewriter touches; the runtime's own type is wider. */
|
|
115
|
+
interface Attributes {
|
|
116
|
+
getAttribute(name: string): string | null;
|
|
117
|
+
setAttribute(name: string, value: string): void;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* `value` under the preview route when it names a page of this site, else null (left as it is). It is resolved
|
|
122
|
+
* against `page`, the unprefixed URL the page was rendered for, so `../x` and `?q` keep their meaning. Files, built
|
|
123
|
+
* assets, the image endpoint, `/_conloca/` and other sites stay where they are.
|
|
124
|
+
*/
|
|
125
|
+
export function previewHref(
|
|
126
|
+
value: string,
|
|
127
|
+
page: URL,
|
|
128
|
+
route: string,
|
|
129
|
+
root: string,
|
|
130
|
+
hosts: ReadonlySet<string>,
|
|
131
|
+
): string | null {
|
|
132
|
+
if (value === '' || value.startsWith('#')) return null;
|
|
133
|
+
let target: URL;
|
|
134
|
+
try {
|
|
135
|
+
target = new URL(value, page);
|
|
136
|
+
} catch {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
if (target.protocol !== 'http:' && target.protocol !== 'https:') return null;
|
|
140
|
+
const own = target.host === page.host;
|
|
141
|
+
if (!own && !hosts.has(target.hostname)) return null;
|
|
142
|
+
const { pathname } = target;
|
|
143
|
+
if (root !== '' && pathname !== root && !pathname.startsWith(`${root}/`)) return null;
|
|
144
|
+
const rest = pathname.slice(root.length) || '/';
|
|
145
|
+
if (rest.startsWith('/_conloca/') || rest.startsWith('/_astro/') || rest === '/_image') return null;
|
|
146
|
+
const last = rest.slice(rest.lastIndexOf('/') + 1);
|
|
147
|
+
if (last.includes('.') && !last.endsWith('.html')) return null;
|
|
148
|
+
const moved = `${route}${rest}${target.search}${target.hash}`;
|
|
149
|
+
return own ? moved : `${target.origin}${moved}`;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** A navigation, the only request that may receive draft HTML; without Sec-Fetch-*, one that asks for HTML. */
|
|
153
|
+
function isNavigation(request: Request): boolean {
|
|
154
|
+
const mode = request.headers.get('sec-fetch-mode');
|
|
155
|
+
if (mode !== null) return mode === 'navigate';
|
|
156
|
+
return (request.headers.get('accept') ?? '').includes('text/html');
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* `srcset` with each candidate URL that `move` answers for replaced, everything else kept byte for byte; null when none
|
|
161
|
+
* moved. A URL runs to the next whitespace, as the HTML parser reads it, so a `data:` URL's commas stay inside it.
|
|
162
|
+
*/
|
|
163
|
+
function movedSrcset(value: string, move: (href: string) => string | null): string | null {
|
|
164
|
+
let out = '';
|
|
165
|
+
let rest = value;
|
|
166
|
+
let moved = false;
|
|
167
|
+
while (rest !== '') {
|
|
168
|
+
const gap = /^[\s,]*/u.exec(rest)?.[0] ?? '';
|
|
169
|
+
const token = /^\S*/u.exec(rest.slice(gap.length))?.[0] ?? '';
|
|
170
|
+
const commas = /,*$/u.exec(token)?.[0] ?? '';
|
|
171
|
+
const href = token.slice(0, token.length - commas.length);
|
|
172
|
+
rest = rest.slice(gap.length + token.length);
|
|
173
|
+
// Descriptors (`1x`, `400w`) run to the next comma, unless the URL already ended at one.
|
|
174
|
+
const descriptor = commas === '' ? (/^[^,]*/u.exec(rest)?.[0] ?? '') : '';
|
|
175
|
+
rest = rest.slice(descriptor.length);
|
|
176
|
+
const target = href === '' ? null : move(href);
|
|
177
|
+
if (target !== null) moved = true;
|
|
178
|
+
out += `${gap}${target ?? href}${commas}${descriptor}`;
|
|
179
|
+
}
|
|
180
|
+
return moved ? out : null;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function linkRewriter(page: URL, route: string, root: string, hosts: ReadonlySet<string>): HTMLRewriter {
|
|
184
|
+
// A `<base href>` changes what relative links resolve against for every link after it.
|
|
185
|
+
let resolveAgainst = page;
|
|
186
|
+
const move = (element: Attributes, name: string): boolean => {
|
|
187
|
+
const value = element.getAttribute(name);
|
|
188
|
+
const moved = value === null ? null : previewHref(value, resolveAgainst, route, root, hosts);
|
|
189
|
+
if (moved !== null) element.setAttribute(name, moved);
|
|
190
|
+
return moved !== null;
|
|
191
|
+
};
|
|
192
|
+
return new HTMLRewriter()
|
|
193
|
+
.on('base[href]', {
|
|
194
|
+
element(element) {
|
|
195
|
+
const value = element.getAttribute('href');
|
|
196
|
+
if (value !== null && URL.canParse(value, page.href)) resolveAgainst = new URL(value, page);
|
|
197
|
+
move(element, 'href');
|
|
198
|
+
},
|
|
199
|
+
})
|
|
200
|
+
.on('a[href], area[href]', {
|
|
201
|
+
element(element) {
|
|
202
|
+
// Astro's prefetch would spend the visitor's 60 requests per 10 s on links they never open.
|
|
203
|
+
if (move(element, 'href')) element.setAttribute('data-astro-prefetch', 'false');
|
|
204
|
+
},
|
|
205
|
+
})
|
|
206
|
+
.on('form[action]', {
|
|
207
|
+
element(element) {
|
|
208
|
+
move(element, 'action');
|
|
209
|
+
},
|
|
210
|
+
})
|
|
211
|
+
.on('[srcset]', {
|
|
212
|
+
element(element) {
|
|
213
|
+
const value = element.getAttribute('srcset');
|
|
214
|
+
const moved =
|
|
215
|
+
value === null ? null : movedSrcset(value, (href) => previewHref(href, resolveAgainst, route, root, hosts));
|
|
216
|
+
if (moved !== null) element.setAttribute('srcset', moved);
|
|
217
|
+
},
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** How the dispatcher checks a pass: with the values the preview build baked, and the overrides its server reads. */
|
|
222
|
+
function passOptions(
|
|
223
|
+
config: DispatcherConfig,
|
|
224
|
+
exit: DispatcherExit,
|
|
225
|
+
env: DispatcherEnv,
|
|
226
|
+
slug: string,
|
|
227
|
+
): PreviewMiddlewareOptions {
|
|
228
|
+
const binding = env.CONLOCA_SAAS;
|
|
229
|
+
const issuer = env.CONLOCA_SAAS_ISSUER || exit.issuer;
|
|
230
|
+
return {
|
|
231
|
+
saasEndpoint: env.CONLOCA_SAAS_ENDPOINT || config.endpoint,
|
|
232
|
+
saasAudience: env.CONLOCA_SAAS_AUDIENCE || exit.audience,
|
|
233
|
+
...(issuer ? { saasIssuer: issuer } : {}),
|
|
234
|
+
repo: exit.repo,
|
|
235
|
+
siteId: exit.siteId,
|
|
236
|
+
branch: exit.branch,
|
|
237
|
+
base: config.base,
|
|
238
|
+
mode: 'd3',
|
|
239
|
+
slug,
|
|
240
|
+
onMiss: 'landing',
|
|
241
|
+
// `preconnect` only satisfies the type: jose calls the function alone.
|
|
242
|
+
...(binding === undefined
|
|
243
|
+
? {}
|
|
244
|
+
: {
|
|
245
|
+
fetchFn: Object.assign((input: Request | string | URL, init?: RequestInit) => binding.fetch(input, init), {
|
|
246
|
+
preconnect: fetch.preconnect,
|
|
247
|
+
}),
|
|
248
|
+
}),
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
export function createDispatcher(config: DispatcherConfig, loadServer: (() => Promise<PreviewServerModule>) | null) {
|
|
253
|
+
const prefix = previewRoutePrefix(config.base);
|
|
254
|
+
const root = config.base.replace(/\/+$/u, '');
|
|
255
|
+
const prerendered = new Set(config.prerendered);
|
|
256
|
+
const hosts = new Set(config.domains);
|
|
257
|
+
|
|
258
|
+
/** The exit route, from the build's own values: the probe never waits for the preview server. */
|
|
259
|
+
async function exit(url: URL, slug: string | undefined): Promise<Response> {
|
|
260
|
+
if (config.exit === null) {
|
|
261
|
+
// No label: Conloca reads "no preview server" and says so, instead of minting a link to a 503 page.
|
|
262
|
+
return new Response(null, { status: 302, headers: { location: config.base, ...PREVIEW_CACHE_HEADERS } });
|
|
263
|
+
}
|
|
264
|
+
const verdict = await handlePreviewRequest(new Request(`${url.origin}${prefix}/__exit${url.search}`), {
|
|
265
|
+
saasEndpoint: config.endpoint,
|
|
266
|
+
saasAudience: config.exit.audience,
|
|
267
|
+
repo: config.exit.repo,
|
|
268
|
+
siteId: config.exit.siteId,
|
|
269
|
+
branch: config.exit.branch,
|
|
270
|
+
base: config.base,
|
|
271
|
+
mode: 'd3',
|
|
272
|
+
...(slug === undefined ? {} : { slug }),
|
|
273
|
+
});
|
|
274
|
+
// The exit branch always answers a response; anything else would be a bug in this call, so fail closed.
|
|
275
|
+
return verdict.kind === 'response'
|
|
276
|
+
? applyPreviewHeaders(verdict.response)
|
|
277
|
+
: applyPreviewHeaders(new Response(null, { status: 302, headers: { location: config.base } }));
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** An entry answer (a redirect or Conloca's own page): headers and `Location` only, never its HTML. */
|
|
281
|
+
function finishEntry(answer: Response, page: URL, route: string): Response {
|
|
282
|
+
const out = applyPreviewHeaders(answer);
|
|
283
|
+
const location = out.headers.get('location');
|
|
284
|
+
const moved = location === null ? null : previewHref(location, page, route, root, hosts);
|
|
285
|
+
if (moved !== null) out.headers.set('location', moved);
|
|
286
|
+
return out;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/** The draft answer with the route put back on its location and links. */
|
|
290
|
+
async function finish(
|
|
291
|
+
answer: Response,
|
|
292
|
+
page: URL,
|
|
293
|
+
route: string,
|
|
294
|
+
published: Pick<PreviewContext, 'branch' | 'grant'> | null,
|
|
295
|
+
): Promise<Response> {
|
|
296
|
+
const out = finishEntry(answer, page, route);
|
|
297
|
+
if (!(out.headers.get('content-type') ?? '').includes('text/html')) return out;
|
|
298
|
+
const rewriter = linkRewriter(page, route, root, hosts);
|
|
299
|
+
if (published === null) return rewriter.transform(out);
|
|
300
|
+
// A page the preview build prerendered: the preview server never saw it, so its banner goes in here.
|
|
301
|
+
out.headers.delete('content-length');
|
|
302
|
+
const html = injectPreviewBanner(
|
|
303
|
+
await out.text(),
|
|
304
|
+
// The pass's own context: a share viewer sees who shared the draft and when the link expires.
|
|
305
|
+
published,
|
|
306
|
+
undefined,
|
|
307
|
+
`${route}/__exit`,
|
|
308
|
+
undefined,
|
|
309
|
+
page.pathname,
|
|
310
|
+
);
|
|
311
|
+
return rewriter.transform(new Response(html, out));
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
return {
|
|
315
|
+
async fetch(request: Request, env: DispatcherEnv, ctx: unknown): Promise<Response> {
|
|
316
|
+
const url = new URL(request.url);
|
|
317
|
+
const headers = new Headers(request.headers);
|
|
318
|
+
// The preview server trusts this header; only this module may set it.
|
|
319
|
+
headers.delete(PREVIEW_SLUG_HEADER);
|
|
320
|
+
const forward = async (load: () => Promise<PreviewServerModule>, target: URL, slug: string | undefined) => {
|
|
321
|
+
if (slug !== undefined) headers.set(PREVIEW_SLUG_HEADER, slug);
|
|
322
|
+
const body = request.method === 'GET' || request.method === 'HEAD' ? null : await request.arrayBuffer();
|
|
323
|
+
const forwarded = new Request(target.href, { method: request.method, headers, body, redirect: 'manual' });
|
|
324
|
+
return (await load()).default.fetch(forwarded, env, ctx);
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
if (url.pathname !== prefix && !url.pathname.startsWith(`${prefix}/`)) {
|
|
328
|
+
// `<base>_image` is listed for draft pages only (the live site's pages are prerendered), so it is the
|
|
329
|
+
// preview's to pay for: it counts against the preview route's limit.
|
|
330
|
+
if (url.pathname === `${root}/_image` && !(await withinLimit(request, env)))
|
|
331
|
+
return renderTooManyPreviewRequests();
|
|
332
|
+
// The site's own on-demand routes (and, with not_found_handling "none", its misses): unprefixed, no draft
|
|
333
|
+
// context, and no catch: production fails loudly here. A failed preview build ships with a null server only
|
|
334
|
+
// when the site lists nothing beyond the prefix (`finishD3Build`), so this fallback is never a live API route.
|
|
335
|
+
return loadServer === null ? env.ASSETS.fetch(request) : forward(loadServer, url, undefined);
|
|
336
|
+
}
|
|
337
|
+
const [first = '', ...rest] = url.pathname.slice(prefix.length + 1).split('/');
|
|
338
|
+
// The probe, and a page's own exit: answered here, never counted, never loading the server.
|
|
339
|
+
if (first === '__exit' && rest.length === 0) return exit(url, undefined);
|
|
340
|
+
const branch = branchOfPreviewSlug(first);
|
|
341
|
+
if (branch !== null && rest.length === 1 && rest[0] === '__exit') return exit(url, first);
|
|
342
|
+
|
|
343
|
+
// Every other request under the route counts, `__status` included, before any other work.
|
|
344
|
+
if (!(await withinLimit(request, env))) return renderTooManyPreviewRequests();
|
|
345
|
+
const entering = url.searchParams.has(PREVIEW_CODE_PARAM);
|
|
346
|
+
const inner = branch === null ? `${root}/${[first, ...rest].join('/')}` : `${root}/${rest.join('/')}`;
|
|
347
|
+
const route = branch === null ? prefix : previewScope('d3', config.base, first).route;
|
|
348
|
+
const { exit: baked } = config;
|
|
349
|
+
if (loadServer === null || baked === null) {
|
|
350
|
+
const page = renderPreviewUnavailable({ retryHref: `${url.pathname}${url.search}`, exitHref: config.base });
|
|
351
|
+
return applyPreviewHeaders(new Response(page.body, { status: 503, headers: page.headers }));
|
|
352
|
+
}
|
|
353
|
+
// Under the route a preview server that throws (a Node-only import, a render error) answers
|
|
354
|
+
// "Preview couldn't load the draft", never Cloudflare's own error page.
|
|
355
|
+
const guarded = async (target: URL, slug: string | undefined): Promise<Response> => {
|
|
356
|
+
try {
|
|
357
|
+
return await forward(loadServer, target, slug);
|
|
358
|
+
} catch (error) {
|
|
359
|
+
console.error('@conloca/cloud-astro: the preview server failed', error);
|
|
360
|
+
const page = renderPreviewUnavailable({
|
|
361
|
+
retryHref: `${url.pathname}${url.search}`,
|
|
362
|
+
exitHref: `${route}/__exit?to=${encodeURIComponent(inner)}`,
|
|
363
|
+
});
|
|
364
|
+
return applyPreviewHeaders(new Response(page.body, { status: 503, headers: page.headers }));
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
const landing = () =>
|
|
368
|
+
applyPreviewHeaders(renderNoPreviewLanding({ pathname: inner, saasEndpoint: config.endpoint }));
|
|
369
|
+
|
|
370
|
+
if (branch === null) {
|
|
371
|
+
// A slugless entry link: the preview server exchanges the code and takes the slug from the pass.
|
|
372
|
+
if (!entering) return landing();
|
|
373
|
+
return finishEntry(await guarded(url, undefined), url, prefix);
|
|
374
|
+
}
|
|
375
|
+
const scope = previewScope('d3', config.base, first);
|
|
376
|
+
const cookie = request.headers.get('cookie');
|
|
377
|
+
const holds =
|
|
378
|
+
parseCookieValues(cookie, scope.pass).length > 0 ||
|
|
379
|
+
(scope.grant !== null && parseCookieValues(cookie, scope.grant).length > 0);
|
|
380
|
+
// Refused before the preview server loads: a request with no credential never pays for its start-up.
|
|
381
|
+
if (!entering && !holds) return landing();
|
|
382
|
+
const page = new URL(`${inner}${url.search}`, url.origin);
|
|
383
|
+
if (entering) {
|
|
384
|
+
// The adapter serves a prerendered page from the static files before any middleware runs, so the code goes
|
|
385
|
+
// to the preview build's entry route (`<prefix>/[...path]`, always on demand), as under D2.
|
|
386
|
+
const entry = new URL(`${prefix}${inner.slice(root.length)}${url.search}`, url.origin);
|
|
387
|
+
return finishEntry(await guarded(entry, first), page, scope.route);
|
|
388
|
+
}
|
|
389
|
+
if (!isNavigation(request)) {
|
|
390
|
+
// Scripts never read drafts: a fetch under the route gets published bytes.
|
|
391
|
+
return applyPreviewHeaders(await env.ASSETS.fetch(new Request(page.href, { headers })));
|
|
392
|
+
}
|
|
393
|
+
if (prerendered.has(normalizeTrailingSlash(inner))) {
|
|
394
|
+
// The preview server never sees a prerendered page, so its pass is checked here, as the server checks every
|
|
395
|
+
// other: one that fails gets the landing page (or the share link's renewal), never the banner.
|
|
396
|
+
const verdict = await handlePreviewRequest(
|
|
397
|
+
new Request(page.href, { headers }),
|
|
398
|
+
passOptions(config, baked, env, first),
|
|
399
|
+
);
|
|
400
|
+
if (verdict.kind !== 'preview')
|
|
401
|
+
return finishEntry(verdict.kind === 'response' ? verdict.response : landing(), page, scope.route);
|
|
402
|
+
return finish(await env.ASSETS.fetch(new Request(page.href, { headers })), page, scope.route, verdict.ctx);
|
|
403
|
+
}
|
|
404
|
+
return finish(await guarded(page, first), page, scope.route, null);
|
|
405
|
+
},
|
|
406
|
+
};
|
|
407
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { type ShareEndedKind, shareEndedOf } from './_dispatch.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Trades the single-use code from a preview link for the pass, server to server, so no pass travels in a link,
|
|
5
|
+
* a browser history or an access log. Conloca accepts a code once, within a minute, and only for the origin,
|
|
6
|
+
* repository and site it was issued for. Only `unknown` (a code already used, or never issued) lets the caller fall
|
|
7
|
+
* back to a pass the visitor already holds; an ended link or any other failure must not open some other preview.
|
|
8
|
+
*/
|
|
9
|
+
export type EntryCodeResult =
|
|
10
|
+
| { ok: true; pass: string }
|
|
11
|
+
| { ok: false; kind: 'unknown' }
|
|
12
|
+
| { ok: false; kind: 'ended'; ended: { verdict: ShareEndedKind; sharedBy: string } }
|
|
13
|
+
| { ok: false; kind: 'unavailable' };
|
|
14
|
+
|
|
15
|
+
export async function exchangeEntryCode(input: {
|
|
16
|
+
saasEndpoint: string;
|
|
17
|
+
code: string;
|
|
18
|
+
origin: string;
|
|
19
|
+
repo: string;
|
|
20
|
+
siteId: string;
|
|
21
|
+
fetchFn?: typeof fetch;
|
|
22
|
+
}): Promise<EntryCodeResult> {
|
|
23
|
+
const fetchImpl = input.fetchFn ?? fetch;
|
|
24
|
+
try {
|
|
25
|
+
const response = await fetchImpl(`${input.saasEndpoint}/preview/exchange`, {
|
|
26
|
+
method: 'POST',
|
|
27
|
+
headers: { 'content-type': 'application/json' },
|
|
28
|
+
body: JSON.stringify({ code: input.code, origin: input.origin, repo: input.repo, siteId: input.siteId }),
|
|
29
|
+
redirect: 'manual',
|
|
30
|
+
});
|
|
31
|
+
if (response.status === 404) {
|
|
32
|
+
const body: unknown = await response.json().catch(() => null);
|
|
33
|
+
const error = typeof body === 'object' && body !== null && 'error' in body ? body.error : undefined;
|
|
34
|
+
return error === 'code-unknown' ? { ok: false, kind: 'unknown' } : UNAVAILABLE;
|
|
35
|
+
}
|
|
36
|
+
if (response.status === 410) {
|
|
37
|
+
const ended = await shareEndedOf(response);
|
|
38
|
+
return ended === null
|
|
39
|
+
? UNAVAILABLE
|
|
40
|
+
: { ok: false, kind: 'ended', ended: { verdict: ended.kind, sharedBy: ended.sharedBy } };
|
|
41
|
+
}
|
|
42
|
+
if (response.status !== 200) return UNAVAILABLE;
|
|
43
|
+
const body: unknown = await response.json();
|
|
44
|
+
const pass = typeof body === 'object' && body !== null && 'pass' in body ? body.pass : undefined;
|
|
45
|
+
return typeof pass === 'string' && pass !== '' ? { ok: true, pass } : UNAVAILABLE;
|
|
46
|
+
} catch {
|
|
47
|
+
return UNAVAILABLE;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const UNAVAILABLE: EntryCodeResult = { ok: false, kind: 'unavailable' };
|
package/src/preview/headers.ts
CHANGED
|
@@ -1,3 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Headers every preview response carries, its redirects and Conloca's own pages included:
|
|
3
|
+
*
|
|
4
|
+
* - `cache-control: private, no-store` — preview content is per-branch and
|
|
5
|
+
* per-pass, so no shared cache may keep it. `no-store` also prevents
|
|
6
|
+
* browser disk persistence, so a shared workstation doesn't expose draft
|
|
7
|
+
* pages.
|
|
8
|
+
* - `cdn-cache-control: no-store` and `vercel-cdn-cache-control: no-store` —
|
|
9
|
+
* CDNs read these before `cache-control` (RFC 9213), so a site-wide CDN
|
|
10
|
+
* rule that caches pages can't cache a draft.
|
|
11
|
+
* - `referrer-policy: same-origin` — a link out of a draft never tells
|
|
12
|
+
* another site the draft's address.
|
|
13
|
+
* - `vary: Cookie` — the same URL answers differently with and without the
|
|
14
|
+
* preview cookie.
|
|
15
|
+
*/
|
|
16
|
+
export const PREVIEW_CACHE_HEADERS = {
|
|
17
|
+
'cache-control': 'private, no-store',
|
|
18
|
+
'cdn-cache-control': 'no-store',
|
|
19
|
+
'vercel-cdn-cache-control': 'no-store',
|
|
20
|
+
'referrer-policy': 'same-origin',
|
|
21
|
+
vary: 'Cookie',
|
|
22
|
+
} as const;
|
|
23
|
+
|
|
1
24
|
/**
|
|
2
25
|
* Wraps a rendered preview response with the SEO/cache protection headers
|
|
3
26
|
* required for all preview responses:
|
|
@@ -7,10 +30,8 @@
|
|
|
7
30
|
* containment. Cloudflare Pages preview deployments already set this
|
|
8
31
|
* for their own preview URLs; we set it again so the protection
|
|
9
32
|
* survives custom domains, non-Pages hosts, and on-prem deployments.
|
|
10
|
-
* -
|
|
11
|
-
*
|
|
12
|
-
* a shared cache. `no-store` also prevents browser disk persistence so
|
|
13
|
-
* a shared workstation doesn't expose draft pages.
|
|
33
|
+
* - {@link PREVIEW_CACHE_HEADERS}, overriding whatever the renderer emitted.
|
|
34
|
+
* `vary` is appended once, so the site's own `Vary` survives.
|
|
14
35
|
* - `content-security-policy: frame-ancestors 'none'` — appended (not set)
|
|
15
36
|
* so it stacks with any CSP the site's own rendered page carries
|
|
16
37
|
* (browsers enforce the intersection of comma-joined policies). This
|
|
@@ -24,7 +45,14 @@
|
|
|
24
45
|
export function applyPreviewHeaders(response: Response): Response {
|
|
25
46
|
const headers = new Headers(response.headers);
|
|
26
47
|
headers.set('x-robots-tag', 'noindex');
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
48
|
+
for (const name of ['cache-control', 'cdn-cache-control', 'vercel-cdn-cache-control', 'referrer-policy'] as const) {
|
|
49
|
+
headers.set(name, PREVIEW_CACHE_HEADERS[name]);
|
|
50
|
+
}
|
|
51
|
+
// Appended, so the site's own Vary and CSP survive; once, because the dispatcher wraps what the server wrapped.
|
|
52
|
+
const varies = (headers.get('vary') ?? '').split(',').map((token) => token.trim().toLowerCase());
|
|
53
|
+
if (!varies.includes('cookie')) headers.append('vary', PREVIEW_CACHE_HEADERS.vary);
|
|
54
|
+
if (!(headers.get('content-security-policy') ?? '').includes("frame-ancestors 'none'")) {
|
|
55
|
+
headers.append('content-security-policy', "frame-ancestors 'none'");
|
|
56
|
+
}
|
|
57
|
+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers });
|
|
30
58
|
}
|
|
@@ -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
|
+
}
|