carlos / platform Public

feat: validate demo source against an offline module lock

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 46207e2fd7a5a770c8f9acc46406fd64f1e155b1 parent 11dadb7
12 files changed, +1,852 −0
  • internal/demobuild/diagnostics.go +113 −0
  • internal/demobuild/diagnostics_test.go +84 −0
  • internal/demobuild/lock.go +207 −0
  • internal/demobuild/lock_generate_test.go +169 −0
  • internal/demobuild/lock_test.go +84 −0
  • internal/demobuild/source.go +418 −0
  • internal/demobuild/source_test.go +326 −0
  • internal/demobuild/stdlib_linux_arm64.txt +175 −0
  • internal/demobuild/testdata/starter/go.mod +34 −0
  • internal/demobuild/testdata/starter/go.sum +56 −0
  • internal/demobuild/testdata/starter/main.go +5 −0
  • internal/demobuild/toolchain.lock.json +181 −0

CI failed — run details

Intent

Human

<task-notification> <task-id>bmycf6e63</task-id> <tool-use-id>toolu_011piMVAZFmPYWg4QXRnFNkw</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/bmycf6e63.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 1 Codex run to finish" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>bj4v1szo3</task-id> <tool-use-id>toolu_019FCTvcbmK6wDsUs2jrBrrZ</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/bj4v1szo3.output</output-file> <status>completed</status> <summary>Background command "Block until Task 1 finishes" completed (exit code 0)</summary> </task-notification>

Human

<task-notification> <task-id>a79226e42addbe7a9</task-id> <tool-use-id>toolu_01UdQDHKBuCTeMVpA2DX8ycs</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/a79226e42addbe7a9.output</output-file> <status>completed</status> <summary>Agent "Review Task 1 (spec + quality)" finished</summary> <note>A task-notification fires each time this agent stops with no live background children of its own. The user can send it another message and resume it, so the same task-id may notify more than once.</note> <result>**Verdict: READY AFTER FIXES** - **P2-1** (`internal/console/apidemo.go:108`): the startup claim scan counts the existing instance catch-all claim key (`domains/*.&lt;parent&gt;.json`) as unreadable. Any deployment with a catch-all claim therefore fails console startup when demos are enabled. - **P2-2** (`internal/console/apidemo.go:240-262`): the status limiter keys on full addresses and refuses every new key once it holds 8,192. One host with an IPv6 /64 can lock all agents out of status. Fix: key IPv6 by /64 and send overflow to a shared bucket. - **P2-3** (`internal/console/apidemo.go:152`): a full live ceiling answers with a 2-second retry, but every retry spends a create attempt. Once Task 5 wires this, agents that obey it will drain the global daily budget and lock everyone out for 24 hours. Fix: a longer retry time, or a read-only ceiling pre-check before spending.</result> <usage><subagent_tokens>137733</subagent_tokens><tool_uses>26</tool_uses><duration_ms>399116</duration_ms></usage> </task-notification>

Human

<task-notification> <task-id>bspmt8s3k</task-id> <tool-use-id>toolu_01BNmgyoBrTnmEtR2zADZ4UF</tool-use-id> <output-file>/home/paulca/.cache/tmp/claude-1001/-home-paulca-amadan-net-carlos-platform/cd1b6de2-ac77-426f-a77d-fc5436969c88/tasks/bspmt8s3k.output</output-file> <status>completed</status> <summary>Background command "Wait for Task 2 Codex run" completed (exit code 0)</summary> </task-notification>

