diff --git a/.github/workflows/bump-scaffold-pins.yml b/.github/workflows/bump-scaffold-pins.yml index dc2b1ea3..04af2260 100644 --- a/.github/workflows/bump-scaffold-pins.yml +++ b/.github/workflows/bump-scaffold-pins.yml @@ -41,6 +41,46 @@ permissions: pull-requests: write jobs: + # Runtime half of the ready-ack contract (issue #206). The offline guard in + # `internal/scaffold/ready_ack_contract_test.go` proves each SDK-free page + # template ships a byte-identical copy of `internal/blockproto/ready-ack.js` + # and that the entry point loads it β€” it CANNOT prove the ack fires, because + # no Go static check can prove JavaScript executes. This job runs the emitter + # in node against a fake host and asserts a single correctly-addressed + # `{type:'BLOCK_READY',payload:{height:0}}` goes out. + # + # πŸ”΄ This is the DRIFT runner, NOT the gate. The gate is the identically-named + # job in ci.yml, which runs on every pull request. A daily job cannot block a + # merge β€” a regression would land green and surface up to 24h later, on a + # workflow with no dependent job β€” so this copy alone would be a guard that + # gates nothing. It exists to catch drift on `main` between PRs (a merged-tree + # interaction, a node bump, an npm-side change), and is deliberately + # independent of the `bump` job below so it runs on every sweep, including the + # usual no-op ones where the pins are already current. + ready-ack-runtime: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + with: + go-version: "1.25" + cache: true + + - uses: actions/setup-node@v4 + with: + node-version: "22" + + # -v so the run REPORTS its controls (an inert emitter and a naive ack are + # both driven through the same assertions and must be rejected) rather than + # just an exit code. + - name: scaffolded ready-ack actually fires + env: + CIVITAI_CHECK_SCAFFOLD_RUNTIME: "1" + run: go test ./internal/scaffold -run TestScaffoldedReadyAckActuallyFires -count=1 -v + bump: runs-on: ubuntu-latest steps: diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e57571bd..e36730f8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -88,6 +88,116 @@ jobs: CIVITAI_CHECK_PUBLISHED_PINS: "1" run: go test ./internal/scaffold -run TestScaffoldPinsSatisfyPublished -v + # Guard B for the block->host ready-ack (issue #206), and the half that GATES. + # + # `internal/scaffold/ready_ack_contract_test.go` runs in the build-test job + # above and proves each SDK-free page template ships a byte-identical copy of + # `internal/blockproto/ready-ack.js` that the entry point RESOLVES to. It + # cannot prove the ack FIRES β€” no Go static check can prove JavaScript + # executes, and an emitter with an inverted `event.source` check passes every + # static assertion while being completely inert. + # + # This job executes the emitter in node against a fake host. It is env-gated + # so `make ci` stays Go-only and offline. The daily `bump-scaffold-pins` sweep + # runs it too, but a DAILY runner gates nothing: a regression would merge green + # and surface up to 24h later, on a workflow with no dependent job. A PR check + # is what makes it a guard. + # + # -v so the run REPORTS its controls (an inert emitter and a naive ack are + # driven through the same assertions and must be rejected) rather than just an + # exit code. + ready-ack-runtime: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + with: + go-version: "1.25" + cache: true + + - uses: actions/setup-node@v4 + with: + node-version: "22" + + - name: scaffolded ready-ack actually fires + env: + CIVITAI_CHECK_SCAFFOLD_RUNTIME: "1" + run: go test ./internal/scaffold -run TestScaffoldedReadyAckActuallyFires -count=1 -v + + # Rot-guard: build the page-vite template. It is the only SDK-free template + # with a build step, and nothing else in CI builds it β€” `template-page-money` + # and `scaffold-currency` both scaffold page-money. + # + # Since #206 its entry module has a HARD RESOLUTION DEPENDENCY on + # `./civitai-host.js`, so a wrong import path is a build failure rather than a + # subtle one. Measured: `import '../nonexistent/civitai-host.js'` survived the + # entire Go suite, and would have shipped a template that cannot build at all. + # + # The bundle assertion is separate from Guard A on purpose. Guard A pins the + # SOURCE tree; Vite output is what the platform actually serves, and a + # tree-shaken or mis-externalised side-effect import would leave a bundle with + # no handshake in it. Control pair, both measured locally: with the import the + # bundle carries BLOCK_INIT/BLOCK_READY, with it commented out it carries + # neither β€” while the positive control (the app's display name) matches in + # both cases, proving the grep reads the bundle either way. + template-page-vite: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-go@v5 + with: + go-version: "1.25" + cache: true + + - uses: actions/setup-node@v4 + with: + node-version: "22" + + - name: scaffold page-vite + run: go run ./cmd/civitai app init "CI Vite Block" --dir ./_ci-page-vite --template page-vite + + - name: install + working-directory: ./_ci-page-vite + run: npm install --no-audit --no-fund + + - name: build + working-directory: ./_ci-page-vite + run: npm run build + + - name: the ready-ack survives bundling + working-directory: ./_ci-page-vite + run: | + set -euo pipefail + bundles=$(find dist -name '*.js' -type f | wc -l) + echo "JS files emitted into dist/: $bundles" + if [ "$bundles" -lt 1 ]; then + echo "::error::the build emitted no JS into dist/ β€” nothing to check, so a pass here would be meaningless" + exit 1 + fi + # POSITIVE CONTROL for the grep itself, FIRST: a string that must be in + # the bundle whatever the handshake does. If this misses, the path or + # the pattern is wrong and the two assertions below prove nothing. + control=$(grep -rlF 'CI Vite Block' dist/ | wc -l) + echo "positive control (app display name): $control file(s)" + if [ "$control" -lt 1 ]; then + echo "::error::positive control failed β€” this step is not reading the built bundle" + exit 1 + fi + for needle in BLOCK_INIT BLOCK_READY; do + n=$(grep -rlF "$needle" dist/ | wc -l) + echo "$needle: $n file(s)" + if [ "$n" -lt 1 ]; then + echo "::error::$needle is absent from the built bundle β€” the ready-ack did not survive the build, so the shipped app never says hello (issue #206)" + exit 1 + fi + done + + - name: validate + working-directory: ./_ci-page-vite + run: go run ../cmd/civitai app validate + # Rot-guard: scaffold the page-money template and run its JS toolchain against # the PUBLISHED SDK (@civitai/blocks-react). Catches a template that renders # but no longer installs / typechecks / tests / builds after an SDK bump β€” the diff --git a/AGENTS.md b/AGENTS.md index 038691dc..09269ac2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -152,9 +152,9 @@ func newWhoAmICmd() *cobra.Command { ## Intentional decisions that look wrong (read before "fixing") -Items 1–3 are deliberate mirrors of the platform (items 4 and 8 are deliberate -*non*-mirrors); items 5–8 cover `civitai app metrics`, the CLI's only analytics -read path. The durable fix for the mirroring is a server-side +Items 1–3, 10 and 11 are deliberate mirrors of the platform (items 4 and 8 are +deliberate *non*-mirrors); items 5–9 cover `civitai app metrics`, the CLI's only +analytics read path. The durable fix for the mirroring is a server-side `civitai app validate` endpoint that calls the real `BlockManifestValidator` β€” until that exists, vendoring is on purpose. @@ -290,8 +290,9 @@ until that exists, vendoring is on purpose. `Origin: null` through the same `DialLocalDevServer` the proxy uses, and reads real response headers. `CheckParentOrigins` is a **heuristic** β€” `VITE_BLOCK_ALLOWED_PARENT_ORIGINS` is inlined into the bundle at transform - time and cannot be observed over HTTP, so it is a **third vendored mirror** - (alongside `schema/` and the slot registry): `resolveViteEnv` reproduces + time and cannot be observed over HTTP, so it is a **vendored mirror** + (one of four β€” `schema/`, the slot registry, this, and the ready-ack + emitter of item 11): `resolveViteEnv` reproduces Vite's dev env resolution, where `.env.` beats `.env` and a REAL process env var beats every file (dotenv does not overwrite existing vars). Getting that last rule backwards warns at authors who exported the value in @@ -355,6 +356,129 @@ until that exists, vendoring is on purpose. absolute redirect, which silently turns the tunnel-Host probe into an ordinary loopback request unless it is re-applied. +11. **The scaffold VENDORS the blockβ†’host ready-ack (`internal/blockproto/`), + and it is the FOURTH vendored mirror.** (Provenance: read against + `civitai@35a9598dc9`. The contract lives in + `src/components/AppBlocks/PageBlockHost.tsx` and + `src/components/AppBlocks/usePostMessage.ts` β€” note `usePostMessage.ts` is + under `AppBlocks/`, **not** `src/hooks/`, where it has never lived.) A + `page` app is not shown by the host until it posts `BLOCK_READY`; that + handler in `PageBlockHost.tsx` is the only transition into `ready`. `page-money` gets this free β€” + `@civitai/blocks-react`'s `IframeTransport` acks from its validated- + `BLOCK_INIT` branch β€” but `static` and `page-vite` are deliberately + SDK-free, so they have to say hello themselves. They didn't, and issue #206 + was the result: measured against the real `PageBlockHost` in Chromium, both + templates rendered fine and NEVER reached ready, ending at a visible + failure card after ~37s of bounded auto-retry (`MAX_AUTO_RETRIES = 2`, + backoff `[2000, 5000]`). This was an original omission, not a regression. + - **One authority, copied β€” not templated.** `ready-ack.js` is `go:embed`ed + in `internal/blockproto` and written VERBATIM by `scaffold.Render` (no + `text/template` pass) into the path `Template.ReadyAckPath()` names. Do + NOT add a per-template `.tmpl` copy: two hand-maintained copies drift, and + drift is invisible locally β€” the app renders and dies only inside the + real host. + - **Ack on `BLOCK_INIT`, never on load** β€” and on INIT *only*. Not because + on-load is broken: an on-load poster was **measured working** (ready in + 178–265 ms) in the same harness. On-INIT is chosen for robustness. The + host registers its `BLOCK_READY` subscriber inside an effect and + **silently drops** a message whose type has no subscriber yet, with no + retry (`usePostMessage.ts`), while it re-posts `BLOCK_INIT` every ~400 ms + until acked (`iframeInitController.ts`) β€” so answering INIT removes the + race. It also hands over `event.origin`, so nothing posts to `'*'`; it is + late enough not to reveal an empty interactive frame (the host fades its + launch overlay and enables `pointerEvents` on ready); and it is what the + SDK's own transport does. Repeats must stay a no-op: the host's inbound + channel is rate-limited across ALL types, so re-acking every retry can + starve `BLOCK_ERROR`. + - **The envelope is `{ type, payload }`.** The host dispatches + `data.payload` to subscribers, so top-level fields arrive as + `payload: undefined`. The host happens to ignore the `BLOCK_READY` + payload, so a wrong envelope would not break *this* message β€” it teaches + the wrong shape for every message the author adds next. That is why the + guards assert the envelope even though the ack would work without it. + - πŸ”΄ **It pins the sender WINDOW, not the sender ORIGIN β€” and that is a + deliberate boundary, not an oversight.** The emitter answers + `window.parent` and replies to whatever origin that window sent from. It + establishes "our embedder", NOT "Civitai". Sound for this one message + (the ack carries `{height: 0}` and discloses nothing a page that chose to + frame us doesn't already know) and **insufficient for anything carrying + data**. We deliberately do NOT vendor an origin allowlist here: the real + set (production, preview subdomains, `dev-*.civit.ai` tunnels) is platform + state that moves without notice, so it would become a FIFTH mirror needing + lockstep, and getting it wrong silently breaks the dev tunnel β€” while + `@civitai/blocks-react` already maintains exactly that list from + `VITE_BLOCK_ALLOWED_PARENT_ORIGINS`. So the decision is: keep the emitter + minimal, and say loudly in both scaffold READMEs and the emitter header + that adopting the SDK is the prerequisite for handling inbound data. If + you ever do add an allowlist here, it is a new vendored mirror and needs a + drift check. + - πŸ”΄ **Adopting the SDK means DELETING the emitter in the same change, and + the docs must keep saying so.** Whichever handshake answers the host's + first `BLOCK_INIT` calls `notifyReady()` β†’ `stop()`, which clears the + retry interval **and** the readiness timeout + (`iframeInitController.ts`). If the vendored emitter wins that race + against a freshly-added `IframeTransport`, the SDK's `waitForInit` rejects + at its own `INIT_TIMEOUT_MS = 10_000` and the host sits in `ready` showing + an app that never started β€” no retry, no failure card. That is strictly + worse than #206 and it is silent. Narrow window, but the upgrade path is + the one place the "don't delete it" instruction reverses, so it is called + out with the mechanism rather than as a footnote. + - **The `acked` latch is set AFTER the post, not before.** `postMessage` + throws `SyntaxError` on a `targetOrigin` it cannot parse as a URL β€” + measured in Chromium 1228, `postMessage(msg, 'null')` β€” and `event.origin` + is the string `"null"` whenever the sender is itself at an opaque origin. + Latching first would make one throw permanently silent while the host + keeps retrying at a listener that has given up. Not reachable through + today's `PageBlockHost`; pinned anyway by Guard B's + `--throw-first-post` mode. + - **`RESIZE_IFRAME` is deliberately ABSENT from the page templates.** Both + raw templates used to demo it; `hostHandlerParity.ts` marks it **N/A for + `PageBlockHost`** (a page block fills the surface and does not size to + content), so it was inert advice that also modelled the wrong envelope. + Don't reintroduce it as a "minimal example". Note `iframe.resizable` in + the vendored `schema/` still describes itself in size-to-content terms; + that is a schema-side wording issue, not a licence to re-add the message. + - **Three guards, and none subsumes the others.** + `ready_ack_contract_test.go` (Guard A, runs in `make ci`) enumerates + `AllTemplates()`, decides subject-hood from the RENDERED manifest and + package.json β€” never a hardcoded list β€” and asserts byte-equality with + `blockproto.ReadyAckSource()` plus that the entry point RESOLVES to it, + with a count floor so a guard wired to nothing can't report a serene pass. + πŸ”΄ **"Resolves" is load-bearing and was earned the hard way**: the first + version matched a BASENAME, and two mutants shipped a broken app past the + entire suite β€” `src="./vendor/civitai-host.js"` (a 404) and + `import '../nonexistent/civitai-host.js'` (a build failure). Never + reintroduce a basename or `strings.Contains` match here; every reference + must resolve to a path and be compared with where the emitter actually is. + Guard A still **cannot prove the ack fires**: an inverted `event.source` + check passes every static assertion. + `ready_ack_runtime_test.go` (Guard B) executes the emitter in node against + a fake host and reads the outbound message. It is env-gated + (`CIVITAI_CHECK_SCAFFOLD_RUNTIME=1`) and has TWO runners, of which only + the first gates: the `ready-ack-runtime` job in **`ci.yml`** (every PR) + and the same-named job in `bump-scaffold-pins.yml` (daily drift). Shipping + only the daily one β€” as the first version did β€” means the very failure + Guard B exists to catch merges green and is reported up to 24h later, on a + workflow nothing depends on. + The `template-page-vite` job in `ci.yml` is the third: it is the only + thing that BUILDS an SDK-free template, and it asserts the ack survives + bundling (Guard A pins the source tree; Vite output is what the platform + serves). + If you add a template, add nothing β€” Guard A picks it up automatically and + fails until `ReadyAckPath()` is set. + - **`BLOCK_HELLO` now exists host-side, and the emitter deliberately does + not send it.** When this landed the host had zero references to it; as of + `civitai@35a9598dc9` it has real ones (`iframeInitController.notifyHello`, + `hostHandlerParity.ts`, host browser tests). Re-verified: it is an + **accelerator, not a gate** β€” `notifyHello()` leaves the retry interval + and the readiness timeout armed by `start()` untouched, and its own + comment forbids it ever becoming a precondition for sending init. So a + block that never announces is served by the unchanged retry loop, which is + exactly what our emitter relies on. Not sending it costs only the latency + of one retry tick, and sending it would add a second vendored message for + no correctness gain. If you reconsider, note the init-fragment fast path + ships gated off and refuses `surface === 'dev-tunnel'` by construction. + **When you change a validation rule, keep both vendored mirrors (`schema/` + the ported Go checks in `internal/validate/`, including the slot registry) in sync with the server, and update `examples_test.go` (asserts shipped examples diff --git a/README.md b/README.md index cb573604..f7b3a2d3 100644 --- a/README.md +++ b/README.md @@ -181,8 +181,8 @@ source <(civitai completion bash) # bash; see `civitai completion --help` for ## SDK packages This CLI scaffolds, validates, and submits β€” but the code your app actually -imports lives in two published npm packages (the `page-money` / `page-vite` -templates wire them for you): +imports lives in two published npm packages (the `page-money` template wires +them for you; `static` and `page-vite` are deliberately dependency-free): | Package | What it is | | --- | --- | @@ -234,13 +234,63 @@ full details and examples. parent-origin config, and a unit-test stub. Run `npm run dev:harness` (plain `npm run dev` renders blank without a host). +### The host handshake (`BLOCK_READY`) + +Every template declares a `page` surface, and the host **will not reveal a page +app until the app posts `BLOCK_READY`** β€” that handler is the only transition +into the host's ready state. An app that never sends it is replaced by a visible +failure card once the host's bounded retries run out, even though the app itself +renders perfectly. Nothing you can run locally reproduces that. + +`page-money` gets the handshake for free: `@civitai/blocks-react`'s iframe +transport acks internally, which is why the SDK templates never touch raw +`postMessage`. The two **SDK-free** templates (`static`, `page-vite`) therefore +ship a small vendored emitter, **`civitai-host.js`**, loaded from the entry +point. Leave it in place. + +> ⚠️ **If you adopt `@civitai/blocks-react`, delete `civitai-host.js` in the +> same change.** This is the one situation where removing it is correct, and +> running both is worse than running neither: whichever handshake answers the +> host's *first* `BLOCK_INIT` cancels the host's retry loop **and** its +> readiness timeout. If the vendored emitter wins that race, the SDK transport +> can be left never having seen an init β€” its `waitForInit` rejects after 10s +> and the host sits "ready", showing an app that never started, with no retry +> and no error card. + +Two rules it encodes, which apply to every message you add afterwards: + +- **The envelope is `{ type, payload }`.** The host dispatches + `event.data.payload` to its subscribers, so fields put at the top level + (`{ type: 'X', height: 0 }`) arrive as `payload: undefined`. +- **Answer, don't announce.** The ack goes out in *response* to the host's + `BLOCK_INIT`, addressed at the origin that init arrived from rather than + broadcast to `'*'`. It is also why nothing is posted when you preview locally: + there is no host to send `BLOCK_INIT`, so the emitter stays silent by design. + +> πŸ”’ **The emitter checks the sender *window*, not the sender's *identity*.** It +> answers `window.parent` β€” whoever framed you β€” which is sound for this one +> message because the ack carries no data. It is **not** sufficient for anything +> you add next. The moment you handle an inbound message carrying a token, a +> viewer, storage or a result, check `event.origin` against an allowlist of +> origins you trust, or any page that frames your app can feed it whatever it +> likes. The emitter deliberately does not vendor that allowlist β€” the real list +> (production, preview subdomains, dev tunnels) is platform state that moves +> without notice, and `@civitai/blocks-react` already maintains it from +> `VITE_BLOCK_ALLOWED_PARENT_ORIGINS`. Adopt the SDK before you handle data. + +`RESIZE_IFRAME` is **not** part of a page app's protocol: the host renders a +page block full-viewport, so it does not size to content and ignores the +message. (`useBlockResize` is surface-agnostic and page-money still calls it β€” +on a page surface it is simply a no-op, which is why the SDK templates can share +component code across surfaces.) + ### Local dev loop (harness: mock vs live) -A scaffolded App is a sandboxed iframe β€” `npm run dev` alone shows a blank -screen because there's no host to send `BLOCK_INIT`. The `page-money` / -`page-vite` templates ship a dev **harness** (the SDK's +A scaffolded App is a sandboxed iframe, and locally there is no host to send +`BLOCK_INIT` β€” so `npm run dev` shows you your own UI and nothing of the +protocol. The **`page-money`** template ships a dev **harness** (the SDK's [`@civitai/blocks-react/testing`](https://www.npmjs.com/package/@civitai/blocks-react) -hosts) with two modes: +hosts) to close that gap, with two modes: | Command | Mode | What it does | |---|---|---| diff --git a/internal/blockproto/blockproto.go b/internal/blockproto/blockproto.go new file mode 100644 index 00000000..f56c3704 --- /dev/null +++ b/internal/blockproto/blockproto.go @@ -0,0 +1,45 @@ +// Package blockproto is the CLI's single authority for the block -> host +// postMessage contract that scaffolded, SDK-free apps must implement +// themselves. +// +// It exists so the handshake code has exactly ONE copy in this repo. The +// templates do not each carry their own `.tmpl` of it β€” `scaffold.Render` +// writes these bytes verbatim into every template that needs it, and +// `internal/scaffold/ready_ack_contract_test.go` asserts the rendered copies +// are byte-identical to what `ReadyAckSource` returns. Two hand-maintained +// copies would drift, and the failure mode of drift is invisible: the app +// renders locally and dies only inside the real host. +// +// This is a VENDORED MIRROR of a server-side contract (civitai/civitai -> +// src/components/AppBlocks/PageBlockHost.tsx and +// src/components/AppBlocks/usePostMessage.ts, read at civitai@35a9598dc9), in +// the same sense as `schema/`, the slot registry in +// `internal/validate/targets.go`, and the dev-embed mirror in +// `internal/devtunnel`. When the platform changes the handshake, this file +// changes with it. See AGENTS.md, "Intentional decisions that look wrong". +package blockproto + +import _ "embed" + +// readyAck is the canonical ready-ack emitter. It is plain, dependency-free, +// ES5-safe JavaScript so the no-build `static` template can load it with a +// bare `}, + {"app.js", "// app"}, + }, + wantAccept: true, + }, + { + name: "accept: the entry module imports it (the page-vite shape)", + ack: ackRel, + files: []file{ + {"index.html", ``}, + {"src/main.jsx", "import './civitai-host.js';\nimport React from 'react';"}, + }, + wantAccept: true, + }, + { + name: "reject: right basename, wrong directory in the script tag", + ack: "civitai-host.js", + files: []file{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + }, + { + name: "reject: right basename, unresolvable relative import", + ack: ackRel, + files: []file{ + {"index.html", ``}, + {"src/main.jsx", "import '../nonexistent/civitai-host.js';"}, + }, + }, + { + name: "reject: a BARE specifier that would resolve to a package", + ack: ackRel, + files: []file{ + {"index.html", ``}, + {"src/main.jsx", "import 'civitai-host.js';"}, + }, + }, + { + name: "reject: referenced only from an HTML comment", + ack: "civitai-host.js", + files: []file{ + {"index.html", "\n"}, + {"app.js", "// app"}, + }, + }, + { + name: "reject: the import is commented out but still greppable", + ack: ackRel, + files: []file{ + {"index.html", ``}, + {"src/main.jsx", "// import './civitai-host.js';\nimport React from 'react';"}, + }, + }, + { + name: "reject: imported by a file nothing loads", + ack: ackRel, + files: []file{ + {"index.html", ``}, + {"src/main.jsx", "import React from 'react';"}, + {"src/orphan.js", "import './civitai-host.js';"}, + }, + }, + { + name: "reject: no script tags at all", + ack: "civitai-host.js", + files: []file{{"index.html", "

