feat: configure the public demo API origin
7 files changed,
+416
−20
cmd/console/main.go+6 −5docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md+10 −10internal/console/apidemo.go+7 −1internal/console/demo_api_origin.go+62 −0internal/console/demo_api_origin_test.go+318 −0internal/console/domainpolicy.go+3 −0internal/console/server.go+10 −4
Intent
Attributed to this commit: 3.74 g CO₂e (415,779 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on demo-api-site-route, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/cmd/console/main.go b/cmd/console/main.go| index 97c495774..f7e903542 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -480,11 +480,12 @@ func serve() { |
| log.Fatalf("%v: %v", console.DemoConfigError(), err) |
| } |
| cfg := console.Config{ |
| - Demo: demoConfig, |
| - Origin: origin, |
| - Keymail: envOr("CONSOLE_KEYMAIL", "https://keymail.dev"), |
| - Registry: envOr("CARLOS_REGISTRY", "/data/registry.db"), |
| - Releases: rel, |
| + DemoAPIOrigin: os.Getenv("CONSOLE_DEMO_API_ORIGIN"), |
| + Demo: demoConfig, |
| + Origin: origin, |
| + Keymail: envOr("CONSOLE_KEYMAIL", "https://keymail.dev"), |
| + Registry: envOr("CARLOS_REGISTRY", "/data/registry.db"), |
| + Releases: rel, |
| // The deployment bucket's NAME, from the same variable openStore() |
| // opens it with — /fleet/architecture draws the box -> bucket edge |
| // from it. Empty on a CARLOS_DEPLOYMENT_DIR deployment, which |
diff --git a/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md b/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md| index 2b641df8a..dc1bf2b47 100644 |
| --- a/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md |
| +++ b/docs/superpowers/plans/2026-11-04-agent-start-demo-4-start-page.md |
| @@ -17,7 +17,7 @@ |
| - Go 1.26.10; module `demo.local/app`; `amadan.net/rastrillo/rastrillo v0.30.2`; complete Plan 1 module closure and checksums; `CGO_ENABLED=0`; entry package `.`; linux-arm64 output. Fiesta is embedded assets, not an added module. Do not run `go mod tidy`, use `@latest`, add `replace`, or change the lock to accommodate the starter. |
| - Source is one gzip stream containing ordinary USTAR files/directories: at most 5,000,000 compressed bytes, 20,000,000 expanded file bytes, 256 files, 2,000,000 bytes per file, and 256 directories. Output binary cap: 33,554,432 bytes. No symlinks, hardlinks, PAX/GNU extension records, sparse files, VCS tree, vendor tree or workspace files. |
| - Binary apps read `--socket` and `--db` flags. Demo SQLite stays on its assigned box with no replica. Public demo hosts are never reused. Do not infer a hostname, database recovery or a replacement app from an earlier run. |
| -- Provider-neutral website and starter; no cloud SDK, vendor build service, bucket reader, background health polling or new per-box polling. Only an active agent polls its returned console job URL, at bounded intervals. |
| +- Provider-neutral website and starter; no cloud SDK, vendor build service, bucket reader, background health polling or new per-box polling. Only an active agent polls its returned site job URL, at bounded intervals. |
| - The demo journey switches default off; Plan A needs no off switch because sites without twins retain their existing behaviour. Website build switch `CARLOS_START_DEMO=1` selects the new journey; unset builds the account path without anonymous-publish instructions. Console admission remains its existing drop-in switch `CARLOS_DEMO_APPS=1`. Neither switch enables the other. **Switch-on date: dev on the day this plan lands.** Public activation waits for Plan A on the serving edges and Plans 2 and 3 merged, enabled and verified, then accompanies the approved website release. Do not land an unused preparatory slice separately. |
| - The dev acceptance target is the existing `dev.trycarlos.com` setup. The console origin is a separate configuration value, never inferred from that name. One `*.trycarlos.com` certificate covers direct demo names; it does not cover invented names below `dev.trycarlos.com`. Use returned URLs and verify their actual TLS. The issuer is the housekeeper, not the ingress. This plan creates no DNS records or certificates. |
| - Demo boxes have 2 GB RAM: no test compilation, browser installation or test suite there. Author/CI checks run off-box; the existing remote builder compiles submitted apps only. Preserve default Go caches; scratch goes under `$TMPDIR` or `~/.cache` and is removed. |
| @@ -78,11 +78,11 @@ One source, `W/src/start/agent.md`, contains the following ordered directives. ` |
| 3. **Choose scope and style.** One binary and one local SQLite database; no outbound calls or restricted capabilities. Existing-app migrations take the account path with an honest rootfs/managed-fleet explanation at the user's level, not an automatic rewrite. Map calm/everyday to `day`, minimal to `plain`, bold to `signal`, and playful to `day` with small local presentation changes (my call). Explain that the three themes are starting points, not four invented theme packages. Keep the initial app to one useful screen and one persisted entity. |
| 4. **Fetch the pinned starter.** Use its same-origin immutable archive and checksum or the complete source listing beside it. Keep `go.mod` and `go.sum` unchanged. No CLI, Go installation, package manager or local compilation is required of the demo user. Use an already available archive/HTTP tool in the agent's environment. A cloud agent without Go must complete the flow. A chat application unable to make outbound requests is out of scope. |
| 5. **Pack the source.** Regular USTAR entries rooted at `go.mod`, `go.sum`, `main.go`, `templates/`, `static/` and `LICENSE.fiesta`, with relative clean names and no enclosing directory or leading `./`. Include new application files explicitly; exclude tests, `.git`, credentials, SQLite files and the output archive. A GNU tar example uses `tar --format=ustar -czf <outside-source>/source.tar.gz go.mod go.sum main.go templates static LICENSE.fiesta`; a Python standard-library alternative specifies `tarfile.USTAR_FORMAT`, enumerates only regular allowlisted files, and assigns the same relative names. Never use an unqualified `tar ... .`. Do not execute generators or change dependency versions to repair an error. |
| -6. **Publish through the console origin.** Send raw archive bytes to `POST <consoleOrigin>/api/demo/apps`, `Content-Type: application/gzip`, `X-Carlos-Client: <actual harness>`, without Authorization on the first create. No multipart, base64 or JSON wrapper. On 202 retain `jobId`, `name`, `statusUrl`, Unix-seconds `expiresAt`, `claimToken`, `claimUrl`, and `claimAvailable` in private agent state; never in the app, repository, public transcript or screenshots. Give the user the returned secret claim link once, privately, as recovery information. Do not claim it works if `claimAvailable` is false. |
| +6. **Publish through the site origin.** Send raw archive bytes to `POST <siteOrigin>/api/demo/apps`, `Content-Type: application/gzip`, `X-Carlos-Client: <actual harness>`, without Authorization on the first create. No multipart, base64 or JSON wrapper. On 202 retain `jobId`, `name`, `statusUrl`, Unix-seconds `expiresAt`, `claimToken`, `claimUrl`, and `claimAvailable` in private agent state; never in the app, repository, public transcript or screenshots. Give the user the returned secret claim link once, privately, as recovery information. Do not claim it works if `claimAvailable` is false. |
| 7. **Wait and repair.** GET the returned `statusUrl` without a bearer token. Poll no faster than its `Retry-After` (2 seconds on main); use 5 seconds if absent, respect longer retry values and allow at most five minutes of automatic waiting (my call). `building`/`starting` are pending; only `live` plus `url` is success. `failed` carries `diagnostics`, `diagnosticsTruncated` and `message`; fix source and resubmit with `Authorization: Bearer <claimToken>` to the same publish endpoint. Retain the original claim fields because update replies omit them. Make at most two automatic repair submissions before explaining the problem; do not consume the lifetime's 60 attempts in a loop. Do not promise rollback unless the response says it occurred. |
| -8. **Handle refusals without creating a second app.** 400/413/415 require source correction; 409 means wait for the active update; 429 can mean a request budget or the lifetime update limit, so follow its response rather than retry indefinitely; 503 means unavailable, not permission to rotate identity. 401/404/410 or unavailable claims never fall back to anonymous create. A lost create response is an unknown outcome with a potentially lost one-time token: stop automatic submission and explain, since main has no create idempotency/recovery endpoint. A transport-level host block is distinct from an API error. Explain one exact console hostname to allow under the agent's internet/network permissions, why it is needed and that settings differ by product; then retry once authorised. Never suggest disabling the sandbox or allowing wildcard domains. |
| -9. **Share the result.** Hand over the returned live URL unchanged, formatted as a full Markdown link, and explain the actual `expiresAt`, fixed 24-hour lifetime and claim availability. Updates use the same bearer and do not extend expiry. Do not synthesize URLs from `name`, shorten a claim link, lose its fragment, or send a token to the live app. HTTP tooling must not follow a credential-bearing request to another origin; validate HTTPS console origin before using returned status/claim endpoints, while preserving valid returned URLs byte-for-byte. |
| -10. **Claim through Plan 3 (declared dependency).** When claiming is available, ask whether they want to keep it; then ask for email, start the declared challenge and ask for the emailed code. Keymail uses the returned browser link. If multiple accounts are returned, ask the person to choose explicitly; do not choose the most recently used account. Plan-limit/permission refusals leave the demo on its original expiry. Follow Plan 3's completion/status contract through data transfer; verification or account choice alone is not success. Share the returned permanent URL only after successful completion, verify a previously saved row there, and discard the consumed demo credential. Do not manufacture a scoped account credential. |
| +8. **Handle refusals without creating a second app.** 400/413/415 require source correction; 409 means wait for the active update; 429 can mean a request budget or the lifetime update limit, so follow its response rather than retry indefinitely; 503 means unavailable, not permission to rotate identity. 401/404/410 or unavailable claims never fall back to anonymous create. A lost create response is an unknown outcome with a potentially lost one-time token: stop automatic submission and explain, since main has no create idempotency/recovery endpoint. A transport-level host block is distinct from an API error. Explain the exact site hostname to allow under the agent's internet/network permissions, why it is needed and that settings differ by product; then retry once authorised. Never suggest disabling the sandbox or allowing wildcard domains. |
| +9. **Share the result.** Hand over the returned live URL unchanged, formatted as a full Markdown link, and explain the actual `expiresAt`, fixed 24-hour lifetime and claim availability. Updates use the same bearer and do not extend expiry. Do not synthesize URLs from `name`, shorten a claim link, lose its fragment, or send a token to the live app. HTTP tooling must never follow redirects with credentials. Validate every agent API endpoint against the exact HTTPS `siteOrigin` and its allowed method/path before sending a request: `POST /api/demo/apps`, `GET /api/demo/jobs/{jobID}`, and the four claim operations only after Plan 3 and the alias follow-up merge. The job ID is one nonempty base64url segment; reject queries, fragments, escapes and noncanonical path spellings. Validate browser claim links against the exact HTTPS `consoleOrigin` and `/demo/claim`, with no query, preserving the secret fragment and the valid returned URL byte-for-byte. Give those links to the human without fetching them. |
| +10. **Claim through Plan 3 (declared dependency).** When claiming is available, use `siteOrigin` for the merged claim API operations. Ask whether they want to keep it; then ask for email, start the declared challenge and ask for the emailed code. Keymail uses the returned browser link. If multiple accounts are returned, ask the person to choose explicitly; do not choose the most recently used account. Plan-limit/permission refusals leave the demo on its original expiry. Follow Plan 3's completion/status contract through data transfer; verification or account choice alone is not success. Share the returned permanent URL only after successful completion, verify a previously saved row there, and discard the consumed demo credential. Do not manufacture a scoped account credential. |
| 11. **The right way after claim.** Offer, rather than silently start, the permanent workflow. Download the matching CLI binary and published checksums from the public `carlosframework/releases` release page; never `go install` the private platform module. Sign in with `carlos auth login --console <consoleOrigin>` and browser code approval, inspect `carlos auth whoami`, select the claimed account/app, put source in the user's chosen repository, and keep tokens/databases/build output out of it. Build the app for the deployment's supported architecture in a development environment, then `carlos deploy --console <consoleOrigin> --account <claimedAccount> --app <claimedApp> ./shop-linux-arm64`. Preserve the database and verify both the new UI and saved row. Do not run `apps create` for an already claimed app. For newcomers explain each step and defer setup until they choose it; the no-install promise applies to the demo, not all future development. |
| ## Task 1: Publish a locked, flag-based Rastrillo and Fiesta starter |
| @@ -120,13 +120,13 @@ One source, `W/src/start/agent.md`, contains the following ordered directives. ` |
| **Interfaces:** |
| -- `loadStartConfig(env: Record<string,string|undefined>) -> StartConfig`; fields `enabled:boolean`, `siteOrigin:string`, `consoleOrigin:string`, `accountUrl:string`, `starterVersion:string`, `claimContractRevision:string`. `CARLOS_START_DEMO` is unset or `1`; enabled builds require `CARLOS_START_SITE_ORIGIN`, `CARLOS_START_CONSOLE_ORIGIN`, `CARLOS_START_ACCOUNT_URL`. Origins must be HTTPS, without credentials/query/fragment/path; account URL must be same-console-origin HTTPS. No origin from a request Host, query parameter or model guess. Starter version is `v1`. |
| +- `loadStartConfig(env: Record<string,string|undefined>) -> StartConfig`; fields `enabled:boolean`, `siteOrigin:string`, `consoleOrigin:string`, `accountUrl:string`, `starterVersion:string`, `claimContractRevision:string`. `CARLOS_START_DEMO` is unset or `1`; enabled builds require `CARLOS_START_SITE_ORIGIN`, `CARLOS_START_CONSOLE_ORIGIN`, `CARLOS_START_ACCOUNT_URL`. Origins must be canonical HTTPS DNS origins, without ports (443 is implicit), credentials, paths, queries, fragments, wildcards or IP literals; account URL must be same-console-origin HTTPS. `siteOrigin` is also the publish/update/poll and merged claim API origin. It must equal the deployment's `CONSOLE_DEMO_API_ORIGIN` and edge `CARLOS_DEMO_API_ORIGIN`; retain `consoleOrigin` for browser claim validation and optional later CLI onboarding. Do not add `demoAPIOrigin` or `CARLOS_START_DEMO_API_ORIGIN`: this journey uses one site host for agent API calls. No origin from a request Host, query parameter or model guess. Starter version is `v1`. |
| - Production site origin is [https://carlosframework.com](https://carlosframework.com); its console origin is [https://console.carloku.com](https://console.carloku.com). Dev values come from the active dev destination, recorded during Task 5. Public copy still contains the single canonical paste line; dev acceptance uses the equivalent deployed dev `/start` URL and verifies the public line separately. |
| - Produces `renderAgent(template: string, config: StartConfig, claimContract: ClaimContract, starter: StarterManifest) -> string` in `hack/start-content.mjs`; replace named deployment/contract placeholders only, reject unresolved placeholders, and preserve all other Markdown bytes. Task 3 consumes this renderer. |
| - Create/update/status consume the actual fields in the Agent content contract. `start-claim-contract.json` has the `ClaimContract` shape and is a website-side documentation fixture, **not a new console endpoint or wire format**. Its keys are `producerCommit`, `producerPlan`, `start`, `verify`, `chooseAccount`, `status`, `browser`, `complete`; each operation records Plan 3's exact method/path/auth/request/response fixture. It contains synthetic secrets only. The build refuses enabled claim instructions without a pinned merged producer revision and complete fixtures. |
| - [ ] **Step 1: Bind the declared Plan 3 dependency.** Once Plan 3 is merged, encode the declared interface table above in `start-claim-contract.json`, cite producer handler file:line and merged SHA, and compare every field to the handlers. Carry account selection, Keymail browser completion, retry/expiry and asynchronous data transfer exactly. If the producer has changed, update this consumer contract before implementing it; if absent, keep this task pending. Do not review against an unmerged producer. Paul need not design the wire protocol. |
| -- [ ] **Step 2: Write failing transcript tests.** Fixtures cover novice, experienced developer, playful/minimal UI, existing-app migration, external API request, blocked host, failed build then bearer update, 429, lost 202 response, expired token and `claimAvailable:false`. Assertions pin ask-before-build, no demo install, bounded polling/repair, unchanged URLs, secret-free public output, no second create and explicit account path. Claim fixtures cover zero/one/multiple accounts, wrong code, Keymail, plan refusal, pending copy, successful permanent URL and consumed token. A canned transcript is contract coverage, not proof of LLM behaviour. |
| +- [ ] **Step 2: Write failing transcript tests.** Fixtures cover novice, experienced developer, playful/minimal UI, existing-app migration, external API request, blocked site host, failed build then bearer update, 429, lost 202 response, expired token and `claimAvailable:false`. Assertions pin ask-before-build, no demo install, bounded polling/repair, unchanged URLs, secret-free public output, no second create and explicit account path. Claim fixtures cover zero/one/multiple accounts, wrong code, Keymail, plan refusal, pending copy, successful permanent URL and consumed token. The blocked-host fixture permits only the exact site hostname for publish/update/poll and merged claim requests; it must not request console-host permission or fetch a browser claim link. Include forged or cross-origin status links, wrong paths and credential-bearing redirects as refusals. A canned transcript is contract coverage, not proof of LLM behaviour. |
| - [ ] **Step 3: Run to verify failure.** `node --test test/start-protocol.test.mjs`; expect missing directives/config/fixtures to fail. Assertions must inspect parsed request transcripts and rendered instructions, not only keyword presence. |
| - [ ] **Step 4: Write the Agent content contract into the single source.** Include complete request/response examples, GNU tar and Python packaging recipes, link to the pinned starter and all required fields. Render the exact merged claim examples from the fixture. Add the public releases link, verified CLI sequence and source-preservation guidance after claim. `llms.txt` gets an anonymous-demo exception to its general replicated-storage description. |
| - [ ] **Step 5: Verify and commit.** Repeat the transcript tests; compare each rendered wire example to its producer fixture. Commit subject `docs: add the agent demo and claim journey`. |
| @@ -185,13 +185,13 @@ One source, `W/src/start/agent.md`, contains the following ordered directives. ` |
| **Interfaces:** |
| -- `verifyStartOrigin(origin: URL) -> Promise<Verification>`, where `Verification={origin:string,version:string,markdownSHA256:string,starterSHA256:string,checks:Record<string,boolean>}`, in the live test checks real negotiated responses, TLS, content hash, release header and starter checksum. It never creates apps by being imported or through the default test command. |
| +- `verifyStartOrigin(origin: URL) -> Promise<Verification>`, where `Verification={origin:string,version:string,markdownSHA256:string,starterSHA256:string,checks:Record<string,boolean>}`, in the live test checks real negotiated responses, TLS, content hash, release header and starter checksum. It also sends a non-mutating, redirect-refusing GET to `<siteOrigin>/api/demo/jobs/<unknownJobID>` with a well-formed unknown ID (32 random bytes encoded as unpadded base64url). Require HTTP 404, `application/json`, the console's `error` response matching its demo-not-found fixture, and `Cache-Control: no-store`; an empty or static 404 fails. It never creates apps by being imported or through the default test command. |
| - Acceptance record holds website/platform/Plan A/Plan 2/Plan 3 SHAs and the serving edge release, starter archive digest, console/site origins, returned public demo/permanent URLs, elapsed times, request counts, agent/harness and result for each scenario. Redact claim links, bearer tokens, email codes, personal email and cookies. Approved human report prose uses the copy table; raw machine evidence is kept separately. |
| - Release script requires explicit console/account/app/channel/site-origin arguments and a clean merged commit. Build artifacts on the author/CI machine and deploy with the public CLI. No implicit flagship defaults, infrastructure provisioning, IAM, direct bucket writes or SSH. Retain the previous static release/version for rollback; ship only built `_site/` output. |
| - [ ] **Step 1: Establish prerequisites and expected failure.** With the feature off, verify the account path remains usable and no anonymous instructions are advertised. Confirm Plan A is merged and released to the website’s serving edge, and Plans 2 and 3 are merged/live and claim availability is true before claiming a complete journey. Run `node --test test/start-live.test.mjs` against the dev site before the new static content is deployed and record the expected content failure. No test result may silently pass because a live case skipped. |
| - [ ] **Step 2: Build and enable the dev release.** Discover and record the dev console/site destination through documented console/CLI configuration and use the existing designated dev scope. Build `_site/` with `CARLOS_START_DEMO=1` and the exact dev origins; deploy through the existing static-site CLI workflow. Keep the route kind, domain claims and placement unchanged. Verify `/start` follows its slash redirect and `/start/` returns HTML or Markdown as Plan A specifies; compare the Markdown bytes with `/start/index.md`. Admission remains the console drop-in already live from Plan 1. |
| -- [ ] **Step 3: Run the decisive cloud-agent witness.** In a fresh real cloud coding-agent session, initially without Go or the CLI, paste only the dev equivalent of the homepage line. Use a phone browser for the human side. Describe a small shop list, answer the experience/feel questions, and approve the small build. Permit at most the one explained console-host allowlist step if blocked. Have the agent fetch the served instructions, obtain/modify/pack the starter, POST source, poll the returned status URL and share the actual live URL. Create a row in the app, ask for one visible change, and verify the bearer update preserves that row and the expiry. Inject one compile error to exercise diagnostics/repair. Target less than five minutes from paste to first working URL; record measured time and network intervention rather than claiming success from a mock. |
| +- [ ] **Step 3: Run the decisive cloud-agent witness.** In a fresh real cloud coding-agent session, initially without Go or the CLI, paste only the dev equivalent of the homepage line. Use a phone browser for the human side. Describe a small shop list, answer the experience/feel questions, and approve the small build. Permit at most the one explained site-host allowlist step if blocked. Have the agent fetch the served instructions, obtain/modify/pack the starter, POST source, poll the returned status URL and share the actual live URL. Create a row in the app, ask for one visible change, and verify the bearer update preserves that row and the expiry. Inject one compile error to exercise diagnostics/repair. Target less than five minutes from paste to first working URL; record measured time and network intervention rather than claiming success from a mock. |
| - [ ] **Step 4: Complete claim and normal development.** Through that agent, use a designated test email and Plan 3's real challenge to keep the app. Verify the copied row at the returned permanent URL, the demo's moved page, and rejection of the old demo token. Record email-verification time separately from transfer time, with the design's under-one-minute claim target. Exercise account-choice, unavailable-claim and Keymail branches through fixtures plus designated real test identities where available; clearly label any live branch not witnessed. After the person opts in, obtain the public CLI release, sign in, place source in a private scratch repo without secrets, deploy a second visible change to the claimed app and verify its existing row. Do not weaken the no-install demo path to make this post-claim check pass. |
| - [ ] **Step 5: Check required harnesses and the release gate.** Run at least the create/live/update journey in Claude Code local and cloud, Codex local and cloud, and Cursor; include phone operation of the real cloud witness. Unknown fetcher UAs must still work from visible HTML. Record actual harness versions and pass/fail, not guessed UA coverage. On the author/CI machine run `npm run check`, all new Node tests and the starter’s targeted checks once. These are future website gates, not a platform full-suite instruction for this authoring session. A missing harness witness remains outstanding acceptance work. |
| - [ ] **Step 6: Review, land, release and clean up.** Obtain one whole-branch review after the dependency gates pass, carrying the history below. Follow the website’s reviewed-branch landing policy and green tip CI; publish the visible dev slice on landing. Public activation uses its existing static release workflow, approved production origins and the previous static version for rollback. Verify Plan A’s edge release and both representations, existing docs/skills and the canonical paste line on all three website hosts from W `AGENTS.md:199`. This plan authorises no new infrastructure or domain/route changes; any expansion needs separately scoped approval. Roll back the static version on failure. Remove only this run’s acceptance apps/data and scratch, stop local processes, and retain the planned dev activation. Commit subject `test: verify the start journey on dev`. |
| @@ -221,4 +221,4 @@ Self-review: design §3's conversation, style, scope, source submission, repair, |
| ## Open questions |
| -None for Paul about what gets built. Plan A’s merge and serving-edge release, the merged Plan 3 wire contract, reviewed human copy and real harness witnesses are explicit execution gates, not unresolved design choices. |
| +None for Paul about what gets built. Plan A’s merge and serving-edge release, the demo API site route release and claim-path follow-up, the merged Plan 3 wire contract, reviewed human copy and real harness witnesses are explicit execution gates, not unresolved design choices. |
diff --git a/internal/console/apidemo.go b/internal/console/apidemo.go| index edfffb3f0..351c93819 100644 |
| --- a/internal/console/apidemo.go |
| +++ b/internal/console/apidemo.go |
| @@ -304,6 +304,9 @@ func demoError(w http.ResponseWriter, err error) { |
| } |
| func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| + if !s.requireDemoAPIProof(w, r) { |
| + return |
| + } |
| w.Header().Set("Cache-Control", "no-store") |
| if !s.cfg.Demo.Enabled { |
| http.NotFound(w, r) |
| @@ -452,7 +455,7 @@ func (s *Server) handleDemoPublish(w http.ResponseWriter, r *http.Request) { |
| demoError(w, err) |
| return |
| } |
| - response := map[string]any{"jobId": job.ID, "name": row.Name, "statusUrl": strings.TrimRight(s.cfg.Origin, "/") + "/api/demo/jobs/" + job.ID, "expiresAt": expiresAt} |
| + response := map[string]any{"jobId": job.ID, "name": row.Name, "statusUrl": strings.TrimRight(s.demoAPIOrigin(), "/") + "/api/demo/jobs/" + job.ID, "expiresAt": expiresAt} |
| if update == nil { |
| response["claimAvailable"] = false |
| response["claimToken"] = identity.Token |
| @@ -512,6 +515,9 @@ func (l *demoStatusLimiter) allow(ip string, now time.Time) bool { |
| return true |
| } |
| func (s *Server) handleDemoStatus(w http.ResponseWriter, r *http.Request) { |
| + if !s.requireDemoAPIProof(w, r) { |
| + return |
| + } |
| w.Header().Set("Cache-Control", "no-store") |
| w.Header().Set("Retry-After", "2") |
| ip, err := demo.CanonicalIP(s.clientIP(r)) |
diff --git a/internal/console/demo_api_origin.go b/internal/console/demo_api_origin.go| new file mode 100644 |
| index 000000000..dfe2a32a8 |
| --- /dev/null |
| +++ b/internal/console/demo_api_origin.go |
| @@ -0,0 +1,62 @@ |
| +package console |
| + |
| +import ( |
| + "errors" |
| + "net" |
| + "net/http" |
| + "net/url" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/edgeproof" |
| +) |
| + |
| +func validateDemoAPIOrigin(raw string) (string, error) { |
| + if raw == "" { |
| + return "", nil |
| + } |
| + u, err := url.Parse(raw) |
| + if err != nil || !demo.ValidDomain(u.Hostname()) || raw != "https://"+u.Hostname() { |
| + // Never echo the value: a mistaken URL may contain credentials. |
| + return "", errors.New("CONSOLE_DEMO_API_ORIGIN must be a canonical HTTPS DNS origin without a port, credentials, path, query or fragment") |
| + } |
| + return raw, nil |
| +} |
| + |
| +func (s *Server) demoAPIOrigin() string { |
| + if s.cfg.DemoAPIOrigin != "" { |
| + return s.cfg.DemoAPIOrigin |
| + } |
| + return s.cfg.Origin |
| +} |
| + |
| +// Configured demo traffic cannot use login's unsigned rollout window or |
| +// fall back to a shared proxy IP during key rotation. Refuse before budgets. |
| +func (s *Server) requireDemoAPIProof(w http.ResponseWriter, r *http.Request) bool { |
| + if s.cfg.DemoAPIOrigin == "" { |
| + return true |
| + } |
| + peer, _, err := net.SplitHostPort(r.RemoteAddr) |
| + if err != nil { |
| + peer = r.RemoteAddr |
| + } |
| + if !s.trustsProxy(peer) { |
| + return true // clientIP ignores forwarded headers from this peer. |
| + } |
| + xff, proofs := r.Header.Values("X-Forwarded-For"), r.Header.Values(edgeproof.Header) |
| + // A local caller can choose Host and replay a proof it received at its |
| + // own app. Require the console host before trusting that proof here. |
| + origin, err := url.Parse(s.cfg.Origin) |
| + if err == nil && origin.Host != "" && normalizeHost(r.Host) == normalizeHost(origin.Host) && len(xff) == 1 && len(proofs) == 1 { |
| + if ip, err := demo.CanonicalIP(xff[0]); err == nil && ip == xff[0] { |
| + current, next := s.edgeProofKeys(r.Context()) |
| + if edgeproof.Verify(current, next, r.Host, xff[0], proofs[0], time.Now()) { |
| + return true |
| + } |
| + } |
| + } |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Retry-After", "2") |
| + w.WriteHeader(http.StatusServiceUnavailable) |
| + return false |
| +} |
diff --git a/internal/console/demo_api_origin_test.go b/internal/console/demo_api_origin_test.go| new file mode 100644 |
| index 000000000..5f82be092 |
| --- /dev/null |
| +++ b/internal/console/demo_api_origin_test.go |
| @@ -0,0 +1,318 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "encoding/hex" |
| + "encoding/json" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/demo" |
| + "github.com/carlosframework/platform/internal/edgeproof" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +func TestDemoPublicAPIOrigin(t *testing.T) { |
| + for _, origin := range []string{"", "https://example.com"} { |
| + for _, forged := range []bool{false, true} { |
| + t.Run(origin+"/"+map[bool]string{false: "canonical", true: "forged"}[forged], func(t *testing.T) { |
| + s, _ := demoJobServer(t) |
| + s.cfg.Origin = "https://console.example.com" |
| + s.cfg.DemoAPIOrigin = origin |
| + r := httptest.NewRequest("POST", s.cfg.Origin+"/api/demo/apps", bytes.NewReader(demoHTTPSource(t))) |
| + r.RemoteAddr = "192.0.2.1:1234" |
| + r.Header.Set("Content-Type", "application/gzip") |
| + if forged { |
| + r.Host = "forged.example.com" |
| + r.Header.Set("X-Forwarded-Host", "forged.example.com") |
| + } |
| + w := newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 202 { |
| + t.Fatalf("publish status = %d", w.Code) |
| + } |
| + var got map[string]any |
| + if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil { |
| + t.Fatal("invalid publish JSON") |
| + } |
| + want := origin |
| + if want == "" { |
| + want = s.cfg.Origin |
| + } |
| + job, _ := got["jobId"].(string) |
| + token, _ := got["claimToken"].(string) |
| + if len(got) != 7 || job == "" || got["statusUrl"] != want+"/api/demo/jobs/"+job { |
| + t.Error("wrong status URL or response shape") |
| + } |
| + if token == "" || got["claimUrl"] != s.cfg.Origin+"/demo/claim#"+token { |
| + t.Error("browser claim origin or fragment changed") |
| + } |
| + }) |
| + } |
| + } |
| + t.Run("construction", func(t *testing.T) { |
| + st, _ := demoTestStore(t) |
| + for _, raw := range []string{"", "https://example.com", "https://shop.example.com", "https://xn--bcher-kva.example.com"} { |
| + s, err := NewServer(Config{Origin: "https://console.example.com", DemoAPIOrigin: raw}, st) |
| + if err != nil { |
| + t.Fatalf("valid origin rejected: %v", err) |
| + } |
| + want := raw |
| + if want == "" { |
| + want = s.cfg.Origin |
| + } |
| + if s.demoAPIOrigin() != want { |
| + t.Error("origin fallback changed") |
| + } |
| + } |
| + for _, raw := range []string{"http://example.com", "//example.com", "https://example.com/", "https://example.com/path", "https://example.com?", "https://example.com?x=1", "https://example.com#", "https://example.com#x", "https://user:secret@example.com", "https://example.com:443", "https://example.com:", "https://example.com:8443", "https://*.example.com", "https://127.0.0.1", "https://[::1]", "https://EXAMPLE.com", "HTTPS://example.com", "https://example.com.", " https://example.com", "https://example.com\n", "https://-shop.example.com", "https://shop_.example.com", "https://localhost", "https://" + strings.Repeat("a", 64) + ".com"} { |
| + if _, err := NewServer(Config{Origin: "https://console.example.com", DemoAPIOrigin: raw}, st); err == nil { |
| + t.Error("invalid origin accepted") |
| + } else if strings.Contains(err.Error(), "secret") { |
| + t.Error("origin diagnostic leaked credentials") |
| + } |
| + } |
| + }) |
| +} |
| + |
| +func TestDemoAPIProofRequired(t *testing.T) { |
| + current := []byte(strings.Repeat("a", 32)) |
| + next := []byte(strings.Repeat("b", 32)) |
| + for _, seen := range []bool{false, true} { |
| + t.Run(map[bool]string{false: "before-latch", true: "after-latch"}[seen], func(t *testing.T) { |
| + s := demoTestServer(t) |
| + s.cfg.DemoAPIOrigin = "https://example.com" |
| + s.cfg.Origin = "https://console.example.com" |
| + s.cfg.EdgeIPs = []string{"198.51.100.9"} |
| + s.edgeProof.loaded.Store(true) |
| + s.edgeProof.seen.Store(seen) |
| + for object, key := range map[string][]byte{edgeproof.MeshKeyObject: current, edgeproof.NextMeshKeyObject: next} { |
| + if _, err := s.cfg.Releases.Put(t.Context(), object, []byte(hex.EncodeToString(key)), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + for _, peer := range []string{"127.0.0.1:1234", "[::1]:1234", "198.51.100.9:1234"} { |
| + for _, bad := range []string{"missing", "duplicate", "invalid", "rotation-mismatch", "wrong-host", "replayed-app-host", "expired", "missing-xff", "duplicate-xff", "chain", "whitespace", "noncanonical", "zone"} { |
| + for _, path := range []string{"/api/demo/apps", "/api/demo/jobs/" + strings.Repeat("A", 43)} { |
| + body := &demoUnreadBody{} |
| + method := "GET" |
| + if path == "/api/demo/apps" { |
| + method = "POST" |
| + } |
| + r := httptest.NewRequest(method, "https://console.example.com"+path, body) |
| + r.RemoteAddr = peer |
| + xff := "192.0.2.1" |
| + switch bad { |
| + case "missing-xff": |
| + xff = "" |
| + case "chain": |
| + xff = "192.0.2.2, 192.0.2.1" |
| + case "whitespace": |
| + xff = " 192.0.2.1" |
| + case "noncanonical": |
| + xff = "2001:0db8::1" |
| + case "zone": |
| + xff = "fe80::1%eth0" |
| + } |
| + r.Header.Set("X-Forwarded-For", xff) |
| + proof := edgeproof.Sign(current, r.Host, xff, time.Now()) |
| + switch bad { |
| + case "missing": |
| + proof = "" |
| + case "invalid": |
| + proof = "invalid" |
| + case "rotation-mismatch": |
| + proof = edgeproof.Sign([]byte(strings.Repeat("c", 32)), r.Host, xff, time.Now()) |
| + case "wrong-host": |
| + proof = edgeproof.Sign(current, "shop.example.com", xff, time.Now()) |
| + case "replayed-app-host": |
| + r.Host = "shop.example.com" |
| + proof = edgeproof.Sign(current, r.Host, xff, time.Now()) |
| + case "expired": |
| + proof = edgeproof.Sign(current, r.Host, xff, time.Now().Add(-2*edgeproof.Skew)) |
| + } |
| + if proof != "" { |
| + r.Header.Set(edgeproof.Header, proof) |
| + } |
| + if bad == "duplicate" { |
| + r.Header.Add(edgeproof.Header, proof) |
| + } |
| + if bad == "duplicate-xff" { |
| + r.Header.Add("X-Forwarded-For", xff) |
| + } |
| + w := newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 503 || w.Body.Len() != 0 || w.Header().Get("Cache-Control") != "no-store" || w.Header().Get("Retry-After") != "2" || body.read { |
| + t.Errorf("%s %s %s: status=%d body-read=%v", peer, bad, path, w.Code, body.read) |
| + } |
| + } |
| + } |
| + } |
| + var attempts int |
| + if err := s.store.db.QueryRow(`SELECT count(*) FROM demo_admissions`).Scan(&attempts); err != nil { |
| + t.Fatal(err) |
| + } |
| + if attempts != 0 || len(s.demoStatus.entries) != 0 || s.demoStatus.overflow.count != 0 { |
| + t.Fatal("proof refusal spent budget") |
| + } |
| + if s.edgeProof.seen.Load() != seen { |
| + t.Fatal("refused proof changed latch") |
| + } |
| + for _, peer := range []string{"127.0.0.1:1234", "198.51.100.9:1234"} { |
| + for _, key := range [][]byte{current, next} { |
| + for _, ip := range []string{"192.0.2.1", "2001:db8::1"} { |
| + r := httptest.NewRequest("GET", "https://console.example.com/api/demo/jobs/"+strings.Repeat("A", 43), nil) |
| + r.RemoteAddr = peer |
| + r.Header.Set("X-Forwarded-For", ip) |
| + r.Header.Set(edgeproof.Header, edgeproof.Sign(key, r.Host, ip, time.Now())) |
| + w := newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 404 || s.clientIP(r) != ip { |
| + t.Errorf("valid proof status=%d or wrong client IP", w.Code) |
| + } |
| + budget, err := demo.BudgetIP(ip) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if s.demoStatus.entries[budget].count == 0 { |
| + t.Fatal("status did not debit verified client") |
| + } |
| + r.Method = "POST" |
| + r.URL.Path = "/api/demo/apps" |
| + r.Body = http.NoBody |
| + r.Header.Set("Authorization", "invalid") |
| + w = newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 401 { |
| + t.Errorf("valid publish proof status=%d, want 401", w.Code) |
| + } |
| + } |
| + } |
| + } |
| + }) |
| + } |
| + for _, origin := range []string{"", "https://example.com"} { |
| + t.Run("peer-"+origin, func(t *testing.T) { |
| + s := demoTestServer(t) |
| + s.cfg.DemoAPIOrigin = origin |
| + r := httptest.NewRequest("GET", "https://console.example.com/api/demo/jobs/"+strings.Repeat("A", 43), nil) |
| + r.RemoteAddr = "192.0.2.9:1234" |
| + r.Header.Set("X-Forwarded-For", "192.0.2.100") |
| + r.Header.Set(edgeproof.Header, "forged") |
| + w := newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 404 || s.clientIP(r) != "192.0.2.9" { |
| + t.Fatal("untrusted peer used forwarding headers") |
| + } |
| + if origin == "" { |
| + r.RemoteAddr = "127.0.0.1:1234" |
| + w = newDemoRecorder() |
| + s.mux.ServeHTTP(w, r) |
| + if w.Code != 404 || s.clientIP(r) != "192.0.2.100" { |
| + t.Fatal("unconfigured legacy forwarding changed") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDemoAPIHostOwnership(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + s := fx.srv |
| + s.cfg.DemoAPIOrigin = "https://example.com" |
| + now := time.Now() |
| + if err := fx.st.CreateAccount(42, "shop", "shop", "owner@example.com", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := fx.st.CreateAppIn(42, "shop", "owner@example.com", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := fx.st.AddMember(42, "member@example.com", RoleMember, now); err != nil { |
| + t.Fatal(err) |
| + } |
| + s.cfg.SystemOperators = []string{"owner@example.com", "outside@example.com"} |
| + owner := cliToken(t, fx, "owner@example.com", "demo-owner") |
| + member := cliToken(t, fx, "member@example.com", "demo-member") |
| + outsider := cliToken(t, fx, "outside@example.com", "demo-outside") |
| + service, err := fx.st.NewAppToken(42, "shop", "owner@example.com", "signup", now) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + reg, err := registry.Open(fx.regPath) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, host := range []string{"shop.example.net", "two.example.net"} { |
| + if err := reg.Upsert(registry.Route{Host: host, Account: "shop", App: "shop", Channel: "stable", Addr: "127.0.0.1:12345"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + reg.Close() |
| + base := domainsURL(fx, "shop", "shop") |
| + for _, token := range []string{member, service} { |
| + for _, body := range []string{attachBody("example.com", "shop.example.net"), platformAttachBody("example.com", "shop.example.net")} { |
| + code, _, _ := rawReq(t, "POST", base, token, body) |
| + if code != 400 && code != 403 { |
| + t.Errorf("member/service attach status=%d", code) |
| + } |
| + } |
| + } |
| + claimAbsent(t, fx, "example.com") |
| + for _, host := range []string{"console.example.com", "hub.example.com"} { |
| + s.cfg.Origin = "https://console.example.com" |
| + s.cfg.TunnelHost = "hub.example.com" |
| + s.cfg.DemoAPIOrigin = "https://" + host |
| + if s.domainHostPolicy(host, "shop") != hostReserved { |
| + t.Error("public origin overrode reserved host") |
| + } |
| + } |
| + s.cfg.DemoAPIOrigin = "https://example.com" |
| + if s.domainHostPolicy("child.example.com", "shop") != hostOpen { |
| + t.Error("public host reserved unrelated child") |
| + } |
| + if code, _, _ := rawReq(t, "POST", base, outsider, platformAttachBody("example.com", "shop.example.net")); code != 404 { |
| + t.Errorf("nonmember operator status=%d", code) |
| + } |
| + if code, _, _ := rawReq(t, "POST", base, owner, platformAttachBody("example.com", "shop.example.net")); code != 200 { |
| + t.Fatalf("operator attach status=%d", code) |
| + } |
| + operations := []struct{ method, url, body string }{ |
| + {"POST", base, platformAttachBody("example.com", "two.example.net")}, |
| + {"PUT", pathsURL(fx, "shop", "shop", "example.com"), `{"paths":{"admin":"shop.example.net"}}`}, |
| + {"DELETE", base + "/example.com", ""}, |
| + } |
| + for _, op := range operations { |
| + for _, token := range []string{member, service, outsider} { |
| + code, _, _ := rawReq(t, op.method, op.url, token, op.body) |
| + want := 403 |
| + if token == outsider { |
| + want = 404 |
| + } |
| + if code != want { |
| + t.Errorf("unauthorized %s status=%d want=%d", op.method, code, want) |
| + } |
| + } |
| + } |
| + c := claimOf(t, fx, "example.com") |
| + if c.Route != "shop.example.net" || len(c.Paths) != 0 { |
| + t.Fatal("refused write changed claim") |
| + } |
| + for _, op := range operations { |
| + if code, _, _ := rawReq(t, op.method, op.url, owner, op.body); code != 200 { |
| + t.Errorf("operator %s status=%d", op.method, code) |
| + } |
| + } |
| + claimAbsent(t, fx, "example.com") |
| + for _, token := range []string{member, service} { |
| + if code, _, _ := rawReq(t, "POST", base, token, attachBody("other.example.com", "shop.example.net")); code != 200 { |
| + t.Errorf("unrelated host status=%d", code) |
| + } |
| + } |
| + s.cfg.DemoAPIOrigin = "" |
| + if s.domainHostPolicy("example.com", "shop") != hostOpen { |
| + t.Error("unset retained reservation") |
| + } |
| +} |
diff --git a/internal/console/domainpolicy.go b/internal/console/domainpolicy.go| index 2137ca3c7..b0bf8e69f 100644 |
| --- a/internal/console/domainpolicy.go |
| +++ b/internal/console/domainpolicy.go |
| @@ -92,6 +92,9 @@ func (s *Server) domainHostPolicy(host, account string) hostPolicy { |
| if domains.HostDenied(host, s.reservedDomains(allowed)) { |
| return hostReserved |
| } |
| + if s.cfg.DemoAPIOrigin != "" && host == strings.TrimPrefix(s.cfg.DemoAPIOrigin, "https://") { |
| + return hostPlatform |
| + } |
| if domains.HostDenied(host, s.platformDomains(allowed)) { |
| return hostPlatform |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index 14a9054da..092fc94bb 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -563,10 +563,11 @@ type Config struct { |
| // SeedData is the home region's data bucket, where seeds/ lives (the |
| // bucket HibernateBucket names, at its root). nil: the seed doors |
| // answer 503. |
| - SeedData release.Store |
| - DBVersions lease.VersionedStore |
| - Origin string // the console's public origin — the OAuth client_id |
| - Keymail string // keymail base URL |
| + SeedData release.Store |
| + DBVersions lease.VersionedStore |
| + Origin string // the console's public origin — the OAuth client_id |
| + DemoAPIOrigin string // optional public site origin for agent demo API links |
| + Keymail string // keymail base URL |
| // Registry is the path to the platform registry DB. Read-mostly (routes, |
| // domains, alerts), but fleets.go's fleet/box/placement doors (customer |
| // fleets plan, Task 7) genuinely write through it via openRegistry |
| @@ -1747,6 +1748,11 @@ func normalizeDelegationZone(raw string) string { |
| // NewServer wires a server over an opened Store, loading (or minting) the |
| // console's Keymail signing key. |
| func NewServer(cfg Config, st *Store) (*Server, error) { |
| + demoAPIOrigin, err := validateDemoAPIOrigin(cfg.DemoAPIOrigin) |
| + if err != nil { |
| + return nil, err |
| + } |
| + cfg.DemoAPIOrigin = demoAPIOrigin |
| if err := validateDemoConfig(cfg, st); err != nil { |
| return nil, err |
| } |