@zero2webmaster/starter-kit 0.5.8 → 0.6.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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # z2w-starter-kit
2
2
 
3
- **Version:** 0.5.8 | **Framework:** 2.13.0
3
+ **Version:** 0.6.0 | **Framework:** 2.13.0
4
4
 
5
5
  > Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.
6
6
 
@@ -99,4 +99,4 @@ For licensing inquiries: kerry@zero2webmaster.com.
99
99
  ---
100
100
 
101
101
  *Scaffolded 2026-05-28 via the [[instantiate-z2w-project]] Claude Code skill v1; reconciled against the consolidated skill v1.1.0 (brief-first + Agent Coordination block) on 2026-05-29.*
102
- *Version: 0.5.8 | Last Updated: 2026-07-30*
102
+ *Version: 0.6.0 | Last Updated: 2026-07-30*
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { writeScaffold } from "./writer.js";
2
2
  import type { ScaffoldFile } from "./scaffolders/common.js";
3
3
  import type { StandardDecision } from "./standards.js";
4
- export declare const version = "0.5.8";
4
+ export declare const version = "0.6.0";
5
5
  export type ProjectType = "wp-plugin" | "cf-worker" | "cf-pages" | "nextjs" | "python-service" | "node-service" | "library" | "protocol-repo";
6
6
  export type BrandPreset = "save-the-frogs" | "bansuri-bliss" | "zero2webmaster" | "custom";
7
7
  export type DbStrategy = "none" | "neon-postgres" | "supabase" | "sqlite" | "mysql-wp" | "other";