hi

"}}, + }, + { + name: "reject: loaded from a CDN URL that merely ends in the name", + ack: "civitai-host.js", + files: []file{ + {"index.html", ``}, + {"app.js", "// app"}, + }, + }, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + dir := t.TempDir() + // The emitter itself always exists where `ack` says β€” so a + // rejection can only come from the REFERENCE, never from a missing + // file. + all := append([]file{{c.ack, "// emitter"}}, c.files...) + for _, f := range all { + p := filepath.Join(dir, filepath.FromSlash(f.path)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(f.body), 0o644); err != nil { + t.Fatal(err) + } + } + chain, err := readyAckWiring(dir, c.ack) + if c.wantAccept { + if err != nil { + t.Fatalf("wiring check REJECTED a correctly wired project: %v", err) + } + t.Logf("accepted: %s", chain) + return + } + if err == nil { + t.Fatalf("wiring check ACCEPTED a project the browser cannot load the emitter in: %q\n"+ + "this is the basename-matching class β€” the reference must RESOLVE to the emitter's real path", chain) + } + t.Logf("rejected: %v", err) + }) + } +} + +// --------------------------------------------------------------------------- +// The per-template contract. +// --------------------------------------------------------------------------- + +// minPageTemplatesNeedingAck is the COUNT POSITIVE CONTROL. Without it a guard +// wired to nothing β€” a manifest decoder that stopped finding `page`, a render +// that stopped emitting, an enumeration that returned an empty slice β€” reports +// a serene pass. `static` and `page-vite` are both SDK-free page templates, so +// this floor is 2 today; raise it when a third lands, never lower it to make a +// run green. +// +// This complements the `AllTemplates() != 3` tripwire in slug_test.go rather +// than duplicating it: that one pins the total, this one pins how many the +// ready-ack guard actually EXAMINED. +const minPageTemplatesNeedingAck = 2 + +// TestScaffoldedPageTemplatesShipTheReadyAck is the contract guard. +func TestScaffoldedPageTemplatesShipTheReadyAck(t *testing.T) { + canonical := blockproto.ReadyAckSource() + + examined := 0 + var ( + pageTemplates []string + sdkTemplates []string + ) + + for _, tmpl := range AllTemplates() { + dest := filepath.Join(t.TempDir(), string(tmpl)) + if _, err := Render(tmpl, dest, Data{Slug: "ready-block", Name: "Ready Block"}); err != nil { + t.Fatalf("render %s: %v", tmpl, err) + } + + if !manifestDeclaresPage(t, tmpl, dest) { + // Not a full-page surface: the readiness contract this guard pins + // is the page host's. Skipped on EVIDENCE from the rendered + // manifest, not from a list in this file. + t.Logf("%s: manifest declares no `page` surface β€” not subject to the page-host ready contract", tmpl) + continue + } + pageTemplates = append(pageTemplates, string(tmpl)) + + if pkgs := civitaiSDKDeps(t, dest); len(pkgs) > 0 { + // `@civitai/blocks-react`'s IframeTransport acks internally (it + // dispatches BLOCK_READY from its validated-BLOCK_INIT branch), so + // a second emitter here would double-post into a rate-limited + // inbound channel. Again: skipped on evidence β€” the rendered + // package.json really depends on the SDK. + sdkTemplates = append(sdkTemplates, string(tmpl)) + t.Logf("%s: depends on %s β€” the SDK transport performs the ack; no vendored emitter expected", + tmpl, strings.Join(pkgs, ", ")) + if rel := tmpl.ReadyAckPath(); rel != "" { + t.Errorf("%s carries the SDK AND declares ReadyAckPath()=%q β€” that double-posts BLOCK_READY; "+ + "pick one", tmpl, rel) + } + continue + } + + rel := tmpl.ReadyAckPath() + if rel == "" { + t.Errorf("template %q declares a `page` surface and carries no @civitai/* SDK, but "+ + "ReadyAckPath() is empty β€” a page app that never posts BLOCK_READY is replaced by a "+ + "failure card in the real host (issue #206). Give it a path in scaffold.go so "+ + "Render ships blockproto's emitter.", tmpl) + continue + } + examined++ + + t.Run(string(tmpl), func(t *testing.T) { + // ASSERTION 1 β€” byte-equality with the single authority. Kept + // independent of the wiring assertion below: a template can ship a + // perfect copy nobody loads, or load a copy that has drifted, and + // the two failures need different fixes. + t.Run("byte-identical to blockproto.ReadyAckSource", func(t *testing.T) { + got, err := os.ReadFile(filepath.Join(dest, filepath.FromSlash(rel))) + if err != nil { + t.Fatalf("%s does not ship %s: %v β€” Render must copy blockproto's emitter in", tmpl, rel, err) + } + if string(got) != string(canonical) { + t.Fatalf("%s ships a ready-ack emitter that is NOT byte-identical to "+ + "blockproto.ReadyAckSource() (%d bytes rendered vs %d canonical).\n"+ + "There must be exactly ONE authority for the handshake β€” edit "+ + "internal/blockproto/ready-ack.js, never a per-template copy.", + tmpl, len(got), len(canonical)) + } + }) + + // ASSERTION 2 β€” the copy is actually LOADED. Byte-equality of an + // orphan file proves nothing about the running app. + t.Run("reached from the rendered entry point", func(t *testing.T) { + chain, err := readyAckWiring(dest, rel) + if err != nil { + t.Fatalf("%s ships %s but nothing loads it: %v\n"+ + "Reference it from index.html (a diff --git a/internal/scaffold/testdata/readyack/driver.mjs b/internal/scaffold/testdata/readyack/driver.mjs new file mode 100644 index 00000000..f3f22a13 --- /dev/null +++ b/internal/scaffold/testdata/readyack/driver.mjs @@ -0,0 +1,175 @@ +// Runtime driver for the scaffold ready-ack guard (Guard B). +// +// Loads a ready-ack emitter under a minimal `window` stub, plays the host's +// side of the handshake at it, and prints what the emitter ACTUALLY did as +// JSON on stdout. It asserts nothing β€” every verdict is made in Go +// (internal/scaffold/ready_ack_runtime_test.go), so this file cannot decide it +// is happy with itself. +// +// Usage: node driver.mjs [--throw-first-post] +// +// `--throw-first-post` makes the FIRST outbound postMessage throw, the way a +// browser does when `targetOrigin` cannot be parsed as a URL (MEASURED in +// Chromium 1228: `postMessage(msg, 'null')` throws +// `SyntaxError: Invalid target origin 'null'`, and `event.origin` is the string +// "null" whenever the sender is itself at an opaque origin). An emitter that +// latches its "already acked" flag BEFORE posting goes permanently silent in +// that case; one that latches after can still answer the host's next retry. +import { readFileSync } from 'node:fs'; + +const emitterPath = process.argv[2]; +if (!emitterPath) { + console.error('usage: driver.mjs [--throw-first-post]'); + process.exit(2); +} +const throwFirstPost = process.argv.includes('--throw-first-post'); + +export const HOST_ORIGIN = 'https://host.civitai.example'; +const FOREIGN_ORIGIN = 'https://not-the-host.example'; + +/** Every outbound postMessage, in order. */ +const posted = []; +/** Posts that threw, in order β€” an attempt the emitter made and lost. */ +const threw = []; +/** Listener registrations, by event type, as the emitter made them. */ +const listeners = Object.create(null); + +const parentWindow = { + postMessage(message, targetOrigin) { + if (throwFirstPost && threw.length === 0) { + threw.push({ message, targetOrigin }); + // Same constructor and shape a browser raises for an unparseable target. + throw new SyntaxError( + `Failed to execute 'postMessage' on 'Window': Invalid target origin '${targetOrigin}' in a call to 'postMessage'.` + ); + } + posted.push({ window: 'parent', message, targetOrigin }); + }, +}; + +// A window that is NOT the parent. If the emitter ever posts here, the source +// check is not doing its job. +const foreignWindow = { + postMessage(message, targetOrigin) { + posted.push({ window: 'foreign', message, targetOrigin }); + }, +}; + +const win = { + parent: parentWindow, + addEventListener(type, fn) { + (listeners[type] ??= []).push(fn); + }, + removeEventListener(type, fn) { + const set = listeners[type]; + if (!set) return; + const i = set.indexOf(fn); + if (i >= 0) set.splice(i, 1); + }, + postMessage(message, targetOrigin) { + posted.push({ window: 'self', message, targetOrigin }); + }, +}; + +globalThis.window = win; +// Enough DOM for an emitter that (wrongly) waits on the document to at least +// load without throwing β€” a crash and an inert emitter must not look alike. +globalThis.document = { + addEventListener(type, fn) { + (listeners[`document:${type}`] ??= []).push(fn); + }, + removeEventListener() {}, + getElementById: () => null, + documentElement: { scrollHeight: 1234 }, + readyState: 'complete', +}; + +let loadError = null; +try { + // Run the emitter the way a