@domandigital/create-site 0.11.2 → 0.11.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # @domandigital/create-site
2
2
 
3
+ ## 0.11.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 6ca7b22: Allow registered private staging domains after checking the live Cloudflare Access policy. Keep public Worker and version URLs disabled, require the canonical reviewer group, and check anonymous denial after upload.
8
+
9
+ Run native package managers directly while retaining Node for JavaScript launchers, so the preview build works with either pnpm installation.
10
+ - 745de2a: Support an existing staging environment behind Access while retaining registered, signature-checked callback routes. Reject production settings and unregistered exceptions.
11
+
3
12
  ## 0.11.2
4
13
 
5
14
  ### Patch Changes
package/README.md CHANGED
@@ -87,10 +87,34 @@ fixed layers over half the height; at 1440 and 1920, on body lines over 80
87
87
  characters. `measure.baseline` lists known failures so they stay visible.
88
88
  `pnpm deploy:preview` is the only deploy: it sets `PUBLIC_PREVIEW` itself,
89
89
  builds, measures with noindex required, and deploys a preview to Cloudflare;
90
- it refuses a route, a custom domain or `--prod`. So a site made
90
+ it refuses `--prod` and public custom domains. A private custom staging
91
+ address is allowed only when the exact hostname and Worker are registered
92
+ in the merged DD Access registry, the live Access policy allows only the
93
+ registered DD reviewers for 24 hours, and both Worker preview URLs are
94
+ disabled. So a site made
91
95
  with create-site cannot build until its programme exists and Stages 05 and 06
92
96
  are done, and cannot reach a URL unmeasured.
93
97
 
98
+ For private staging, register the gate with `dd-access-gate` first and apply
99
+ it before the first upload. Set `preview.protected` in `site.programme.json`
100
+ with `gateKey`, `workerName`, `hostname`, `accountId`, `appName`, `teamDomain`,
101
+ `reviewerGroupId` and `probePaths` (the root, a real page and a real asset).
102
+ The hostname must start with `staging.`. The Wrangler JSON or JSONC config
103
+ must name that exact Worker and account, set `workers_dev: false` and
104
+ `preview_urls: false`, and contain only one route:
105
+ `{ "pattern": "staging.example.com", "custom_domain": true }`.
106
+ Named Wrangler environments are refused for this path.
107
+
108
+ The guard reads `config/access-gates.json` from `origin/main` in
109
+ `~/GitHub/dd-agent-kit`, so another session's local kit edits cannot change
110
+ the approved policy. Fetch that repo when adopting a new gate. Missing
111
+ registry data or a failed Cloudflare read stops deployment. The guard uses
112
+ the existing `cf` login, checks every page of Access apps, groups and identity
113
+ providers, refuses overlapping apps and bypass rules, and repeats the check
114
+ immediately before uploading. After upload it checks the live Worker URL
115
+ settings and anonymous redirects for all probe paths. A failed final check
116
+ means the upload happened but the preview is not ready to share.
117
+
94
118
  The gate scripts are house files, identical on every site and reported by
95
119
  `--check` when they drift. Everything that differs between sites is in
96
120
  `site.programme.json`.
package/dist/cli.js CHANGED
@@ -437,7 +437,8 @@ var GATES = [
437
437
  "null-check.mjs",
438
438
  "mobile-first.mjs",
439
439
  "measure.mjs",
440
- "deploy-preview.mjs"
440
+ "deploy-preview.mjs",
441
+ "protected-preview.mjs"
441
442
  ];
