@domandigital/create-site 0.11.2 → 0.12.0

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,30 @@
1
1
  # @domandigital/create-site
2
2
 
3
+ ## 0.12.0
4
+
5
+ ### Minor Changes
6
+
7
+ - e51ab59: A site cannot be started without passing its programme. A real run now calls `dd-programme gate` (Stage 05 accepted) and refuses, writing nothing, when it fails or when dd-programme is not installed. `--no-gate` (or `DD_CREATE_SITE_NO_GATE=1`, for the nightly starter job) skips it and the start label records the skip.
8
+
9
+ New `.dd/site-start.json` says how the site was started: `mode`, `programme`, the gate result and, for a handover, the reason and the visible pieces added. It describes the site; the proof is `create-site --check` passing.
10
+
11
+ New `--handover --reason "..." --programme DOM-123 [--with credit,consent,analytics,legal,press,resources]` starts an existing live site copied in as Astro. It adds the invisible layers only (facts, routes, redirects, JSON-LD, SEO tests, gates) and keeps the client's look and copy. In handover mode the build blocks on facts, reports the direction and mobile-first checks without stopping, and skips tokens, night contrast, the copy deck and the null check. A visible piece is added only when named in `--with`. `--check` keeps the mode from the label.
12
+
13
+ `site.programme.json` gains `mode`.
14
+
15
+ ### Patch Changes
16
+
17
+ - 0936ad3: The protected preview guard accepts the registered allow_outside_domain addresses: the live Access policy must be the reviewers group plus exactly those addresses, each with a reason. Any other address, bypass, service token or bare allow still fails.
18
+
19
+ ## 0.11.3
20
+
21
+ ### Patch Changes
22
+
23
+ - 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.
24
+
25
+ Run native package managers directly while retaining Node for JavaScript launchers, so the preview build works with either pnpm installation.
26
+ - 745de2a: Support an existing staging environment behind Access while retaining registered, signature-checked callback routes. Reject production settings and unregistered exceptions.
27
+
3
28
  ## 0.11.2
4
29
 
5
30
  ### Patch Changes
package/README.md CHANGED
@@ -87,14 +87,60 @@ 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`.
97
121
 
122
+ ## Starting is mandatory: the programme gate, the label and handover
123
+
124
+ A real run first asks `dd-programme gate DOM-123 --stage 05`, so nothing is scaffolded before the
125
+ programme has accepted Stage 05. If the gate fails, or `dd-programme` is not installed, the run is refused and writes
126
+ nothing. `--no-gate` (or `DD_CREATE_SITE_NO_GATE=1`, which the nightly starter job uses) skips it; the label records the skip.
127
+
128
+ `.dd/site-start.json` says how the site was started: `mode` (`programme` or `handover`), the programme issue, the
129
+ gate result, and for a handover the reason and the visible pieces added. It describes; it is not the proof. The proof is
130
+ `create-site --check` passing, which the estate sweep in dd-repo-registry runs against every site, in any GitHub account.
131
+
132
+ A site copied in from a client's live build is started with:
133
+
134
+ ```bash
135
+ create-site --handover --reason "client's existing Astro site, copied in" --programme DOM-123
136
+ ```
137
+
138
+ It adds the invisible layers only: the facts file, routes, redirects, JSON-LD, the SEO tests and the gates. It keeps the client's
139
+ look and copy. The build then blocks on `facts.mjs`, reports `check-direction.mjs` and `mobile-first.mjs` without stopping, and skips tokens,
140
+ night contrast, the copy deck and the null check. Nothing a visitor can see is added until the founder says yes for that site; then
141
+ re-run with `--with credit,consent,analytics,legal,press,resources` for the pieces agreed. `--check` reads the mode from the label.
142
+ Capture the live site's claims with `dd-claims` before anything else changes.
143
+
98
144
  ## What it never does
99
145
 
100
146
  - Write outside the project, or anything at all when it refuses.
@@ -115,7 +161,7 @@ The gate scripts are house files, identical on every site and reported by
115
161
  create-site [dir] [--client <legal name>] [--trading-name <name>]
116
162
  [--site-url <https://...>] [--sector trades|beauty|clinics|professional]
117
163
  [--description "<one or two sentences>"] [--programme DOM-123]
118
- [--answers <file.json>]
164
+ [--answers <file.json>] [--handover --reason "<why>" [--with <pieces>]] [--no-gate]
119
165
  [--visibility private|public] [--dry-run] [--check] [--force]
120
166
  [--skip-install] [--yes] [--help] [--version]
121
167
  ```
package/dist/cli.js CHANGED
@@ -6,11 +6,11 @@ var __export = (target, all) => {
6
6
  };
7
7
 
8
8
  // src/cli.ts
9
- import { execFileSync } from "child_process";
9
+ import { execFileSync, spawnSync } from "child_process";
10
10
  import { createInterface } from "readline/promises";
11
11
 
12
12
  // src/run.ts
13
- import { readFileSync as readFileSync6 } from "fs";
13
+ import { readFileSync as readFileSync7 } from "fs";
14
14
  import { resolve as resolve2 } from "path";
15
15
 
16
16
  // src/answers.ts