diff --git a/internal/demobuild/diagnostics.go b/internal/demobuild/diagnostics.go
new file mode 100644
index 000000000..8eaa51346
--- /dev/null
+++ b/internal/demobuild/diagnostics.go
@@ -0,0 +1,113 @@
+package demobuild
+
+import (
+ "errors"
+ "regexp"
+ "strconv"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+)
+
+// DraftCopy is DRAFT pending copy review. Callers use copy IDs for platform
+// refusals; tool output is never substituted into these messages.
+var DraftCopy = map[string]string{
+ "DEMO-SOURCE": "The source archive does not match the demo starter requirements.",
+ "DEMO-BUILD": "The demo build could not be completed.",
+}
+
+var (
+ ErrSource = errors.New("DEMO-SOURCE")
+ ErrLock = errors.New("DEMO-BUILD")
+)
+
+func safeDiagnosticFile(file string) bool {
+ return validPath(file) && !secretMessage.MatchString(file)
+}
+
+type Diagnostic struct {
+ File string `json:"file"`
+ Line int `json:"line"`
+ Message string `json:"message"`
+}
+
+const (
+ diagnosticRawMax = 64 * 1024
+ diagnosticMaxBytes = 16 * 1024
+ diagnosticMaxEntries = 50
+)
+
+var (
+ diagnosticLine = regexp.MustCompile(`^([^:]+):([0-9]+):(?:[0-9]+:)?[ \t]*(.*)$`)
+ ansiSequence = regexp.MustCompile("\x1b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\x07\x1b]*(?:\x07|\x1b\\\\)|[@-_])")
+ secretMessage = regexp.MustCompile(`(?i)(bearer\s|token|password|passwd|secret|credential|authorization|[A-Z_][A-Z_0-9]*=|[a-z0-9_+/=-]{32,})`)
+ hostPath = regexp.MustCompile("(?:^|[^[:alnum:]_./~-])(?:/|[A-Za-z]:[\\\\/]|\\.\\.[\\\\/]|~[\\\\/])")
+)
+
+// TrimDiagnostics accepts only relative file:line[:column]:message records.
+// It drops banners and messages containing paths, credentials or environment
+// assignments instead of trying to infer which fragment of them is safe.
+func TrimDiagnostics(raw []byte) []Diagnostic {
+ cut := len(raw) > diagnosticRawMax
+ if cut {
+ raw = raw[:diagnosticRawMax]
+ if i := strings.LastIndexByte(string(raw), '\n'); i >= 0 {
+ raw = raw[:i]
+ } else {
+ return nil
+ }
+ }
+ clean := ansiSequence.ReplaceAllString(strings.ToValidUTF8(string(raw), ""), "")
+ var out []Diagnostic
+ remaining := diagnosticMaxBytes
+ for _, line := range strings.Split(clean, "\n") {
+ if len(out) == diagnosticMaxEntries {
+ break
+ }
+ m := diagnosticLine.FindStringSubmatch(line)
+ if m == nil {
+ continue
+ }
+ file := strings.TrimPrefix(m[1], "./")
+ if !safeDiagnosticFile(file) {
+ continue
+ }
+ n, err := strconv.Atoi(m[2])
+ if err != nil || n <= 0 {
+ continue
+ }
+ msg := strings.TrimSpace(m[3])
+ if strings.ContainsAny(msg, "\\\x1b") || secretMessage.MatchString(msg) || hostPath.MatchString(msg) {
+ continue
+ }
+ bad := false
+ for _, r := range msg {
+ if unicode.IsControl(r) && r != '\t' {
+ bad = true
+ }
+ if unicode.Is(unicode.Cf, r) {
+ bad = true
+ }
+ }
+ if bad || msg == "" {
+ continue
+ }
+ // Count every returned string byte, including filenames, within the budget.
+ room := remaining - len(file)
+ if room <= 0 {
+ break
+ }
+ if len(msg) > room {
+ msg = msg[:room]
+ for !utf8.ValidString(msg) {
+ msg = msg[:len(msg)-1]
+ }
+ }
+ if msg == "" {
+ break
+ }
+ out = append(out, Diagnostic{File: file, Line: n, Message: msg})
+ remaining -= len(file) + len(msg)
+ }
+ return out
+}
diff --git a/internal/demobuild/diagnostics_test.go b/internal/demobuild/diagnostics_test.go
new file mode 100644
index 000000000..5cd9c4ea2
--- /dev/null
+++ b/internal/demobuild/diagnostics_test.go
@@ -0,0 +1,84 @@
+package demobuild
+
+import (
+ "archive/tar"
+ "bytes"
+ "fmt"
+ "strings"
+ "testing"
+ "unicode/utf8"
+)
+
+func TestDemoDiagnostics(t *testing.T) {
+ t.Run("source-refusal-filename", func(t *testing.T) {
+ name := strings.Repeat("Ab3_", 11) + ".go"
+ b := archive(t, append(starter(t), archiveEntry{name, "invalid Go", tar.TypeReg}))
+ _, ds, err := ValidateSource(bytes.NewReader(b), testLock(t))
+ if err == nil || len(ds) != 1 || ds[0].File != "" {
+ t.Fatalf("unsafe refusal: %v %+v", err, ds)
+ }
+ })
+ t.Run("filename-and-quoted-path-leaks", func(t *testing.T) {
+ for _, raw := range []string{
+ strings.Repeat("Ab3_", 11) + ".go:1: undefined: item\n",
+ "claimToken=short.go:1: undefined: item\n",
+ "main.go:1: open `/home/operator/private`: denied\n",
+ "main.go:1: open [/home/operator/private]: denied\n",
+ } {
+ if got := TrimDiagnostics([]byte(raw)); len(got) != 0 {
+ t.Fatalf("leaked: %+v", got)
+ }
+ }
+ })
+ t.Run("preserve", func(t *testing.T) {
+ got := TrimDiagnostics([]byte("# demo.local/app\n./shop/main.go:12:7: undefined: item\n"))
+ if len(got) != 1 || got[0].File != "shop/main.go" || got[0].Line != 12 || got[0].Message != "undefined: item" {
+ t.Fatalf("%+v", got)
+ }
+ })
+ t.Run("entries", func(t *testing.T) {
+ got := TrimDiagnostics([]byte(strings.Repeat("main.go:1:2: bad\n", 51)))
+ if len(got) != 50 {
+ t.Fatal(len(got))
+ }
+ })
+ t.Run("utf8-budget", func(t *testing.T) {
+ got := TrimDiagnostics([]byte(strings.Repeat("main.go:1:2: "+strings.Repeat("é", 1000)+"\n", 40)))
+ n := 0
+ for _, d := range got {
+ n += len(d.File) + len(d.Message)
+ if !utf8.ValidString(d.Message) {
+ t.Fatal("invalid UTF8")
+ }
+ }
+ if n > 16384 || len(got) == 0 {
+ t.Fatal(n)
+ }
+ })
+ t.Run("raw-budget", func(t *testing.T) {
+ got := TrimDiagnostics([]byte(strings.Repeat("#", 65536) + "\nmain.go:1:2: secret\n"))
+ if len(got) != 0 {
+ t.Fatal(got)
+ }
+ })
+ t.Run("sanitise", func(t *testing.T) {
+ token := strings.Repeat("Ab3_", 11)
+ raw := fmt.Sprintf("go: downloading host-secret\n/host/private.go:1:2: secret\n../secret.go:2: bad\nmain.go:3:2: \x1b[31mundefined: item\x1b[0m\nmain.go:4:2: open /home/operator/private: denied\nmain.go:5:2: token=%s\nmain.go:6:2: Bearer short-secret\nmain.go:7:2: HOME=/home/operator\nmain.go:8:2: C:\\host\\secret\nmain.go:9:2: claimToken=short\n", token)
+ got := TrimDiagnostics([]byte(raw))
+ s := fmt.Sprint(got)
+ for _, secret := range []string{"\x1b", "/host", "../", "/home", "short-secret", token, "HOME=", "C:\\host", "claimToken=short"} {
+ if strings.Contains(s, secret) {
+ t.Fatalf("leaked %q: %s", secret, s)
+ }
+ }
+ found := false
+ for _, d := range got {
+ if d.Line == 3 && d.Message == "undefined: item" {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatal(got)
+ }
+ })
+}
diff --git a/internal/demobuild/lock.go b/internal/demobuild/lock.go
new file mode 100644
index 000000000..d70aff4fe
--- /dev/null
+++ b/internal/demobuild/lock.go
@@ -0,0 +1,207 @@
+package demobuild
+
+import (
+ "bytes"
+ "crypto/sha256"
+ _ "embed"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "io"
+ "path"
+ "slices"
+ "strings"
+
+ "golang.org/x/mod/module"
+)
+
+const (
+ ToolchainVersion = "1.26.10"
+ rastrilloPath = "amadan.net/rastrillo/rastrillo"
+ rastrilloVersion = "v0.30.2"
+)
+
+type ModulePin struct {
+ Path string `json:"path"`
+ Version string `json:"version"`
+}
+
+type Module struct {
+ Path string `json:"path"`
+ Version string `json:"version"`
+ Sum string `json:"sum"`
+ GoModSum string `json:"go_mod_sum"`
+}
+
+// Lock is trusted operator input, never part of a submitted archive. The
+// generator resolves the complete graph; ReadLock checks its shape and pins.
+// The worker separately verifies its compiler/cache bundle against this lock.
+type Lock struct {
+ GoVersion string `json:"go_version"`
+ Rastrillo ModulePin `json:"rastrillo"`
+ Modules []Module `json:"modules"`
+ ImportPrefixes []string `json:"import_prefixes"`
+ EntryPackage string `json:"entry_package"`
+}
+
+// ModulesDigest returns lowercase hex SHA-256 of compact UTF-8 JSON with no
+// trailing newline. Keys occur in this order: go_version, rastrillo, modules,
+// import_prefixes, entry_package. The rastrillo object has path, version; each
+// module has path, version, sum, go_mod_sum, in that order. Modules sort by path,
+// then version, sum, go_mod_sum; import prefixes sort lexicographically. Arrays
+// are always JSON arrays (including when empty). Strings use encoding/json's
+// escaping. The digest covers exactly these dependency fields, never bundle
+// files or a bundle digest. It does not mutate or validate the lock.
+func (l Lock) ModulesDigest() string {
+ l.Modules = append([]Module{}, l.Modules...)
+ l.ImportPrefixes = append([]string{}, l.ImportPrefixes...)
+ slices.SortFunc(l.Modules, func(a, b Module) int {
+ for _, pair := range [][2]string{{a.Path, b.Path}, {a.Version, b.Version}, {a.Sum, b.Sum}, {a.GoModSum, b.GoModSum}} {
+ if c := strings.Compare(pair[0], pair[1]); c != 0 {
+ return c
+ }
+ }
+ return 0
+ })
+ slices.Sort(l.ImportPrefixes)
+ b, _ := json.Marshal(l) // This struct contains only strings and slices.
+ h := sha256.Sum256(b)
+ return hex.EncodeToString(h[:])
+}
+
+func ReadLock(r io.Reader) (Lock, error) {
+ b, err := io.ReadAll(io.LimitReader(r, 1<<20+1))
+ if err != nil || len(b) > 1<<20 || !uniqueJSONKeys(json.NewDecoder(bytes.NewReader(b))) {
+ return Lock{}, ErrLock
+ }
+ d := json.NewDecoder(bytes.NewReader(b))
+ d.DisallowUnknownFields()
+ var l Lock
+ if err := d.Decode(&l); err != nil || l.validate() != nil {
+ return Lock{}, ErrLock
+ }
+ if d.Decode(new(any)) != io.EOF {
+ return Lock{}, ErrLock
+ }
+ return l, nil
+}
+
+// encoding/json otherwise silently accepts repeated keys, including in modules.
+func uniqueJSONKeys(d *json.Decoder) bool {
+ t, err := d.Token()
+ if err != nil {
+ return false
+ }
+ delim, ok := t.(json.Delim)
+ if !ok {
+ return true
+ }
+ switch delim {
+ case '{':
+ seen := map[string]bool{}
+ for d.More() {
+ k, err := d.Token()
+ key, ok := k.(string)
+ key = strings.ToLower(key) // JSON struct-field matching also ignores case.
+ if err != nil || !ok || seen[key] {
+ return false
+ }
+ seen[key] = true
+ if !uniqueJSONKeys(d) {
+ return false
+ }
+ }
+ case '[':
+ for d.More() {
+ if !uniqueJSONKeys(d) {
+ return false
+ }
+ }
+ default:
+ return false
+ }
+ _, err = d.Token()
+ return err == nil
+}
+
+func (l Lock) validate() error {
+ if l.GoVersion != ToolchainVersion || l.EntryPackage != "." || l.Rastrillo != (ModulePin{rastrilloPath, rastrilloVersion}) || !slices.Equal(l.ImportPrefixes, []string{rastrilloPath}) || len(l.Modules) == 0 {
+ return ErrLock
+ }
+ seen := map[string]bool{}
+ found := false
+ for _, m := range l.Modules {
+ if seen[m.Path] || module.Check(m.Path, m.Version) != nil || module.CanonicalVersion(m.Version) != m.Version || !validH1(m.Sum) || !validH1(m.GoModSum) {
+ return ErrLock
+ }
+ seen[m.Path] = true
+ if m.Path == l.Rastrillo.Path {
+ if m.Version != l.Rastrillo.Version {
+ return ErrLock
+ }
+ found = true
+ }
+ }
+ if !found {
+ return ErrLock
+ }
+ return nil
+}
+
+func validH1(s string) bool {
+ if !strings.HasPrefix(s, "h1:") {
+ return false
+ }
+ b, err := base64.StdEncoding.Strict().DecodeString(s[3:])
+ return err == nil && len(b) == sha256.Size && base64.StdEncoding.EncodeToString(b) == s[3:]
+}
+
+//go:embed stdlib_linux_arm64.txt
+var stdlibInventory string
+
+var stdlibPackages = func() map[string]bool {
+ m := map[string]bool{}
+ for _, p := range strings.Fields(stdlibInventory) {
+ m[p] = true
+ }
+ return m
+}()
+
+func (l Lock) allowsImport(p string, files map[string][]byte) bool {
+ if module.CheckImportPath(p) != nil || p == "C" {
+ return false
+ }
+ if stdlibPackages[p] {
+ return true
+ }
+ if p == "demo.local/app" || strings.HasPrefix(p, "demo.local/app/") {
+ dir := strings.TrimPrefix(p, "demo.local/app")
+ dir = strings.TrimPrefix(dir, "/")
+ if dir == "" {
+ dir = "."
+ }
+ for file := range files {
+ if path.Dir(file) == dir && strings.HasSuffix(file, ".go") && !strings.HasSuffix(file, "_test.go") {
+ return true
+ }
+ }
+ return false
+ }
+ // A nested transitive module owns its packages even beneath an allowed
+ // prefix. In particular, Rastrillo's money module is not a direct import.
+ owner := ""
+ for _, m := range l.Modules {
+ if (p == m.Path || strings.HasPrefix(p, m.Path+"/")) && len(m.Path) > len(owner) {
+ owner = m.Path
+ }
+ }
+ if owner != l.Rastrillo.Path {
+ return false
+ }
+ for _, prefix := range l.ImportPrefixes {
+ if p == prefix || strings.HasPrefix(p, prefix+"/") {
+ return true
+ }
+ }
+ return false
+}
diff --git a/internal/demobuild/lock_generate_test.go b/internal/demobuild/lock_generate_test.go
new file mode 100644
index 000000000..9352f8344
--- /dev/null
+++ b/internal/demobuild/lock_generate_test.go
@@ -0,0 +1,169 @@
+package demobuild
+
+import (
+ "bytes"
+ "encoding/json"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strings"
+ "testing"
+)
+
+var updateLock = flag.Bool("update", false, "regenerate the demo lock and starter with the pinned Go toolchain")
+var verifyLock = flag.Bool("verify-lock", false, "resolve and rebuild the demo starter offline, then compare generated files")
+
+// Reproduce from the repository root with Go 1.26.10 and the default populated
+// module cache (no proxy/network fallback):
+//
+// nice -n 10 go test ./internal/demobuild -run '^TestLockMatchesStarter$' -count=1 -update
+// nice -n 10 go test ./internal/demobuild -run '^TestLockMatchesStarter$' -count=1 -verify-lock
+//
+// The seed is only demo.local/app, Go 1.26.10, and Rastrillo v0.30.2. The Go
+// command supplies every selected version and h1 sum. The full graph is made
+// explicit in the starter so an offline -mod=readonly build cannot select new
+// versions. The standard-library inventory comes from the same toolchain for
+// CGO_ENABLED=0, GOOS=linux, GOARCH=arm64, excluding internal/vendor packages.
+func TestLockMatchesStarter(t *testing.T) {
+ if *updateLock || *verifyLock {
+ generateLock(t, *updateLock)
+ }
+ l := testLock(t)
+ es := starter(t)
+ main, err := os.ReadFile("testdata/starter/main.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ es[2].body = string(main)
+ validate(t, archive(t, es), true)
+ if l.ModulesDigest() == "" {
+ t.Fatal("missing digest")
+ }
+}
+
+func generateLock(t *testing.T, update bool) {
+ t.Helper()
+ tmp := os.Getenv("TMPDIR")
+ if tmp == "" || !filepath.IsAbs(tmp) || tmp == "/tmp" || strings.HasPrefix(tmp, "/tmp/") {
+ t.Fatal("set TMPDIR to an absolute on-disk scratch directory")
+ }
+ dir, err := os.MkdirTemp(tmp, "demobuild-lock-")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() {
+ if err := os.RemoveAll(dir); err != nil {
+ t.Error(err)
+ }
+ })
+ env := []string{}
+ for _, e := range os.Environ() {
+ key, _, _ := strings.Cut(e, "=")
+ if strings.HasPrefix(key, "GO") || key == "CGO_ENABLED" {
+ continue
+ }
+ env = append(env, e)
+ }
+ env = append(env, "GOTOOLCHAIN=local", "GOWORK=off", "GOENV=off", "GOFLAGS=-mod=mod -buildvcs=false", "GOPROXY=off", "GOSUMDB=off", "CGO_ENABLED=0", "GOOS=linux", "GOARCH=arm64")
+ run := func(args ...string) []byte {
+ t.Helper()
+ cmd := exec.Command("go", args...)
+ cmd.Dir, cmd.Env = dir, env
+ var stderr bytes.Buffer
+ cmd.Stderr = &stderr
+ b, err := cmd.Output()
+ if err != nil {
+ t.Fatalf("go %s: %v\n%s", strings.Join(args, " "), err, stderr.String())
+ }
+ return b
+ }
+ if got := strings.TrimSpace(string(run("env", "GOVERSION"))); got != "go"+ToolchainVersion {
+ t.Fatalf("toolchain %s", got)
+ }
+ write := func(name string, b []byte) {
+ t.Helper()
+ if err := os.WriteFile(filepath.Join(dir, name), b, 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ write("go.mod", fmt.Appendf(nil, "module demo.local/app\n\ngo %s\n\nrequire %s %s\n", ToolchainVersion, rastrilloPath, rastrilloVersion))
+ main, err := os.ReadFile("testdata/starter/main.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ write("main.go", main)
+ d := json.NewDecoder(bytes.NewReader(run("mod", "download", "-json", "all")))
+ l := Lock{GoVersion: ToolchainVersion, Rastrillo: ModulePin{rastrilloPath, rastrilloVersion}, ImportPrefixes: []string{rastrilloPath}, EntryPackage: "."}
+ for {
+ var m struct{ Path, Version, Sum, GoModSum, Error string }
+ if err := d.Decode(&m); err == io.EOF {
+ break
+ } else if err != nil {
+ t.Fatal(err)
+ }
+ if m.Error != "" {
+ t.Fatal(m.Error)
+ }
+ l.Modules = append(l.Modules, Module{m.Path, m.Version, m.Sum, m.GoModSum})
+ }
+ slices.SortFunc(l.Modules, func(a, b Module) int { return strings.Compare(a.Path, b.Path) })
+ if err := l.validate(); err != nil {
+ t.Fatalf("resolved invalid lock: %v", err)
+ }
+ var mod, sum strings.Builder
+ fmt.Fprintf(&mod, "module demo.local/app\n\ngo %s\n\nrequire (\n", l.GoVersion)
+ for _, m := range l.Modules {
+ indirect := " // indirect"
+ if m.Path == l.Rastrillo.Path {
+ indirect = ""
+ }
+ fmt.Fprintf(&mod, "\t%s %s%s\n", m.Path, m.Version, indirect)
+ fmt.Fprintf(&sum, "%s %s %s\n%s %s/go.mod %s\n", m.Path, m.Version, m.Sum, m.Path, m.Version, m.GoModSum)
+ }
+ mod.WriteString(")\n")
+ write("go.mod", []byte(mod.String()))
+ write("go.sum", []byte(sum.String()))
+ // This also proves that the starter's framework can build without cgo.
+ run("build", "-mod=readonly", "-trimpath", "-o", filepath.Join(dir, "starter"), ".")
+ for name, want := range map[string]string{"go.mod": mod.String(), "go.sum": sum.String()} {
+ got, err := os.ReadFile(filepath.Join(dir, name))
+ if err != nil || string(got) != want {
+ t.Fatalf("readonly build changed %s: %v", name, err)
+ }
+ }
+ var std []string
+ for _, p := range strings.Fields(string(run("list", "std"))) {
+ if p == "C" || slices.Contains(strings.Split(p, "/"), "internal") || slices.Contains(strings.Split(p, "/"), "vendor") {
+ continue
+ }
+ std = append(std, p)
+ }
+ slices.Sort(std)
+ b, err := json.MarshalIndent(l, "", " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ outputs := map[string][]byte{
+ "toolchain.lock.json": append(b, '\n'),
+ "testdata/starter/go.mod": []byte(mod.String()),
+ "testdata/starter/go.sum": []byte(sum.String()),
+ "stdlib_linux_arm64.txt": []byte(strings.Join(std, "\n") + "\n"),
+ }
+ for name, want := range outputs {
+ if update {
+ if err := os.WriteFile(name, want, 0644); err != nil {
+ t.Fatal(err)
+ }
+ } else {
+ got, err := os.ReadFile(name)
+ if err != nil || !bytes.Equal(got, want) {
+ t.Errorf("%s differs from toolchain output: %v", name, err)
+ }
+ }
+ }
+ t.Logf("resolved %d modules; built linux/arm64 starter offline; ModulesDigest=%s", len(l.Modules), l.ModulesDigest())
+}
diff --git a/internal/demobuild/lock_test.go b/internal/demobuild/lock_test.go
new file mode 100644
index 000000000..03acf7244
--- /dev/null
+++ b/internal/demobuild/lock_test.go
@@ -0,0 +1,84 @@
+package demobuild
+
+import (
+ "bytes"
+ "encoding/json"
+ "slices"
+ "strings"
+ "testing"
+)
+
+func TestDemoLock(t *testing.T) {
+ l := testLock(t)
+ if l.GoVersion != "1.26.10" || l.Rastrillo.Path != "amadan.net/rastrillo/rastrillo" || l.Rastrillo.Version != "v0.30.2" || l.EntryPackage != "." {
+ t.Fatalf("unexpected pins: %+v", l)
+ }
+ if len(l.Modules) != 28 || len(l.ModulesDigest()) != 64 {
+ t.Fatalf("modules=%d digest=%s", len(l.Modules), l.ModulesDigest())
+ }
+ // Independently computed from the documented compact JSON serialization.
+ if got := l.ModulesDigest(); got != "0875320b5f1ae3f37cfe2ab9275c1c327e53f408cdd9938038d2a8ccd50bbf73" {
+ t.Fatalf("canonical digest changed: %s", got)
+ }
+ data, err := json.Marshal(l)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for name, mutate := range map[string]func(*Lock){
+ "toolchain": func(l *Lock) { l.GoVersion = "1.26.0" },
+ "pin": func(l *Lock) { l.Rastrillo.Version = "v0.30.1" },
+ "entry": func(l *Lock) { l.EntryPackage = "./..." },
+ "prefix": func(l *Lock) { l.ImportPrefixes = append(l.ImportPrefixes, "modernc.org/sqlite") },
+ "duplicate-module": func(l *Lock) { l.Modules = append(l.Modules, l.Modules[0]) },
+ "missing-framework": func(l *Lock) {
+ l.Modules = slices.DeleteFunc(l.Modules, func(m Module) bool { return m.Path == l.Rastrillo.Path })
+ },
+ "sum": func(l *Lock) { l.Modules[0].Sum = "h1:bad" },
+ "gomod-sum": func(l *Lock) { l.Modules[0].GoModSum = "" },
+ "module-path": func(l *Lock) { l.Modules[0].Path = "../bad" },
+ "version": func(l *Lock) { l.Modules[0].Version = "latest" },
+ } {
+ t.Run(name, func(t *testing.T) {
+ var bad Lock
+ if err := json.Unmarshal(data, &bad); err != nil {
+ t.Fatal(err)
+ }
+ mutate(&bad)
+ b, _ := json.Marshal(bad)
+ if _, err := ReadLock(bytes.NewReader(b)); err == nil {
+ t.Fatal("accepted invalid lock")
+ }
+ if _, _, err := ValidateSource(bytes.NewReader(nil), bad); err != ErrLock {
+ t.Fatalf("unvalidated lock: %v", err)
+ }
+ })
+ }
+ for _, bad := range []string{
+ string(data) + "{}", strings.Replace(string(data), "{", `{"bundle_sha256":"abc",`, 1),
+ strings.Replace(string(data), "{", `{"go_version":"1.26.10",`, 1), "null", "{}",
+ strings.Replace(string(data), "{", `{"GO_VERSION":"1.26.10",`, 1),
+ } {
+ if _, err := ReadLock(strings.NewReader(bad)); err == nil {
+ t.Fatal("accepted ambiguous JSON")
+ }
+ }
+ shuffled := l
+ shuffled.Modules = slices.Clone(l.Modules)
+ slices.Reverse(shuffled.Modules)
+ if shuffled.ModulesDigest() != l.ModulesDigest() {
+ t.Fatal("digest depends on module order")
+ }
+ for _, mutate := range []func(*Lock){
+ func(l *Lock) { l.GoVersion += "x" }, func(l *Lock) { l.Rastrillo.Version += "x" },
+ func(l *Lock) { l.EntryPackage += "x" }, func(l *Lock) { l.ImportPrefixes = []string{"example.com"} },
+ func(l *Lock) { l.Modules[0].Version += "x" }, func(l *Lock) { l.Modules[0].Sum += "x" },
+ func(l *Lock) { l.Modules[0].GoModSum += "x" },
+ } {
+ var other Lock
+ json.Unmarshal(data, &other)
+ mutate(&other)
+ if other.ModulesDigest() == l.ModulesDigest() {
+ t.Fatal("digest omitted a field")
+ }
+ }
+}
diff --git a/internal/demobuild/source.go b/internal/demobuild/source.go
new file mode 100644
index 000000000..5f22c917a
--- /dev/null
+++ b/internal/demobuild/source.go
@@ -0,0 +1,418 @@
+// Package demobuild validates anonymous source before an isolated offline build.
+package demobuild
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "crypto/sha256"
+ "encoding/hex"
+ "go/parser"
+ "go/token"
+ "io"
+ "path"
+ "sort"
+ "strconv"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/carlosframework/platform/internal/demo"
+ "golang.org/x/mod/modfile"
+)
+
+const (
+ // ExpandedMaxBytes limits file contents; tar framing has a separate bound.
+ ExpandedMaxBytes = 20_000_000
+ FileMaxBytes = 2_000_000
+ MaxFiles = 256
+ BinaryMaxBytes = 33_554_432
+ // Directories are separately bounded, as is all tar framing and padding.
+ maxDirectories = 256
+ tarMaxBytes = ExpandedMaxBytes + (MaxFiles*2+maxDirectories+2)*512
+)
+
+type Source struct {
+ Archive []byte
+ SHA256 string
+ Files []SourceFile
+}
+
+type SourceFile struct {
+ Path string
+ Size int64
+ SHA256 string
+}
+
+// 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) {
+ 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 {
+ return Source{}, nil, ErrLock
+ }
+ original, err := io.ReadAll(io.LimitReader(r, demo.SourceMaxBytes+1))
+ if err != nil || len(original) > demo.SourceMaxBytes {
+ return refuse("", 0)
+ }
+ compressed := bytes.NewReader(original)
+ gz, err := gzip.NewReader(compressed)
+ if err != nil {
+ return refuse("", 0)
+ }
+ gz.Multistream(false)
+ expanded, readErr := io.ReadAll(io.LimitReader(gz, tarMaxBytes+1))
+ closeErr := gz.Close()
+ if readErr != nil || closeErr != nil || len(expanded) > tarMaxBytes || compressed.Len() != 0 {
+ return refuse("", 0)
+ }
+ // Check physical records before archive/tar can hide GNU/PAX extension or
+ // sparse headers. Only ordinary file/directory records are in this contract.
+ if !plainTar(expanded) {
+ return refuse("", 0)
+ }
+ tr := tar.NewReader(bytes.NewReader(expanded))
+ entries := map[string]bool{} // true means directory
+ files := map[string][]byte{}
+ total, dirs := int64(0), 0
+ for {
+ h, err := tr.Next()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ return refuse("", 0)
+ }
+ name := h.Name
+ if h.Typeflag == tar.TypeDir {
+ name = strings.TrimSuffix(name, "/")
+ }
+ if !validPath(name) {
+ return refuse("", 0)
+ }
+ if _, exists := entries[name]; exists {
+ return refuse(name, 0)
+ }
+ isDir := h.Typeflag == tar.TypeDir
+ if forbiddenFile(name, isDir) {
+ return refuse(name, 0)
+ }
+ entries[name] = isDir
+ if isDir {
+ dirs++
+ if dirs > maxDirectories || h.Size != 0 {
+ return refuse(name, 0)
+ }
+ continue
+ }
+ if len(files) >= MaxFiles || h.Size < 0 || h.Size > FileMaxBytes || total+h.Size > ExpandedMaxBytes {
+ return refuse(name, 0)
+ }
+ body, err := io.ReadAll(tr)
+ if err != nil || int64(len(body)) != h.Size {
+ return refuse(name, 0)
+ }
+ files[name] = body
+ total += h.Size
+ }
+ for name := range entries {
+ for dir := path.Dir(name); dir != "."; dir = path.Dir(dir) {
+ if isDir, exists := entries[dir]; exists && !isDir {
+ return refuse(name, 0)
+ }
+ }
+ }
+ if !validModule(files["go.mod"], files["go.sum"], lock) {
+ return refuse("go.mod", 0)
+ }
+ names := make([]string, 0, len(files))
+ for name := range files {
+ names = append(names, name)
+ }
+ sort.Strings(names)
+ inventory := make([]SourceFile, 0, len(names))
+ hasMain := false
+ for _, name := range names {
+ body := files[name]
+ if strings.HasSuffix(name, ".go") {
+ fs := token.NewFileSet()
+ f, err := parser.ParseFile(fs, name, body, parser.ParseComments|parser.AllErrors)
+ if err != nil {
+ return refuse(name, 1)
+ }
+ if path.Dir(name) == "." && f.Name.Name == "main" && !strings.HasSuffix(name, "_test.go") {
+ hasMain = true
+ }
+ for _, imp := range f.Imports {
+ p, err := strconv.Unquote(imp.Path.Value)
+ if err != nil || !lock.allowsImport(p, files) {
+ return refuse(name, fs.PositionFor(imp.Pos(), false).Line)
+ }
+ }
+ for _, group := range f.Comments {
+ for _, comment := range group.List {
+ text := comment.Text
+ if strings.HasPrefix(text, "//line ") || strings.HasPrefix(text, "/*line ") {
+ return refuse(name, fs.PositionFor(comment.Pos(), false).Line)
+ }
+ if !strings.HasPrefix(text, "//go:") {
+ continue
+ }
+ switch {
+ case strings.HasPrefix(text, "//go:build "):
+ case strings.HasPrefix(text, "//go:embed ") || strings.HasPrefix(text, "//go:embed\t"):
+ if !validEmbeds(strings.TrimSpace(text[len("//go:embed"):]), path.Dir(name), files) {
+ return refuse(name, fs.PositionFor(comment.Pos(), false).Line)
+ }
+ default:
+ return refuse(name, fs.PositionFor(comment.Pos(), false).Line)
+ }
+ }
+ }
+ }
+ digest := sha256.Sum256(body)
+ inventory = append(inventory, SourceFile{Path: name, Size: int64(len(body)), SHA256: hex.EncodeToString(digest[:])})
+ }
+ if !hasMain {
+ return refuse("", 0)
+ }
+ digest := sha256.Sum256(original)
+ return Source{Archive: original, SHA256: hex.EncodeToString(digest[:]), Files: inventory}, nil, nil
+}
+
+func validPath(name string) bool {
+ if name == "" || name == "." || strings.HasPrefix(name, "/") || strings.ContainsAny(name, "\\:\x00") || path.Clean(name) != name || !utf8.ValidString(name) {
+ return false
+ }
+ for _, r := range name {
+ if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) {
+ return false
+ }
+ }
+ for _, part := range strings.Split(name, "/") {
+ if part == "." || part == ".." || part == "" {
+ return false
+ }
+ }
+ return true
+}
+
+func forbiddenFile(name string, isDir bool) bool {
+ for _, part := range strings.Split(name, "/") {
+ if part == "vendor" || part == ".git" || part == ".hg" || part == ".svn" || part == ".bzr" {
+ return true
+ }
+ }
+ base := path.Base(name)
+ if base == "go.work" || base == "go.work.sum" || ((base == "go.mod" || base == "go.sum") && (name != base || isDir)) {
+ return true
+ }
+ if isDir {
+ return false
+ }
+ switch strings.ToLower(path.Ext(name)) {
+ case ".s", ".syso", ".c", ".h", ".cc", ".cpp", ".cxx", ".m", ".mm", ".f", ".for", ".f90", ".o", ".a", ".swig", ".swigcxx":
+ return true
+ }
+ return false
+}
+
+func plainTar(b []byte) bool {
+ for len(b) >= 512 {
+ h := b[:512]
+ if bytes.Equal(h, make([]byte, 512)) {
+ // Require the two terminating blocks, and allow only zero record padding.
+ if len(b) < 1024 || len(b)%512 != 0 {
+ return false
+ }
+ for _, v := range b {
+ if v != 0 {
+ return false
+ }
+ }
+ return true
+ }
+ if h[156] != tar.TypeReg && h[156] != tar.TypeRegA && h[156] != tar.TypeDir {
+ return false
+ }
+ // NUL is a terminator in USTAR, never a way to smuggle another name.
+ for _, field := range [][]byte{h[:100], h[345:500]} {
+ if i := bytes.IndexByte(field, 0); i >= 0 {
+ for _, v := range field[i:] {
+ if v != 0 {
+ return false
+ }
+ }
+ }
+ }
+ // Let archive/tar validate checksums and formats, but don't accept numeric
+ // extensions which could make the physical and logical parsers disagree.
+ size, err := strconv.ParseInt(strings.Trim(string(h[124:136]), " \x00"), 8, 64)
+ if err != nil || size < 0 || size > FileMaxBytes {
+ return false
+ }
+ if h[156] == tar.TypeDir && size != 0 {
+ return false
+ }
+ n := int64(512) + (size+511)/512*512
+ if n > int64(len(b)) {
+ return false
+ }
+ b = b[n:]
+ }
+ return false
+}
+
+func validModule(mod, sum []byte, lock Lock) bool {
+ f, err := modfile.Parse("go.mod", mod, nil)
+ if err != nil || f.Module == nil || f.Module.Mod.Path != "demo.local/app" || f.Go == nil || f.Go.Version != lock.GoVersion {
+ return false
+ }
+ // Permit only these grammar productions, including in block syntax.
+ for _, stmt := range f.Syntax.Stmt {
+ switch s := stmt.(type) {
+ case *modfile.Line:
+ if len(s.Token) == 0 || !moduleDirective(s.Token[0]) {
+ return false
+ }
+ case *modfile.LineBlock:
+ if len(s.Token) != 1 || s.Token[0] != "require" {
+ return false
+ }
+ default:
+ return false
+ }
+ }
+ if len(f.Require) != len(lock.Modules) {
+ return false
+ }
+ modules := map[string]Module{}
+ for _, m := range lock.Modules {
+ modules[m.Path] = m
+ }
+ seen := map[string]bool{}
+ for _, req := range f.Require {
+ m, ok := modules[req.Mod.Path]
+ if !ok || seen[m.Path] || req.Mod.Version != m.Version {
+ return false
+ }
+ seen[m.Path] = true
+ }
+ expected := map[string]string{}
+ for _, m := range lock.Modules {
+ expected[m.Path+" "+m.Version] = m.Sum
+ expected[m.Path+" "+m.Version+"/go.mod"] = m.GoModSum
+ }
+ seen = map[string]bool{}
+ for _, line := range strings.Split(string(sum), "\n") {
+ parts := strings.Fields(line)
+ if len(parts) == 0 {
+ continue
+ }
+ if len(parts) != 3 {
+ return false
+ }
+ key := parts[0] + " " + parts[1]
+ if seen[key] || expected[key] != parts[2] {
+ return false
+ }
+ seen[key] = true
+ }
+ return len(seen) == len(expected)
+}
+func moduleDirective(s string) bool { return s == "module" || s == "go" || s == "require" }
+
+func validEmbeds(text, dir string, files map[string][]byte) bool {
+ patterns, ok := embedPatterns(text)
+ if !ok || len(patterns) == 0 {
+ return false
+ }
+ for _, pattern := range patterns {
+ all := strings.HasPrefix(pattern, "all:")
+ pattern = strings.TrimPrefix(pattern, "all:")
+ if !validPath(pattern) {
+ return false
+ }
+ if _, err := path.Match(pattern, ""); err != nil {
+ return false
+ }
+ matched := false
+ for file := range files {
+ rel := file
+ if dir != "." {
+ if !strings.HasPrefix(file, dir+"/") {
+ continue
+ }
+ rel = strings.TrimPrefix(file, dir+"/")
+ }
+ if !all {
+ hidden := false
+ for _, part := range strings.Split(rel, "/") {
+ if strings.HasPrefix(part, ".") || strings.HasPrefix(part, "_") {
+ hidden = true
+ }
+ }
+ if hidden {
+ continue
+ }
+ }
+ for candidate := rel; candidate != "."; candidate = path.Dir(candidate) {
+ if yes, _ := path.Match(pattern, candidate); yes {
+ matched = true
+ break
+ }
+ }
+ }
+ if !matched {
+ return false
+ }
+ }
+ return true
+}
+
+func embedPatterns(text string) ([]string, bool) {
+ var out []string
+ for text = strings.TrimSpace(text); text != ""; text = strings.TrimSpace(text) {
+ if text[0] == '"' || text[0] == '`' {
+ quote := text[0]
+ end := 1
+ for end < len(text) {
+ if quote == '"' && text[end] == '\\' {
+ end += 2
+ continue
+ }
+ if text[end] == quote {
+ break
+ }
+ end++
+ }
+ if end >= len(text) {
+ return nil, false
+ }
+ value, err := strconv.Unquote(text[:end+1])
+ if err != nil {
+ return nil, false
+ }
+ out = append(out, value)
+ text = text[end+1:]
+ if text != "" && !unicode.IsSpace(rune(text[0])) {
+ return nil, false
+ }
+ } else {
+ end := strings.IndexFunc(text, unicode.IsSpace)
+ if end < 0 {
+ end = len(text)
+ }
+ out = append(out, text[:end])
+ text = text[end:]
+ }
+ }
+ return out, true
+}
diff --git a/internal/demobuild/source_test.go b/internal/demobuild/source_test.go
new file mode 100644
index 000000000..4074a3ff3
--- /dev/null
+++ b/internal/demobuild/source_test.go
@@ -0,0 +1,326 @@
+package demobuild
+
+import (
+ "archive/tar"
+ "bytes"
+ "compress/gzip"
+ "crypto/sha256"
+ "encoding/hex"
+ "fmt"
+ "io"
+ "os"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/demo"
+)
+
+type archiveEntry struct {
+ name, body string
+ kind byte
+}
+
+func starter(t *testing.T) []archiveEntry {
+ t.Helper()
+ mod, err := os.ReadFile("testdata/starter/go.mod")
+ if err != nil {
+ t.Fatal(err)
+ }
+ sum, err := os.ReadFile("testdata/starter/go.sum")
+ if err != nil {
+ t.Fatal(err)
+ }
+ return []archiveEntry{{"go.mod", string(mod), tar.TypeReg}, {"go.sum", string(sum), tar.TypeReg}, {"main.go", "package main\nfunc main() {}\n", tar.TypeReg}}
+}
+func testLock(t *testing.T) Lock {
+ t.Helper()
+ f, err := os.Open("toolchain.lock.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer f.Close()
+ l, err := ReadLock(f)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return l
+}
+func tarBytes(t *testing.T, entries []archiveEntry) []byte {
+ t.Helper()
+ var b bytes.Buffer
+ w := tar.NewWriter(&b)
+ for _, e := range entries {
+ h := &tar.Header{Name: e.name, Mode: 0644, Size: int64(len(e.body)), Typeflag: e.kind, Format: tar.FormatUSTAR}
+ if e.kind != tar.TypeReg {
+ h.Size = 0
+ }
+ if e.kind == tar.TypeLink || e.kind == tar.TypeSymlink {
+ h.Linkname = "main.go"
+ }
+ if err := w.WriteHeader(h); err != nil {
+ t.Fatal(err)
+ }
+ if h.Size > 0 {
+ if _, err := io.WriteString(w, e.body); err != nil {
+ t.Fatal(err)
+ }
+ }
+ }
+ if err := w.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return b.Bytes()
+}
+func gzipBytes(t *testing.T, b []byte) []byte {
+ t.Helper()
+ var out bytes.Buffer
+ w := gzip.NewWriter(&out)
+ if _, err := w.Write(b); err != nil {
+ t.Fatal(err)
+ }
+ if err := w.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return out.Bytes()
+}
+func archive(t *testing.T, entries []archiveEntry) []byte { return gzipBytes(t, tarBytes(t, entries)) }
+func validate(t *testing.T, b []byte, want bool) Source {
+ t.Helper()
+ src, ds, err := ValidateSource(bytes.NewReader(b), testLock(t))
+ if (err == nil) != want {
+ t.Fatalf("accepted=%v, want %v; err=%v diagnostics=%+v", err == nil, want, err, ds)
+ }
+ if !want && (len(src.Archive) != 0 || len(src.Files) != 0 || src.SHA256 != "") {
+ t.Fatal("rejected source returned partial authority")
+ }
+ if want {
+ sum := sha256.Sum256(b)
+ if !bytes.Equal(src.Archive, b) || src.SHA256 != hex.EncodeToString(sum[:]) {
+ t.Fatal("original bytes/digest changed")
+ }
+ if !slices.IsSortedFunc(src.Files, func(a, b SourceFile) int { return strings.Compare(a.Path, b.Path) }) {
+ t.Fatal("inventory is not sorted")
+ }
+ gz, err := gzip.NewReader(bytes.NewReader(src.Archive))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer gz.Close()
+ tr := tar.NewReader(gz)
+ for {
+ h, err := tr.Next()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if h.Typeflag == tar.TypeDir {
+ continue
+ }
+ body, err := io.ReadAll(tr)
+ if err != nil {
+ t.Fatal(err)
+ }
+ digest := sha256.Sum256(body)
+ i := slices.IndexFunc(src.Files, func(f SourceFile) bool { return f.Path == h.Name })
+ if i < 0 || src.Files[i].Size != int64(len(body)) || src.Files[i].SHA256 != hex.EncodeToString(digest[:]) {
+ t.Fatalf("inventory mismatch for %s", h.Name)
+ }
+ }
+ }
+ return src
+}
+func TestDemoSourceLimits(t *testing.T) {
+ if BinaryMaxBytes != 33554432 {
+ t.Fatal(BinaryMaxBytes)
+ }
+ for _, n := range []int{2_000_000, 2_000_001} {
+ t.Run(fmt.Sprintf("file-%d", n), func(t *testing.T) {
+ validate(t, archive(t, append(starter(t), archiveEntry{"asset", strings.Repeat("x", n), tar.TypeReg})), n == 2_000_000)
+ })
+ }
+ for _, n := range []int{20_000_000, 20_000_001} {
+ t.Run(fmt.Sprintf("expanded-%d", n), func(t *testing.T) {
+ es := starter(t)
+ used := 0
+ for _, e := range es {
+ used += len(e.body)
+ }
+ for i := 0; used < n; i++ {
+ size := min(2_000_000, n-used)
+ es = append(es, archiveEntry{fmt.Sprintf("asset%d", i), strings.Repeat("x", size), tar.TypeReg})
+ used += size
+ }
+ validate(t, archive(t, es), n == 20_000_000)
+ })
+ }
+ for _, n := range []int{256, 257} {
+ t.Run(fmt.Sprintf("files-%d", n), func(t *testing.T) {
+ es := starter(t)
+ for len(es) < n {
+ es = append(es, archiveEntry{fmt.Sprintf("f%d", len(es)), "", tar.TypeReg})
+ }
+ validate(t, archive(t, es), n == 256)
+ })
+ }
+ // Incompressible stored DEFLATE blocks let the payload land on the exact compressed bound.
+ for _, n := range []int{demo.SourceMaxBytes, demo.SourceMaxBytes + 1} {
+ t.Run(fmt.Sprintf("compressed-%d", n), func(t *testing.T) {
+ es := starter(t)
+ for i := 0; i < 3; i++ {
+ es = append(es, archiveEntry{fmt.Sprintf("data%d", i), strings.Repeat("x", 1_650_000), tar.TypeReg})
+ }
+ raw := tarBytes(t, es)
+ var b bytes.Buffer
+ w, err := gzip.NewWriterLevel(&b, gzip.NoCompression)
+ if err != nil {
+ t.Fatal(err)
+ }
+ // A legal gzip Extra field pads the input without changing the tar.
+ probe := new(bytes.Buffer)
+ p, _ := gzip.NewWriterLevel(probe, gzip.NoCompression)
+ p.Write(raw)
+ p.Close()
+ w.Extra = bytes.Repeat([]byte{'p'}, n-probe.Len()-2)
+ w.Write(raw)
+ w.Close()
+ if b.Len() != n {
+ t.Fatalf("fixture size %d", b.Len())
+ }
+ validate(t, b.Bytes(), n == demo.SourceMaxBytes)
+ })
+ }
+}
+func TestDemoSourceCannotEscapeLock(t *testing.T) {
+ for _, kind := range []byte{tar.TypeXHeader, tar.TypeXGlobalHeader, tar.TypeGNULongName, tar.TypeGNULongLink} {
+ t.Run(fmt.Sprintf("extension-%c", kind), func(t *testing.T) {
+ b := tarBytes(t, starter(t))
+ b[156] = kind
+ fixHeaderChecksum(b)
+ validate(t, gzipBytes(t, b), false)
+ })
+ }
+ t.Run("duplicate-directory", func(t *testing.T) {
+ validate(t, archive(t, append(starter(t), archiveEntry{"assets/", "", tar.TypeDir}, archiveEntry{"assets", "", tar.TypeDir})), false)
+ })
+ for _, name := range []string{"wrong-go-version", "wrong-module", "missing-requirement", "extra-requirement", "duplicate-requirement", "missing-sum", "extra-sum", "duplicate-sum"} {
+ t.Run(name, func(t *testing.T) {
+ es := starter(t)
+ switch name {
+ case "wrong-go-version":
+ es[0].body = strings.Replace(es[0].body, "go 1.26.10", "go 1.26.0", 1)
+ case "wrong-module":
+ es[0].body = strings.Replace(es[0].body, "demo.local/app", "example.com/shop", 1)
+ case "missing-requirement":
+ es[0].body = strings.Replace(es[0].body, "\tamadan.net/rastrillo/rastrillo v0.30.2\n", "", 1)
+ case "extra-requirement":
+ es[0].body += "require example.com/shop v1.0.0\n"
+ case "duplicate-requirement":
+ es[0].body += "require amadan.net/rastrillo/rastrillo v0.30.2\n"
+ case "missing-sum":
+ _, es[1].body, _ = strings.Cut(es[1].body, "\n")
+ case "extra-sum":
+ es[1].body += "example.com/shop v1.0.0 h1:bad\n"
+ case "duplicate-sum":
+ line, _, _ := strings.Cut(es[1].body, "\n")
+ es[1].body += line + "\n"
+ }
+ validate(t, archive(t, es), false)
+ })
+ }
+ for _, name := range []string{"../escape", "/absolute", "a/../b", "./main.go", "a//b", "a\\b", "C:/host", "a/./b"} {
+ t.Run(name, func(t *testing.T) {
+ validate(t, archive(t, append(starter(t), archiveEntry{name, "", tar.TypeReg})), false)
+ })
+ }
+ for _, kind := range []byte{tar.TypeSymlink, tar.TypeLink, tar.TypeChar, tar.TypeBlock, tar.TypeFifo} {
+ t.Run(fmt.Sprintf("type-%c", kind), func(t *testing.T) { validate(t, archive(t, append(starter(t), archiveEntry{"bad", "", kind})), false) })
+ }
+ for _, name := range []string{"go.work", "go.work.sum", "vendor/x.go", "nested/go.mod", "nested/go.sum", "x.syso", "x.s", "x.S", "x.c", "x.h", "x.o", "x.a"} {
+ t.Run(name, func(t *testing.T) {
+ validate(t, archive(t, append(starter(t), archiveEntry{name, "", tar.TypeReg})), false)
+ })
+ }
+ for _, extra := range []string{"replace amadan.net/rastrillo/rastrillo => ./fork\n", "exclude amadan.net/rastrillo/rastrillo v0.30.2\n", "toolchain go1.26.10\n", "tool example.com/tool\n", "godebug panicnil=1\n"} {
+ t.Run(strings.Fields(extra)[0], func(t *testing.T) { es := starter(t); es[0].body += extra; validate(t, archive(t, es), false) })
+ }
+ for name, code := range map[string]string{
+ "generate": "package main\n//go:generate touch bad\n", "linkname": "package main\nimport _ \"unsafe\"\n//go:linkname x runtime.x\nvar x int\n",
+ "import-C": "package main\nimport \"C\"\n", "embed-parent": "package main\nimport _ \"embed\"\n//go:embed ../secret\nvar x string\n",
+ "embed-absolute": "package main\nimport _ \"embed\"\n//go:embed /etc/passwd\nvar x string\n", "embed-missing": "package main\nimport _ \"embed\"\n//go:embed absent\nvar x string\n",
+ "line-directive": "package main\n//line /host/secret:1\nfunc main(){}\n",
+ } {
+ t.Run(name, func(t *testing.T) { es := starter(t); es[2].body = code; validate(t, archive(t, es), false) })
+ }
+ t.Run("duplicate", func(t *testing.T) {
+ validate(t, archive(t, append(starter(t), archiveEntry{"main.go", "package main", tar.TypeReg})), false)
+ })
+ t.Run("directory-file-conflict", func(t *testing.T) {
+ validate(t, archive(t, append(starter(t), archiveEntry{"assets", "", tar.TypeReg}, archiveEntry{"assets/x", "", tar.TypeReg})), false)
+ })
+ t.Run("wrong-version", func(t *testing.T) {
+ es := starter(t)
+ es[0].body = strings.ReplaceAll(es[0].body, "v0.30.2", "v0.30.1")
+ validate(t, archive(t, es), false)
+ })
+ t.Run("wrong-sum", func(t *testing.T) {
+ es := starter(t)
+ es[1].body = strings.Replace(es[1].body, "h1:", "h1:bad", 1)
+ validate(t, archive(t, es), false)
+ })
+ t.Run("gzip-member", func(t *testing.T) { b := archive(t, starter(t)); validate(t, append(b, b...), false) })
+ t.Run("gzip-trailing", func(t *testing.T) { validate(t, append(archive(t, starter(t)), 0), false) })
+ t.Run("tar-trailing", func(t *testing.T) {
+ validate(t, gzipBytes(t, append(tarBytes(t, starter(t)), []byte("hidden")...)), false)
+ })
+ t.Run("tar-truncated", func(t *testing.T) { b := tarBytes(t, starter(t)); validate(t, gzipBytes(t, b[:len(b)-1024]), false) })
+ t.Run("gzip-checksum", func(t *testing.T) { b := archive(t, starter(t)); b[len(b)-8] ^= 1; validate(t, b, false) })
+ t.Run("sparse", func(t *testing.T) {
+ b := tarBytes(t, []archiveEntry{{"bad", "", tar.TypeReg}})
+ b[156] = tar.TypeGNUSparse
+ fixHeaderChecksum(b)
+ validate(t, gzipBytes(t, b), false)
+ })
+ t.Run("nul", func(t *testing.T) {
+ b := tarBytes(t, []archiveEntry{{"bad", "", tar.TypeReg}})
+ copy(b[:100], []byte("a\x00b"))
+ fixHeaderChecksum(b)
+ validate(t, gzipBytes(t, b), false)
+ })
+}
+func fixHeaderChecksum(b []byte) {
+ for i := 148; i < 156; i++ {
+ b[i] = ' '
+ }
+ sum := 0
+ for _, c := range b[:512] {
+ sum += int(c)
+ }
+ copy(b[148:156], fmt.Sprintf("%06o\x00 ", sum))
+}
+func TestDemoImports(t *testing.T) {
+ for name, code := range map[string]string{
+ "transitive": "package main\nimport _ \"modernc.org/sqlite\"\n", "submodule": "package main\nimport _ \"amadan.net/rastrillo/rastrillo/money\"\n", "prefix-lookalike": "package main\nimport _ \"amadan.net/rastrillo/rastrillo-evil\"\n", "fake-stdlib": "package main\nimport _ \"madeup/pkg\"\n", "test": "package main\nimport _ \"example.com/bad\"\n", "excluded": "//go:build never\n\npackage main\nimport _ \"example.com/bad\"\n",
+ } {
+ t.Run(name, func(t *testing.T) {
+ es := starter(t)
+ file := "hidden.go"
+ if name == "test" {
+ file = "hidden_test.go"
+ }
+ es = append(es, archiveEntry{file, code, tar.TypeReg})
+ validate(t, archive(t, es), false)
+ })
+ }
+ t.Run("stdlib-framework-local-embed", func(t *testing.T) {
+ es := starter(t)
+ es[2].body = "package main\nimport (_ \"fmt\"; _ \"amadan.net/rastrillo/rastrillo\"; _ \"demo.local/app/shop\"; _ \"embed\")\n//go:embed assets/*.css\nvar css string\nfunc main() {}\n"
+ es = append(es, archiveEntry{"assets/", "", tar.TypeDir}, archiveEntry{"shop/shop.go", "package shop\n", tar.TypeReg}, archiveEntry{"assets/fiesta.css", "body {}", tar.TypeReg})
+ src := validate(t, archive(t, es), true)
+ if len(src.Files) != 5 {
+ t.Fatal(src.Files)
+ }
+ })
+}
diff --git a/internal/demobuild/stdlib_linux_arm64.txt b/internal/demobuild/stdlib_linux_arm64.txt
new file mode 100644
index 000000000..fcf284520
--- /dev/null
+++ b/internal/demobuild/stdlib_linux_arm64.txt
@@ -0,0 +1,175 @@
+archive/tar
+archive/zip
+bufio
+bytes
+cmp
+compress/bzip2
+compress/flate
+compress/gzip
+compress/lzw
+compress/zlib
+container/heap
+container/list
+container/ring
+context
+crypto
+crypto/aes
+crypto/cipher
+crypto/des
+crypto/dsa
+crypto/ecdh
+crypto/ecdsa
+crypto/ed25519
+crypto/elliptic
+crypto/fips140
+crypto/hkdf
+crypto/hmac
+crypto/hpke
+crypto/md5
+crypto/mlkem
+crypto/mlkem/mlkemtest
+crypto/pbkdf2
+crypto/rand
+crypto/rc4
+crypto/rsa
+crypto/sha1
+crypto/sha256
+crypto/sha3
+crypto/sha512
+crypto/subtle
+crypto/tls
+crypto/x509
+crypto/x509/pkix
+database/sql
+database/sql/driver
+debug/buildinfo
+debug/dwarf
+debug/elf
+debug/gosym
+debug/macho
+debug/pe
+debug/plan9obj
+embed
+encoding
+encoding/ascii85
+encoding/asn1
+encoding/base32
+encoding/base64
+encoding/binary
+encoding/csv
+encoding/gob
+encoding/hex
+encoding/json
+encoding/pem
+encoding/xml
+errors
+expvar
+flag
+fmt
+go/ast
+go/build
+go/build/constraint
+go/constant
+go/doc
+go/doc/comment
+go/format
+go/importer
+go/parser
+go/printer
+go/scanner
+go/token
+go/types
+go/version
+hash
+hash/adler32
+hash/crc32
+hash/crc64
+hash/fnv
+hash/maphash
+html
+html/template
+image
+image/color
+image/color/palette
+image/draw
+image/gif
+image/jpeg
+image/png
+index/suffixarray
+io
+io/fs
+io/ioutil
+iter
+log
+log/slog
+log/syslog
+maps
+math
+math/big
+math/bits
+math/cmplx
+math/rand
+math/rand/v2
+mime
+mime/multipart
+mime/quotedprintable
+net
+net/http
+net/http/cgi
+net/http/cookiejar
+net/http/fcgi
+net/http/httptest
+net/http/httptrace
+net/http/httputil
+net/http/pprof
+net/mail
+net/netip
+net/rpc
+net/rpc/jsonrpc
+net/smtp
+net/textproto
+net/url
+os
+os/exec
+os/signal
+os/user
+path
+path/filepath
+plugin
+reflect
+regexp
+regexp/syntax
+runtime
+runtime/coverage
+runtime/debug
+runtime/metrics
+runtime/pprof
+runtime/race
+runtime/trace
+slices
+sort
+strconv
+strings
+structs
+sync
+sync/atomic
+syscall
+testing
+testing/cryptotest
+testing/fstest
+testing/iotest
+testing/quick
+testing/slogtest
+testing/synctest
+text/scanner
+text/tabwriter
+text/template
+text/template/parse
+time
+time/tzdata
+unicode
+unicode/utf16
+unicode/utf8
+unique
+unsafe
+weak
diff --git a/internal/demobuild/testdata/starter/go.mod b/internal/demobuild/testdata/starter/go.mod
new file mode 100644
index 000000000..36b00a9b4
--- /dev/null
+++ b/internal/demobuild/testdata/starter/go.mod
@@ -0,0 +1,34 @@
+module demo.local/app
+
+go 1.26.10
+
+require (
+ amadan.net/rastrillo/rastrillo v0.30.2
+ amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect
+ github.com/BurntSushi/toml v1.6.0 // indirect
+ github.com/chromedp/cdproto v0.158.6 // indirect
+ github.com/chromedp/chromedp v0.21.0 // indirect
+ github.com/dustin/go-humanize v1.0.1 // indirect
+ github.com/go-chi/chi/v5 v5.3.2 // indirect
+ github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 // indirect
+ github.com/google/uuid v1.6.0 // indirect
+ github.com/jinzhu/inflection v1.0.0 // indirect
+ github.com/jinzhu/now v1.1.5 // indirect
+ github.com/keymaildev/signin v0.1.1 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/ncruces/go-strftime v1.0.0 // indirect
+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+ github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e // indirect
+ golang.org/x/crypto v0.53.0 // indirect
+ golang.org/x/mod v0.37.0 // indirect
+ golang.org/x/sync v0.21.0 // indirect
+ golang.org/x/sys v0.46.0 // indirect
+ golang.org/x/text v0.39.0 // indirect
+ golang.org/x/tools v0.47.0 // indirect
+ gorm.io/gorm v1.31.2 // indirect
+ gorm.io/plugin/dbresolver v1.6.2 // indirect
+ modernc.org/libc v1.74.1 // indirect
+ modernc.org/mathutil v1.7.1 // indirect
+ modernc.org/memory v1.11.0 // indirect
+ modernc.org/sqlite v1.55.0 // indirect
+)
diff --git a/internal/demobuild/testdata/starter/go.sum b/internal/demobuild/testdata/starter/go.sum
new file mode 100644
index 000000000..96f6e826f
--- /dev/null
+++ b/internal/demobuild/testdata/starter/go.sum
@@ -0,0 +1,56 @@
+amadan.net/rastrillo/rastrillo v0.30.2 h1:xZ/cAfSvWFoWWL1xD5Lsq90xwxF+jigD1GsZmwgTcxs=
+amadan.net/rastrillo/rastrillo v0.30.2/go.mod h1:K7Clrt14+25ruVupgRjlIhH2GQp/OdL9VoD8xPmkt0w=
+amadan.net/rastrillo/rastrillo/money v0.1.0 h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonajNqeLIzmmaM=
+amadan.net/rastrillo/rastrillo/money v0.1.0/go.mod h1:cmgkjBEIQh1pFSYvQk0UU6oPYS8kSDypdT9+t4Flx0U=
+github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=
+github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=
+github.com/chromedp/cdproto v0.158.6 h1:jaKiXWuhcxbvKbSe8U6Dp5U4Hcj2w6lETYgZqBD5n34=
+github.com/chromedp/cdproto v0.158.6/go.mod h1:h68JaIuFr9o3yiayxEYhBdvaxgYO3shDrPSYhNlyfu0=
+github.com/chromedp/chromedp v0.21.0 h1:nVHgS2LHyhZJ1l3BWRbG2eFIFYiJMnvkJbELbd8WBoQ=
+github.com/chromedp/chromedp v0.21.0/go.mod h1:6z1Y5FdKUxRzxx2qcC5h1xjaBJrSWrZp1mjgITfNZig=
+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
+github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
+github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 h1:UADEEmDKgfXbtnGJZ97beY5XLo9ZechG1nlU4KnRrkE=
+github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
+github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
+github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
+github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
+github.com/keymaildev/signin v0.1.1 h1:gO+1IAM99sqUkBtCezkgGxab+/DOrqwDxd5H32N1s9Q=
+github.com/keymaildev/signin v0.1.1/go.mod h1:Eb/sCmEel1jlcdkgPOrNeMn5jvxzoFvJrdjDUxOBHls=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
+github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
+github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
+golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
+golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
+golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
+golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
+golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
+golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
+golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
+golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
+golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
+golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
+golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
+gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
+gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
+gorm.io/plugin/dbresolver v1.6.2 h1:F4b85TenghUeITqe3+epPSUtHH7RIk3fXr5l83DF8Pc=
+gorm.io/plugin/dbresolver v1.6.2/go.mod h1:tctw63jdrOezFR9HmrKnPkmig3m5Edem9fdxk9bQSzM=
+modernc.org/libc v1.74.1 h1:bdR4VTKFMC4966QSNZ05XLGI/VwzVa2kTUX51Dm0riQ=
+modernc.org/libc v1.74.1/go.mod h1:uH4t5bOx3G3g9Xcmj10YKlTcVISlRDwv8VoQJG9n8Os=
+modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
+modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
+modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
+modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
+modernc.org/sqlite v1.55.0 h1:hIFh0MCH0rGinQ/4KYb5/UbCkRkb+UP+OkLCVWa5MTM=
+modernc.org/sqlite v1.55.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
diff --git a/internal/demobuild/testdata/starter/main.go b/internal/demobuild/testdata/starter/main.go
new file mode 100644
index 000000000..2fb3bed7d
--- /dev/null
+++ b/internal/demobuild/testdata/starter/main.go
@@ -0,0 +1,5 @@
+package main
+
+import _ "amadan.net/rastrillo/rastrillo"
+
+func main() {}
diff --git a/internal/demobuild/toolchain.lock.json b/internal/demobuild/toolchain.lock.json
new file mode 100644
index 000000000..556d8082e
--- /dev/null
+++ b/internal/demobuild/toolchain.lock.json
@@ -0,0 +1,181 @@
+{
+ "go_version": "1.26.10",
+ "rastrillo": {
+ "path": "amadan.net/rastrillo/rastrillo",
+ "version": "v0.30.2"
+ },
+ "modules": [
+ {
+ "path": "amadan.net/rastrillo/rastrillo",
+ "version": "v0.30.2",
+ "sum": "h1:xZ/cAfSvWFoWWL1xD5Lsq90xwxF+jigD1GsZmwgTcxs=",
+ "go_mod_sum": "h1:K7Clrt14+25ruVupgRjlIhH2GQp/OdL9VoD8xPmkt0w="
+ },
+ {
+ "path": "amadan.net/rastrillo/rastrillo/money",
+ "version": "v0.1.0",
+ "sum": "h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonajNqeLIzmmaM=",
+ "go_mod_sum": "h1:cmgkjBEIQh1pFSYvQk0UU6oPYS8kSDypdT9+t4Flx0U="
+ },
+ {
+ "path": "github.com/BurntSushi/toml",
+ "version": "v1.6.0",
+ "sum": "h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk=",
+ "go_mod_sum": "h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho="
+ },
+ {
+ "path": "github.com/chromedp/cdproto",
+ "version": "v0.158.6",
+ "sum": "h1:jaKiXWuhcxbvKbSe8U6Dp5U4Hcj2w6lETYgZqBD5n34=",
+ "go_mod_sum": "h1:h68JaIuFr9o3yiayxEYhBdvaxgYO3shDrPSYhNlyfu0="
+ },
+ {
+ "path": "github.com/chromedp/chromedp",
+ "version": "v0.21.0",
+ "sum": "h1:nVHgS2LHyhZJ1l3BWRbG2eFIFYiJMnvkJbELbd8WBoQ=",
+ "go_mod_sum": "h1:6z1Y5FdKUxRzxx2qcC5h1xjaBJrSWrZp1mjgITfNZig="
+ },
+ {
+ "path": "github.com/dustin/go-humanize",
+ "version": "v1.0.1",
+ "sum": "h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=",
+ "go_mod_sum": "h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto="
+ },
+ {
+ "path": "github.com/go-chi/chi/v5",
+ "version": "v5.3.2",
+ "sum": "h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=",
+ "go_mod_sum": "h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto="
+ },
+ {
+ "path": "github.com/go-json-experiment/json",
+ "version": "v0.0.0-20260820222146-c27c302e5fc3",
+ "sum": "h1:UADEEmDKgfXbtnGJZ97beY5XLo9ZechG1nlU4KnRrkE=",
+ "go_mod_sum": "h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg="
+ },
+ {
+ "path": "github.com/google/uuid",
+ "version": "v1.6.0",
+ "sum": "h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=",
+ "go_mod_sum": "h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo="
+ },
+ {
+ "path": "github.com/jinzhu/inflection",
+ "version": "v1.0.0",
+ "sum": "h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=",
+ "go_mod_sum": "h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc="
+ },
+ {
+ "path": "github.com/jinzhu/now",
+ "version": "v1.1.5",
+ "sum": "h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=",
+ "go_mod_sum": "h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8="
+ },
+ {
+ "path": "github.com/keymaildev/signin",
+ "version": "v0.1.1",
+ "sum": "h1:gO+1IAM99sqUkBtCezkgGxab+/DOrqwDxd5H32N1s9Q=",
+ "go_mod_sum": "h1:Eb/sCmEel1jlcdkgPOrNeMn5jvxzoFvJrdjDUxOBHls="
+ },
+ {
+ "path": "github.com/mattn/go-isatty",
+ "version": "v0.0.20",
+ "sum": "h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=",
+ "go_mod_sum": "h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y="
+ },
+ {
+ "path": "github.com/ncruces/go-strftime",
+ "version": "v1.0.0",
+ "sum": "h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=",
+ "go_mod_sum": "h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls="
+ },
+ {
+ "path": "github.com/remyoudompheng/bigfft",
+ "version": "v0.0.0-20230129092748-24d4a6f8daec",
+ "sum": "h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=",
+ "go_mod_sum": "h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo="
+ },
+ {
+ "path": "github.com/skip2/go-qrcode",
+ "version": "v0.0.0-20200617195104-da1b6568686e",
+ "sum": "h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=",
+ "go_mod_sum": "h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M="
+ },
+ {
+ "path": "golang.org/x/crypto",
+ "version": "v0.53.0",
+ "sum": "h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=",
+ "go_mod_sum": "h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio="
+ },
+ {
+ "path": "golang.org/x/mod",
+ "version": "v0.37.0",
+ "sum": "h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=",
+ "go_mod_sum": "h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0="
+ },
+ {
+ "path": "golang.org/x/sync",
+ "version": "v0.21.0",
+ "sum": "h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=",
+ "go_mod_sum": "h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0="
+ },
+ {
+ "path": "golang.org/x/sys",
+ "version": "v0.46.0",
+ "sum": "h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=",
+ "go_mod_sum": "h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw="
+ },
+ {
+ "path": "golang.org/x/text",
+ "version": "v0.39.0",
+ "sum": "h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=",
+ "go_mod_sum": "h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM="
+ },
+ {
+ "path": "golang.org/x/tools",
+ "version": "v0.47.0",
+ "sum": "h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=",
+ "go_mod_sum": "h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA="
+ },
+ {
+ "path": "gorm.io/gorm",
+ "version": "v1.31.2",
+ "sum": "h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=",
+ "go_mod_sum": "h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs="
+ },
+ {
+ "path": "gorm.io/plugin/dbresolver",
+ "version": "v1.6.2",
+ "sum": "h1:F4b85TenghUeITqe3+epPSUtHH7RIk3fXr5l83DF8Pc=",
+ "go_mod_sum": "h1:tctw63jdrOezFR9HmrKnPkmig3m5Edem9fdxk9bQSzM="
+ },
+ {
+ "path": "modernc.org/libc",
+ "version": "v1.74.1",
+ "sum": "h1:bdR4VTKFMC4966QSNZ05XLGI/VwzVa2kTUX51Dm0riQ=",
+ "go_mod_sum": "h1:uH4t5bOx3G3g9Xcmj10YKlTcVISlRDwv8VoQJG9n8Os="
+ },
+ {
+ "path": "modernc.org/mathutil",
+ "version": "v1.7.1",
+ "sum": "h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=",
+ "go_mod_sum": "h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg="
+ },
+ {
+ "path": "modernc.org/memory",
+ "version": "v1.11.0",
+ "sum": "h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=",
+ "go_mod_sum": "h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw="
+ },
+ {
+ "path": "modernc.org/sqlite",
+ "version": "v1.55.0",
+ "sum": "h1:hIFh0MCH0rGinQ/4KYb5/UbCkRkb+UP+OkLCVWa5MTM=",
+ "go_mod_sum": "h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw="
+ }
+ ],
+ "import_prefixes": [
+ "amadan.net/rastrillo/rastrillo"
+ ],
+ "entry_package": "."
+}