carlos / platform Public

console: keep a claimed demo's source; Download source; Keep going

Paul's approved change (2026-11-07). At claim time the source archive of
the serving demo version is copied (create-only, one GET + one PUT) to
apps/<account>/<app>/source/claims/<op>/; the claim aborts without it.
Owners and members fetch it from Download source or carlos apps source
pull (audited first, rate-limited, no-store; same 404 for non-members,
401 without sign-in). Kept until permanent purge; later deploys never
replace it. The done page gets two Keep going paths and the three CLI
steps, shown only to the claiming browser or a member. Opus security
review: blocked, fixed, approved; census approved on #280.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from claim-source into main.
Co-Authored-By: claude <claude~paul@keymail.dev>
codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 326d4677f01751145c2761b1790efa42811a39cc parent b389c34
46 files changed, +2,863 −76
  • apps.go +4 −0
  • apps_source.go +141 −0
  • apps_source_e2e_test.go +269 −0
  • apps_source_test.go +178 −0
  • docs/site/cli.md +9 −0
  • docs/superpowers/notes/census-proposal-claim-source.md +17 −0
  • docs/superpowers/specs/2026-11-07-claimed-app-source-design.md +260 −0
  • docs/superpowers/specs/LUNA-COPY-BRIEF-CLAIM-SOURCE.md +7 −0
  • docs/superpowers/specs/LUNA-COPY-RESULT-CLAIM-SOURCE.md +33 −0
  • docs/superpowers/specs/LUNA-COPY-RESULT-COUNTDOWN.md +2 −1
  • internal/console/app_source.go +289 −0
  • internal/console/app_source_browser_test.go +131 −0
  • internal/console/app_source_test.go +932 −0
  • internal/console/appsettings.go +5 −0
  • internal/console/authcli.go +6 −1
  • internal/console/claim_invariant_fixtures_test.go +2 −0
  • internal/console/claim_invariant_source_test.go +64 −0
  • internal/console/demo_claim_browser_test.go +1 −1
  • internal/console/demo_claim_csp_test.go +3 −4
  • internal/console/demo_claim_kept_test.go +63 −2
  • internal/console/demo_claim_moved_test.go +1 −1
  • internal/console/demo_claim_page.go +37 −1
  • internal/console/demo_claim_resume_browser_test.go +3 −0
  • internal/console/demo_claim_store.go +8 −3
  • internal/console/demo_claim_target.go +2 −0
  • internal/console/demo_claim_transfer.go +60 −10
  • internal/console/demo_claim_transfer_test.go +13 −0
  • internal/console/demo_claim_ux_test.go +1 −1
  • internal/console/demo_jobs_test.go +10 −2
  • internal/console/server.go +7 −1
  • internal/console/static/demo_claim.js +30 −16
  • internal/console/store.go +13 −2
  • internal/console/svcroutes_test.go +21 −9
  • internal/console/templates/app_overview.html +2 −0
  • internal/console/templates/demo_claim.html +9 −6
  • internal/console/testdata/app_source_browser.mjs +83 −0
  • internal/console/testdata/claim-routes.txt +2 −0
  • internal/console/testdata/demo_claim_browser.mjs +1 −1
  • internal/console/testdata/demo_claim_resume_browser.mjs +11 −11
  • internal/console/testdata/perf-budgets.txt +1 −0
  • internal/demobuild/source.go +15 −2
  • internal/demobuild/source_test.go +74 −0
  • internal/provision/claim_source_census_test.go +30 −0
  • internal/provision/plan9_b8_census_test.go +1 −1
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-claim-source.tsv +11 −0

CI passed — run details