@@ -269,6 +269,29 @@ function applyPlan(plan, clientName, exec) {
269
269
 
270
270
  // src/args.ts
271
271
  import { parseArgs } from "util";
272
+
273
+ // src/handover.ts
274
+ var VISIBLE_PIECES = ["credit", "consent", "analytics", "legal", "press", "resources"];
275
+ var PIECE_FILES = {
276
+ credit: /\/DesignerCredit\.(tsx|astro)$/,
277
+ consent: /\/CookieBanner\.(tsx|astro)$/,
278
+ analytics: /\/WebAnalytics\.(tsx|astro)$/,
279
+ legal: /\/(privacy|cookies|terms|accessibility)(\/page\.tsx|\.astro)$/,
280
+ press: /\/press(\/page\.tsx|\.astro)$/,
281
+ resources: /\/resources(\/page\.tsx|\/index\.astro)$/
282
+ };
283
+ function pieceOf(template) {
284
+ const path = `/${template}`;
285
+ for (const piece of VISIBLE_PIECES) if (PIECE_FILES[piece].test(path)) return piece;
286
+ return null;
287
+ }
288
+ function installs(template, handover) {
289
+ if (!handover) return true;
290
+ const piece = pieceOf(template);
291
+ return piece === null || handover.with.includes(piece);
292
+ }
293
+
294
+ // src/args.ts
272
295
  var USAGE = `create-site: start a Doman Digital client site on the house foundation.
273
296
 
274
297
  Run it inside a fresh Next.js (App Router) or Astro TypeScript project:
@@ -280,10 +303,23 @@ Usage
280
303
  [--site-url <https://...>] [--sector trades|beauty|clinics|professional]
281
304
  [--description "<one or two sentences>"] [--programme DOM-123]
282
305
  [--answers <file.json>] [--visibility private|public]
283
- [--dry-run] [--check] [--force] [--skip-install] [--yes] [--help] [--version]
306
+ [--handover --reason "<why>" [--with credit,consent,analytics,legal,press,resources]]
307
+ [--no-gate] [--dry-run] [--check] [--force] [--skip-install] [--yes] [--help] [--version]
284
308
 
285
309
  --programme The site's programme issue in Linear, opened from the Site programme
286
310
  template. The build refuses to run until site.programme.json names it.
311
+ A real run first passes the programme gate: Stage 05 accepted
312
+ (dd-programme gate DOM-123 --stage 05), so nothing is scaffolded early.
313
+ --handover Start an existing live site that is being copied in (an Astro handover).
314
+ Needs --programme (a Site handover programme) and --reason. It adds the
315
+ invisible layers only (facts, routes, redirects, JSON-LD, SEO tests, gates
316
+ in advisory mode) and keeps the client's look and copy. Anything a visitor
317
+ can see is added only when named in --with, one site at a time.
318
+ --with A handover's visible pieces: credit (Website by Doman Digital), consent
319
+ (cookie banner), analytics (Cloudflare Web Analytics), legal (privacy,
320
+ cookies, terms, accessibility), press, resources.
321
+ --no-gate Skip the programme gate (the nightly starter check and tests). The start
322
+ label records it, and the estate sweep does not count the site as started.
287
323
  --dry-run Print the plan and stop. Writes nothing, runs nothing.
288
324
  --check Like --dry-run, never prompts, and exits 3 when there is work to do,
289
325
  a house file that differs from its template included. For CI.
@@ -310,6 +346,10 @@ function parseOptions(argv) {
310
346
  description: { type: "string" },
311
347
  programme: { type: "string" },
312
348
  answers: { type: "string" },
349
+ handover: { type: "boolean", default: false },
350
+ reason: { type: "string" },
351
+ with: { type: "string" },
352
+ "no-gate": { type: "boolean", default: false },
313
353
  "dry-run": { type: "boolean", default: false },
314
354
  check: { type: "boolean", default: false },
315
355
  visibility: { type: "string", default: "private" },
@@ -322,6 +362,11 @@ function parseOptions(argv) {
322
362
  });
323
363
  if (positionals.length > 1) return `one directory at most, got ${positionals.length}`;
324
364
  if (values.visibility !== "private" && values.visibility !== "public") return `--visibility is private or public, not ${values.visibility}`;
365
+ const withList = values.with ? values.with.split(",").map((w) => w.trim()).filter(Boolean) : [];
366
+ const bad = withList.filter((w) => !VISIBLE_PIECES.includes(w));
367
+ if (bad.length) return `--with takes ${VISIBLE_PIECES.join(", ")}, not ${bad.join(", ")}`;
368
+ if (withList.length && !values.handover) return "--with is for --handover: a new build adds every piece";
369
+ if (values.reason && !values.handover) return "--reason is for --handover";
325
370
  return {
326
371
  dir: positionals[0],
327
372
  client: values.client,
@@ -331,6 +376,10 @@ function parseOptions(argv) {
331
376
  description: values.description,
332
377
  programme: values.programme,
333
378
  answers: values.answers,
379
+ handover: values.handover ?? false,
380
+ reason: values.reason,
381
+ with: [...new Set(withList)],
382
+ noGate: values["no-gate"] ?? false,
334
383
  dryRun: values["dry-run"] ?? false,
335
384
  check: values.check ?? false,
336
385
  visibility: values.visibility,
@@ -421,9 +470,71 @@ function detectProject(root, userAgent) {
421
470
  };
422
471
  }
423
472
 
473
+ // src/label.ts
474
+ import { existsSync as existsSync3, readFileSync as readFileSync5 } from "fs";
475
+ import { join as join3 } from "path";
476
+
477
+ // src/templates.ts
478
+ import { readFileSync as readFileSync4 } from "fs";
479
+ import { dirname as dirname2, posix, relative } from "path";
480
+ import { fileURLToPath } from "url";
481
+ var TEMPLATE_ROOT = fileURLToPath(new URL("../templates/", import.meta.url));
482
+ function readTemplate(path) {
483
+ return readFileSync4(`${TEMPLATE_ROOT}${path}`, "utf8");
484
+ }
485
+ var SITE_IMPORT = /(["'])~site\/([^"']+)\1/g;
486
+ function rewriteSiteImports(text2, dest, siteKeys) {
487
+ return text2.replace(SITE_IMPORT, (_match, quote, key) => {
488
+ const target = siteKeys[key];
489
+ if (!target) throw new Error(`template for ${dest} imports ~site/${key}, which this project layout does not provide`);
490
+ const fromDir = dirname2(dest);
491
+ let spec = relative(fromDir, target).split("\\").join(posix.sep).replace(/\.tsx?$/, "");
492
+ if (!spec.startsWith(".")) spec = `./${spec}`;
493
+ return `${quote}${spec}${quote}`;
494
+ });
495
+ }
496
+
497
+ // src/label.ts
498
+ var LABEL_PATH = ".dd/site-start.json";
499
+ var TOOL_NAME = "@domandigital/create-site";
500
+ function toolVersion() {
501
+ return JSON.parse(readFileSync5(`${TEMPLATE_ROOT}../package.json`, "utf8")).version;
502
+ }
503
+ function renderLabel(start, programme, today) {
504
+ const label = {
505
+ $comment: "How this site was started. A label only: the proof is `create-site --check` passing. Written by @domandigital/create-site; never replaced.",
506
+ tool: TOOL_NAME,
507
+ version: start.version,
508
+ mode: start.mode,
509
+ programme,
510
+ ...start.stage05Gate === void 0 ? {} : { stage05Gate: start.stage05Gate },
511
+ ...start.handoverGate === void 0 ? {} : { handoverGate: start.handoverGate },
512
+ ...start.mode === "handover" ? { reason: start.reason ?? null, with: start.with } : {},
513
+ startedAt: today
514
+ };
515
+ return `${JSON.stringify(label, null, 2)}
516
+ `;
517
+ }
518
+ function readLabel(root) {
519
+ const path = join3(root, LABEL_PATH);
520
+ if (!existsSync3(path)) return null;
521
+ try {
522
+ const raw = JSON.parse(readFileSync5(path, "utf8"));
523
+ const mode = raw.mode === "handover" || raw.mode === "programme" ? raw.mode : void 0;
524
+ return {
525
+ mode,
526
+ reason: typeof raw.reason === "string" ? raw.reason : void 0,
527
+ with: Array.isArray(raw.with) ? raw.with.filter((w) => typeof w === "string") : [],
528
+ programme: typeof raw.programme === "string" ? raw.programme : null
529
+ };
530
+ } catch {
531
+ return null;
532
+ }
533
+ }
534
+
424
535
  // src/plan.ts
425
- import { existsSync as existsSync5, readdirSync as readdirSync3, readFileSync as readFileSync5 } from "fs";
426
- import { join as join5 } from "path";
536
+ import { existsSync as existsSync6, readdirSync as readdirSync3, readFileSync as readFileSync6 } from "fs";
537
+ import { join as join6 } from "path";
427
538
 
428
539
  // src/adapters.ts
429
540
  var GATES = [
@@ -437,7 +548,8 @@ var GATES = [
437
548
  "null-check.mjs",
438
549
  "mobile-first.mjs",
439
550
  "measure.mjs",
440
- "deploy-preview.mjs"
551
+ "deploy-preview.mjs",
552
+ "protected-preview.mjs"
441
553
  ];
442
554
  function layoutFor(project) {
443
555
  const base = project.srcBase;
@@ -754,12 +866,13 @@ function renderRedirects() {
754
866
  return `${JSON.stringify({ $schema: "./node_modules/@domandigital/seo/redirects.schema.json", redirects: [] }, null, 2)}
755
867
  `;
756
868
  }
757
- function renderProgramme(a, project) {
869
+ function renderProgramme(a, project, mode = "programme") {
758
870
  const base = project.srcBase;
759
871
  const source = base ? [base.replace(/\/$/, "")] : ["app", "components", "lib", "content"];
760
872
  const host = a.stack.host === "cloudflare" ? a.stack.host : null;
761
873
  const programme = {
762
874
  $comment: "Read by scripts/gates/ before every build and preview deploy. docs/site-programme.md says what each key is for. Written by @domandigital/create-site; yours to edit, never overwritten.",
875
+ mode,
763
876
  issue: a.programme,
764
877
  registeredDirection: null,
765
878
  paths: {
@@ -1017,38 +1130,18 @@ function patchPnpmWorkspace(text2) {
1017
1130
  ${block}` : block;
1018
1131
  }
