From 596543cc37a3e549678cbc20dbad93ead0a630ac Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 18 Oct 2026 14:06:31 +0000 Subject: [PATCH 1/5] =?UTF-8?q?BL5:=20the=20cirrus=20standard=20=E2=80=94?= =?UTF-8?q?=20no=20kiox,=20generated=20component=20docs,=20the=20context?= =?UTF-8?q?=20pack,=20SVG=20uploads=20closed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Close a stored XSS: uploads accepted any image/*, SVG included, and /api/blob served it from the app's own origin. Uploads are now raster images only (PNG, JPEG, GIF, WebP, AVIF; media type without parameters, case-insensitive), one list in lib/blob/content-types.ts shared by the route and the uploader's accept/check. /api/blob answers every object with `Content-Security-Policy: default-src 'none'; sandbox` beside nosniff, and its comment no longer claims to authenticate. tests/web (16 tests, was 11) and testing/e2e.test.sh assert both (risk BL-L). - Remove kiox.yaml/kiox.lock and their two blueprint modules: nothing ran the kiox pin (v2.15.0); every workflow pins orun through orun-action. - Generate docs/{overview,architecture,runbook}.md for every component from what it declares (tooling/catalog/gen-component-docs.py), and fail Baseline CI when they drift (--check). - Add ai/context/{current,decisions,open-risks}.md (this repository's own; nothing places them). - Close out BL4 (shipped, tagged baseline-v1), note the footer's Vercel logo the page-copy section left out, and record BL5 (BL-6). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01D8AmgTwmnp4M8mgmnS9aha --- .baseline/product/README.md | 16 +- .github/workflows/baseline.yml | 6 + README.md | 8 +- ai/context/current.md | 44 ++ ai/context/decisions.md | 20 + ai/context/open-risks.md | 17 + ai/context/operations.md | 7 +- apps/web/README.md | 12 +- apps/web/app/api/blob/route.ts | 16 +- apps/web/app/api/upload/route.ts | 10 +- apps/web/components/uploader.tsx | 13 +- apps/web/docs/architecture.md | 27 + apps/web/docs/overview.md | 20 + apps/web/docs/runbook.md | 40 ++ apps/web/lib/blob/client.ts | 4 + apps/web/lib/blob/content-types.ts | 23 + apps/web/lib/blob/server.ts | 13 +- .../cloudflare-r2/docs/architecture.md | 29 + .../terraform/cloudflare-r2/docs/overview.md | 19 + infra/terraform/cloudflare-r2/docs/runbook.md | 20 + kiox.lock | 11 - kiox.yaml | 6 - repo-blueprint.yaml | 12 +- specs/epics/README.md | 2 +- .../blob-starter/IMPLEMENTATION-STATUS.md | 60 +- specs/epics/blob-starter/README.md | 9 +- specs/epics/blob-starter/design.md | 5 +- specs/epics/blob-starter/epic.yaml | 8 + .../epics/blob-starter/implementation-plan.md | 34 +- .../blob-starter/risks-and-open-questions.md | 24 + tasks/BL-6.TaskContract.yaml | 38 ++ testing/e2e.test.sh | 33 +- testing/phases.test.sh | 2 +- tests/web/docs/architecture.md | 8 + tests/web/docs/overview.md | 18 + tests/web/docs/runbook.md | 26 + tests/web/src/blob.test.ts | 72 ++- tooling/catalog/gen-component-docs.py | 519 ++++++++++++++++++ tooling/rebrand/rebrand.mjs | 1 - 39 files changed, 1159 insertions(+), 93 deletions(-) create mode 100644 ai/context/current.md create mode 100644 ai/context/decisions.md create mode 100644 ai/context/open-risks.md create mode 100644 apps/web/docs/architecture.md create mode 100644 apps/web/docs/overview.md create mode 100644 apps/web/docs/runbook.md create mode 100644 apps/web/lib/blob/content-types.ts create mode 100644 infra/terraform/cloudflare-r2/docs/architecture.md create mode 100644 infra/terraform/cloudflare-r2/docs/overview.md create mode 100644 infra/terraform/cloudflare-r2/docs/runbook.md delete mode 100644 kiox.lock delete mode 100644 kiox.yaml create mode 100644 tasks/BL-6.TaskContract.yaml create mode 100644 tests/web/docs/architecture.md create mode 100644 tests/web/docs/overview.md create mode 100644 tests/web/docs/runbook.md create mode 100644 tooling/catalog/gen-component-docs.py diff --git a/.baseline/product/README.md b/.baseline/product/README.md index c903e40..19c25c9 100644 --- a/.baseline/product/README.md +++ b/.baseline/product/README.md @@ -23,8 +23,8 @@ and how to operate it is in |---|---| | The page and the uploader | `apps/web/app/page.tsx`, `apps/web/components/uploader.tsx` | | The site's name and source link | `apps/web/app/site.ts` | -| Upload (PUT, image/* ≤ 50MB, random suffix) and delivery (GET, private) | `apps/web/app/api/upload/route.ts`, `apps/web/app/api/blob/route.ts` | -| The browser upload helper and the bucket's checks | `apps/web/lib/blob/client.ts`, `apps/web/lib/blob/server.ts` | +| Upload (PUT, PNG/JPEG/GIF/WebP/AVIF ≤ 50MB — no SVG — random suffix) and delivery (GET, private, sandboxed) | `apps/web/app/api/upload/route.ts`, `apps/web/app/api/blob/route.ts` | +| The browser upload helper, the bucket's checks, and the upload types they share | `apps/web/lib/blob/client.ts`, `apps/web/lib/blob/server.ts`, `apps/web/lib/blob/content-types.ts` | | Workers build, bindings and deploy contract | `apps/web/next.config.mjs`, `open-next.config.ts`, `wrangler.template.jsonc` + `wiring.fixture.json` (→ `wrangler.jsonc`), `component.yaml` | | The R2 bucket (stage, prod) | `infra/terraform/cloudflare-r2` | | Tests | `tests/web` (vitest: both routes against an in-memory bucket) | @@ -51,11 +51,13 @@ repository it links to in `apps/web/app/site.ts`. ## How uploads work The browser PUTs the file to `/api/upload?pathname=` with progress; -the route accepts images only, up to 50MB, stores the file in the bucket -under the name plus a random suffix, and answers -`{ pathname, contentType, size }`. `/api/blob?pathname=` -streams it back with its content type. The bucket is private: nothing is -served from it except through that route. +the route accepts raster images only — PNG, JPEG, GIF, WebP, AVIF; not SVG, +which can carry script — up to 50MB, stores the file in the bucket under the +name plus a random suffix, and answers `{ pathname, contentType, size }`. +`/api/blob?pathname=` streams it back with its content type, +`nosniff`, and `Content-Security-Policy: default-src 'none'; sandbox`, so +nothing it serves can run script on the site's origin. The bucket is +private: nothing is served from it except through that route. There is no storage key to configure. The Worker binds the bucket as `BLOB`, and the binding is the credential. Its name is never hand-written: diff --git a/.github/workflows/baseline.yml b/.github/workflows/baseline.yml index 87c7314..b71c792 100644 --- a/.github/workflows/baseline.yml +++ b/.github/workflows/baseline.yml @@ -51,6 +51,12 @@ jobs: echo "── $t" bash "testing/$t.test.sh" done + # Every component's docs/{overview,architecture,runbook}.md is generated + # from what the component declares (its manifest, Worker config, + # Terraform, migrations, package scripts). A pull request that changes + # one of those facts without regenerating the pages fails here. + - name: Component docs match their manifests + run: python3 tooling/catalog/gen-component-docs.py --check # Tier 1. THE BLUEPRINT, READ AND PLACED BY THE BINARY A BOOTSTRAP RUNS. # diff --git a/README.md b/README.md index d6587e4..a315498 100644 --- a/README.md +++ b/README.md @@ -64,8 +64,8 @@ bucket names. None of this repository's machinery ships. |---|---| | The page and the uploader | `apps/web/app/page.tsx`, `apps/web/components/uploader.tsx` | | The site's name and source link | `apps/web/app/site.ts` | -| Upload (PUT, image/* ≤ 50MB, random suffix) and delivery (GET, private) | `apps/web/app/api/upload/route.ts`, `apps/web/app/api/blob/route.ts` | -| The two halves of what `@vercel/blob` did | `apps/web/lib/blob/client.ts`, `apps/web/lib/blob/server.ts` | +| Upload (PUT, PNG/JPEG/GIF/WebP/AVIF ≤ 50MB — no SVG — random suffix) and delivery (GET, private, sandboxed) | `apps/web/app/api/upload/route.ts`, `apps/web/app/api/blob/route.ts` | +| The two halves of what `@vercel/blob` did, and the upload types they share | `apps/web/lib/blob/client.ts`, `apps/web/lib/blob/server.ts`, `apps/web/lib/blob/content-types.ts` | | Workers build, bindings and deploy contract | `apps/web/next.config.mjs`, `open-next.config.ts`, `wrangler.template.jsonc` + `wiring.fixture.json` (→ the committed `wrangler.jsonc`), `component.yaml` | | The R2 bucket (stage, prod) | `infra/terraform/cloudflare-r2` | | The wrangler renderer | `tooling/wire` | @@ -93,8 +93,8 @@ pnpm --filter @app/web preview # wrangler dev over the built Worker, same loc |---|---| | Next.js hosting | One Cloudflare Worker (`.open-next/worker.js`) + Static Assets | | Vercel Blob (`BLOB_READ_WRITE_TOKEN`) | R2 bucket bound as `BLOB`; the binding is the credential | -| `upload()` client token handshake + direct upload | `PUT /api/upload?pathname=` through the Worker, with progress; same checks, same result shape | -| `GET /api/blob` private delivery | Same route, streaming from R2 | +| `upload()` client token handshake + direct upload | `PUT /api/upload?pathname=` through the Worker, with progress; the same checks, with images narrowed to raster formats (an SVG can carry script); same result shape | +| `GET /api/blob` private delivery | Same route, streaming from R2, under `nosniff` and a CSP that sandboxes what it serves | | A store created in the dashboard | `infra/terraform/cloudflare-r2`, applied by Orun before the Worker deploys | | Deploy on push | Orun applies the bucket and deploys `-web-{stage,prod}` on merge to `main` (`apps/web/component.yaml`) | | "Deploy with Vercel" (clone the template) | `orun new --blueprint repo-blueprint.yaml` — a new repository, branded, deployed | diff --git a/ai/context/current.md b/ai/context/current.md new file mode 100644 index 0000000..ac6d66c --- /dev/null +++ b/ai/context/current.md @@ -0,0 +1,44 @@ +# blob-starter — where this repository stands + +The entry page for anyone (or any agent) picking this repository up. It is +this repository's own state and does not ship to a product built from it; +the two pages that do are [operations.md](operations.md) and +[deployment.md](deployment.md). + +## What it is + +Vercel's Blob Next.js Starter — an image uploader with a private delivery +route — on Cloudflare Workers + Static Assets, with the files in an R2 bucket +Terraform provisions, packaged as an Orun baseline: `orun new --blueprint +repo-blueprint.yaml` builds a new product in its own repository and takes it +to live on stage and prod in one landing (`01-product`: the bucket applied, +then the Worker deployed), then records what went live (`02-docs`). + +## Release + +| | | +|---|---| +| Latest tag | `baseline-v1` (BL4) | +| On `main` since | BL5 — the cirrus standard (no kiox, generated component docs, this context pack) and SVG uploads closed (risk BL-L) | +| Proven live | No. Everything short of the platform is proven offline in Baseline CI, an upload round-tripped through the built Worker included; a live bootstrap from a tag is still to come (risk BL-G) | + +`baseline-v1` accepts any `image/*` upload, SVG included, and serves it from +the product's own origin (BL-L). A product built from it needs BL5's change +to `apps/web/lib/blob`, the delivery route and the uploader. + +## Where to read + +| Question | Page | +|---|---| +| What shipped, and every departure from upstream | `specs/epics/blob-starter/IMPLEMENTATION-STATUS.md` | +| Why it is built this way | [decisions.md](decisions.md), then `specs/epics/blob-starter/design.md` | +| What could still go wrong | [open-risks.md](open-risks.md), then `specs/epics/blob-starter/risks-and-open-questions.md` | +| How to instantiate it | `BOOTSTRAP.md`, `docs/phases/` | +| What each component is | `apps/web/docs/`, `tests/web/docs/`, `infra/terraform/cloudflare-r2/docs/` (generated; `python3 tooling/catalog/gen-component-docs.py`) | + +## Next + +1. Cut the next `baseline-vN` with `tag.yml`, so the registry can pin BL5 and + no new product starts with SVG uploads open. +2. Bootstrap one product from that tag against a workspace whose Cloudflare + account has R2 enabled (BL-J), and record its timings (closes BL-G). diff --git a/ai/context/decisions.md b/ai/context/decisions.md new file mode 100644 index 0000000..6f70463 --- /dev/null +++ b/ai/context/decisions.md @@ -0,0 +1,20 @@ +# blob-starter — decisions + +The choices that shape this repository, one line each, with where the full +reasoning lives. Superseded decisions stay listed, marked, so the history +reads in order. + +| # | Decision | Why | Source | +|---|---|---|---| +| 1 | The upload goes through the Worker (`PUT /api/upload`, buffered, 50MB max), not a presigned R2 URL | One credential (the binding) and the template's checks stay on the server; presigned URLs need an S3 key pair the baseline would have to broker | `specs/epics/blob-starter/design.md` §2, risk BL-A | +| 2 | Delivery stays a private route (`GET /api/blob?pathname=`), as upstream | The bucket is not public; nothing is served from it but through the Worker | design.md §2, epic README | +| 3 | The `BLOB` binding is the storage credential; no storage key | Replaces `BLOB_READ_WRITE_TOKEN`: a product stores and serves files from its first deploy with nothing but the Cloudflare connection | IMPLEMENTATION-STATUS (BL4) | +| 4 | `wrangler.jsonc` is rendered from the R2 root's wiring document per environment, and the fixture render is committed | The deploy lane checks the config exists before the build; Checks diffs the committed render | risk BL-E | +| 5 | dev renders the fixture; stage and prod refuse without the real document | No root applies in dev, which only verifies | risk BL-F | +| 6 | The R2 root applies with its own `r2-data` key (`CLOUDFLARE_R2_TOKEN`) | The `workers-deploy` token cannot touch R2 | risk BL-H | +| 7 | One landing (`01-product`) then the record (`02-docs`); `apps/web` `dependsOn: cloudflare-r2`, enforced on main, advisory on a pull request | The plan, not a landing boundary, orders the bucket before the Worker (cirrus-baseline since baseline-v22) | design.md §7 | +| 8 | `ci.yml` plans nothing while `intent.yaml` names `ws_CHANGE_ME` | A bootstrap cannot set a repository variable (replaced the `ORUN_CI` gate) | IMPLEMENTATION-STATUS (BL4) | +| 9 | stack-tectonic 0.19.0, not 0.20.0 | Next 16's Turbopack refuses 0.20.0's out-of-tree install | IMPLEMENTATION-STATUS (BL4), design.md §7 | +| 10 | Uploads are raster images only (PNG, JPEG, GIF, WebP, AVIF), one list shared by the route and the uploader; the delivery route serves every object under `default-src 'none'; sandbox` | `image/*` admitted SVG, which the route served from the app's origin as script — a stored XSS | risk BL-L, IMPLEMENTATION-STATUS (BL5) | +| 11 | orun is pinned only where it runs (the `orun-action` `version:` in each workflow); no kiox | `kiox.yaml` pinned a version (v2.15.0) nothing ran | IMPLEMENTATION-STATUS (BL5) | +| 12 | Component docs are generated from the manifests and checked in CI | A hand-written copy of the dependency graph and bindings drifts silently | `tooling/catalog/gen-component-docs.py` | diff --git a/ai/context/open-risks.md b/ai/context/open-risks.md new file mode 100644 index 0000000..46a51ac --- /dev/null +++ b/ai/context/open-risks.md @@ -0,0 +1,17 @@ +# blob-starter — open risks + +What is not yet proven or not yet decided. The full write-up of every risk, +including the accepted and resolved ones, is +`specs/epics/blob-starter/risks-and-open-questions.md`; this page lists only +what is still live, so it should be short. + +| ID | Risk | State | What closes it | +|---|---|---|---| +| BL-G | No live bootstrap yet: the repository created and linked, the two tokens minted, a real `terraform apply` of the bucket, the published wiring document, a real `wrangler deploy` and the probes are all unproven | OPEN | One bootstrap from a tag against a workspace whose Cloudflare account has R2 enabled | + +Accepted, and worth knowing before you change them: BL-A (the upload is +buffered through the Worker), BL-C (anonymous uploads, as upstream), +BL-I (the bootstrap floor plans every edge enforced), BL-J (R2 is +switched on per account by its owner), BL-K (a custom domain is the owner's +step). Resolved in BL5: BL-L (SVG uploads), for products built from a later +tag than `baseline-v1`. diff --git a/ai/context/operations.md b/ai/context/operations.md index 576dd6b..e763403 100644 --- a/ai/context/operations.md +++ b/ai/context/operations.md @@ -18,9 +18,10 @@ component-native desired-state repo. publishes a wiring document — `{r2_bucket_name}` — as the Orun secret `WIRING_CLOUDFLARE_R2` on that environment. - **`apps/web`** — the uploader: Next.js built by `@opennextjs/cloudflare` - into one Worker plus Static Assets. `PUT /api/upload?pathname=` accepts an - image (≤ 50MB) and stores it in the `BLOB` R2 binding under the name plus - a random suffix; `GET /api/blob?pathname=` streams it back. The page + into one Worker plus Static Assets. `PUT /api/upload?pathname=` accepts a + raster image (PNG, JPEG, GIF, WebP, AVIF; ≤ 50MB) and stores it in the + `BLOB` R2 binding under the name plus a random suffix; `GET + /api/blob?pathname=` streams it back, sandboxed by its CSP. The page renders per request (its metadata takes the request's origin). - **`tests/web`** — both routes against an in-memory bucket (vitest), verified on the `dev` rung. diff --git a/apps/web/README.md b/apps/web/README.md index d39a718..f0e5d72 100644 --- a/apps/web/README.md +++ b/apps/web/README.md @@ -7,15 +7,19 @@ running on Cloudflare Workers + Static Assets with the files in a **Cloudflare R2** bucket instead of Vercel Blob: - `app/page.tsx` — the page around `` -- `components/uploader.tsx` — pick or drop an image (image/* only, 50MB - max), preview, upload with progress, a toast linking the stored file +- `components/uploader.tsx` — pick or drop an image (PNG, JPEG, GIF, WebP + or AVIF, 50MB max), preview, upload with progress, a toast linking the + stored file - `app/api/upload/route.ts` — `PUT ?pathname=`: the same checks again on the server, then `BLOB.put` under the name plus a random suffix; answers `{ pathname, contentType, size }` - `app/api/blob/route.ts` — `GET ?pathname=`: streams the object with its - content type, or the route's own `Not found` 404 + content type, `nosniff` and a CSP that sandboxes it, or the route's own + `Not found` 404 - `lib/blob/client.ts`, `lib/blob/server.ts` — the two halves of what - `@vercel/blob` did + `@vercel/blob` did; `lib/blob/content-types.ts` — the raster types both + accept (no SVG: it can carry script, and the route serves from this + origin) - `app/site.ts` — the site's name and the repository its links point at ```bash diff --git a/apps/web/app/api/blob/route.ts b/apps/web/app/api/blob/route.ts index ddf27d3..865a748 100644 --- a/apps/web/app/api/blob/route.ts +++ b/apps/web/app/api/blob/route.ts @@ -2,8 +2,19 @@ import { type NextRequest, NextResponse } from 'next/server' import { bucket } from '@/lib/blob/server' // Delivery route for private blobs. -// The R2 bucket is not public; this route streams the object after -// authenticating the request. +// The R2 bucket is not public; this route is the only way to read it, and it +// streams the object to anyone who asks for its stored name. +// +// ⚠️ Authenticate and authorize users before streaming the object. +// Otherwise, anyone with the name can read it — nothing here checks who asks. +// +// What it serves comes from this app's own origin, so the response is locked +// down whatever the bucket holds: `nosniff` holds the browser to the stored +// content type, and the CSP gives no source to load from and sandboxes the +// object (no script, an opaque origin) — so even a file that is a document, +// such as an SVG stored before the upload route refused them, cannot run. +const CONTENT_SECURITY_POLICY = "default-src 'none'; sandbox" + export async function GET(request: NextRequest) { // ⚠️ Add your own authentication here. // For example: await authRequest(request) @@ -27,6 +38,7 @@ export async function GET(request: NextRequest) { 'Content-Length': String(object.size), ETag: object.httpEtag, 'X-Content-Type-Options': 'nosniff', + 'Content-Security-Policy': CONTENT_SECURITY_POLICY, }, }) } diff --git a/apps/web/app/api/upload/route.ts b/apps/web/app/api/upload/route.ts index 48a75b5..7101f9f 100644 --- a/apps/web/app/api/upload/route.ts +++ b/apps/web/app/api/upload/route.ts @@ -1,6 +1,7 @@ import { NextResponse } from 'next/server' import { MAX_UPLOAD_BYTES, + NOT_ALLOWED_MESSAGE, bucket, isAllowedContentType, putBlob, @@ -8,8 +9,11 @@ import { // Receives the browser's upload and stores it in R2. This is the Worker's // front door for uploads (Blob's `handleUpload` minted a client token for a -// direct upload instead): the same checks the template declared — -// image/* only, 50MB max, a random suffix on the name. +// direct upload instead): the checks the template declared — images only, +// 50MB max, a random suffix on the name — with "images" narrowed to raster +// formats (PNG, JPEG, GIF, WebP, AVIF). The template's `image/*` admitted +// SVG, which the delivery route would serve from this origin as a document +// that can run script. // // ⚠️ Authenticate and authorize users before accepting the upload. // Otherwise, you're allowing anonymous uploads. @@ -23,7 +27,7 @@ export async function PUT(request: Request): Promise { return NextResponse.json({ error: 'Missing pathname' }, { status: 400 }) } if (!isAllowedContentType(contentType)) { - return NextResponse.json({ error: 'We only accept image files' }, { status: 400 }) + return NextResponse.json({ error: NOT_ALLOWED_MESSAGE }, { status: 400 }) } if (length > MAX_UPLOAD_BYTES) { return NextResponse.json({ error: 'File size too big (max 50MB)' }, { status: 400 }) diff --git a/apps/web/components/uploader.tsx b/apps/web/components/uploader.tsx index 0a9322c..ef99975 100644 --- a/apps/web/components/uploader.tsx +++ b/apps/web/components/uploader.tsx @@ -2,7 +2,12 @@ import { useState, type FormEvent } from 'react' import toast from 'react-hot-toast' -import { upload } from '@/lib/blob/client' +import { + ALLOWED_CONTENT_TYPES, + NOT_ALLOWED_MESSAGE, + isAllowedContentType, + upload, +} from '@/lib/blob/client' import ProgressBar from './progress-bar' export default function Uploader() { @@ -76,8 +81,8 @@ export default function Uploader() { function handleFileChange(file: File) { toast.dismiss() - if (file.type.split('/')[0] !== 'image') { - toast.error('We only accept image files') + if (!isAllowedContentType(file.type)) { + toast.error(NOT_ALLOWED_MESSAGE) return } @@ -178,7 +183,7 @@ export default function Uploader() { id="image-upload" name="image" type="file" - accept="image/*" + accept={ALLOWED_CONTENT_TYPES.join(',')} className="sr-only" onChange={(event) => { const file = event.currentTarget?.files?.[0] diff --git a/apps/web/docs/architecture.md b/apps/web/docs/architecture.md new file mode 100644 index 0000000..46c05f2 --- /dev/null +++ b/apps/web/docs/architecture.md @@ -0,0 +1,27 @@ +# web — architecture + +Built by the turbo pipeline from `apps/web` and deployed with wrangler. + +| | | +|---|---| +| Worker config | `apps/web/wrangler.template.jsonc` | +| Entry | `.open-next/worker.js` | +| Compatibility date | `2026-10-01` | +| Compatibility flags | `nodejs_compat`, `global_fetch_strictly_public` | + +## Bindings + +| Binding | Kind | Source | +|---|---|---| +| `BLOB` | R2 bucket | `r2_bucket_name` from `cloudflare-r2` | +| `ASSETS` | Static assets | `.open-next/assets` | + +Identifiers marked *from* a component are filled in at deploy time from +that component's published outputs for the environment being deployed. + +## Wiring + +Resolved at deploy time from secrets the infrastructure lanes publish (names only): + +- `WIRING_CLOUDFLARE_R2_PROD` +- `WIRING_CLOUDFLARE_R2_STAGE` diff --git a/apps/web/docs/overview.md b/apps/web/docs/overview.md new file mode 100644 index 0000000..1ea6bfd --- /dev/null +++ b/apps/web/docs/overview.md @@ -0,0 +1,20 @@ +# web + +The image uploader (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, per environment) + +A Cloudflare Worker with Static Assets (server rendering plus static files), deployed per environment by its CI lane. + +| | | +|---|---| +| Type | `cloudflare-workers-assets-turbo` | +| Source | `apps/web` | +| Package | `@app/web` | +| Environments | `dev`: `verify` · `stage`: `verify`, `deploy` on a push to `main` · `prod`: `verify`, `deploy` on a push to `main` | + +## Depends on + +- **cloudflare-r2** — Provisions the Cloudflare R2 bucket the app binds (stage and prod) + +## Depended on by + +- (none) diff --git a/apps/web/docs/runbook.md b/apps/web/docs/runbook.md new file mode 100644 index 0000000..746c883 --- /dev/null +++ b/apps/web/docs/runbook.md @@ -0,0 +1,40 @@ +# web — runbook + +## How it runs + +Pull requests verify it; a merge to `main` deploys it to `stage`, `prod`. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Local commands + +```bash +pnpm --filter @app/web dev +pnpm --filter @app/web build +pnpm --filter @app/web typecheck +pnpm --filter @app/web lint +pnpm --filter @app/web preview +``` + +## Verify + +After a deploy the lane runs this smoke against the environment it +deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL: + +```bash +out=$(curl -s -w ' %{http_code}' "${DEPLOYED_URL}/api/blob?pathname=smoke/$(date +%s)-${RANDOM}.png") && [ "${out}" = 'Not found 404' ] && html=$(curl -sfL "${DEPLOYED_URL}/") && echo "${html}" | grep -q 'Upload an image' +``` + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream + has not applied for this environment yet. Within one convergence the plan + runs it first; on its own, re-run that lane. +- **The smoke fails right after a first deploy**: a new workers.dev route can + answer 4xx for a few seconds and the lane retries. A failure that persists + is a regression in the deployed code. diff --git a/apps/web/lib/blob/client.ts b/apps/web/lib/blob/client.ts index e0c3db1..cbc7c53 100644 --- a/apps/web/lib/blob/client.ts +++ b/apps/web/lib/blob/client.ts @@ -4,6 +4,10 @@ // the route; here the route is the store's front door, so no token round // trip and no size the Worker cannot see. +// The types the route accepts, for the file input and the uploader's own +// check before it sends anything: raster images only, no SVG. +export { ALLOWED_CONTENT_TYPES, NOT_ALLOWED_MESSAGE, isAllowedContentType } from './content-types' + export interface UploadOptions { access?: 'private' | 'public' handleUploadUrl: string diff --git a/apps/web/lib/blob/content-types.ts b/apps/web/lib/blob/content-types.ts new file mode 100644 index 0000000..363bcee --- /dev/null +++ b/apps/web/lib/blob/content-types.ts @@ -0,0 +1,23 @@ +// What an upload may be, shared by the uploader (the file input's `accept` +// and its check before the upload) and the upload route (the check that +// counts). Raster images only: an SVG is a document that can carry script, +// and the delivery route serves whatever the bucket holds from this app's +// own origin. + +export const ALLOWED_CONTENT_TYPES = [ + 'image/png', + 'image/jpeg', + 'image/gif', + 'image/webp', + 'image/avif', +] as const + +export const NOT_ALLOWED_MESSAGE = 'We only accept PNG, JPEG, GIF, WebP and AVIF images' + +// Compares the media type alone: parameters (`; charset=…`) and case do not +// change what the browser will make of the file. +export function isAllowedContentType(contentType: string | null | undefined): boolean { + if (!contentType) return false + const [mediaType = ''] = contentType.split(';') + return (ALLOWED_CONTENT_TYPES as readonly string[]).includes(mediaType.trim().toLowerCase()) +} diff --git a/apps/web/lib/blob/server.ts b/apps/web/lib/blob/server.ts index f6fd7b5..e6d6af1 100644 --- a/apps/web/lib/blob/server.ts +++ b/apps/web/lib/blob/server.ts @@ -5,16 +5,11 @@ import { getCloudflareContext } from '@opennextjs/cloudflare' // `addRandomSuffix` did), `get` streams it back. export const MAX_UPLOAD_BYTES = 50 * 1024 * 1024 // 50MB, as the template -export const ALLOWED_CONTENT_TYPES = ['image/*'] -export function isAllowedContentType(contentType: string | null): boolean { - if (!contentType) return false - return ALLOWED_CONTENT_TYPES.some((allowed) => - allowed.endsWith('/*') - ? contentType.startsWith(allowed.slice(0, -1)) - : contentType === allowed, - ) -} +// Raster images only (PNG, JPEG, GIF, WebP, AVIF). The template allowed +// `image/*`, which admits `image/svg+xml` — a document that runs script when +// the delivery route serves it from this origin. +export { ALLOWED_CONTENT_TYPES, NOT_ALLOWED_MESSAGE, isAllowedContentType } from './content-types' export function withRandomSuffix(pathname: string, random = crypto.randomUUID()): string { const suffix = random.replace(/-/g, '').slice(0, 30) diff --git a/infra/terraform/cloudflare-r2/docs/architecture.md b/infra/terraform/cloudflare-r2/docs/architecture.md new file mode 100644 index 0000000..f528c5b --- /dev/null +++ b/infra/terraform/cloudflare-r2/docs/architecture.md @@ -0,0 +1,29 @@ +# cloudflare-r2 — architecture + +A `terraform` root at `infra/terraform/cloudflare-r2/terraform`. + +- **State** lives in the Orun Cloud HTTP state backend — no local state and + no state bucket to manage. +- **Credentials are brokered per run** from the workspace's provider + connections and resolved by name; none is stored in this repository. +- **Adoption** (`adopt.tf`): when state is empty but the resource already + exists, plan-time import adopts it instead of failing. + +## Resources + +- `cloudflare_r2_bucket.app` + +## Published outputs + +Written as job-output secrets on each environment after an apply; deploy +lanes downstream resolve them by name. + +| Secret | Terraform output | +|---|---| +| `WIRING_CLOUDFLARE_R2` | `wiring` | + +## Resolved at run time (names only) + +- `CLOUDFLARE_ACCOUNT_ID` +- `CLOUDFLARE_API_TOKEN` +- `TF_VAR_cloudflare_account_id` diff --git a/infra/terraform/cloudflare-r2/docs/overview.md b/infra/terraform/cloudflare-r2/docs/overview.md new file mode 100644 index 0000000..5cda23e --- /dev/null +++ b/infra/terraform/cloudflare-r2/docs/overview.md @@ -0,0 +1,19 @@ +# cloudflare-r2 + +Provisions the Cloudflare R2 bucket the app binds (stage and prod) + +Terraform-managed infrastructure, planned and applied per environment by its CI lane. + +| | | +|---|---| +| Type | `terraform` | +| Source | `infra/terraform/cloudflare-r2` | +| Environments | `stage`: `plan-only`, `apply` on a push to `main` · `prod`: `plan-only`, `apply` on a push to `main` | + +## Depends on + +- (none) + +## Depended on by + +- **web** — The image uploader (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, per environment) diff --git a/infra/terraform/cloudflare-r2/docs/runbook.md b/infra/terraform/cloudflare-r2/docs/runbook.md new file mode 100644 index 0000000..37bee3b --- /dev/null +++ b/infra/terraform/cloudflare-r2/docs/runbook.md @@ -0,0 +1,20 @@ +# cloudflare-r2 — runbook + +## How it runs + +Pull requests plan it; a merge to `main` applies it to `stage`, `prod`. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **Provider authentication fails**: the workspace's provider connection is + missing or revoked. Reconnect it in the console; credentials are brokered + from it per run. +- **"Already exists" on a first apply**: state is empty but the resource is + not. `adopt.tf` imports it at plan time; if it still fails, the resource was renamed outside Terraform. diff --git a/kiox.lock b/kiox.lock deleted file mode 100644 index 6e14690..0000000 --- a/kiox.lock +++ /dev/null @@ -1,11 +0,0 @@ -apiVersion: kiox.io/v1 -kind: WorkspaceLock -metadata: - name: example-platform -providers: - - alias: orun - provider: sourceplane/orun - source: ghcr.io/sourceplane/orun:v2.15.0 - version: v2.15.0 - resolved: ghcr.io/sourceplane/orun@sha256:1d28be8612dc8d8083b508f97cd71a24c090f6472c43c71f68455e3709a6a3c1 - store: e02472f57f2eb5fb5168b7d270ea547e5bffbf83824c4286abd7ba20f87cb9d1 diff --git a/kiox.yaml b/kiox.yaml deleted file mode 100644 index d654da0..0000000 --- a/kiox.yaml +++ /dev/null @@ -1,6 +0,0 @@ -apiVersion: kiox.io/v1 -kind: Workspace -metadata: - name: example-platform -providers: - orun: ghcr.io/sourceplane/orun:v2.15.0 diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml index c65574b..e446958 100644 --- a/repo-blueprint.yaml +++ b/repo-blueprint.yaml @@ -184,16 +184,6 @@ modules: source: baseline from: turbo.json to: turbo.json - - name: root-kiox - mode: copy - source: baseline - from: kiox.yaml - to: kiox.yaml - - name: root-kiox-lock - mode: copy - source: baseline - from: kiox.lock - to: kiox.lock - name: root-gitignore mode: copy source: baseline @@ -404,7 +394,7 @@ phases: await: "One convergence is deploying the product: the R2 bucket first, then the uploader built bound to it, on stage and prod side by side. The Next.js build is the long pole; nothing is stuck." done: "{{ .inputs.reponame }} is live on stage and prod — {{ .meta.files }} files on main, branded as {{ .inputs.productname }}, the uploader answering from its bucket. That took {{ .meta.elapsed }}." failed: "The product did not come up. The failing lane above names the component — the R2 apply, or the uploader's build, deploy or smoke — and a provider error is in its log; whatever deployed is still there." - modules: [ai-deployment, ai-operations, cloudflare-r2, discovery-roots, github-workflows, rebrand-values, root-gitignore, root-intent, root-kiox, root-kiox-lock, root-package-json, root-pnpm-lock, root-pnpm-workspace, root-readme, root-turbo, tooling-eslint, tooling-tsconfig, tooling-wire, vscode, web, web-tests] + modules: [ai-deployment, ai-operations, cloudflare-r2, discovery-roots, github-workflows, rebrand-values, root-gitignore, root-intent, root-package-json, root-pnpm-lock, root-pnpm-workspace, root-readme, root-turbo, tooling-eslint, tooling-tsconfig, tooling-wire, vscode, web, web-tests] # THE PLATFORM MUST BE ABLE TO SEE THE REPOSITORY BEFORE IT EXISTS. Every # phase lands a pull request that files under its task, and the platform # learns of a PR only through the GitHub App installation on the account diff --git a/specs/epics/README.md b/specs/epics/README.md index 9ccee28..fdd314e 100644 --- a/specs/epics/README.md +++ b/specs/epics/README.md @@ -7,6 +7,6 @@ folder is the adoption; the merge creates the epic in the workspace. | Epic | Cluster | Status | What it is | |------|---------|--------|------------| -| [`blob-starter/`](./blob-starter/) | **BL** | ✅ Shipped | Vercel's Blob Next.js Starter, equivalent in code and function, on Cloudflare Workers with uploads stored in R2 — and an Orun baseline that instantiates it in one landing (BL4) | +| [`blob-starter/`](./blob-starter/) | **BL** | ✅ Shipped (`baseline-v1`); live bootstrap pending | Vercel's Blob Next.js Starter, equivalent in code and function, on Cloudflare Workers with uploads stored in R2 — and an Orun baseline that instantiates it in one landing (BL4) | As-built ≠ intent: what shipped lives in each epic's `IMPLEMENTATION-STATUS.md`. diff --git a/specs/epics/blob-starter/IMPLEMENTATION-STATUS.md b/specs/epics/blob-starter/IMPLEMENTATION-STATUS.md index 798c543..c2141a2 100644 --- a/specs/epics/blob-starter/IMPLEMENTATION-STATUS.md +++ b/specs/epics/blob-starter/IMPLEMENTATION-STATUS.md @@ -9,7 +9,8 @@ the code departed from `design.md` or from the upstream template. | BL1 — uploads on R2 | ✅ Shipped | [#2](https://github.com/sourceplane/blob-starter/pull/2) | | BL2 — the R2 bucket from Terraform | ✅ Shipped (validated; apply gated on a linked workspace) | [#3](https://github.com/sourceplane/blob-starter/pull/3) | | BL3 — ready to instantiate | ✅ Shipped | [#4](https://github.com/sourceplane/blob-starter/pull/4) | -| BL4 — a baseline, in one landing | ✅ Shipped (offline-proven; no live bootstrap yet, risk BL-G) | this PR (BL-5), to be tagged `baseline-v1` | +| BL4 — a baseline, in one landing | ✅ Shipped (offline-proven; no live bootstrap yet, risk BL-G) | [#5](https://github.com/sourceplane/blob-starter/pull/5) (BL-5), tagged `baseline-v1` | +| BL5 — the cirrus standard, SVG uploads closed | ✅ Shipped | BL-6 — on `main` after `baseline-v1`, not yet tagged | ## Departures from the upstream template @@ -18,16 +19,19 @@ the code departed from `design.md` or from the upstream template. `upload(pathname, file, { handleUploadUrl, onUploadProgress })` keeps its signature; it PUTs the file to the route over XHR (progress events) instead of the token handshake + direct upload. `components/uploader.tsx` changes -its import line only. +its import line only — until BL5, which gives its file input and its check +the route's raster-only list (below). ### `app/api/upload/route.ts` is a PUT that stores, not a POST that mints a token Same checks (image/*, 50MB, random suffix), `BLOB.put` instead of -`handleUpload`, the completion log inline. +`handleUpload`, the completion log inline. Since BL5 "image/*" is raster +images only — see the cirrus standard (BL5) below. ### `app/api/blob/route.ts` reads R2 -`BLOB.get(pathname)` streamed with content type, length, ETag and `nosniff`. +`BLOB.get(pathname)` streamed with content type, length, ETag and `nosniff` +— and, since BL5, `Content-Security-Policy: default-src 'none'; sandbox`. ### `next.config.mjs` (ESM) with `initOpenNextCloudflareForDev()`, no Blob image domain @@ -35,7 +39,8 @@ Same checks (image/*, 50MB, random suffix), `BLOB.put` instead of "Blob on Vercel" → "R2 on Cloudflare"; the Vercel Blob link → Cloudflare R2 docs; the deploy button → this repository; the layout title → "R2 Blob -Starter". +Starter". Not changed: the footer's Vercel logo +(`apps/web/public/vercel.svg`) still links vercel.com, as upstream's does. ### eslint-config-next 16 flat config, Next 16.3.8 @@ -86,6 +91,51 @@ Vercel Blob's token (`BLOB_READ_WRITE_TOKEN`) with the Worker's R2 binding, so a product built with nothing but the Cloudflare connection stores and serves files from its first deploy. Nothing third-party remains. +## The cirrus standard, SVG uploads closed (BL5) + +One fix to the app, and the baseline brought to cirrus-baseline's standard +around it: + +| What | Before | After | Why | +|---|---|---|---| +| what an upload may be | `ALLOWED_CONTENT_TYPES = ['image/*']`, a prefix match — `image/svg+xml` passed | `image/png`, `image/jpeg`, `image/gif`, `image/webp`, `image/avif`, matched on the media type without parameters, case-insensitive, in `apps/web/lib/blob/content-types.ts`; `server.ts` re-exports it, the route refuses the rest with "We only accept PNG, JPEG, GIF, WebP and AVIF images" | an SVG is a document that can carry script, and the delivery route served it from the app's origin: a stored XSS, with anonymous uploads (risk BL-L) | +| the delivery route's response | content type, length, ETag, `nosniff` | plus `Content-Security-Policy: default-src 'none'; sandbox` | whatever a bucket already holds cannot run script on the app's origin | +| the delivery route's comment | "streams the object after authenticating the request" | says the route does not authenticate, as the upload route's does | it never did: nothing ships auth (BL-C) | +| the uploader | `accept="image/*"`, `file.type.split('/')[0] === 'image'` | `accept` and the check from the same list (`lib/blob/client.ts` re-exports it) | the browser refuses what the route would | +| tests | — | `tests/web`: an SVG refused (400, nothing stored), each raster type stored, the policy on a served object; `testing/e2e.test.sh`: the uploader's `accept`, an SVG refused and the policy, on the built Worker | — | +| orun pin | `kiox.yaml` (v2.15.0) + `kiox.lock`, shipped to every product | gone; orun is pinned where it runs, the `orun-action` `version:` in each workflow | nothing ran the kiox pin, and it disagreed with the lanes (v2.78.4) | +| `root-kiox`, `root-kiox-lock` modules | in `01-product` | removed (`testing/phases.test.sh` and the rebrand's skip list follow) | a product is placed with 81 files: 73 − 2 kiox + 9 docs pages + `content-types.ts` | +| component docs | none | `apps/web/docs/`, `tests/web/docs/`, `infra/terraform/cloudflare-r2/docs/` — `overview.md`, `architecture.md`, `runbook.md` | cirrus-baseline documents every component; the workspace Docs library renders `docs/` beside each `component.yaml` | +| how the docs stay true | — | `tooling/catalog/gen-component-docs.py` derives them from the manifest, the Worker config, Terraform and package scripts; Baseline CI runs it with `--check` | a hand-written copy of a manifest drifts silently | +| context pack | `operations.md`, `deployment.md` | plus `current.md`, `decisions.md`, `open-risks.md` | cirrus-baseline's shape; the three new pages are this repository's own and no module places them (the leak gate still allows exactly two) | +| status | BL4 "to be tagged" | BL4 shipped and tagged `baseline-v1`; the page-copy note names the Vercel logo it kept | the tag existed; the documents had not caught up | + +## Verified (BL5) + +- `testing/{manifest,phases,coverage,rebrand,retouch,bootstrap-defer,wire}.test.sh` + green; `gen-component-docs.py --check` green (3 components, 9 pages). +- `orun new --status` (v2.58.11, the bootstrap floor): `01-product` 81 files, + `02-docs` hook-only. +- `testing/leak.test.sh` (v2.58.11): 81 files derived (73 − 2 kiox + 9 docs + pages + `content-types.ts`); ai/context still exactly the two declared + pages; 74 shipped sources name no factory path. +- `testing/placement.test.sh` (v2.78.4, as Baseline CI runs it): 81 files + placed, both landings, branded, re-tenanted; the product's own plan applies + `cloudflare-r2` (with `CLOUDFLARE_R2_TOKEN`) at level 0 and deploys `web` + at level 1 on stage and prod; a pull request waits on nothing; the 02-docs + merge plans 0 jobs. +- `pnpm install --frozen-lockfile`, `wire:fixture` (committed render + unchanged), `typecheck`, `lint` (the one upstream unused-variable + warning), `test` (16 tests, was 11), `build` green. +- `testing/e2e.test.sh` (v2.78.4): the 01-product landing passes the Checks + sequence; the stage lane's four steps pass in the staged job tree, `BLOB` + bound to the stage document's bucket; under `wrangler dev` the component's + smoke passes, the page offers the five raster types, one PNG uploaded + twice is stored under two suffixed names and streamed back byte for byte + with the sandboxing CSP and `nosniff`, and a PDF, an SVG, a missing name + and an unknown object are refused. +- `orun task check BL-6` complete. + ## Verified (BL4) - `orun new --status` reads the blueprint at v2.58.11 (the bootstrap floor), diff --git a/specs/epics/blob-starter/README.md b/specs/epics/blob-starter/README.md index 9f69083..aaec571 100644 --- a/specs/epics/blob-starter/README.md +++ b/specs/epics/blob-starter/README.md @@ -8,15 +8,15 @@ The port keeps the template's page, uploader, progress bar, toasts and styles. I | Field | Value | |-------|-------| -| Status | ✅ Shipped — BL0–BL3 landed (#1–#4); BL4 — a baseline, in one landing (BL-5); R2 apply and live deploy proven only by a live bootstrap | -| Cluster | **BL** (BL0–BL4) | +| Status | ✅ BL0–BL4 shipped (#1–#5), tagged `baseline-v1`; BL5 (the cirrus standard, SVG uploads closed — BL-6) on `main`, not yet tagged. R2 apply and live deploy proven only by a live bootstrap (risk BL-G) | +| Cluster | **BL** (BL0–BL5) | | Owner(s) | `apps/web` (the uploader, the routes, `lib/blob`) · `tests/web` · `infra/terraform/cloudflare-r2` | | Builds on | `cirrus-baseline` conventions: the R2 root and the `@@wiring(...)@@` deploy-time render; the `kv-redis-starter` port's binding shape | | Upstream | [vercel/examples `storage/blob-starter`](https://github.com/vercel/examples/tree/main/storage/blob-starter) | -| Changes | The store (Vercel Blob → R2), the upload path (client token → upload route), the Workers build, tests, the R2 root, the deploy contract; page copy says R2 | +| Changes | The store (Vercel Blob → R2), the upload path (client token → upload route), the Workers build, tests, the R2 root, the deploy contract; page copy says R2; since BL5, raster uploads only and a sandboxed delivery route (risk BL-L) | | Decisions locked | (1) The upload goes through the Worker (one route, bounded at 50MB), not a presigned R2 URL: it keeps the template's server-side checks where they were. (2) Delivery stays a private route (`/api/blob?pathname=`), as upstream. (3) `wrangler.jsonc` rendered per environment — and, since BL4, committed as the fixture render, because the deploy lane checks it exists before the build (risk BL-E). (4) BL4: one landing — the plan, not a landing boundary, orders the bucket before the Worker; the bucket's apply has a token of its own (`r2-data`), because the deploy token cannot touch R2. | | Gate | BL1 is the first user-visible rung. BL2 applies only with a linked workspace; verified by `terraform validate`. | -| Shipped as | `main` after [#4](https://github.com/sourceplane/blob-starter/pull/4); verified locally under `wrangler dev` with a local bucket | +| Shipped as | `baseline-v1` ([#5](https://github.com/sourceplane/blob-starter/pull/5)), then BL5 on `main`; proven offline (Baseline CI: an upload round-tripped through the built Worker under `wrangler dev`), deploy gated until a workspace is linked | ## Read order @@ -34,3 +34,4 @@ The port keeps the template's page, uploader, progress bar, toasts and styles. I | BL2 — the R2 bucket from Terraform | `infra/terraform/cloudflare-r2` | the root validates; the wiring key matches the template | | BL3 — ready to instantiate | README, as-built status | a reader can run, test, preview and deploy it | | BL4 — a baseline, in one landing | card, build document, rename, bootstrap tooling, tests | a new product goes from nothing to live in one landing, the R2 bucket applied before the Worker; Baseline CI green | +| BL5 — the cirrus standard, SVG uploads closed | raster-only uploads and a sandboxed delivery route; no kiox, generated component docs, the context pack, status that agrees with the tags | an SVG upload is refused and a served object cannot run script; Baseline CI green with the docs check | diff --git a/specs/epics/blob-starter/design.md b/specs/epics/blob-starter/design.md index 72fbc8e..682196d 100644 --- a/specs/epics/blob-starter/design.md +++ b/specs/epics/blob-starter/design.md @@ -16,8 +16,8 @@ toast with a "View file" link. `POST /api/upload` runs Blob's | Next.js hosting | Cloudflare Workers + Static Assets; the Worker is `@opennextjs/cloudflare`'s output | | Vercel Blob store (`BLOB_READ_WRITE_TOKEN`) | R2 bucket bound as `BLOB`; no token, the binding is the credential | | `upload()` from `@vercel/blob/client` (token handshake, direct upload, progress) | `lib/blob/client.ts` `upload()`: same signature, `PUT /api/upload?pathname=` over XHR with progress; resolves `{ pathname, contentType, size }` | -| `handleUpload` in `POST /api/upload` | `PUT /api/upload`: image/* only, 50MB max (header and body), random suffix (`withRandomSuffix`), `BLOB.put` with the content type, the same completion log | -| `get(pathname, { access: 'private' })` in `GET /api/blob` | `BLOB.get(pathname)` streamed with content type, length, ETag, `nosniff` | +| `handleUpload` in `POST /api/upload` | `PUT /api/upload`: image/* only — raster types only since BL5 (PNG, JPEG, GIF, WebP, AVIF; risk BL-L) — 50MB max (header and body), random suffix (`withRandomSuffix`), `BLOB.put` with the content type, the same completion log | +| `get(pathname, { access: 'private' })` in `GET /api/blob` | `BLOB.get(pathname)` streamed with content type, length, ETag, `nosniff` — and, since BL5, `Content-Security-Policy: default-src 'none'; sandbox` | | `images.domains` for the Blob host | Not needed: delivery is this app's own route | | A store created in the dashboard | `infra/terraform/cloudflare-r2`: one bucket per environment, name published as the `WIRING_CLOUDFLARE_R2` secret | | Deploy on push | Orun: `apps/web/component.yaml` renders the config for `$ORUN_ENVIRONMENT`, builds, and deploys `blob-starter-web-{stage,prod}` on merge to `main` once the product is linked — after the bucket's apply (BL4) | @@ -56,6 +56,7 @@ fixture (BL-F); `wrangler dev` and `next dev` (through apps/web the template + the Workers build lib/blob/client.ts the browser upload helper (replaces @vercel/blob/client) lib/blob/server.ts the bucket, the checks, the suffix (replaces @vercel/blob) + lib/blob/content-types.ts the raster types an upload may be, shared by both halves (BL5) app/api/upload/route.ts PUT: validate and store app/api/blob/route.ts GET: stream a private object app/site.ts the site's name and source link (BL4: the rename seam) + the request origin diff --git a/specs/epics/blob-starter/epic.yaml b/specs/epics/blob-starter/epic.yaml index 577bc3b..28acc7a 100644 --- a/specs/epics/blob-starter/epic.yaml +++ b/specs/epics/blob-starter/epic.yaml @@ -39,3 +39,11 @@ spec: - "a product built from it carries the product only, renamed throughout to its own name, repository, Worker and bucket names" - "Baseline CI is green: contract tests, the blueprint read by the pinned orun, the leak gate, the offline bootstrap and the end-to-end tier" tasks: [BL-5] + - name: "BL5 — the cirrus standard, SVG uploads closed" + exitCriteria: + - "uploads are raster images only (PNG, JPEG, GIF, WebP, AVIF) — an SVG is refused — and the delivery route serves every object under a CSP that sandboxes it, so nothing stored can run script on the app's origin" + - "no file names kiox: orun is pinned where CI runs it (the orun-action `version:` in each workflow)" + - "every component carries generated docs/{overview,architecture,runbook}.md, and Baseline CI fails a pull request whose manifests and pages disagree" + - "ai/context carries this repository's current.md, decisions.md and open-risks.md, and none of them ships to a product" + - "every milestone's status row agrees with the tags" + tasks: [BL-6] diff --git a/specs/epics/blob-starter/implementation-plan.md b/specs/epics/blob-starter/implementation-plan.md index 260c5e6..d24bbd4 100644 --- a/specs/epics/blob-starter/implementation-plan.md +++ b/specs/epics/blob-starter/implementation-plan.md @@ -60,9 +60,41 @@ enforced `dependsOn: cloudflare-r2` on main, `packages/`. - the status file records what is proven offline and what only a live bootstrap can prove +## BL5 — the cirrus standard, SVG uploads closed (BL-6) ✅ + +One security fix to the app, and the baseline brought to cirrus-baseline's +standard around it. + +- **SVG uploads closed (risk BL-L).** The upload route and the uploader take + raster images only — PNG, JPEG, GIF, WebP, AVIF — from one list + (`apps/web/lib/blob/content-types.ts`), matched on the media type without + parameters; the delivery route serves every object under + `Content-Security-Policy: default-src 'none'; sandbox` beside `nosniff`. + Its comment stops claiming it authenticates. +- **No kiox.** `kiox.yaml`/`kiox.lock` pinned an orun (v2.15.0) that nothing + ran: every workflow installs orun itself through `orun-action` with its own + `version:`. The files, their two modules and the rebrand's skip entry go. +- **Component docs.** `tooling/catalog/gen-component-docs.py` writes each + component's `docs/overview.md`, `docs/architecture.md` and `docs/runbook.md` + from what the component declares, as cirrus-baseline's do; the pages ship + with the component. Baseline CI runs it with `--check`. +- **The context pack.** `ai/context/current.md`, `decisions.md` and + `open-risks.md` beside the two pages a product ships with — this + repository's own, so no module places them. +- **Status that agrees with the tags.** BL4 is shipped and tagged. + +**Done when** +- `tests/web` refuses an SVG upload (400), stores each raster type, and finds + the policy on a served object; `testing/e2e.test.sh` does the same against + the built Worker +- `git grep -i kiox` finds nothing, and the leak gate and the offline + bootstrap pass without the two modules +- the docs check is green in Baseline CI +- this file, the status file and `epic.yaml` agree + ## After BL4 (outside this repository) -1. Cut `baseline-v1` with `tag.yml` from the merged `main`. +1. Cut `baseline-v1` with `tag.yml` from the merged `main` — done: `baseline-v1` is BL4. 2. Register the row in orun-cloud's `infra/baselines-registry/baselines.yaml` (unlisted) with the card vendored at the tag. 3. Bootstrap one product from the tag against a workspace whose Cloudflare diff --git a/specs/epics/blob-starter/risks-and-open-questions.md b/specs/epics/blob-starter/risks-and-open-questions.md index 87d6fba..5a0b9c2 100644 --- a/specs/epics/blob-starter/risks-and-open-questions.md +++ b/specs/epics/blob-starter/risks-and-open-questions.md @@ -25,6 +25,10 @@ auth. "Blob on Vercel", the Vercel Blob link and the deploy button point at R2 and this repository; the layout title reads "R2 Blob Starter". +(Note, BL5: the title has been `SITE_NAME` since BL4, and the footer's +Vercel logo still links vercel.com, as upstream's does — it was not among the +links this risk changed.) + ## BL-E — The deploy lane checked for a config only the build makes (RESOLVED in BL4) stack-tectonic's `cloudflare-workers-assets-turbo` runs `verify-app-structure` @@ -104,3 +108,23 @@ Attaching a domain to a Worker needs zone permissions the brokered `workers-deploy` token does not carry, and `dns-edit` needs zone ids a build does not have. The product's README says how to attach one; nothing in the repository changes, because the page takes its origin from the request. + +## BL-L — SVG uploads were a stored XSS on the app's origin (RESOLVED in BL5) + +The upload route accepted the template's `image/*`, and `image/*` admits +`image/svg+xml`. An SVG is a document that can carry script, and `GET +/api/blob` served it from the app's own origin with its stored content type +and no policy — so anyone who opened its URL (the uploader's "View file" +toast links it) ran the uploader's script as the app. Uploads are anonymous +(BL-C), so anyone could plant one. Fix: an allow-list of raster types — +`image/png`, `image/jpeg`, `image/gif`, `image/webp`, `image/avif` — compared +on the media type without parameters, case-insensitive +(`apps/web/lib/blob/content-types.ts`), which the route checks and the +uploader uses for its file input's `accept` and its own check; and the +delivery route answers with `Content-Security-Policy: default-src 'none'; +sandbox` beside `nosniff`, so an object already in a bucket cannot run +script either. `tests/web/src/blob.test.ts` refuses an SVG (400, nothing +stored), accepts each raster type, and reads the policy on a served object +(an SVG stored before the fix included); `testing/e2e.test.sh` checks the +same against the built Worker. A product built from `baseline-v1` carries +the old check until it takes the same change. diff --git a/tasks/BL-6.TaskContract.yaml b/tasks/BL-6.TaskContract.yaml new file mode 100644 index 0000000..7ce23ca --- /dev/null +++ b/tasks/BL-6.TaskContract.yaml @@ -0,0 +1,38 @@ +apiVersion: orun.io/v1 +kind: TaskContract +metadata: + name: BL-6 + title: "The cirrus standard, SVG uploads closed" +spec: + goal: Uploads cannot plant script on the app's origin — the upload route and the uploader take raster images only and the delivery route serves every object sandboxed — and the baseline meets cirrus-baseline's standard — no kiox pin (orun is pinned where CI runs it), every component documented by generated overview/architecture/runbook pages that CI keeps in step with the manifests, the agent context pack, and status documents that agree with the tags + affects: + - apps/web/lib/blob/** + - apps/web/app/api/** + - apps/web/components/uploader.tsx + - apps/web/README.md + - tests/web/src/** + - testing/e2e.test.sh + - kiox.yaml + - kiox.lock + - repo-blueprint.yaml + - testing/phases.test.sh + - tooling/rebrand/** + - tooling/catalog/** + - .github/workflows/baseline.yml + - apps/web/docs/** + - tests/web/docs/** + - infra/terraform/cloudflare-r2/docs/** + - ai/context/** + - README.md + - .baseline/product/** + - specs/** + - tasks/** + doneWhen: + - an SVG upload is refused (400) and each raster type (PNG, JPEG, GIF, WebP, AVIF) is stored, in tests/web and against the built Worker in testing/e2e.test.sh + - "the delivery route answers every object with `Content-Security-Policy: default-src 'none'; sandbox` and `nosniff`" + - no file names kiox, and the leak gate and the offline bootstrap place a product without it + - every component has docs/overview.md, docs/architecture.md and docs/runbook.md, and `python3 tooling/catalog/gen-component-docs.py --check` is green in Baseline CI + - ai/context carries current.md, decisions.md and open-risks.md for this repository (none of them ships) + - every milestone's status row agrees with the tags + gates: + - checks diff --git a/testing/e2e.test.sh b/testing/e2e.test.sh index ab3ab28..c718fba 100755 --- a/testing/e2e.test.sh +++ b/testing/e2e.test.sh @@ -31,9 +31,10 @@ # the upload, which only the Worker answers: an image PUT to # /api/upload is stored in the BLOB bucket under a name with a random # suffix (a different one on every request) and streamed back -# byte-for-byte from /api/blob, while a non-image, a missing name and an -# unknown object are refused. wrangler dev provides the bucket locally, -# with nothing but the build: no storage key, no third-party service. +# byte-for-byte from /api/blob under a CSP that sandboxes it, while a +# non-image, an SVG, a missing name and an unknown object are refused. +# wrangler dev provides the bucket locally, with nothing but the build: +# no storage key, no third-party service. # # What it cannot do is the platform's half: create the repository, mint the # brokered Cloudflare tokens, apply the bucket, deploy for real and probe @@ -237,8 +238,9 @@ if "blob-starter" in page or "R2 on Cloudflare" in page: og = re.search(r'' +s, h, b = upload("logo.svg", svg, "image/svg+xml") +if s != 400 or json.loads(b or b"{}").get("error") != refused: + bad(f"an SVG upload answered {s} {b[:120]!r}, not 400 {refused!r}") s, h, b = upload(None, png, "image/png") if s != 400: bad(f"an upload with no pathname answered {s}, not 400") @@ -298,8 +311,8 @@ if problems: print(f" ✕ {p}", file=sys.stderr) sys.exit(1) print(f" / (the product's name, links, origin and uploader); one image uploaded twice, stored as") -print(f" {stored[0]!r} and {stored[1]!r}, streamed back byte for byte;") -print(f" a PDF, a missing name and an unknown object refused; the Open Graph image, the static") +print(f" {stored[0]!r} and {stored[1]!r}, streamed back byte for byte, sandboxed;") +print(f" a PDF, an SVG, a missing name and an unknown object refused; the Open Graph image, the static") print(f" assets and a 404 — the product's own") PY diff --git a/testing/phases.test.sh b/testing/phases.test.sh index 3b16820..0f86720 100755 --- a/testing/phases.test.sh +++ b/testing/phases.test.sh @@ -43,7 +43,7 @@ if not phases: PARTITION = { "01-product": ["ai-deployment", "ai-operations", "cloudflare-r2", "discovery-roots", "github-workflows", "rebrand-values", "root-gitignore", "root-intent", - "root-kiox", "root-kiox-lock", "root-package-json", "root-pnpm-lock", + "root-package-json", "root-pnpm-lock", "root-pnpm-workspace", "root-readme", "root-turbo", "tooling-eslint", "tooling-tsconfig", "tooling-wire", "vscode", "web", "web-tests"], "02-docs": [], diff --git a/tests/web/docs/architecture.md b/tests/web/docs/architecture.md new file mode 100644 index 0000000..30f3901 --- /dev/null +++ b/tests/web/docs/architecture.md @@ -0,0 +1,8 @@ +# web-tests — architecture + +A test package at `tests/web`. Its lane runs the suite before it builds. + +## Suites (2) + +- `blob.test.ts` +- `site.test.ts` diff --git a/tests/web/docs/overview.md b/tests/web/docs/overview.md new file mode 100644 index 0000000..6e02b2d --- /dev/null +++ b/tests/web/docs/overview.md @@ -0,0 +1,18 @@ +# web-tests + +The test suite for **web**. It deploys nothing: its lane installs, builds and runs the tests. + +| | | +|---|---| +| Type | `turbo-package` | +| Source | `tests/web` | +| Package | `@app/web-tests` | +| Environments | `dev`: `quick-check` | + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/tests/web/docs/runbook.md b/tests/web/docs/runbook.md new file mode 100644 index 0000000..c687de2 --- /dev/null +++ b/tests/web/docs/runbook.md @@ -0,0 +1,26 @@ +# web-tests — runbook + +## How it runs + +Its lane runs on every pull request that changes it; it has no deployed surface. +CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`; +the plan orders a component after everything it depends on. + +## Local commands + +```bash +pnpm --filter @app/web-tests build +pnpm --filter @app/web-tests test +pnpm --filter @app/web-tests typecheck +pnpm --filter @app/web-tests lint +``` + +## Rollback + +Revert the commit on `main`. The next convergence applies the previous desired +state; nothing was changed out of band, so there is nothing else to undo. + +## Common failures + +- **A dependent fails to build after a change here**: run `pnpm typecheck` + across the workspace before merging. diff --git a/tests/web/src/blob.test.ts b/tests/web/src/blob.test.ts index 736ae9b..78b0125 100644 --- a/tests/web/src/blob.test.ts +++ b/tests/web/src/blob.test.ts @@ -29,13 +29,39 @@ beforeEach(() => { store.get.mockClear(); }); +// The raster formats an upload may be. SVG is an image too, but a document +// that can run script — served from the app's origin, a stored XSS. +const RASTER = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/avif"]; + describe("lib/blob/server", () => { - it("accepts images only", async () => { - const { isAllowedContentType } = await import("@/lib/blob/server"); - expect(isAllowedContentType("image/png")).toBe(true); - expect(isAllowedContentType("image/webp")).toBe(true); + it("accepts raster images only", async () => { + const { ALLOWED_CONTENT_TYPES, isAllowedContentType } = await import("@/lib/blob/server"); + expect([...ALLOWED_CONTENT_TYPES]).toEqual(RASTER); + for (const type of RASTER) expect(isAllowedContentType(type)).toBe(true); expect(isAllowedContentType("application/pdf")).toBe(false); expect(isAllowedContentType(null)).toBe(false); + expect(isAllowedContentType("")).toBe(false); + }); + + it("refuses SVG, a wildcard and look-alikes, whatever the case or parameters", async () => { + const { isAllowedContentType } = await import("@/lib/blob/server"); + expect(isAllowedContentType("image/svg+xml")).toBe(false); + expect(isAllowedContentType("IMAGE/SVG+XML")).toBe(false); + expect(isAllowedContentType("image/svg+xml; charset=utf-8")).toBe(false); + expect(isAllowedContentType("image/*")).toBe(false); + expect(isAllowedContentType("image/pngx")).toBe(false); + expect(isAllowedContentType("text/html")).toBe(false); + expect(isAllowedContentType("image/png, image/svg+xml")).toBe(false); + // …while the media type alone decides: parameters and case do not. + expect(isAllowedContentType("IMAGE/PNG")).toBe(true); + expect(isAllowedContentType("image/jpeg; charset=binary")).toBe(true); + }); + + it("gives the browser the same list as the route", async () => { + const server = await import("@/lib/blob/server"); + const client = await import("@/lib/blob/client"); + expect(client.ALLOWED_CONTENT_TYPES).toBe(server.ALLOWED_CONTENT_TYPES); + expect(client.isAllowedContentType).toBe(server.isAllowedContentType); }); it("adds a random suffix before the extension, like Blob's addRandomSuffix", async () => { @@ -68,6 +94,31 @@ describe("PUT /api/upload", () => { expect(store.put).not.toHaveBeenCalled(); }); + it("refuses an SVG with 400 and stores nothing", async () => { + const svg = ''; + for (const type of ["image/svg+xml", "image/SVG+xml; charset=utf-8"]) { + const res = await put({ pathname: "logo.svg", type, body: svg }); + expect(res.status).toBe(400); + expect(((await res.json()) as { error: string }).error).toBe( + "We only accept PNG, JPEG, GIF, WebP and AVIF images", + ); + } + expect(store.put).not.toHaveBeenCalled(); + expect(objects.size).toBe(0); + }); + + it("accepts each raster type", async () => { + for (const type of RASTER) { + const ext = type.split("/")[1]; + const res = await put({ pathname: `photo.${ext}`, type, body: new Uint8Array([1, 2, 3]) }); + expect(res.status, type).toBe(200); + const json = (await res.json()) as { pathname: string; contentType: string }; + expect(json.contentType).toBe(type); + expect(objects.get(json.pathname)?.contentType).toBe(type); + } + expect(store.put).toHaveBeenCalledTimes(RASTER.length); + }); + it("stores an image under a suffixed pathname and returns it", async () => { const res = await put({ pathname: "photo.png", type: "image/png", body: new Uint8Array([1, 2, 3]) }); expect(res.status).toBe(200); @@ -93,6 +144,19 @@ describe("GET /api/blob", () => { expect(res.status).toBe(200); expect(res.headers.get("content-type")).toBe("image/png"); expect(res.headers.get("x-content-type-options")).toBe("nosniff"); + expect(res.headers.get("content-security-policy")).toBe("default-src 'none'; sandbox"); expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([9, 8, 7])); }); + + it("serves an SVG already in the bucket sandboxed, so its script cannot run", async () => { + const svg = new TextEncoder().encode(''); + objects.set("old-1.svg", { body: svg.buffer as ArrayBuffer, contentType: "image/svg+xml" }); + const { GET } = await import("@/app/api/blob/route"); + const res = await GET(new NextRequest("https://app.example.com/api/blob?pathname=old-1.svg")); + expect(res.status).toBe(200); + expect(res.headers.get("x-content-type-options")).toBe("nosniff"); + const csp = res.headers.get("content-security-policy") ?? ""; + expect(csp).toContain("default-src 'none'"); + expect(csp.split(";").map((d) => d.trim())).toContain("sandbox"); + }); }); diff --git a/tooling/catalog/gen-component-docs.py b/tooling/catalog/gen-component-docs.py new file mode 100644 index 0000000..2a6a8b8 --- /dev/null +++ b/tooling/catalog/gen-component-docs.py @@ -0,0 +1,519 @@ +#!/usr/bin/env python3 +"""Generate each component's docs (overview / architecture / runbook). + + python3 tooling/catalog/gen-component-docs.py # write + python3 tooling/catalog/gen-component-docs.py --check # fail on drift (CI) + +The Orun workspace's Docs library renders the `docs/` folder next to every +`component.yaml`. These pages are generated, not hand-written, because almost +everything in them is already declared somewhere CI validates: the component's +manifest (type, description, dependencies, environments, the secrets a lane +resolves, the smoke), its Worker config (bindings, triggers, the wiring the +deploy fills in), its Terraform (resources and outputs), its migrations and its +package scripts. A hand-written copy of those facts drifts the first time one +changes; a generated one cannot, because `--check` fails the pull request that +changes the fact without the page. + +What is NOT derivable (why a component exists, what a failure means for this +product in particular) belongs in the component's `description` and in the +product's own docs, not here. + +The pages ship with the component into every product built from this tree, so +they say nothing about where they came from: no factory paths, no generator +path, no provenance. Zero dependencies beyond PyYAML. +""" + +from __future__ import annotations + +import json +import pathlib +import re +import sys + +try: + import yaml +except ImportError: # pragma: no cover - the contract job installs it + sys.exit("gen-component-docs needs PyYAML (pip install pyyaml)") + +ROOT = pathlib.Path(__file__).resolve().parents[2] +ROOTS = ("apps", "packages", "infra", "tests") +SKIP_DIRS = {"node_modules", "dist", ".turbo", "docs", ".next", ".open-next", + ".wrangler", ".svelte-kit", ".nuxt", ".output", ".astro", "coverage"} + +# Paths a shipped page must never name: products are not placed with them. +FACTORY = re.compile( + r"repo-blueprint|BOOTSTRAP\.md|(? str: + """JSONC → JSON: drop comments outside strings, then trailing commas.""" + out, i, n, in_str = [], 0, len(text), False + while i < n: + c = text[i] + if in_str: + out.append(c) + if c == "\\" and i + 1 < n: + out.append(text[i + 1]) + i += 2 + continue + if c == '"': + in_str = False + i += 1 + continue + if c == '"': + in_str = True + out.append(c) + i += 1 + elif text.startswith("//", i): + j = text.find("\n", i) + i = n if j < 0 else j + elif text.startswith("/*", i): + j = text.find("*/", i + 2) + i = n if j < 0 else j + 2 + else: + out.append(c) + i += 1 + return re.sub(r",(\s*[}\]])", r"\1", "".join(out)) + + +def read_json(path: pathlib.Path) -> dict | None: + try: + return json.loads(strip_jsonc(path.read_text(encoding="utf-8"))) + except (OSError, ValueError): + return None + + +def rel(p: pathlib.Path) -> str: + return p.relative_to(ROOT).as_posix() + + +def discover() -> list[dict]: + found = [] + for root in ROOTS: + base = ROOT / root + if not base.is_dir(): + continue + stack = [base] + while stack: + d = stack.pop() + for entry in sorted(d.iterdir()): + if entry.is_dir(): + if entry.name in SKIP_DIRS or entry.name.startswith("."): + continue + if (entry / "main.tf").exists() and not (entry / "component.yaml").exists(): + continue + if len(entry.relative_to(base).parts) <= 3: + stack.append(entry) + elif entry.name == "component.yaml": + found.append(read_component(entry)) + comps = [c for c in found if c["name"] and c["type"]] + return sorted(comps, key=lambda c: c["name"]) + + +def read_component(file: pathlib.Path) -> dict: + doc = yaml.safe_load(file.read_text(encoding="utf-8")) or {} + meta, spec = doc.get("metadata") or {}, doc.get("spec") or {} + params = spec.get("parameters") or {} + deps = [d.get("component") for d in (spec.get("dependsOn") or []) if isinstance(d, dict)] + envs = [] + for e in ((spec.get("subscribe") or {}).get("environments") or []): + rules = [(r.get("profile"), ((r.get("when") or {}).get("triggerRef"))) + for r in (e.get("profileRules") or [])] + envs.append({"name": e.get("name"), "profile": e.get("profile"), "rules": rules}) + return { + "dir": file.parent, + "path": rel(file.parent), + "name": meta.get("name"), + "description": (meta.get("description") or "").strip(), + "type": spec.get("type"), + "deps": [d for d in deps if d], + "secret_env": sorted((spec.get("secretEnv") or {}).keys()), + "envs": envs, + "params": params, + "migrations_path": spec.get("path") if spec.get("type") == "db-migrate" else None, + } + + +def package_of(c: dict) -> dict | None: + return read_json(c["dir"] / "package.json") + + +def worker_config(c: dict) -> tuple[str | None, dict | None]: + """The config a deploy uses: the template when wiring renders one.""" + names = ["wrangler.template.jsonc", c["params"].get("wranglerConfig") or "", + "wrangler.jsonc", "wrangler.json"] + for name in names: + if name and (c["dir"] / name).is_file(): + return name, read_json(c["dir"] / name) + return None, None + + +WIRING = re.compile(r"@@wiring\(([^/)]+)/__ENV__:([^)]+)\)@@") + + +def wired(value) -> str | None: + m = WIRING.search(str(value)) if value is not None else None + return f"`{m.group(2)}` from `{m.group(1)}`" if m else None + + +def bindings(cfg: dict) -> list[tuple[str, str, str]]: + rows = [] + for kv in cfg.get("kv_namespaces") or []: + rows.append((kv.get("binding"), "Workers KV namespace", wired(kv.get("id")) or "declared in the config")) + for b in cfg.get("r2_buckets") or []: + rows.append((b.get("binding"), "R2 bucket", wired(b.get("bucket_name")) or f"`{b.get('bucket_name')}`")) + for d in cfg.get("d1_databases") or []: + rows.append((d.get("binding"), "D1 database", wired(d.get("database_id")) or "declared in the config")) + for h in cfg.get("hyperdrive") or []: + rows.append((h.get("binding"), "Hyperdrive (pooled Postgres)", wired(h.get("id")) or "declared in the config")) + if isinstance(cfg.get("ai"), dict) and cfg["ai"].get("binding"): + rows.append((cfg["ai"]["binding"], "Workers AI", "account-level; no resource to provision")) + for d in ((cfg.get("durable_objects") or {}).get("bindings") or []): + rows.append((d.get("name"), "Durable Object", f"class `{d.get('class_name')}`")) + for s in cfg.get("services") or []: + rows.append((s.get("binding"), "Service binding", f"Worker `{s.get('service')}`")) + for q in ((cfg.get("queues") or {}).get("producers") or []): + rows.append((q.get("binding"), "Queue producer", f"queue `{q.get('queue')}`")) + for r in cfg.get("ratelimits") or []: + simple = r.get("simple") or {} + rows.append((r.get("name"), "Rate limiter", + f"{simple.get('limit')} requests / {simple.get('period')}s per location")) + assets = cfg.get("assets") or {} + if assets.get("binding"): + rows.append((assets["binding"], "Static assets", f"`{assets.get('directory')}`")) + return [r for r in rows if r[0]] + + +def tf_facts(c: dict) -> dict: + tf_dir = c["dir"] / (c["params"].get("terraformDir") or "terraform") + resources, outputs, variables, backend = [], [], [], None + for f in sorted(tf_dir.glob("*.tf")) if tf_dir.is_dir() else []: + text = f.read_text(encoding="utf-8") + resources += [f"{t}.{n}" for t, n in re.findall(r'^resource\s+"([^"]+)"\s+"([^"]+)"', text, re.M)] + outputs += re.findall(r'^output\s+"([^"]+)"', text, re.M) + variables += re.findall(r'^variable\s+"([^"]+)"', text, re.M) + m = re.search(r'backend\s+"([^"]+)"', text) + backend = backend or (m.group(1) if m else None) + imports = (tf_dir / "adopt.tf").is_file() if tf_dir.is_dir() else False + return {"dir": rel(tf_dir) if tf_dir.is_dir() else None, "resources": resources, + "outputs": outputs, "variables": variables, "backend": backend, "adopt": imports} + + +def published(c: dict) -> list[tuple[str, str]]: + spec = c["params"].get("secretOutputs") or "" + pairs = [] + for part in str(spec).split(","): + if "=" in part: + k, v = part.split("=", 1) + pairs.append((k.strip(), v.strip())) + return pairs + + +def test_files(c: dict) -> list[str]: + out = [] + for p in sorted(c["dir"].rglob("*")): + if any(part in SKIP_DIRS for part in p.relative_to(c["dir"]).parts): + continue + if p.is_file() and re.search(r"\.(test|spec)\.(ts|tsx|js|mjs|cjs)$", p.name): + out.append(p.name) + return out + + +def migrations(c: dict) -> list[str]: + path = c["migrations_path"] + if not path: + return [] + d = ROOT / path + if not d.is_dir(): + return [] + return sorted(p.name for p in d.iterdir() if p.is_dir() or p.suffix == ".sql") + + +# ── phrasing ───────────────────────────────────────────────────────────── + +KIND = { + "cloudflare-worker-turbo": "A Cloudflare Worker, deployed per environment by its CI lane.", + "cloudflare-workers-assets-turbo": "A Cloudflare Worker with Static Assets (server rendering plus " + "static files), deployed per environment by its CI lane.", + "terraform": "Terraform-managed infrastructure, planned and applied per environment by its CI lane.", + "db-migrate": "Applies this repository's ordered database migrations per environment: " + "plan on pull requests, apply on merge to `main`.", + "turbo-package": "A workspace package built by the turbo pipeline. It deploys nothing itself: " + "its lane type-checks, lints, tests and builds it.", +} + +TRIGGER = {"github-push-main": "a push to `main`", "github-pull-request": "a pull request"} + + +def env_line(e: dict) -> str: + s = f"`{e['name']}`: `{e['profile']}`" + for profile, ref in e["rules"]: + s += f", `{profile}` on {TRIGGER.get(ref, f'`{ref}`')}" + return s + + +def is_tests(c: dict) -> bool: + return c["name"].endswith("-tests") or c["path"].startswith("tests/") + + +def subject_of(c: dict, by_name: dict) -> str | None: + if c["name"].endswith("-tests"): + s = c["name"][: -len("-tests")] + return s if s in by_name else None + return None + + +def bullet_list(names: list[str], by_name: dict) -> list[str]: + if not names: + return ["- (none)"] + out = [] + for n in names: + d = by_name.get(n) + out.append(f"- **{n}** — {d['description']}" if d and d["description"] else f"- **{n}**") + return out + + +# ── pages ──────────────────────────────────────────────────────────────── + +def overview(c: dict, by_name: dict, dependents: list[str]) -> str: + pkg = package_of(c) + kind = KIND.get(c["type"], f"A `{c['type']}` component.") + subject = subject_of(c, by_name) + if is_tests(c): + kind = (f"The test suite for **{subject}**. " if subject else "A test suite. ") + \ + "It deploys nothing: its lane installs, builds and runs the tests." + lines = [f"# {c['name']}", ""] + if c["description"]: + lines += [c["description"], ""] + lines += [kind, "", "| | |", "|---|---|", f"| Type | `{c['type']}` |", f"| Source | `{c['path']}` |"] + if pkg and pkg.get("name"): + lines.append(f"| Package | `{pkg['name']}` |") + if c["envs"]: + lines.append(f"| Environments | {' · '.join(env_line(e) for e in c['envs'])} |") + lines += ["", "## Depends on", "", *bullet_list(c["deps"], by_name), + "", "## Depended on by", "", *bullet_list(dependents, by_name), ""] + return "\n".join(lines) + + +def architecture(c: dict, by_name: dict) -> str: + lines = [f"# {c['name']} — architecture", ""] + t = c["type"] + + if t == "terraform": + f = tf_facts(c) + lines += [f"A `terraform` root at `{f['dir'] or c['path']}`.", ""] + if f["backend"] == "http": + lines += ["- **State** lives in the Orun Cloud HTTP state backend — no local state and", + " no state bucket to manage."] + lines += ["- **Credentials are brokered per run** from the workspace's provider", + " connections and resolved by name; none is stored in this repository."] + if f["adopt"]: + lines += ["- **Adoption** (`adopt.tf`): when state is empty but the resource already", + " exists, plan-time import adopts it instead of failing."] + lines.append("") + if f["resources"]: + lines += ["## Resources", "", *[f"- `{r}`" for r in f["resources"]], ""] + pub = published(c) + if pub: + lines += ["## Published outputs", "", + "Written as job-output secrets on each environment after an apply; deploy", + "lanes downstream resolve them by name.", "", + "| Secret | Terraform output |", "|---|---|", + *[f"| `{k}` | `{v}` |" for k, v in pub], ""] + elif f["outputs"]: + lines += ["## Outputs", "", *[f"- `{o}`" for o in f["outputs"]], ""] + if c["secret_env"]: + lines += ["## Resolved at run time (names only)", "", + *[f"- `{k}`" for k in c["secret_env"]], ""] + return "\n".join(lines) + + if t == "db-migrate": + migs = migrations(c) + lines += [f"Applies the migrations under `{c['migrations_path']}` in order, recording each one", + "it applies so a run only ever applies what is new. An already-applied migration", + "is never edited: a change is a new, later migration.", ""] + if migs: + lines += ["## Migrations", "", *[f"- `{m}`" for m in migs], ""] + if c["secret_env"]: + lines += ["## Resolved at run time (names only)", "", + *[f"- `{k}`" for k in c["secret_env"]], ""] + return "\n".join(lines) + + pkg = package_of(c) + if t.startswith("cloudflare-"): + cfg_name, cfg = worker_config(c) + lines += [f"Built by the turbo pipeline from `{c['path']}` and deployed with wrangler.", ""] + if cfg: + lines += ["| | |", "|---|---|", f"| Worker config | `{c['path']}/{cfg_name}` |"] + if cfg.get("main"): + lines.append(f"| Entry | `{cfg['main']}` |") + if cfg.get("compatibility_date"): + lines.append(f"| Compatibility date | `{cfg['compatibility_date']}` |") + if cfg.get("compatibility_flags"): + lines.append(f"| Compatibility flags | {', '.join(f'`{x}`' for x in cfg['compatibility_flags'])} |") + lines.append("") + rows = bindings(cfg) + lines += ["## Bindings", ""] + if rows: + lines += ["| Binding | Kind | Source |", "|---|---|---|", + *[f"| `{b}` | {k} | {s} |" for b, k, s in rows], ""] + if any("from `" in s for _, _, s in rows): + lines += ["Identifiers marked *from* a component are filled in at deploy time from", + "that component's published outputs for the environment being deployed.", ""] + else: + lines += ["None: the Worker binds no storage or service.", ""] + crons = (cfg.get("triggers") or {}).get("crons") or [] + if crons: + lines += ["## Scheduled triggers", "", *[f"- `{x}`" for x in crons], ""] + env_names = sorted((cfg.get("env") or {}).keys()) + var_names = sorted((cfg.get("vars") or {}).keys()) + if var_names: + lines += ["## Variables", "", ", ".join(f"`{v}`" for v in var_names) + + (f" — overridden per environment ({', '.join(f'`{e}`' for e in env_names)})." + if env_names else "."), ""] + wiring = [k for k in c["secret_env"] if k.startswith("WIRING_")] + others = [k for k in c["secret_env"] if not k.startswith("WIRING_")] + if wiring: + lines += ["## Wiring", "", + "Resolved at deploy time from secrets the infrastructure lanes publish (names only):", + "", *[f"- `{k}`" for k in wiring], ""] + if others: + lines += ["## Secrets resolved by the lane (names only)", "", *[f"- `{k}`" for k in others], ""] + return "\n".join(lines) + + # turbo-package + if is_tests(c): + files = test_files(c) + lines += [f"A test package at `{c['path']}`. Its lane runs the suite before it builds.", ""] + if files: + lines += [f"## Suites ({len(files)})", "", *[f"- `{f}`" for f in files], ""] + return "\n".join(lines) + lines += [f"A workspace package at `{c['path']}`, consumed at build time by the components", + "that depend on it. It holds no credentials and opens no connections of its own.", ""] + if pkg and pkg.get("exports"): + ex = pkg["exports"] + keys = sorted(ex.keys()) if isinstance(ex, dict) else ["."] + lines += ["## Exports", "", *[f"- `{k}`" for k in keys], ""] + return "\n".join(lines) + + +def runbook(c: dict, by_name: dict) -> str: + t = c["type"] + pkg = package_of(c) + lines = [f"# {c['name']} — runbook", "", "## How it runs", ""] + deploys = [e["name"] for e in c["envs"] + if any(ref == "github-push-main" for _, ref in e["rules"])] + if deploys and t in ("terraform", "db-migrate"): + lines += [f"Pull requests plan it; a merge to `main` applies it to " + f"{', '.join(f'`{e}`' for e in deploys)}."] + elif deploys: + lines += [f"Pull requests verify it; a merge to `main` deploys it to " + f"{', '.join(f'`{e}`' for e in deploys)}."] + else: + lines += ["Its lane runs on every pull request that changes it; it has no deployed surface."] + lines += ["CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`;", + "the plan orders a component after everything it depends on.", ""] + + if pkg and pkg.get("scripts"): + name = pkg.get("name") + wanted = [s for s in ("dev", "build", "test", "typecheck", "lint", "preview") if s in pkg["scripts"]] + if name and wanted: + lines += ["## Local commands", "", "```bash", + *[f"pnpm --filter {name} {s}" for s in wanted], "```", ""] + + smoke = c["params"].get("smokeCommand") + if smoke and "No smoke" not in str(smoke): + lines += ["## Verify", "", "After a deploy the lane runs this smoke against the environment it", + "deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL:", "", + "```bash", str(smoke).strip(), "```", ""] + + lines += ["## Rollback", "", + "Revert the commit on `main`. The next convergence applies the previous desired", + "state; nothing was changed out of band, so there is nothing else to undo.", "", + "## Common failures", ""] + if t == "terraform": + lines += ["- **Provider authentication fails**: the workspace's provider connection is", + " missing or revoked. Reconnect it in the console; credentials are brokered", + " from it per run.", + "- **\"Already exists\" on a first apply**: state is empty but the resource is", + " not." + (" `adopt.tf` imports it at plan time; if it still fails, the resource" + " was renamed outside Terraform." if tf_facts(c)["adopt"] else + " Import it, or delete the stray resource, then re-run."), ""] + elif t == "db-migrate": + lines += ["- **An applied migration's file changed**: the run stops rather than guess.", + " Restore the file and write the change as a new migration.", + "- **The database is unreachable**: the infrastructure lane it depends on has", + " not applied for this environment; that lane runs first in a convergence.", ""] + elif t.startswith("cloudflare-"): + lines += ["- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream", + " has not applied for this environment yet. Within one convergence the plan", + " runs it first; on its own, re-run that lane.", + "- **The smoke fails right after a first deploy**: a new workers.dev route can", + " answer 4xx for a few seconds and the lane retries. A failure that persists", + " is a regression in the deployed code.", ""] + else: + lines += ["- **A dependent fails to build after a change here**: run `pnpm typecheck`", + " across the workspace before merging.", ""] + return "\n".join(lines) + + +# ── main ───────────────────────────────────────────────────────────────── + +def main() -> int: + check = "--check" in sys.argv[1:] + comps = discover() + if not comps: + print("no component.yaml found", file=sys.stderr) + return 1 + by_name = {c["name"]: c for c in comps} + dependents: dict[str, list[str]] = {c["name"]: [] for c in comps} + for c in comps: + for d in c["deps"]: + dependents.setdefault(d, []).append(c["name"]) + + drifted, written, leaks = [], 0, [] + for c in comps: + pages = { + "overview.md": overview(c, by_name, sorted(dependents.get(c["name"], []))), + "architecture.md": architecture(c, by_name), + "runbook.md": runbook(c, by_name), + } + for fname, body in pages.items(): + target = c["dir"] / "docs" / fname + for n, line in enumerate(body.splitlines(), 1): + m = FACTORY.search(line) + if m: + leaks.append(f"{rel(target)}:{n} would name {m.group(0)!r}") + current = target.read_text(encoding="utf-8") if target.exists() else None + if current == body: + continue + if check: + drifted.append(rel(target)) + continue + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(body, encoding="utf-8") + written += 1 + + if leaks: + print("✗ a generated page would name a path products do not have:", file=sys.stderr) + for l in leaks: + print(f" {l}", file=sys.stderr) + return 1 + if check: + if drifted: + print(f"✗ {len(drifted)} component doc(s) differ from what the manifests say:", file=sys.stderr) + for f in drifted: + print(f" {f}", file=sys.stderr) + print("\nRun: python3 tooling/catalog/gen-component-docs.py", file=sys.stderr) + return 1 + print(f"✓ component docs match {len(comps)} component.yaml file(s)") + return 0 + print(f"✓ wrote {written} page(s) for {len(comps)} component(s)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tooling/rebrand/rebrand.mjs b/tooling/rebrand/rebrand.mjs index c5851cd..b7d6510 100644 --- a/tooling/rebrand/rebrand.mjs +++ b/tooling/rebrand/rebrand.mjs @@ -180,7 +180,6 @@ const EXCLUDE_RE = new RegExp( // product claim to be a baseline called by the product's own name. "^\\.baseline/", "^pnpm-lock\\.yaml$", - "^kiox\\.lock$", "\\.(png|jpg|jpeg|ico|gif|webp|woff2?|ttf|eot)$", ].join("|"), ); From 870ca7389454f3372313cbaf90397fe1332bc645 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 18 Oct 2026 14:31:53 +0000 Subject: [PATCH 2/5] Regenerate component docs: prettier-padded tables, accurate wording The generator now lays tables out the way prettier does (an app whose lint is `prettier --check` accepts the pages as written), lists the WIRING_* failure only for Workers that take wiring, and no longer claims a package holds no credentials. - Word the kiox exit criterion as it can be true: nothing outside this milestone's own record names kiox. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01D8AmgTwmnp4M8mgmnS9aha --- apps/web/docs/architecture.md | 20 +++---- apps/web/docs/overview.md | 10 ++-- .../cloudflare-r2/docs/architecture.md | 6 +-- .../terraform/cloudflare-r2/docs/overview.md | 8 +-- specs/epics/blob-starter/epic.yaml | 2 +- .../epics/blob-starter/implementation-plan.md | 2 +- tasks/BL-6.TaskContract.yaml | 2 +- tests/web/docs/overview.md | 10 ++-- tooling/catalog/gen-component-docs.py | 53 ++++++++++++------- 9 files changed, 64 insertions(+), 49 deletions(-) diff --git a/apps/web/docs/architecture.md b/apps/web/docs/architecture.md index 46c05f2..2dc1dcb 100644 --- a/apps/web/docs/architecture.md +++ b/apps/web/docs/architecture.md @@ -2,21 +2,21 @@ Built by the turbo pipeline from `apps/web` and deployed with wrangler. -| | | -|---|---| -| Worker config | `apps/web/wrangler.template.jsonc` | -| Entry | `.open-next/worker.js` | -| Compatibility date | `2026-10-01` | +| | | +| ------------------- | ----------------------------------------------- | +| Worker config | `apps/web/wrangler.template.jsonc` | +| Entry | `.open-next/worker.js` | +| Compatibility date | `2026-10-01` | | Compatibility flags | `nodejs_compat`, `global_fetch_strictly_public` | ## Bindings -| Binding | Kind | Source | -|---|---|---| -| `BLOB` | R2 bucket | `r2_bucket_name` from `cloudflare-r2` | -| `ASSETS` | Static assets | `.open-next/assets` | +| Binding | Kind | Source | +| -------- | ------------- | ------------------------------------- | +| `BLOB` | R2 bucket | `r2_bucket_name` from `cloudflare-r2` | +| `ASSETS` | Static assets | `.open-next/assets` | -Identifiers marked *from* a component are filled in at deploy time from +Identifiers marked _from_ a component are filled in at deploy time from that component's published outputs for the environment being deployed. ## Wiring diff --git a/apps/web/docs/overview.md b/apps/web/docs/overview.md index 1ea6bfd..a2936ca 100644 --- a/apps/web/docs/overview.md +++ b/apps/web/docs/overview.md @@ -4,11 +4,11 @@ The image uploader (Next.js on Cloudflare Workers + Static Assets via @opennextj A Cloudflare Worker with Static Assets (server rendering plus static files), deployed per environment by its CI lane. -| | | -|---|---| -| Type | `cloudflare-workers-assets-turbo` | -| Source | `apps/web` | -| Package | `@app/web` | +| | | +| ------------ | ------------------------------------------------------------------------------------------------------------------ | +| Type | `cloudflare-workers-assets-turbo` | +| Source | `apps/web` | +| Package | `@app/web` | | Environments | `dev`: `verify` · `stage`: `verify`, `deploy` on a push to `main` · `prod`: `verify`, `deploy` on a push to `main` | ## Depends on diff --git a/infra/terraform/cloudflare-r2/docs/architecture.md b/infra/terraform/cloudflare-r2/docs/architecture.md index f528c5b..a0da9e1 100644 --- a/infra/terraform/cloudflare-r2/docs/architecture.md +++ b/infra/terraform/cloudflare-r2/docs/architecture.md @@ -18,9 +18,9 @@ A `terraform` root at `infra/terraform/cloudflare-r2/terraform`. Written as job-output secrets on each environment after an apply; deploy lanes downstream resolve them by name. -| Secret | Terraform output | -|---|---| -| `WIRING_CLOUDFLARE_R2` | `wiring` | +| Secret | Terraform output | +| ---------------------- | ---------------- | +| `WIRING_CLOUDFLARE_R2` | `wiring` | ## Resolved at run time (names only) diff --git a/infra/terraform/cloudflare-r2/docs/overview.md b/infra/terraform/cloudflare-r2/docs/overview.md index 5cda23e..69c7ee8 100644 --- a/infra/terraform/cloudflare-r2/docs/overview.md +++ b/infra/terraform/cloudflare-r2/docs/overview.md @@ -4,10 +4,10 @@ Provisions the Cloudflare R2 bucket the app binds (stage and prod) Terraform-managed infrastructure, planned and applied per environment by its CI lane. -| | | -|---|---| -| Type | `terraform` | -| Source | `infra/terraform/cloudflare-r2` | +| | | +| ------------ | ---------------------------------------------------------------------------------------------------- | +| Type | `terraform` | +| Source | `infra/terraform/cloudflare-r2` | | Environments | `stage`: `plan-only`, `apply` on a push to `main` · `prod`: `plan-only`, `apply` on a push to `main` | ## Depends on diff --git a/specs/epics/blob-starter/epic.yaml b/specs/epics/blob-starter/epic.yaml index 28acc7a..85886ea 100644 --- a/specs/epics/blob-starter/epic.yaml +++ b/specs/epics/blob-starter/epic.yaml @@ -42,7 +42,7 @@ spec: - name: "BL5 — the cirrus standard, SVG uploads closed" exitCriteria: - "uploads are raster images only (PNG, JPEG, GIF, WebP, AVIF) — an SVG is refused — and the delivery route serves every object under a CSP that sandboxes it, so nothing stored can run script on the app's origin" - - "no file names kiox: orun is pinned where CI runs it (the orun-action `version:` in each workflow)" + - "nothing outside this milestone's own record names kiox: orun is pinned where CI runs it (the orun-action `version:` in each workflow)" - "every component carries generated docs/{overview,architecture,runbook}.md, and Baseline CI fails a pull request whose manifests and pages disagree" - "ai/context carries this repository's current.md, decisions.md and open-risks.md, and none of them ships to a product" - "every milestone's status row agrees with the tags" diff --git a/specs/epics/blob-starter/implementation-plan.md b/specs/epics/blob-starter/implementation-plan.md index d24bbd4..0d0964b 100644 --- a/specs/epics/blob-starter/implementation-plan.md +++ b/specs/epics/blob-starter/implementation-plan.md @@ -87,7 +87,7 @@ standard around it. - `tests/web` refuses an SVG upload (400), stores each raster type, and finds the policy on a served object; `testing/e2e.test.sh` does the same against the built Worker -- `git grep -i kiox` finds nothing, and the leak gate and the offline +- `git grep -i kiox` finds only this milestone's own record, and the leak gate and the offline bootstrap pass without the two modules - the docs check is green in Baseline CI - this file, the status file and `epic.yaml` agree diff --git a/tasks/BL-6.TaskContract.yaml b/tasks/BL-6.TaskContract.yaml index 7ce23ca..ef645d5 100644 --- a/tasks/BL-6.TaskContract.yaml +++ b/tasks/BL-6.TaskContract.yaml @@ -30,7 +30,7 @@ spec: doneWhen: - an SVG upload is refused (400) and each raster type (PNG, JPEG, GIF, WebP, AVIF) is stored, in tests/web and against the built Worker in testing/e2e.test.sh - "the delivery route answers every object with `Content-Security-Policy: default-src 'none'; sandbox` and `nosniff`" - - no file names kiox, and the leak gate and the offline bootstrap place a product without it + - nothing outside this milestone's own record names kiox, and the leak gate and the offline bootstrap place a product without it - every component has docs/overview.md, docs/architecture.md and docs/runbook.md, and `python3 tooling/catalog/gen-component-docs.py --check` is green in Baseline CI - ai/context carries current.md, decisions.md and open-risks.md for this repository (none of them ships) - every milestone's status row agrees with the tags diff --git a/tests/web/docs/overview.md b/tests/web/docs/overview.md index 6e02b2d..3534e6b 100644 --- a/tests/web/docs/overview.md +++ b/tests/web/docs/overview.md @@ -2,11 +2,11 @@ The test suite for **web**. It deploys nothing: its lane installs, builds and runs the tests. -| | | -|---|---| -| Type | `turbo-package` | -| Source | `tests/web` | -| Package | `@app/web-tests` | +| | | +| ------------ | -------------------- | +| Type | `turbo-package` | +| Source | `tests/web` | +| Package | `@app/web-tests` | | Environments | `dev`: `quick-check` | ## Depends on diff --git a/tooling/catalog/gen-component-docs.py b/tooling/catalog/gen-component-docs.py index 2a6a8b8..cda768f 100644 --- a/tooling/catalog/gen-component-docs.py +++ b/tooling/catalog/gen-component-docs.py @@ -232,6 +232,18 @@ def migrations(c: dict) -> list[str]: return sorted(p.name for p in d.iterdir() if p.is_dir() or p.suffix == ".sql") +# ── markdown ───────────────────────────────────────────────────────────── + +def md_table(header: list[str], rows: list[list[str]]) -> list[str]: + """A table laid out the way prettier lays it out, so a repo whose lint is + `prettier --check` accepts the page as written.""" + cols = len(header) + width = [max(3, len(header[i]), *(len(r[i]) for r in rows)) for i in range(cols)] + def line(cells): + return "| " + " | ".join(c.ljust(width[i]) for i, c in enumerate(cells)) + " |" + return [line(header), "| " + " | ".join("-" * w for w in width) + " |", *(line(r) for r in rows)] + + # ── phrasing ───────────────────────────────────────────────────────────── KIND = { @@ -288,11 +300,12 @@ def overview(c: dict, by_name: dict, dependents: list[str]) -> str: lines = [f"# {c['name']}", ""] if c["description"]: lines += [c["description"], ""] - lines += [kind, "", "| | |", "|---|---|", f"| Type | `{c['type']}` |", f"| Source | `{c['path']}` |"] + facts = [["Type", f"`{c['type']}`"], ["Source", f"`{c['path']}`"]] if pkg and pkg.get("name"): - lines.append(f"| Package | `{pkg['name']}` |") + facts.append(["Package", f"`{pkg['name']}`"]) if c["envs"]: - lines.append(f"| Environments | {' · '.join(env_line(e) for e in c['envs'])} |") + facts.append(["Environments", " · ".join(env_line(e) for e in c["envs"])]) + lines += [kind, "", *md_table(["", ""], facts)] lines += ["", "## Depends on", "", *bullet_list(c["deps"], by_name), "", "## Depended on by", "", *bullet_list(dependents, by_name), ""] return "\n".join(lines) @@ -321,8 +334,7 @@ def architecture(c: dict, by_name: dict) -> str: lines += ["## Published outputs", "", "Written as job-output secrets on each environment after an apply; deploy", "lanes downstream resolve them by name.", "", - "| Secret | Terraform output |", "|---|---|", - *[f"| `{k}` | `{v}` |" for k, v in pub], ""] + *md_table(["Secret", "Terraform output"], [[f"`{k}`", f"`{v}`"] for k, v in pub]), ""] elif f["outputs"]: lines += ["## Outputs", "", *[f"- `{o}`" for o in f["outputs"]], ""] if c["secret_env"]: @@ -347,21 +359,20 @@ def architecture(c: dict, by_name: dict) -> str: cfg_name, cfg = worker_config(c) lines += [f"Built by the turbo pipeline from `{c['path']}` and deployed with wrangler.", ""] if cfg: - lines += ["| | |", "|---|---|", f"| Worker config | `{c['path']}/{cfg_name}` |"] + facts = [["Worker config", f"`{c['path']}/{cfg_name}`"]] if cfg.get("main"): - lines.append(f"| Entry | `{cfg['main']}` |") + facts.append(["Entry", f"`{cfg['main']}`"]) if cfg.get("compatibility_date"): - lines.append(f"| Compatibility date | `{cfg['compatibility_date']}` |") + facts.append(["Compatibility date", f"`{cfg['compatibility_date']}`"]) if cfg.get("compatibility_flags"): - lines.append(f"| Compatibility flags | {', '.join(f'`{x}`' for x in cfg['compatibility_flags'])} |") - lines.append("") + facts.append(["Compatibility flags", ", ".join(f"`{x}`" for x in cfg["compatibility_flags"])]) + lines += [*md_table(["", ""], facts), ""] rows = bindings(cfg) lines += ["## Bindings", ""] if rows: - lines += ["| Binding | Kind | Source |", "|---|---|---|", - *[f"| `{b}` | {k} | {s} |" for b, k, s in rows], ""] + lines += [*md_table(["Binding", "Kind", "Source"], [[f"`{b}`", k, s] for b, k, s in rows]), ""] if any("from `" in s for _, _, s in rows): - lines += ["Identifiers marked *from* a component are filled in at deploy time from", + lines += ["Identifiers marked _from_ a component are filled in at deploy time from", "that component's published outputs for the environment being deployed.", ""] else: lines += ["None: the Worker binds no storage or service.", ""] @@ -391,8 +402,8 @@ def architecture(c: dict, by_name: dict) -> str: if files: lines += [f"## Suites ({len(files)})", "", *[f"- `{f}`" for f in files], ""] return "\n".join(lines) - lines += [f"A workspace package at `{c['path']}`, consumed at build time by the components", - "that depend on it. It holds no credentials and opens no connections of its own.", ""] + lines += [f"A workspace package at `{c['path']}`, consumed by the components that depend", + "on it. It has no deployed surface of its own.", ""] if pkg and pkg.get("exports"): ex = pkg["exports"] keys = sorted(ex.keys()) if isinstance(ex, dict) else ["."] @@ -448,10 +459,14 @@ def runbook(c: dict, by_name: dict) -> str: "- **The database is unreachable**: the infrastructure lane it depends on has", " not applied for this environment; that lane runs first in a convergence.", ""] elif t.startswith("cloudflare-"): - lines += ["- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream", - " has not applied for this environment yet. Within one convergence the plan", - " runs it first; on its own, re-run that lane.", - "- **The smoke fails right after a first deploy**: a new workers.dev route can", + _, cfg = worker_config(c) + takes_wiring = any(k.startswith("WIRING_") for k in c["secret_env"]) or \ + bool(cfg and WIRING.search(json.dumps(cfg))) + if takes_wiring: + lines += ["- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream", + " has not applied for this environment yet. Within one convergence the plan", + " runs it first; on its own, re-run that lane."] + lines += ["- **The smoke fails right after a first deploy**: a new workers.dev route can", " answer 4xx for a few seconds and the lane retries. A failure that persists", " is a regression in the deployed code.", ""] else: From 2992273a2e9f2c14a95d56ba0446cbe6869571db Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 18 Oct 2026 14:35:10 +0000 Subject: [PATCH 3/5] Component docs: list optional and per-environment secrets The generator now reads `optionalSecretEnv` (listed as "(optional)") and secrets declared per environment under `subscribe.environments[]`, so a page no longer leaves out a secret its component declares. Its tables are laid out as prettier lays them out, the WIRING_* failure is listed only for Workers that take wiring, and a package is no longer said to hold no credentials. Every starter now carries the identical generator. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01D8AmgTwmnp4M8mgmnS9aha --- tooling/catalog/gen-component-docs.py | 37 ++++++++++++++++++--------- 1 file changed, 25 insertions(+), 12 deletions(-) diff --git a/tooling/catalog/gen-component-docs.py b/tooling/catalog/gen-component-docs.py index cda768f..9a39931 100644 --- a/tooling/catalog/gen-component-docs.py +++ b/tooling/catalog/gen-component-docs.py @@ -119,7 +119,13 @@ def read_component(file: pathlib.Path) -> dict: params = spec.get("parameters") or {} deps = [d.get("component") for d in (spec.get("dependsOn") or []) if isinstance(d, dict)] envs = [] + # Secrets may be declared for the whole component or per environment + # (`subscribe.environments[].secretEnv`); a page lists both. + req_env = set((spec.get("secretEnv") or {}).keys()) + opt_env = set((spec.get("optionalSecretEnv") or {}).keys()) for e in ((spec.get("subscribe") or {}).get("environments") or []): + req_env |= set((e.get("secretEnv") or {}).keys()) + opt_env |= set((e.get("optionalSecretEnv") or {}).keys()) rules = [(r.get("profile"), ((r.get("when") or {}).get("triggerRef"))) for r in (e.get("profileRules") or [])] envs.append({"name": e.get("name"), "profile": e.get("profile"), "rules": rules}) @@ -130,7 +136,8 @@ def read_component(file: pathlib.Path) -> dict: "description": (meta.get("description") or "").strip(), "type": spec.get("type"), "deps": [d for d in deps if d], - "secret_env": sorted((spec.get("secretEnv") or {}).keys()), + "secret_env": sorted(req_env), + "optional_env": sorted(opt_env - req_env), "envs": envs, "params": params, "migrations_path": spec.get("path") if spec.get("type") == "db-migrate" else None, @@ -278,6 +285,14 @@ def subject_of(c: dict, by_name: dict) -> str | None: return None +def names_list(c: dict, keep) -> list[str]: + """Secret names a lane resolves, required first; an optional one (from + `optionalSecretEnv`) is resolved when it exists and skipped when not.""" + req = [f"- `{k}`" for k in c["secret_env"] if keep(k)] + opt = [f"- `{k}` (optional)" for k in c["optional_env"] if keep(k)] + return req + opt + + def bullet_list(names: list[str], by_name: dict) -> list[str]: if not names: return ["- (none)"] @@ -337,9 +352,8 @@ def architecture(c: dict, by_name: dict) -> str: *md_table(["Secret", "Terraform output"], [[f"`{k}`", f"`{v}`"] for k, v in pub]), ""] elif f["outputs"]: lines += ["## Outputs", "", *[f"- `{o}`" for o in f["outputs"]], ""] - if c["secret_env"]: - lines += ["## Resolved at run time (names only)", "", - *[f"- `{k}`" for k in c["secret_env"]], ""] + if c["secret_env"] or c["optional_env"]: + lines += ["## Resolved at run time (names only)", "", *names_list(c, lambda k: True), ""] return "\n".join(lines) if t == "db-migrate": @@ -349,9 +363,8 @@ def architecture(c: dict, by_name: dict) -> str: "is never edited: a change is a new, later migration.", ""] if migs: lines += ["## Migrations", "", *[f"- `{m}`" for m in migs], ""] - if c["secret_env"]: - lines += ["## Resolved at run time (names only)", "", - *[f"- `{k}`" for k in c["secret_env"]], ""] + if c["secret_env"] or c["optional_env"]: + lines += ["## Resolved at run time (names only)", "", *names_list(c, lambda k: True), ""] return "\n".join(lines) pkg = package_of(c) @@ -385,14 +398,14 @@ def architecture(c: dict, by_name: dict) -> str: lines += ["## Variables", "", ", ".join(f"`{v}`" for v in var_names) + (f" — overridden per environment ({', '.join(f'`{e}`' for e in env_names)})." if env_names else "."), ""] - wiring = [k for k in c["secret_env"] if k.startswith("WIRING_")] - others = [k for k in c["secret_env"] if not k.startswith("WIRING_")] + wiring = names_list(c, lambda k: k.startswith("WIRING_")) + others = names_list(c, lambda k: not k.startswith("WIRING_")) if wiring: lines += ["## Wiring", "", "Resolved at deploy time from secrets the infrastructure lanes publish (names only):", - "", *[f"- `{k}`" for k in wiring], ""] + "", *wiring, ""] if others: - lines += ["## Secrets resolved by the lane (names only)", "", *[f"- `{k}`" for k in others], ""] + lines += ["## Secrets resolved by the lane (names only)", "", *others, ""] return "\n".join(lines) # turbo-package @@ -460,7 +473,7 @@ def runbook(c: dict, by_name: dict) -> str: " not applied for this environment; that lane runs first in a convergence.", ""] elif t.startswith("cloudflare-"): _, cfg = worker_config(c) - takes_wiring = any(k.startswith("WIRING_") for k in c["secret_env"]) or \ + takes_wiring = any(k.startswith("WIRING_") for k in c["secret_env"] + c["optional_env"]) or \ bool(cfg and WIRING.search(json.dumps(cfg))) if takes_wiring: lines += ["- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream", From f1aafc9d8eaecc42a07af46312d08497fec0e356 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 21 Oct 2026 12:13:21 +0000 Subject: [PATCH 4/5] BL5: read the workers.dev subdomain from the Cloudflare connection MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - blueprint.yaml: the subdomain input declares `from: connection.cloudflare.workersSubdomain`; the console fills it from the connection the build is bound to (the one CLOUDFLARE_ACCOUNT_ID and the deploy tokens mint from) and renders no field for it - testing/manifest.test.sh: cirrus-baseline's check, byte for byte — a `connection..` source is accepted only when spec.requires.integrations lists the provider (mutation-checked) - repo-blueprint.yaml, BOOTSTRAP.md, docs/phases/README.md: a hand-run build still passes --set subdomain - records: BL-7 joins BL5; status, plan, epic index, current.md and decisions.md say BL5 ships as baseline-v2 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01D8AmgTwmnp4M8mgmnS9aha --- BOOTSTRAP.md | 6 ++++ ai/context/current.md | 13 ++++--- ai/context/decisions.md | 1 + ai/context/open-risks.md | 4 +-- blueprint.yaml | 12 +++++++ docs/phases/README.md | 6 ++-- repo-blueprint.yaml | 8 ++++- specs/epics/README.md | 2 +- .../blob-starter/IMPLEMENTATION-STATUS.md | 36 ++++++++++++++++++- specs/epics/blob-starter/README.md | 6 ++-- specs/epics/blob-starter/epic.yaml | 3 +- .../epics/blob-starter/implementation-plan.md | 8 ++++- tasks/BL-7.TaskContract.yaml | 25 +++++++++++++ testing/manifest.test.sh | 15 ++++++-- 14 files changed, 124 insertions(+), 21 deletions(-) create mode 100644 tasks/BL-7.TaskContract.yaml diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md index 67f0d19..ecfacfe 100644 --- a/BOOTSTRAP.md +++ b/BOOTSTRAP.md @@ -64,6 +64,12 @@ orun new --blueprint repo-blueprint.yaml \ --set subdomain= ``` +`subdomain` is the workers.dev subdomain of the Cloudflare account you deploy +into (Workers & Pages → your subdomain). A build started from the console, or +with `orun baseline new --from bst_…`, never asks for it: the platform reads +it from the workspace's Cloudflare connection, the same one the deploy tokens +mint from. Only a hand-run build like this one passes it. + **`--run-hooks` is the difference between placing files and bootstrapping a product.** Without it `orun new` writes the tree and stops: no repository, no landing, no convergence watch, no probe. That is deliberate — it is what diff --git a/ai/context/current.md b/ai/context/current.md index ac6d66c..7f9e109 100644 --- a/ai/context/current.md +++ b/ai/context/current.md @@ -18,13 +18,13 @@ then the Worker deployed), then records what went live (`02-docs`). | | | |---|---| -| Latest tag | `baseline-v1` (BL4) | -| On `main` since | BL5 — the cirrus standard (no kiox, generated component docs, this context pack) and SVG uploads closed (risk BL-L) | +| Latest tag | `baseline-v2` (BL5 — the cirrus standard: no kiox, generated component docs, this context pack, and the console card reading `subdomain` from the Cloudflare connection; SVG uploads closed, risk BL-L); `baseline-v1` is BL4 | | Proven live | No. Everything short of the platform is proven offline in Baseline CI, an upload round-tripped through the built Worker included; a live bootstrap from a tag is still to come (risk BL-G) | `baseline-v1` accepts any `image/*` upload, SVG included, and serves it from the product's own origin (BL-L). A product built from it needs BL5's change -to `apps/web/lib/blob`, the delivery route and the uploader. +to `apps/web/lib/blob`, the delivery route and the uploader, which +`baseline-v2` carries. ## Where to read @@ -38,7 +38,6 @@ to `apps/web/lib/blob`, the delivery route and the uploader. ## Next -1. Cut the next `baseline-vN` with `tag.yml`, so the registry can pin BL5 and - no new product starts with SVG uploads open. -2. Bootstrap one product from that tag against a workspace whose Cloudflare - account has R2 enabled (BL-J), and record its timings (closes BL-G). +1. Bootstrap one product from `baseline-v2` against a workspace whose + Cloudflare account has R2 enabled (BL-J), and record its timings (closes + BL-G). diff --git a/ai/context/decisions.md b/ai/context/decisions.md index 6f70463..3f5bb6c 100644 --- a/ai/context/decisions.md +++ b/ai/context/decisions.md @@ -18,3 +18,4 @@ reads in order. | 10 | Uploads are raster images only (PNG, JPEG, GIF, WebP, AVIF), one list shared by the route and the uploader; the delivery route serves every object under `default-src 'none'; sandbox` | `image/*` admitted SVG, which the route served from the app's origin as script — a stored XSS | risk BL-L, IMPLEMENTATION-STATUS (BL5) | | 11 | orun is pinned only where it runs (the `orun-action` `version:` in each workflow); no kiox | `kiox.yaml` pinned a version (v2.15.0) nothing ran | IMPLEMENTATION-STATUS (BL5) | | 12 | Component docs are generated from the manifests and checked in CI | A hand-written copy of the dependency graph and bindings drifts silently | `tooling/catalog/gen-component-docs.py` | +| 13 | The console card reads `subdomain` from the Cloudflare connection (`from: connection.cloudflare.workersSubdomain`); only a hand-run build passes it | It belongs to the account like its id and has one right answer; a typed one could only be wrong, and wrong showed up after deploy (cirrus-baseline since baseline-v23) | `blueprint.yaml`, IMPLEMENTATION-STATUS (BL-7) | diff --git a/ai/context/open-risks.md b/ai/context/open-risks.md index 46a51ac..244d95d 100644 --- a/ai/context/open-risks.md +++ b/ai/context/open-risks.md @@ -13,5 +13,5 @@ Accepted, and worth knowing before you change them: BL-A (the upload is buffered through the Worker), BL-C (anonymous uploads, as upstream), BL-I (the bootstrap floor plans every edge enforced), BL-J (R2 is switched on per account by its owner), BL-K (a custom domain is the owner's -step). Resolved in BL5: BL-L (SVG uploads), for products built from a later -tag than `baseline-v1`. +step). Resolved in BL5: BL-L (SVG uploads), for products built from +`baseline-v2` on. diff --git a/blueprint.yaml b/blueprint.yaml index acaaebb..34d9bdf 100644 --- a/blueprint.yaml +++ b/blueprint.yaml @@ -94,6 +94,18 @@ spec: pattern: "^[a-z0-9][a-z0-9-]{0,62}$" help: The workers.dev subdomain of the Cloudflare account the site deploys into. example: acme + # READ FROM THE CLOUDFLARE CONNECTION, not asked. The subdomain belongs + # to the account the same way its id does, and there is exactly one + # right answer — a typed one could only be wrong, and wrong showed up + # after deploy, in the smoke checks and the verify URLs below. The + # integration reads it from Cloudflare at connect and on its hourly + # health check; the bootstrap door fills this input from the connection + # the build is BOUND to, the same one CLOUDFLARE_ACCOUNT_ID and the + # deploy tokens mint from, so all three name one account. The console + # renders no field for it, and an account with no workers.dev subdomain + # refuses the build at the door, naming the fix, before anything is + # created. + from: connection.cloudflare.workersSubdomain # ── PREVIEW ONLY. repo-blueprint.yaml's `orun.integrations/reconcile@v1` # hooks mint these, brokered, during 01-product. ───────────────────────── diff --git a/docs/phases/README.md b/docs/phases/README.md index 71e84af..7d0c75b 100644 --- a/docs/phases/README.md +++ b/docs/phases/README.md @@ -57,8 +57,10 @@ the blueprint's **required** inputs — `reponame`, `productname`, must be supplied on every invocation, single-phase ones included. A `--values` file is easier than repeating `--set`. -- `subdomain` — the workers.dev subdomain of the Cloudflare account. It is - in every URL the phases probe. +- `subdomain` — the workers.dev subdomain of the Cloudflare account you + deploy into. It is in every URL the phases probe. A console or + `--from bst_…` build reads it from the Cloudflare connection; pass it only + for a hand-run build. - `orunWorkspace` — workspace id (`ws_…`). Unset, it is the workspace the build runs in (`from: workspace`); with none anywhere, a placeholder that fails loudly rather than silently claiming another tenant's workspace. diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml index e446958..dbdfd11 100644 --- a/repo-blueprint.yaml +++ b/repo-blueprint.yaml @@ -53,7 +53,13 @@ inputs: subdomain: type: string default: "your-workers-subdomain" - description: The workers.dev subdomain of the Cloudflare account the site deploys into — its URLs and the probes. + description: >- + The workers.dev subdomain of the Cloudflare account the site deploys + into — its URLs and the probes. + A console or `--from bst_…` build gets it from the workspace's + Cloudflare connection (blueprint.yaml declares + `from: connection.cloudflare.workersSubdomain`); pass it with --set + only for a hand-run build. repoPrivate: type: boolean default: true diff --git a/specs/epics/README.md b/specs/epics/README.md index fdd314e..fbeac43 100644 --- a/specs/epics/README.md +++ b/specs/epics/README.md @@ -7,6 +7,6 @@ folder is the adoption; the merge creates the epic in the workspace. | Epic | Cluster | Status | What it is | |------|---------|--------|------------| -| [`blob-starter/`](./blob-starter/) | **BL** | ✅ Shipped (`baseline-v1`); live bootstrap pending | Vercel's Blob Next.js Starter, equivalent in code and function, on Cloudflare Workers with uploads stored in R2 — and an Orun baseline that instantiates it in one landing (BL4) | +| [`blob-starter/`](./blob-starter/) | **BL** | ✅ Shipped (`baseline-v2`); live bootstrap pending | Vercel's Blob Next.js Starter, equivalent in code and function, on Cloudflare Workers with uploads stored in R2 — and an Orun baseline that instantiates it in one landing (BL4) | As-built ≠ intent: what shipped lives in each epic's `IMPLEMENTATION-STATUS.md`. diff --git a/specs/epics/blob-starter/IMPLEMENTATION-STATUS.md b/specs/epics/blob-starter/IMPLEMENTATION-STATUS.md index c2141a2..50686c4 100644 --- a/specs/epics/blob-starter/IMPLEMENTATION-STATUS.md +++ b/specs/epics/blob-starter/IMPLEMENTATION-STATUS.md @@ -10,7 +10,7 @@ the code departed from `design.md` or from the upstream template. | BL2 — the R2 bucket from Terraform | ✅ Shipped (validated; apply gated on a linked workspace) | [#3](https://github.com/sourceplane/blob-starter/pull/3) | | BL3 — ready to instantiate | ✅ Shipped | [#4](https://github.com/sourceplane/blob-starter/pull/4) | | BL4 — a baseline, in one landing | ✅ Shipped (offline-proven; no live bootstrap yet, risk BL-G) | [#5](https://github.com/sourceplane/blob-starter/pull/5) (BL-5), tagged `baseline-v1` | -| BL5 — the cirrus standard, SVG uploads closed | ✅ Shipped | BL-6 — on `main` after `baseline-v1`, not yet tagged | +| BL5 — the cirrus standard, SVG uploads closed | ✅ Shipped | [#6](https://github.com/sourceplane/blob-starter/pull/6) (BL-6), [#7](https://github.com/sourceplane/blob-starter/pull/7) (BL-7), tagged `baseline-v2` | ## Departures from the upstream template @@ -110,6 +110,40 @@ around it: | context pack | `operations.md`, `deployment.md` | plus `current.md`, `decisions.md`, `open-risks.md` | cirrus-baseline's shape; the three new pages are this repository's own and no module places them (the leak gate still allows exactly two) | | status | BL4 "to be tagged" | BL4 shipped and tagged `baseline-v1`; the page-copy note names the Vercel logo it kept | the tag existed; the documents had not caught up | +### The subdomain from the Cloudflare connection (BL-7) + +The console card's `subdomain` input was typed by hand, though it belongs to +the Cloudflare account the same way its id does and has exactly one right +answer. A wrong value surfaced only after deploy, in the smoke checks and the +verify URLs. `blueprint.yaml` now declares +`from: connection.cloudflare.workersSubdomain`, as cirrus-baseline does since +`baseline-v23`: the Cloudflare integration reads the subdomain from the +account at connect and on its hourly health check, and the bootstrap door +fills the input from the connection the build is bound to — the same one +`CLOUDFLARE_ACCOUNT_ID` and the deploy tokens mint from. The console renders +no field for it, and an account with no workers.dev subdomain is refused at +the door, naming the fix. + +- `testing/manifest.test.sh` takes cirrus-baseline's check: a + `connection..` source is accepted, and only when the card's + `spec.requires.integrations` lists the provider (this card lists + `[github, cloudflare]`). +- `repo-blueprint.yaml` keeps the input and its default; its description, + `BOOTSTRAP.md` and `docs/phases/README.md` say a hand-run `orun new` still + passes `--set subdomain`. +- Nothing a product runs changed: no app, Terraform, test or tooling file. + +Verified: `testing/{manifest,phases,coverage,rebrand,retouch,bootstrap-defer,wire}.test.sh` +green; `gen-component-docs.py --check` green (3 components); at v2.58.11, +`orun new --status` on `repo-blueprint.yaml` (`01-product` 81 files) and +`testing/leak.test.sh` (81 files derived; 74 shipped sources name no factory +path); at v2.78.4, `testing/placement.test.sh` (81 tracked files; +cloudflare-r2 → web; `--resume` changes nothing); `orun task check BL-7` +complete. Mutation check: with `cloudflare` removed from +`spec.requires.integrations`, `manifest.test.sh` fails with the one finding +`inputs[subdomain].from is 'connection.cloudflare.workersSubdomain' but +spec.requires.integrations does not list cloudflare`; restored, it passes. + ## Verified (BL5) - `testing/{manifest,phases,coverage,rebrand,retouch,bootstrap-defer,wire}.test.sh` diff --git a/specs/epics/blob-starter/README.md b/specs/epics/blob-starter/README.md index aaec571..079ae9f 100644 --- a/specs/epics/blob-starter/README.md +++ b/specs/epics/blob-starter/README.md @@ -8,7 +8,7 @@ The port keeps the template's page, uploader, progress bar, toasts and styles. I | Field | Value | |-------|-------| -| Status | ✅ BL0–BL4 shipped (#1–#5), tagged `baseline-v1`; BL5 (the cirrus standard, SVG uploads closed — BL-6) on `main`, not yet tagged. R2 apply and live deploy proven only by a live bootstrap (risk BL-G) | +| Status | ✅ BL0–BL5 shipped (#1–#7; BL4 tagged `baseline-v1`, BL5 — the cirrus standard, SVG uploads closed, BL-6 and BL-7 — tagged `baseline-v2`). R2 apply and live deploy proven only by a live bootstrap (risk BL-G) | | Cluster | **BL** (BL0–BL5) | | Owner(s) | `apps/web` (the uploader, the routes, `lib/blob`) · `tests/web` · `infra/terraform/cloudflare-r2` | | Builds on | `cirrus-baseline` conventions: the R2 root and the `@@wiring(...)@@` deploy-time render; the `kv-redis-starter` port's binding shape | @@ -16,7 +16,7 @@ The port keeps the template's page, uploader, progress bar, toasts and styles. I | Changes | The store (Vercel Blob → R2), the upload path (client token → upload route), the Workers build, tests, the R2 root, the deploy contract; page copy says R2; since BL5, raster uploads only and a sandboxed delivery route (risk BL-L) | | Decisions locked | (1) The upload goes through the Worker (one route, bounded at 50MB), not a presigned R2 URL: it keeps the template's server-side checks where they were. (2) Delivery stays a private route (`/api/blob?pathname=`), as upstream. (3) `wrangler.jsonc` rendered per environment — and, since BL4, committed as the fixture render, because the deploy lane checks it exists before the build (risk BL-E). (4) BL4: one landing — the plan, not a landing boundary, orders the bucket before the Worker; the bucket's apply has a token of its own (`r2-data`), because the deploy token cannot touch R2. | | Gate | BL1 is the first user-visible rung. BL2 applies only with a linked workspace; verified by `terraform validate`. | -| Shipped as | `baseline-v1` ([#5](https://github.com/sourceplane/blob-starter/pull/5)), then BL5 on `main`; proven offline (Baseline CI: an upload round-tripped through the built Worker under `wrangler dev`), deploy gated until a workspace is linked | +| Shipped as | `baseline-v1` ([#5](https://github.com/sourceplane/blob-starter/pull/5)), `baseline-v2` ([#6](https://github.com/sourceplane/blob-starter/pull/6), [#7](https://github.com/sourceplane/blob-starter/pull/7)); proven offline (Baseline CI: an upload round-tripped through the built Worker under `wrangler dev`), deploy gated until a workspace is linked | ## Read order @@ -34,4 +34,4 @@ The port keeps the template's page, uploader, progress bar, toasts and styles. I | BL2 — the R2 bucket from Terraform | `infra/terraform/cloudflare-r2` | the root validates; the wiring key matches the template | | BL3 — ready to instantiate | README, as-built status | a reader can run, test, preview and deploy it | | BL4 — a baseline, in one landing | card, build document, rename, bootstrap tooling, tests | a new product goes from nothing to live in one landing, the R2 bucket applied before the Worker; Baseline CI green | -| BL5 — the cirrus standard, SVG uploads closed | raster-only uploads and a sandboxed delivery route; no kiox, generated component docs, the context pack, status that agrees with the tags | an SVG upload is refused and a served object cannot run script; Baseline CI green with the docs check | +| BL5 — the cirrus standard, SVG uploads closed | raster-only uploads and a sandboxed delivery route; no kiox, generated component docs, the context pack, status that agrees with the tags; the console card reads `subdomain` from the Cloudflare connection | an SVG upload is refused and a served object cannot run script; Baseline CI green with the docs check | diff --git a/specs/epics/blob-starter/epic.yaml b/specs/epics/blob-starter/epic.yaml index 85886ea..cb6f860 100644 --- a/specs/epics/blob-starter/epic.yaml +++ b/specs/epics/blob-starter/epic.yaml @@ -46,4 +46,5 @@ spec: - "every component carries generated docs/{overview,architecture,runbook}.md, and Baseline CI fails a pull request whose manifests and pages disagree" - "ai/context carries this repository's current.md, decisions.md and open-risks.md, and none of them ships to a product" - "every milestone's status row agrees with the tags" - tasks: [BL-6] + - "the console card reads subdomain from the Cloudflare connection (from: connection.cloudflare.workersSubdomain), as cirrus-baseline since baseline-v23" + tasks: [BL-6, BL-7] diff --git a/specs/epics/blob-starter/implementation-plan.md b/specs/epics/blob-starter/implementation-plan.md index 0d0964b..124a433 100644 --- a/specs/epics/blob-starter/implementation-plan.md +++ b/specs/epics/blob-starter/implementation-plan.md @@ -60,7 +60,7 @@ enforced `dependsOn: cloudflare-r2` on main, `packages/`. - the status file records what is proven offline and what only a live bootstrap can prove -## BL5 — the cirrus standard, SVG uploads closed (BL-6) ✅ +## BL5 — the cirrus standard, SVG uploads closed (BL-6, BL-7) ✅ One security fix to the app, and the baseline brought to cirrus-baseline's standard around it. @@ -82,6 +82,12 @@ standard around it. `open-risks.md` beside the two pages a product ships with — this repository's own, so no module places them. - **Status that agrees with the tags.** BL4 is shipped and tagged. +- **The subdomain from the Cloudflare connection (BL-7).** The card's + `subdomain` input declares `from: connection.cloudflare.workersSubdomain`, + as cirrus-baseline since `baseline-v23`: the console fills it from the + connection the build is bound to and renders no field; `manifest.test.sh` + accepts the source only while the card requires `cloudflare`. A hand-run + build still passes `--set subdomain`. **Done when** - `tests/web` refuses an SVG upload (400), stores each raster type, and finds diff --git a/tasks/BL-7.TaskContract.yaml b/tasks/BL-7.TaskContract.yaml new file mode 100644 index 0000000..ea8da0f --- /dev/null +++ b/tasks/BL-7.TaskContract.yaml @@ -0,0 +1,25 @@ +apiVersion: orun.io/v1 +kind: TaskContract +metadata: + name: BL-7 + title: "The subdomain from the Cloudflare connection" +spec: + goal: The console card reads the workers.dev subdomain from the workspace's Cloudflare connection (from connection.cloudflare.workersSubdomain), as cirrus-baseline does since baseline-v23, so a console or `--from bst_…` build never asks for it and it always names the account the deploy tokens mint from; a hand-run build still passes it with --set + affects: + - blueprint.yaml + - repo-blueprint.yaml + - testing/manifest.test.sh + - BOOTSTRAP.md + - docs/phases/README.md + - ai/context/current.md + - ai/context/decisions.md + - ai/context/open-risks.md + - specs/** + - tasks/** + doneWhen: + - "blueprint.yaml's subdomain input declares `from: connection.cloudflare.workersSubdomain`, and spec.requires.integrations lists cloudflare" + - testing/manifest.test.sh accepts that source only when the card requires the provider's integration, and fails naming the input when it does not (mutation-checked) + - BOOTSTRAP.md, docs/phases/README.md and repo-blueprint.yaml say a hand-run build still passes --set subdomain + - the contract tests, the docs check, the leak gate and the offline bootstrap are green + gates: + - checks diff --git a/testing/manifest.test.sh b/testing/manifest.test.sh index 3fd6af8..5374cb5 100755 --- a/testing/manifest.test.sh +++ b/testing/manifest.test.sh @@ -217,9 +217,20 @@ for path in manifests: # field for it (saas-bootstrap-console BC-K5). Two ways to get it # wrong, and the platform refuses both — check them here too, so the # mistake is caught in this repo rather than at a live bootstrap. + # + # A `connection..` source is read from the connection + # the build is bound to, so the provider must be one the manifest + # requires — the platform's parser refuses it otherwise. + sources_known = ("repo.name", "repo.owner", "repo.fullName", + "connection.cloudflare.workersSubdomain") src = field.get("from") - if src is not None and src not in ("repo.name", "repo.owner", "repo.fullName"): - B(f"inputs[{key}].from is {src!r} — must be repo.name, repo.owner or repo.fullName") + if src is not None and src not in sources_known: + B(f"inputs[{key}].from is {src!r} — must be one of {', '.join(sources_known)}") + if isinstance(src, str) and src.startswith("connection."): + provider = src.split(".")[1] + if provider not in ((spec.get("requires") or {}).get("integrations") or []): + B(f"inputs[{key}].from is {src!r} but spec.requires.integrations " + f"does not list {provider} — there is no connection to read it from") # ── secrets: BOTH or NEITHER, checked both ways ─────────────────────── declared = {s.get("key"): (s.get("provider"), s.get("template")) for s in (spec.get("secrets") or [])} From 958274c5fc7cb2003c5fabd172bbfe9f6c7834aa Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 03:47:56 +0000 Subject: [PATCH 5/5] =?UTF-8?q?BL6:=20the=20console=20asks=20for=20no=20do?= =?UTF-8?q?main=20=E2=80=94=20the=20domain=20is=20set=20later?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The site goes live on workers.dev from its first deploy and nothing in the build needs a domain — the page builds its absolute links from the request it answers — so the console's Product step no longer asks for one. The logic that uses a domain stays where it is, waiting for one. - blueprint.yaml: no productdomain input - repo-blueprint.yaml: productdomain is optional, default empty - rebrand.mjs: productdomain no longer required; empty brands the reserved placeholder .example.com (RFC 2606) where the domain goes (BASE_DOMAIN), so setting it later is replacing one string - the product README and ai/context/operations.md say how to set it - testing/fixtures/acme.json carries no domain; rebrand.test.sh pins the placeholder; baseline.yml's blueprint read sets no domain - records: BL6 / BL-8, tagged baseline-v3 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01D8AmgTwmnp4M8mgmnS9aha --- .baseline/product/README.md | 7 +++- .github/workflows/baseline.yml | 1 - BOOTSTRAP.md | 14 ++++--- README.md | 2 +- ai/context/current.md | 6 +-- ai/context/decisions.md | 1 + ai/context/operations.md | 2 +- blueprint.yaml | 11 ++--- docs/phases/README.md | 12 ++++-- repo-blueprint.yaml | 14 +++++-- specs/epics/README.md | 2 +- .../blob-starter/IMPLEMENTATION-STATUS.md | 42 +++++++++++++++++++ specs/epics/blob-starter/README.md | 7 ++-- specs/epics/blob-starter/epic.yaml | 6 +++ .../epics/blob-starter/implementation-plan.md | 8 ++++ tasks/BL-8.TaskContract.yaml | 30 +++++++++++++ testing/fixtures/acme.json | 8 ++-- testing/rebrand.test.sh | 8 ++++ tooling/rebrand/rebrand.mjs | 10 +++-- 19 files changed, 155 insertions(+), 36 deletions(-) create mode 100644 tasks/BL-8.TaskContract.yaml diff --git a/.baseline/product/README.md b/.baseline/product/README.md index 19c25c9..09c14ba 100644 --- a/.baseline/product/README.md +++ b/.baseline/product/README.md @@ -100,5 +100,8 @@ The site answers on workers.dev from its first deploy. To serve it on your own domain, add the domain to the Cloudflare account the site deploys into and attach it to the Worker (dashboard → Workers & Pages → `blob-starter-web-prod` → Settings → Domains & Routes → Add → Custom -domain). Nothing in the repository changes: the page builds its absolute -links from the request it is answering. +domain). The page builds its absolute links from the request it is +answering, so nothing else has to change; the repository names the domain in +one place, `BASE_DOMAIN` in `intent.yaml`, which the site was born with as +the reserved placeholder `blob-starter.example.com`. Replace it with your +domain in the same change that records it. diff --git a/.github/workflows/baseline.yml b/.github/workflows/baseline.yml index b71c792..d7c2cbf 100644 --- a/.github/workflows/baseline.yml +++ b/.github/workflows/baseline.yml @@ -94,7 +94,6 @@ jobs: --out "$(mktemp -d)" \ --set reponame=acme-uploads \ --set "productname=Acme Uploads" \ - --set productdomain=acme.dev \ --set githuborg=acme-inc - name: the leak gate — what a product carries run: bash testing/leak.test.sh diff --git a/BOOTSTRAP.md b/BOOTSTRAP.md index ecfacfe..5fa1846 100644 --- a/BOOTSTRAP.md +++ b/BOOTSTRAP.md @@ -59,7 +59,7 @@ cd blob-starter orun new --blueprint repo-blueprint.yaml \ --out ~/sites/acme-uploads --run-hooks --resume \ --set reponame=acme-uploads --set productname="Acme Uploads" \ - --set productdomain=acme.dev --set githuborg=acme-inc \ + --set githuborg=acme-inc \ --set orunWorkspace=ws_XXXXXXXX \ --set subdomain= ``` @@ -96,9 +96,13 @@ orun new --blueprint repo-blueprint.yaml --out ~/sites/acme-uploads --run-hooks `02-docs` reads the identity back from `.rebrand/values.json` in the placed tree, but the blueprint's **required** inputs — `reponame`, `productname`, -`productdomain`, `githuborg` — are validated before anything runs, so pass -them every time (a `--values` file is easier). The full guide, one page per -phase: [docs/phases/README.md](docs/phases/README.md). +`githuborg` — are validated before anything runs, so pass them every time (a +`--values` file is easier). The domain is not one of them: the site goes live +on workers.dev, and `productdomain` defaults to empty, which brands the +reserved placeholder `.example.com` into `BASE_DOMAIN` for an owner +to replace when they attach a domain (README, "Custom domain"). Pass +`--set productdomain=` only for a site that already has its domain. +The full guide, one page per phase: [docs/phases/README.md](docs/phases/README.md). | flag | what it does | |---|---| @@ -232,7 +236,7 @@ at the tag and refuses the whole catalogue if it 404s. | Convergence failed AFTER the PR merged; re-running lands nothing | expected on its own — the files are on main. Re-run the phase (`--phase 01-product`, `--redo 01-product`, or the console's Retry): its `retouch` hook gives the landing a diff and the R2 root and the uploader re-plan | | The product's `intent.yaml` says `workspace: ws_SET_ME` | `orunWorkspace` was empty and the build ran outside a workspace; set it and re-run `01-product` | | A bootstrap stopped before `02-docs`; prod no longer waits on stage | the gate is deferred, not dropped: run `02-docs`, or `node tooling/bootstrap/promotion.mjs --restore --file /intent.yaml` | -| `✕ input "productdomain" is required` | all four required inputs must be set on every invocation, single-phase ones included | +| `✕ input "productname" is required` | all three required inputs (`reponame`, `productname`, `githuborg`) must be set on every invocation, single-phase ones included | | `unknown flag: --phase` or a parse error in the blueprint | the CLI is below the v2.58.11 floor | | web lane `verify-app-structure` fails on `wrangler.jsonc` | the config is not committed. It is the fixture render of `wrangler.template.jsonc`: `pnpm run wire:fixture` and commit it | | web lane `build-app`: `Symlink apps/web/node_modules/next is invalid, it points out of the filesystem root` | the product's intent pins stack-tectonic ≥ 0.20.0, whose lane-scoped install links each job's node_modules out of its tree, which Next 16's Turbopack refuses. Pin 0.19.0 (`intent.yaml` says why) | diff --git a/README.md b/README.md index a315498..c2b3c67 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ design, the milestones and the as-built status. git clone --depth 1 --branch https://github.com/sourceplane/blob-starter cd blob-starter orun new --blueprint repo-blueprint.yaml --out ~/sites/acme-uploads --run-hooks --resume \ - --set reponame=acme-uploads --set productname="Acme Uploads" --set productdomain=acme.dev \ + --set reponame=acme-uploads --set productname="Acme Uploads" \ --set githuborg=acme-inc --set subdomain= ``` diff --git a/ai/context/current.md b/ai/context/current.md index 7f9e109..302655a 100644 --- a/ai/context/current.md +++ b/ai/context/current.md @@ -18,13 +18,13 @@ then the Worker deployed), then records what went live (`02-docs`). | | | |---|---| -| Latest tag | `baseline-v2` (BL5 — the cirrus standard: no kiox, generated component docs, this context pack, and the console card reading `subdomain` from the Cloudflare connection; SVG uploads closed, risk BL-L); `baseline-v1` is BL4 | +| Latest tag | `baseline-v3` (BL6 — the domain is set later: the console asks for no domain, and a site is born with the placeholder `.example.com` for an owner to replace); `baseline-v2` is BL5 (the cirrus standard; SVG uploads closed, risk BL-L), `baseline-v1` BL4 | | Proven live | No. Everything short of the platform is proven offline in Baseline CI, an upload round-tripped through the built Worker included; a live bootstrap from a tag is still to come (risk BL-G) | `baseline-v1` accepts any `image/*` upload, SVG included, and serves it from the product's own origin (BL-L). A product built from it needs BL5's change to `apps/web/lib/blob`, the delivery route and the uploader, which -`baseline-v2` carries. +`baseline-v2` and later carry. ## Where to read @@ -38,6 +38,6 @@ to `apps/web/lib/blob`, the delivery route and the uploader, which ## Next -1. Bootstrap one product from `baseline-v2` against a workspace whose +1. Bootstrap one product from `baseline-v3` against a workspace whose Cloudflare account has R2 enabled (BL-J), and record its timings (closes BL-G). diff --git a/ai/context/decisions.md b/ai/context/decisions.md index 3f5bb6c..f8330ae 100644 --- a/ai/context/decisions.md +++ b/ai/context/decisions.md @@ -19,3 +19,4 @@ reads in order. | 11 | orun is pinned only where it runs (the `orun-action` `version:` in each workflow); no kiox | `kiox.yaml` pinned a version (v2.15.0) nothing ran | IMPLEMENTATION-STATUS (BL5) | | 12 | Component docs are generated from the manifests and checked in CI | A hand-written copy of the dependency graph and bindings drifts silently | `tooling/catalog/gen-component-docs.py` | | 13 | The console card reads `subdomain` from the Cloudflare connection (`from: connection.cloudflare.workersSubdomain`); only a hand-run build passes it | It belongs to the account like its id and has one right answer; a typed one could only be wrong, and wrong showed up after deploy (cirrus-baseline since baseline-v23) | `blueprint.yaml`, IMPLEMENTATION-STATUS (BL-7) | +| 14 | The console asks for no domain; an empty `productdomain` brands the placeholder `.example.com` | The site goes live on workers.dev and nothing in the build needs a domain; attaching one is an owner's step, and the placeholder keeps every place the domain goes in the repository, ready to replace | `repo-blueprint.yaml`, `tooling/rebrand/rebrand.mjs`, IMPLEMENTATION-STATUS (BL-8) | diff --git a/ai/context/operations.md b/ai/context/operations.md index e763403..fc78e1f 100644 --- a/ai/context/operations.md +++ b/ai/context/operations.md @@ -135,7 +135,7 @@ orun integrations list --org --json && orun cloud check --org | redeploy without a change | edit the last line of `apps/web/component.yaml` (`# orun: redeploy `) and merge — it is a deploy trigger, nothing reads it | | list or delete stored files | `wrangler r2 object …` on the bucket named in the environment's `WIRING_CLOUDFLARE_R2` (`--remote`), or the dashboard's R2 page | | add a binding (D1, KV, another bucket) | a Terraform root under `infra/terraform/` that publishes `WIRING_`, a token in `wrangler.template.jsonc`, its fixture entry, the root in the build's `--components`, the `WIRING__` secretEnv and an enforced `dependsOn` on it in `apps/web/component.yaml` | -| serve a custom domain | attach it to the Worker in Cloudflare (README, "Custom domain"); nothing in the repository changes | +| serve a custom domain | attach it to the Worker in Cloudflare (README, "Custom domain"), then replace the placeholder `blob-starter.example.com` in `intent.yaml`'s `BASE_DOMAIN` with it | | add a runtime secret | `orun secrets set --org --env ` | | headless credentials | `ORUN_TOKEN` (workspace-scoped) + `GITHUB_TOKEN` | diff --git a/blueprint.yaml b/blueprint.yaml index 34d9bdf..4e76179 100644 --- a/blueprint.yaml +++ b/blueprint.yaml @@ -65,6 +65,12 @@ spec: # already holds says so with `from`. repo-blueprint.yaml declares the same # names; `repoPrivate`, `orunWorkspace` and `epicSlug` are build inputs with # defaults (or filled from the build's workspace) and are not asked. + # + # NOR IS THE DOMAIN. The site goes live on workers.dev, and a domain is an + # owner's step after the bootstrap: `productdomain` defaults to empty, the + # rebrand writes the reserved placeholder `.example.com` where + # the domain goes, and the site's README ("Custom domain") says how to + # set it. Nothing that needs a domain is removed — it waits for one. inputs: - key: reponame label: Repo name @@ -76,11 +82,6 @@ spec: pattern: "^[A-Za-z0-9][A-Za-z0-9 .,'&-]{1,48}$" help: The name visitors see — the page's heading and its title. example: Acme Uploads - - key: productdomain - label: Site domain - pattern: "^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$" - help: The domain the site will answer on. It does not need to exist — the site goes live on workers.dev first. - example: acme.dev - key: githuborg label: GitHub organisation pattern: "^[A-Za-z0-9][A-Za-z0-9-]*$" diff --git a/docs/phases/README.md b/docs/phases/README.md index 7d0c75b..50f7835 100644 --- a/docs/phases/README.md +++ b/docs/phases/README.md @@ -53,9 +53,15 @@ its absolute links from the request. `01-product` takes the site's identity once and writes it into the repo (`.rebrand/values.json`); `02-docs` reads it back from the placed tree. But the blueprint's **required** inputs — `reponame`, `productname`, -`productdomain`, `githuborg` — are validated before any phase runs, so they -must be supplied on every invocation, single-phase ones included. A -`--values` file is easier than repeating `--set`. +`githuborg` — are validated before any phase runs, so they must be supplied +on every invocation, single-phase ones included. A `--values` file is easier +than repeating `--set`. + +- `productdomain` — NOT ASKED, default empty. The site goes live on + workers.dev; empty brands the reserved placeholder `.example.com` + into `BASE_DOMAIN`, for an owner to replace when they attach a domain (the + site's README, "Custom domain"). Pass it only for a site that already has + its domain. - `subdomain` — the workers.dev subdomain of the Cloudflare account you deploy into. It is in every URL the phases probe. A console or diff --git a/repo-blueprint.yaml b/repo-blueprint.yaml index dbdfd11..e02287e 100644 --- a/repo-blueprint.yaml +++ b/repo-blueprint.yaml @@ -35,11 +35,17 @@ inputs: description: The site's display name (e.g. "Acme Uploads") — the page heading and its title. productdomain: type: string - required: true + default: "" description: >- - The domain the site will answer on (e.g. acme.dev) — BASE_DOMAIN and the - custom-domain guidance. It does not need to exist: the site answers on - workers.dev from its first deploy. + The site's own domain, once it has one (e.g. acme.dev). NOT ASKED: the + site answers on workers.dev from its first deploy, and a domain is an + owner's step after it. Empty, the rebrand writes the reserved + placeholder `.example.com` where the domain goes (BASE_DOMAIN + under each environment's `env:` in intent.yaml), so setting it later is + replacing that one string — the site's README, "Custom domain", says + how. The page builds its absolute links from the request it answers, so + nothing else follows it. Pass it with --set only to brand a hand-run + build with a domain it already has. githuborg: type: string pattern: "^[A-Za-z0-9][A-Za-z0-9-]*$" diff --git a/specs/epics/README.md b/specs/epics/README.md index fbeac43..cfd41a5 100644 --- a/specs/epics/README.md +++ b/specs/epics/README.md @@ -7,6 +7,6 @@ folder is the adoption; the merge creates the epic in the workspace. | Epic | Cluster | Status | What it is | |------|---------|--------|------------| -| [`blob-starter/`](./blob-starter/) | **BL** | ✅ Shipped (`baseline-v2`); live bootstrap pending | Vercel's Blob Next.js Starter, equivalent in code and function, on Cloudflare Workers with uploads stored in R2 — and an Orun baseline that instantiates it in one landing (BL4) | +| [`blob-starter/`](./blob-starter/) | **BL** | ✅ Shipped (`baseline-v3`); live bootstrap pending | Vercel's Blob Next.js Starter, equivalent in code and function, on Cloudflare Workers with uploads stored in R2 — and an Orun baseline that instantiates it in one landing (BL4) | As-built ≠ intent: what shipped lives in each epic's `IMPLEMENTATION-STATUS.md`. diff --git a/specs/epics/blob-starter/IMPLEMENTATION-STATUS.md b/specs/epics/blob-starter/IMPLEMENTATION-STATUS.md index 50686c4..5cf17fe 100644 --- a/specs/epics/blob-starter/IMPLEMENTATION-STATUS.md +++ b/specs/epics/blob-starter/IMPLEMENTATION-STATUS.md @@ -11,6 +11,7 @@ the code departed from `design.md` or from the upstream template. | BL3 — ready to instantiate | ✅ Shipped | [#4](https://github.com/sourceplane/blob-starter/pull/4) | | BL4 — a baseline, in one landing | ✅ Shipped (offline-proven; no live bootstrap yet, risk BL-G) | [#5](https://github.com/sourceplane/blob-starter/pull/5) (BL-5), tagged `baseline-v1` | | BL5 — the cirrus standard, SVG uploads closed | ✅ Shipped | [#6](https://github.com/sourceplane/blob-starter/pull/6) (BL-6), [#7](https://github.com/sourceplane/blob-starter/pull/7) (BL-7), tagged `baseline-v2` | +| BL6 — the domain is set later | ✅ Shipped | [#8](https://github.com/sourceplane/blob-starter/pull/8) (BL-8), tagged `baseline-v3` | ## Departures from the upstream template @@ -144,6 +145,47 @@ complete. Mutation check: with `cloudflare` removed from `inputs[subdomain].from is 'connection.cloudflare.workersSubdomain' but spec.requires.integrations does not list cloudflare`; restored, it passes. +## The domain is set later (BL6, BL-8) + +The console asked for the site's domain, with help text that said it did not +need to exist — and nothing in the build needed one: the site answers on +workers.dev from its first deploy, the page builds its absolute links (the +Open Graph image included) from the request it is answering, and the one +place the repository names the domain is `BASE_DOMAIN` in `intent.yaml`. A +domain is an owner's step after the bootstrap (README, "Custom domain"), so +the form no longer asks for it. + +- `blueprint.yaml` declares no `productdomain` input; the console's Product + step asks for the site's name alone. +- `repo-blueprint.yaml`'s `productdomain` is optional, default empty. No hook, + probe or `when:` reads it — the only use is the `.rebrand/values.json` + template, which writes `""`. A hand-run build may still pass + `--set productdomain=` for a site that already has its domain. +- `rebrand.mjs` no longer requires it. Empty, it brands the reserved + placeholder `.example.com` (RFC 2606 — never someone else's + domain) where the domain goes — `BASE_DOMAIN` in dev, stage and prod — so + setting it later is replacing one string; the product README and + `ai/context/operations.md` say so. +- `testing/fixtures/acme.json` carries no domain, so the leak gate, the + offline bootstrap and the e2e tier exercise exactly what a console build + supplies; `testing/rebrand.test.sh` pins the placeholder for an absent and + an empty domain; `baseline.yml`'s blueprint read sets no domain. + +Nothing that needs a domain was removed — it waits for one. + +Verified: `testing/{manifest,phases,coverage,rebrand,retouch,bootstrap-defer,wire}.test.sh` +green (rebrand: 33 checks, the two new ones included); `gen-component-docs.py +--check` green (3 components); `orun new --status` on `repo-blueprint.yaml` +with no domain (01-product pending, 81 files) and `testing/leak.test.sh` (81 +files derived; 74 shipped sources name no factory path) at v2.58.11; +`testing/placement.test.sh` at v2.78.4, as Baseline CI runs it (81 tracked +files; cloudflare-r2 → web on stage and prod; the 02-docs merge plans 0 +jobs; `--resume` changes nothing). The offline bootstrap of the fixture, +which names no domain, writes `"productdomain": ""` and brands +`acme-blob-uploads.example.com` into the site's three `BASE_DOMAIN` lines, +its README and its `operations.md` (5 lines, 3 files), with no +`blob-starter.example.com` left. `orun task check BL-8` complete. + ## Verified (BL5) - `testing/{manifest,phases,coverage,rebrand,retouch,bootstrap-defer,wire}.test.sh` diff --git a/specs/epics/blob-starter/README.md b/specs/epics/blob-starter/README.md index 079ae9f..baf9aae 100644 --- a/specs/epics/blob-starter/README.md +++ b/specs/epics/blob-starter/README.md @@ -8,15 +8,15 @@ The port keeps the template's page, uploader, progress bar, toasts and styles. I | Field | Value | |-------|-------| -| Status | ✅ BL0–BL5 shipped (#1–#7; BL4 tagged `baseline-v1`, BL5 — the cirrus standard, SVG uploads closed, BL-6 and BL-7 — tagged `baseline-v2`). R2 apply and live deploy proven only by a live bootstrap (risk BL-G) | -| Cluster | **BL** (BL0–BL5) | +| Status | ✅ BL0–BL6 shipped (#1–#8; BL4 tagged `baseline-v1`, BL5 — the cirrus standard, SVG uploads closed, BL-6 and BL-7 — tagged `baseline-v2`, BL6 — the domain is set later, BL-8 — tagged `baseline-v3`). R2 apply and live deploy proven only by a live bootstrap (risk BL-G) | +| Cluster | **BL** (BL0–BL6) | | Owner(s) | `apps/web` (the uploader, the routes, `lib/blob`) · `tests/web` · `infra/terraform/cloudflare-r2` | | Builds on | `cirrus-baseline` conventions: the R2 root and the `@@wiring(...)@@` deploy-time render; the `kv-redis-starter` port's binding shape | | Upstream | [vercel/examples `storage/blob-starter`](https://github.com/vercel/examples/tree/main/storage/blob-starter) | | Changes | The store (Vercel Blob → R2), the upload path (client token → upload route), the Workers build, tests, the R2 root, the deploy contract; page copy says R2; since BL5, raster uploads only and a sandboxed delivery route (risk BL-L) | | Decisions locked | (1) The upload goes through the Worker (one route, bounded at 50MB), not a presigned R2 URL: it keeps the template's server-side checks where they were. (2) Delivery stays a private route (`/api/blob?pathname=`), as upstream. (3) `wrangler.jsonc` rendered per environment — and, since BL4, committed as the fixture render, because the deploy lane checks it exists before the build (risk BL-E). (4) BL4: one landing — the plan, not a landing boundary, orders the bucket before the Worker; the bucket's apply has a token of its own (`r2-data`), because the deploy token cannot touch R2. | | Gate | BL1 is the first user-visible rung. BL2 applies only with a linked workspace; verified by `terraform validate`. | -| Shipped as | `baseline-v1` ([#5](https://github.com/sourceplane/blob-starter/pull/5)), `baseline-v2` ([#6](https://github.com/sourceplane/blob-starter/pull/6), [#7](https://github.com/sourceplane/blob-starter/pull/7)); proven offline (Baseline CI: an upload round-tripped through the built Worker under `wrangler dev`), deploy gated until a workspace is linked | +| Shipped as | `baseline-v3` ([#8](https://github.com/sourceplane/blob-starter/pull/8), BL6: no domain asked), `baseline-v1` ([#5](https://github.com/sourceplane/blob-starter/pull/5)), `baseline-v2` ([#6](https://github.com/sourceplane/blob-starter/pull/6), [#7](https://github.com/sourceplane/blob-starter/pull/7)); proven offline (Baseline CI: an upload round-tripped through the built Worker under `wrangler dev`), deploy gated until a workspace is linked | ## Read order @@ -35,3 +35,4 @@ The port keeps the template's page, uploader, progress bar, toasts and styles. I | BL3 — ready to instantiate | README, as-built status | a reader can run, test, preview and deploy it | | BL4 — a baseline, in one landing | card, build document, rename, bootstrap tooling, tests | a new product goes from nothing to live in one landing, the R2 bucket applied before the Worker; Baseline CI green | | BL5 — the cirrus standard, SVG uploads closed | raster-only uploads and a sandboxed delivery route; no kiox, generated component docs, the context pack, status that agrees with the tags; the console card reads `subdomain` from the Cloudflare connection | an SVG upload is refused and a served object cannot run script; Baseline CI green with the docs check | +| BL6 — the domain is set later | the console asks for no domain; an empty `productdomain` brands the placeholder `.example.com` for an owner to replace | Baseline CI green on a fixture with no domain | diff --git a/specs/epics/blob-starter/epic.yaml b/specs/epics/blob-starter/epic.yaml index cb6f860..9e88965 100644 --- a/specs/epics/blob-starter/epic.yaml +++ b/specs/epics/blob-starter/epic.yaml @@ -48,3 +48,9 @@ spec: - "every milestone's status row agrees with the tags" - "the console card reads subdomain from the Cloudflare connection (from: connection.cloudflare.workersSubdomain), as cirrus-baseline since baseline-v23" tasks: [BL-6, BL-7] + - name: "BL6 — the domain is set later" + exitCriteria: + - "the console card asks for no domain: a site goes live on workers.dev, and productdomain is an optional build input that defaults to empty" + - "a site built without a domain is branded with the reserved placeholder .example.com wherever the domain goes (BASE_DOMAIN), and its README says how an owner sets the real one" + - "Baseline CI places, leak-checks and plans a site built with no domain" + tasks: [BL-8] diff --git a/specs/epics/blob-starter/implementation-plan.md b/specs/epics/blob-starter/implementation-plan.md index 124a433..04e5c41 100644 --- a/specs/epics/blob-starter/implementation-plan.md +++ b/specs/epics/blob-starter/implementation-plan.md @@ -98,6 +98,14 @@ standard around it. - the docs check is green in Baseline CI - this file, the status file and `epic.yaml` agree +## BL6 — the domain is set later (BL-8) ✅ + +**Done when** the console card asks for no domain; `productdomain` is an +optional build input, empty by default; a site built without one is branded +with the reserved placeholder `.example.com` where the domain goes +and its README says how an owner sets the real one; Baseline CI places, +leak-checks and plans a site built with no domain. Shipped in `baseline-v3`. + ## After BL4 (outside this repository) 1. Cut `baseline-v1` with `tag.yml` from the merged `main` — done: `baseline-v1` is BL4. diff --git a/tasks/BL-8.TaskContract.yaml b/tasks/BL-8.TaskContract.yaml new file mode 100644 index 0000000..a6994b7 --- /dev/null +++ b/tasks/BL-8.TaskContract.yaml @@ -0,0 +1,30 @@ +apiVersion: orun.io/v1 +kind: TaskContract +metadata: + name: BL-8 + title: "The domain is set later" +spec: + goal: "The console no longer asks for the site's domain. A site goes live on workers.dev; productdomain is an optional build input (default empty), the rebrand writes the reserved placeholder .example.com where the domain goes, and the site's README says how an owner replaces it once a domain is attached" + affects: + - blueprint.yaml + - repo-blueprint.yaml + - tooling/rebrand/rebrand.mjs + - testing/rebrand.test.sh + - testing/fixtures/acme.json + - .github/workflows/baseline.yml + - .baseline/product/README.md + - BOOTSTRAP.md + - README.md + - docs/phases/README.md + - ai/context/operations.md + - ai/context/current.md + - ai/context/decisions.md + - specs/** + - tasks/** + doneWhen: + - blueprint.yaml declares no productdomain input, and repo-blueprint.yaml's productdomain is optional with an empty default + - "rebrand.mjs no longer requires productdomain and brands .example.com when it is empty (testing/rebrand.test.sh)" + - testing/fixtures/acme.json carries no domain, so the leak gate and the offline bootstrap exercise what a console build supplies + - the contract tests, the docs check, the leak gate and the offline bootstrap are green + gates: + - checks diff --git a/testing/fixtures/acme.json b/testing/fixtures/acme.json index 298252d..e2d997f 100644 --- a/testing/fixtures/acme.json +++ b/testing/fixtures/acme.json @@ -8,15 +8,15 @@ "strings and HTML), a hyphenated repo slug that CONTAINS a word of the", "baseline's own (`blob`, which is also the binding's name, the route's", "path and the library's directory), an owner other than the baseline's,", - "and a multi-label domain — because a fixture that only uses values the", - "templates were written against proves the templates work on the values", - "they were written against.", + "and NO domain — a console build asks for none, so the placeholder", + ".example.com is what a site is born with — because a fixture", + "that only uses values the templates were written against proves the", + "templates work on the values they were written against.", "Every key here is an input repo-blueprint.yaml declares. A key it does not", "declare is a fixture that has drifted, and orun refuses it." ], "reponame": "acme-blob-uploads", "productname": "Sam's Photos & Files", - "productdomain": "photos.acme.dev", "githuborg": "acme-inc", "subdomain": "acme", "orunWorkspace": "ws_0000000000000000000000000000000f", diff --git a/testing/rebrand.test.sh b/testing/rebrand.test.sh index f1a19bc..9c7e43d 100755 --- a/testing/rebrand.test.sh +++ b/testing/rebrand.test.sh @@ -93,6 +93,14 @@ check "…and so does the committed render's binding" \ check "the placeholder domain is the product's domain, not a renamed slug" \ "$acme" intent.yaml ' BASE_DOMAIN: blob-starter.example.com' \ ' BASE_DOMAIN: acme.dev' +check "no domain given: the reserved placeholder, for an owner to replace later" \ + '{"reponame":"acme-uploads","productname":"Acme Uploads","githuborg":"acme-inc","subdomain":"acme"}' \ + intent.yaml ' BASE_DOMAIN: blob-starter.example.com' \ + ' BASE_DOMAIN: acme-uploads.example.com' +check "an empty domain is no domain" \ + '{"reponame":"acme-uploads","productname":"Acme Uploads","productdomain":""}' \ + intent.yaml ' BASE_DOMAIN: blob-starter.example.com' \ + ' BASE_DOMAIN: acme-uploads.example.com' check "the repo slug" \ "$acme" package.json ' "name": "blob-starter",' \ ' "name": "acme-uploads",' diff --git a/tooling/rebrand/rebrand.mjs b/tooling/rebrand/rebrand.mjs index b7d6510..ae5ecb5 100644 --- a/tooling/rebrand/rebrand.mjs +++ b/tooling/rebrand/rebrand.mjs @@ -28,7 +28,7 @@ // { // "reponame": "acme-notes", // required — repo slug // "productname": "Acme Notes", // required — the site's display name -// "productdomain": "acme.dev", // required — the product domain +// "productdomain": "acme.dev", // optional — default .example.com (set later) // "githuborg": "acme-inc", // owner of the product repo (source link) // "brandSlug": "acme", // default: reponame — worker name prefix // "subdomain": "acme", // default: your-workers-subdomain @@ -69,7 +69,7 @@ if (!verifyOnly && !valuesPath) { } if (valuesPath) { values = JSON.parse(fs.readFileSync(valuesPath, "utf8")); - for (const required of ["reponame", "productname", "productdomain"]) { + for (const required of ["reponame", "productname"]) { if (typeof values[required] !== "string" || values[required].length === 0) { console.error(`rebrand: values file is missing required field "${required}"`); process.exit(2); @@ -132,7 +132,11 @@ const rx = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // All fields are unused under --verify; the fallbacks keep derivation total. const reponame = values.reponame ?? ""; const productname = values.productname ?? ""; -const productdomain = values.productdomain ?? ""; +// The domain is NOT ASKED at bootstrap: a product goes live on workers.dev and +// an owner sets a domain later. Until then the reserved placeholder +// `.example.com` (RFC 2606 — it can never be someone else's) stands +// wherever the domain goes, so setting it is replacing one string. +const productdomain = (values.productdomain ?? "").trim() || (reponame ? `${reponame}.example.com` : ""); const githuborg = (values.githuborg ?? "").trim() || baseline.githubOwner; const brandSlug = (values.brandSlug ?? "").trim() || reponame; const subdomain = (values.subdomain ?? "").trim() || "your-workers-subdomain";