442
443
  function layoutFor(project) {
443
444
  const base = project.srcBase;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@domandigital/create-site",
3
- "version": "0.11.2",
3
+ "version": "0.11.3",
4
4
  "private": false,
5
5
  "description": "The first thing that runs on a new Doman Digital client site: installs the house packages and writes the per-site files they read (the facts file, route policy, backlink register, redirects, JSON-LD, the designer credit, house docs and the SEO checks), so every build starts on the same foundation and stays upgradeable by bumping packages.",
6
6
  "license": "Apache-2.0",
@@ -41,9 +41,9 @@
41
41
  "tsup": "^8.3.5",
42
42
  "typescript": "^5.6.3",
43
43
  "vitest": "^4.0.0",
44
- "@domandigital/craft": "^0.24.0",
45
- "@domandigital/graph": "^0.7.1",
46
- "@domandigital/seo": "^0.3.2"
44
+ "@domandigital/craft": "^0.24.3",
45
+ "@domandigital/seo": "^0.3.2",
46
+ "@domandigital/graph": "^0.7.1"
47
47
  },
48
48
  "publishConfig": {
49
49
  "access": "public",
@@ -104,4 +104,4 @@ pricing modules and writes the facts the redesign renders.
104
104
  | `nullCheck` | `harvest` (a path, `~/` allowed) and `justified` (phrase to reason) |
105
105
  | `facts` | `importer`: the site's importer script, or null |
106
106
  | `mobileFirst` | `exceptions`: the files allowed a `max-width` query or `max-*:` variant, each `{ "file": "src/styles/print.css", "reason": "..." }` |
107
- | `preview` | `host`: `cloudflare`, or null to find it from the config |
107
+ | `preview` | `host`: `cloudflare`, or null to find it from the config. Optional `protected`: an exact staging hostname and Worker registered in the merged DD Access registry; see create-site's private staging setup. The gate verifies the live reviewer policy before upload and anonymous denial afterwards |
@@ -5,7 +5,9 @@
5
5
  // 390 with --preview (noindex required); and only then deploys, preview only:
6
6
  //
7
7
  // Cloudflare: wrangler deploy, refused while the wrangler config carries a
8
- // route, a custom domain or workers_dev: false.
8
+ // route, a custom domain or workers_dev: false unless the exact staging
9
+ // hostname is protected by a verified Cloudflare Access app. Public Worker
10
+ // and version URLs must be disabled for that protected staging route.
9
11
  //
10
12
  // The host is preview.host in site.programme.json, or found from the
11
13
  // wrangler config. Going live is a separate,
@@ -19,11 +21,13 @@ import { spawnSync } from "node:child_process";
19
21
  import { existsSync, readFileSync } from "node:fs";
20
22
  import { join } from "node:path";
21
23
  import { programme, root, stop } from "./programme.mjs";
24
+ import { stagingConfig, probeCallbacks, parseJsonc, validateProtectedConfig, assertAccessProtection, assertWorkerProtection, probeProtectedPreview } from "./protected-preview.mjs";
22
25
 
23
26
  const GATE = "deploy-preview";
24
27
  if (process.argv.includes("--prod")) stop(GATE, "09", "this script never deploys to production. Going live is the Stage 09 release decision.");
25
28
  const dryRun = process.argv.includes("--dry-run");
26
29
  const { preview = {} } = programme();
30
+ if (preview.environment && !preview.protected) stop(GATE, "06", "named environments require protected staging settings");
27
31
  const env = { ...process.env, PUBLIC_PREVIEW: "1", NEXT_PUBLIC_PREVIEW: "1" };
28
32
  const bin = (name) => join(root, "node_modules", ".bin", name);
29
33
 
@@ -33,18 +37,29 @@ if (!host) stop(GATE, "06", "no preview host. Set preview.host in site.programme
33
37
 
34
38
  if (host === "cloudflare") {
35
39
  if (!wranglerFile) stop(GATE, "06", "preview.host is cloudflare but there is no wrangler config.");
40
+ if (preview.protected) {
41
+ try {
42
+ if (wranglerFile.endsWith(".toml")) throw new Error("protected staging requires wrangler.json or wrangler.jsonc");
43
+ validateProtectedConfig(stagingConfig(parseJsonc(readFileSync(join(root, wranglerFile), "utf8")), preview.environment), preview.protected);
44
+ assertAccessProtection(preview.protected);
45
+ } catch (error) { stop(GATE, "06", error.message); }
46
+ } else {
36
47
  // Comments out, so a commented-out route still counts as no route.
37
48
  const text = readFileSync(join(root, wranglerFile), "utf8").replace(/^\s*(\/\/|#).*$/gm, "").replace(/\/\*[\s\S]*?\*\//g, "");
38
49
  if (/["']?\broutes?\b["']?\s*[:=]/.test(text)) stop(GATE, "06", `${wranglerFile} carries a route. A preview has none: the live domain is attached only by the Stage 09 release.`);
39
50
  if (/custom_domain/.test(text)) stop(GATE, "06", `${wranglerFile} carries a custom domain. A preview has none.`);
40
51
  if (/workers_dev["']?\s*[:=]\s*false/.test(text)) stop(GATE, "06", `${wranglerFile} sets workers_dev to false, so a preview would have no address.`);
52
+ }
41
53
  } else {
42
54
  stop(GATE, "06", `preview.host is ${host}; this script knows cloudflare.`);
43
55
  }
44
56
 
45
57
  // The package manager that ran this script, so the build is the one `build` names.
46
58
  const pm = process.env.npm_execpath;
47
- const build = pm ? spawnSync(process.execPath, [pm, "run", "build"], { cwd: root, env, stdio: "inherit" }) : spawnSync("npm", ["run", "build"], { cwd: root, env, stdio: "inherit" });
59
+ const isJsEntry = pm && /\.[cm]?js$/i.test(pm);
60
+ const command = isJsEntry ? process.execPath : (pm || "npm");
61
+ const args = isJsEntry ? [pm, "run", "build"] : ["run", "build"];
62
+ const build = spawnSync(command, args, { cwd: root, env, stdio: "inherit" });
48
63
  if (build.status !== 0) stop(GATE, "06", "the preview build failed. Nothing was deployed.");
49
64
 
50
65
  const measured = spawnSync(process.execPath, [join(root, "scripts", "gates", "measure.mjs"), "--serve", "--preview"], { cwd: root, env, stdio: "inherit" });
@@ -54,6 +69,22 @@ if (dryRun) {
54
69
  console.log(`${GATE}: built and measured; --dry-run, so nothing was deployed.`);
55
70
  process.exit(0);
56
71
  }
57
- const deploy = spawnSync(existsSync(bin("wrangler")) ? bin("wrangler") : "npx", existsSync(bin("wrangler")) ? ["deploy"] : ["wrangler", "deploy"], { cwd: root, env, stdio: "inherit" });
72
+ // Re-read immediately before uploading: the build and measurement can take time.
73
+ if (preview.protected) {
74
+ try {
75
+ validateProtectedConfig(stagingConfig(parseJsonc(readFileSync(join(root, wranglerFile), "utf8")), preview.environment), preview.protected);
76
+ assertAccessProtection(preview.protected);
77
+ } catch (error) { stop(GATE, "06", error.message); }
78
+ }
79
+ const environmentArgs = preview.environment ? ["--env", preview.environment] : [];
80
+ const deploy = spawnSync(existsSync(bin("wrangler")) ? bin("wrangler") : "npx", existsSync(bin("wrangler")) ? ["deploy", ...environmentArgs] : ["wrangler", "deploy", ...environmentArgs], { cwd: root, env, stdio: "inherit" });
58
81
  if (deploy.status !== 0) stop(GATE, "06", `the ${host} deploy failed.`);
82
+ if (preview.protected) {
83
+ try {
84
+ assertAccessProtection(preview.protected);
85
+ assertWorkerProtection(preview.protected);
86
+ await probeProtectedPreview(preview.protected);
87
+ await probeCallbacks(preview.protected);
88
+ } catch (error) { stop(GATE, "06", `${error.message}. Upload completed but protection verification failed; this preview is not ready to share.`); }
89
+ }
59
90
  console.log(`${GATE}: measured and deployed to a ${host} preview. The live site is untouched.`);
@@ -0,0 +1,203 @@
1
+ // Private custom staging is allowed only after the live Access rules match.
2
+ // This module makes no Cloudflare changes and never reads credentials itself.
3
+ import { spawnSync } from "node:child_process";
4
+ import { homedir } from "node:os";
5
+ import { join } from "node:path";
6
+
7
+ const fail = (message) => { throw new Error(`protected preview: ${message}`); };
8
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
9
+ const empty = (value) => value == null || (Array.isArray(value) && value.length === 0);
10
+
11
+ // Preserve strings (including URLs) while removing JSONC comments.
12
+ export function parseJsonc(source) {
13
+ let text = "", string = false, escaped = false;
14
+ for (let i = 0; i < source.length; i++) {
15
+ const c = source[i], next = source[i + 1];
16
+ if (string) {
17
+ text += c;
18
+ if (escaped) escaped = false;
19
+ else if (c === "\\") escaped = true;
20
+ else if (c === '"') string = false;
21
+ } else if (c === '"') { string = true; text += c; }
22
+ else if (c === "/" && next === "/") {
23
+ while (i + 1 < source.length && source[i + 1] !== "\n") i++;
24
+ text += " ";
25
+ } else if (c === "/" && next === "*") {
26
+ const end = source.indexOf("*/", i + 2);
27
+ if (end < 0) fail("unterminated JSONC comment");
28
+ i = end + 1; text += " ";
29
+ } else if (c === ",") {
30
+ // Comments are removed first; trailing commas are handled below.
31
+ text += c;
32
+ } else text += c;
33
+ }
34
+ let clean = ""; string = false; escaped = false;
35
+ for (let i = 0; i < text.length; i++) {
36
+ const c = text[i];
37
+ if (string) {
38
+ clean += c;
39
+ if (escaped) escaped = false;
40
+ else if (c === "\\") escaped = true;
41
+ else if (c === '"') string = false;
42
+ } else if (c === '"') { string = true; clean += c; }
43
+ else if (c !== "," || !/^[\s]*[}\]]/.test(text.slice(i + 1))) clean += c;
44
+ }
45
+ return JSON.parse(clean);
46
+ }
47
+
48
+ // Select only a named staging environment, retaining Wrangler's non-inherited bindings.
49
+ export function stagingConfig(config, environment) {
50
+ if (environment == null) return config;
51
+ if (environment !== "staging" || !config.env?.staging) fail("only an existing staging environment is supported");
52
+ const { env, ...base } = config;
53
+ const selected = env.staging;
54
+ for (const key of ["vars", "d1_databases", "kv_namespaces", "r2_buckets", "services", "queues", "durable_objects", "triggers"]) delete base[key];
55
+ if (selected.vars?.ENVIRONMENT !== "staging" || selected.vars?.REVIEW_INVITATIONS_ENABLED === "true" || selected.triggers?.crons?.length) fail("staging must disable production mode, invitations and scheduled jobs");
56
+ return { ...base, ...selected };
57
+ }
58
+
59
+ export function validateProtectedConfig(wrangler, protection) {
60
+ if (!protection || typeof protection !== "object") fail("missing Access settings");
61
+ const { hostname, accountId, appName, teamDomain, reviewerGroupId, probePaths } = protection;
62
+ if (!/^[a-z0-9-]+$/.test(protection.gateKey || "")) fail("a canonical Access gateKey is required");
63
+ if (typeof hostname !== "string" || !/^staging\.(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/.test(hostname)) fail("only an exact staging subdomain is allowed; never apex, www, wildcards or paths");
64
+ if (!/^[a-f0-9]{32}$/.test(accountId || "") || wrangler.account_id !== accountId) fail("account_id must match the Access account");
65
+ if (!appName || !/^[a-z0-9-]+\.cloudflareaccess\.com$/.test(teamDomain || "") || !/^[a-f0-9-]{36}$/.test(reviewerGroupId || "")) fail("invalid Access application, team or reviewer group");
66
+ if (wrangler.workers_dev !== false || wrangler.preview_urls !== false) fail("workers_dev and preview_urls must both be false");
67
+ if (wrangler.route != null || !same(wrangler.routes, [{ pattern: hostname, custom_domain: true }])) fail("exactly one matching custom staging route is required");
68
+ if (wrangler.env && Object.keys(wrangler.env).length) fail("named Wrangler environments are not supported for protected previews");
69
+ if (!/^[a-z0-9-]+$/.test(wrangler.name || "") || wrangler.name !== protection.workerName) fail("the exact registered staging Worker name is required");
70
+ if (!Array.isArray(probePaths) || probePaths.length < 3 || !probePaths.includes("/") || probePaths.some(p => typeof p !== "string" || !/^\/(?!\/)[A-Za-z0-9_./-]*$/.test(p) || p.includes(".."))) fail("probePaths must include the root, a real page and a real asset, with local absolute paths only");
71
+ if (!probePaths.some(p => /\.[a-z0-9]+$/i.test(p)) || !probePaths.some(p => p !== "/" && !/\.[a-z0-9]+$/i.test(p))) fail("probePaths need both a page and an asset");
72
+ return protection;
73
+ }
74
+
75
+ export function canonicalReviewers(protection, registry) {
76
+ const gate = registry.gates?.[protection.gateKey];
77
+ if (!gate || !gate.worker || gate.worker !== protection.workerName || gate.account !== protection.accountId || gate.app !== protection.appName || `${gate.team}.cloudflareaccess.com` !== protection.teamDomain || !same(gate.hosts, [protection.hostname]) || gate.session !== "24h") fail("settings do not match the merged canonical Access registry");
78
+ const groups = [...new Set([...(registry.default_groups || []), ...(gate.groups || [])])];
79
+ if (!same(groups, ["Doman Digital reviewers"]) || !empty(gate.allow) || !empty(gate.service_tokens)) fail("the registered gate must allow only the DD reviewer group");
80
+ const callbacks = gate.bypass || [];
81
+ if (callbacks.some(b => !/^\/api\/(?:webhooks\/[a-z0-9-]+|revalidate)$/.test(b.path || "") || !b.why || !b.authProbe || b.authProbe.method !== "POST" || ![400, 401, 403].includes(b.authProbe.status))) fail("callback exceptions require exact API paths and an unsigned POST rejection probe");
82
+ const reviewers = registry.groups?.[groups[0]];
83
+ if (!Array.isArray(reviewers) || !reviewers.length || reviewers.some(email => typeof email !== "string" || !email.endsWith("@domandigital.co.uk"))) fail("the canonical reviewer group is missing or invalid");
84
+ return [...reviewers].sort();
85
+ }
86
+
87
+ export function readCanonicalRegistry(run = spawnSync) {
88
+ // origin/main is the merged source, unaffected by another session's dirty
89
+ // kit checkout. Fetch that canonical repo before adopting a new gate.
90
+ const result = run("git", ["-C", join(homedir(), "GitHub", "dd-agent-kit"), "show", "origin/main:config/access-gates.json"], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024 });
91
+ if (result.status !== 0) fail("the merged canonical Access registry is unavailable");
92
+ return JSON.parse(result.stdout);
93
+ }
94
+
95
+ function publicDestinations(app) {
96
+ return [app.domain, ...(app.destinations || []).filter(d => d.type === "public").map(d => d.uri)].filter(Boolean);
97
+ }
98
+
99
+ function matchesHost(destination, hostname) {
100
+ const host = destination.split("/")[0].toLowerCase();
101
+ const escaped = host.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
102
+ return new RegExp(`^${escaped}$`).test(hostname);
103
+ }
104
+
105
+ export function validateAccessState(protection, state, registry) {
106
+ const reviewers = canonicalReviewers(protection, registry);
107
+ const { hostname, appName, reviewerGroupId, teamDomain } = protection;
108
+ if (state.organization.auth_domain !== teamDomain) fail("the live Zero Trust team does not match");
109
+ const apps = state.applications.filter(app => publicDestinations(app).some(d => matchesHost(d, hostname)));
110
+ const callbacks = registry.gates[protection.gateKey].bypass || [];
111
+ if (apps.length !== 1 + callbacks.length) fail("unexpected overlapping or path-specific Access app");
112
+ for (const callback of callbacks) {
113
+ const domain = `${hostname}${callback.path}`;
114
+ const match = apps.filter(a => a.domain === domain);
115
+ const bypass = match[0];
116
+ if (match.length !== 1 || bypass.type !== "self_hosted" || !same(bypass.destinations, [{type: "public", uri: domain}]) || bypass.policies?.length !== 1) fail("callback Access app does not match the canonical exact path");
117
+ const policy = bypass.policies[0];
118
+ if (policy.decision !== "bypass" || !same(policy.include, [{everyone: {}}]) || !empty(policy.exclude) || !empty(policy.require)) fail("callback must carry only its registered bypass policy");
119
+ }
120
+ const rootApps = apps.filter(a => a.domain === hostname);
121
+ if (rootApps.length !== 1) fail("exactly one root reviewer app is required");
122
+ const app = rootApps[0];
123
+ if (app.name !== appName || app.type !== "self_hosted" || app.domain !== hostname || !same(app.destinations, [{ type: "public", uri: hostname }]) || app.session_duration !== "24h") fail("live Access app does not match the exact staging hostname and 24h session");
124
+ if (!Array.isArray(app.policies) || app.policies.length !== 1) fail("exactly one reviewer allow policy is required");
125
+ const policy = app.policies[0];
126
+ if (policy.decision !== "allow" || !same(policy.include, [{ group: { id: reviewerGroupId } }]) || !empty(policy.exclude) || !empty(policy.require) || policy.session_duration !== "24h") fail("live policy must allow only the reviewer group for 24h; no bypass or service token");
127
+ const group = state.groups.find(g => g.id === reviewerGroupId);
128
+ const expected = reviewers.map(email => ({ email: { email } }));
129
+ if (!group || group.name !== "Doman Digital reviewers" || !empty(group.require) || !empty(group.exclude) || !Array.isArray(group.include) || !same([...group.include].sort((a, b) => JSON.stringify(a).localeCompare(JSON.stringify(b))), expected)) fail("the live reviewer group differs from the canonical named DD reviewers");
130
+ const providers = state.identityProviders.filter(p => app.allowed_idps?.includes(p.id));
131
+ if (app.allowed_idps?.length !== 2 || providers.length !== 2 || !same(providers.map(p => p.type).sort(), ["cloudflare", "onetimepin"])) fail("only the existing Cloudflare and one-time PIN providers are allowed");
132
+ return { appId: app.id, hostname, teamDomain, session: "24h", reviewers: reviewers.length };
133
+ }
134
+
135
+ export function readAccessState(protection, run = spawnSync) {
136
+ const read = (args) => {
137
+ const result = run("cf", ["zero-trust", ...args], { env: { ...process.env, CLOUDFLARE_ACCOUNT_ID: protection.accountId }, encoding: "utf8", timeout: 60000, maxBuffer: 8 * 1024 * 1024 });
138
+ if (result.status !== 0) fail(`Cloudflare read failed (${args.join(" ")}); nothing may be deployed`);
139
+ const data = JSON.parse(result.stdout);
140
+ return data.result ?? data;
141
+ };
142
+ const list = (args) => {
143
+ const rows = [], seen = new Set();
144
+ for (let page = 1; page <= 100; page++) {
145
+ const batch = read([...args, "--page", String(page), "--per-page", "50"]);
146
+ if (!Array.isArray(batch)) fail("Cloudflare list response is not an array");
147
+ for (const row of batch) {
148
+ if (!row.id || seen.has(row.id)) fail("Cloudflare pagination repeated a row or omitted its id");
149
+ seen.add(row.id); rows.push(row);
150
+ }
151
+ if (batch.length < 50) return rows;
152
+ }
153
+ fail("Cloudflare pagination exceeded the safe limit; completeness is unknown");
154
+ };
155
+ return {
156
+ organization: read(["organization", "get"]),
157
+ applications: list(["access", "applications", "list"]),
158
+ groups: list(["access", "rule-groups", "list"]),
159
+ identityProviders: list(["identity-providers", "list"]),
160
+ };
161
+ }
162
+
163
+ export function assertAccessProtection(protection) {
164
+ const registry = readCanonicalRegistry();
165
+ canonicalReviewers(protection, registry);
166
+ const evidence = validateAccessState(protection, readAccessState(protection), registry);
167
+ console.log(`protected preview: live Access app ${evidence.appId} protects ${evidence.hostname}; 24h, ${evidence.reviewers} DD reviewers.`);
168
+ return evidence;
169
+ }
170
+
171
+ export function validateWorkerProtection(protection, worker) {
172
+ if (worker.name !== protection.workerName || worker.subdomain?.enabled !== false || worker.subdomain?.previews_enabled !== false) fail("the live Worker still exposes workers.dev or version preview URLs");
173
+ const domains = worker.references?.domains;
174
+ if (!Array.isArray(domains) || domains.some(domain => (domain.hostname ?? domain.domain ?? domain.name) !== protection.hostname)) fail("the live Worker has an unexpected custom domain, or domain readback is missing");
175
+ return worker.subdomain;
176
+ }
177
+
178
+ export function assertWorkerProtection(protection, run = spawnSync) {
179
+ const result = run("cf", ["workers", "get", protection.workerName], { env: { ...process.env, CLOUDFLARE_ACCOUNT_ID: protection.accountId }, encoding: "utf8", timeout: 60000, maxBuffer: 1024 * 1024 });
180
+ if (result.status !== 0) fail("cannot verify the deployed Worker's alternate URLs");
181
+ const data = JSON.parse(result.stdout);
182
+ const subdomain = validateWorkerProtection(protection, data.result ?? data);
183
+ console.log("protected preview: live workers.dev and version preview URLs are disabled.");
184
+ return subdomain;
185
+ }
186
+
187
+ export async function probeProtectedPreview(protection, fetcher = fetch) {
188
+ for (const path of protection.probePaths) {
189
+ const response = await fetcher(`https://${protection.hostname}${path}`, { redirect: "manual", signal: AbortSignal.timeout(20000), headers: { "Cache-Control": "no-cache" } });
190
+ let location;
191
+ try { location = new URL(response.headers.get("location")); } catch { fail(`anonymous ${path} did not redirect to Access`); }
192
+ if (response.status !== 302 || location.protocol !== "https:" || location.hostname !== protection.teamDomain || !location.pathname.startsWith("/cdn-cgi/access/login")) fail(`anonymous ${path} was not protected by the expected Access login`);
193
+ console.log(`protected preview: anonymous ${path} -> Access login (302).`);
194
+ }
195
+ }
196
+
197
+ export async function probeCallbacks(protection, registry = readCanonicalRegistry(), fetcher = fetch) {
198
+ canonicalReviewers(protection, registry);
199
+ for (const callback of registry.gates[protection.gateKey].bypass || []) {
200
+ const response = await fetcher(`https://${protection.hostname}${callback.path}`, {method: "POST", body: "{}", headers: {"Content-Type": "application/json"}, redirect: "manual", signal: AbortSignal.timeout(20000)});
201
+ if (response.status !== callback.authProbe.status) fail(`unsigned callback ${callback.path} did not reject with ${callback.authProbe.status}`);
202
+ }
203
+ }