@@ -112,6 +112,33 @@ export interface ScaffoldInputs {
112
112
  * failed silently" surface.
113
113
  */
114
114
  hasObservability?: boolean;
115
+ /**
116
+ * Whether the incoming `Host` header selects the tenant — a HOST-ROUTED
117
+ * multi-tenant app, where each tenant has its own front door (its own custom
118
+ * domain) served by one deployment. True for `org-hq`, `site-control`,
119
+ * `z2w-member-match`; false for a single-tenant app that has exactly one
120
+ * canonical domain.
121
+ *
122
+ * When `true`, the `nextjs` scaffolder changes two things:
123
+ *
124
+ * 1. **`next.config.mjs` omits the `*.vercel.app` → custom-domain alias
125
+ * redirect.** That redirect assumes ONE canonical destination, which is
126
+ * precisely what a host-routed app does not have — redirecting an alias to a
127
+ * fixed host drops visitors into some other tenant's app.
128
+ * 2. **A `middleware.ts` host guard is emitted instead**, which returns **404**
129
+ * for a production request on a known-non-canonical host. Per the 2026-07-30
130
+ * ruling (reached across `org-hq`, `site-control` and `z2w-member-match`):
131
+ * **404 on an unmapped Host, never a redirect to a fixed one.**
132
+ *
133
+ * It also emits the `CANONICAL_HOSTS` allowlist stub in `.env.example`, since a
134
+ * Host-routed app needs to know which hosts are legitimately its own.
135
+ *
136
+ * Optional and defaults to `false` (single-tenant — the alias redirect ships as
137
+ * before). Honored only by the `nextjs` type; other types have no Host-based
138
+ * routing surface. Deliberately opt-in on the `--input` / programmatic paths so
139
+ * an existing caller's output is unchanged.
140
+ */
141
+ hostRoutedTenancy?: boolean;
115
142
  /** Present only when `brand === "custom"`. */
116
143
  customBrand?: CustomBrandInputs;
117
144
  /**
package/dist/index.js CHANGED
@@ -21,7 +21,7 @@ import * as path from "node:path";
21
21
  import { Writable } from "node:stream";
22
22
  import { isValidSlug } from "./parse-brief.js";
23
23
  import { writeScaffold } from "./writer.js";
24
- export const version = "0.5.8";
24
+ export const version = "0.6.0";
25
25
  // Canonical enum value-arrays. These live here, next to the type unions they
26
26
  // enumerate, so both the CLI's confirm/wizard flows (which re-export them) and
27
27
  // the programmatic `validateScaffoldInputs` share one source of truth. Keep
@@ -6,4 +6,4 @@ export declare function scaffoldNextjs(inputs: ScaffoldInputs, opts?: Scaffolder
6
6
  * they can assert / require the canonical SEO baseline file list without
7
7
  * hardcoding the paths in two places.
8
8
  */
9
- export declare const NEXTJS_SEO_BASELINE_PATHS: readonly ["app/layout.tsx", "app/page.tsx", "app/sitemap.ts", "app/robots.ts", "app/opengraph-image.tsx", "lib/analytics/utm.ts", "lib/analytics/Analytics.tsx", "lib/analytics/RouteTracker.tsx", "SEO-CHECKLIST.md", ".env.example"];
9
+ export declare const NEXTJS_SEO_BASELINE_PATHS: readonly ["app/layout.tsx", "app/page.tsx", "app/sitemap.ts", "app/robots.ts", "lib/seo/canonical-host.mjs", "app/opengraph-image.tsx", "lib/analytics/utm.ts", "lib/analytics/Analytics.tsx", "lib/analytics/RouteTracker.tsx", "SEO-CHECKLIST.md", ".env.example"];
@@ -11,8 +11,12 @@
11
11
  // descriptive alt where appropriate (placeholder content uses semantic
12
12
  // HTML; no decorative images at scaffold time).
13
13
  // 5. JSON-LD — `Organization` schema injected in app/layout.tsx.
14
- // 6. sitemap.xml + robots.txt — app/sitemap.ts + app/robots.ts; preview
15
- // noindex gated on `VERCEL_ENV !== 'production'`.
14
+ // 6. sitemap.xml + robots.txt — app/sitemap.ts + app/robots.ts. Indexable
15
+ // requires BOTH `VERCEL_ENV === 'production'` AND a real canonical domain
16
+ // (not the *.example.com placeholder, not *.vercel.app) — gating on
17
+ // VERCEL_ENV alone published `Allow: /` with placeholder sitemap URLs on the
18
+ // first prod deploy. Predicate lives in lib/seo/canonical-host.mjs, shared
19
+ // with next.config.mjs so robots and the alias redirect cannot disagree.
16
20
  // 7. Fathom — the three-file pattern under lib/analytics/ (utm.ts +
17
21
  // Analytics.tsx + RouteTracker.tsx), mounted as <Analytics /> in
18
22
  // app/layout.tsx, gated on `NEXT_PUBLIC_FATHOM_SITE_ID` (per
@@ -25,6 +29,18 @@
25
29
  // next.config.mjs that redirects the production *.vercel.app alias to the
26
30
  // custom domain (SEO-duplicate fix — Z2W heads-up 2026-06-29; self-disabling
27
31
  // until NEXT_PUBLIC_SITE_URL is a real custom domain).
32
+ //
33
+ // Conditional on `hostRoutedTenancy` (a HOST-ROUTED multi-tenant app, where the
34
+ // Host selects the tenant): the single-destination alias redirect is OMITTED —
35
+ // wrong shape, there is no one canonical domain — and a `middleware.ts` host
36
+ // guard is emitted that returns **404** on a known-non-canonical production host.
37
+ // Ruling 2026-07-30 across org-hq / site-control / z2w-member-match: 404 on an
38
+ // unmapped Host, never a redirect to a fixed one.
39
+ //
40
+ // Conditional on `sendsEmail` or `hostRoutedTenancy`: a `CANONICAL_HOSTS`
41
+ // allowlist stub in `.env.example`. This CLI emits no auth code, so it plants the
42
+ // seam + the pointer at [[z2w-magic-link-auth]] §0 rule 2b rather than a check —
43
+ // see CANONICAL_HOSTS_ENV_BLOCK for why that is the honest half.
28
44
  import { commonBaseFiles, EMAIL_DEPS, EMAIL_ENV_BLOCK, emailFiles, localEnvFrom, resolveBrandSpec, sub, } from "./common.js";
29
45
  const NARRATIVE = `## What this is
30
46
 
@@ -44,8 +60,9 @@ npm run build && npm start # production build
44
60
  - \`app/layout.tsx\` — root \`metadata\` with \`title.template\`, \`title.default\`, \`description\`, \`openGraph\`, \`twitter\`, \`metadataBase\`; mounts \`<Analytics />\`; JSON-LD Organization schema.
45
61
  - \`app/page.tsx\` — per-page \`metadata\` (unique title + description; never inherit defaults); exactly one \`<h1>\`; semantic HTML.
46
62
  - \`lib/analytics/{utm.ts,Analytics.tsx,RouteTracker.tsx}\` — Fathom (per [[fathom-analytics]]); the RouteTracker fires \`trackPageview()\` on route change + captures first-touch UTM. Gated on \`NEXT_PUBLIC_FATHOM_SITE_ID\`.
47
- - \`app/sitemap.ts\` — sitemap generator; lists indexable pages.
48
- - \`app/robots.ts\` — robots generator; preview/staging emits \`noindex\` (gated on \`VERCEL_ENV !== 'production'\`).
63
+ - \`app/sitemap.ts\` — sitemap generator; lists indexable pages. \`lastModified\` is deliberately omitted until you have a real content timestamp.
64
+ - \`app/robots.ts\` — robots generator. Indexable requires BOTH a production deployment AND a real canonical domain in \`NEXT_PUBLIC_SITE_URL\`; anything else emits \`Disallow: /\`. **Both files are prerendered at build time, so changing \`NEXT_PUBLIC_SITE_URL\` needs a redeploy.**
65
+ - \`lib/seo/canonical-host.mjs\` — the one canonical-host predicate, shared by \`app/robots.ts\` and \`next.config.mjs\` so the indexability gate and the alias redirect cannot disagree.
49
66
  - \`app/opengraph-image.tsx\` — default OG image (replace placeholder before launch).
50
67
  - \`SEO-CHECKLIST.md\` — per-page checklist; consult before adding new pages.
51
68
 
@@ -80,8 +97,76 @@ const PACKAGE_JSON_TEMPLATE = `{
80
97
  "homepage": "https://github.com/{{github_org}}/{{slug}}"
81
98
  }
82
99
  `;
100
+ /**
101
+ * ONE definition of "is this host a real canonical domain?", shared by
102
+ * `next.config.mjs` (the alias redirect) and `app/robots.ts` (the indexability
103
+ * gate). Emitted as `.mjs` on purpose: `next.config.mjs` is plain ESM loaded
104
+ * before any TypeScript exists, so it cannot import a `.ts` module — while the
105
+ * scaffolded `tsconfig.json` sets `allowJs: true`, so `app/robots.ts`
106
+ * type-checks this same file and picks up its JSDoc types. Two copies would let
107
+ * robots.txt say "index me" while the alias redirect is off — the single most
108
+ * invisible drift available in this file family (`site-control`, 2026-07-29).
109
+ */
110
+ const CANONICAL_HOST_MODULE_TEMPLATE = `// Shared canonical-host predicate. Imported by BOTH next.config.mjs (alias
111
+ // redirect) and app/robots.ts (indexability gate) so the two can never disagree.
112
+ //
113
+ // Emitted as .mjs deliberately: next.config.mjs is plain ESM loaded before any
114
+ // TypeScript exists and cannot import a .ts module. tsconfig.json sets
115
+ // \`allowJs: true\`, so app/robots.ts type-checks this file too.
116
+
117
+ /**
118
+ * Host suffixes that are NEVER a canonical domain.
119
+ *
120
+ * \`.vercel.app\` is in here for consistency, not as an extra rule: the alias
121
+ * redirect in next.config.mjs already 301s every production *.vercel.app host to
122
+ * the custom domain precisely so they are not crawled as duplicates. Treating one
123
+ * as canonical would contradict a redirect this project already ships.
124
+ *
125
+ * \`.example.com\` is the scaffold's own placeholder default, which is by
126
+ * definition what NEXT_PUBLIC_SITE_URL holds on day one.
127
+ */
128
+ export const NON_CANONICAL_HOST_SUFFIXES = [".vercel.app", ".example.com"];
129
+
130
+ /**
131
+ * The canonical host from a site URL, or "" when there isn't one yet.
132
+ *
133
+ * @param {string | undefined} rawSiteUrl typically process.env.NEXT_PUBLIC_SITE_URL
134
+ * @returns {string} a real custom-domain host, else ""
135
+ */
136
+ export function canonicalHost(rawSiteUrl) {
137
+ try {
138
+ const { host } = new URL(rawSiteUrl || "");
139
+ // "localhost:3000" (no scheme) parses with an EMPTY host rather than throwing.
140
+ if (!host) return "";
141
+ return NON_CANONICAL_HOST_SUFFIXES.some((s) => host.endsWith(s)) ? "" : host;
142
+ } catch {
143
+ // Not a valid absolute URL yet (blank, or a bare hostname).
144
+ return "";
145
+ }
146
+ }
147
+
148
+ /**
149
+ * Whether this deployment may be indexed by search engines.
150
+ *
151
+ * Requires BOTH a production deployment AND a real canonical domain. Gating on
152
+ * VERCEL_ENV alone means the FIRST production deploy publishes \`Allow: /\` plus a
153
+ * sitemap of placeholder URLs, because NEXT_PUBLIC_SITE_URL is unset on day one
154
+ * and the fallback is a domain this project does not own. Getting placeholder
155
+ * URLs back out of a search index is slow and awkward, so this fails toward the
156
+ * visible error: a misconfigured deploy stays \`Disallow: /\`, which one \`curl\`
157
+ * reveals and one env var fixes.
158
+ *
159
+ * @param {Record<string, string | undefined>} [env] defaults to process.env
160
+ * @returns {boolean}
161
+ */
162
+ export function isIndexableDeployment(env = process.env) {
163
+ return env.VERCEL_ENV === "production" && canonicalHost(env.NEXT_PUBLIC_SITE_URL) !== "";
164
+ }
165
+ `;
83
166
  const NEXT_CONFIG_TEMPLATE = `/** @type {import('next').NextConfig} */
84
167
 
168
+ import { canonicalHost } from "./lib/seo/canonical-host.mjs";
169
+
85
170
  // SEO: redirect EVERY auto-assigned PRODUCTION *.vercel.app alias to the custom
86
171
  // domain so none is crawled as an indexable duplicate of the whole site
87
172
  // (Z2W standing heads-up 2026-06-29; recipe = [[portable-stack]] §24).
@@ -101,25 +186,15 @@ const NEXT_CONFIG_TEMPLATE = `/** @type {import('next').NextConfig} */
101
186
  // While it is blank, the *.example.com placeholder, or itself a *.vercel.app
102
187
  // host, the redirect list is empty — so a fresh scaffold never self-redirects,
103
188
  // and the custom domain (not *.vercel.app) never matches the regex → no loop.
189
+ //
190
+ // \`canonicalHost\` is imported rather than defined here so app/robots.ts decides
191
+ // indexability from the SAME predicate. See lib/seo/canonical-host.mjs.
104
192
  const isVercelProduction = process.env.VERCEL_ENV === "production";
105
193
 
106
- function canonicalHost() {
107
- const raw = process.env.NEXT_PUBLIC_SITE_URL || "";
108
- try {
109
- const host = new URL(raw).host;
110
- if (host && !host.endsWith(".vercel.app") && !host.endsWith(".example.com")) {
111
- return host;
112
- }
113
- } catch {
114
- // NEXT_PUBLIC_SITE_URL not a valid absolute URL yet — no redirect.
115
- }
116
- return "";
117
- }
118
-
119
194
  const nextConfig = {
120
195
  reactStrictMode: true,
121
196
  async redirects() {
122
- const host = canonicalHost();
197
+ const host = canonicalHost(process.env.NEXT_PUBLIC_SITE_URL);
123
198
  // Only in production, and only once a real custom domain is configured.
124
199
  if (!host || !isVercelProduction) return [];
125
200
  return [
@@ -136,6 +211,84 @@ const nextConfig = {
136
211
 
137
212
  export default nextConfig;
138
213
  `;
214
+ /**
215
+ * The `next.config.mjs` variant for a HOST-ROUTED multi-tenant app, where the
216
+ * incoming Host selects the tenant. Emitted when `hostRoutedTenancy` is set.
217
+ *
218
+ * The single-destination alias redirect above is wrong for this shape: there is
219
+ * no one canonical domain to redirect to — every tenant has its own front door,
220
+ * so redirecting a `*.vercel.app` alias to a fixed host lands visitors in some
221
+ * other tenant's app. The ruling (2026-07-30, three projects deep: `org-hq`,
222
+ * `site-control`, `z2w-member-match`) is **404 on an unmapped Host**, never a
223
+ * redirect to a fixed one. The redirect is therefore omitted here and the guard
224
+ * lives in `middleware.ts`.
225
+ */
226
+ const NEXT_CONFIG_HOST_ROUTED_TEMPLATE = `/** @type {import('next').NextConfig} */
227
+
228
+ // HOST-ROUTED MULTI-TENANT APP — the incoming Host selects the tenant.
229
+ //
230
+ // NOTE the deliberate ABSENCE of the *.vercel.app → custom-domain alias redirect
231
+ // that single-tenant Z2W Next.js apps ship. That redirect assumes ONE canonical
232
+ // destination, which is exactly what this shape does not have: every tenant has
233
+ // its own front door, so redirecting an alias to a fixed host would drop visitors
234
+ // into some other tenant's app. The ruling is **404 on an unmapped Host, never a
235
+ // redirect to a fixed one** — enforced in middleware.ts, which is the only place
236
+ // that sees the request Host at runtime. See lib/seo/canonical-host.mjs.
237
+
238
+ const nextConfig = {
239
+ reactStrictMode: true,
240
+ };
241
+
242
+ export default nextConfig;
243
+ `;
244
+ /**
245
+ * The Host guard for a host-routed multi-tenant app: a production request
246
+ * arriving on a known-non-canonical host maps to no tenant, so it 404s.
247
+ *
248
+ * Scope is deliberately narrow — middleware cannot resolve tenant vanity domains
249
+ * without a DB read (which would burn Neon CU-hours on every request, per
250
+ * [[neon-postgres]]), so this rejects only the host classes the scaffold KNOWS
251
+ * are nobody's tenant. Resolving real tenant domains stays the app's job.
252
+ */
253
+ const MIDDLEWARE_HOST_GUARD_TEMPLATE = `// Host guard for this HOST-ROUTED multi-tenant app.
254
+ //
255
+ // A production request arriving on a known-non-canonical host (*.vercel.app, the
256
+ // *.example.com placeholder) maps to NO tenant. Per the Z2W alias ruling it gets
257
+ // a 404 — never a redirect to a fixed canonical host, because there is no single
258
+ // canonical host in a host-routed app and redirecting would drop the visitor into
259
+ // a different tenant's front door.
260
+ //
261
+ // Deliberately narrow: this does NOT resolve tenant vanity domains, because that
262
+ // needs a DB read on every request and would burn Neon's CU-hour quota
263
+ // ([[neon-postgres]]). It rejects only the host classes that are nobody's tenant.
264
+ // Your tenant resolver still has to 404 a host it cannot map.
265
+
266
+ import { NextResponse } from "next/server";
267
+ import type { NextRequest } from "next/server";
268
+ import { NON_CANONICAL_HOST_SUFFIXES } from "@/lib/seo/canonical-host.mjs";
269
+
270
+ export function middleware(request: NextRequest) {
271
+ // Only in production. Preview deployments and localhost are *.vercel.app /
272
+ // localhost by nature, and blocking them would make every preview unusable.
273
+ if (process.env.VERCEL_ENV !== "production") return NextResponse.next();
274
+
275
+ const host = (request.headers.get("x-forwarded-host") ?? request.headers.get("host") ?? "")
276
+ .toLowerCase()
277
+ .split(":")[0];
278
+
279
+ if (NON_CANONICAL_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix))) {
280
+ return new NextResponse(null, { status: 404 });
281
+ }
282
+
283
+ return NextResponse.next();
284
+ }
285
+
286
+ export const config = {
287
+ // Skip Next internals and the health endpoint — an uptime monitor pointed at
288
+ // the platform alias must keep working ([[uptime-kuma-monitor]]).
289
+ matcher: ["/((?!_next/|api/health).*)"],
290
+ };
291
+ `;
139
292
  const TSCONFIG_TEMPLATE = `{
140
293
  "compilerOptions": {
141
294
  "target": "ES2022",
@@ -440,25 +593,45 @@ export default function sitemap(): MetadataRoute.Sitemap {
440
593
  return [
441
594
  {
442
595
  url: siteUrl,
443
- lastModified: new Date(),
596
+ // \`lastModified\` is deliberately OMITTED rather than set to \`new Date()\`.
597
+ // An always-now value claims the page changed on every fetch of the
598
+ // sitemap; Google documents ignoring \`lastmod\` once it proves unreliable,
599
+ // so a value that is always wrong spends the signal to say nothing — worse
600
+ // than not sending it. Add it back when you have a REAL content timestamp
601
+ // (a CMS \`updated_at\`, a file mtime, a build-pinned constant).
444
602
  changeFrequency: "weekly",
445
603
  priority: 1,
446
604
  },
447
605
  ];
448
606
  }
449
607
  `;
450
- const APP_ROBOTS_TEMPLATE = `// Robots generator — production indexable, preview/staging noindex per SEO
451
- // baseline. Gated on \`VERCEL_ENV\`; for non-Vercel hosts swap in the
452
- // equivalent env var (e.g. \`CF_PAGES_BRANCH !== 'main'\`).
608
+ const APP_ROBOTS_TEMPLATE = `// Robots generator — indexable ONLY on a production deployment that also has a
609
+ // real canonical domain. Everything else (preview, staging, and a production
610
+ // deploy still on the placeholder domain) emits \`Disallow: /\`.
611
+ //
612
+ // Two conditions, not one. Gating on \`VERCEL_ENV\` ALONE means the very first
613
+ // \`vercel --prod\` — or the first push after connecting the repo, since
614
+ // auto-deploy is on by default — publishes \`Allow: /\` advertising a sitemap of
615
+ // \`{{slug}}.example.com\` URLs, a domain this project does not own.
616
+ // \`NEXT_PUBLIC_SITE_URL\` is unset on day one by definition, so the placeholder is
617
+ // what ships. (Reported by \`site-control\` 2026-07-29 after it cost two deferred
618
+ // deploys: the deploy was never the hazard, the gate was.)
619
+ //
620
+ // ⚠️ robots.txt and sitemap.xml are PRERENDERED at build time (\`○ (Static)\`), so
621
+ // setting NEXT_PUBLIC_SITE_URL later requires a REDEPLOY — editing the env var
622
+ // alone changes nothing.
623
+ //
624
+ // For non-Vercel hosts, swap the VERCEL_ENV check inside
625
+ // lib/seo/canonical-host.mjs for the equivalent (e.g. \`CF_PAGES_BRANCH === 'main'\`).
453
626
 
454
627
  import type { MetadataRoute } from "next";
628
+ import { isIndexableDeployment } from "@/lib/seo/canonical-host.mjs";
455
629
 
456
630
  // \`||\` not \`??\` — a blank NEXT_PUBLIC_SITE_URL must fall back (see app/layout.tsx).
457
631
  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || "https://{{slug}}.example.com";
458
- const isProduction = process.env.VERCEL_ENV === "production";
459
632
 
460
633
  export default function robots(): MetadataRoute.Robots {
461
- if (!isProduction) {
634
+ if (!isIndexableDeployment()) {
462
635
  return {
463
636
  rules: { userAgent: "*", disallow: "/" },
464
637
  };
@@ -538,7 +711,8 @@ Per Z2W standing org requirement 2026-05-30. Run before adding a new page AND be
538
711
  - ✅ \`app/layout.tsx\` — root metadata + JSON-LD Organization
539
712
  - ✅ \`app/page.tsx\` — per-page metadata template
540
713
  - ✅ \`app/sitemap.ts\`
541
- - ✅ \`app/robots.ts\` (preview-noindex gated on \`VERCEL_ENV\`)
714
+ - ✅ \`app/robots.ts\` (indexable requires production **and** a real canonical domain — see \`lib/seo/canonical-host.mjs\`)
715
+ - ⚠️ \`robots.txt\` + \`sitemap.xml\` are PRERENDERED at build time. Until \`NEXT_PUBLIC_SITE_URL\` is your real domain this site is \`Disallow: /\` **by design**; setting the env var requires a **redeploy** to take effect. Verify with \`curl https://your-domain/robots.txt\`.
542
716
  - ✅ \`app/opengraph-image.tsx\` (placeholder — replace before launch)
543
717
  - ✅ Fathom three-file pattern (\`lib/analytics/\`) mounted as \`<Analytics />\`; RouteTracker fires \`trackPageview()\` on route change (gated on \`NEXT_PUBLIC_FATHOM_SITE_ID\`)
544
718
  - ✅ \`NEXT_PUBLIC_SITE_URL\` env var stub for \`metadataBase\`
@@ -562,6 +736,41 @@ NEXT_PUBLIC_SITE_URL=https://{{slug}}.example.com
562
736
  # One Fathom site = one deployment.
563
737
  NEXT_PUBLIC_FATHOM_SITE_ID=
564
738
  `;
739
+ /**
740
+ * The `CANONICAL_HOSTS` allowlist seam.
741
+ *
742
+ * Appended when the project sends auth email (`sendsEmail`) or routes by Host
743
+ * (`hostRoutedTenancy`) — the two shapes that have somewhere to enforce it.
744
+ *
745
+ * Why the scaffolder plants the env var and the pointer rather than the code:
746
+ * this CLI does not emit `auth.ts` (it emits no auth code at all), so there is no
747
+ * emitted host check to patch. The gap `audit-engine` measured on 2026-07-29 —
748
+ * 10 repos with `trustHost: true`, no `AUTH_URL`, and only 2 validating the host
749
+ * — propagated through the *guidance*, not through this scaffold. So the
750
+ * scaffolder's honest half is the seam: an env var that exists on day one, and a
751
+ * pointer at the recipe, in the file the next agent actually opens.
752
+ */
753
+ const CANONICAL_HOSTS_ENV_BLOCK = `
754
+ # ── Canonical host allowlist ────────────────────────────────────────────────
755
+ # Comma-separated list of the hostnames this deployment legitimately answers on.
756
+ # Normalize to lowercase when you parse it.
757
+ #
758
+ # UNSET MUST MEAN NOBODY, NOT EVERYBODY. An env-var typo has to lock the door,
759
+ # not remove it — the same fail-closed-on-empty rule as ALLOWED_EMAILS.
760
+ #
761
+ # Magic-link auth needs this and it is not optional: \`trustHost: true\` with no
762
+ # AUTH_URL (the correct Z2W setting — a fixed AUTH_URL breaks tenant vanity
763
+ # domains) means Auth.js derives every magic-link URL from the incoming Host
764
+ # header with NOTHING validating it. An attacker can request a link for someone
765
+ # else's address on a forged Host; the victim gets a genuine, correctly-signed
766
+ # email pointing at the attacker's server. Validate inside
767
+ # sendVerificationRequest and fail CLOSED — send nothing, do not fall back to a
768
+ # canonical host (that is an enumeration oracle). Allow anything when
769
+ # NODE_ENV !== "production" so preview deployments and localhost keep working.
770
+ #
771
+ # Copy-paste recipe + the isKnownHost() helper: [[z2w-magic-link-auth]] §0 rule 2b.
772
+ CANONICAL_HOSTS=
773
+ `;
565
774
  /**
566
775
  * Merge the email SDK deps into an already-substituted package.json string.
567
776
  * Only called on the email path, so the no-email package.json stays the exact
@@ -576,15 +785,27 @@ export function scaffoldNextjs(inputs, opts) {
576
785
  const spec = resolveBrandSpec(inputs);
577
786
  const base = commonBaseFiles(inputs, opts, NARRATIVE);
578
787
  const sendsEmail = inputs.sendsEmail === true;
788
+ const hostRouted = inputs.hostRoutedTenancy === true;
579
789
  let packageJson = sub(PACKAGE_JSON_TEMPLATE, inputs, opts, spec);
580
790
  if (sendsEmail)
581
791
  packageJson = withEmailDeps(packageJson);
582
792
  let envExample = sub(ENV_EXAMPLE_TEMPLATE, inputs, opts, spec);
583
793
  if (sendsEmail)
584
794
  envExample += EMAIL_ENV_BLOCK;
795
+ // The host allowlist serves auth email (magic links derive URLs from the Host)
796
+ // and Host-routed tenancy (the Host selects the tenant). Emitted once for both.
797
+ if (sendsEmail || hostRouted)
798
+ envExample += CANONICAL_HOSTS_ENV_BLOCK;
585
799
  const typeSpecific = [
586
800
  { path: "package.json", content: packageJson },
587
- { path: "next.config.mjs", content: sub(NEXT_CONFIG_TEMPLATE, inputs, opts, spec) },
801
+ {
802
+ path: "next.config.mjs",
803
+ content: sub(hostRouted ? NEXT_CONFIG_HOST_ROUTED_TEMPLATE : NEXT_CONFIG_TEMPLATE, inputs, opts, spec),
804
+ },
805
+ {
806
+ path: "lib/seo/canonical-host.mjs",
807
+ content: sub(CANONICAL_HOST_MODULE_TEMPLATE, inputs, opts, spec),
808
+ },
588
809
  { path: "tsconfig.json", content: sub(TSCONFIG_TEMPLATE, inputs, opts, spec) },
589
810
  { path: "app/layout.tsx", content: sub(APP_LAYOUT_TEMPLATE, inputs, opts, spec) },
590
811
  { path: "app/page.tsx", content: sub(APP_PAGE_TEMPLATE, inputs, opts, spec) },
@@ -617,6 +838,12 @@ export function scaffoldNextjs(inputs, opts) {
617
838
  path: ".env.local",
618
839
  content: localEnvFrom(envExample, ".env.local", inputs.slug),
619
840
  });
841
+ if (hostRouted) {
842
+ typeSpecific.push({
843
+ path: "middleware.ts",
844
+ content: sub(MIDDLEWARE_HOST_GUARD_TEMPLATE, inputs, opts, spec),
845
+ });
846
+ }
620
847
  if (sendsEmail) {
621
848
  typeSpecific.push(...emailFiles(inputs, opts, spec, "nextjs"));
622
849
  }
@@ -632,6 +859,10 @@ export const NEXTJS_SEO_BASELINE_PATHS = [
632
859
  "app/page.tsx",
633
860
  "app/sitemap.ts",
634
861
  "app/robots.ts",
862
+ // The shared canonical-host predicate. Part of the baseline because the
863
+ // indexability gate in app/robots.ts and the alias redirect in next.config.mjs
864
+ // both read it — a scaffold missing it has no indexability gate at all.
865
+ "lib/seo/canonical-host.mjs",
635
866
  "app/opengraph-image.tsx",
636
867
  // Fathom (SEO baseline item 7) — the three-file pattern; the loader alone
637
868
  // (data-auto="false" with no RouteTracker) records zero pageviews.
package/dist/standards.js CHANGED
@@ -371,7 +371,7 @@ This project participates in the Z2W cross-project coordination bulletin.
371
371
  \`\`\`
372
372
  - 2026-07-25 · z2w-starter-kit · ACTION · Trim your bulletin file — it's over the 256 KB read-cap · §Open questions
373
373
  \`\`\`
374
- Applies to every inbound form: a \`[→ {them}]\` question, a heads-up you filed in their file, or a maintainer directive. **The recipient deletes the line when they handle it**, so leaving it un-deleted is the signal that the item is still live. *(Adopted 2026-07-25 from \`z2w-starter-kit\`'s 2026-07-15 proposal on Kerry's observation that finding messages addressed to a project was too hard — one session had to grep a 705 KB file across three sections to find a directive aimed at it — and \`z2w-agent-command-center\`'s independent endorsement after the same failure bit it. The Command Center renders this block as the phone-first "addressed to you" queue.)*
374
+ Applies to every inbound form: a \`[→ {them}]\` question, a heads-up you filed in their file, or a maintainer directive. **The recipient deletes the line when they handle it**, so leaving it un-deleted is the signal that the item is still live. **Two send-side rules (v0.1.22, both detailed in §8.11):** (1) **grep their file for an existing thread on your topic before you file** — you already have the file open to append, so the check is free; if a thread exists, \`↳\` co-sign it (saying what's *different* about your instance) rather than opening a second one; (2) **if you later WITHDRAW an item, delete your own triage line yourself** — post the \`↳ retracted\` reply first, then remove the line. Retraction is the only case where a sender deletes; \`ACTION\` outranks everything in the recipient's queue, so a withdrawn ACTION is not clutter, it is real work being pushed down the list. *(Adopted 2026-07-25 from \`z2w-starter-kit\`'s 2026-07-15 proposal on Kerry's observation that finding messages addressed to a project was too hard — one session had to grep a 705 KB file across three sections to find a directive aimed at it — and \`z2w-agent-command-center\`'s independent endorsement after the same failure bit it. The Command Center renders this block as the phone-first "addressed to you" queue.)*
375
375
  - **ANSWERING a \`[→ you]\` question counts as "writing something addressed to another project" — so the reply ALSO needs a \`## 📥 Needs attention\` line, in the ASKER's file (v0.1.21).** This is the case the rule above always covered in principle and that everyone (including the maintainer) reads past in practice, because replying *feels* like closing an item rather than sending one. It isn't. Per §8.2 the thread lives in **your** file, which means **the asker has nothing in their own file to tell them an answer arrived** — they filed into your file and then never look at it again. Posting the \`↳\` is not delivering it.
376
376
  \`\`\`
377
377
  - 2026-07-27 · z2w-agent-coordination · FYI · RULING on your \`## Integrations\` question — answered in full on the thread in my file · projects/z2w-agent-coordination.md §Open questions
@@ -409,6 +409,11 @@ This project participates in the Z2W cross-project coordination bulletin.
409
409
  **The trigger is "carries cross-project signal," NOT "committed code" (v0.1.15).** A decision, a heads-up, a capability→home mapping, a naming or scope change, a new build-target, an answered question, a discovered gotcha — all qualify, and **synthesis, audit, and planning sessions routinely commit zero code yet carry the highest cross-project value.** An agent that gates Tier 2 on \`git log\` says nothing exactly when it has the most to say. Skip Tier 2 only when the session genuinely produced nothing anyone else would act on (pure local exploration with no outcome) — and Tier 1 still runs even then. *(Adopted 2026-07-25 from \`z2w-starter-kit\`'s 2026-07-11 ask on Kerry's instruction, after a zero-commit \`z2w-forms\` extraction audit generated a new build-target, a Kerry decision, a delivery model, a naming fix, and heads-ups landing on three other projects — none of which a code-gated wrap-up would have published.)*
410
410
  - **Keep \`## Integrations\` + your Live status current — a never-ask standing step, exactly like \`## Current focus\` (v0.1.14).** If this session changed how this project relates to another Z2W app — it started consuming an engine/service, stopped using one, or became a provider another app now depends on — update your file's \`## Integrations\` edges. If the project's lifecycle changed — scaffolded → live in prod, went dormant, retired — update the **Live status** line and its date. This is the capture mechanism behind the ecosystem dependency map + live-status badges on \`agents.z2w.us\`; a stale edge or status silently misleads every other agent (real 2026-07-20 miss: an audit called a LIVE engine "unbuilt" because no single place recorded its status). Decide and do it — do not ask. Absent section = nothing to report yet; create it lazily the first time you have an edge or a status to record. Schema + conventions in §8.10.
411
411
  - **Size discipline (v0.1.11):** before appending, if \`projects/{this-project}.md\` is approaching ~200 KB (the point where agents can no longer \`Read\` it in one call), trim FIRST — archive old \`## Active sessions\` and \`## Recent commits\` entries and resolved \`## Open questions\` threads into \`projects/{this-project}-archive.md\` (a separate, commit-flagged operation). Keep your live file readable whole. \`## Current focus\` is rewritten in place (never appended), which is the main thing that keeps a project file from growing without bound — never let a single field accumulate a multi-session history.
412
+ - **Your project file is a COORDINATION SURFACE, not a log (v0.1.22).** The test, and it is a good one: **"would another agent load this file to answer a question?"** Session recaps, npm publish state, test counts, defect post-mortems and build narrative all fail it — that is \`STATUS.md\` / \`CHANGELOG.md\` content in your own repo, and duplicating it here makes ~40 other agents pay for it on every read while approximately none of them need it. Two bright lines:
413
+ 1. **\`## Current focus\` and \`## Active sessions\` answer "what is this project doing, and is it alive" — nothing more.** Current focus ≲1.5 KB (it renders on Kerry's phone); each Active-sessions entry ≲400 bytes — one line: what shipped, the test count, a commit SHA. The narrative goes in your own repo, where you are already writing it.
414
+ 2. **Archive a thread in the same commit that resolves it.** Not in a later sweep. If you post a closing \`↳\`, you move the thread. This is the only self-enforcing rule of the set, because the agent that knows a thread is done is the agent closing it. *(Do NOT auto-archive on "reply older than N days" — a reply is not a resolution, and several of the longest-running live threads in this bulletin have replies. Resolution is a judgment, so the action belongs at the moment of judgment.)* **"Resolved" means BOTH parties are done — never archive a thread you are the ASKER on until the answer lands.** The live-ness signal for a thread you are waiting on is a \`## 📥 Needs attention\` line in *someone else's* file, which you cannot see from your own, so "no live line in my queue" is not evidence the thread is closed. *(Found the hard way 2026-07-29: \`z2w-starter-kit\`'s own careful trim — which explicitly spared every thread with a live queue line — archived the very thread carrying its unanswered proposal, because the waiting line was in the maintainer's queue.)*
415
+
416
+ **Enforced at push, not by good intentions:** \`.github/workflows/file-size-check.yml\` runs \`scripts/check-file-sizes.sh\` on every push touching \`projects/**.md\` or \`global.md\` — hard-fail over 256 KB, warning over 200 KB, \`*-archive.md\` exempt by design. *(Adopted 2026-07-29 from \`z2w-starter-kit\`'s 2026-07-27 proposal, made after it trimmed its own file three times in one month and re-grew it ~70 KB in a single session. Its rule 3 — a per-session soft byte budget — is deliberately NOT adopted: it fails for exactly the reason the v0.1.11 rule above fails, namely that it asks an agent to measure mid-task, and agents do not measure mid-task. Push is the one moment measurement is automatic and free. The check belongs to the repo it guards, so the maintainer wrote it rather than handing the offer back.)*
412
417
  - \`git commit -m "{this-project}: {summary}"\` (see §8.2 for agent-identifier format in commit messages and session entries) and \`git push\`.
413
418
  - If push fails due to concurrent write from another session: \`git pull --rebase\`, resolve any conflicts (they should be rare — append-only within sections), retry push.
414
419
  - **Local auto-push hooks:** if your project has a post-commit hook that auto-pushes, expect it to race your explicit \`git push\` and grab the ref lock first. The commit still lands — verify with \`git log origin/main\` rather than re-pushing.
@@ -466,7 +471,11 @@ const SEO_BASELINE_BODY = `### SEO baseline (non-WP web UI)
466
471
  > **Scope:** applies to every Z2W non-WP web app with a public indexable surface. Does NOT apply to: WordPress sites (RankMath), API-only services with no HTML surface, CLI libraries, protocol repos, Cloudflare Workers without a public HTML response.`;
467
472
  const EMAIL_SERVICE_BODY = `### Email service selection (any project that will send mail)
468
473
 
469
- > **Email service:** Kerry's portfolio has FOUR sanctioned email services covering distinct sweet spots — FluentCRM (WP marketing/CRM), Amazon SES (cheap high-volume transactional), Resend (developer-friendly transactional + NextAuth magic links + React Email), Cloudflare Email Service (Workers-native send/receive). Before wiring any email feature in this project — magic-link auth, transactional notification, marketing broadcast, anything — load [[email-service-router]] and walk the decision matrix. Do NOT introduce a fifth service (SendGrid, Mailgun, Postmark, Mailchimp, MailerSend, Brevo/Sendinblue, etc.) — the router skill explains why and routes to the right one of the four.`;
474
+ > **Email service:** Kerry's portfolio has FOUR sanctioned email services covering distinct sweet spots — FluentCRM (WP marketing/CRM), Amazon SES (cheap high-volume transactional), Resend (developer-friendly transactional + NextAuth magic links + React Email), Cloudflare Email Service (Workers-native send/receive). Before wiring any email feature in this project — magic-link auth, transactional notification, marketing broadcast, anything — load [[email-service-router]] and walk the decision matrix. Do NOT introduce a fifth service (SendGrid, Mailgun, Postmark, Mailchimp, MailerSend, Brevo/Sendinblue, etc.) — the router skill explains why and routes to the right one of the four.
475
+ >
476
+ > **🔐 If this project uses magic-link auth, the Host allowlist is NOT optional — and the rule you already know is only half of it.** The Z2W rule is \`trustHost: true\` with **no** \`AUTH_URL\` (a fixed \`AUTH_URL\` breaks tenant vanity domains — that stands, do not reverse it). But "no \`AUTH_URL\`" also means **"accept ANY Host"** until you add an allowlist: Auth.js derives every magic-link URL from the incoming \`Host\` header with nothing validating it, so an attacker who requests a link for **someone else's** address on a forged Host causes that person to receive a genuine, correctly-signed email pointing at the attacker's server. **So: keep \`trustHost: true\`, keep \`AUTH_URL\` unset, AND validate the host** inside \`sendVerificationRequest\` against a \`CANONICAL_HOSTS\` env allowlist plus your DB's tenant domains. **Fail CLOSED — send nothing;** falling back to the canonical host is an enumeration oracle. **Unset \`CANONICAL_HOSTS\` must mean nobody, not everybody.** Allow anything when \`NODE_ENV !== "production"\` so preview deployments and localhost keep working. Copy-paste recipe: **[[z2w-magic-link-auth]] §0 rule 2b**.
477
+ >
478
+ > *Why this is spelled out here rather than left to the skill: \`audit-engine\` measured 10 Z2W repos on 2026-07-29 running \`trustHost: true\` with no \`AUTH_URL\` and only 2 validating the host. Several cite the rule by section number in a code comment — they followed the guidance exactly, and the guidance was missing its companion clause. **Honest scope: a guidance gap with one confirmed HIGH precedent (\`event-engine\` H-1, remediated with exactly this allowlist), not 10 confirmed vulnerabilities** — exploitability was not tested per repo.*`;
470
479
  const MODERATION_BODY = `### Moderation baseline (user-generated content)
471
480
 
472
481
  > **This project accepts user-generated content, so trust & safety is an at-instantiation decision — not a Phase-8 afterthought.** Before building the first surface where one user's input is shown to others (posts, comments, profiles, listings, direct messages), load [[moderation-system]] and follow its shape. It is battle-tested across two live Z2W apps (z2w-social shipped it Step 8; event-engine built the second reference implementation) — do NOT hand-roll a per-content-type moderation system.
package/dist/writer.js CHANGED
@@ -405,6 +405,18 @@ export function parseScaffoldInputs(json) {
405
405
  }
406
406
  inputs.hasObservability = obj["hasObservability"];
407
407
  }
408
+ // Optional: whether the incoming Host selects the tenant (a HOST-ROUTED
409
+ // multi-tenant app). Defaults to false (single-tenant). When true, the nextjs
410
+ // scaffolder omits the single-destination *.vercel.app alias redirect — wrong
411
+ // shape, there is no one canonical domain — and emits a `middleware.ts` host
412
+ // guard that 404s a known-non-canonical production host instead. Ruling
413
+ // 2026-07-30 across org-hq / site-control / z2w-member-match.
414
+ if (obj["hostRoutedTenancy"] !== undefined) {
415
+ if (typeof obj["hostRoutedTenancy"] !== "boolean") {
416
+ throw new WriterError(`--input field "hostRoutedTenancy" must be a boolean, got ${typeof obj["hostRoutedTenancy"]}.`);
417
+ }
418
+ inputs.hostRoutedTenancy = obj["hostRoutedTenancy"];
419
+ }
408
420
  // Optional: the verbatim instantiation prompt, recorded on the Airtable row.
409
421
  // The --input path has no brief to capture, so callers may supply it here;
410
422
  // when omitted, the Airtable write reminds the agent to add it by hand.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zero2webmaster/starter-kit",
3
- "version": "0.5.8",
3
+ "version": "0.6.0",
4
4
  "description": "Node CLI to scaffold new Z2W projects from canonical Templates + AGENTS.md.",
5
5
  "author": {
6
6
  "name": "Dr. Kerry Kriger",