diff --git a/.github/workflows/cloudflare-release.yml b/.github/workflows/cloudflare-release.yml new file mode 100644 index 0000000..f1a8026 --- /dev/null +++ b/.github/workflows/cloudflare-release.yml @@ -0,0 +1,35 @@ +name: Prepare Cloudflare release +on: + workflow_dispatch: + inputs: + profile: + description: Checked-in installation profile (not the placeholder example) + required: true + type: string +permissions: + contents: read +jobs: + prepare: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - uses: oven-sh/setup-bun@v2 + with: + bun-version: 1.4.3 + - uses: actions/setup-node@v4 + with: + node-version: 22 + - run: bun install --frozen-lockfile + - run: bun run check + - run: bun run test:workerd + - name: Prepare reviewable release (offline) + env: + PROFILE: ${{ inputs.profile }} + run: bun run cloudflare:prepare "$PROFILE" cloudflare-release > cloudflare-review.json + - uses: actions/upload-artifact@v4 + with: + name: cloudflare-release-${{ github.sha }} + path: | + cloudflare-release/ + cloudflare-review.json + if-no-files-found: error diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 8da7dbc..1c61d8b 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -5,6 +5,20 @@ on: permissions: contents: read jobs: + infrastructure: + runs-on: ubuntu-24.04 + defaults: + run: + working-directory: infra/cloudflare + steps: + - uses: actions/checkout@v4 + - uses: opentofu/setup-opentofu@v1 + with: + tofu_version: 1.13.2 + - run: tofu init -backend=false -input=false + - run: tofu fmt -check -recursive + - run: tofu validate + - run: tofu test verify: runs-on: ubuntu-24.04 steps: diff --git a/README.md b/README.md index b434364..a1bb1e7 100644 --- a/README.md +++ b/README.md @@ -38,8 +38,10 @@ Documentor has matching opt-in installation through `publish.site.concourse`. The API uses `/__concourse/` on the publication's own origin. Configure Access, site membership, a migrated D1 database and a Worker route before enabling it. -There is no production debug-login option. See the deployment guide for the -owner-selected `helix.synaptiq.tools` target and staged rollout. +There is no production debug-login option. Use the small [Terraform foundation](infra/cloudflare/README.md) and +[Wrangler release procedure](docs/helix/05-deploy/first-slices.md) for the +owner-selected `helix.synaptiq.tools` target. `cloudflare:prepare` works offline; +`cloudflare:deploy` requires a reviewed release digest and never runs migrations. Install the repository pre-commit gate with `git config core.hooksPath .githooks`. Use the installed HELIX catalog; methodology templates are not vendored here. diff --git a/deploy/cloudflare/profile.example.json b/deploy/cloudflare/profile.example.json new file mode 100644 index 0000000..086961c --- /dev/null +++ b/deploy/cloudflare/profile.example.json @@ -0,0 +1,16 @@ +{ + "name": "helix-concourse", + "account_id": "REPLACE_ACCOUNT_ID", + "compatibility_date": "2026-08-06", + "workers_dev": false, + "preview_urls": false, + "routes": [ + { "pattern": "helix.synaptiq.tools/__concourse/*", "zone_id": "REPLACE_ZONE_ID" } + ], + "vars": { + "SITES": "[{\"id\":\"helix\",\"origin\":\"https://helix.synaptiq.tools\",\"issuer\":\"https://REPLACE_TEAM.cloudflareaccess.com\",\"audience\":\"REPLACE_ACCESS_AUDIENCE\",\"domains\":[\"synaptiq.ai\"],\"emails\":[]}]" + }, + "d1_databases": [ + { "binding": "DB", "database_name": "helix-concourse-comments", "database_id": "REPLACE_DATABASE_ID" } + ] +} diff --git a/docs/helix/00-discover/owner-input.md b/docs/helix/00-discover/owner-input.md index 0b4f058..a050c56 100644 --- a/docs/helix/00-discover/owner-input.md +++ b/docs/helix/00-discover/owner-input.md @@ -45,3 +45,16 @@ special cases from reusable protected publishing. Goal two is inline comments on HELIX microsites for logged-in users. Existing domains and infrastructure resource identities must survive refactoring. Provider coverage beyond the existing Access configuration remains separately qualified. + +## Hosting and deployment direction — 2026-10-29 + +The owner requested a Batten-hosted Concourse backend plugin on Databricks Apps +and a separate static-content plugin serving a complete publication directory +from a volume behind the Apps proxy. This is a required additional hosting +profile; Batten integration and identity/storage qualification remain design work. + +For Cloudflare, the owner selected a Wrangler profile coupled with a very small +reusable Terraform module that can be consumed by Synaptiq infrastructure. +Application deployment must be repeatable and explicitly reviewed. Shared +infrastructure stays with its existing owner; preparing this package does not +authorize applying infrastructure, reading credentials or running migrations. diff --git a/docs/helix/02-design/architecture.md b/docs/helix/02-design/architecture.md index 4097bf2..dfb6c89 100644 --- a/docs/helix/02-design/architecture.md +++ b/docs/helix/02-design/architecture.md @@ -43,6 +43,8 @@ Existing infrastructure owns Access/DNS; each publication owns its site inputs. | src/browser | Inline UI and same-origin client | mountComments | shared, DOM | Server, CLI, Node/Bun | | src/cli | Protected-host check and distribution installation | CLI | Bun/Node, shared | server/browser internals | | infra/protected-publication | Pages/Access/DNS resource composition | Module inputs/outputs | Cloudflare provider | Site-name branching | +| infra/cloudflare | Installation foundation: publication module and protected D1 lifetime | Terraform inputs and installation output | protected-publication, Cloudflare provider | Worker code, routes or deployment credentials | +| scripts/cloudflare | Validate Wrangler profile, prepare and verify release bytes, explicit deployment command | CONTRACT-001 deployment surface | server/config public validator, Node/Bun, pinned Wrangler CLI | Browser internals, automatic migrations, Terraform mutation | **Integration Owners**: server/auth.ts owns Access translation; server/store.ts owns D1 SQL; browser owns DOM/UI; infra module owns provider composition. @@ -63,6 +65,27 @@ qualify separate profiles. Cloud backup/restore and retention need a production runbook and owner policy before real data admission. No cloud resources are provisioned by this local build. +The supported Cloudflare installation entry point is `infra/cloudflare`. +Terraform owns Pages project/domain, DNS, Access and D1 lifetime. Wrangler owns +Worker code, bindings and `/__concourse/*` routes exclusively. Existing login +providers are referenced by ID, never recreated. The earlier +`infra/collaboration-worker` is a legacy alternative and must not manage a +Wrangler-owned Worker or route. + +An installation keeps one explicit Wrangler JSON profile. Preparation runs +offline, validates the selected audience/hosts, disables workers.dev and version +URLs, and packages built Worker/configuration/migration bytes with hashes. The +separate deployment command requires the reviewed release digest and rechecks +all bytes before invoking the pinned Wrangler. It does not apply migrations or +publish static content. Its summary is desired configuration, not a cloud-state +diff; an initial infrastructure plan and live protection checks remain required. +The consumer's existing static build/sign/upload pipeline owns content releases. + +Databricks Apps/Batten is an additional required hosting profile, with separate +backend and volume publication plugins. Cloudflare tooling does not establish +that profile's identity, storage or proxy guarantees and is not a portable +backend contract. No Batten runtime support is claimed by this package. + ## Data Flow 1. Static page loads the opt-in component with site, source resource and revision. @@ -101,3 +124,10 @@ validation. CONTRACT-001 owns the native v1 protocol; this local profile does no claim UMF projection, generation or action qualification. Append-only SQL is the persistence authority; unknown request members are rejected, never erased from UMF documents. No UMF document is ingested by this slice. + +Deployment uses Wrangler 4.156.0's native configuration schema, not a new UMF +model. The preparer accepts a bounded subset and fixes bundle/migration paths; +the actual pinned Wrangler dry-run verifies vendor compatibility. The release +manifest is local distribution-integrity metadata, with no UMF identity, action +or transaction semantics. The earlier UMF inspection supplies no appropriate +replacement for this provider-specific configuration. diff --git a/docs/helix/02-design/contracts/CONTRACT-001-first-slices.md b/docs/helix/02-design/contracts/CONTRACT-001-first-slices.md index b4c985e..1f0ce32 100644 --- a/docs/helix/02-design/contracts/CONTRACT-001-first-slices.md +++ b/docs/helix/02-design/contracts/CONTRACT-001-first-slices.md @@ -88,6 +88,42 @@ path qualify, never substring matches in query parameters. `install-hugo.ts ## Precedence and Compatibility +### Cloudflare deployment surface + +`infra/cloudflare` composes `infra/protected-publication` with a D1 database +whose lifecycle prevents destruction. It accepts that module's publication +inputs and returns `installation` (account_id, zone_id, hostname, worker_name, +database_id, database_name, audience). It MUST NOT own Worker code, bindings or +routes. The consumer pins a reviewed source revision and supplies the existing +identity-provider IDs. Neither module applies SQL or reads credentials itself. + +`deploy/cloudflare/profile.example.json` demonstrates the native Wrangler +configuration subset. Profiles are JSON (comments are not accepted by the +preparation tool). Exactly one DB binding and one or more unique site routes are +required. Each route MUST match a configured site's HTTPS host and exactly +`/__concourse/*`, with an explicit zone_id. Unknown settings, environments, +assets, build hooks and alternative entry points refuse. The runtime's SITES +validator supplies membership and identity validation. The compatibility date +is pinned to the tested first-slice profile; workers_dev and preview_urls MUST +be false. Profiles contain IDs and policy, never credentials. + +`bun run cloudflare:prepare ` reads the +profile, built `dist/worker.js` and committed SQL files. It creates a new release +directory with `worker.js`, normalized `wrangler.json`, `migrations/*.sql`, and +`release.json`. It refuses existing output directories, placeholders and unsafe +routes. The manifest includes source commit, pinned Wrangler version, per-file +SHA-256 digests and a release digest over its canonical payload. Preparation +does not contact Cloudflare or inspect credentials. + +`bun run cloudflare:deploy --approve ` MUST +verify the digest and all file hashes, reject extra files and symlinks, validate +configuration again and require the installed Wrangler version to match before +invoking `wrangler deploy --config /wrangler.json`. No automatic SQL, +Terraform apply, static publication upload or rollback is permitted. Wrong or +missing approval, changed bytes or invalid profile aborts before Wrangler starts. +The digest is a review/integrity boundary, not a signature or cloud-state plan. +The command uses the invoking operator's separately authorized credential. + Unknown protocol/config version or fields refuse. Site host/config and verified principal take precedence over browser fields. Wire v1 is separate from any UMF extension or native action profile. Additive wire changes need explicit version diff --git a/docs/helix/04-build/evidence/cloudflare-profile.json b/docs/helix/04-build/evidence/cloudflare-profile.json new file mode 100644 index 0000000..1828bd5 --- /dev/null +++ b/docs/helix/04-build/evidence/cloudflare-profile.json @@ -0,0 +1,41 @@ +{ + "date": "2026-10-29", + "scope": "Wrangler release profile and reusable Terraform foundation; no live deployment", + "versions": { + "bun": "1.4.3", + "node": "26.12.1 (local; CI selects 22)", + "wrangler": "4.156.0", + "opentofu": "1.13.2", + "cloudflare_provider": "5.17.0" + }, + "checks": { + "bun run check": "passed: strict types, lint, boundaries, build, 17 tests / 148 assertions", + "Wrangler deploy --dry-run": "passed against real prepared Worker bundle and explicit bindings; no credentials supplied; release hashes unchanged", + "bun run test:workerd": "passed existing local workerd/D1 integration", + "tofu validate": "passed, backend disabled; cached provider, local plugin execution", + "tofu test": "passed one mocked-provider plan test; no cloud-state plan or apply", + "tofu fmt -check -recursive infra/cloudflare": "passed", + "HELIX architecture and CONTRACT-001": "passed, zero findings", + "workflow YAML and git diff --check": "passed" + }, + "limits": [ + "No cloud credentials read, infrastructure plan/apply, deployment, or remote SQL executed.", + "Hosted CI is pending; local native runtime is not live Access qualification.", + "Existing state adoption, actual installation IDs, remote migration review, restore/retention policy and authenticated admission probes remain before production use.", + "Batten/Databricks Apps profile is recorded owner intent, not implemented or qualified here." + ], + "sha256": { + "scripts/cloudflare/profile.ts": "6da3fc36b1965a23c486be03512d18a6d761213cf92b12715fa1fd0e8e1602cc", + "scripts/cloudflare/release.ts": "e49d11531b8643960f0da4d956eb0e33c609765dfb8bb276439600607a8f93f1", + "tests/cloudflare.test.ts": "95598929b72cc237f730f45180d5f8c896cca0e162e6be9add53478b6b052f66", + "deploy/cloudflare/profile.example.json": "e18b04696b54a2e8efb7049ac82c1d714119ae62fa88ebf17c6ea00c7b760467", + ".github/workflows/cloudflare-release.yml": "cf5d22767f18df3da2c17f575386403e66054dd20903d15416dfe04c88c2d0ca", + ".github/workflows/test.yml": "42cfb544831aea6d2aa248a6bca0705abc14138c3e66e55eff03bb615c4bdbd5", + "infra/cloudflare/main.tf": "49f6803c6449139438d8ef4f1f34427ce69e70d18bc711fa27f47d84a8fca265", + "infra/cloudflare/variables.tf": "8df21afae858b3ac869efc54098d2f8371a49b63642cccb41db618609aa4dc9f", + "infra/cloudflare/versions.tf": "c04e2e72d3ba27187accd645f0f27e7a6791ee299b7f6b41702cd540a31d67ab", + "infra/cloudflare/tests/foundation.tftest.hcl": "46a21e609db4c436df42d8f603558517dc322c0bfd977046bcce92bf8fe0465e", + "package.json": "0b59bc99c5f9d14b85b4d77a9bdbc007b5871df6dcc5177864f83cb9eec23bae", + "bun.lock": "aff1f2017e1bf71977bcbeaa6803af2f600d0f44fdd62af202152878af518a40" + } +} diff --git a/docs/helix/04-build/first-slices-plan.md b/docs/helix/04-build/first-slices-plan.md index 4f8771b..8e0ba7b 100644 --- a/docs/helix/04-build/first-slices-plan.md +++ b/docs/helix/04-build/first-slices-plan.md @@ -46,7 +46,19 @@ login, validation/error/replay states covered. Destructive actions are absent. Service diagnostics contain only generic outcome/status; no OTel receiver integration is claimed. Add OTel wiring before broader production operations. -## Observed results +## Cloudflare packaging follow-up + +Owner selected Wrangler plus a minimal reusable Terraform foundation. Implement +`infra/cloudflare`, an example native Wrangler profile and offline preparation / +explicit digest-approved deployment commands. Test route/profile refusal, +artifact tampering and approval failure before any subprocess invocation; run +the actual pinned Wrangler dry-run against a prepared bundle. Validate the +module against Cloudflare v5 without a backend or credentials. Keep migrations, +existing-state adoption, live protection verification and production data +admission separately reviewed. No change to another repository is needed to +prepare the consumable module and example. + +## Observed first-slice results See evidence/first-slices.json for source hashes, scoped passing results and open cloud gates. The actual Worker bundle passes local D1 execution; real HELIX diff --git a/docs/helix/05-deploy/first-slices.md b/docs/helix/05-deploy/first-slices.md index 00e580c..a216953 100644 --- a/docs/helix/05-deploy/first-slices.md +++ b/docs/helix/05-deploy/first-slices.md @@ -1,27 +1,158 @@ -# First deployment: HELIX protected mirror - -Owner selected `helix.synaptiq.tools` with existing Synaptiq Google Workspace -login on 2026-10-29. Source changes span Concourse, infrastructure, Entropy -Exchange and HELIX. Each consumer must pin the reviewed Concourse commit. - -1. Build Concourse with the lockfile and run `bun run check` plus browser proof. -2. In infrastructure, review a saved plan for the generic module state moves, - new `helix-internal` Pages/Access/domain and optional collaboration runtime. - Playbooks must have no resource replacement. Supply a reviewed Worker bundle - and the exact Access team issuer through normal infrastructure configuration. -3. Apply only the reviewed plan after authorization. The D1 store has destruction - protection. It is initially empty; use the committed migration with Wrangler - only after separately approving database initialization. Do not admit private - reader data until retention/export/restore and abuse controls are settled. -4. Build HELIX's source with pinned Concourse assets, existing signing pipeline, - baseURL `https://helix.synaptiq.tools/` and comments enabled. The public GitHub - Pages build leaves comments disabled. Upload the private build to - `helix-internal` through the configured deployment credential. -5. Verify Google login, logout/expiry, all origin/preview/custom hosts and private - assets. Then post/reply/reload beside a real section, recover an interrupted - write and verify cross-site/anonymous denials. Local signatures and SQLite - tests do not qualify this deployed behavior. - -Rollback disables comments/redeploys the previous Worker/static artifact; retain -D1. Reverse state moves only with an explicit reviewed infrastructure plan. -No automated deletion of comments or schema rollback is included. +# Cloudflare deployment: HELIX and reusable installations + +The owner selected `helix.synaptiq.tools` with existing Synaptiq Google Workspace +login, then chose Wrangler plus a small reusable Terraform module. This guide +covers preparation and explicit operations. Nothing here establishes a live +Cloudflare installation or authorizes an apply, credential read or migration. + +## Ownership + +| Owner | Resources / operation | +|---|---| +| Existing infrastructure, using `infra/cloudflare` | Pages project (optional creation), Pages custom domain, DNS, Access application/policy, D1 database lifetime | +| Concourse Wrangler profile | Worker code, bindings, exact `/__concourse/*` routes, disabled workers.dev/version URLs | +| Publication's existing pipeline | Build/sign static content and upload it to the selected Pages project | +| Explicit database operation | Review and apply SQL migrations independently of code deployment | + +The Terraform module references existing login-provider IDs. It has no backend, +provider credentials, Worker bundle or per-site source branches. D1 has +`prevent_destroy`. Do not manage the same Worker/routes through the legacy +`infra/collaboration-worker` module and Wrangler. + +## 1. Review the infrastructure foundation + +Copy the short [module example](../../../infra/cloudflare/README.md) into the +infrastructure root and pin its source to a reviewed immutable Concourse commit. +Use the infrastructure repository's existing account, zone and Google provider +references. The module exports one `installation` object with the IDs required +by the Wrangler profile. + +For existing resources, add explicit state moves/imports in that root. Review a +saved Terraform/OpenTofu plan: existing Playbooks resources must have no +replacements, deletions or changed admission policy. Do not mix this adoption +with a production refactor. Apply only the reviewed plan after authorization. +There is no need to give Concourse the infrastructure repository's state access. + +New empty Pages origins can exist before upload; do not upload private bytes +until the production, wildcard-preview and custom origins are protected. A +successful plan/apply is not proof of admission behavior. + +## 2. Keep one explicit installation profile + +Copy `deploy/cloudflare/profile.example.json` to an installation file, such as +`deploy/cloudflare/helix.json`. Replace placeholders with the module's output, +the existing Access team issuer and the intended site's explicit membership. +These IDs/policy values are not credentials. A profile can be kept in the public +repository only when its hostnames and membership policy are suitable for public +source; otherwise prepare it in the consuming repository or locally. + +Profiles use JSON and the pinned Wrangler configuration subset in CONTRACT-001. +There are no environment inheritance rules, build hooks or automatic resource +creation. The preparer supplies the fixed bundle and migration paths. One +Worker can have multiple configured site routes, with one audience/membership +entry per site. Terraform foundation calls remain per publication; reuse one +installation's D1 for that shared Worker rather than allocating an unused +second database. Additional publication-only foundations can use +`infra/protected-publication` directly. + +Review the exact account, database ID, issuer, audience and membership against +the infrastructure outputs. Every route must be an exact configured hostname +plus `/__concourse/*`; broad and foreign-host routes refuse. Alternate Worker +origins are disabled. Full private-site protection is the Terraform default; +`access_path = "/__concourse"` is for deliberately public static publications. + +## 3. Prepare and review a release offline + +Use the reviewed Concourse checkout, Bun 1.4.3 and Node 22+: + +```sh +bun install --frozen-lockfile +bun run check +bun run test:workerd +bun run cloudflare:prepare deploy/cloudflare/helix.json /tmp/helix-release +``` + +The output directory must not exist. Preparation makes no Cloudflare calls and +reads no credentials. It packages the built Worker, normalized `wrangler.json` +and SQL files with a `release.json` manifest and prints a review summary and +release digest. The commit is provenance; file hashes identify the actual built +bytes, including any local changes. Review those changes before approval. + +Inspect the summary and packaged configuration, Worker artifact and SQL. Keep +the previous release and recorded deployed Worker version. The summary describes +desired configuration; it is not a Terraform-style remote-state diff. Compare +existing Worker settings/routes on initial adoption and when changing them. + +The manual **Prepare Cloudflare release** GitHub workflow performs the same +checks and uploads the release plus review summary. It has read-only repository +permissions, no deployment secret and no cloud deployment step. To deploy its +artifact, check out the workflow's exact commit, install its lockfile and use +the extracted release directory. Never approve a digest supplied by an +unreviewed artifact without inspecting its contents. + +## 4. Initialize storage only after separate approval + +List pending remote D1 migrations using the packaged configuration through the +normal authenticated operator process. Review the SQL, pending migration set, +backup/export/restore procedure and data policy before approving changes. For +an approved initialization, use the installed pinned Wrangler: + +```sh +bunx --no-install wrangler d1 migrations apply DB --remote --config /tmp/helix-release/wrangler.json +``` + +This is a real mutation and is not run by preparation or deployment. Do not +admit private reader data until retention/export/restore and abuse controls are +settled. Later schema changes require a reviewed compatibility and recovery +plan; application rollback does not roll back D1. + +## 5. Explicitly deploy the reviewed artifact + +After approval, supply the exact printed digest: + +```sh +bun run cloudflare:deploy /tmp/helix-release --approve REVIEWED_RELEASE_DIGEST +``` + +The command rechecks the manifest, every packaged byte, profile and pinned +Wrangler/lockfile before invoking Wrangler. Missing approval, placeholders, +changed files, extra files, symlinks and unsafe profiles abort before Wrangler +starts. It deploys only Worker code/bindings/routes; SQL and static content stay +separate. The invoking operator supplies a separately authorized, scoped +Cloudflare credential through the normal Wrangler mechanism. Never store it in +the profile or artifact. The digest is an integrity/review check, not a signature +or a substitute for operator authorization. + +Build HELIX with pinned Concourse assets, its signing pipeline, baseURL +`https://helix.synaptiq.tools/` and comments enabled. The public GitHub Pages +build leaves comments disabled. Its existing content pipeline uploads the +protected output to `helix-internal`; the Concourse runtime release does not. + +## 6. Verify before enabling real use + +Run the shared publication probes for production/custom/preview origins, +HTML/assets/search/downloads. Verify Google login, logout/expiry and direct API +access. Then post/reply/reload beside a real section, recover an interrupted +write and verify cross-site/anonymous denials. Local JWT/SQLite and Wrangler +`--dry-run` checks do not qualify deployed Access behavior or retention/restore. +Record the deployment/version ID and probe results alongside the release digest. + +## Rollback + +Disable the site's comments integration or redeploy the retained previous +release through the same review/digest procedure. Confirm the old application's +schema compatibility first. Retain D1 and its data. A Cloudflare Worker rollback +alone does not restore database schema or external infrastructure configuration; +check routes/bindings and rerun admission probes. Static content rollback belongs +to its existing signed publication pipeline. No automatic destruction or reverse +migration is provided. + +## References and other hosts + +The native [Wrangler configuration](https://developers.cloudflare.com/workers/wrangler/configuration/) +is the source of truth for Worker settings. [Worker versions and deployments](https://developers.cloudflare.com/workers/versions-and-deployments/) +explain why upload, activation and database recovery are distinct operations. + +Batten/Databricks Apps is a separate required host profile: collaboration backend +plugin plus a volume-backed static publication plugin behind the Apps proxy. +This Cloudflare package does not claim to implement or qualify that profile. diff --git a/docs/helix/README.md b/docs/helix/README.md index 9cc4873..fa603bd 100644 --- a/docs/helix/README.md +++ b/docs/helix/README.md @@ -30,6 +30,13 @@ and inline section comments. [Deployment](05-deploy/first-slices.md) covers the cross-repository rollout; [execution evidence](04-build/evidence/first-slices.json) qualifies local checks and records open cloud gates. +For Cloudflare adoption, use the small [Terraform foundation](../../infra/cloudflare/README.md) +and [Wrangler release procedure](05-deploy/first-slices.md). Terraform owns +publication infrastructure and D1 lifetime; Wrangler owns application code, +bindings and routes. Preparation is offline, deployment requires the reviewed +release digest, and SQL stays separately approved. The manual release workflow +only produces an artifact; it cannot deploy. + The first slice provides append-only comments/replies and retry recovery. Editing, moderation, public multi-provider qualification, structured actions and production retention/export/restore remain later scoped work. Session revocation diff --git a/infra/cloudflare/README.md b/infra/cloudflare/README.md new file mode 100644 index 0000000..94c1bbe --- /dev/null +++ b/infra/cloudflare/README.md @@ -0,0 +1,55 @@ +# Cloudflare foundation + +One module call creates the publication's Access application, Pages domain/DNS +and D1 database. Set `create_project = true` for a new direct-upload Pages +project; omit it for an existing project. It references existing login providers. +Wrangler owns the Worker, bindings and routes; this module never uploads code or +executes SQL. Terraform state remains in the consuming infrastructure repository. + +```hcl +module "helix_concourse" { + source = "git::https://github.com/DocumentDrivenDX/concourse.git//infra/cloudflare?ref=REVIEWED_COMMIT" + + account_id = local.cloudflare_account_id + zone_id = local.synaptiq_tools_zone_id + name = "helix-concourse" + hostname = "helix.synaptiq.tools" + pages_project = "helix-internal" + create_project = true + allowed_idps = [local.existing_google_workspace_idp_id] + allowed_email_domains = ["synaptiq.ai"] +} + +output "helix_concourse" { + value = module.helix_concourse.installation +} +``` + +The local names above are illustrative inputs, not claims about Synaptiq's +configuration. Replace the source ref with a reviewed immutable commit. No +provider or backend configuration is embedded. Use the consuming repository's +Cloudflare v5 provider and its normal credentials and saved-plan/apply process. + +The default protects the entire site, including production and wildcard preview +Pages origins. `access_path = "/__concourse"` deliberately leaves static content +public and protects collaboration only. Do not use it for private publications. + +After reviewing/applying the infrastructure plan, copy the `installation` output +into the [Wrangler example](../../deploy/cloudflare/profile.example.json) and +add the existing Access team issuer and explicit site membership. IDs are not +credentials. Follow the [release procedure](../../docs/helix/05-deploy/first-slices.md). + +## Existing resources + +For adoption, use explicit `moved` blocks (or separately reviewed imports) in +the consuming root. Publication resource addresses are nested beneath +`module.helix_concourse.module.publication`; the D1 address is +`module.helix_concourse.cloudflare_d1_database.comments`. A saved plan must show +no replacement/deletion of existing Access, DNS, Pages or D1 resources. Do not +create a parallel Access application for an already protected hostname. + +The old `infra/collaboration-worker` manages Worker code/routes and must not be +combined with this Wrangler profile. If already applied, transferring Worker +ownership needs a separate saved plan that relinquishes those resources without +destroying them, preserves the D1 ID, then verifies Wrangler configuration. +Switching module source alone is not an ownership migration. diff --git a/infra/cloudflare/main.tf b/infra/cloudflare/main.tf new file mode 100644 index 0000000..f0e6167 --- /dev/null +++ b/infra/cloudflare/main.tf @@ -0,0 +1,35 @@ +module "publication" { + source = "../protected-publication" + account_id = var.account_id + zone_id = var.zone_id + name = var.name + hostname = var.hostname + pages_project = var.pages_project + create_project = var.create_project + allowed_idps = var.allowed_idps + allowed_email_domains = var.allowed_email_domains + allowed_emails = var.allowed_emails + session_duration = var.session_duration + access_path = var.access_path +} + +resource "cloudflare_d1_database" "comments" { + account_id = var.account_id + name = "${var.name}-comments" + lifecycle { + prevent_destroy = true + } +} + +output "installation" { + description = "Non-secret IDs to copy into the installation's reviewed Wrangler profile." + value = { + account_id = var.account_id + zone_id = var.zone_id + hostname = var.hostname + worker_name = var.name + database_id = cloudflare_d1_database.comments.id + database_name = cloudflare_d1_database.comments.name + audience = module.publication.audience + } +} diff --git a/infra/cloudflare/tests/foundation.tftest.hcl b/infra/cloudflare/tests/foundation.tftest.hcl new file mode 100644 index 0000000..1d73545 --- /dev/null +++ b/infra/cloudflare/tests/foundation.tftest.hcl @@ -0,0 +1,23 @@ +mock_provider "cloudflare" {} + +run "foundation_without_runtime_ownership" { + command = plan + variables { + account_id = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" + zone_id = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb" + name = "review-concourse" + hostname = "guide.example" + pages_project = "review-publication" + allowed_idps = ["existing-google-provider"] + allowed_email_domains = ["example.org"] + create_project = true + } + assert { + condition = output.installation.worker_name == "review-concourse" && output.installation.hostname == "guide.example" + error_message = "The Wrangler handoff must retain the explicitly selected Worker and hostname." + } + assert { + condition = cloudflare_d1_database.comments.name == "review-concourse-comments" && output.installation.account_id == var.account_id + error_message = "The D1 foundation must use the installation's account and stable database name." + } +} diff --git a/infra/cloudflare/variables.tf b/infra/cloudflare/variables.tf new file mode 100644 index 0000000..4a3a639 --- /dev/null +++ b/infra/cloudflare/variables.tf @@ -0,0 +1,58 @@ +variable "account_id" { type = string } +variable "name" { + description = "Stable Worker name and database-name prefix used by the Wrangler installation." + type = string + validation { + condition = can(regex("^[a-z0-9][a-z0-9-]{0,53}$", var.name)) + error_message = "name must be a lowercase slug of at most 54 characters (leaving room for -comments)." + } +} +variable "pages_project" { + type = string + validation { + condition = can(regex("^[a-z0-9][a-z0-9-]*$", var.pages_project)) + error_message = "pages_project must be a Pages project slug." + } +} +variable "hostname" { + type = string + validation { + condition = can(regex("^[a-z0-9][a-z0-9.-]*\\.[a-z]{2,}$", var.hostname)) + error_message = "hostname must be an explicit lowercase DNS hostname, without a scheme, wildcard or path." + } +} +variable "zone_id" { type = string } +variable "allowed_idps" { + type = list(string) + validation { + condition = length(var.allowed_idps) > 0 + error_message = "Explicit identity providers are required." + } +} +variable "allowed_email_domains" { + type = list(string) + default = [] +} +variable "allowed_emails" { + type = list(string) + default = [] +} +variable "session_duration" { + type = string + default = "24h" +} +variable "access_path" { + description = "Empty protects the whole site; /__concourse protects only collaboration on a public site." + type = string + default = "" + validation { + condition = contains(["", "/__concourse"], var.access_path) + error_message = "Use whole-site protection or /__concourse." + } +} + +variable "create_project" { + description = "Create a new direct-upload Pages project; keep false for existing content pipelines." + type = bool + default = false +} diff --git a/infra/cloudflare/versions.tf b/infra/cloudflare/versions.tf new file mode 100644 index 0000000..081bc16 --- /dev/null +++ b/infra/cloudflare/versions.tf @@ -0,0 +1,6 @@ +terraform { + required_version = ">= 1.9" + required_providers { + cloudflare = { source = "cloudflare/cloudflare", version = "~> 5.0" } + } +} diff --git a/infra/collaboration-worker/README.md b/infra/collaboration-worker/README.md new file mode 100644 index 0000000..2ab42fd --- /dev/null +++ b/infra/collaboration-worker/README.md @@ -0,0 +1,7 @@ +# Legacy Terraform runtime alternative + +This module owns Worker code, bindings, routes and D1. New installations should +use [`infra/cloudflare`](../cloudflare/README.md) with Wrangler owning the +application release. Do not use both to manage the same Worker, routes or D1. +Existing state requires a separately reviewed ownership transfer; no automated +state change or destruction is provided here. diff --git a/infra/protected-publication/README.md b/infra/protected-publication/README.md index 06b0771..667cca0 100644 --- a/infra/protected-publication/README.md +++ b/infra/protected-publication/README.md @@ -1,7 +1,7 @@ # Protected publication module Generic Cloudflare v5 Pages custom-domain, DNS and Access composition. The Pages -project must already exist. Infrastructure owns this module's deployment; content +project may already exist or be created with `create_project = true`. Infrastructure owns this module's deployment; content pipelines upload build output. No caller-specific defaults, cloud credentials, provider registration or deployment is embedded. @@ -18,3 +18,7 @@ custom/Pages/preview hosts and representative asset/index/download routes. Pin the module source to an immutable Concourse revision. Do not use a developer checkout path in production infrastructure. + +For a complete collaboration foundation including D1, prefer the small +[`infra/cloudflare`](../cloudflare/README.md) wrapper and its Wrangler release +profile. This lower-level module remains useful for publication-only adoption. diff --git a/package.json b/package.json index be9cdfa..ce82e03 100644 --- a/package.json +++ b/package.json @@ -8,13 +8,15 @@ "typecheck": "tsc --noEmit", "test": "bun test tests", "check:boundaries": "bun scripts/check-boundaries.ts", - "check": "bun run typecheck && bun run lint && bun run check:boundaries && bun test tests && bun run build", + "check": "bun run typecheck && bun run lint && bun run check:boundaries && bun run build && bun test tests", "dev": "wrangler dev --local", "test:browser": "bun scripts/browser-test.ts", "lint": "biome lint src", "test:workerd": "node scripts/workerd-test.mjs", "build:browser": "bun scripts/build.ts --browser-only", - "test:hugo-browser": "bun scripts/hugo-browser.ts" + "test:hugo-browser": "bun scripts/hugo-browser.ts", + "cloudflare:prepare": "bun scripts/cloudflare/release.ts prepare", + "cloudflare:deploy": "bun scripts/cloudflare/release.ts deploy" }, "dependencies": { "jose": "6.2.14" diff --git a/scripts/cloudflare/profile.ts b/scripts/cloudflare/profile.ts new file mode 100644 index 0000000..3960432 --- /dev/null +++ b/scripts/cloudflare/profile.ts @@ -0,0 +1,69 @@ +import { sites } from '../../src/server/config.ts'; + +export type Profile = { + name: string; account_id: string; compatibility_date: string; + workers_dev: false; preview_urls: false; + routes: { pattern: string; zone_id: string }[]; + vars: { SITES: string }; + d1_databases: { binding: 'DB'; database_name: string; database_id: string }[]; +}; + +function record(value: unknown, keys: string): Record { + if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('Expected configuration object'); + const result = value as Record; + if (Object.keys(result).sort().join(',') !== keys.split(',').sort().join(',')) throw new Error('Unexpected or missing profile settings'); + return result; +} +function match(value: unknown, pattern: RegExp): string { + if (typeof value !== 'string' || !pattern.test(value)) throw new Error('Invalid or placeholder profile value'); + return value; +} +const id = /^[a-f0-9]{32}$/; +const slug = /^[a-z0-9][a-z0-9-]{0,62}$/; + +// A deliberately bounded subset of the pinned native Wrangler configuration. +// main/no_bundle/migrations_dir are fixed by release preparation, never caller hooks. +export function profile(value: unknown): Profile { + const p = record(value, 'name,account_id,compatibility_date,workers_dev,preview_urls,routes,vars,d1_databases'); + match(p.name, slug); match(p.account_id, id); + if (p.compatibility_date !== '2026-08-06' || p.workers_dev !== false || p.preview_urls !== false) throw new Error('Unsupported runtime or public alternate origin'); + const vars = record(p.vars, 'SITES'); + if (typeof vars.SITES !== 'string' || /REPLACE_|PLACEHOLDER/i.test(vars.SITES)) throw new Error('SITES must contain explicit installation values'); + const configured = sites(vars.SITES); + const expected = new Set(configured.map(s => `${new URL(s.origin).hostname}/__concourse/*`)); + if (!Array.isArray(p.routes) || p.routes.length !== expected.size) throw new Error('Every configured site needs one route'); + for (const value of p.routes) { + const route = record(value, 'pattern,zone_id'); + match(route.zone_id, id); + if (typeof route.pattern !== 'string' || !expected.delete(route.pattern)) throw new Error('Unsafe, duplicate or unconfigured Worker route'); + } + if (expected.size) throw new Error('Missing Worker route'); + if (!Array.isArray(p.d1_databases) || p.d1_databases.length !== 1) throw new Error('Exactly one comment database is required'); + const db = record(p.d1_databases[0], 'binding,database_name,database_id'); + if (db.binding !== 'DB') throw new Error('Expected DB binding'); + match(db.database_name, slug); + match(db.database_id, /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/); + if (db.database_id === '00000000-0000-0000-0000-000000000000') throw new Error('Placeholder database'); + // Routes are hostname-based; runtime lookup is exact-origin based. + if (configured.some(s => new URL(s.origin).port !== '')) throw new Error('Cloudflare publication origins must use the default HTTPS port'); + return p as unknown as Profile; +} + +export function wranglerConfig(p: Profile) { + return { ...p, main: 'worker.js', no_bundle: true, + d1_databases: p.d1_databases.map(db => ({ ...db, migrations_dir: 'migrations' })) }; +} + +export function fromWrangler(value: unknown): Profile { + const config = record(value, 'name,account_id,compatibility_date,workers_dev,preview_urls,routes,vars,d1_databases,main,no_bundle'); + if (config.main !== 'worker.js' || config.no_bundle !== true) throw new Error('Release must use the reviewed bundle'); + if (!Array.isArray(config.d1_databases)) throw new Error('Missing database'); + const databases = config.d1_databases.map(value => { + const db = record(value, 'binding,database_name,database_id,migrations_dir'); + if (db.migrations_dir !== 'migrations') throw new Error('Unsafe migrations path'); + const { migrations_dir: _, ...rest } = db; + return rest; + }); + const { main: _, no_bundle: __, ...rest } = config; + return profile({ ...rest, d1_databases: databases }); +} diff --git a/scripts/cloudflare/release.ts b/scripts/cloudflare/release.ts new file mode 100644 index 0000000..30741ce --- /dev/null +++ b/scripts/cloudflare/release.ts @@ -0,0 +1,98 @@ +import { lstat, mkdir, readdir, realpath } from 'node:fs/promises'; +import { resolve, join } from 'node:path'; +import { profile, wranglerConfig, fromWrangler } from './profile.ts'; + +type Manifest = { + format: number; sourceCommit: string; wranglerVersion: string; + lockHash: string; files: Record; digest: string; +}; +const root = resolve(import.meta.dir, '../..'); +const json = (v: unknown) => `${JSON.stringify(v, null, 2)}\n`; +export const hash = (data: string | Uint8Array) => new Bun.CryptoHasher('sha256').update(data).digest('hex'); +function digest(manifest: Omit) { + return hash(JSON.stringify({ format: manifest.format, sourceCommit: manifest.sourceCommit, + wranglerVersion: manifest.wranglerVersion, lockHash: manifest.lockHash, + files: Object.fromEntries(Object.entries(manifest.files).sort(([a], [b]) => a.localeCompare(b))) })); +} +async function fileNames(directory: string, prefix = ''): Promise { + const result: string[] = []; + for (const name of await readdir(join(directory, prefix))) { + const path = prefix ? `${prefix}/${name}` : name; + const stat = await lstat(join(directory, path)); + if (stat.isSymbolicLink()) throw new Error('Release symlinks are forbidden'); + if (stat.isDirectory() && path === 'migrations') result.push(...await fileNames(directory, path)); + else if (stat.isFile()) result.push(path); + else throw new Error('Unexpected release entry'); + } + return result.sort(); +} +export async function prepare(profilePath: string, directory: string): Promise { + const p = profile(await Bun.file(profilePath).json()); + const worker = await Bun.file(join(root, 'dist/worker.js')).bytes(); + const migrations = (await readdir(join(root, 'migrations'))).filter(n => /^\d{4}_[a-z0-9_]+\.sql$/.test(n)).sort(); + if (!worker.length || !migrations.length) throw new Error('Build Worker and supply migrations before preparation'); + const source = Bun.spawn(['git', 'rev-parse', 'HEAD'], { cwd: root, stdout: 'pipe', stderr: 'pipe' }); + const sourceCommit = (await new Response(source.stdout).text()).trim(); + if (await source.exited !== 0 || !/^[a-f0-9]{40}$/.test(sourceCommit)) throw new Error('Cannot identify source commit'); + // No recursive creation: an existing release can never be silently overwritten. + await mkdir(directory); + await mkdir(join(directory, 'migrations')); + await Bun.write(join(directory, 'worker.js'), worker); + await Bun.write(join(directory, 'wrangler.json'), json(wranglerConfig(p))); + for (const name of migrations) await Bun.write(join(directory, 'migrations', name), await Bun.file(join(root, 'migrations', name)).bytes()); + const files: Record = {}; + for (const name of await fileNames(directory)) files[name] = hash(await Bun.file(join(directory, name)).bytes()); + const pkg = await Bun.file(join(root, 'package.json')).json(); + const payload = { format: 1, sourceCommit, wranglerVersion: pkg.devDependencies.wrangler as string, + lockHash: hash(await Bun.file(join(root, 'bun.lock')).bytes()), files }; + const manifest = { ...payload, digest: digest(payload) }; + await Bun.write(join(directory, 'release.json'), json(manifest)); + return manifest; +} +export async function verify(directory: string, approved: string): Promise { + if (!/^[a-f0-9]{64}$/.test(approved)) throw new Error('An explicit reviewed release digest is required'); + if ((await lstat(directory)).isSymbolicLink()) throw new Error('Release symlinks are forbidden'); + const names = await fileNames(directory); + const manifest = await Bun.file(join(directory, 'release.json')).json() as Manifest; + if (Object.keys(manifest).sort().join(',') !== 'digest,files,format,lockHash,sourceCommit,wranglerVersion') throw new Error('Invalid manifest'); + if (manifest.format !== 1 || manifest.digest !== approved || digest(manifest) !== approved) throw new Error('Release approval does not match'); + if (!manifest.files || Object.keys(manifest.files).sort().join('\n') !== names.filter(n => n !== 'release.json').join('\n')) throw new Error('Release file list changed'); + if (!manifest.files['worker.js'] || !manifest.files['wrangler.json'] || !names.some(n => n.startsWith('migrations/'))) throw new Error('Incomplete release'); + for (const name of Object.keys(manifest.files)) { + if (!/^(worker\.js|wrangler\.json|migrations\/\d{4}_[a-z0-9_]+\.sql)$/.test(name)) throw new Error('Unexpected release file'); + if (hash(await Bun.file(join(directory, name)).bytes()) !== manifest.files[name]) throw new Error('Release bytes changed'); + } + fromWrangler(await Bun.file(join(directory, 'wrangler.json')).json()); + const installed = await Bun.file(join(root, 'node_modules/wrangler/package.json')).json(); + if (installed.version !== manifest.wranglerVersion || hash(await Bun.file(join(root, 'bun.lock')).bytes()) !== manifest.lockHash) throw new Error('Deployment toolchain changed'); + return manifest; +} + +export async function deploymentCommand(directory: string, approved: string): Promise { + await verify(directory, approved); + return ['node', join(root, 'node_modules/wrangler/bin/wrangler.js'), 'deploy', '--config', join(await realpath(directory), 'wrangler.json')]; +} + +if (import.meta.main) { + try { + const [action, path, outputOrFlag, approved] = process.argv.slice(2); + if (action === 'prepare' && path && outputOrFlag && !approved) { + const manifest = await prepare(path, outputOrFlag); + const p = fromWrangler(await Bun.file(join(outputOrFlag, 'wrangler.json')).json()); + console.log(json({ release: resolve(outputOrFlag), digest: manifest.digest, sourceCommit: manifest.sourceCommit, + worker: p.name, account: p.account_id, routes: p.routes, databases: p.d1_databases, + sites: JSON.parse(p.vars.SITES), files: manifest.files, + note: 'Desired configuration only; no cloud diff, deployment or migration performed.' })); + } else if (action === 'deploy' && path && outputOrFlag === '--approve' && approved && process.argv.length === 6) { + const command = await deploymentCommand(path, approved); + // Installation account/environment come from the approved profile only. + const { CLOUDFLARE_ENV: _, CLOUDFLARE_ACCOUNT_ID: __, ...environment } = process.env; + const child = Bun.spawn(command, { cwd: await realpath(path), stdin: 'inherit', stdout: 'inherit', stderr: 'inherit', + env: { ...environment, CI: 'true', WRANGLER_SEND_METRICS: 'false' } }); + process.exitCode = await child.exited; + } else throw new Error('Usage: prepare | deploy --approve '); + } catch (error) { + console.error(error instanceof Error ? error.message : 'Release failed'); + process.exitCode = 1; + } +} diff --git a/tests/cloudflare.test.ts b/tests/cloudflare.test.ts new file mode 100644 index 0000000..65f1cde --- /dev/null +++ b/tests/cloudflare.test.ts @@ -0,0 +1,92 @@ +import { test, expect } from 'bun:test'; +import { mkdtemp, rm, symlink, realpath } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { profile, wranglerConfig, fromWrangler, type Profile } from '../scripts/cloudflare/profile.ts'; +import { prepare, verify, deploymentCommand } from '../scripts/cloudflare/release.ts'; + +function fixture(): Profile { + return { + name: 'review-concourse', account_id: 'a'.repeat(32), compatibility_date: '2026-08-06', + workers_dev: false, preview_urls: false, + routes: [{ pattern: 'guide.example/__concourse/*', zone_id: 'b'.repeat(32) }], + vars: { SITES: JSON.stringify([{ id: 'guide', origin: 'https://guide.example', issuer: 'https://test.cloudflareaccess.com', audience: 'test-audience', domains: ['example.org'], emails: [] }]) }, + d1_databases: [{ binding: 'DB', database_name: 'review-comments', database_id: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee' }], + }; +} +test('profile refuses broad/foreign/duplicate routes, alternate origins and executable hooks', async () => { + expect(fromWrangler(wranglerConfig(profile(fixture())))).toEqual(fixture()); + const cases = [ + { ...fixture(), workers_dev: true }, { ...fixture(), preview_urls: true }, + { ...fixture(), routes: [{ pattern: 'guide.example/*', zone_id: 'b'.repeat(32) }] }, + { ...fixture(), routes: [{ pattern: 'foreign.example/__concourse/*', zone_id: 'b'.repeat(32) }] }, + { ...fixture(), routes: [...fixture().routes, ...fixture().routes] }, + { ...fixture(), build: { command: 'unreviewed-command' } }, + { ...fixture(), env: { production: {} } }, { ...fixture(), account_id: 'REPLACE_ACCOUNT_ID' }, + { ...fixture(), vars: { SITES: '[]' } }, + ]; + for (const value of cases) expect(() => profile(value)).toThrow(); + expect(() => profile(awaitedExample)).toThrow(); +}); +const awaitedExample = await Bun.file('deploy/cloudflare/profile.example.json').json(); + +test('release approval binds actual bytes, config, SQL and toolchain; rejects tampering before command creation', async () => { + const root = await mkdtemp(join(tmpdir(), 'concourse-release-')); + try { + const path = join(root, 'profile.json'), release = join(root, 'release'); + await Bun.write(path, JSON.stringify(fixture())); + const manifest = await prepare(path, release); + expect((await verify(release, manifest.digest)).digest).toBe(manifest.digest); + expect(await deploymentCommand(release, manifest.digest)).toContain(join(await realpath(release), 'wrangler.json')); + await expect(deploymentCommand(release, '')).rejects.toThrow('explicit'); + await expect(deploymentCommand(release, '0'.repeat(64))).rejects.toThrow('approval'); + await expect(prepare(path, release)).rejects.toThrow(); + const worker = await Bun.file(join(release, 'worker.js')).bytes(); + await Bun.write(join(release, 'worker.js'), '// changed'); + await expect(deploymentCommand(release, manifest.digest)).rejects.toThrow('bytes changed'); + await Bun.write(join(release, 'worker.js'), worker); + await Bun.write(join(release, 'unexpected.txt'), 'extra'); + await expect(deploymentCommand(release, manifest.digest)).rejects.toThrow('file list'); + await rm(join(release, 'unexpected.txt')); + const sql = await Bun.file(join(release, 'migrations/0001_comments.sql')).bytes(); + await Bun.write(join(release, 'migrations/0001_comments.sql'), '-- changed'); + await expect(deploymentCommand(release, manifest.digest)).rejects.toThrow('bytes changed'); + await Bun.write(join(release, 'migrations/0001_comments.sql'), sql); + await rm(join(release, 'worker.js')); + await symlink(join(root, 'profile.json'), join(release, 'worker.js')); + await expect(deploymentCommand(release, manifest.digest)).rejects.toThrow('symlinks'); + } finally { await rm(root, { recursive: true }); } +}); + +test('one profile safely routes two sites without granting a wildcard route', () => { + const p = fixture(); + const configured = JSON.parse(p.vars.SITES); + configured.push({ ...configured[0], id: 'second', origin: 'https://second.example' }); + p.vars.SITES = JSON.stringify(configured); + p.routes.push({ pattern: 'second.example/__concourse/*', zone_id: 'b'.repeat(32) }); + expect(profile(p).routes).toHaveLength(2); + p.routes.pop(); + expect(() => profile(p)).toThrow('Every configured site'); +}); + +test('pinned Wrangler accepts the prepared Worker and bindings in a real offline dry-run', async () => { + const root = await mkdtemp(join(tmpdir(), 'concourse-wrangler-')); + try { + const path = join(root, 'profile.json'), release = join(root, 'release'); + await Bun.write(path, JSON.stringify(fixture())); + const manifest = await prepare(path, release); + const command = await deploymentCommand(release, manifest.digest); + const child = Bun.spawn([...command, '--dry-run', '--outdir', join(root, 'dry-run')], { + cwd: release, stdout: 'pipe', stderr: 'pipe', + env: { PATH: process.env.PATH, CI: 'true', WRANGLER_SEND_METRICS: 'false', + WRANGLER_LOG_PATH: join(root, 'logs'), XDG_CONFIG_HOME: join(root, 'config') }, + }); + const [stdout, stderr, code] = await Promise.all([ + new Response(child.stdout).text(), new Response(child.stderr).text(), child.exited, + ]); + expect({ code, output: stdout + stderr }).toMatchObject({ code: 0 }); + expect(stdout + stderr).toContain('dry-run'); + // Wrangler did not mutate any approved release bytes. + expect((await verify(release, manifest.digest)).digest).toBe(manifest.digest); + } finally { await rm(root, { recursive: true }); } +}, 30_000);