diff --git a/apps.go b/apps.go
index f2412ddf0..38fd37be6 100644
--- a/apps.go
+++ b/apps.go
@@ -36,6 +36,8 @@ import (
const appsUsage = `usage: carlos apps <create|place|build-probe|set|show|delete|restore|ttl|keep|list> [flags] <app>
+ source pull --app <app> [--account <name-or-sqid> | --account-id <sqid>] --console <origin> [--output <path>]
+
create --app <name> [flags] claim a new app name in an account, through
the console API — the same claim the console's New app
form makes, so a name the form would refuse is refused
@@ -152,6 +154,8 @@ func RunApps(args []string) {
os.Exit(1)
}
switch args[0] {
+ case "source":
+ runAppsSource(args[1:])
case "create":
runAppsCreate(args[1:])
case "place":
diff --git a/apps_source.go b/apps_source.go
new file mode 100644
index 000000000..14e797d53
--- /dev/null
+++ b/apps_source.go
@@ -0,0 +1,141 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+)
+
+const sourceIntegrity = "Source failed integrity or size checks. Nothing was saved."
+const sourceTemporary = "Source download is temporarily unavailable. Try again."
+const sourceExists = "Output already exists. Choose another `--output` path."
+const sourcePullUsage = "carlos apps source pull --app <app> [--account <name-or-sqid> | --account-id <sqid>] --console <origin> [--output <path>]"
+
+func runAppsSource(args []string) {
+ if len(args) == 0 || args[0] != "pull" {
+ log.Fatal(sourcePullUsage)
+ }
+ fs := flag.NewFlagSet("apps source pull", flag.ExitOnError)
+ app := appFlag(fs, "app name")
+ account := fs.String("account", "", "account (sqid or name)")
+ accountID := fs.String("account-id", "", "account sqid")
+ console := consoleOption(fs, "console origin")
+ output := fs.String("output", "", "<path>")
+ fs.Usage = flagUsage(fs, sourcePullUsage)
+ fs.Parse(args[1:])
+ if fs.NArg() != 0 || strings.TrimSpace(*app) == "" {
+ log.Fatal(sourcePullUsage)
+ }
+ if err := validAppName(*app); err != nil {
+ log.Fatal(err)
+ }
+ sess, err := resolveMode(*console)
+ var missing *notLoggedInError
+ if sess == nil && (err == nil || errors.As(err, &missing) || errors.Is(err, errNoDeploymentTarget)) {
+ origin, originErr := loginConsole(*console)
+ if originErr != nil {
+ log.Fatal(originErr)
+ }
+ log.Fatalf("Sign in with `carlos auth login --console %s`.", origin)
+ }
+ if err != nil {
+ log.Fatal(err)
+ }
+ acct := resolvedAccount(sess, account, accountID)
+ if *output == "" {
+ *output = *app + "-source.tar.gz"
+ }
+ at, err := pullAppSource(context.Background(), sess.c, apiPath(acct, *app, "/source"), *output)
+ if err != nil {
+ log.Fatal(err)
+ }
+ fmt.Fprintf(stdout, "Saved claimed-at source to %s (%s)\n", *output, at)
+}
+
+func pullAppSource(ctx context.Context, c *consoleClient, path, output string) (string, error) {
+ ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
+ defer cancel()
+ if _, err := os.Lstat(output); err == nil {
+ return "", errors.New(sourceExists)
+ } else if !errors.Is(err, os.ErrNotExist) {
+ return "", errors.New(sourceTemporary)
+ }
+ f, err := os.CreateTemp(filepath.Dir(output), ".carlos-source-*")
+ if err != nil {
+ return "", errors.New(sourceTemporary)
+ }
+ defer func() {
+ _ = f.Close()
+ _ = os.Remove(f.Name())
+ }()
+ req, err := http.NewRequestWithContext(ctx, "GET", c.base+path, nil)
+ if err != nil {
+ return "", errors.New(sourceTemporary)
+ }
+ req.Header.Set("Authorization", "Bearer "+c.token)
+ req.Header.Set("Accept-Encoding", "identity")
+ client := &http.Client{Timeout: 30 * time.Second, CheckRedirect: neverFollow, Transport: c.transport()}
+ res, err := client.Do(req)
+ if err != nil {
+ return "", errors.New(sourceTemporary)
+ }
+ defer res.Body.Close()
+ switch res.StatusCode {
+ case 200:
+ case 401:
+ return "", fmt.Errorf("Sign in with `carlos auth login --console %s`.", c.base)
+ case 404: // The authenticated missing-snapshot refusal is distinct from the opaque gate.
+ b, _ := io.ReadAll(io.LimitReader(res.Body, 1024))
+ if strings.TrimSpace(string(b)) == "No saved source for this app." {
+ return "", errors.New("No saved source for this app.")
+ }
+ return "", errMembershipNotFound
+ case 429:
+ return "", errors.New("Too many source downloads. Try again in a minute.")
+ default:
+ return "", errors.New(sourceTemporary)
+ }
+ if res.ContentLength <= 0 || res.ContentLength > demo.SourceMaxBytes || res.Header.Get("Content-Encoding") != "" || res.Header.Get("Content-Type") != "application/gzip" {
+ return "", errors.New(sourceIntegrity)
+ }
+ b, err := io.ReadAll(io.LimitReader(res.Body, demo.SourceMaxBytes+1))
+ if err != nil || int64(len(b)) != res.ContentLength {
+ return "", errors.New(sourceIntegrity)
+ }
+ src, err := demobuild.ValidateArchive(bytes.NewReader(b))
+ if err != nil || src.SHA256 != res.Header.Get("X-Carlos-Source-SHA256") {
+ return "", errors.New(sourceIntegrity)
+ }
+ at, err := time.Parse(time.RFC3339, res.Header.Get("X-Carlos-Source-Claimed-At"))
+ if err != nil {
+ return "", errors.New(sourceIntegrity)
+ }
+ if _, err = f.Write(b); err != nil {
+ return "", errors.New(sourceTemporary)
+ }
+ if err = f.Close(); err != nil {
+ return "", errors.New(sourceTemporary)
+ }
+ if err = ctx.Err(); err != nil {
+ return "", errors.New(sourceTemporary)
+ }
+ if err = os.Link(f.Name(), output); err != nil {
+ if errors.Is(err, os.ErrExist) {
+ return "", errors.New(sourceExists)
+ }
+ return "", errors.New(sourceTemporary)
+ }
+ return at.UTC().Format(time.RFC3339), nil
+}
diff --git a/apps_source_e2e_test.go b/apps_source_e2e_test.go
new file mode 100644
index 000000000..e46ec6315
--- /dev/null
+++ b/apps_source_e2e_test.go
@@ -0,0 +1,269 @@
+package main
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/ed25519"
+ "crypto/rand"
+ "crypto/sha256"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "database/sql"
+ "encoding/hex"
+ "encoding/json"
+ "encoding/pem"
+ "fmt"
+ "io"
+ "math/big"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/console"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/provision"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestAppsSourceThreeSteps(t *testing.T) {
+ bin := buildCarlos(t)
+ dir := t.TempDir()
+ ctx, cancel := context.WithTimeout(t.Context(), 3*time.Minute)
+ defer cancel()
+ const app = "kept"
+ const account = "bab"
+ const person = "source@example.com"
+ const host = "kept.bab.oncarlos.test"
+ store := release.NewDirStore(filepath.Join(dir, "store"))
+ public, key, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ dbpath := filepath.Join(dir, "console.db")
+ st, err := console.Open(dbpath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer st.Close()
+ if err = st.AddMember(console.OpsAccountID, person, console.RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = st.CreateAppIn(console.OpsAccountID, app, person, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ var archive bytes.Buffer
+ gz := gzip.NewWriter(&archive)
+ tw := tar.NewWriter(gz)
+ for _, file := range [][2]string{{"go.mod", "module demo.local/app\n\ngo 1.22\n"}, {"main.go", "package main\nfunc main() {}\n"}} {
+ if err = tw.WriteHeader(&tar.Header{Name: file[0], Size: int64(len(file[1])), Mode: 0600}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = io.WriteString(tw, file[1]); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err = tw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if err = gz.Close(); err != nil {
+ t.Fatal(err)
+ }
+ op, _ := demobuild.NewJobID()
+ job, _ := demobuild.NewJobID()
+ sum := sha256.Sum256(archive.Bytes())
+ sourceKey := "apps/" + account + "/" + app + "/source/claims/" + op + "/source.tar.gz"
+ if _, err = store.Put(ctx, sourceKey, archive.Bytes(), ""); err != nil {
+ t.Fatal(err)
+ }
+ db, err := sql.Open("sqlite", dbpath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var lifetime string
+ if err = db.QueryRow(`SELECT lifetime FROM apps WHERE account_id=? AND app=?`, console.OpsAccountID, app).Scan(&lifetime); err != nil {
+ t.Fatal(err)
+ }
+ descriptor, _ := json.Marshal(map[string]any{"schema": 1, "operation": op, "lifetime": lifetime, "job": job, "sha256": hex.EncodeToString(sum[:]), "bytes": archive.Len(), "version": "v0.0.0-demo.1", "claimed_at": time.Now().UTC().Truncate(time.Second)})
+ if _, err = db.Exec(`UPDATE apps SET claimed_source=? WHERE account_id=? AND app=?`, string(descriptor), console.OpsAccountID, app); err != nil {
+ t.Fatal(err)
+ }
+ db.Close()
+ if _, err = release.SetPipeline(ctx, store, key, account, app, release.DefaultPipelineChannels(), person); err != nil {
+ t.Fatal(err)
+ }
+ manifest := provision.Manifest{Schema: 1, App: app, Domain: account + ".oncarlos.test", Channel: "edge"}
+ if err = provision.PutManifestIfMatch(ctx, store, account, app, manifest, ""); err != nil {
+ t.Fatal(err)
+ }
+ if err = provision.CreateRecord(ctx, store, provision.Record{Host: host, App: app, Account: account, Channel: "edge", CreatedAt: time.Now().UTC(), Region: "eu-west-1"}); err != nil {
+ t.Fatal(err)
+ }
+ var srv *console.Server
+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/auth/cli/start" {
+ rec := httptest.NewRecorder()
+ srv.ServeHTTP(rec, r)
+ var start struct {
+ UserCode string `json:"user_code"`
+ }
+ if err := json.Unmarshal(rec.Body.Bytes(), &start); err != nil {
+ t.Error(err)
+ }
+ if err := st.ApproveCLIAuth(start.UserCode, person, time.Now()); err != nil {
+ t.Error(err)
+ }
+ for k, vs := range rec.Header() {
+ w.Header()[k] = vs
+ }
+ w.WriteHeader(rec.Code)
+ _, _ = w.Write(rec.Body.Bytes())
+ return
+ }
+ srv.ServeHTTP(w, r)
+ }))
+ defer api.Close()
+ srv, err = console.NewServer(console.Config{Origin: api.URL, Keymail: "http://keymail.invalid", Registry: filepath.Join(dir, "registry.db"), Releases: store, ReleasePub: public, Key: key, AppScheme: "http", AppsDomain: "oncarlos.test"}, st)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, token := range []string{"", "expired-token"} {
+ out := filepath.Join(dir, "unsigned-source.tar.gz")
+ _, err := pullAppSource(ctx, newConsoleClient(api.URL, token), "/api/cli/apps/"+account+"/"+app+"/source?exact=sqid", out)
+ if err == nil || err.Error() != "Sign in with `carlos auth login --console "+api.URL+"`." {
+ t.Fatalf("production 401 sign-in branch: %v", err)
+ }
+ if _, err := os.Lstat(out); !os.IsNotExist(err) {
+ t.Fatal("unsigned output created", err)
+ }
+ }
+ // Route only the fixture hostname through loopback TLS; the subprocess
+ // still exercises its ordinary HTTPS deploy watch without DNS changes.
+ proxy, ca := sourceLoopbackEdge(t, host, func(w http.ResponseWriter, r *http.Request) {
+ ptr, err := release.Channel(r.Context(), store, public, account, app, "edge")
+ if err != nil || ptr == nil {
+ http.Error(w, "not ready", 503)
+ return
+ }
+ w.Header().Set("X-Carlos-Version", ptr.Version)
+ w.WriteHeader(200)
+ })
+ creds := filepath.Join(dir, "credentials")
+ env := carlosTestEnv(t, "CARLOS_CREDENTIALS="+creds, "CARLOS_DEPLOYMENT_BUCKET=", "CARLOS_DEPLOYMENT_DIR=", "HTTPS_PROXY="+proxy, "HTTP_PROXY="+proxy, "NO_PROXY=127.0.0.1,localhost", "SSL_CERT_FILE="+ca)
+ run := func(cwd string, args ...string) string {
+ t.Helper()
+ cmd := exec.CommandContext(ctx, bin, args...)
+ cmd.Env = env
+ cmd.Dir = cwd
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("%v: %v\n%s", args, err, out)
+ }
+ return string(out)
+ }
+ run(dir, "auth", "login", "--console", api.URL)
+ out := run(dir, "apps", "source", "pull", "--console", api.URL, "--account-id", account, "--app", app)
+ if !strings.Contains(out, "Saved claimed-at source to kept-source.tar.gz") {
+ t.Fatal(out)
+ }
+ project := filepath.Join(dir, app)
+ if err = os.Mkdir(project, 0700); err != nil {
+ t.Fatal(err)
+ }
+ unpack := exec.CommandContext(ctx, "tar", "--no-same-owner", "--no-same-permissions", "-xzf", app+"-source.tar.gz", "-C", app)
+ unpack.Dir = dir
+ if out, err := unpack.CombinedOutput(); err != nil {
+ t.Fatalf("tar %v %s", err, out)
+ }
+ build := exec.CommandContext(ctx, "go", "build", "-trimpath", "-buildvcs=false", "-o", "app", ".")
+ build.Dir = project
+ build.Env = append(os.Environ(), "CGO_ENABLED=0", "GOOS=linux", "GOARCH=arm64", "GOWORK=off")
+ if out, err := build.CombinedOutput(); err != nil {
+ t.Fatalf("build %v %s", err, out)
+ }
+ out = run(project, "deploy", "--console", api.URL, "--account-id", account, "--app", app, "--channel", "edge", "--kind", "binary", "--target", "linux-arm64", "--version", "v1", "--swap", "hold", "--no-assets", "./app")
+ if !strings.Contains(out, "live https://"+host) {
+ t.Fatal(out)
+ }
+ m, err := release.GetManifest(ctx, store, account, app, "v1")
+ if err != nil {
+ t.Fatal(err)
+ }
+ built, err := os.ReadFile(filepath.Join(project, "app"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ builtSum := sha256.Sum256(built)
+ if m.Artifacts["linux-arm64"].SHA256 != hex.EncodeToString(builtSum[:]) {
+ t.Fatal("deployed wrong binary")
+ }
+ saved, _, err := store.Get(ctx, sourceKey)
+ if err != nil || !bytes.Equal(saved, archive.Bytes()) {
+ t.Fatal("deploy changed snapshot", err)
+ }
+}
+
+func sourceLoopbackEdge(t *testing.T, host string, h http.HandlerFunc) (string, string) {
+ t.Helper()
+ pub, key, err := ed25519.GenerateKey(rand.Reader)
+ if err != nil {
+ t.Fatal(err)
+ }
+ cert := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: host}, DNSNames: []string{host}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, IsCA: true, BasicConstraintsValid: true}
+ der, err := x509.CreateCertificate(rand.Reader, cert, cert, pub, key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ private, err := x509.MarshalPKCS8PrivateKey(key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ pemCert := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
+ pair, err := tls.X509KeyPair(pemCert, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: private}))
+ if err != nil {
+ t.Fatal(err)
+ }
+ ca := filepath.Join(t.TempDir(), "ca.pem")
+ if err = os.WriteFile(ca, pemCert, 0600); err != nil {
+ t.Fatal(err)
+ }
+ edge := httptest.NewUnstartedServer(h)
+ edge.TLS = &tls.Config{Certificates: []tls.Certificate{pair}}
+ edge.StartTLS()
+ t.Cleanup(edge.Close)
+ proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != "CONNECT" || r.Host != host+":443" {
+ http.Error(w, "refused", 403)
+ return
+ }
+ upstream, err := net.Dial("tcp", edge.Listener.Addr().String())
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ defer upstream.Close()
+ client, rw, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ defer client.Close()
+ _, _ = fmt.Fprint(rw, "HTTP/1.1 200 Connection Established\r\n\r\n")
+ _ = rw.Flush()
+ done := make(chan struct{})
+ go func() { _, _ = io.Copy(upstream, rw); close(done) }()
+ _, _ = io.Copy(client, upstream)
+ client.Close()
+ <-done
+ }))
+ t.Cleanup(proxy.Close)
+ return proxy.URL, ca
+}
diff --git a/apps_source_test.go b/apps_source_test.go
new file mode 100644
index 000000000..a8e48923b
--- /dev/null
+++ b/apps_source_test.go
@@ -0,0 +1,178 @@
+package main
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func sourceCLIArchive(t *testing.T) []byte {
+ t.Helper()
+ var b bytes.Buffer
+ gz := gzip.NewWriter(&b)
+ tw := tar.NewWriter(gz)
+ body := []byte("package main\nfunc main() {}\n")
+ if err := tw.WriteHeader(&tar.Header{Name: "main.go", Mode: 0600, Size: int64(len(body))}); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := tw.Write(body); err != nil {
+ t.Fatal(err)
+ }
+ if err := tw.Close(); err != nil {
+ t.Fatal(err)
+ }
+ if err := gz.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return b.Bytes()
+}
+func TestAppsSourcePull(t *testing.T) {
+ b := sourceCLIArchive(t)
+ sum := sha256.Sum256(b)
+ for _, mode := range []string{"ok", "digest", "length", "oversize", "archive", "timestamp", "encoding", "redirect", "truncated", "exists", "symlink", "unauthorized", "cancel", "racing-output"} {
+ t.Run(mode, func(t *testing.T) {
+ targetCalls := 0
+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { targetCalls++; t.Error("cross-origin redirect followed") }))
+ defer target.Close()
+ requests := 0
+ dir := t.TempDir()
+ out := filepath.Join(dir, "source.tar.gz")
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ requests++
+ if _, err := os.Lstat(out); !os.IsNotExist(err) {
+ t.Error("output visible before verification", err)
+ }
+ if mode == "unauthorized" {
+ http.Error(w, "not signed in", 401)
+ return
+ }
+ if mode == "cancel" {
+ cancel()
+ return
+ }
+ if mode == "racing-output" {
+ if err := os.WriteFile(out, []byte("keep"), 0600); err != nil {
+ t.Error(err)
+ }
+ }
+ if r.URL.Path != "/api/cli/apps/account/demo/source" || r.Header.Get("Authorization") != "Bearer local-token" {
+ t.Error("wrong request")
+ }
+ if mode == "redirect" {
+ http.Redirect(w, r, target.URL, 302)
+ return
+ }
+ w.Header().Set("Content-Type", "application/gzip")
+ w.Header().Set("Content-Length", fmt.Sprint(len(b)))
+ w.Header().Set("X-Carlos-Source-SHA256", hex.EncodeToString(sum[:]))
+ w.Header().Set("X-Carlos-Source-Claimed-At", "2026-11-07T12:00:00Z")
+ switch mode {
+ case "digest":
+ w.Header().Set("X-Carlos-Source-SHA256", strings.Repeat("0", 64))
+ case "length":
+ w.Header().Set("Content-Length", fmt.Sprint(len(b)+1))
+ case "oversize":
+ w.Header().Set("Content-Length", "5000001")
+ case "timestamp":
+ w.Header().Set("X-Carlos-Source-Claimed-At", "bad")
+ case "encoding":
+ w.Header().Set("Content-Encoding", "gzip")
+ case "archive":
+ bad := bytes.Repeat([]byte("x"), len(b))
+ h := sha256.Sum256(bad)
+ w.Header().Set("X-Carlos-Source-SHA256", hex.EncodeToString(h[:]))
+ _, _ = w.Write(bad)
+ return
+ case "truncated":
+ _, _ = w.Write(b[:len(b)/2])
+ return
+ }
+ _, _ = w.Write(b)
+ }))
+ defer server.Close()
+ if mode == "exists" {
+ if err := os.WriteFile(out, []byte("keep"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if mode == "symlink" {
+ if err := os.Symlink(filepath.Join(dir, "missing"), out); err != nil {
+ t.Fatal(err)
+ }
+ }
+ at, err := pullAppSource(ctx, newConsoleClient(server.URL, "local-token"), "/api/cli/apps/account/demo/source", out)
+ if mode == "ok" {
+ if err != nil || at != "2026-11-07T12:00:00Z" {
+ t.Fatal(at, err)
+ }
+ got, e := os.ReadFile(out)
+ if e != nil || !bytes.Equal(got, b) {
+ t.Fatal("bytes changed", e)
+ }
+ st, e := os.Stat(out)
+ if e != nil || st.Mode().Perm() != 0600 {
+ t.Fatal("mode", e)
+ }
+ } else {
+ if err == nil {
+ t.Fatal("accepted bad download")
+ }
+ if mode == "unauthorized" && err.Error() != "Sign in with `carlos auth login --console "+server.URL+"`." {
+ t.Fatal("wrong sign-in refusal", err)
+ }
+ if mode == "racing-output" {
+ got, readErr := os.ReadFile(out)
+ if readErr != nil || string(got) != "keep" || err.Error() != sourceExists {
+ t.Fatal("raced output clobbered", string(got), err, readErr)
+ }
+ } else if mode == "exists" || mode == "symlink" {
+ if requests != 0 {
+ t.Fatal("clobber attempted")
+ }
+ } else if _, err := os.Lstat(out); !os.IsNotExist(err) {
+ t.Fatal("partial file survived", err)
+ }
+ }
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, entry := range entries {
+ if entry.Name() != "source.tar.gz" {
+ t.Errorf("temporary file survived: %s", entry.Name())
+ }
+ }
+ if targetCalls != 0 {
+ t.Fatal(targetCalls)
+ }
+ })
+ }
+}
+
+func TestAppsSourceSignInCopy(t *testing.T) {
+ bin := buildCarlos(t)
+ dir := t.TempDir()
+ cmd := exec.Command(bin, "apps", "source", "pull", "--console", "http://127.0.0.1:1", "--account-id", "bab", "--app", "kept")
+ cmd.Dir = dir
+ cmd.Env = carlosTestEnv(t, "CARLOS_DEPLOYMENT_BUCKET=", "CARLOS_DEPLOYMENT_DIR=")
+ out, err := cmd.CombinedOutput()
+ if err == nil || !strings.Contains(string(out), "Sign in with `carlos auth login --console http://127.0.0.1:1`.") {
+ t.Fatalf("%v %s", err, out)
+ }
+ if _, err = os.Stat(filepath.Join(dir, "kept-source.tar.gz")); !os.IsNotExist(err) {
+ t.Fatal("output before sign-in", err)
+ }
+}
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 9804272bd..fd2b2132a 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -3284,3 +3284,12 @@ carlos ops restore-verify
Prints the command list, grouped the way this page is. It goes to stdout and
exits 0, so `carlos help | less` works. A bare `carlos` with no arguments
prints the same text on stderr and exits 2, because that one is a mistake.
+
+## carlos apps source pull
+
+Download the source saved when you kept this app. Later deployments do not update it.
+
+```sh
+carlos apps source pull --console '<console-origin>' --account-id '<sqid>' --app '<app>'
+carlos apps source pull --console '<console-origin>' --account '<name-or-sqid>' --app '<app>' --output '<path>'
+```
diff --git a/docs/superpowers/notes/census-proposal-claim-source.md b/docs/superpowers/notes/census-proposal-claim-source.md
new file mode 100644
index 000000000..800ac2d34
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-claim-source.md
@@ -0,0 +1,17 @@
+# Census approval: claim-source
+
+Ruling `census-ruling-claim-source`. The independent reviewer approves or rejects every change below, 3 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `.`, `internal/demobuild`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `apps_source.go:pullAppSource`: reads +file:CreateTemp, +file:Lstat, +file:ReadAll ×2; written legacy, accepted-legacy, frozen
+- new `internal/demobuild/source.go:validateSource`: reads +file:ReadAll ×3; written legacy, accepted-legacy, frozen
+- quiet `internal/demobuild/source.go:ValidateSource`: reads nothing now; retired while it reads nothing (or its row keeps no sites)
+
+Seal: `160744b3062d0ab9a0cb3c7be3a391ae38cf89ffe410ddd5d179e0c3cb509b66` → `9cdff432a5de2ffeaa147fdafd6a486c61c27a0c38f77466bddc86b149332c7d`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-claim-source.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/specs/2026-11-07-claimed-app-source-design.md b/docs/superpowers/specs/2026-11-07-claimed-app-source-design.md
new file mode 100644
index 000000000..0df119e9a
--- /dev/null
+++ b/docs/superpowers/specs/2026-11-07-claimed-app-source-design.md
@@ -0,0 +1,260 @@
+# Keep source with a claimed app
+
+Proposed design, 2026-11-07. Paul approved preserving and retrieving source;
+the decisions below await controller acceptance and Opus security review.
+Review history: no rounds yet. This change lands as one usable slice: preservation,
+download, CLI and continuation instructions enabled together for new claims.
+
+## Which source
+
+Today `handleDemoPublish`, registered at `POST /api/demo/apps`, accepts
+`application/gzip`, caps compressed input at 5,000,000 bytes and calls
+`demobuild.ValidateSource` (`internal/console/apidemo.go:276`,
+`internal/console/apidemo.go:428`). Validation retains the original archive,
+allows at most 256 files, 2,000,000 bytes per file and 20,000,000 expanded
+file bytes, and separately bounds tar framing (`internal/demobuild/source.go:25`,
+`internal/demobuild/source.go:61`, `internal/demobuild/source.go:187`).
+
+`insertDemoJob` stores it temporarily in SQLite's `demo_job_outbox`;
+`flushDemoOutbox` writes the immutable object at
+`apps/<demo-account>/<demo-app>/demo-build-data/<job-id>/source.tar.gz`, then
+the signed `demo-build/current.json` job and removes the outbox entry
+(`internal/console/demo_jobs.go:83`, `internal/console/demo_jobs.go:144`,
+`internal/console/demo_jobs.go:248`). This uses `Config.Releases`, the
+deployment store: S3 through `CARLOS_DEPLOYMENT_BUCKET`, or a directory through
+`CARLOS_DEPLOYMENT_DIR` (`internal/console/demo_jobs.go:579`,
+`cmd/console/main.go:441`, `cmd/console/main.go:488`, `cmd/console/main.go:933`).
+The worker reads that exact key, validates its digest, and builds under
+`/var/lib/carlos-demo-builds/<job-id>/<attempt>`
+(`internal/host/demo_jobs.go:577`, `internal/demobuild/worker.go:27`,
+`internal/demobuild/worker.go:215`).
+
+**Last accepted means the job for the settled, serving `edge` version.**
+`demoVersion(job)` is `v0.0.0-demo.<generation>`; publication records
+`state='published'` after readiness, while failed publication can roll back
+to an earlier published generation (`internal/console/demo_publish.go:38`,
+`internal/console/demo_publish.go:228`, `internal/console/demo_publish.go:396`,
+`internal/console/demo_publish.go:418`). Extend `pinDemoClaim` to select exactly
+one published job whose `demoVersion` equals its verified channel pointer,
+whose binary digest matches the manifest, and whose demo/account/app/lifetime
+match the source. Persist that job ID and its `SourceSHA256`. Refuse missing
+or ambiguous provenance. Keep its busy/settlement gates
+(`internal/console/demo_claim_transfer.go:220`). Do not select by binary digest
+alone, newest upload, or `demo_apps.source_sha256`: the latter changes at
+enqueue, before success (`internal/console/demo_jobs.go:161`).
+
+Demos expire after 24 hours. Retirement waits for worker and initialization
+cleanup, then purges the demo app prefix; job rows disappear seven days after
+purge (`internal/console/demo_store.go:257`,
+`internal/console/demo_expiry.go:309`, `internal/console/demo_expiry.go:328`,
+`internal/console/demo_store.go:483`). The archive must leave that lifetime.
+
+## Copy before committing the claim
+
+Store the snapshot in the same provider-neutral `release.Store`, at
+`apps/<target-sqid>/<target-app>/source/claims/<claim-op-id>/source.tar.gz`.
+Derive every segment from validated claim records, never a request-supplied key.
+Add an optional, versioned `claimed_source` descriptor to the target **apps
+row**: operation ID, original target lifetime, source job ID, source digest,
+compressed size, serving version and claim timestamp. It is app-owned metadata,
+with no foreign key or lookup dependency on disposable demo rows.
+
+In `advanceDemoClaimLocked`'s **reserved** phase, immediately after pinning and
+before pipeline/seed/binary work or freezing, add `copyDemoClaimSource`.
+The current phase ordering is at `internal/console/demo_claim_transfer.go:109`.
+Persist source identity on the operation and a separate `source_copied` progress
+flag. Stream-read with `release.OpenObjectStreaming`, limited to 5,000,001 bytes;
+check size, SHA-256 and safe archive structure before a create-only `Put`.
+The interface already specifies create-only writes and idempotent deletion
+(`internal/release/store.go:45`, `internal/release/store.go:353`). No AWS API
+belongs in this logic. Normal work is one bounded GET and one PUT; no polling,
+listing or HEAD request is needed. An uncertain PUT may read the destination:
+accept identical bytes, refuse a mismatch, never overwrite it.
+
+**Do not complete a new claim without source.** Retry transient storage failures
+through the existing persisted retry clock, within the original claim deadline;
+missing/corrupt source aborts. This preserves the promise without freezing a demo
+while copying source. Existing abort cleanup removes uncommitted destination
+objects before releasing the app reservation; committed claims cannot abort
+(`internal/console/demo_claim_transfer.go:786`,
+`internal/console/demo_claim_transfer.go:867`,
+`internal/console/demo_claim_transfer.go:896`). Commit must require the pinned
+copy flag and atomically attach the descriptor alongside the current commit
+transaction (`internal/console/demo_claim_transfer.go:650`). Recovery reuses
+the identity and key; a lost progress write cannot select another upload.
+
+Completed snapshots are outside source-demo expiry, retirement and stray sweeps
+(`internal/console/demo_expiry.go:328`, `internal/console/demo_expiry.go:391`).
+Only an aborted, uncommitted claim may remove its destination copy. On rollout,
+uncommitted older operations must establish this prerequisite before proceeding
+or abort safely; already committed legacy claims remain valid with no snapshot.
+Do not invent source or promise backfill after demo purge.
+
+## Download contract and security
+
+Fix these names now:
+
+| Surface | Name |
+| --- | --- |
+| Browser | `GET /a/{sqid}/apps/{app}/source` — **Download source** |
+| CLI API | `GET /api/cli/apps/{account}/{app}/source` |
+| CLI | `carlos apps source pull --app <app> --account <name-or-sqid> --console <origin>` |
+| Start guide | `/start#after-you-keep-it` |
+
+Add the browser route in `server.go` and the API through `cliRoute` in
+`authcli.go`, using `svcrole.Set{}` and `apiPerson` before `apiAccountApp`.
+Those are the existing person-only registration and membership conventions
+(`internal/console/authcli.go:609`, `internal/console/apicli.go:312`,
+`internal/console/apicli.go:228`). Both **owner and member** may download;
+service/app credentials, demo tokens and operators without membership may not.
+Browser authentication follows `accountApp` (`internal/console/server.go:4411`).
+Recheck current membership, live account/app, descriptor ownership and completed
+claim under the lifecycle locks before handing out bytes. A pending claim,
+deleted app, foreign app or guessed ID gives the same non-disclosing 404 on each
+door. Perform these checks before object access; never accept a key, job ID or
+account from query metadata. No public or presigned download URL.
+
+Share one bounded reader between both handlers. Verify the whole archive's size
+and digest before sending bytes, with a 30-second request deadline. Return
+`Content-Type: application/gzip`, validated `Content-Length`,
+`Content-Disposition: attachment; filename="<app>-source.tar.gz"`,
+`Cache-Control: private, no-store`, `X-Content-Type-Options: nosniff`, and
+`X-Carlos-Source-SHA256` and `X-Carlos-Source-Claimed-At` (UTC RFC3339).
+Do not set `Content-Encoding`; no range or conditional
+cache responses. Apply no-store to errors too. Bound downloads to ten per minute
+per person/account/app, and bound concurrent buffering.
+
+Before releasing bytes, require successful `Store.RecordActivity` with action
+`app-source-download`, account, app, actor, UTC time and snapshot identity;
+describe it as a download started, not proof of client receipt. The existing
+audit table carries these fields (`internal/console/store.go:3050`). Use its
+error-returning method directly: `Server.audit` deliberately ignores failures
+(`internal/console/server.go:5265`). Audit failure returns 503 and no source.
+
+Treat archives as untrusted code. Reuse the structural tar checks without
+requiring today's dependency lock: reject traversal, absolute paths, links,
+special files, duplicate paths, oversized expansion and unsupported tar/gzip
+extensions. Existing checks are in `internal/demobuild/source.go:76`,
+`internal/demobuild/source.go:190`, `internal/demobuild/source.go:227`.
+Do not execute, extract or render source in the console. Validation is not
+secret scanning: the submitted bytes already reach storage and the build worker,
+and the validator's file exclusions do not exclude `.env`
+(`internal/console/demo_jobs.go:267`, `internal/host/demo_jobs.go:577`,
+`internal/demobuild/source.go:207`). Claiming additionally transfers the running
+binary and database snapshot (`internal/console/demo_claim_transfer.go:132`,
+`internal/console/demo_claim_transfer.go:182`). Preserve the user's exact source,
+including any embedded secrets, for current account members only; keep it out of
+logs, prompts and telemetry. The build/platform storage operators remain trusted.
+
+## CLI and the fresh-agent handoff
+
+Follow `runAppsCreate`'s API-only flags: `--app`, `--account`, `--account-id`
+(exact sqid, takes precedence), `--console`; no bucket fallback
+(`apps.go:510`). Add optional `--output <path>`, default `<app>-source.tar.gz`.
+Write a mode-0600 file with exclusive creation; refuse existing files/symlinks,
+remove partial output, verify the response digest and cap independently, and
+refuse redirects to another origin. Print the saved path and snapshot timestamp.
+Prefer an archive over automatic extraction: it avoids a new filesystem-write
+surface. Check archive structure before saving; never run its contents.
+
+The three steps below are the fixed contract for both the done-page CLI
+disclosure and the new `/start` section. Substitute shell-quoted app, canonical
+account sqid and console origin; `v1` is an example fresh release label, changed
+for each subsequent deploy. Prerequisites: CLI and Go installed; inspect source,
+including dotfiles/configuration, before building.
+
+```sh
+# 1. Sign in; the person approves the displayed code in their browser.
+carlos auth login --console '<console-origin>'
+
+# 2. Fetch source, then unpack into a new empty directory.
+carlos apps source pull --console '<console-origin>' --account-id '<sqid>' --app '<app>'
+mkdir '<app>'
+tar --no-same-owner --no-same-permissions -xzf '<app>-source.tar.gz' -C '<app>'
+cd '<app>'
+
+# 3. After inspecting and editing, build and deploy to the existing app.
+CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -buildvcs=false -o app .
+carlos deploy --console '<console-origin>' --account-id '<sqid>' --app '<app>' --channel edge --kind binary --target linux-arm64 --version v1 --swap hold --no-assets ./app
+```
+
+Login's browser approval is implemented in `auth.go:700`. The demo entry package
+is `.` and its build target is linux/arm64 with cgo disabled
+(`internal/demobuild/lock.go:128`, `internal/demobuild/runner.go:36`). Deploy
+accepts these flags and an artifact; zero-argument deployment instead requires
+saved configuration or the interactive wizard (`deploy.go:128`, `deploy.go:278`).
+Claim installs the `edge` pipeline and promotes the copied binary there
+(`internal/console/demo_claim_transfer.go:120`,
+`internal/console/demo_claim_transfer.go:408`). No new app, region, host, AWS
+access or server-side source build is required by this continuation path.
+
+Extend `demoClaimPageData` with canonical account identity and use the trusted
+console origin. The done page already has copyable agent and CLI blocks, but the
+CLI text currently contains only login (`internal/console/demo_claim_page.go:36`,
+`internal/console/demo_claim_page.go:129`,
+`internal/console/templates/demo_claim.html:173`). Proposed agent prompt:
+“Continue app `<app>` in account `<name>` (ID `<sqid>`) on console `<origin>`.
+Follow [https://carlosframework.com/start#after-you-keep-it](https://carlosframework.com/start#after-you-keep-it):
+help me sign in, fetch its claimed source, then build and deploy my changes to
+that existing app.” Populate only after success; a claim-status cookie is never
+download authority. Coordinate the anchor with the website controller.
+
+Copy inventory for later Luna review: “Download source”; “Source saved when you
+kept this app; later deployments do not update it”; “Sign in / Fetch source /
+Deploy changes”; the agent prompt above; CLI usage/flag help and saved-file
+confirmation (“Saved claimed-at source to `<path>` (`<timestamp>`)”). Proposed
+refusals: “Sign in with carlos auth login --console `<origin>`”; “No saved source
+for this app”; “Source download is temporarily unavailable. Try again”; “Source
+failed integrity or size checks; nothing was saved”; “Output already exists;
+choose another --output path”; “Too many source downloads; try again in a
+minute”; “This app has saved source; moving it between accounts is not supported
+yet”. Reuse existing generic authorization errors; show the missing-snapshot
+message only after account/app authorization.
+
+## Retention, rollout and proof
+
+Keep the immutable **claimed-at snapshot** until permanent app deletion. Later
+deploys never replace it. Trash disables download but retains it for restore,
+following the existing 30-day cooloff; permanent purge deletes the prefix and
+app-owned descriptor (`internal/release/trash.go:31`,
+`internal/release/trash.go:325`, `internal/console/ownership.go:607`). Account
+deletion already requires zero app rows, including Trash, so it must follow
+those purges (`internal/console/ownership.go:819`). Storage backup/version
+retention follows the deployment's deletion policy; this is not a promise of
+immediate erasure from backups.
+
+Region changes retain the same account/app key; the current default-region
+setter changes only SQLite placement defaults (`internal/console/appregionset.go:3`).
+Renaming shipped apps is already refused (`internal/console/appsettings.go:903`).
+The account move is a route-mismatch repair that moves the console record
+(`internal/console/appsettings.go:1650`, `internal/console/appsettings.go:1735`).
+Explicitly refuse rename/account repair for snapshot-bearing apps under their
+mutation locks; a future transfer must copy and verify into the destination
+account before changing ownership, then remove the old copy. Never leave a
+cross-account pointer.
+
+Build failing tests first through the **production router**, then implement:
+
+- Publish A, reject/roll back B (including equal binary digests), claim, and
+ retrieve A byte-for-byte after demo expiry and metadata purge.
+- Inject missing/oversized/corrupt source, failed GET/PUT, lost PUT acknowledgment,
+ crashes at copy/progress/commit boundaries, expiry and abort. Prove no new
+ source-less committed app, no wrong-job retry and complete abort cleanup.
+- Exercise both routes as owner/member, removed member, stranger, other-account
+ same-name app, operator-only, service credential and demo capability. Check
+ identical unauthorized responses and zero storage reads. Race deletion and
+ membership removal; check headers, audit attribution and audit failure.
+- Test archive attacks, CLI no-clobber/partial cleanup, size limits and redirects;
+ preserve through deploy/Trash/restore/region change, purge before account
+ deletion, and refuse rename/account repair. Count object operations: no listing
+ or idle polling. Run storage tests with directory and local S3-adapter mocks.
+- Verify copied prompt/anchor and all three steps against the built CLI in an
+ isolated local fixture; add the command to `docs/site/cli.md` when implemented.
+
+Controller decisions, with recommendations: accept abort-on-source-failure,
+member-and-owner access, retention through Trash until purge, and refusal of the
+existing account repair for snapshot-bearing apps. Keep legacy claims without
+source honest. Schedule Opus review before implementation lands, covering these
+trust boundaries and retention; stop at the first round with no P1, fix P2s
+without reopening, and carry any P3s forward. No product code, infrastructure
+changes or security-review verdict is part of this design commit.
diff --git a/docs/superpowers/specs/LUNA-COPY-BRIEF-CLAIM-SOURCE.md b/docs/superpowers/specs/LUNA-COPY-BRIEF-CLAIM-SOURCE.md
new file mode 100644
index 000000000..ae6903231
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-BRIEF-CLAIM-SOURCE.md
@@ -0,0 +1,7 @@
+You are the copy-review gate itself. Do NOT run the copy-review skill or start any server. Read only.
+
+Read the design /home/paulca/amadan.net/carlos/platform/.claude/worktrees/claim-source/docs/superpowers/specs/2026-11-07-claimed-app-source-design.md (its "Copy inventory" and "CLI and the fresh-agent handoff" sections), the current done page in /home/paulca/amadan.net/carlos/platform/internal/console/templates/demo_claim.html and demo_claim_copy.go (the "Keep going" block: CLAIM-UX-47..56 in docs/superpowers/specs/LUNA-COPY-RESULT-CLAIM-UX.md), and Paul's request below.
+
+Paul (2026-11-07): "'Keep going' after a claim is wrong without context. A fresh agent has no source code, no idea the demo was kept, and /start leads it to build a new demo. Done page 'Keep going', two clear paths: (i) 'Still in the chat where you built it?' tell your agent you kept it; /start's after-claim section takes over (sign in, deploy to the permanent app). (ii) 'Starting fresh, in a new chat or another agent?' a copyable prompt carrying the context: app name, account, console, and a pointer to a NEW /start section (#after-you-keep-it) that explains sign-in, fetching the source, and deploying changes to the claimed app. (iii) The CLI disclosure gets the same three steps for a person (sign in, fetch source, deploy)." Plus a "Download source" action for the claimed app in the console app page.
+
+Produce a copy deck table ID | surface/state | approved text | note, IDs KEEP-01.. for every human-read string: the Keep going heading (keep or change), path (i) heading + one-line instruction (what to tell the agent; give the exact short line the person pastes or says, e.g. "I kept {app}. It now lives at {address} in my account {account}."), path (ii) heading + explanation + the copyable prompt (start from the design's proposed prompt; it is read by an AI agent but also seen by the person, keep it plain; placeholders {app}, {account}, {sqid}, {console}, and the link https://carlosframework.com/start#after-you-keep-it), the Copy button (reuse shipped "Copy"), the CLI disclosure summary (reuse "Prefer the command line?" or improve) and its three step labels with one short line each (Sign in / Fetch the source / Deploy changes), the note that the source was saved when the app was kept and later deploys don't update it, the console "Download source" button and its one-line description, and the CLI's person-facing messages from the design (saved-file confirmation and refusals). Leave command lines themselves verbatim (they are code). Rules: plain, calm, direct, no em dashes, no exclamation marks, never name a tenant, keep placeholders. Then a short list of choices. No other prose.
diff --git a/docs/superpowers/specs/LUNA-COPY-RESULT-CLAIM-SOURCE.md b/docs/superpowers/specs/LUNA-COPY-RESULT-CLAIM-SOURCE.md
new file mode 100644
index 000000000..356c76f0f
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-RESULT-CLAIM-SOURCE.md
@@ -0,0 +1,33 @@
+| ID | surface/state | approved text | note |
+|---|---|---|---|
+| KEEP-01 | Done page, heading | Keep going | Keep the heading. |
+| KEEP-02 | Done page, path (i) heading | Still in the chat where you built it? | |
+| KEEP-03 | Done page, path (i) instruction | Tell your agent: “I kept {app}. It now lives at {address} in my account {account}.” | Paste or say the sentence to the agent. |
+| KEEP-04 | Done page, path (ii) heading | Starting fresh, in a new chat or with another agent? | |
+| KEEP-05 | Done page, path (ii) explanation | Give your agent this prompt so it can help you sign in, fetch the source, and deploy changes to this app. | |
+| KEEP-06 | Done page, copyable agent prompt | Continue app {app} in account {account} (ID {sqid}) on console {console}. Follow https://carlosframework.com/start#after-you-keep-it to help me sign in, fetch its claimed source, then build and deploy my changes to that existing app. | The prompt is also visible to the person. |
+| KEEP-07 | Done page, prompt button | Copy | Reuse shipped “Copy.” |
+| KEEP-08 | CLI disclosure summary | Prefer the command line? | Reuse current wording. |
+| KEEP-09 | CLI step 1 label | Sign in | |
+| KEEP-10 | CLI step 1 instruction | Sign in to the console with the CLI. | |
+| KEEP-11 | CLI step 2 label | Fetch the source | |
+| KEEP-12 | CLI step 2 instruction | Download the saved source and unpack it into a new folder. | |
+| KEEP-13 | CLI step 3 label | Deploy changes | |
+| KEEP-14 | CLI step 3 instruction | Inspect and edit the source, then build and deploy changes to this app. | |
+| KEEP-15 | Done page, source note | Source was saved when you kept this app. Later deployments do not update it. | The snapshot is the source from when the app was kept. |
+| KEEP-16 | Console app page, button | Download source | |
+| KEEP-17 | Console app page, description | Download the source saved when you kept this app. Later deployments do not update it. | |
+| KEEP-18 | CLI, saved-file confirmation | Saved claimed-at source to {path} ({timestamp}) | |
+| KEEP-19 | CLI, sign-in refusal | Sign in with `carlos auth login --console {origin}`. | |
+| KEEP-20 | CLI, missing source refusal | No saved source for this app. | Show only after account and app authorization. |
+| KEEP-21 | CLI, temporary refusal | Source download is temporarily unavailable. Try again. | |
+| KEEP-22 | CLI, integrity or size refusal | Source failed integrity or size checks. Nothing was saved. | |
+| KEEP-23 | CLI, existing output refusal | Output already exists. Choose another `--output` path. | |
+| KEEP-24 | CLI, rate-limit refusal | Too many source downloads. Try again in a minute. | |
+| KEEP-25 | CLI, account move refusal | This app has saved source. Moving it between accounts is not supported yet. | |
+
+Choices:
+
+- Keep “Keep going” as the heading.
+- Use the exact short sentence in KEEP-03 for the in-chat handoff.
+- Use a plain URL in the prompt so it is easy to copy and follow.
\ No newline at end of file
diff --git a/docs/superpowers/specs/LUNA-COPY-RESULT-COUNTDOWN.md b/docs/superpowers/specs/LUNA-COPY-RESULT-COUNTDOWN.md
index dbf4c6c32..215c19eff 100644
--- a/docs/superpowers/specs/LUNA-COPY-RESULT-COUNTDOWN.md
+++ b/docs/superpowers/specs/LUNA-COPY-RESULT-COUNTDOWN.md
@@ -20,4 +20,5 @@
- Keep the approved mixed style: `{h} h {m} m` for hours and minutes, then `min` below an hour, matching Paul’s examples.
- Use `{m} min {s} s left` in the final five minutes because the explicit units are clear and avoid a clock-like format.
-- Make the static banner conservative in its final five minutes and under one minute so its text does not overstate the time remaining.
\ No newline at end of file
+- Make the static banner conservative in its final five minutes and under one minute so its text does not overstate the time remaining.
+Controller ruling (2026-11-07, applied in code): Paul asked for the same wording on the ticket and the banner, so the banner at 1 h or more shows "{h} h {m} m left", not COUNTDOWN-02's "{h} h left". Do not "correct" the code back to that row.
diff --git a/internal/console/app_source.go b/internal/console/app_source.go
new file mode 100644
index 000000000..75ed04ad1
--- /dev/null
+++ b/internal/console/app_source.go
@@ -0,0 +1,289 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "log"
+ "net/http"
+ "strconv"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/controlname"
+ "github.com/carlosframework/platform/internal/demo"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/release"
+)
+
+const sourceUnavailable = "Source download is temporarily unavailable. Try again."
+const sourceMissing = "No saved source for this app."
+const sourceRateLimited = "Too many source downloads. Try again in a minute."
+const sourceMoveRefused = "This app has saved source. Moving it between accounts is not supported yet."
+
+var errClaimSourceInvalid = errors.New("claim source: invalid archive or identity")
+
+type claimedSource struct {
+ Schema int `json:"schema"`
+ Operation string `json:"operation"`
+ Lifetime string `json:"lifetime"`
+ Job string `json:"job"`
+ SHA256 string `json:"sha256"`
+ Bytes int64 `json:"bytes"`
+ Version string `json:"version"`
+ ClaimedAt time.Time `json:"claimed_at"`
+}
+
+func (c claimedSource) valid() bool {
+ return c.Schema == 1 && demobuild.ValidJobID(c.Operation) && demobuild.ValidJobID(c.Job) && c.Lifetime != "" && demobuild.ValidDigest(c.SHA256) && c.Bytes > 0 && c.Bytes <= demo.SourceMaxBytes && c.Version != "" && !c.ClaimedAt.IsZero()
+}
+func claimedSourceKey(sqid, app, op string) string {
+ return "apps/" + sqid + "/" + app + "/source/claims/" + op + "/source.tar.gz"
+}
+func readClaimedSource(ctx context.Context, store release.Store, key, digest string, size int64) ([]byte, error) {
+ r, _, err := release.OpenObjectStreaming(ctx, store, key)
+ if err != nil {
+ return nil, err
+ }
+ b, err := io.ReadAll(io.LimitReader(r, demo.SourceMaxBytes+1))
+ err = errors.Join(err, r.Close())
+ if err != nil {
+ return nil, err
+ }
+ if len(b) == 0 || len(b) > demo.SourceMaxBytes || size > 0 && int64(len(b)) != size {
+ return nil, errClaimSourceInvalid
+ }
+ src, err := demobuild.ValidateArchive(bytes.NewReader(b))
+ if err != nil || src.SHA256 != digest {
+ return nil, errClaimSourceInvalid
+ }
+ return b, nil
+}
+func (s *Server) copyDemoClaimSource(ctx context.Context, op *claimOp) error {
+ if !controlname.ValidAccount(op.Target.Sqid) || !release.ValidApp(op.Target.App) || !demobuild.ValidJobID(op.ID) || !demobuild.ValidJobID(op.SourceJobID) || !demobuild.ValidDigest(op.SourceSHA256) {
+ return errClaimSourceInvalid
+ }
+ d, err := s.store.demoByID(ctx, op.DemoID)
+ if err != nil {
+ return err
+ }
+ if !controlname.ValidAccount(d.AccountSqid) || !release.ValidApp(d.App) {
+ return errClaimSourceInvalid
+ }
+ sourceKey := "apps/" + d.AccountSqid + "/" + d.App + "/demo-build-data/" + op.SourceJobID + "/source.tar.gz"
+ b, err := readClaimedSource(ctx, s.cfg.Releases, sourceKey, op.SourceSHA256, op.SourceBytes)
+ if err != nil {
+ return err
+ }
+ if err = s.claimBoundary("source-read"); err != nil {
+ return err
+ }
+ key := claimedSourceKey(op.Target.Sqid, op.Target.App, op.ID)
+ if _, err = s.cfg.Releases.Put(ctx, key, b, ""); err != nil {
+ existing, readErr := readClaimedSource(ctx, s.cfg.Releases, key, op.SourceSHA256, int64(len(b)))
+ if readErr != nil {
+ if errors.Is(readErr, errClaimSourceInvalid) {
+ return readErr
+ }
+ return err
+ }
+ if !bytes.Equal(b, existing) {
+ return errClaimSourceInvalid
+ }
+ }
+ if err = s.claimBoundary("source-object"); err != nil {
+ return err
+ }
+ op.SourceBytes = int64(len(b))
+ tx, err := s.store.demoTx(ctx)
+ if err != nil {
+ return err
+ }
+ defer tx.Rollback()
+ res, err := tx.ExecContext(ctx, `UPDATE demo_claim_ops SET source_bytes=? WHERE id=? AND source_job_id=? AND source_sha256=? AND phase='reserved'`, op.SourceBytes, op.ID, op.SourceJobID, op.SourceSHA256)
+ if err != nil {
+ return err
+ }
+ if n, err := res.RowsAffected(); err != nil {
+ return err
+ } else if n != 1 {
+ return errClaimSourceInvalid
+ }
+ if _, err = tx.ExecContext(ctx, `UPDATE demo_claim_progress SET source_copied=1 WHERE operation_id=?`, op.ID); err != nil {
+ return err
+ }
+ if err = tx.Commit(); err != nil {
+ return err
+ }
+ return s.claimBoundary("source-progress")
+}
+
+type sourceDownloads struct {
+ mu sync.Mutex
+ active int
+ windows map[string]sourceWindow
+}
+type sourceWindow struct {
+ at time.Time
+ count int
+}
+
+func (l *sourceDownloads) take(key string, now time.Time) (func(), bool) {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ if l.windows == nil {
+ l.windows = map[string]sourceWindow{}
+ }
+ for k, v := range l.windows {
+ if now.Sub(v.at) >= time.Minute {
+ delete(l.windows, k)
+ }
+ }
+ v := l.windows[key]
+ if v.count >= 10 || l.active >= 4 {
+ return nil, false
+ }
+ if v.count == 0 {
+ v.at = now
+ }
+ v.count++
+ l.windows[key] = v
+ l.active++
+ return func() { l.mu.Lock(); l.active--; l.mu.Unlock() }, true
+}
+
+// Authorization helpers may render or redirect on refusal. This door always
+// emits the same 404; no rendered account detail crosses the gate.
+type sourceGateWriter struct{ h http.Header }
+
+func (w sourceGateWriter) Header() http.Header { return w.h }
+func (w sourceGateWriter) WriteHeader(int) {}
+func (w sourceGateWriter) Write(p []byte) (int, error) { return len(p), nil }
+func (s *Server) sourceAdmission(next http.HandlerFunc, cli bool) http.HandlerFunc {
+ return func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Cache-Control", "private, no-store")
+ ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
+ defer cancel()
+ r = r.WithContext(ctx)
+ if r.Method != http.MethodGet {
+ http.NotFound(w, r)
+ return
+ }
+ if cli {
+ // No usable credential is the gate's own question: it answers
+ // 401 "not signed in" exactly as at every other CLI door. A real
+ // principal that is not a person (a service or app credential)
+ // gets the same 404 as a stranger, before any storage read.
+ p, ok := s.store.CLIPrincipal(bearer(r), time.Now())
+ if ok && p.Kind != PrincipalUser {
+ http.NotFound(w, r)
+ return
+ }
+ }
+ next(w, r)
+ }
+}
+func (s *Server) handleBrowserAppSource(w http.ResponseWriter, r *http.Request) {
+ s.sourceAdmission(s.handleAppSource, false)(w, r)
+}
+
+func (s *Server) handleAppSource(w http.ResponseWriter, r *http.Request) {
+ gate := sourceGateWriter{make(http.Header)}
+ actor, _, acct, _, app, ok := s.accountApp(gate, r)
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ s.serveAppSource(w, r, actor, acct, app)
+}
+func (s *Server) handleAPIAppSource(w http.ResponseWriter, r *http.Request) {
+ gate := sourceGateWriter{make(http.Header)}
+ if !s.apiPerson(gate, r) {
+ http.NotFound(w, r)
+ return
+ }
+ actor, acct, app, ok := s.apiAccountApp(gate, r)
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ s.serveAppSource(w, r, actor, acct, app)
+}
+func (s *Server) sourceForMember(ctx context.Context, actor string, acct *Account, app string) (claimedSource, string, error) {
+ if !controlname.ValidAccount(acct.Sqid) || !release.ValidApp(app) {
+ return claimedSource{}, "", errClaimSourceInvalid
+ }
+ var raw string
+ err := s.store.db.QueryRowContext(ctx, `SELECT a.claimed_source FROM apps a JOIN accounts c ON c.id=a.account_id JOIN memberships m ON m.account_id=c.id
+ WHERE a.account_id=? AND c.sqid=? AND a.app=? AND m.address=? AND m.role IN ('owner','member') AND c.deleted_at=0 AND a.deleted_at=0 AND a.restoring=0 AND a.demo_id='' AND a.demo_claim_op=''`, acct.ID, acct.Sqid, app, actor).Scan(&raw)
+ if err != nil {
+ return claimedSource{}, raw, err
+ }
+ var c claimedSource
+ if raw != "" && (json.Unmarshal([]byte(raw), &c) != nil || !c.valid()) {
+ return c, raw, errClaimSourceInvalid
+ }
+ return c, raw, nil
+}
+func (s *Server) serveAppSource(w http.ResponseWriter, r *http.Request, actor string, acct *Account, app string) {
+ ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
+ defer cancel()
+ var c claimedSource
+ var b []byte
+ status, message := func() (int, string) {
+ defer s.lockMembers(acct.Sqid)()
+ defer s.lockAccount(acct.Sqid)()
+ defer s.lockApp(acct.Sqid, app)()
+ var raw string
+ var err error
+ c, raw, err = s.sourceForMember(ctx, actor, acct, app)
+ if err != nil {
+ return 404, "404 page not found"
+ }
+ if raw == "" {
+ return 404, sourceMissing
+ }
+ done, ok := s.sourceDownloads.take(actor+"\x00"+acct.Sqid+"\x00"+app, time.Now())
+ if !ok {
+ return 429, sourceRateLimited
+ }
+ defer done()
+ b, err = readClaimedSource(ctx, s.cfg.Releases, claimedSourceKey(acct.Sqid, app, c.Operation), c.SHA256, c.Bytes)
+ if err != nil {
+ log.Printf("app source download: storage read failed account=%s app=%s", acct.Sqid, app)
+ return 503, sourceUnavailable
+ }
+ // Recheck membership and snapshot under the lifecycle locks before audit.
+ _, current, err := s.sourceForMember(ctx, actor, acct, app)
+ if err != nil || current != raw {
+ return 404, "404 page not found"
+ }
+ if ctx.Err() != nil {
+ return 503, sourceUnavailable
+ }
+ if err = s.store.RecordActivity(acct.ID, app, actor, Activity{Action: "app-source-download", TargetType: "claimed-source", Target: c.Operation, Detail: `{"state":"started","sha256":"` + c.SHA256 + `"}`}, time.Now().UTC()); err != nil {
+ return 503, sourceUnavailable
+ }
+ return 200, ""
+ }()
+ _ = http.NewResponseController(w).SetWriteDeadline(time.Now().Add(30 * time.Second))
+ if status != 200 {
+ http.Error(w, message, status)
+ return
+ }
+ w.Header().Set("Content-Type", "application/gzip")
+ w.Header().Set("Content-Length", strconv.Itoa(len(b)))
+ w.Header().Set("Content-Disposition", `attachment; filename="`+app+`-source.tar.gz"`)
+ w.Header().Set("X-Content-Type-Options", "nosniff")
+ w.Header().Set("X-Carlos-Source-SHA256", c.SHA256)
+ w.Header().Set("X-Carlos-Source-Claimed-At", c.ClaimedAt.UTC().Format(time.RFC3339))
+ _, _ = w.Write(b)
+}
+
+func (s *Store) hasClaimedSource(accountID int64, app string) (bool, error) {
+ var exists bool
+ err := s.db.QueryRow(`SELECT claimed_source!='' FROM apps WHERE account_id=? AND app=?`, accountID, app).Scan(&exists)
+ return exists, err
+}
diff --git a/internal/console/app_source_browser_test.go b/internal/console/app_source_browser_test.go
new file mode 100644
index 000000000..06636bc67
--- /dev/null
+++ b/internal/console/app_source_browser_test.go
@@ -0,0 +1,131 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+)
+
+func sourceDoneFixture(t *testing.T) (*Server, claimOp, string, string) {
+ t.Helper()
+ s, op, data := claimTransferFixture(t)
+ claimToVerify(t, s, op, data)
+ claimAdvance(t, s, op)
+ s = sourceRouter(t, s)
+ cookie, _ := randomToken()
+ if err := s.store.attachDemoClaimBrowser(t.Context(), cookie, claimFlow{Hash: op.FlowHash}); err != nil {
+ t.Fatal(err)
+ }
+ session, err := s.store.CreateSession(op.Person, "", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s, op, cookie, session
+}
+func TestAppSourceDonePage(t *testing.T) {
+ s, op, cookie, _ := sourceDoneFixture(t)
+ r := httptest.NewRequest("GET", "/demo/claim", nil)
+ r.AddCookie(&http.Cookie{Name: demoClaimBrowserCookie, Value: cookie})
+ w := httptest.NewRecorder()
+ s.ServeHTTP(w, r)
+ if w.Code != 200 {
+ t.Fatalf("%d %s", w.Code, w.Body)
+ }
+ acct, err := s.store.AccountByID(op.Target.AccountID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{"Still in the chat where you built it?", "Starting fresh, in a new chat or with another agent?", acct.Name, op.Target.Sqid, "https://" + op.Target.Host, "https://carlosframework.com/start#after-you-keep-it", "carlos apps source pull", "--version v1 --swap hold --no-assets ./app", "Source was saved when you kept this app. Later deployments do not update it."} {
+ if !strings.Contains(w.Body.String(), want) {
+ t.Errorf("missing %q", want)
+ }
+ }
+ // Status cookie alone has no download authority.
+ r = httptest.NewRequest("GET", "/a/"+op.Target.Sqid+"/apps/"+op.Target.App+"/source", nil)
+ r.AddCookie(&http.Cookie{Name: demoClaimBrowserCookie, Value: cookie})
+ w = httptest.NewRecorder()
+ s.ServeHTTP(w, r)
+ if w.Code != 404 {
+ t.Fatal(w.Code)
+ }
+ r = httptest.NewRequest("GET", "/demo/claim", nil)
+ w = httptest.NewRecorder()
+ s.ServeHTTP(w, r)
+ if strings.Contains(w.Body.String(), op.Target.Sqid) {
+ t.Fatal("account identity without browser capability")
+ }
+}
+func TestAppSourceHeadless(t *testing.T) {
+ chromium, err := exec.LookPath("chromium")
+ if err != nil {
+ t.Fatal("Chromium required", err)
+ }
+ node, err := exec.LookPath("node")
+ if err != nil {
+ t.Fatal(err)
+ }
+ s, op, cookie, session := sourceDoneFixture(t)
+ ts := httptest.NewServer(s)
+ defer ts.Close()
+ s.cfg.Origin = ts.URL
+ shots := os.Getenv("CARLOS_CLAIM_SOURCE_SCREENSHOTS")
+ if shots != "" {
+ if err = os.MkdirAll(shots, 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), 90*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, node, "testdata/app_source_browser.mjs", chromium, t.TempDir(), ts.URL, cookie, session, "/a/"+op.Target.Sqid+"/apps/"+op.Target.App, shots)
+ out, err := cmd.CombinedOutput()
+ if err != nil {
+ t.Fatalf("browser: %v\n%s", err, out)
+ }
+ t.Log(string(out))
+}
+
+// Progress browser tests simulate worker phases; give their completed-page
+// fixture the same descriptor shape a real source-bearing claim attaches.
+func stampSourcePageFixture(t *testing.T, s *Server) {
+ t.Helper()
+ op, err := scanDemoClaimOp(s.store.db.QueryRow(`SELECT ` + demoClaimOpColumns + ` FROM demo_claim_ops LIMIT 1`))
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ src := demoJobSource()
+ descriptor, err := json.Marshal(claimedSource{Schema: 1, Operation: op.ID, Lifetime: op.Target.Lifetime, Job: op.ID, SHA256: src.SHA256, Bytes: int64(len(src.Archive)), Version: op.Version, ClaimedAt: time.Now().UTC()})
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ if _, err = s.store.db.Exec(`UPDATE apps SET claimed_source=? WHERE account_id=? AND app=?`, string(descriptor), op.Target.AccountID, op.Target.App); err != nil {
+ t.Error(err)
+ }
+}
+
+func TestAppSourceDoneDeletedAccount(t *testing.T) {
+ s, op, cookie, _ := sourceDoneFixture(t)
+ if err := s.store.TrashAppRow(op.Target.AccountID, op.Target.App, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.store.PurgeAppRow(op.Target.AccountID, op.Target.App); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.store.DeleteAccount(op.Target.AccountID, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ r := httptest.NewRequest("GET", "/demo/claim", nil)
+ r.AddCookie(&http.Cookie{Name: demoClaimBrowserCookie, Value: cookie})
+ w := httptest.NewRecorder()
+ s.ServeHTTP(w, r)
+ if w.Code != 200 || strings.Contains(w.Body.String(), "carlos apps source pull") {
+ t.Fatalf("deleted account continuation: %d", w.Code)
+ }
+}
diff --git a/internal/console/app_source_test.go b/internal/console/app_source_test.go
new file mode 100644
index 000000000..c556cc6f5
--- /dev/null
+++ b/internal/console/app_source_test.go
@@ -0,0 +1,932 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/credentials"
+ awss3 "github.com/aws/aws-sdk-go-v2/service/s3"
+ "github.com/carlosframework/platform/internal/demobuild"
+ "github.com/carlosframework/platform/internal/release"
+ "github.com/carlosframework/platform/internal/s3fake"
+ "github.com/carlosframework/platform/internal/svcrole"
+ "io"
+ "log"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestAppSourceClaimDownload(t *testing.T) {
+ s, op, data := claimTransferFixture(t)
+ claimToVerify(t, s, op, data)
+ claimAdvance(t, s, op)
+ s = sourceRouter(t, s)
+ session, err := s.store.CreateSession(op.Person, "", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ r := httptest.NewRequest("GET", "/a/"+op.Target.Sqid+"/apps/"+op.Target.App+"/source", nil)
+ r.AddCookie(&http.Cookie{Name: sessionCookie, Value: session})
+ w := httptest.NewRecorder()
+ s.ServeHTTP(w, r)
+ if w.Code != 200 {
+ t.Fatalf("download: %d %s", w.Code, w.Body.String())
+ }
+ if !bytes.Equal(w.Body.Bytes(), demoJobSource().Archive) {
+ t.Fatal("source differs")
+ }
+ if w.Header().Get("Content-Type") != "application/gzip" || w.Header().Get("Cache-Control") != "private, no-store" {
+ t.Fatal(w.Header())
+ }
+}
+
+func sourceRouter(t *testing.T, seed *Server) *Server {
+ t.Helper()
+ cfg := seed.cfg
+ fk := newFakeKeymail(t, "shop@example.com")
+ cfg.Keymail = fk.srv.URL
+ s, err := NewServer(cfg, seed.store)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return s
+}
+
+func sourceToken(t *testing.T, s *Server, person string) string {
+ t.Helper()
+ _, _, err := s.store.ResolveSignIn(MethodEmail, person, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ user, device, err := s.store.NewCLIAuth("source-test", "127.0.0.1", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = s.store.ApproveCLIAuth(user, person, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ _, token, _, err := s.store.PollCLIAuth(device, time.Now())
+ if err != nil || token == "" {
+ t.Fatal(err)
+ }
+ return token
+}
+func sourceRequest(t *testing.T, s *Server, op claimOp, door, person, token string) *httptest.ResponseRecorder {
+ t.Helper()
+ path := "/a/" + op.Target.Sqid + "/apps/" + op.Target.App + "/source"
+ if door == "cli" {
+ path = "/api/cli/apps/" + op.Target.Sqid + "/" + op.Target.App + "/source?exact=sqid"
+ }
+ r := httptest.NewRequest("GET", path, nil)
+ if person != "" && door == "browser" {
+ session, err := s.store.CreateSession(person, "", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ r.AddCookie(&http.Cookie{Name: sessionCookie, Value: session})
+ }
+ if token != "" {
+ r.Header.Set("Authorization", "Bearer "+token)
+ }
+ r.Header.Set("Range", "bytes=0-1")
+ r.Header.Set("If-None-Match", "*")
+ w := httptest.NewRecorder()
+ s.ServeHTTP(w, r)
+ return w
+}
+
+func TestAppSourceDoors(t *testing.T) {
+ seed, op, data := claimTransferFixture(t)
+ claimToVerify(t, seed, op, data)
+ claimAdvance(t, seed, op)
+ s := sourceRouter(t, seed)
+ if err := s.store.AddMember(op.Target.AccountID, "member@example.com", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ count := &sourceCountStore{Store: s.cfg.Releases}
+ s.cfg.Releases = count
+ for _, door := range []string{"browser", "cli"} {
+ for _, person := range []string{op.Person, "member@example.com"} {
+ token := sourceToken(t, s, person)
+ count.reads = 0
+ w := sourceRequest(t, s, op, door, person, token)
+ if w.Code != 200 || !bytes.Equal(w.Body.Bytes(), demoJobSource().Archive) {
+ t.Fatalf("%s %s: %d %s", door, person, w.Code, w.Body)
+ }
+ if count.reads != 1 {
+ t.Fatalf("reads %d", count.reads)
+ }
+ if w.Header().Get("Content-Encoding") != "" || w.Header().Get("Content-Type") != "application/gzip" || w.Header().Get("X-Content-Type-Options") != "nosniff" || w.Header().Get("Content-Length") == "" || w.Header().Get("X-Carlos-Source-SHA256") != demoJobSource().SHA256 {
+ t.Fatal(w.Header())
+ }
+ events, err := s.store.Events(op.Target.AccountID, op.Target.App, 1)
+ if err != nil || len(events) != 1 || events[0].Address != person || events[0].Action != "app-source-download" {
+ t.Fatalf("audit: %+v %v", events, err)
+ }
+ }
+ }
+ if err := s.store.RemoveMember(op.Target.AccountID, "member@example.com"); err != nil {
+ t.Fatal(err)
+ }
+ serviceToken, err := s.store.NewServicePrincipal(op.Target.AccountID, "source-service", op.Target.App, svcrole.Publish, op.Person, time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ other := claimAccount(t, s, 888, "other@example.com", RoleOwner)
+ if _, err = s.store.CreateAppIn(other.ID, op.Target.App, "other@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.store.AddMember(OpsAccountID, "operator@example.com", RoleOwner, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ appToken, err := s.store.NewAppToken(op.Target.AccountID, op.Target.App, op.Person, "source test", time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, door := range []string{"browser", "cli"} {
+ for _, person := range []string{"member@example.com", "stranger@example.com", "operator@example.com", "other@example.com"} {
+ token := "invalid-demo-capability"
+ if person != "" {
+ token = sourceToken(t, s, person)
+ }
+ count.reads = 0
+ w := sourceRequest(t, s, op, door, person, token)
+ if w.Code != 404 || w.Body.String() != "404 page not found\n" || count.reads != 0 || w.Header().Get("Cache-Control") != "private, no-store" {
+ t.Fatalf("%s %s: %d %q reads=%d", door, person, w.Code, w.Body, count.reads)
+ }
+ }
+ for _, token := range []string{"", "invalid-demo-capability"} {
+ count.reads = 0
+ w := sourceRequest(t, s, op, door, "", token)
+ want, cache := 404, "private, no-store"
+ if door == "cli" {
+ want, cache = 401, "no-store"
+ }
+ if w.Code != want || count.reads != 0 || w.Header().Get("Cache-Control") != cache {
+ t.Fatalf("%s no credential: %d %s reads=%d", door, w.Code, w.Body, count.reads)
+ }
+ if door == "cli" && !strings.Contains(w.Body.String(), "not signed in") {
+ t.Fatal("missing standard sign-in refusal", w.Body)
+ }
+ if door == "browser" && w.Body.String() != "404 page not found\n" {
+ t.Fatal("browser refusal changed", w.Body)
+ }
+ }
+ count.reads = 0
+ denied := sourceRequest(t, s, op, door, "", serviceToken)
+ if denied.Code != 404 || denied.Body.String() != "404 page not found\n" || count.reads != 0 {
+ t.Fatalf("service: %d %s", denied.Code, denied.Body)
+ }
+ count.reads = 0
+ w := sourceRequest(t, s, op, door, "", appToken)
+ if w.Code != 404 || w.Body.String() != "404 page not found\n" || count.reads != 0 {
+ t.Fatalf("app token: %d %s", w.Code, w.Body)
+ }
+ }
+}
+
+type sourceCountStore struct {
+ release.Store
+ reads, puts, lists int
+ failRead, failPut, loseAck bool
+ beforeRead func()
+}
+
+func (s *sourceCountStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) {
+ s.reads++
+ if s.beforeRead != nil {
+ s.beforeRead()
+ }
+ if s.failRead {
+ return nil, "", errors.New("injected source GET")
+ }
+ return release.OpenObjectStreaming(ctx, s.Store, key)
+}
+func (s *sourceCountStore) Put(ctx context.Context, key string, b []byte, etag string) (string, error) {
+ s.puts++
+ if s.failPut {
+ return "", errors.New("injected source PUT")
+ }
+ tag, err := s.Store.Put(ctx, key, b, etag)
+ if err == nil && s.loseAck {
+ return "", errors.New("injected lost acknowledgement")
+ }
+ return tag, err
+}
+func (s *sourceCountStore) List(ctx context.Context, prefix string) ([]string, error) {
+ s.lists++
+ return s.Store.List(ctx, prefix)
+}
+
+func TestAppSourceAuditFailureAndRate(t *testing.T) {
+ for _, mode := range []string{"audit", "rate", "removed-during-read", "trash"} {
+ t.Run(mode, func(t *testing.T) {
+ seed, op, data := claimTransferFixture(t)
+ claimToVerify(t, seed, op, data)
+ claimAdvance(t, seed, op)
+ s := sourceRouter(t, seed)
+ token := sourceToken(t, s, op.Person)
+ if mode == "audit" {
+ if _, err := s.store.db.Exec(`CREATE TRIGGER fail_source_audit BEFORE INSERT ON audit WHEN NEW.action='app-source-download' BEGIN SELECT RAISE(ABORT,'audit failure'); END`); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if mode == "removed-during-read" {
+ s.cfg.Releases = &sourceCountStore{Store: s.cfg.Releases, beforeRead: func() {
+ if _, err := s.store.db.Exec(`DELETE FROM memberships WHERE account_id=? AND address=?`, op.Target.AccountID, op.Person); err != nil {
+ t.Fatal(err)
+ }
+ }}
+ }
+ if mode == "trash" {
+ if _, err := s.store.db.Exec(`UPDATE apps SET deleted_at=? WHERE account_id=? AND app=?`, time.Now().Unix(), op.Target.AccountID, op.Target.App); err != nil {
+ t.Fatal(err)
+ }
+ }
+ want := 503
+ if mode == "removed-during-read" || mode == "trash" {
+ want = 404
+ }
+ if mode == "rate" {
+ for i := 0; i < 10; i++ {
+ if w := sourceRequest(t, s, op, "cli", "", token); w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ }
+ want = 429
+ }
+ w := sourceRequest(t, s, op, "cli", "", token)
+ if w.Code != want || bytes.Equal(w.Body.Bytes(), demoJobSource().Archive) {
+ t.Fatalf("%d %s", w.Code, w.Body)
+ }
+ })
+ }
+}
+
+func TestAppSourceCopyBoundaries(t *testing.T) {
+ for _, boundary := range []string{"source-pin", "source-read", "source-object", "source-progress", "before-commit", "commit"} {
+ t.Run(boundary, func(t *testing.T) {
+ s, op, data := claimTransferFixture(t)
+ hit := false
+ s.demoClaimBoundary = func(at string) error {
+ if at == boundary && !hit {
+ hit = true
+ return errors.New("crash")
+ }
+ return nil
+ }
+ if boundary == "before-commit" || boundary == "commit" {
+ claimToVerify(t, s, op, data)
+ }
+ if err := s.advanceDemoClaim(t.Context(), op.ID); err == nil || !hit {
+ t.Fatalf("boundary %s not hit: %v", boundary, err)
+ }
+ s.demoClaimBoundary = nil
+ if boundary == "source-progress" {
+ claimAdvance(t, s, op)
+ } else if boundary == "source-pin" || boundary == "source-read" || boundary == "source-object" {
+ claimAdvance(t, s, op)
+ }
+ current, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if current.Phase == "freezing" {
+ if err = s.ackDemoClaim(t.Context(), op.ID, "freeze", uint64(op.Generation)); err != nil {
+ t.Fatal(err)
+ }
+ claimAdvance(t, s, op)
+ if err = claimSnapshot(t, s, op, data); err != nil {
+ t.Fatal(err)
+ }
+ }
+ claimAdvance(t, s, op)
+ current, _ = s.store.demoClaimOp(t.Context(), op.ID)
+ if current.Phase != "done" {
+ t.Fatal(current.Phase)
+ }
+ s = sourceRouter(t, s)
+ w := sourceRequest(t, s, op, "browser", op.Person, "")
+ if w.Code != 200 || !bytes.Equal(w.Body.Bytes(), demoJobSource().Archive) {
+ t.Fatalf("%d %s", w.Code, w.Body)
+ }
+ })
+ }
+}
+
+func TestAppSourceCopyOperations(t *testing.T) {
+ for _, mode := range []string{"normal", "lost-ack", "get-failure", "put-failure", "mismatch"} {
+ t.Run(mode, func(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ if err := s.pinDemoClaim(t.Context(), &op); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`INSERT OR IGNORE INTO demo_claim_progress(operation_id) VALUES(?)`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ count := &sourceCountStore{Store: s.cfg.Releases, loseAck: mode == "lost-ack", failRead: mode == "get-failure", failPut: mode == "put-failure"}
+ if mode == "mismatch" {
+ if _, err := count.Store.Put(t.Context(), claimedSourceKey(op.Target.Sqid, op.Target.App, op.ID), []byte("foreign bytes"), ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ s.cfg.Releases = count
+ err := s.copyDemoClaimSource(t.Context(), &op)
+ if mode == "normal" || mode == "lost-ack" {
+ if err != nil {
+ t.Fatal(err)
+ }
+ } else if err == nil {
+ t.Fatal("failure accepted")
+ }
+ if count.lists != 0 {
+ t.Fatal("copy listed storage")
+ }
+ if mode == "normal" && (count.reads != 1 || count.puts != 1) {
+ t.Fatalf("GET=%d PUT=%d", count.reads, count.puts)
+ }
+ if mode == "lost-ack" && (count.reads != 2 || count.puts != 1) {
+ t.Fatalf("GET=%d PUT=%d", count.reads, count.puts)
+ }
+ })
+ }
+}
+
+func TestAppSourceMissingCorruptAbort(t *testing.T) {
+ for _, mode := range []string{"missing", "corrupt", "oversized", "expired"} {
+ t.Run(mode, func(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ if err := s.pinDemoClaim(t.Context(), &op); err != nil {
+ t.Fatal(err)
+ }
+ d, err := s.store.demoByID(t.Context(), op.DemoID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ key := "apps/" + d.AccountSqid + "/" + d.App + "/demo-build-data/" + op.SourceJobID + "/source.tar.gz"
+ if mode == "expired" {
+ if _, err = s.store.db.Exec(`UPDATE demo_claim_ops SET deadline=1 WHERE id=?`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ if err = s.cfg.Releases.Delete(t.Context(), key); err != nil {
+ t.Fatal(err)
+ }
+ if mode != "missing" {
+ bad := []byte("corrupt")
+ if mode == "oversized" {
+ bad = bytes.Repeat([]byte("x"), 5_000_001)
+ }
+ if _, err = s.cfg.Releases.Put(t.Context(), key, bad, ""); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ if err = s.advanceDemoClaim(t.Context(), op.ID); err != nil {
+ t.Fatal(err)
+ }
+ fresh, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fresh.Phase != "aborted" && fresh.Phase != "aborting" {
+ t.Fatal(fresh.Phase)
+ }
+ var n int
+ if err = s.store.db.QueryRow(`SELECT count(*) FROM demo_claim_commits WHERE operation_id=?`, op.ID).Scan(&n); err != nil || n != 0 {
+ t.Fatal(n, err)
+ }
+ if _, _, err = s.cfg.Releases.Get(t.Context(), claimedSourceKey(op.Target.Sqid, op.Target.App, op.ID)); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("source survived abort", err)
+ }
+ })
+ }
+}
+
+func TestAppSourceProvenanceAndRetention(t *testing.T) {
+ s, op, data := claimTransferFixture(t)
+ d, err := s.store.demoByID(t.Context(), op.DemoID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // A failed later publication has identical binary bytes but different source.
+ var raw []byte
+ if err = s.store.db.QueryRow(`SELECT job FROM demo_jobs WHERE demo_id=? AND state='published'`, d.ID).Scan(&raw); err != nil {
+ t.Fatal(err)
+ }
+ var a demobuild.Job
+ if err = json.Unmarshal(raw, &a); err != nil {
+ t.Fatal(err)
+ }
+ b := a
+ b.ID, _ = demobuild.NewJobID()
+ b.Generation++
+ b.SourceSHA256 = strings.Repeat("f", 64)
+ wire, _ := json.Marshal(b)
+ if _, err = s.store.db.Exec(`INSERT INTO demo_jobs(id,demo_id,generation,attempt,box,deadline,state,wire,job,binary_sha256,publish_stage) SELECT ?,demo_id,?,attempt,box,deadline,'failed',wire,?,binary_sha256,'' FROM demo_jobs WHERE id=?`, b.ID, b.Generation, wire, a.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.store.db.Exec(`UPDATE demo_apps SET source_sha256=?,generation=? WHERE demo_id=?`, []byte(b.SourceSHA256), b.Generation, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ op.Generation = int64(b.Generation)
+ if _, err = s.store.db.Exec(`UPDATE demo_claim_ops SET generation=? WHERE id=?`, op.Generation, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ claimToVerify(t, s, op, data)
+ claimAdvance(t, s, op)
+ op, err = s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if op.SourceJobID != a.ID || op.SourceSHA256 != a.SourceSHA256 {
+ t.Fatal("wrong provenance", op.SourceJobID)
+ }
+ // The source demo and all of its metadata may disappear independently.
+ keys, err := s.cfg.Releases.List(t.Context(), "apps/"+d.AccountSqid+"/"+d.App+"/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, key := range keys {
+ if err = s.cfg.Releases.Delete(t.Context(), key); err != nil {
+ t.Fatal(err)
+ }
+ }
+ for _, table := range []string{"demo_claim_progress", "demo_claim_commits", "demo_claim_outbox"} {
+ if _, err = s.store.db.Exec("DELETE FROM "+table+" WHERE operation_id=?", op.ID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err = s.store.db.Exec(`DELETE FROM demo_claim_ops WHERE id=?`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.store.db.Exec(`DELETE FROM demo_jobs WHERE demo_id=?`, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.store.db.Exec(`DELETE FROM demo_apps WHERE demo_id=?`, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ s = sourceRouter(t, s)
+ for _, stage := range []string{"purged-demo", "deploy", "trash", "restore", "region"} {
+ switch stage {
+ case "deploy":
+ m := release.Manifest{App: op.Target.App, Version: "v1", Kind: "binary", Artifacts: map[string]release.Artifact{"linux-arm64": {File: "app", SHA256: strings.Repeat("a", 64), Size: 1}}}
+ // The serving pointer can advance without changing app-owned source metadata.
+ raw, _ := json.Marshal(m)
+ if _, err = s.cfg.Releases.Put(t.Context(), release.ManifestKey(op.Target.Sqid, op.Target.App, "v1"), raw, ""); err != nil {
+ t.Fatal(err)
+ }
+ case "trash":
+ if err = s.store.TrashAppRow(op.Target.AccountID, op.Target.App, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ case "restore":
+ if err = s.store.RestoreAppRow(op.Target.AccountID, op.Target.App); err != nil {
+ t.Fatal(err)
+ }
+ case "region":
+ if _, err = s.store.db.Exec(`UPDATE apps SET region='us-east-1' WHERE account_id=? AND app=?`, op.Target.AccountID, op.Target.App); err != nil {
+ t.Fatal(err)
+ }
+ }
+ w := sourceRequest(t, s, op, "browser", op.Person, "")
+ if stage == "trash" {
+ if w.Code != 404 {
+ t.Fatal(w.Code)
+ }
+ } else if w.Code != 200 || !bytes.Equal(w.Body.Bytes(), demoJobSource().Archive) {
+ t.Fatalf("%s: %d %s", stage, w.Code, w.Body)
+ }
+ }
+ if err = s.store.RenameAppIn(op.Target.AccountID, op.Target.App, "renamed"); err == nil {
+ t.Fatal("renamed snapshot")
+ }
+ dest := claimAccount(t, s, 777, op.Person, RoleOwner)
+ if err = s.store.MoveApp(op.Target.App, op.Target.AccountID, dest.ID); err == nil {
+ t.Fatal("moved snapshot")
+ }
+ at := time.Now().Add(-31 * 24 * time.Hour)
+ if err = release.TrashApp(t.Context(), s.cfg.Releases, op.Target.Sqid, op.Target.App, op.Person, at); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.store.TrashAppRow(op.Target.AccountID, op.Target.App, at); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.store.DeleteAccount(op.Target.AccountID, time.Now()); err == nil {
+ t.Fatal("deleted account before Trash purge")
+ }
+ if err = release.PurgeApp(t.Context(), s.cfg.Releases, s.cfg.ReleasePub, op.Target.Sqid, op.Target.App, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.store.PurgeAppRow(op.Target.AccountID, op.Target.App); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err = s.cfg.Releases.Get(t.Context(), claimedSourceKey(op.Target.Sqid, op.Target.App, op.ID)); !errors.Is(err, os.ErrNotExist) {
+ t.Fatal("source survived permanent purge", err)
+ }
+ if err = s.store.DeleteAccount(op.Target.AccountID, time.Now()); err != nil {
+ t.Fatal("account deletion after purge", err)
+ }
+}
+
+func TestAppSourceS3Adapter(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ if err := s.pinDemoClaim(t.Context(), &op); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`INSERT OR IGNORE INTO demo_claim_progress(operation_id) VALUES(?)`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ fake := s3fake.New(s.cfg.Releases.(*release.DirStore))
+ var methods []string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ methods = append(methods, r.Method)
+ fake.ServeHTTP(w, r)
+ }))
+ defer server.Close()
+ client := awss3.New(awss3.Options{Region: "us-east-1", Credentials: credentials.NewStaticCredentialsProvider("x", "y", ""), BaseEndpoint: aws.String(server.URL), UsePathStyle: true, RequestChecksumCalculation: aws.RequestChecksumCalculationWhenRequired, ResponseChecksumValidation: aws.ResponseChecksumValidationWhenRequired})
+ s.cfg.Releases = &release.S3Store{Client: client, Bucket: "local-source"}
+ if err := s.copyDemoClaimSource(t.Context(), &op); err != nil {
+ t.Fatal(err)
+ }
+ if !reflect.DeepEqual(methods, []string{"GET", "PUT"}) {
+ t.Fatal(methods)
+ }
+ got, err := readClaimedSource(t.Context(), s.cfg.Releases, claimedSourceKey(op.Target.Sqid, op.Target.App, op.ID), op.SourceSHA256, op.SourceBytes)
+ if err != nil || !bytes.Equal(got, demoJobSource().Archive) {
+ t.Fatal(err)
+ }
+}
+
+func TestAppSourceAbortAfterCopyAndLegacy(t *testing.T) {
+ for _, mode := range []string{"abort-after-copy", "legacy-inflight", "legacy-done"} {
+ t.Run(mode, func(t *testing.T) {
+ s, op, data := claimTransferFixture(t)
+ if mode == "legacy-done" {
+ claimToVerify(t, s, op, data)
+ claimAdvance(t, s, op)
+ if _, err := s.store.db.Exec(`UPDATE apps SET claimed_source='' WHERE account_id=? AND app=?`, op.Target.AccountID, op.Target.App); err != nil {
+ t.Fatal(err)
+ }
+ claimAdvance(t, s, op)
+ s = sourceRouter(t, s)
+ w := sourceRequest(t, s, op, "browser", op.Person, "")
+ if w.Code != 404 || strings.TrimSpace(w.Body.String()) != sourceMissing {
+ t.Fatalf("legacy source invented: %d %s", w.Code, w.Body)
+ }
+ return
+ }
+ s.demoClaimBoundary = func(at string) error {
+ if at == "source-progress" {
+ return errors.New("crash")
+ }
+ return nil
+ }
+ if err := s.advanceDemoClaim(t.Context(), op.ID); err == nil {
+ t.Fatal("no copy boundary")
+ }
+ s.demoClaimBoundary = nil
+ if mode == "legacy-inflight" {
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase='freezing',source_job_id='',source_sha256='',source_bytes=0 WHERE id=?`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_progress SET source_copied=0 WHERE operation_id=?`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET deadline=1 WHERE id=?`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ claimAdvance(t, s, op)
+ fresh, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil || fresh.Phase != "aborted" {
+ t.Fatalf("%s %v", fresh.Phase, err)
+ }
+ keys, err := s.cfg.Releases.List(t.Context(), "apps/"+op.Target.Sqid+"/"+op.Target.App+"/")
+ if err != nil || len(keys) != 0 {
+ t.Fatalf("abort leftovers: %v %v", keys, err)
+ }
+ var n int
+ if err = s.store.db.QueryRow(`SELECT count(*) FROM apps WHERE account_id=? AND app=?`, op.Target.AccountID, op.Target.App).Scan(&n); err != nil || n != 0 {
+ t.Fatal(n, err)
+ }
+ })
+ }
+}
+
+func TestAppSourceSQLInventory(t *testing.T) {
+ s := openGatedStore(t)
+ tables, err := claimSQLCensus(s.bootDB(), claimSQLTables)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for table, columns := range map[string][]string{"apps": {"claimed_source"}, "demo_claim_ops": {"source_job_id", "source_sha256", "source_bytes"}, "demo_claim_progress": {"source_copied"}} {
+ for _, column := range columns {
+ found := false
+ for _, got := range tables[table].cols {
+ found = found || got == column
+ }
+ if !found {
+ t.Fatalf("%s.%s missing", table, column)
+ }
+ }
+ }
+ for _, columns := range claimAppsTerminal {
+ for _, column := range columns {
+ if column == "claimed_source" {
+ t.Fatal("terminal update can replace snapshot")
+ }
+ }
+ }
+}
+
+func TestAppSourcePinnedJobCannotChange(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ if err := s.pinDemoClaim(t.Context(), &op); err != nil {
+ t.Fatal(err)
+ }
+ var raw []byte
+ if err := s.store.db.QueryRow(`SELECT job FROM demo_jobs WHERE id=?`, op.SourceJobID).Scan(&raw); err != nil {
+ t.Fatal(err)
+ }
+ var job demobuild.Job
+ if err := json.Unmarshal(raw, &job); err != nil {
+ t.Fatal(err)
+ }
+ job.SourceSHA256 = strings.Repeat("e", 64)
+ raw, _ = json.Marshal(job)
+ if _, err := s.store.db.Exec(`UPDATE demo_jobs SET job=? WHERE id=?`, raw, op.SourceJobID); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.pinDemoClaim(t.Context(), &op); err == nil {
+ t.Fatal("retry switched source identity")
+ }
+}
+
+func TestAppSourceProgressTransactionFailure(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ if _, err := s.store.db.Exec(`CREATE TRIGGER fail_source_progress BEFORE UPDATE OF source_copied ON demo_claim_progress BEGIN SELECT RAISE(ABORT,'progress failure'); END`); err != nil {
+ t.Fatal(err)
+ }
+ if err := s.advanceDemoClaim(t.Context(), op.ID); err == nil {
+ t.Fatal("progress failure ignored")
+ }
+ fresh, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if fresh.Phase != "reserved" || fresh.SourceJobID == "" || fresh.SourceBytes != 0 {
+ t.Fatalf("partial progress committed: %+v", fresh)
+ }
+ if _, err = s.store.db.Exec(`DROP TRIGGER fail_source_progress`); err != nil {
+ t.Fatal(err)
+ }
+ claimAdvance(t, s, op)
+ fresh, err = s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil || fresh.Phase != "freezing" || fresh.SourceBytes == 0 {
+ t.Fatal(fresh.Phase, err)
+ }
+}
+
+func TestAppSourceBufferAdmission(t *testing.T) {
+ var limits sourceDownloads
+ var done []func()
+ now := time.Now()
+ for _, key := range []string{"a", "b", "c", "d"} {
+ release, ok := limits.take(key, now)
+ if !ok {
+ t.Fatal("early refusal")
+ }
+ done = append(done, release)
+ }
+ if _, ok := limits.take("e", now); ok {
+ t.Fatal("unbounded buffering")
+ }
+ for _, release := range done {
+ release()
+ }
+ for i := 0; i < 9; i++ {
+ release, ok := limits.take("a", now)
+ if !ok {
+ t.Fatal("early rate refusal")
+ }
+ release()
+ }
+ if _, ok := limits.take("a", now); ok {
+ t.Fatal("rate limit exceeded")
+ }
+ release, ok := limits.take("a", now.Add(time.Minute))
+ if !ok {
+ t.Fatal("window did not reset")
+ }
+ release()
+}
+
+func TestAppSourceDeletionRace(t *testing.T) {
+ seed, op, data := claimTransferFixture(t)
+ claimToVerify(t, seed, op, data)
+ claimAdvance(t, seed, op)
+ s := sourceRouter(t, seed)
+ entered, finish := make(chan struct{}), make(chan struct{})
+ count := &sourceCountStore{Store: s.cfg.Releases, beforeRead: func() { close(entered); <-finish }}
+ s.cfg.Releases = count
+ result := make(chan *httptest.ResponseRecorder, 1)
+ go func() { result <- sourceRequest(t, s, op, "browser", op.Person, "") }()
+ <-entered
+ deleted := make(chan error, 1)
+ go func() {
+ unlock := s.lockApp(op.Target.Sqid, op.Target.App)
+ defer unlock()
+ deleted <- s.store.TrashAppRow(op.Target.AccountID, op.Target.App, time.Now())
+ }()
+ select {
+ case err := <-deleted:
+ t.Fatalf("deletion crossed download: %v", err)
+ case <-time.After(30 * time.Millisecond):
+ }
+ close(finish)
+ if w := <-result; w.Code != 200 {
+ t.Fatal(w.Code)
+ }
+ if err := <-deleted; err != nil {
+ t.Fatal(err)
+ }
+ count.reads = 0
+ count.beforeRead = nil
+ w := sourceRequest(t, s, op, "browser", op.Person, "")
+ if w.Code != 404 || count.reads != 0 {
+ t.Fatalf("deleted: %d reads=%d", w.Code, count.reads)
+ }
+}
+
+func TestAppSourceRealPublicationRollback(t *testing.T) {
+ var accepted demobuild.Job
+ s, op, data := claimTransferFixtureBefore(t, func(s *Server, d DemoRow, a demobuild.Job, out demobuild.Result) {
+ accepted = a
+ d, err := s.store.demoByID(t.Context(), d.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ sourceB := demoJobSource("// changed upload B, same binary result\n")
+ b, err := s.enqueueDemo(t.Context(), d, sourceB)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = s.pickupDemo(t.Context(), b.ID, b.Attempt, b.Fleet, b.Box); err != nil {
+ t.Fatal(err)
+ }
+ row, err := s.readDemoJob(t.Context(), b.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ b = row.Job
+ out.JobID, out.Attempt, out.SourceSHA256, out.BinaryPath = b.ID, b.Attempt, b.SourceSHA256, ""
+ if err = s.storeDemoResult(t.Context(), b, out, []byte("demo executable bytes")); err != nil {
+ t.Fatal(err)
+ }
+ if err = s.store.db.QueryRow(`SELECT spool_path FROM demo_jobs WHERE id=?`, b.ID).Scan(&out.BinaryPath); err != nil {
+ t.Fatal(err)
+ }
+ d, err = s.store.demoByID(t.Context(), d.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = s.publishDemo(t.Context(), d, b, out); err != nil {
+ t.Fatal(err)
+ }
+ demoAcceptReadiness(s, demoVersion(a))
+ if err = s.finishDemoPublish(t.Context(), b, false); err != nil {
+ t.Fatal(err)
+ }
+ ptr, err := release.Channel(t.Context(), s.cfg.Releases, s.cfg.ReleasePub, d.AccountSqid, d.App, "edge")
+ if err != nil || ptr.Version != demoVersion(a) {
+ t.Fatal("rollback did not restore A", err)
+ }
+ row, err = s.readDemoJob(t.Context(), b.ID)
+ if err != nil || row.State != "failed" {
+ t.Fatal(row.State, err)
+ }
+ })
+ claimToVerify(t, s, op, data)
+ claimAdvance(t, s, op)
+ fresh, err := s.store.demoClaimOp(t.Context(), op.ID)
+ if err != nil || fresh.SourceJobID != accepted.ID {
+ t.Fatal("wrong source job", err)
+ }
+ d, err := s.store.demoByID(t.Context(), op.DemoID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ keys, err := s.cfg.Releases.List(t.Context(), "apps/"+d.AccountSqid+"/"+d.App+"/")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, key := range keys {
+ if err = s.cfg.Releases.Delete(t.Context(), key); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if _, err = s.store.db.Exec(`DELETE FROM demo_jobs WHERE demo_id=?`, d.ID); err != nil {
+ t.Fatal(err)
+ }
+ s = sourceRouter(t, s)
+ w := sourceRequest(t, s, op, "browser", op.Person, "")
+ if w.Code != 200 || !bytes.Equal(w.Body.Bytes(), demoJobSource().Archive) {
+ t.Fatalf("%d %s", w.Code, w.Body)
+ }
+}
+
+func TestAppSourceLegacyArtifactPin(t *testing.T) {
+ s, op, _ := claimTransferFixture(t)
+ if _, err := s.store.db.Exec(`INSERT INTO demo_claim_progress(operation_id,copied) VALUES(?,1)`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ op.Version = "v0.0.0-demo.999"
+ if err := s.pinDemoClaim(t.Context(), &op); err == nil {
+ t.Fatal("legacy copied artifact rebound")
+ }
+}
+
+type sourceStalledWriter struct {
+ *httptest.ResponseRecorder
+ started, resume chan struct{}
+ deadline time.Time
+}
+
+func (w *sourceStalledWriter) SetWriteDeadline(deadline time.Time) error {
+ w.deadline = deadline
+ return nil
+}
+func (w *sourceStalledWriter) Write(b []byte) (int, error) {
+ close(w.started)
+ <-w.resume
+ return w.ResponseRecorder.Write(b)
+}
+func TestAppSourceStalledReaderReleasesLocks(t *testing.T) {
+ seed, op, data := claimTransferFixture(t)
+ claimToVerify(t, seed, op, data)
+ claimAdvance(t, seed, op)
+ s := sourceRouter(t, seed)
+ token := sourceToken(t, s, op.Person)
+ r := httptest.NewRequest("GET", "/api/cli/apps/"+op.Target.Sqid+"/"+op.Target.App+"/source?exact=sqid", nil)
+ r.Header.Set("Authorization", "Bearer "+token)
+ w := &sourceStalledWriter{ResponseRecorder: httptest.NewRecorder(), started: make(chan struct{}), resume: make(chan struct{})}
+ finished := make(chan struct{})
+ go func() { defer close(finished); s.ServeHTTP(w, r) }()
+ defer func() { close(w.resume); <-finished }()
+ select {
+ case <-w.started:
+ case <-time.After(10 * time.Second):
+ t.Fatal("write never started")
+ }
+ if w.deadline.IsZero() || time.Until(w.deadline) > 30*time.Second {
+ t.Error("response has no bounded write deadline")
+ }
+ acquired := make(chan struct{})
+ go func() {
+ defer s.lockMembers(op.Target.Sqid)()
+ defer s.lockAccount(op.Target.Sqid)()
+ defer s.lockApp(op.Target.Sqid, op.Target.App)()
+ close(acquired)
+ }()
+ select {
+ case <-acquired:
+ case <-time.After(time.Second):
+ t.Error("stalled response blocks account locks")
+ }
+ s.sourceDownloads.mu.Lock()
+ active := s.sourceDownloads.active
+ s.sourceDownloads.mu.Unlock()
+ if active != 0 {
+ t.Error("stalled response holds buffer slot", active)
+ }
+}
+func TestAppSourceStorageFailureLogged(t *testing.T) {
+ seed, op, data := claimTransferFixture(t)
+ claimToVerify(t, seed, op, data)
+ claimAdvance(t, seed, op)
+ s := sourceRouter(t, seed)
+ token := sourceToken(t, s, op.Person)
+ s.cfg.Releases = &sourceCountStore{Store: s.cfg.Releases, failRead: true}
+ var logs bytes.Buffer
+ before := log.Writer()
+ log.SetOutput(&logs)
+ defer log.SetOutput(before)
+ w := sourceRequest(t, s, op, "cli", "", token)
+ if w.Code != 503 || !strings.Contains(logs.String(), "app source download: storage read failed") {
+ t.Fatalf("storage refusal not logged: %d %s", w.Code, logs.String())
+ }
+ for _, secret := range []string{token, string(demoJobSource().Archive)} {
+ if strings.Contains(logs.String(), secret) {
+ t.Fatal("source or secret in log")
+ }
+ }
+}
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go
index 8fbeac7a8..8984a5dbc 100644
--- a/internal/console/appsettings.go
+++ b/internal/console/appsettings.go
@@ -1038,6 +1038,11 @@ func (s *Server) appPolicyState(ctx context.Context, acct *Account, name string)
// behind, and the moved app, which no create clears for, would take up an
// earlier app's at the destination. "" means the move may go ahead.
func (s *Server) movePolicyRefusal(ctx context.Context, from, to *Account, app string) string {
+ if has, err := s.store.hasClaimedSource(from.ID, app); err != nil {
+ return sourceUnavailable
+ } else if has {
+ return sourceMoveRefused
+ }
for _, acct := range []*Account{from, to} {
present, err := s.appPolicyState(ctx, acct, app)
switch {
diff --git a/internal/console/authcli.go b/internal/console/authcli.go
index 589f5d1d5..f33b71d0e 100644
--- a/internal/console/authcli.go
+++ b/internal/console/authcli.go
@@ -452,7 +452,11 @@ func (s *Server) cliRoute(pattern string, allow svcrole.Set, h http.HandlerFunc)
s.cliRoles = map[string]svcrole.Set{}
}
s.cliRoles[pattern] = allow
- s.registerRoute(pattern, s.cliGate(allow, h))
+ gate := s.cliGate(allow, h)
+ if pattern == "GET /api/cli/apps/{account}/{app}/source" {
+ gate = s.sourceAdmission(gate, true)
+ }
+ s.registerRoute(pattern, gate)
}
// cliRouteJournaled is cliRoute whose role gate, when it refuses a service
@@ -594,6 +598,7 @@ func (s *Server) registerCLIRoutes() {
// The app's region, the default for its NEW instances (appregionset.go).
// A person only: an account owner or a deployment operator may change
// it, so no service role reaches either door.
+ s.cliRoute("GET /api/cli/apps/{account}/{app}/source", svcrole.Set{}, s.handleAPIAppSource)
s.cliRoute("GET /api/cli/apps/{account}/{app}/region", svcrole.Set{}, s.handleAPIAppRegionGet)
s.cliRoute("PUT /api/cli/apps/{account}/{app}/region", svcrole.Set{}, s.handleAPIAppRegionSet)
s.cliRoute("GET /api/cli/apps/{account}/{app}/channels", svcrole.Allow(svcrole.Publish, svcrole.Deploy), s.handleAPIChannels)
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index c43bbfcad..b848a2e97 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -731,6 +731,8 @@ func (cx *claimCase) crashedRestore(t *testing.T) {
// ---- the table ----------------------------------------------------------------
var claimFixtures = map[string]claimFixture{
+ "route GET /a/{sqid}/apps/{app}/source": claimSourceDownloadFixture(true),
+ "route GET /api/cli/apps/{account}/{app}/source": claimSourceDownloadFixture(false),
"route POST /api/fleet/replicas/{account}/{app}/{host}/coordinator": {door: claimReplicaDoor("coordinator")},
"route POST /api/fleet/replicas/{account}/{app}/{host}/release": {door: claimReplicaDoor("release")},
"route GET /accounts": claimRead("renders only the signed-in person’s account memberships"),
diff --git a/internal/console/claim_invariant_source_test.go b/internal/console/claim_invariant_source_test.go
new file mode 100644
index 000000000..0db59e65d
--- /dev/null
+++ b/internal/console/claim_invariant_source_test.go
@@ -0,0 +1,64 @@
+package console
+
+import (
+ "encoding/json"
+ "net/http"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/demobuild"
+)
+
+// Source download is a GET with an app-scoped audit write. Exercise its
+// real success and its foreign-exclusive refusal, like the DB download.
+func claimSourceDownloadFixture(browser bool) claimFixture {
+ return claimFixture{door: &claimDoor{
+ apps: claimRefs("bab/titogo"),
+ setup: func(t *testing.T, cx *claimCase) {
+ id, err := cx.st.ClaimAppID(OpsAccountID, "titogo")
+ if err != nil {
+ t.Fatal(err)
+ }
+ life, err := cx.st.AppLife(OpsAccountID, "titogo")
+ if err != nil {
+ t.Fatal(err)
+ }
+ op, err := demobuild.NewJobID()
+ if err != nil {
+ t.Fatal(err)
+ }
+ src := demoJobSource()
+ raw, err := json.Marshal(claimedSource{Schema: 1, Operation: op, Lifetime: life.Lifetime, Job: op, SHA256: src.SHA256, Bytes: int64(len(src.Archive)), Version: "v0.0.0-demo.1", ClaimedAt: time.Now().UTC()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ scope := []claimSQLScope{{AccountID: OpsAccountID, App: "titogo", AppID: id, Mode: claimModeEffect}}
+ err = cx.st.withClaimSQL(gateCtx(t), scope, allowAllClaimSQL, func(v *Store) error {
+ _, err := v.db.Exec(`UPDATE apps SET claimed_source=? WHERE account_id=? AND app=?`, string(raw), OpsAccountID, "titogo")
+ return err
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = cx.rel.Put(t.Context(), claimedSourceKey("bab", "titogo", op), src.Archive, ""); err != nil {
+ t.Fatal(err)
+ }
+ },
+ do: func(t *testing.T, cx *claimCase) int {
+ if browser {
+ return cx.pageReply(t, "/a/bab/apps/titogo/source").Status
+ }
+ return cx.api(t, http.MethodGet, "/api/cli/apps/bab/titogo/source", "")
+ },
+ check: func(t *testing.T, cx *claimCase, open bool) string {
+ n := cx.sqlCount(t, `SELECT COUNT(*) FROM audit WHERE account_id=? AND app=? AND action='app-source-download'`, OpsAccountID, "titogo")
+ if open && n != 1 {
+ return "source download did not write exactly one audit row"
+ }
+ if !open && n != 0 {
+ return "source download audited under a foreign exclusive operation"
+ }
+ return ""
+ },
+ }}
+}
diff --git a/internal/console/demo_claim_browser_test.go b/internal/console/demo_claim_browser_test.go
index 600c4b3fb..693a0edde 100644
--- a/internal/console/demo_claim_browser_test.go
+++ b/internal/console/demo_claim_browser_test.go
@@ -321,7 +321,7 @@ func TestDemoClaimBrowserStatus(t *testing.T) {
if w.Code != 200 {
t.Fatalf("%s status: %d", phase, w.Code)
}
- if phase == "done" && (!strings.Contains(w.Body.String(), op.Target.Host) || !strings.Contains(w.Body.String(), op.Target.App) || !strings.Contains(w.Body.String(), "carlos auth login --console "+s.cfg.Origin)) {
+ if phase == "done" && (!strings.Contains(w.Body.String(), op.Target.Host) || !strings.Contains(w.Body.String(), op.Target.App) || !strings.Contains(w.Body.String(), sourceMissing)) {
t.Fatalf("result missing: %s", w.Body.String())
}
}
diff --git a/internal/console/demo_claim_csp_test.go b/internal/console/demo_claim_csp_test.go
index 9c45a6b09..9e80f62af 100644
--- a/internal/console/demo_claim_csp_test.go
+++ b/internal/console/demo_claim_csp_test.go
@@ -130,15 +130,14 @@ func TestDemoClaimMobileMarkup(t *testing.T) {
}
func TestDemoClaimCommandMarkup(t *testing.T) {
- p := demoClaimPageData{State: "claimed", Copy: demoClaimBrowserCopy()}
- p.Copy["next"] = "carlos auth login --console https://console.example.com"
+ p := demoClaimPageData{State: "claimed", Copy: demoClaimBrowserCopy(), AccountSqid: "byv", SourceSteps: claimSourceSteps("kept", "byv", "https://console.example.com")}
var body strings.Builder
if err := demoClaimPageTemplate.ExecuteTemplate(&body, "demo_claim.html", p); err != nil {
t.Fatal(err)
}
for _, want := range []string{
- `<p>Sign in once, then send changes with carlos deploy.</p>`,
- `<pre><code id="claim-cli-command">` + p.Copy["next"] + `</code></pre>`,
+ `<p>Sign in to the console with the CLI.</p>`,
+ `<pre><code id="claim-cli-command">` + strings.ReplaceAll(p.SourceSteps[0].Command, "'", "&#39;") + `</code></pre>`,
`data-copy="Copy" data-copied="Copied" aria-live="polite" hidden>Copy</button>`,
} {
if !strings.Contains(body.String(), want) {
diff --git a/internal/console/demo_claim_kept_test.go b/internal/console/demo_claim_kept_test.go
index b385271d7..6846d9806 100644
--- a/internal/console/demo_claim_kept_test.go
+++ b/internal/console/demo_claim_kept_test.go
@@ -8,6 +8,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
+ "regexp"
"strings"
"testing"
"time"
@@ -25,7 +26,10 @@ func keptFixture(t *testing.T) (*Server, string, string, claimOp) {
}
s.demoClaimTestEnabled = true
f, flow := claimProved(t, s, demoToken, "kept-person@example.com")
- a := claimAccount(t, s, 801, f.Person, RoleOwner)
+ a, _, err := s.chooseDemoClaimAccount(t.Context(), f, "")
+ if err != nil {
+ t.Fatal(err)
+ }
w := claimPost(s, "/api/demo/claims/select", map[string]string{"flowToken": flow, "accountId": a.Sqid})
if w.Code != 202 {
t.Fatalf("create: %d %s", w.Code, w.Body)
@@ -48,6 +52,10 @@ func keptFixture(t *testing.T) (*Server, string, string, claimOp) {
if err != nil {
t.Fatal(err)
}
+ acct, err := s.store.AccountByID(op.Target.AccountID)
+ if err != nil || acct == nil || acct.Name != f.Person {
+ t.Fatal("fixture must mint an account named by the claimant email", err)
+ }
return s, token, flow, op
}
@@ -104,6 +112,14 @@ func TestDemoClaimKeptExchange(t *testing.T) {
if !strings.Contains(page, `data-state="claimed"`) || strings.Contains(page, `data-reveal="true"`) {
t.Fatal("reload must be settled after progress")
}
+ if keptPageHasAccountID(page, op) {
+ t.Fatal("status cookie leaked account ID outside public app URL")
+ }
+ for _, private := range []string{op.Person, `class="claim-next"`, `id="claim-agent-command"`, `id="claim-source-command"`} {
+ if strings.Contains(page, private) {
+ t.Fatalf("status cookie that did not complete the claim leaked %q", private)
+ }
+ }
}
replay := claimPost(s, "/api/demo/claims/select", map[string]string{"flowToken": flow, "accountId": op.Target.Sqid})
r := httptest.NewRequest("GET", "/api/demo/claims/status", nil)
@@ -249,7 +265,10 @@ func TestDemoClaimKeptDoneAndAtomic(t *testing.T) {
if !strings.Contains(page, `data-state="claimed"`) || strings.Contains(page, `data-reveal="true"`) != (i == 0) {
t.Fatal("reveal not once")
}
- for _, secret := range []string{token, op.Person, `action="/demo/claim/select"`} {
+ if keptPageHasAccountID(page, op) {
+ t.Fatal("kept page leaked account ID outside public app URL")
+ }
+ for _, secret := range []string{token, op.Person, `class="claim-next"`, `id="claim-agent-command"`, `id="claim-source-command"`, `action="/demo/claim/select"`} {
if strings.Contains(page, secret) {
t.Fatal("status page leaked authority/identity")
}
@@ -505,3 +524,45 @@ func TestDemoClaimKeptExchangeRollback(t *testing.T) {
t.Fatal("expired status credential retained")
}
}
+
+func TestDemoClaimKeptContinuationMembership(t *testing.T) {
+ s, token, _, op := keptFixture(t)
+ stampSourcePageFixture(t, s)
+ if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase='done' WHERE id=?`, op.ID); err != nil {
+ t.Fatal(err)
+ }
+ b := &claimBrowser{t: t, s: s}
+ b.request("GET", "/demo/claim/kept", nil)
+ if w := b.post("/demo/claim/kept", url.Values{"keptToken": {token}}); w.Code != 303 {
+ t.Fatal(w.Code)
+ }
+ for _, role := range []string{"", RoleMember, RoleOwner, "unknown"} {
+ person := "viewer@example.com"
+ if role != "" {
+ if err := s.store.AddMember(op.Target.AccountID, person, RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := s.store.db.Exec(`UPDATE memberships SET role=? WHERE account_id=? AND address=?`, role, op.Target.AccountID, person); err != nil {
+ t.Fatal(err)
+ }
+ }
+ b.login(person, MethodEmail, false)
+ page := b.request("GET", "/demo/claim", nil).Body.String()
+ authorized := role == RoleOwner || role == RoleMember
+ if keptPageHasAccountID(page, op) != authorized {
+ t.Errorf("role %q: account ID visibility outside public app URL", role)
+ }
+ for _, private := range []string{op.Person, `class="claim-next"`, `id="claim-agent-command"`, `id="claim-source-command"`} {
+ if strings.Contains(page, private) != authorized {
+ t.Errorf("role %q: private continuation visibility for %q", role, private)
+ }
+ }
+ }
+}
+
+// The public app URL already contains the sqid. Check all other occurrences
+// as identifiers, so a short sqid such as "bac" does not match CSS "background".
+func keptPageHasAccountID(page string, op claimOp) bool {
+ page = strings.ReplaceAll(page, op.Target.Host, "public-app-host")
+ return regexp.MustCompile(`\b` + regexp.QuoteMeta(op.Target.Sqid) + `\b`).MatchString(page)
+}
diff --git a/internal/console/demo_claim_moved_test.go b/internal/console/demo_claim_moved_test.go
index 3671e7586..38b5f461c 100644
--- a/internal/console/demo_claim_moved_test.go
+++ b/internal/console/demo_claim_moved_test.go
@@ -372,7 +372,7 @@ func TestDemoMovedSnapshotSkipsBadRow(t *testing.T) {
claimToVerify(t, s, op, data)
claimAdvance(t, s, op)
// A second committed operation has a corrupt notice; the first stays publishable.
- _, err := s.store.db.Exec(`INSERT INTO demo_claim_ops SELECT 'other-op','',?,source_lifetime,source_box,person,version,artifact_sha256,phase,generation,account_id,target_sqid,app,host,target_lifetime,region,seed_id,deadline,source_expires_at,'' FROM demo_claim_ops WHERE id=?`, "AAAAAAAAAAAAAAAAAAAAAA", op.ID)
+ _, err := s.store.db.Exec(`INSERT INTO demo_claim_ops SELECT 'other-op','',?,source_lifetime,source_box,person,version,artifact_sha256,phase,generation,account_id,target_sqid,app,host,target_lifetime,region,seed_id,deadline,source_expires_at,'','','',0 FROM demo_claim_ops WHERE id=?`, "AAAAAAAAAAAAAAAAAAAAAA", op.ID)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/console/demo_claim_page.go b/internal/console/demo_claim_page.go
index 10757185d..d118f3846 100644
--- a/internal/console/demo_claim_page.go
+++ b/internal/console/demo_claim_page.go
@@ -34,6 +34,8 @@ var demoClaimStyleHash = func() string {
}()
type demoClaimPageData struct {
+ SourceSteps []claimSourceStep
+ AccountName, AccountSqid string
Reveal, AutoSubmit bool
SelectedAccount string
Chrome page
@@ -153,6 +155,28 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
p.State = "claimed"
p.App = op.Target.App
p.URL = "https://" + op.Target.Host
+ canContinue := keptErr != nil && err == nil && hash == op.FlowHash && op.Person != ""
+ if !canContinue && address != "" {
+ role, roleErr := s.store.Role(op.Target.AccountID, address)
+ canContinue = roleErr == nil && (role == RoleOwner || role == RoleMember)
+ }
+ if canContinue {
+ if acct, err := s.store.AccountByID(op.Target.AccountID); err == nil && acct != nil && acct.Sqid == op.Target.Sqid {
+ p.AccountName, p.AccountSqid = acct.Name, acct.Sqid
+ p.Copy["sameChat"] = "Still in the chat where you built it?"
+ p.Copy["sameChatLine"] = fmt.Sprintf("Tell your agent: “I kept %s. It now lives at %s in my account %s.”", p.App, p.URL, acct.Name)
+ p.Copy["agentHeading"] = "Starting fresh, in a new chat or with another agent?"
+ p.Copy["agentDetail"] = "Give your agent this prompt so it can help you sign in, fetch the source, and deploy changes to this app."
+ p.Copy["agentLine"] = fmt.Sprintf("Continue app %s in account %s (ID %s) on console %s. Follow https://carlosframework.com/start#after-you-keep-it to help me sign in, fetch its claimed source, then build and deploy my changes to that existing app.", p.App, acct.Name, acct.Sqid, s.cfg.Origin)
+ p.Copy["sourceNote"] = "Source was saved when you kept this app. Later deployments do not update it."
+ if has, err := s.store.hasClaimedSource(acct.ID, p.App); err == nil && has {
+ p.SourceSteps = claimSourceSteps(p.App, acct.Sqid, s.cfg.Origin)
+ } else {
+ p.Copy["sourceNote"] = "No saved source for this app."
+ p.Copy["agentLine"] = ""
+ }
+ }
+ }
}
if op.Phase == "aborted" {
p.State = "aborted"
@@ -231,7 +255,7 @@ func (s *Server) handleDemoClaimPage(w http.ResponseWriter, r *http.Request) {
p.EndTime = time.Unix(p.ExpiresAt, 0).UTC().Format(time.RFC3339)
}
p.Copy["completeHeading"] = strings.ReplaceAll(demoClaimUX43, "{app}", p.App)
- p.Copy["agentLine"] = strings.ReplaceAll(demoClaimUX50, "{app}", p.App)
+
p.Copy["accountsIntro"] = strings.ReplaceAll(demoClaimUX25, "{used}", fmt.Sprint(len(p.Accounts)))
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err = demoClaimPageTemplate.ExecuteTemplate(w, "demo_claim.html", p); err != nil {
@@ -705,3 +729,15 @@ func (s *Server) demoClaimAccountView(ctx context.Context, a Account, count bool
}
return c
}
+
+type claimSourceStep struct{ ID, Label, Instruction, Command string }
+
+func sourceShellQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", "'\"'\"'") + "'" }
+func claimSourceSteps(app, sqid, origin string) []claimSourceStep {
+ a, c, o := sourceShellQuote(app), sourceShellQuote(sqid), sourceShellQuote(origin)
+ return []claimSourceStep{
+ {"claim-cli-command", "Sign in", "Sign in to the console with the CLI.", "carlos auth login --console " + o},
+ {"claim-source-command", "Fetch the source", "Download the saved source and unpack it into a new folder.", "carlos apps source pull --console " + o + " --account-id " + c + " --app " + a + "\nmkdir " + a + "\ntar --no-same-owner --no-same-permissions -xzf " + sourceShellQuote(app+"-source.tar.gz") + " -C " + a + "\ncd " + a},
+ {"claim-deploy-command", "Deploy changes", "Inspect and edit the source, then build and deploy changes to this app.", "CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -trimpath -buildvcs=false -o app .\ncarlos deploy --console " + o + " --account-id " + c + " --app " + a + " --channel edge --kind binary --target linux-arm64 --version v1 --swap hold --no-assets ./app"},
+ }
+}
diff --git a/internal/console/demo_claim_resume_browser_test.go b/internal/console/demo_claim_resume_browser_test.go
index 065f8e69c..bebf6a2b0 100644
--- a/internal/console/demo_claim_resume_browser_test.go
+++ b/internal/console/demo_claim_resume_browser_test.go
@@ -78,6 +78,9 @@ func TestDemoClaimSelectStepUpHeadless(t *testing.T) {
if _, err := s.store.db.Exec(`UPDATE demo_claim_ops SET phase=?`, phase); err != nil {
t.Error(err)
}
+ if phase == "done" {
+ stampSourcePageFixture(t, s)
+ }
}
if strings.HasPrefix(r.URL.Path, "/auth/") {
if _, err := r.Cookie(browserClaimCookieName); err == nil {
diff --git a/internal/console/demo_claim_store.go b/internal/console/demo_claim_store.go
index 23585dceb..77397560c 100644
--- a/internal/console/demo_claim_store.go
+++ b/internal/console/demo_claim_store.go
@@ -53,6 +53,11 @@ func (s *Store) migrateDemoClaims() error {
`ALTER TABLE demo_claim_ops ADD COLUMN kept_hash TEXT NOT NULL DEFAULT ''`,
`ALTER TABLE demo_claim_browsers ADD COLUMN operation_id TEXT NOT NULL DEFAULT ''`,
`ALTER TABLE demo_claim_browsers ADD COLUMN reveal INTEGER NOT NULL DEFAULT 0`,
+ `ALTER TABLE apps ADD COLUMN claimed_source TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE demo_claim_ops ADD COLUMN source_job_id TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE demo_claim_ops ADD COLUMN source_sha256 TEXT NOT NULL DEFAULT ''`,
+ `ALTER TABLE demo_claim_ops ADD COLUMN source_bytes INTEGER NOT NULL DEFAULT 0`,
+ `ALTER TABLE demo_claim_progress ADD COLUMN source_copied INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE demo_claim_progress ADD COLUMN hold_cleared INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE demo_claim_progress ADD COLUMN retry_delay INTEGER NOT NULL DEFAULT 0`,
`ALTER TABLE demo_claim_progress ADD COLUMN target_generation INTEGER NOT NULL DEFAULT 0`,
@@ -136,12 +141,12 @@ func newDemoClaimFlow(raw, address string, d DemoRow, life AppLife, now time.Tim
return f
}
-const demoClaimOpColumns = `id,flow_hash,demo_id,source_lifetime,source_box,person,version,artifact_sha256,phase,generation,account_id,target_sqid,app,host,target_lifetime,region,seed_id,deadline,source_expires_at`
+const demoClaimOpColumns = `id,flow_hash,demo_id,source_lifetime,source_box,person,version,artifact_sha256,phase,generation,account_id,target_sqid,app,host,target_lifetime,region,seed_id,deadline,source_expires_at,source_job_id,source_sha256,source_bytes`
func scanDemoClaimOp(row interface{ Scan(...any) error }) (claimOp, error) {
var op claimOp
var deadline int64
- err := row.Scan(&op.ID, &op.FlowHash, &op.DemoID, &op.SourceLifetime, &op.SourceBox, &op.Person, &op.Version, &op.ArtifactSHA256, &op.Phase, &op.Generation, &op.Target.AccountID, &op.Target.Sqid, &op.Target.App, &op.Target.Host, &op.Target.Lifetime, &op.Target.Region, &op.Target.SeedID, &deadline, &op.SourceExpiresAt)
+ err := row.Scan(&op.ID, &op.FlowHash, &op.DemoID, &op.SourceLifetime, &op.SourceBox, &op.Person, &op.Version, &op.ArtifactSHA256, &op.Phase, &op.Generation, &op.Target.AccountID, &op.Target.Sqid, &op.Target.App, &op.Target.Host, &op.Target.Lifetime, &op.Target.Region, &op.Target.SeedID, &deadline, &op.SourceExpiresAt, &op.SourceJobID, &op.SourceSHA256, &op.SourceBytes)
op.Deadline = time.Unix(deadline, 0)
return op, err
}
@@ -209,7 +214,7 @@ func (s *Store) reserveDemoClaimRows(ctx context.Context, f claimFlow, op claimO
if err = tx.QueryRowContext(ctx, `SELECT lifetime FROM apps WHERE account_id=? AND app=?`, op.Target.AccountID, op.Target.App).Scan(&op.Target.Lifetime); err != nil {
return claimOp{}, err
}
- _, err = tx.ExecContext(ctx, `INSERT INTO demo_claim_ops (`+demoClaimOpColumns+`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, op.ID, op.FlowHash, op.DemoID, op.SourceLifetime, op.SourceBox, op.Person, op.Version, op.ArtifactSHA256, op.Phase, op.Generation, op.Target.AccountID, op.Target.Sqid, op.Target.App, op.Target.Host, op.Target.Lifetime, op.Target.Region, op.Target.SeedID, op.Deadline.Unix(), op.SourceExpiresAt)
+ _, err = tx.ExecContext(ctx, `INSERT INTO demo_claim_ops (`+demoClaimOpColumns+`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, op.ID, op.FlowHash, op.DemoID, op.SourceLifetime, op.SourceBox, op.Person, op.Version, op.ArtifactSHA256, op.Phase, op.Generation, op.Target.AccountID, op.Target.Sqid, op.Target.App, op.Target.Host, op.Target.Lifetime, op.Target.Region, op.Target.SeedID, op.Deadline.Unix(), op.SourceExpiresAt, op.SourceJobID, op.SourceSHA256, op.SourceBytes)
if err != nil {
return claimOp{}, err
}
diff --git a/internal/console/demo_claim_target.go b/internal/console/demo_claim_target.go
index e83221ce1..8ce4376c9 100644
--- a/internal/console/demo_claim_target.go
+++ b/internal/console/demo_claim_target.go
@@ -23,6 +23,8 @@ type claimTarget struct {
Sqid, App, Host, Lifetime, Region, SeedID string
}
type claimOp struct {
+ SourceJobID, SourceSHA256 string
+ SourceBytes int64
keptToken string // Creation response only; never loaded from SQL.
ID, FlowHash, DemoID, SourceLifetime, SourceBox, Person, Version, ArtifactSHA256, Phase string
Generation int64
diff --git a/internal/console/demo_claim_transfer.go b/internal/console/demo_claim_transfer.go
index 4e0a3afeb..33822745e 100644
--- a/internal/console/demo_claim_transfer.go
+++ b/internal/console/demo_claim_transfer.go
@@ -5,6 +5,7 @@ import (
"crypto/sha256"
"database/sql"
"encoding/hex"
+ "encoding/json"
"errors"
"io"
"log"
@@ -23,6 +24,7 @@ import (
)
type demoClaimProgress struct {
+ SourceCopied bool
Wire []byte
Action, SHA, Reason string
HoldReady, HoldAck, Copied, Cleanup, AbortAck, HoldCleared bool
@@ -34,7 +36,7 @@ func (s *Store) demoClaimOp(ctx context.Context, id string) (claimOp, error) {
}
func (s *Server) claimProgress(ctx context.Context, id string) (demoClaimProgress, error) {
var p demoClaimProgress
- err := s.store.db.QueryRowContext(ctx, `SELECT work,action,hold_ready,hold_ack,snapshot_sha,snapshot_bytes,copied,cleanup,abort_ack,reason,retry_at,phase_until,hold_cleared FROM demo_claim_progress WHERE operation_id=?`, id).Scan(&p.Wire, &p.Action, &p.HoldReady, &p.HoldAck, &p.SHA, &p.Bytes, &p.Copied, &p.Cleanup, &p.AbortAck, &p.Reason, &p.RetryAt, &p.Until, &p.HoldCleared)
+ err := s.store.db.QueryRowContext(ctx, `SELECT work,action,hold_ready,hold_ack,snapshot_sha,snapshot_bytes,copied,cleanup,abort_ack,reason,retry_at,phase_until,hold_cleared,source_copied FROM demo_claim_progress WHERE operation_id=?`, id).Scan(&p.Wire, &p.Action, &p.HoldReady, &p.HoldAck, &p.SHA, &p.Bytes, &p.Copied, &p.Cleanup, &p.AbortAck, &p.Reason, &p.RetryAt, &p.Until, &p.HoldCleared, &p.SourceCopied)
return p, err
}
func (s *Server) claimBoundary(at string) error {
@@ -106,6 +108,10 @@ func (s *Server) advanceDemoClaimLocked(ctx context.Context, id string) error {
bounded, cancel := context.WithDeadline(ctx, op.Deadline)
defer cancel()
ctx = bounded
+ // Older in-flight claims must not cross the new commit prerequisite.
+ if op.Phase != "reserved" && !p.SourceCopied {
+ return s.beginDemoClaimAbort(ctx, op, "source_unready")
+ }
switch op.Phase {
case "reserved":
if !s.demoClaimEnabled() {
@@ -117,6 +123,17 @@ func (s *Server) advanceDemoClaimLocked(ctx context.Context, id string) error {
if err = s.pinDemoClaim(ctx, &op); err != nil {
return s.beginDemoClaimAbort(ctx, op, "source_unready")
}
+ if err = s.claimBoundary("source-pin"); err != nil {
+ return err
+ }
+ if !p.SourceCopied {
+ if err = s.copyDemoClaimSource(ctx, &op); err != nil {
+ if errors.Is(err, errClaimSourceInvalid) || errors.Is(err, os.ErrNotExist) {
+ return s.beginDemoClaimAbort(ctx, op, "source_unready")
+ }
+ return err
+ }
+ }
if _, err = release.SetPipeline(ctx, s.cfg.Releases, s.cfg.Key, op.Target.Sqid, op.Target.App, release.DefaultPipelineChannels(), op.Person); err != nil {
return err
}
@@ -256,22 +273,46 @@ func (s *Server) pinDemoClaim(ctx context.Context, op *claimOp) error {
if m.Kind != "binary" || len(m.Artifacts) != 1 || !demobuild.ValidDigest(art.SHA256) || art.Size <= 0 || art.Size > demobuild.BinaryMaxBytes {
return ErrDemoToken
}
- var published int
- if err = s.store.db.QueryRowContext(ctx, `SELECT count(*) FROM demo_jobs WHERE demo_id=? AND state='published' AND binary_sha256=?`, d.ID, art.SHA256).Scan(&published); err != nil {
+ rows, err := s.store.db.QueryContext(ctx, `SELECT id,job FROM demo_jobs WHERE demo_id=? AND state='published' AND binary_sha256=? AND ('v0.0.0-demo.' || generation)=?`, d.ID, art.SHA256, ptr.Version)
+ if err != nil {
return err
}
- if published == 0 {
- return ErrDemoToken
+ var selected demobuild.Job
+ count := 0
+ for rows.Next() {
+ var id string
+ var raw []byte
+ if err = rows.Scan(&id, &raw); err != nil {
+ break
+ }
+ var j demobuild.Job
+ if json.Unmarshal(raw, &j) != nil || j.ID != id || j.DemoID != d.ID || j.Account != d.AccountSqid || j.App != d.App || j.Lifetime != op.SourceLifetime || demoVersion(j) != ptr.Version || !demobuild.ValidJobID(j.ID) || !demobuild.ValidDigest(j.SourceSHA256) {
+ err = ErrDemoToken
+ break
+ }
+ selected = j
+ count++
}
- p, err := s.claimProgress(ctx, op.ID)
+ err = errors.Join(err, rows.Err(), rows.Close())
if err != nil {
return err
}
- if p.Copied && (op.Version != ptr.Version || op.ArtifactSHA256 != art.SHA256) {
+ if count != 1 {
+ return ErrDemoToken
+ }
+ var artifactCopied bool
+ if err = s.store.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM demo_claim_progress WHERE operation_id=? AND copied=1)`, op.ID).Scan(&artifactCopied); err != nil {
+ return err
+ }
+ if artifactCopied && (op.Version != ptr.Version || op.ArtifactSHA256 != art.SHA256) {
+ return ErrDemoToken
+ }
+ if op.SourceJobID != "" && (op.SourceJobID != selected.ID || op.SourceSHA256 != selected.SourceSHA256 || op.Version != ptr.Version || op.ArtifactSHA256 != art.SHA256) {
return ErrDemoToken
}
op.Version, op.ArtifactSHA256 = ptr.Version, art.SHA256
- _, err = s.store.db.ExecContext(ctx, `UPDATE demo_claim_ops SET version=?,artifact_sha256=? WHERE id=? AND phase='reserved'`, op.Version, op.ArtifactSHA256, op.ID)
+ op.SourceJobID, op.SourceSHA256 = selected.ID, selected.SourceSHA256
+ _, err = s.store.db.ExecContext(ctx, `UPDATE demo_claim_ops SET version=?,artifact_sha256=?,source_job_id=?,source_sha256=? WHERE id=? AND phase='reserved'`, op.Version, op.ArtifactSHA256, op.SourceJobID, op.SourceSHA256, op.ID)
return err
}
func demoClaimSourceMatches(op claimOp, d DemoRow, life *AppLife) bool {
@@ -653,7 +694,7 @@ func (s *Server) commitDemoClaim(ctx context.Context, op claimOp) error {
JOIN accounts c ON c.id=o.account_id
JOIN demo_apps d ON d.demo_id=o.demo_id JOIN apps src ON src.account_id=d.account_id AND src.app=d.app
WHERE o.id=? AND o.phase='verifying' AND o.deadline>? AND o.source_expires_at>?
- AND p.hold_ack=1 AND p.snapshot_sha!='' AND p.phase_until>?
+ AND p.source_copied=1 AND o.source_job_id!='' AND o.source_sha256!='' AND o.source_bytes>0 AND p.hold_ack=1 AND p.snapshot_sha!='' AND p.phase_until>?
AND a.demo_claim_op=o.id AND a.lifetime=o.target_lifetime AND a.deleted_at=0 AND a.expires_at=0 AND a.demo_id='' AND a.restoring=0
AND c.deleted_at=0 AND c.sqid=o.target_sqid AND m.role IN ('owner','member')
AND d.state='anonymous' AND d.purged_at=0 AND d.active_job_id='' AND d.claim_token_hash IS NOT NULL
@@ -671,11 +712,20 @@ func (s *Server) commitDemoClaim(ctx context.Context, op claimOp) error {
if err = reserveDemoMovedCapacity(ctx, tx, nil, time.Now()); err != nil {
return err
}
+ snapshot := claimedSource{Schema: 1, Operation: op.ID, Lifetime: op.Target.Lifetime, Job: op.SourceJobID, SHA256: op.SourceSHA256, Bytes: op.SourceBytes, Version: op.Version, ClaimedAt: time.Now().UTC().Truncate(time.Second)}
+ if !snapshot.valid() {
+ return ErrDemoToken
+ }
+ descriptor, err := json.Marshal(snapshot)
+ if err != nil {
+ return err
+ }
for _, q := range []struct {
sql string
args []any
}{
- {`INSERT INTO demo_claim_commits(operation_id,demo_id,committed_at) VALUES(?,?,?)`, []any{op.ID, op.DemoID, time.Now().Unix()}},
+ {`UPDATE apps SET claimed_source=? WHERE account_id=? AND app=? AND demo_claim_op=?`, []any{string(descriptor), op.Target.AccountID, op.Target.App, op.ID}},
+ {`INSERT INTO demo_claim_commits(operation_id,demo_id,committed_at) VALUES(?,?,?)`, []any{op.ID, op.DemoID, snapshot.ClaimedAt.Unix()}},
{`UPDATE demo_claim_ops SET phase='committed' WHERE id=?`, []any{op.ID}},
{`INSERT INTO demo_spent_tokens(hash,reason,spent_at) SELECT claim_token_hash,'kept',? FROM demo_apps WHERE demo_id=? AND claim_token_hash IS NOT NULL`, []any{time.Now().Unix(), op.DemoID}},
{`UPDATE demo_apps SET claim_token_hash=NULL WHERE demo_id=?`, []any{op.DemoID}},
diff --git a/internal/console/demo_claim_transfer_test.go b/internal/console/demo_claim_transfer_test.go
index e6dba1560..90db78a27 100644
--- a/internal/console/demo_claim_transfer_test.go
+++ b/internal/console/demo_claim_transfer_test.go
@@ -19,6 +19,7 @@ import (
"time"
lsfile "github.com/benbjohnson/litestream/file"
+ "github.com/carlosframework/platform/internal/demobuild"
"github.com/carlosframework/platform/internal/democlaim"
"github.com/carlosframework/platform/internal/provision"
"github.com/carlosframework/platform/internal/release"
@@ -26,6 +27,10 @@ import (
)
func claimTransferFixture(t *testing.T, flowOut ...*string) (*Server, claimOp, []byte) {
+ t.Helper()
+ return claimTransferFixtureBefore(t, nil, flowOut...)
+}
+func claimTransferFixtureBefore(t *testing.T, before func(*Server, DemoRow, demobuild.Job, demobuild.Result), flowOut ...*string) (*Server, claimOp, []byte) {
t.Helper()
s, d, j, out := demoPublishFixture(t)
s.demoClaimTestEnabled = true
@@ -40,6 +45,14 @@ func claimTransferFixture(t *testing.T, flowOut ...*string) (*Server, claimOp, [
if _, err := s.store.db.Exec(`UPDATE demo_apps SET active_job_id='' WHERE demo_id=?`, d.ID); err != nil {
t.Fatal(err)
}
+ if before != nil {
+ before(s, d, j, out)
+ var err error
+ d, err = s.store.demoByID(t.Context(), d.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
raw, _ := randomToken()
if len(flowOut) > 0 {
*flowOut[0] = raw
diff --git a/internal/console/demo_claim_ux_test.go b/internal/console/demo_claim_ux_test.go
index 86dc45dd9..cef83bb9f 100644
--- a/internal/console/demo_claim_ux_test.go
+++ b/internal/console/demo_claim_ux_test.go
@@ -43,7 +43,7 @@ func TestDemoClaimUXProductionPages(t *testing.T) {
t.Error("ticket lost after selection")
}
if phase == "done" {
- for _, want := range []string{"Open your app", "Keep building with your agent", `<details class="claim-command">`, `data-state="claimed"`} {
+ for _, want := range []string{"Open your app", "Still in the chat where you built it?", "No saved source for this app.", `data-state="claimed"`} {
if !strings.Contains(body, want) {
t.Errorf("result missing %q", want)
}
diff --git a/internal/console/demo_jobs_test.go b/internal/console/demo_jobs_test.go
index 35642151a..737881514 100644
--- a/internal/console/demo_jobs_test.go
+++ b/internal/console/demo_jobs_test.go
@@ -71,8 +71,16 @@ func (s *demoCountingStore) Put(ctx context.Context, key string, b []byte, tag s
}
return s.Store.Put(ctx, key, b, tag)
}
-func demoJobSource() demobuild.Source {
- b := []byte("validated test source")
+func demoJobSource(extra ...string) demobuild.Source {
+ var buf bytes.Buffer
+ gz := gzip.NewWriter(&buf)
+ tw := tar.NewWriter(gz)
+ body := []byte("package main\nfunc main() {}\n" + strings.Join(extra, ""))
+ _ = tw.WriteHeader(&tar.Header{Name: "main.go", Mode: 0600, Size: int64(len(body))})
+ _, _ = tw.Write(body)
+ _ = tw.Close()
+ _ = gz.Close()
+ b := buf.Bytes()
hash := sha256.Sum256(b)
return demobuild.Source{Archive: b, SHA256: hex.EncodeToString(hash[:])}
}
diff --git a/internal/console/server.go b/internal/console/server.go
index bb4db0a20..42670a55c 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -998,6 +998,7 @@ type Config struct {
// Server is the console's http.Handler.
type Server struct {
+ sourceDownloads sourceDownloads
haPools map[string][]string
haScopeInvalid bool
capacityStart sync.Once
@@ -2047,6 +2048,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
s.registerRoute("GET /a/{sqid}/apps/new", s.handleNewAppForm)
s.registerRoute("POST /a/{sqid}/apps/new", s.handleNewApp)
s.registerRoute("POST /a/{sqid}/apps/new/region", s.handleNewAppRegion)
+ s.registerRoute("GET /a/{sqid}/apps/{app}/source", s.handleBrowserAppSource)
s.registerRoute("GET /a/{sqid}/apps/{app}", s.handleApp)
s.registerRoute("GET /a/{sqid}/apps/{app}/index", s.handleAppIndex)
s.registerRoute("GET /a/{sqid}/apps/{app}/releases", s.handleAppReleases)
@@ -2450,7 +2452,8 @@ func normalizeHost(host string) string {
// page is the one bag every template reads from; unused fields are ignored.
type page struct {
- RegionPicker *regionPickerView // new-app page: nil = no picker
+ HasClaimedSource bool
+ RegionPicker *regionPickerView // new-app page: nil = no picker
// NewAppAnalytics is the new-app page's analytics checkbox: nil = no
// checkbox, and the app follows the account (analyticsonramp.go).
NewAppAnalytics *newAppAnalyticsView
@@ -4455,6 +4458,9 @@ func (s *Server) appPage(w http.ResponseWriter, r *http.Request, tab string) (pa
p := s.accountPage(w, r, addr, raw, acct, role)
p.Title = app
p.AppName = app
+ if role == RoleOwner || role == RoleMember {
+ p.HasClaimedSource, _ = s.store.hasClaimedSource(acct.ID, app)
+ }
p.ActiveTab = tab
p.ActiveNav = "apps"
p.Detail = &views[0]
diff --git a/internal/console/static/demo_claim.js b/internal/console/static/demo_claim.js
index c3a0fef57..d0239811b 100644
--- a/internal/console/static/demo_claim.js
+++ b/internal/console/static/demo_claim.js
@@ -55,20 +55,23 @@
HTMLFormElement.prototype.submit.call(form);
});
}
- for (const copy of document.querySelectorAll("[data-copy-target]")) {
- const command = document.getElementById(copy.dataset.copyTarget);
- if (!command || typeof navigator.clipboard?.writeText !== "function") continue;
- copy.hidden = false;
- let reset;
- copy.addEventListener("click", async () => {
- try {
- await navigator.clipboard.writeText(command.textContent);
- copy.textContent = copy.dataset.copied;
- clearTimeout(reset);
- reset = setTimeout(() => { copy.textContent = copy.dataset.copy; }, 2000);
- } catch (_) { copy.hidden = true; }
- });
- }
+ const bindCopies = root => {
+ for (const copy of root.querySelectorAll("[data-copy-target]")) {
+ const command = document.getElementById(copy.dataset.copyTarget);
+ if (!command || typeof navigator.clipboard?.writeText !== "function") continue;
+ copy.hidden = false;
+ let reset;
+ copy.addEventListener("click", async () => {
+ try {
+ await navigator.clipboard.writeText(command.textContent);
+ copy.textContent = copy.dataset.copied;
+ clearTimeout(reset);
+ reset = setTimeout(() => { copy.textContent = copy.dataset.copy; }, 2000);
+ } catch (_) { copy.hidden = true; }
+ });
+ }
+ };
+ bindCopies(document);
const choice = document.querySelector('form[action="/demo/claim/select"]');
if (choice) {
const radios = choice.querySelectorAll('input[type="radio"]:not(:disabled)');
@@ -146,7 +149,18 @@
// Never advance beyond the server's last reported stage.
while (stage < target) { await hold(); await setStage(stage + 1); }
};
- const finish = result => {
+ const finish = async result => {
+ const response = await fetch("/demo/claim", {credentials:"same-origin", mode:"same-origin", cache:"no-store", signal:AbortSignal.timeout(10000)});
+ if (!response.ok) throw new Error();
+ const page = new DOMParser().parseFromString(await response.text(), "text/html");
+ if (page.getElementById("claim")?.dataset.state !== "claimed") throw new Error();
+ const next = page.querySelector(".claim-next");
+ const previous = claim.querySelector(".claim-next");
+ if (next) {
+ if (previous) previous.replaceWith(next);
+ else document.getElementById("claim-finished").append(next);
+ bindCopies(next);
+ } else previous?.remove();
const url = new URL(result.url);
if (url.protocol !== "https:" || url.username || url.password) throw new Error();
const finished = document.getElementById("claim-finished");
@@ -185,7 +199,7 @@
if (result.state === "aborted") return;
} else {
await advance(result.step);
- if (result.state === "claimed") { await hold(); finish(result); return; }
+ if (result.state === "claimed") { await hold(); await finish(result); return; }
}
failures = 0;
} catch (_) {
diff --git a/internal/console/store.go b/internal/console/store.go
index ad99449b1..7803e63d6 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -2399,6 +2399,13 @@ func (s *Store) moveApp(app string, from, to int64) error {
if atSrc == 0 {
return fmt.Errorf("console: account %d does not claim %q", from, app)
}
+ var savedSource string
+ if err := tx.QueryRow(`SELECT claimed_source FROM apps WHERE account_id=? AND app=?`, from, app).Scan(&savedSource); err != nil {
+ return err
+ }
+ if savedSource != "" {
+ return errors.New(sourceMoveRefused)
+ }
var srcExpires int64
if err := tx.QueryRow(`SELECT expires_at FROM apps WHERE app = ? AND account_id = ?`, app, from).Scan(&srcExpires); err != nil {
return err
@@ -2543,14 +2550,18 @@ func (s *Store) renameAppIn(accountID int64, from, to string, undo bool) error {
return err
}
defer tx.Rollback()
+ var savedSource string
var createdAt, expiresAt int64
- err = tx.QueryRow(`SELECT created_at, expires_at FROM apps WHERE account_id = ? AND app = ? AND deleted_at = 0`,
- accountID, from).Scan(&createdAt, &expiresAt)
+ err = tx.QueryRow(`SELECT created_at, expires_at, claimed_source FROM apps WHERE account_id = ? AND app = ? AND deleted_at = 0`,
+ accountID, from).Scan(&createdAt, &expiresAt, &savedSource)
if err == sql.ErrNoRows {
return fmt.Errorf("console: this account does not claim %q", from)
} else if err != nil {
return err
}
+ if savedSource != "" {
+ return errors.New("This app has shipped — its name is baked into its releases' bucket keys, so renaming it is not supported. Create a new app and ship there instead.")
+ }
if expiresAt > 0 {
return ErrTemporaryApp
}
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go
index 3fa8c1bab..ab86d009e 100644
--- a/internal/console/svcroutes_test.go
+++ b/internal/console/svcroutes_test.go
@@ -100,6 +100,9 @@ var (
// Only an equality catches both; "no empty Sets" catches neither, and "these
// are empty" catches only the first.
var closedDoors = []string{
+ // Claimed app source: people (owners and members) only; no service or
+ // app credential may fetch an app's source.
+ "GET /api/cli/apps/{account}/{app}/source",
"GET /api/cli/fleets/{account}/{fleet}",
"GET /api/cli/system/managed-fleets",
"PUT /api/cli/system/managed-fleets",
@@ -1144,8 +1147,11 @@ func TestServiceRoleReachesTheDoorItNames(t *testing.T) {
//
// The credential holds ADMIN, the role most likely to slip through, and it is
// account-scoped so no app binding can be doing the refusing instead of the
-// role gate. Every answer must be the closed-door 403, whose body is the same
-// bytes at every door (TestClosedDoorRefusalIsItsOwnMessage).
+// role gate. Answers use the closed-door 403, whose body is constant
+// (TestClosedDoorRefusalIsItsOwnMessage), except for the claimed source door.
+// Its admission wrapper requires the same 404 for service/app credentials
+// and non-members; TestAppSourceDoors proves that no
+// storage read precedes these refusals. The walk checks its exact 404 too.
func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) {
fx := newConsoleFixture(t)
tok := serviceToken(t, fx.st, OpsAccountID, "root", "", svcrole.Admin)
@@ -1178,16 +1184,22 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) {
body = `{}`
}
status, _, out := rawReq(t, method, fx.ts.URL+u, tok, body)
- if status != http.StatusForbidden {
- t.Errorf("%s = %d %s, want the closed-door 403", pattern, status, out)
- }
- if !strings.Contains(out, "closed to service credentials") {
- t.Errorf("%s body = %s, want the closed-door refusal", pattern, out)
+ if pattern == "GET /api/cli/apps/{account}/{app}/source" {
+ if status != http.StatusNotFound || out != "404 page not found\n" {
+ t.Errorf("%s = %d %q, want the claimed source door's identical 404", pattern, status, out)
+ }
+ } else {
+ if status != http.StatusForbidden {
+ t.Errorf("%s = %d %s, want the closed-door 403", pattern, status, out)
+ }
+ if !strings.Contains(out, "closed to service credentials") {
+ t.Errorf("%s body = %s, want the closed-door refusal", pattern, out)
+ }
}
seen++
}
- if seen != len(closedDoors) || seen != 86 {
- t.Errorf("walked %d closed doors, want all %d (and 86 today: three domain purchase doors, two managed admission doors, the fleet show door, two managed configuration doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, the copy count, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, the PDF status door, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)",
+ if seen != len(closedDoors) || seen != 87 {
+ t.Errorf("walked %d closed doors, want all %d (and 87 today: three domain purchase doors, two managed admission doors, the fleet show door, two managed configuration doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, the copy count, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, the PDF status door, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, the billing house door, and the claimed source door)",
seen, len(closedDoors))
}
}
diff --git a/internal/console/templates/app_overview.html b/internal/console/templates/app_overview.html
index 5436d95ff..df7a9df6f 100644
--- a/internal/console/templates/app_overview.html
+++ b/internal/console/templates/app_overview.html
@@ -2,6 +2,8 @@
{{if .Flash}}<p class="banner">{{.Flash}}</p>{{end}}
{{if .FlashErr}}<p class="banner error">{{.FlashErr}}</p>{{end}}
{{template "appnav" .}}
+{{if .HasClaimedSource}}<section class="card"><p><a class="btn btn-secondary" href="/a/{{.Account.Sqid}}/apps/{{.AppName}}/source">Download source</a></p><p>Download the source saved when you kept this app. Later deployments do not update it.</p></section>{{end}}
+
{{template "accountreviewbanner" .}}
{{with .Overview}}
<section class="pagehead" aria-label="App status">
diff --git a/internal/console/templates/demo_claim.html b/internal/console/templates/demo_claim.html
index e027dedf4..a22f78dab 100644
--- a/internal/console/templates/demo_claim.html
+++ b/internal/console/templates/demo_claim.html
@@ -173,12 +173,15 @@
<div id="claim-finished"{{if ne .State "claimed"}} hidden{{end}}>
<p>{{.Copy.completeDetail}}</p>
<p class="claim-result"><a class="btn claim-open" href="{{.URL}}" rel="noreferrer">{{.Copy.open}}</a></p><p class="claim-result-address">{{.URL}}</p>
-<section class="claim-next"><h2>{{.Copy.keepGoing}}</h2><h3>{{.Copy.agentHeading}}</h3><p>{{.Copy.agentDetail}}</p>
-<div class="claim-paste"><code id="claim-agent-command">{{.Copy.agentLine}}</code><button class="btn-sm btn-secondary" type="button" data-copy-target="claim-agent-command" data-copy="{{.Copy.copy}}" data-copied="{{.Copy.copied}}" hidden>{{.Copy.copy}}</button></div>
-<details class="claim-command"><summary>{{.Copy.cliHeading}}</summary>
-<p>{{.Copy.cliCommandLabel}}</p><pre><code id="claim-cli-command">{{.Copy.next}}</code></pre>
-<button id="claim-copy" data-copy-target="claim-cli-command" class="btn-sm btn-secondary" type="button" data-copy="{{.Copy.copy}}" data-copied="{{.Copy.copied}}" aria-live="polite" hidden>{{.Copy.copy}}</button>
-</details><p class="claim-detail">{{.Copy.oldAddress}}</p></section></div>
+{{if .AccountSqid}}<section class="claim-next"><h2>{{.Copy.keepGoing}}</h2>
+{{if .AccountSqid}}<h3>{{.Copy.sameChat}}</h3><p>{{.Copy.sameChatLine}}</p>
+{{if .SourceSteps}}<h3>{{.Copy.agentHeading}}</h3><p>{{.Copy.agentDetail}}</p>
+<div class="claim-paste"><code id="claim-agent-command">{{.Copy.agentLine}}</code><button class="btn-sm btn-secondary" type="button" data-copy-target="claim-agent-command" data-copy="{{.Copy.copy}}" data-copied="{{.Copy.copied}}" hidden>{{.Copy.copy}}</button></div>{{end}}
+<p class="claim-detail">{{.Copy.sourceNote}}</p>
+{{if .SourceSteps}}<details class="claim-command"><summary>{{.Copy.cliHeading}}</summary>
+{{range .SourceSteps}}<h3>{{.Label}}</h3><p>{{.Instruction}}</p><pre><code id="{{.ID}}">{{.Command}}</code></pre>
+<button data-copy-target="{{.ID}}" class="btn-sm btn-secondary" type="button" data-copy="{{$.Copy.copy}}" data-copied="{{$.Copy.copied}}" aria-live="polite" hidden>{{$.Copy.copy}}</button>{{end}}
+</details>{{end}}{{end}}<p class="claim-detail">{{.Copy.oldAddress}}</p></section>{{end}}</div>
{{end}}
{{if and .HasIntent .CanClaim}}
{{if .Address}}
diff --git a/internal/console/testdata/app_source_browser.mjs b/internal/console/testdata/app_source_browser.mjs
new file mode 100644
index 000000000..ea0a1869e
--- /dev/null
+++ b/internal/console/testdata/app_source_browser.mjs
@@ -0,0 +1,83 @@
+import {spawn} from 'node:child_process';
+import assert from 'node:assert/strict';
+import {writeFile} from 'node:fs/promises';
+import {captureClaim, watchClaimCSP} from './demo_claim_layout.mjs';
+
+const [binary, profile, origin, cookie, token, appPath, screenshots] = process.argv.slice(2);
+const chrome = spawn(binary, ['--headless', '--no-sandbox', '--disable-gpu',
+ '--disable-dev-shm-usage', '--disable-background-networking', '--disable-component-update',
+ '--disable-default-apps', '--disable-extensions', '--disable-sync', '--no-proxy-server',
+ '--no-first-run', '--no-default-browser-check', '--remote-debugging-pipe',
+ '--user-data-dir=' + profile], {stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe']});
+let sequence = 0, buffered = '', session;
+const pending = new Map();
+chrome.stdio[4].on('data', bytes => {
+ buffered += bytes.toString();
+ let end;
+ while ((end = buffered.indexOf('\0')) !== -1) {
+ const message = JSON.parse(buffered.slice(0, end));
+ buffered = buffered.slice(end + 1);
+ const resolve = pending.get(message.id);
+ if (resolve) { pending.delete(message.id); resolve(message); }
+ }
+});
+async function call(method, params = {}, attached = true) {
+ const id = ++sequence;
+ const result = new Promise(resolve => pending.set(id, resolve));
+ chrome.stdio[3].write(JSON.stringify({id, method, params, ...(attached && session ? {sessionId:session} : {})}) + '\0');
+ const message = await result;
+ assert.equal(message.error, undefined, JSON.stringify(message.error));
+ return message.result;
+}
+async function evaluate(expression) {
+ const result = await call('Runtime.evaluate', {expression, returnByValue:true});
+ assert.equal(result.exceptionDetails, undefined);
+ return result.result.value;
+}
+async function until(expression) {
+ for (let i = 0; i < 150; i++) {
+ if (await evaluate(expression)) return;
+ await new Promise(resolve => setTimeout(resolve, 100));
+ }
+ throw Error('browser_condition_timeout: ' + await evaluate('JSON.stringify({text:document.body.innerText,email:document.getElementById("email")?.value,focus:document.activeElement.tagName,valid:document.querySelector("form")?.checkValidity()})'));
+}
+async function key(key, code, number) {
+ await call('Input.dispatchKeyEvent', {type:key === 'Enter' ? 'keyDown' : 'rawKeyDown', key, code, windowsVirtualKeyCode:number, ...(key === 'Enter' ? {text:'\r', unmodifiedText:'\r'} : {})});
+ await call('Input.dispatchKeyEvent', {type:'keyUp', key, code, windowsVirtualKeyCode:number});
+}
+
+const timer=setTimeout(()=>{chrome.kill('SIGKILL');process.exitCode=1},80000);
+try {
+ const created=await call('Target.createTarget',{url:'about:blank'},false);
+ session=(await call('Target.attachToTarget',{targetId:created.targetId,flatten:true},false)).sessionId;
+ await call('Page.enable');
+ await call('Page.addScriptToEvaluateOnNewDocument',{source:watchClaimCSP});
+ await call('Browser.grantPermissions',{origin,permissions:['clipboardReadWrite','clipboardSanitizedWrite']},false);
+ await call('Network.setCookie',{name:'carlos_demo_claim_flow',value:cookie,url:origin,path:'/demo/claim'});
+ await call('Network.setCookie',{name:'carlos_console_session',value:token,url:origin,path:'/'});
+ await call('Page.navigate',{url:origin+'/demo/claim'});
+ await until('document.readyState === "complete" && document.querySelector(".claim-next [data-copy-target]")?.hidden === false');
+ assert.equal(await evaluate('document.querySelector(".claim-command").open'),false);
+ await captureClaim(call,evaluate,screenshots,'done-closed');
+ await evaluate('document.querySelector(".claim-command").open=true');
+ await captureClaim(call,evaluate,screenshots,'done-open');
+ const ids=await evaluate('Array.from(document.querySelectorAll(".claim-next [data-copy-target]"),b=>b.dataset.copyTarget)');
+ assert.equal(ids.length,4);
+ for (const id of ids) {
+ const expected=await evaluate(`document.getElementById(${JSON.stringify(id)}).textContent`);
+ await call('Runtime.evaluate',{expression:`document.querySelector('[data-copy-target="${id}"]').click()`,userGesture:true});
+ await new Promise(resolve=>setTimeout(resolve,100));
+ const copied=await call('Runtime.evaluate',{expression:'navigator.clipboard.readText()',awaitPromise:true,returnByValue:true,userGesture:true});
+ assert.equal(copied.result.value,expected);
+ }
+ await call('Page.navigate',{url:origin+appPath});
+ await until('document.readyState === "complete" && Array.from(document.querySelectorAll("a")).some(a=>a.textContent==="Download source")');
+ assert.equal(await evaluate('Array.from(document.querySelectorAll("a")).find(a=>a.textContent==="Download source").getAttribute("href")'),appPath+'/source');
+ await captureClaim(call,evaluate,screenshots,'app-source');
+ assert.deepEqual(await evaluate('window.claimCSPViolations'),[]);
+ process.stdout.write('12 screenshots; four Copy buttons; zero CSP violations\n');
+} finally {
+ clearTimeout(timer);
+ await call('Browser.close',{},false).catch(()=>{});
+ chrome.kill();
+}
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index f04729465..e5b489801 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -42,6 +42,7 @@ route GET /a/{sqid}/apps/{app}/releases
route GET /a/{sqid}/apps/{app}/settings
route GET /a/{sqid}/apps/{app}/settings/index
route GET /a/{sqid}/apps/{app}/settings/{section}
+route GET /a/{sqid}/apps/{app}/source
route GET /a/{sqid}/billing
route GET /a/{sqid}/billing/continue
route GET /a/{sqid}/billing/done
@@ -109,6 +110,7 @@ route GET /api/cli/apps/{account}/{app}/routes
route GET /api/cli/apps/{account}/{app}/schedules
route GET /api/cli/apps/{account}/{app}/sidecars
route GET /api/cli/apps/{account}/{app}/sidecars/{name}
+route GET /api/cli/apps/{account}/{app}/source
route GET /api/cli/apps/{account}/{app}/store
route GET /api/cli/apps/{account}/{app}/store/scan
route GET /api/cli/apps/{account}/{app}/store/scan/object
diff --git a/internal/console/testdata/demo_claim_browser.mjs b/internal/console/testdata/demo_claim_browser.mjs
index c22c0c43f..91953663a 100644
--- a/internal/console/testdata/demo_claim_browser.mjs
+++ b/internal/console/testdata/demo_claim_browser.mjs
@@ -166,7 +166,7 @@ async function runUX(scenes) {
await call('Page.reload');
await until('document.readyState === "complete" && document.getElementById("claim")?.dataset.state === "claimed"');
assert.equal(await evaluate('document.getElementById("claim").classList.contains("is-celebrating")'),false);
- assert.equal(await evaluate('document.querySelector(".claim-command").open'),false);
+ assert.equal(await evaluate('document.querySelector(".claim-command")?.open ?? false'),false);
}
await captureClaim(call,evaluate,screenshots,scene.Name,[390,1280]);
if (scene.Name === 'fast') await liveMotion(scene);
diff --git a/internal/console/testdata/demo_claim_resume_browser.mjs b/internal/console/testdata/demo_claim_resume_browser.mjs
index 016410fb3..0de1d29b7 100644
--- a/internal/console/testdata/demo_claim_resume_browser.mjs
+++ b/internal/console/testdata/demo_claim_resume_browser.mjs
@@ -186,24 +186,24 @@ try {
await evaluate('document.querySelector(".claim-command").open = true');
assert.equal(security.length,0,JSON.stringify(security));
process.stdout.write('progress: polled to step 2 and done automatically; no CSP violations\n');
- assert.equal(await evaluate('document.getElementById("claim-copy").hidden'), false);
- await evaluate('document.getElementById("claim-copy").click()');
- await until('document.getElementById("claim-copy").textContent === "Copied"');
- assert.equal(await evaluate('window.claimClipboard'), 'carlos auth login --console '+target);
- await until('document.getElementById("claim-copy").textContent === "Copy"');
+ assert.equal(await evaluate('document.querySelector("[data-copy-target=claim-cli-command]").hidden'), false);
+ await evaluate('document.querySelector("[data-copy-target=claim-cli-command]").click()');
+ await until('document.querySelector("[data-copy-target=claim-cli-command]").textContent === "Copied"');
+ assert.equal(await evaluate('window.claimClipboard'), "carlos auth login --console '"+target+"'");
+ await until('document.querySelector("[data-copy-target=claim-cli-command]").textContent === "Copy"');
await call('Page.removeScriptToEvaluateOnNewDocument', {identifier:clipboardStub.identifier});
const noClipboard = await call('Page.addScriptToEvaluateOnNewDocument', {source:
"Object.defineProperty(navigator, 'clipboard', {value:undefined})"});
await call('Page.navigate', {url:target+'/demo/claim'});
- await until('document.readyState === "complete" && !!document.getElementById("claim-copy")');
- assert.equal(await evaluate('document.getElementById("claim-copy").getBoundingClientRect().height'), 0);
- assert.equal(await evaluate('document.getElementById("claim-cli-command").textContent'), 'carlos auth login --console '+target);
+ await until('document.readyState === "complete" && !!document.querySelector("[data-copy-target=claim-cli-command]")');
+ assert.equal(await evaluate('document.querySelector("[data-copy-target=claim-cli-command]").getBoundingClientRect().height'), 0);
+ assert.equal(await evaluate('document.getElementById("claim-cli-command").textContent'), "carlos auth login --console '"+target+"'");
await call('Page.removeScriptToEvaluateOnNewDocument', {identifier:noClipboard.identifier});
await call('Network.setBlockedURLs', {urls:['*demo_claim.js*']});
await call('Page.navigate', {url:target+'/demo/claim'});
- await until('document.readyState === "complete" && !!document.getElementById("claim-copy")');
- assert.equal(await evaluate('document.getElementById("claim-copy").getBoundingClientRect().height'), 0);
- assert.equal(await evaluate('document.getElementById("claim-cli-command").textContent'), 'carlos auth login --console '+target);
+ await until('document.readyState === "complete" && !!document.querySelector("[data-copy-target=claim-cli-command]")');
+ assert.equal(await evaluate('document.querySelector("[data-copy-target=claim-cli-command]").getBoundingClientRect().height'), 0);
+ assert.equal(await evaluate('document.getElementById("claim-cli-command").textContent'), "carlos auth login --console '"+target+"'");
await call('Network.setBlockedURLs', {urls:[]});
assert.deepEqual(await evaluate('window.claimCSPViolations'), []);
process.stdout.write('clipboard: copied command, reset label, hidden without clipboard or script\n');
diff --git a/internal/console/testdata/perf-budgets.txt b/internal/console/testdata/perf-budgets.txt
index 35ca3fbc7..d277fb8ba 100644
--- a/internal/console/testdata/perf-budgets.txt
+++ b/internal/console/testdata/perf-budgets.txt
@@ -35,6 +35,7 @@
GET /auth/callback skip: needs a live OAuth state and makes a token POST to Keymail
GET /auth/stepup/callback skip: needs a live OAuth state and makes a token POST to Keymail
GET /auth/cli/whoami skip: a bearer-token JSON door, not a screen; timed in production
+GET /a/{sqid}/apps/{app}/source skip: an authenticated archive download, not a screen; covered by TestAppSource
GET /fleet/protection/data skip: the operator Protection page's JSON door, not a screen; the page makes the same reads (protectionview.go)
GET /static/{hash}/{file...} skip: static asset, not a screen; consolePerfSkip leaves it unmeasured
/fleet/architecture/refresh skip: POST-only door; a GET answers 404 on its first line by design (archpage.go)
diff --git a/internal/demobuild/source.go b/internal/demobuild/source.go
index 8debef255..bcbfc5927 100644
--- a/internal/demobuild/source.go
+++ b/internal/demobuild/source.go
@@ -44,18 +44,27 @@ type SourceFile struct {
SHA256 string
}
+func ValidateArchive(r io.Reader) (Source, error) {
+ src, _, err := validateSource(r, Lock{}, true)
+ return src, err
+}
+
// ValidateSource never extracts files or executes tools. Archive contains the
// accepted original gzip bytes. Files is a sorted inventory of regular files;
// consumers must revalidate stored bytes before extracting in their sandbox.
// Extraction must use fixed safe modes and ownership, ignoring tar metadata.
func ValidateSource(r io.Reader, lock Lock) (Source, []Diagnostic, error) {
+ return validateSource(r, lock, false)
+}
+
+func validateSource(r io.Reader, lock Lock, archiveOnly bool) (Source, []Diagnostic, error) {
refuse := func(file string, line int) (Source, []Diagnostic, error) {
if !safeDiagnosticFile(file) {
file, line = "", 0
}
return Source{}, []Diagnostic{{File: file, Line: line, Message: "DEMO-SOURCE"}}, ErrSource
}
- if err := lock.validate(); err != nil {
+ if err := lock.validate(); !archiveOnly && err != nil {
return Source{}, nil, ErrLock
}
original, err := io.ReadAll(io.LimitReader(r, demo.SourceMaxBytes+1))
@@ -101,7 +110,7 @@ func ValidateSource(r io.Reader, lock Lock) (Source, []Diagnostic, error) {
return refuse(name, 0)
}
isDir := h.Typeflag == tar.TypeDir
- if forbiddenFile(name, isDir) {
+ if !archiveOnly && forbiddenFile(name, isDir) {
return refuse(name, 0)
}
entries[name] = isDir
@@ -129,6 +138,10 @@ func ValidateSource(r io.Reader, lock Lock) (Source, []Diagnostic, error) {
}
}
}
+ if archiveOnly {
+ digest := sha256.Sum256(original)
+ return Source{Archive: original, SHA256: hex.EncodeToString(digest[:])}, nil, nil
+ }
if !validModule(files["go.mod"], files["go.sum"], lock) {
return refuse("go.mod", 0)
}
diff --git a/internal/demobuild/source_test.go b/internal/demobuild/source_test.go
index a4d4d0dbc..40c072664 100644
--- a/internal/demobuild/source_test.go
+++ b/internal/demobuild/source_test.go
@@ -12,6 +12,7 @@ import (
"slices"
"strings"
"testing"
+ "time"
"github.com/carlosframework/platform/internal/demo"
)
@@ -367,3 +368,76 @@ func TestDemoImports(t *testing.T) {
}
})
}
+
+func TestClaimedSourceArchive(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ entries []archiveEntry
+ ok bool
+ }{
+ {"no-current-lock", []archiveEntry{{"go.mod", "module old.example/app\ngo 1.22\n", tar.TypeReg}, {".env", "TOKEN=exact-source-secret", tar.TypeReg}}, true},
+ {"traversal", []archiveEntry{{"../escape", "bad", tar.TypeReg}}, false},
+ {"absolute", []archiveEntry{{"/escape", "bad", tar.TypeReg}}, false},
+ {"windows", []archiveEntry{{"C:/escape", "bad", tar.TypeReg}}, false},
+ {"link", []archiveEntry{{"link", "", tar.TypeSymlink}}, false},
+ {"hardlink", []archiveEntry{{"link", "", tar.TypeLink}}, false},
+ {"fifo", []archiveEntry{{"fifo", "", tar.TypeFifo}}, false},
+ {"duplicate", []archiveEntry{{"file", "a", tar.TypeReg}, {"file", "b", tar.TypeReg}}, false},
+ {"parent-file", []archiveEntry{{"file", "a", tar.TypeReg}, {"file/child", "b", tar.TypeReg}}, false},
+ {"file-cap", []archiveEntry{{"big", strings.Repeat("x", FileMaxBytes+1), tar.TypeReg}}, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ b := gzipBytes(t, tarBytes(t, tc.entries))
+ src, err := ValidateArchive(bytes.NewReader(b))
+ if (err == nil) != tc.ok {
+ t.Fatal(err)
+ }
+ if tc.ok && !bytes.Equal(src.Archive, b) {
+ t.Fatal("archive changed")
+ }
+ })
+ }
+ b := gzipBytes(t, tarBytes(t, []archiveEntry{{"a", "b", tar.TypeReg}}))
+ for _, bad := range [][]byte{append(append([]byte{}, b...), b...), append(append([]byte{}, b...), 1), b[:len(b)-1]} {
+ if _, err := ValidateArchive(bytes.NewReader(bad)); err == nil {
+ t.Fatal("gzip framing accepted")
+ }
+ }
+}
+
+func TestClaimedSourcePublishedStructure(t *testing.T) {
+ for _, header := range []gzip.Header{{}, {Extra: []byte("legal extra")}, {Name: "source.tar", Comment: "source", ModTime: time.Unix(123, 0), OS: 3}, {Extra: []byte("extra"), Name: "source.tar", Comment: "source"}} {
+ var b bytes.Buffer
+ gz := gzip.NewWriter(&b)
+ gz.Header = header
+ if _, err := gz.Write(tarBytes(t, starter(t))); err != nil {
+ t.Fatal(err)
+ }
+ if err := gz.Close(); err != nil {
+ t.Fatal(err)
+ }
+ published, _, err := ValidateSource(bytes.NewReader(b.Bytes()), testLock(t))
+ if err != nil {
+ t.Fatal("publish", err)
+ }
+ claimed, err := ValidateArchive(bytes.NewReader(published.Archive))
+ if err != nil || claimed.SHA256 != published.SHA256 || !bytes.Equal(claimed.Archive, published.Archive) {
+ t.Errorf("published gzip header %+v rejected or changed: %v", header, err)
+ }
+ }
+}
+
+func TestClaimedSourceIgnoresPublishFilePolicy(t *testing.T) {
+ for _, name := range []string{"vendor/old.go", ".git/config", "go.work", "nested/go.mod", "native.c"} {
+ t.Run(name, func(t *testing.T) {
+ b := gzipBytes(t, tarBytes(t, append(starter(t), archiveEntry{name, "historical source", tar.TypeReg})))
+ if _, _, err := ValidateSource(bytes.NewReader(b), testLock(t)); err == nil {
+ t.Fatal("publish policy not exercised")
+ }
+ got, err := ValidateArchive(bytes.NewReader(b))
+ if err != nil || !bytes.Equal(got.Archive, b) {
+ t.Fatal("historical snapshot rejected by publish policy", err)
+ }
+ })
+ }
+}
diff --git a/internal/provision/claim_source_census_test.go b/internal/provision/claim_source_census_test.go
new file mode 100644
index 000000000..bca4ac0d9
--- /dev/null
+++ b/internal/provision/claim_source_census_test.go
@@ -0,0 +1,30 @@
+package provision
+
+// The source PUT is create-only at the validated reserved target's
+// source/claims/<operation>/source.tar.gz key. It never writes an instance
+// record. The route registries add person-only source GET doors and retain
+// their existing instance/sidecar registrations. These are author
+// classifications; Opus approved them on #280 (tip 08bf8193). NewServer's
+// digest was re-pinned after 0d64f55f, whose only change there registers the
+// browser source door under the named handleBrowserAppSource (same wrapper).
+func claimSourceWriteCensusInventory() []censusEntry {
+ entries := append([]censusEntry(nil), regionHAG2FixesWriteCensusInventory()...)
+ for _, next := range []censusEntry{
+ {"internal/console/authcli.go", "Server.registerCLIRoutes", "key-site", "lit:instances,lit:sidecars", "0a4379408122d8252e77f108c512c537fea272b830315a5d61354f6e57ce6151"},
+ {"internal/console/server.go", "NewServer", "key-site", "lit:instances", "e47072fc65d5a2ac941b2e19debec95cd9f906a1dd4924918342cdea6c6adbaa"},
+ {"internal/console/app_source.go", "Server.copyDemoClaimSource", "nonrecord", "sel:Put", "d4f17ca3c5009fbef5c419ad5335178868361a409426a861b66180b6e733f36e"},
+ } {
+ found := false
+ for i, old := range entries {
+ if old.File == next.File && old.Unit == next.Unit {
+ entries[i] = next
+ found = true
+ break
+ }
+ }
+ if !found {
+ entries = append(entries, next)
+ }
+ }
+ return entries
+}
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go
index 205059a69..5f3d95215 100644
--- a/internal/provision/plan9_b8_census_test.go
+++ b/internal/provision/plan9_b8_census_test.go
@@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) {
if len(got) < 100 {
t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root)
}
- inventory := regionHAG2FixesWriteCensusInventory()
+ inventory := claimSourceWriteCensusInventory()
problems := append(censusDiff(inventory, got), censusPolicy(inventory)...)
if len(problems) > 0 {
t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n "))
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 8bbf82d75..bca61cb2b 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -119,3 +119,4 @@ plan14-root-reads-region-ha-g3-fixes.tsv cd001bf3a9a8871f12d1ca9cfa0a925760c1fc3
plan14-root-reads-claim-countdown.tsv 5b31785441c6a48ddae93e9f3c0f8962f7983b55d89b3acb90d9a6b505647b36
plan14-root-reads-region-ha-dr2.tsv 7247af7f4de84593d83c6f60c0147d0a04836146197dd60c2ed2bf78919cad22
plan14-root-reads-dr1-left-link.tsv 160744b3062d0ab9a0cb3c7be3a391ae38cf89ffe410ddd5d179e0c3cb509b66
+plan14-root-reads-claim-source.tsv 9cdff432a5de2ffeaa147fdafd6a486c61c27a0c38f77466bddc86b149332c7d
diff --git a/internal/provision/testdata/plan14-root-reads-claim-source.tsv b/internal/provision/testdata/plan14-root-reads-claim-source.tsv
new file mode 100644
index 000000000..323ef293f
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-claim-source.tsv
@@ -0,0 +1,11 @@
+# Census overlay claim-source, written by census-propose (#369). census-ruling-claim-source, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-claim-source.md.
+# 0 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 3 new dispositions: 0 reads re-frozen at their disposition with the claim, 2 new units frozen accepted-legacy, 1 quiet units retired while they read nothing, 0 other.
+@legacy ce662056de8337479a7f03ed10e81e1b05baddd2673bf72330422e4a36f93c03 apps_source.go pullAppSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=New CLI command carlos apps source pull: reads the HTTPS response body from the console (bounded, digest-checked), refuses an existing output path or symlink before any request, writes a CreateTemp file (0600) in the operator-chosen directory and links it into place without overwriting; never extracts or executes the archive. file:CreateTemp@353,file:Lstat@184,file:ReadAll@1211,file:ReadAll@1791 02308bb42402538daf2374f6e6843700e5e71d2dd1434bdeba014ddd371fdac5
+@legacy 87697f10fe185506553dc8bd6b6e5badcf4ba7b44e00327257a0692c3eff1356 internal/demobuild/source.go validateSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=Shared archive validator split out of ValidateSource: reads only the in-memory gzip/tar stream (bounded), rejects traversal, absolute paths, links, special files, duplicates and oversized expansion; the archive-only re-read path skips publish-time file-name exclusions; no filesystem paths opened. file:ReadAll@2025,file:ReadAll@430,file:ReadAll@733 4676f3aecb28adbda6fdb84d909ba2f5448ac3e763a9024a50afc419481d145f
+apps_source.go pullAppSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=New CLI command carlos apps source pull: reads the HTTPS response body from the console (bounded, digest-checked), refuses an existing output path or symlink before any request, writes a CreateTemp file (0600) in the operator-chosen directory and links it into place without overwriting; never extracts or executes the archive. file:CreateTemp@353,file:Lstat@184,file:ReadAll@1211,file:ReadAll@1791 02308bb42402538daf2374f6e6843700e5e71d2dd1434bdeba014ddd371fdac5
+internal/demobuild/source.go validateSource legacy accepted-legacy accepted-legacy;rev3=census-ruling-claim-source;basis=Shared archive validator split out of ValidateSource: reads only the in-memory gzip/tar stream (bounded), rejects traversal, absolute paths, links, special files, duplicates and oversized expansion; the archive-only re-read path skips publish-time file-name exclusions; no filesystem paths opened. file:ReadAll@2025,file:ReadAll@430,file:ReadAll@733 4676f3aecb28adbda6fdb84d909ba2f5448ac3e763a9024a50afc419481d145f
+@remove internal/demobuild/source.go ValidateSource
+@removed internal/demobuild/source.go ValidateSource H3 census-ruling-claim-source;basis=Now a thin wrapper over validateSource with the full publish-time checks; reads nothing itself.
+@coverage . 53a314c86fbc8de278a574d7a54a65a01a7c85629739a50740ec5c31f1e71330
+@coverage internal/demobuild 43b41e2ef861a0bced6f3cc11eaf25ae1949c8d9d8b9961ca768a2c58eeda78d