1019
1132
 
1020
- // src/templates.ts
1021
- import { readFileSync as readFileSync4 } from "fs";
1022
- import { dirname as dirname2, posix, relative } from "path";
1023
- import { fileURLToPath } from "url";
1024
- var TEMPLATE_ROOT = fileURLToPath(new URL("../templates/", import.meta.url));
1025
- function readTemplate(path) {
1026
- return readFileSync4(`${TEMPLATE_ROOT}${path}`, "utf8");
1027
- }
1028
- var SITE_IMPORT = /(["'])~site\/([^"']+)\1/g;
1029
- function rewriteSiteImports(text2, dest, siteKeys) {
1030
- return text2.replace(SITE_IMPORT, (_match, quote, key) => {
1031
- const target = siteKeys[key];
1032
- if (!target) throw new Error(`template for ${dest} imports ~site/${key}, which this project layout does not provide`);
1033
- const fromDir = dirname2(dest);
1034
- let spec = relative(fromDir, target).split("\\").join(posix.sep).replace(/\.tsx?$/, "");
1035
- if (!spec.startsWith(".")) spec = `./${spec}`;
1036
- return `${quote}${spec}${quote}`;
1037
- });
1038
- }
1039
-
1040
1133
  // templates/next/tests/seo/routes-on-disk.ts
1041
1134
  var routes_on_disk_exports = {};
1042
1135
  __export(routes_on_disk_exports, {
1043
1136
  dynamicRoutesOnDisk: () => dynamicRoutesOnDisk,
1044
1137
  routesOnDisk: () => routesOnDisk
1045
1138
  });
1046
- import { existsSync as existsSync3, readdirSync } from "fs";
1047
- import { join as join3 } from "path";
1139
+ import { existsSync as existsSync4, readdirSync } from "fs";
1140
+ import { join as join4 } from "path";
1048
1141
  var PAGE_FILE = /^page\.(tsx|ts|jsx|js|mdx|md)$/;
1049
1142
  var OPTIONAL_CATCH_ALL2 = /^\[\[\.\.\..+\]\]$/;
1050
1143
  function walk(root) {
1051
- const appDir = [join3(root, "app"), join3(root, "src", "app")].find((dir) => existsSync3(dir));
1144
+ const appDir = [join4(root, "app"), join4(root, "src", "app")].find((dir) => existsSync4(dir));
1052
1145
  const routes = /* @__PURE__ */ new Set();
1053
1146
  const dynamicRoutes = /* @__PURE__ */ new Set();
1054
1147
  if (!appDir) return { routes: [], dynamicRoutes: [] };
@@ -1058,7 +1151,7 @@ function walk(root) {
1058
1151
  if (entry.isDirectory()) {
1059
1152
  if (name.startsWith("_") || name.startsWith("@") || name.startsWith("(.")) continue;
1060
1153
  const isGroup = name.startsWith("(") && name.endsWith(")");
1061
- visit(join3(dir, name), isGroup ? segments : [...segments, name]);
1154
+ visit(join4(dir, name), isGroup ? segments : [...segments, name]);
1062
1155
  } else if (PAGE_FILE.test(name)) {
1063
1156
  const path = `/${segments.join("/")}`;
1064
1157
  const firstDynamic = segments.findIndex((s) => s.startsWith("["));
@@ -1087,21 +1180,21 @@ __export(routes_on_disk_exports2, {
1087
1180
  dynamicRoutesOnDisk: () => dynamicRoutesOnDisk2,
1088
1181
  routesOnDisk: () => routesOnDisk2
1089
1182
  });
1090
- import { existsSync as existsSync4, readdirSync as readdirSync2 } from "fs";
1091
- import { join as join4 } from "path";
1183
+ import { existsSync as existsSync5, readdirSync as readdirSync2 } from "fs";
1184
+ import { join as join5 } from "path";
1092
1185
  var PAGE_FILE2 = /^(.+)\.(astro|md|mdx|html)$/;
1093
1186
  var NOT_PAGES = /* @__PURE__ */ new Set(["404", "500"]);
1094
1187
  function walk2(root) {
1095
- const pagesDir = join4(root, "src", "pages");
1188
+ const pagesDir = join5(root, "src", "pages");
1096
1189
  const routes = /* @__PURE__ */ new Set();
1097
1190
  const dynamicRoutes = /* @__PURE__ */ new Set();
1098
- if (!existsSync4(pagesDir)) return { routes: [], dynamicRoutes: [] };
1191
+ if (!existsSync5(pagesDir)) return { routes: [], dynamicRoutes: [] };
1099
1192
  const visit = (dir, segments) => {
1100
1193
  for (const entry of readdirSync2(dir, { withFileTypes: true })) {
1101
1194
  const name = entry.name;
1102
1195
  if (name.startsWith("_")) continue;
1103
1196
  if (entry.isDirectory()) {
1104
- visit(join4(dir, name), [...segments, name]);
1197
+ visit(join5(dir, name), [...segments, name]);
1105
1198
  continue;
1106
1199
  }
1107
1200
  const match = PAGE_FILE2.exec(name);
@@ -1133,21 +1226,21 @@ var PM_ADD = {
1133
1226
  var HOUSE_IMPORT = "@docs/HOUSE.md";
1134
1227
  var specs = (deps) => Object.entries(deps).map(([name, range]) => `${name}@${range}`);
1135
1228
  function hasWorkflows(root) {
1136
- const dir = join5(root, ".github", "workflows");
1137
- return existsSync5(dir) && readdirSync3(dir).some((f) => /\.ya?ml$/.test(f));
1229
+ const dir = join6(root, ".github", "workflows");
1230
+ return existsSync6(dir) && readdirSync3(dir).some((f) => /\.ya?ml$/.test(f));
1138
1231
  }
1139
1232
  function programmeIssueIn(root) {
1140
1233
  try {
1141
- const issue = JSON.parse(readFileSync5(join5(root, "site.programme.json"), "utf8")).issue;
1234
+ const issue = JSON.parse(readFileSync6(join6(root, "site.programme.json"), "utf8")).issue;
1142
1235
  return typeof issue === "string" && issue ? issue : null;
1143
1236
  } catch {
1144
1237
  return null;
1145
1238
  }
1146
1239
  }
1147
1240
  function actionFor(root, path, contents, data, force) {
1148
- const abs = join5(root, path);
1149
- if (!existsSync5(abs)) return "create";
1150
- if (readFileSync5(abs, "utf8") === contents) return "unchanged";
1241
+ const abs = join6(root, path);
1242
+ if (!existsSync6(abs)) return "create";
1243
+ if (readFileSync6(abs, "utf8") === contents) return "unchanged";
1151
1244
  if (data) return "keep-data";
1152
1245
  return force ? "overwrite" : "skip-exists";
1153
1246
  }
@@ -1160,7 +1253,14 @@ function planScaffold(project, answers, options) {
1160
1253
  "hand docs/client-facts.entry.json to Doman Digital's client register, and fill every null in it first (the register's own check names them)."
1161
1254
  );
1162
1255
  const files = [];
1256
+ const start = options.start ?? { mode: "programme", with: [], version: "0.0.0" };
1257
+ const handover = start.mode === "handover" ? { with: start.with } : null;
1258
+ if (handover) {
1259
+ const left = VISIBLE_PIECES.filter((p) => !start.with.includes(p));
1260
+ if (left.length) notes.push(`handover: nothing a visitor can see was added (${left.join(", ")}). Each needs the founder's yes for this site, then --with <piece>.`);
1261
+ }
1163
1262
  for (const t of layout.templates) {
1263
+ if (!installs(t.template, handover)) continue;
1164
1264
  if (t.template.endsWith("config.test.ts") && !project.configFile) {
1165
1265
  notes.push(`no ${project.framework} config file, so tests/seo/config.test.ts was not written: ${MANUAL_INSTRUCTIONS[project.framework]}`);
1166
1266
  continue;
@@ -1179,7 +1279,8 @@ function planScaffold(project, answers, options) {
1179
1279
  { path: "docs/seo-launch-checklist.md", contents: renderChecklist(answers), data: true },
1180
1280
  { path: "docs/seo-baseline.md", contents: renderBaseline(answers, options.today), data: true },
1181
1281
  { path: "docs/client-facts.entry.json", contents: renderStackEntry(answers, project.framework, options.today), data: true },
1182
- { path: "site.programme.json", contents: renderProgramme(answers, project), data: true },
1282
+ { path: "site.programme.json", contents: renderProgramme(answers, project, start.mode), data: true },
1283
+ { path: LABEL_PATH, contents: renderLabel(start, answers.programme ?? programmeIssueIn(root), options.today), data: true },
1183
1284
  { path: "art-direction.sheets.json", contents: renderSheets(), data: true }
1184
1285
  );
1185
1286
  if (!answers.programme && !programmeIssueIn(root)) {
@@ -1187,7 +1288,7 @@ function planScaffold(project, answers, options) {
1187
1288
  }
1188
1289
  const workflowPath = ".github/workflows/seo-check.yml";
1189
1290
  const workflow = renderWorkflow(project, options.visibility ?? "private");
1190
- if (existsSync5(join5(root, workflowPath)) || workflow && !hasWorkflows(root)) {
1291
+ if (existsSync6(join6(root, workflowPath)) || workflow && !hasWorkflows(root)) {
1191
1292
  if (workflow) files.push({ path: workflowPath, contents: workflow, data: false });
1192
1293
  } else if (!workflow) {
1193
1294
  notes.push(`no CI workflow written for ${project.packageManager}: run seo:check in your CI`);
@@ -1227,25 +1328,25 @@ function planScaffold(project, answers, options) {
1227
1328
  }
1228
1329
  let config = null;
1229
1330
  if (project.configFile) {
1230
- const patched = patchConfig(project.framework, project.configFile, readFileSync5(join5(root, project.configFile), "utf8"));
1331
+ const patched = patchConfig(project.framework, project.configFile, readFileSync6(join6(root, project.configFile), "utf8"));
1231
1332
  if (patched.kind === "patched") config = { file: project.configFile, text: patched.text };
1232
1333
  if (patched.kind === "manual") notes.push(`${patched.reason}: ${MANUAL_INSTRUCTIONS[project.framework]}. tests/seo/config.test.ts fails until it does.`);
1233
1334
  }
1234
1335
  let pnpmWorkspace = null;
1235
1336
  if (project.packageManager === "pnpm") {
1236
- const path = join5(root, "pnpm-workspace.yaml");
1237
- const current = existsSync5(path) ? readFileSync5(path, "utf8") : null;
1337
+ const path = join6(root, "pnpm-workspace.yaml");
1338
+ const current = existsSync6(path) ? readFileSync6(path, "utf8") : null;
1238
1339
  const text2 = patchPnpmWorkspace(current);
1239
1340
  if (text2 !== null) pnpmWorkspace = { text: text2, created: current === null };
1240
1341
  }
1241
- const claudePath = join5(root, "CLAUDE.md");
1242
- const claudeText = existsSync5(claudePath) ? readFileSync5(claudePath, "utf8") : null;
1342
+ const claudePath = join6(root, "CLAUDE.md");
1343
+ const claudeText = existsSync6(claudePath) ? readFileSync6(claudePath, "utf8") : null;
1243
1344
  const claudeMd = claudeText === null ? { text: `${HOUSE_IMPORT}
1244
1345
  `, created: true } : claudeText.includes(HOUSE_IMPORT) ? null : { text: `${claudeText.trimEnd()}
1245
1346
  ${HOUSE_IMPORT}
1246
1347
  `, created: false };
1247
- const artDirection = existsSync5(join5(root, "art-direction.json"));
1248
- const craftInstalled = existsSync5(join5(root, "node_modules", "@domandigital", "craft", "package.json"));
1348
+ const artDirection = existsSync6(join6(root, "art-direction.json"));
1349
+ const craftInstalled = existsSync6(join6(root, "node_modules", "@domandigital", "craft", "package.json"));
1249
1350
  const craftInit = !artDirection && (craftInstalled || commands.length > 0);
1250
1351
  if (!artDirection && !craftInit) notes.push(`after installing, run: npx craft direction init --client ${JSON.stringify(answers.tradingName)}`);
1251
1352
  return {
@@ -1314,7 +1415,7 @@ ${USAGE}`);
1314
1415
  return 0;
1315
1416
  }
1316
1417
  if (options.version) {
1317
- io.out(JSON.parse(readFileSync6(`${TEMPLATE_ROOT}../package.json`, "utf8")).version);
1418
+ io.out(JSON.parse(readFileSync7(`${TEMPLATE_ROOT}../package.json`, "utf8")).version);
1318
1419
  return 0;
1319
1420
  }
1320
1421
  const root = resolve2(io.cwd, options.dir ?? ".");
@@ -1340,8 +1441,52 @@ ${USAGE}`);
1340
1441
  io.err(`create-site: ${answers}`);
1341
1442
  return 2;
1342
1443
  }
1444
+ const existing = readLabel(root);
1445
+ const handover = options.handover || existing?.mode === "handover";
1446
+ const reason = options.reason ?? existing?.reason;
1447
+ const withPieces = options.handover ? options.with : existing?.with ?? [];
1448
+ const programme = answers.programme ?? programmeIssueIn(root);
1449
+ const readOnly = options.check || options.dryRun;
1450
+ if (handover && !readOnly) {
1451
+ if (!reason || reason.trim().length < 10) {
1452
+ io.err('create-site: --handover needs --reason "<why this site is copied in, in a sentence>".');
1453
+ return 2;
1454
+ }
1455
+ if (!programme) {
1456
+ io.err("create-site: --handover needs --programme DOM-123, the Site handover programme in Linear.");
1457
+ return 2;
1458
+ }
1459
+ }
1460
+ let gateResult;
1461
+ if (!readOnly && !existing) {
1462
+ const kind = handover ? "handover" : "stage05";
1463
+ if (options.noGate || io.noGateEnv === "1") {
1464
+ gateResult = false;
1465
+ io.err(`create-site: --no-gate skips the programme gate. The start label records it, and the estate sweep does not count this site as started.`);
1466
+ } else if (!programme) {
1467
+ io.err("create-site: name the programme with --programme DOM-123. Nothing is scaffolded before the programme gate passes.");
1468
+ return 1;
1469
+ } else if (!io.gate) {
1470
+ io.err(`create-site: cannot run the programme gate here (dd-programme is not installed). Run it where dd-programme is, or pass --no-gate and accept that the site is not counted as started.`);
1471
+ return 1;
1472
+ } else {
1473
+ const result = await io.gate(programme, kind);
1474
+ if (!result.ok) {
1475
+ io.err(`create-site: the programme gate for ${programme} did not pass, so nothing was written.
1476
+ ${result.message}`);
1477
+ return 1;
1478
+ }
1479
+ gateResult = true;
1480
+ }
1481
+ }
1482
+ const start = {
1483
+ mode: handover ? "handover" : "programme",
1484
+ ...handover ? { reason: reason?.trim(), handoverGate: gateResult } : { stage05Gate: gateResult },
1485
+ with: withPieces.filter((w) => VISIBLE_PIECES.includes(w)),
1486
+ version: toolVersion()
1487
+ };
1343
1488
  const today = io.now().toISOString().slice(0, 10);
1344
- const plan = planScaffold(project, answers, { force: options.force, skipInstall: options.skipInstall, today, visibility: options.visibility });
1489
+ const plan = planScaffold(project, answers, { force: options.force, skipInstall: options.skipInstall, today, visibility: options.visibility, start });
1345
1490
  io.out(formatPlan(plan, answers.tradingName));
1346
1491
  if (options.check) {
1347
1492
  const work = pendingWork(plan);
@@ -1356,6 +1501,23 @@ ${work.map((w) => ` ${w}`).join("\n")}`);
1356
1501
  if (options.dryRun || !hasWork(plan)) return 0;
1357
1502
  const pending = applyPlan(plan, answers.tradingName, io.exec);
1358
1503
  const pm = project.packageManager === "npm" ? "npm run" : project.packageManager;
1504
+ if (handover) {
1505
+ io.out(
1506
+ [
1507
+ "",
1508
+ "Next (handover):",
1509
+ " 1. Fill in site.facts.ts from the live site: contact details, hours, accreditations, profiles. Unknown stays null.",
1510
+ " 2. Capture the live site's claims with dd-claims before anything else changes; keep every one.",
1511
+ " 3. Put <JsonLd graph={buildPageGraph(...)} /> on every page. That is invisible to visitors.",
1512
+ " 4. Redirects: every old URL that moved goes in redirects.json; run seo:check.",
1513
+ " 5. The build runs in handover mode: facts is blocking; the direction and mobile-first checks report only.",
1514
+ " Anything a visitor can see (credit, cookie banner, analytics, legal pages, /press, /resources) needs the founder's yes",
1515
+ " for this site, then re-run with --with <piece>.",
1516
+ ...pending.map((p) => ` Still to run: ${p}`)
1517
+ ].join("\n")
1518
+ );
1519
+ return 0;
1520
+ }
1359
1521
  io.out(
1360
1522
  [
1361
1523
  "",
@@ -1381,6 +1543,9 @@ process.stdout.on("error", (error) => {
1381
1543
  if (error.code === "EPIPE") process.exit(process.exitCode ?? 0);
1382
1544
  throw error;
1383
1545
  });
1546
+ function hasProgrammeTool() {
1547
+ return spawnSync("dd-programme", ["--help"], { stdio: "ignore" }).status === 0;
1548
+ }
1384
1549
  var interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
1385
1550
  var rl = interactive ? createInterface({ input: process.stdin, output: process.stdout }) : void 0;
1386
1551
  void run2(process.argv.slice(2), {
@@ -1395,7 +1560,13 @@ void run2(process.argv.slice(2), {
1395
1560
  execFileSync(cmd, args, { cwd, stdio: "inherit", shell: process.platform === "win32" && cmd !== process.execPath });
1396
1561
  },
1397
1562
  now: () => /* @__PURE__ */ new Date(),
1398
- userAgent: process.env.npm_config_user_agent
1563
+ gate: hasProgrammeTool() ? async (programme, kind) => {
1564
+ const args = kind === "handover" ? ["gate", programme, "--handover"] : ["gate", programme, "--stage", "05"];
1565
+ const result = spawnSync("dd-programme", args, { encoding: "utf8" });
1566
+ return { ok: result.status === 0, message: `${result.stdout ?? ""}${result.stderr ?? ""}`.trim() };
1567
+ } : void 0,
1568
+ userAgent: process.env.npm_config_user_agent,
1569
+ noGateEnv: process.env.DD_CREATE_SITE_NO_GATE
1399
1570
  }).then((code) => {
1400
1571
  process.exitCode = code;
1401
1572
  }).finally(() => rl?.close());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@domandigital/create-site",
3
- "version": "0.11.2",
3
+ "version": "0.12.0",
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,7 +41,7 @@
41
41
  "tsup": "^8.3.5",
42
42
  "typescript": "^5.6.3",
43
43
  "vitest": "^4.0.0",
44
- "@domandigital/craft": "^0.24.0",
44
+ "@domandigital/craft": "^0.24.3",
45
45
  "@domandigital/graph": "^0.7.1",
46
46
  "@domandigital/seo": "^0.3.2"
47
47
  },
@@ -93,6 +93,18 @@ the governed file holds. `apps/site/scripts/facts.ts` in Doman-Digital is the
93
93
  worked example: it imports `docs/brand-facts.json` and the marketing app's
94
94
  pricing modules and writes the facts the redesign renders.
95
95
 
96
+ ## Handover sites
97
+
98
+ A site copied in from a client's live build is started with `create-site --handover` and has
99
+ `"mode": "handover"` in `site.programme.json` and `.dd/site-start.json`. It keeps the client's look and
100
+ copy, so the build runs differently:
101
+
102
+ - `facts.mjs` still blocks the build.
103
+ - `check-direction.mjs` and `mobile-first.mjs` report and never stop it.
104
+ - `tokens.mjs`, `night-contrast.mjs`, `copy-deck.mjs` and `null-check.mjs` do not run.
105
+ - Nothing a visitor can see is added unless the founder said yes for this site: re-run with
106
+ `--with credit,consent,analytics,legal,press,resources` for the pieces agreed.
107
+
96
108
  ## site.programme.json
97
109
 
98
110
  | Key | What it is |
@@ -104,4 +116,4 @@ pricing modules and writes the facts the redesign renders.
104
116
  | `nullCheck` | `harvest` (a path, `~/` allowed) and `justified` (phrase to reason) |
105
117
  | `facts` | `importer`: the site's importer script, or null |
106
118
  | `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 |
119
+ | `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.`);
@@ -11,6 +11,13 @@ import { spawnSync } from "node:child_process";
11
11
  import { join } from "node:path";
12
12
  import { programme, root, stop } from "./programme.mjs";
13
13
 
14
+ // A handover (an existing live site copied in) keeps the client's look and copy.
15
+ // Facts still block the build. The direction and mobile-first checks report and
16
+ // never stop it. Tokens, night contrast, the copy deck and the null check do not
17
+ // run: they build a new design, and the design is the client's.
18
+ const HANDOVER_BLOCKING = [["facts.mjs"]];
19
+ const HANDOVER_ADVISORY = [["check-direction.mjs"], ["mobile-first.mjs"]];
20
+
14
21
  const GATES = [
15
22
  ["check-direction.mjs"],
16
23
  ["tokens.mjs"],
@@ -22,11 +29,26 @@ const GATES = [
22
29
  ];
23
30
 
24
31
  // Stage 01: the site has a programme in Linear before anything is built.
25
- const { issue } = programme();
32
+ const { issue, mode } = programme();
26
33
  if (typeof issue !== "string" || !/^[A-Z]+-\d+$/.test(issue)) {
27
34
  stop("programme", "01", "site.programme.json names no programme issue. Open the programme from the Site programme template in Linear and put its id (DOM-123) in issue.");
28
35
  }
29
36
 
37
+ if (mode === "handover") {
38
+ for (const [script, ...args] of HANDOVER_ADVISORY) {
39
+ const run = spawnSync(process.execPath, [join(root, "scripts", "gates", script), ...args], { cwd: root, stdio: "inherit" });
40
+ if (run.status !== 0) console.error(`\nHandover: ${script} reports a problem. It does not stop this build; docs/site-programme.md says what it checks.`);
41
+ }
42
+ for (const [script, ...args] of HANDOVER_BLOCKING) {
43
+ const run = spawnSync(process.execPath, [join(root, "scripts", "gates", script), ...args], { cwd: root, stdio: "inherit" });
44
+ if (run.status !== 0) {
45
+ console.error(`\nThe build stops at ${script}. docs/site-programme.md says what it needs.`);
46
+ process.exit(run.status || 1);
47
+ }
48
+ }
49
+ process.exit(0);
50
+ }
51
+
30
52
  for (const [script, ...args] of GATES) {
31
53
  const run = spawnSync(process.execPath, [join(root, "scripts", "gates", script), ...args], { cwd: root, stdio: "inherit" });
32
54
  if (run.status !== 0) {
@@ -0,0 +1,220 @@
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
+ // Registered named exceptions: exact lower-case addresses, each with a reason.
76
+ export function outsideAddresses(gate) {
77
+ const rows = gate.allow_outside_domain ?? [];
78
+ if (!Array.isArray(rows)) fail("allow_outside_domain must be a list");
79
+ const emails = rows.map(row => {
80
+ if (!row || typeof row.email !== "string" || row.email !== row.email.toLowerCase() || !/^[^\s@*]+@[^\s@*]+\.[^\s@*]+$/.test(row.email)) fail("each allow_outside_domain entry needs one exact lower-case email");
81
+ if (typeof row.why !== "string" || !row.why.trim()) fail(`allow_outside_domain ${row.email} has no reason`);
82
+ return row.email;
83
+ });
84
+ if (new Set(emails).size !== emails.length) fail("allow_outside_domain repeats an address");
85
+ return emails.sort();
86
+ }
87
+
88
+ export function canonicalReviewers(protection, registry) {
89
+ const gate = registry.gates?.[protection.gateKey];
90
+ 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");
91
+ const groups = [...new Set([...(registry.default_groups || []), ...(gate.groups || [])])];
92
+ if (!same(groups, ["Doman Digital reviewers"]) || !empty(gate.allow) || !empty(gate.service_tokens)) fail("the registered gate must allow only the DD reviewer group and its registered outside-domain addresses");
93
+ outsideAddresses(gate);
94
+ const callbacks = gate.bypass || [];
95
+ 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");
96
+ const reviewers = registry.groups?.[groups[0]];
97
+ 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");
98
+ return [...reviewers].sort();
99
+ }
100
+
101
+ export function readCanonicalRegistry(run = spawnSync) {
102
+ // origin/main is the merged source, unaffected by another session's dirty
103
+ // kit checkout. Fetch that canonical repo before adopting a new gate.
104
+ 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 });
105
+ if (result.status !== 0) fail("the merged canonical Access registry is unavailable");
106
+ return JSON.parse(result.stdout);
107
+ }
108
+
109
+ function publicDestinations(app) {
110
+ return [app.domain, ...(app.destinations || []).filter(d => d.type === "public").map(d => d.uri)].filter(Boolean);
111
+ }
112
+
113
+ function matchesHost(destination, hostname) {
114
+ const host = destination.split("/")[0].toLowerCase();
115
+ const escaped = host.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
116
+ return new RegExp(`^${escaped}$`).test(hostname);
117
+ }
118
+
119
+ export function validateAccessState(protection, state, registry) {
120
+ const reviewers = canonicalReviewers(protection, registry);
121
+ const { hostname, appName, reviewerGroupId, teamDomain } = protection;
122
+ if (state.organization.auth_domain !== teamDomain) fail("the live Zero Trust team does not match");
123
+ const apps = state.applications.filter(app => publicDestinations(app).some(d => matchesHost(d, hostname)));
124
+ const callbacks = registry.gates[protection.gateKey].bypass || [];
125
+ if (apps.length !== 1 + callbacks.length) fail("unexpected overlapping or path-specific Access app");
126
+ for (const callback of callbacks) {
127
+ const domain = `${hostname}${callback.path}`;
128
+ const match = apps.filter(a => a.domain === domain);
129
+ const bypass = match[0];
130
+ 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");
131
+ const policy = bypass.policies[0];
132
+ if (policy.decision !== "bypass" || !same(policy.include, [{everyone: {}}]) || !empty(policy.exclude) || !empty(policy.require)) fail("callback must carry only its registered bypass policy");
133
+ }
134
+ const rootApps = apps.filter(a => a.domain === hostname);
135
+ if (rootApps.length !== 1) fail("exactly one root reviewer app is required");
136
+ const app = rootApps[0];
137
+ 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");
138
+ if (!Array.isArray(app.policies) || app.policies.length !== 1) fail("exactly one reviewer allow policy is required");
139
+ const policy = app.policies[0];
140
+ const outside = outsideAddresses(registry.gates[protection.gateKey]);
141
+ const wanted = [JSON.stringify({ group: { id: reviewerGroupId } }), ...outside.map(email => JSON.stringify({ email: { email } }))].sort();
142
+ const have = Array.isArray(policy.include) ? policy.include.map(rule => JSON.stringify(rule)).sort() : null;
143
+ if (policy.decision !== "allow" || !same(have, wanted) || !empty(policy.exclude) || !empty(policy.require) || policy.session_duration !== "24h") fail("live policy must allow only the reviewer group and registered outside-domain addresses for 24h; no bypass or service token");
144
+ const group = state.groups.find(g => g.id === reviewerGroupId);
145
+ const expected = reviewers.map(email => ({ email: { email } }));
146
+ 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");
147
+ const providers = state.identityProviders.filter(p => app.allowed_idps?.includes(p.id));
148
+ 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");
149
+ return { appId: app.id, hostname, teamDomain, session: "24h", reviewers: reviewers.length };
150
+ }
151
+
152
+ export function readAccessState(protection, run = spawnSync) {
153
+ const read = (args) => {
154
+ const result = run("cf", ["zero-trust", ...args], { env: { ...process.env, CLOUDFLARE_ACCOUNT_ID: protection.accountId }, encoding: "utf8", timeout: 60000, maxBuffer: 8 * 1024 * 1024 });
155
+ if (result.status !== 0) fail(`Cloudflare read failed (${args.join(" ")}); nothing may be deployed`);
156
+ const data = JSON.parse(result.stdout);
157
+ return data.result ?? data;
158
+ };
159
+ const list = (args) => {
160
+ const rows = [], seen = new Set();
161
+ for (let page = 1; page <= 100; page++) {
162
+ const batch = read([...args, "--page", String(page), "--per-page", "50"]);
163
+ if (!Array.isArray(batch)) fail("Cloudflare list response is not an array");
164
+ for (const row of batch) {
165
+ if (!row.id || seen.has(row.id)) fail("Cloudflare pagination repeated a row or omitted its id");
166
+ seen.add(row.id); rows.push(row);
167
+ }
168
+ if (batch.length < 50) return rows;
169
+ }
170
+ fail("Cloudflare pagination exceeded the safe limit; completeness is unknown");
171
+ };
172
+ return {
173
+ organization: read(["organization", "get"]),
174
+ applications: list(["access", "applications", "list"]),
175
+ groups: list(["access", "rule-groups", "list"]),
176
+ identityProviders: list(["identity-providers", "list"]),
177
+ };
178
+ }
179
+
180
+ export function assertAccessProtection(protection) {
181
+ const registry = readCanonicalRegistry();
182
+ canonicalReviewers(protection, registry);
183
+ const evidence = validateAccessState(protection, readAccessState(protection), registry);
184
+ console.log(`protected preview: live Access app ${evidence.appId} protects ${evidence.hostname}; 24h, ${evidence.reviewers} DD reviewers.`);
185
+ return evidence;
186
+ }
187
+
188
+ export function validateWorkerProtection(protection, worker) {
189
+ 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");
190
+ const domains = worker.references?.domains;
191
+ 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");
192
+ return worker.subdomain;
193
+ }
194
+
195
+ export function assertWorkerProtection(protection, run = spawnSync) {
196
+ const result = run("cf", ["workers", "get", protection.workerName], { env: { ...process.env, CLOUDFLARE_ACCOUNT_ID: protection.accountId }, encoding: "utf8", timeout: 60000, maxBuffer: 1024 * 1024 });
197
+ if (result.status !== 0) fail("cannot verify the deployed Worker's alternate URLs");
198
+ const data = JSON.parse(result.stdout);
199
+ const subdomain = validateWorkerProtection(protection, data.result ?? data);
200
+ console.log("protected preview: live workers.dev and version preview URLs are disabled.");
201
+ return subdomain;
202
+ }
203
+
204
+ export async function probeProtectedPreview(protection, fetcher = fetch) {
205
+ for (const path of protection.probePaths) {
206
+ const response = await fetcher(`https://${protection.hostname}${path}`, { redirect: "manual", signal: AbortSignal.timeout(20000), headers: { "Cache-Control": "no-cache" } });
207
+ let location;
208
+ try { location = new URL(response.headers.get("location")); } catch { fail(`anonymous ${path} did not redirect to Access`); }
209
+ 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`);
210
+ console.log(`protected preview: anonymous ${path} -> Access login (302).`);
211
+ }
212
+ }
213
+
214
+ export async function probeCallbacks(protection, registry = readCanonicalRegistry(), fetcher = fetch) {
215
+ canonicalReviewers(protection, registry);
216
+ for (const callback of registry.gates[protection.gateKey].bypass || []) {
217
+ const response = await fetcher(`https://${protection.hostname}${callback.path}`, {method: "POST", body: "{}", headers: {"Content-Type": "application/json"}, redirect: "manual", signal: AbortSignal.timeout(20000)});
218
+ if (response.status !== callback.authProbe.status) fail(`unsigned callback ${callback.path} did not reject with ${callback.authProbe.status}`);
219
+ }
220
+ }
@@ -48,24 +48,38 @@ describe("the facts file is the single source of contact details", () => {
48
48
  });
49
49
  });
50
50
 
51
+ // .dd/site-start.json says how the site was started. A handover keeps the
52
+ // client's look and copy, so it only has to place the visible pieces it was
53
+ // started with (create-site --handover --with <piece>). A new build places all.
54
+ function startedWith(): { handover: boolean; pieces: string[] } {
55
+ try {
56
+ const label = JSON.parse(readFileSync(join(ROOT, ".dd", "site-start.json"), "utf8")) as { mode?: string; with?: unknown };
57
+ return { handover: label.mode === "handover", pieces: Array.isArray(label.with) ? label.with.filter((w): w is string => typeof w === "string") : [] };
58
+ } catch {
59
+ return { handover: false, pieces: [] };
60
+ }
61
+ }
62
+ const started = startedWith();
63
+ const places = (piece: string) => !started.handover || started.pieces.includes(piece);
64
+
51
65
  describe.runIf(mode === "launch")("ready to launch", () => {
52
- test("the designer credit is placed on the site", () => {
66
+ test.runIf(places("credit"))("the designer credit is placed on the site", () => {
53
67
  const placed = sourceFiles().some((file) => !/DesignerCredit\.(tsx|astro)$/.test(file) && readFileSync(file, "utf8").includes("<DesignerCredit"));
54
68
  expect(placed).toBe(true);
55
69
  });
56
70
 
57
- test("the cookie banner is placed on the site", () => {
71
+ test.runIf(places("consent"))("the cookie banner is placed on the site", () => {
58
72
  const placed = sourceFiles().some((file) => !/CookieBanner\.(tsx|astro)$/.test(file) && readFileSync(file, "utf8").includes("<CookieBanner"));
59
73
  expect(placed).toBe(true);
60
74
  });
61
75
 
62
- test("Cloudflare Web Analytics is placed on the site and has its token", () => {
76
+ test.runIf(places("analytics"))("Cloudflare Web Analytics is placed on the site and has its token", () => {
63
77
  const placed = sourceFiles().some((file) => !/WebAnalytics\.(tsx|astro)$/.test(file) && readFileSync(file, "utf8").includes("<WebAnalytics"));
64
78
  expect(placed).toBe(true);
65
79
  expect(facts.webAnalytics?.token ?? null).not.toBeNull();
66
80
  });
67
81
 
68
- test("the legal pages have what every site needs: retention, the processors, the governing law, a review date", () => {
82
+ test.runIf(places("legal"))("the legal pages have what every site needs: retention, the processors, the governing law, a review date", () => {
69
83
  const missing = [
70
84
  legal.retention ? null : "legal.retention",
71
85
  legal.processors.length > 0 ? null : "legal.processors (the host at least)",